Using the API

The engine interface is based on Direct3D11 and Direct3D12 APIs. If you are not familiar with these APIs, it is highly recommended to take a look at Direct3D help pages first.

Initializing the Engine

Before you can use any functionality provided by the engine, you need to create a render device, an immediate context and a swap chain.

Win32

On Win32 platform, you can create OpenGL, Direct3D11, Direct3D12, or Vulkan device as shown in the following code snippet:

On Windows, the engine can be statically linked to the application or built as a separate DLL. In the former case, factory functions GetEngineFactoryGL(), GetEngineFactoryD3D11()GetEngineFactoryD3D12() , and  GetEngineFactoryVk() can be called directly. In the latter case, you need to load the DLL into the process’s address space using LoadGraphicsEngineOpenGL(), LoadGraphicsEngineD3D11()LoadGraphicsEngineD3D12()  or  LoadGraphicsEngineVk() function. Each function loads appropriate dynamic library and imports the functions required to initialize the engine. You need to include the following headers:

You also need to add the following directories to the include search paths:

  • DiligentCore\Graphics\GraphicsEngineD3D11\interface
  • DiligentCore\Graphics\GraphicsEngineD3D12\interface
  • DiligentCore\Graphics\GraphicsEngineOpenGL\interface
  • DiligentCore\Graphics\GraphicsEngineVulkan\interface

A man is more intended to get prescription of cheapest cialis india from our website without any hassle. Make sure to follow these simple tips are highly effective in enhancing your sexual function unica-web.com side effects levitra and performance. All these pols need to be consumed in a daily routine, will help get rid of erectile dysfunction levitra canada pharmacy pills that can help you to treat this issue rapidly. Although these medicines viagra sales france are made available without a prescription from a registered physician or a medical condition which tends to be faced by a person when he crosses age of 70.
Also, enable Diligent namespace:

IEngineFactoryD3D11::CreateDeviceAndContextsD3D11(), IEngineFactoryD3D12::CreateDeviceAndContextsD3D12()  and  IEngineFactoryVk::CreateDeviceAndContextsVk() functions can also create a specified number of deferred contexts, which can be used for multi-threaded command recording. Deferred contexts can only be created during the initialization of the engine. The function populates an array of pointers to the contexts, where the immediate context goes at position 0, followed by all deferred contexts.

For more details, take a look at Tutorial00_HelloWin32.cpp file located in DiligentSamples/Tutorials/Tutorial00_HelloWin32 folder that implements initialization of the engine on Win32 platform.

Universal Windows Platform

On Universal Windows Platform, you can create Direct3D11 or Direct3D12 device. Only static linking is currently supported, but dynamic linking can also be implemented. Initialization is performed the same way as on Win32 Platform. The difference is that you first create the render device and device contexts by calling IEngineFactoryD3D11::CreateDeviceAndContextsD3D11()  or IEngineFactoryD3D12::CreateDeviceAndContextsD3D12(). The swap chain is created later by a call to IEngineFactoryD3D11::CreateSwapChainD3D11() or IEngineFactoryD3D12::CreateSwapChainD3D12(). Please look at the SampleAppUWP.cpp file located in diligentsamples\Samples\SampleBase\Src\UWP\Common for more details.

Android

On Android, you can create OpenGLES or Vulkan device, for example:

If engine is built as dynamic library, the library needs to be loaded by the native activity. The following code shows one possible way:

Linux

On Linux platform, OpenGL and Vulkan backends are supported. Initialization of GL context on Linux is tightly coupled with window creation. As a result, Diligent Engine does not initialize the context, but attaches to the one initialized by the app. An example of the engine initialization on Linux can be found in Tutorial00_HelloLinux.cpp.

MacOS

On MacOS, Diligent Engine provides OpenGL, Vulkan and Metal backends. Initialization of GL context on MacOS is performed by the application, and the engine attaches to the context initialized by the app; please take a look GLView.m for details.

iOS

On Android, you can create OpenGLES or Metal backend. Initialization of GL context on iOS is performed by the application, and the engine attaches to the context initialized by the app; see EAGLView.m for details.

Attaching to Already Initialized Graphics API

An alternative way to initialize the engine is to attach to existing D3D11/D3D12 device or OpenGL/GLES context. Refer to Native API interoperability for more details.

Destroying the Engine

The engine performs automatic reference counting and is destroyed when the last reference is released.

Creating Resources

Device resources are created by the render device. The two main resource types are buffers, which represent linear memory, and textures, which use memory layouts optimized for fast filtering. To create a buffer, you need to populate BufferDesc structure and call IRenderDevice::CreateBuffer(). The following code creates a uniform (constant) buffer:

Similar, to create a texture, populate TextureDesc structure and call IRenderDevice::CreateTexture() as in the following example:

There is only one function CreateTexture() that is capable of creating all types of textures. Type, format, array size and all other parameters are specified by the members of the TextureDesc structure.

For every bind flag specified during the texture creation time, the texture object creates a default view. Default shader resource view addresses the entire texture, default render target and depth stencil views reference all array slices in the most detailed mip level, and unordered access view references the entire texture. To get a default view from the texture, use ITexture::GetDefaultView() function. Note that this function does not increase reference counter on the returned interface. You can create additional texture views using ITexture::CreateView(). Use IBuffer::CreateView() to create additional views of a buffer.

Creating Shaders

To create a shader, populate ShaderCreateInfo structure. There are two ways to create a shader. The first way is to provide a pointer to the shader source code through   ShaderCreateInfo::Source member. The second way is to provide a file name. Graphics Engine is entirely decoupled from the platform. Since the host file system is platform-dependent, the structure exposes  ShaderCreateInfo::pShaderSourceStreamFactory member that is intended to provide the engine access to the file system. If you provided the source file name, you must also provide non-null pointer to the shader source stream factory. If the shader source contains any #include directives, the source stream factory will also be used to load these files. The engine provides default implementation for every supported platform that should be sufficient in most cases. You can however define your own implementation.

An important member is ShaderCreateInfo::SourceLanguage. The following are valid values for this member:

  • SHADER_SOURCE_LANGUAGE_DEFAULT  – The shader source format matches the underlying graphics API: HLSL for D3D11 or D3D12 mode, and GLSL for OpenGL, OpenGLES and Vulkan modes.
  • SHADER_SOURCE_LANGUAGE_HLSL  – The shader source is in HLSL. For OpenGL and OpenGLES modes, the source code will be converted to GLSL. See shader converter for details.
  • SHADER_SOURCE_LANGUAGE_GLSL  – The shader source is in GLSL. There is currently no GLSL to HLSL converter.

Other members of the  ShaderCreateInfo structure define shader include search directories, shader macro definitions, shader entry point and other parameters.

When everything is ready, call IRenderDevice::CreateShader()  to create the shader object:

 

Initializing Pipeline State

Diligent Engine follows Direct3D12 style to configure the graphics/compute pipeline. One big Pipelines State Object (PSO) encompasses all required states (all shader stages, input layout description, depth stencil, rasterizer and blend state descriptions etc.). To create a pipeline state object, define instance of PipelineStateDesc structure:

Describe the pipeline specifics such as if the pipeline is a compute pipeline, number and format of render targets as well as depth-stencil format:

Initialize depth-stencil state description structure  DepthStencilStateDesc. Note that the constructor initializes the members with default values and you can only set the ones that are different from default.

Initialize blend state description structure  BlendStateDesc :

Initialize rasterizer state description structure  RasterizerStateDesc:

Initialize input layout description structure InputLayoutDesc:

Define primitive topology, and set shaders:

 

Pipeline Resource Layout

Pipeline resource layout informs the engine how the application is going to use different shader resource variables. To allow grouping of resources based on the frequency of expected change, Diligent Engine introduces classification of shader variables:

  • Static variables ( SHADER_RESOURCE_VARIABLE_TYPE_STATIC) are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers.
  • Mutable variables ( SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE) define resources that are expected to change on a per-material frequency. Examples may include diffuse textures, normal maps etc.
  • Dynamic variables ( SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) are expected to change frequently and randomly.

This post gives more details about the resource binding model in Diligent Engine. To define variable types, prepare an array of ShaderResourceVariableDesc structures and initialize PSODesc.ResourceLayout.Variables and PSODesc.ResourceLayout.NumVariables. Also PSODesc.ResourceLayout.DefaultVariableType can be used to set the type that will be used if variable name is not provided.

When creating a pipeline state, textures can be assigned static samplers. If static sampler is assigned, it will always be used instead of the one initialized in the texture shader resource view. To initialize static samplers, prepare an array of StaticSamplerDesc structures and intialize  PSODesc.ResourceLayout.StaticSamplers and PSODesc.ResourceLayout.NumStaticSamplers. Notice that static samplers can be assigned to a texture variable of any type, not necessarily static, so that the texture binding can be changed at run-time, while the sampler will stay immutable. It is highly recommended to use static samplers whenever possible.

When all required fields of PSO description structure are set, call IRenderDevice::CreatePipelineState() to create the PSO object:

Binding Shader Resources

Shader resource binding in Diligent Engine is based on grouping variables in 3 different groups (static, mutable and dynamic). Static variables are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers. They are bound directly to the PSO:

Mutable and dynamic variables are bound via a new object called Shader Resource Binding (SRB), which is created by the pipeline state ( IPipelineState::CreateShaderResourceBinding()):

Dynamic and mutable resources are then bound through SRB object:

The difference between mutable and dynamic resources is that mutable ones can only be set once for every instance of a shader resource binding. Dynamic resources can be set multiple times. It is important to properly set the variable type as this may affect performance. Static variables are generally most efficient, followed by mutable. Dynamic variables are most expensive from performance point of view. This post explains shader resource binding in more details.

An alternative way to bind shader resources is to create IResourceMapping interface that maps resource literal names to the actual resources:

The resource mapping can then be used to bind all resources in a shader ( IShader::BindResources()):

in a shader resource binding ( IShaderResourceBinding::BindResources()):

or in a pipeline state ( IPipelineState::BindShaderResources() ):

The last parameter to all  BindResources()  functions defines how resources should be resolved:

  • BIND_SHADER_RESOURCES_RESET_BINDINGS  – Reset all bindings. If this flag is specified, all bindings will be reset to null before new bindings are set. By default all existing bindings are preserved.
  • BIND_SHADER_RESOURCES_UPDATE_UNRESOLVED  – If this flag is specified, only unresolved bindings will be updated. All resolved bindings will keep their original values. If this flag is not specified, every shader variable will be updated if the mapping contains corresponding resource.
  • BIND_SHADER_RESOURCES_ALL_RESOLVED  – If this flag is specified, all shader bindings are expected be resolved after the call. If this is not the case, debug error will be displayed.

BindResources() may be called several times with different resource mappings to bind resources. However, it is recommended to use one large resource mapping as the size of the mapping does not affect element search time.

The engine performs run-time checks to verify that correct resources are being bound. For example, if you try to bind a constant buffer to a shader resource view variable, an error will be output to the debug console.

Setting the Pipeline State and Invoking Draw Command

Before any draw command can be invoked, all required vertex and index buffers as well as the pipeline state should be bound to the device context:

Also, all shader resources must be committed to the device context. This is accomplished by the IDeviceContext::CommitShaderResources() method:

If the method is not called, the engine will detect that resources are not committed and output debug message. Note that CommitShaderResources() must be called after the right pipeline state has been bound to the context. Note that the last parameter tells the system to transition resources to correct states. If this flag is not specified, the resources must be explicitly transitioned to right states by a call to IDeviceContext::TransitionShaderResources():

Note that the method requires pointer to the pipeline state that created the shader resource binding.

When all required states and resources are bound, IDeviceContext::Draw() can be used to execute draw command or IDeviceContext::DispatchCompute() can be used to execute compute command. Note that for a draw command, graphics pipeline must be bound, and for dispatch command, compute pipeline must be bound. Draw() takes DrawAttribs structure as an argument. The structure members define all attributes required to perform the command (primitive topology, number of vertices or indices, if draw call is indexed or not, if draw call is instanced or not, if draw call is indirect or not, etc.). For example:

DispatchCompute()  takes DispatchComputeAttribs structure that defines compute grid dimensions:

You can learn more about the engine API by looking at the engine samples‘ source code and the header files that are extensively commented.