Skip to content

Using advanced shaders

Chuck Walbourn edited this page Jul 26, 2021 · 34 revisions

In this lesson we learn about other built-in shader types and some of their uses.

Setup

First create a new project using the instructions from the first two lessons: The basic game loop and Adding the DirectX Tool Kit which we will use for this lesson.

Environment mapping

Start by saving wood.dds and cubemap.dds into your new project's directory, and then from the top menu select Project / Add Existing Item.... Select "wood.dds" and click "OK". Repeat for "cubemap.dds"

In the Game.h file, add the following variables to the bottom of the Game class's private declarations (right after the m_graphicsMemory variable you already added as part of setup):

DirectX::SimpleMath::Matrix m_world;
DirectX::SimpleMath::Matrix m_view;
DirectX::SimpleMath::Matrix m_proj;
std::unique_ptr<DirectX::CommonStates> m_states;
std::unique_ptr<DirectX::GeometricPrimitive> m_shape;
std::unique_ptr<DirectX::EnvironmentMapEffect> m_effect;
std::unique_ptr<DirectX::DescriptorHeap> m_resourceDescriptors;
Microsoft::WRL::ComPtr<ID3D12Resource> m_texture;
Microsoft::WRL::ComPtr<ID3D12Resource> m_cubemap;

enum Descriptors
{
    Wood,
    EnvMap,
    Count
};

In Game.cpp, add to the TODO of CreateDevice after where you have created m_graphicsMemory:

RenderTargetState rtState(DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_D32_FLOAT);

m_resourceDescriptors = std::make_unique<DescriptorHeap>(m_d3dDevice.Get(),
    Descriptors::Count);

ResourceUploadBatch resourceUpload(m_d3dDevice.Get());

resourceUpload.Begin();

DX::ThrowIfFailed(
    CreateDDSTextureFromFile(m_d3dDevice.Get(), resourceUpload, L"wood.dds",
        m_texture.ReleaseAndGetAddressOf(), false));

CreateShaderResourceView(m_d3dDevice.Get(), m_texture.Get(),
    m_resourceDescriptors->GetCpuHandle(Descriptors::Wood));

bool isCubeMap = false;
DX::ThrowIfFailed(
    CreateDDSTextureFromFile(m_d3dDevice.Get(), resourceUpload, L"cubemap.dds",
        m_cubemap.ReleaseAndGetAddressOf(), false, 0, nullptr, &isCubeMap));

CreateShaderResourceView(m_d3dDevice.Get(), m_cubemap.Get(),
    m_resourceDescriptors->GetCpuHandle(Descriptors::EnvMap), isCubeMap);

m_states = std::make_unique<CommonStates>(m_d3dDevice.Get());

EffectPipelineStateDescription pd(
    &GeometricPrimitive::VertexType::InputLayout,
    CommonStates::Opaque,
    CommonStates::DepthDefault,
    CommonStates::CullNone,
    rtState);

m_effect = std::make_unique<EnvironmentMapEffect>(m_d3dDevice.Get(),
    EffectFlags::Lighting | EffectFlags::Fresnel, pd);
m_effect->EnableDefaultLighting();

m_effect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::Wood),
    m_states->LinearWrap());
m_effect->SetEnvironmentMap(m_resourceDescriptors->GetGpuHandle(Descriptors::EnvMap),
    m_states->LinearWrap());

m_shape = GeometricPrimitive::CreateTeapot();

m_world = Matrix::Identity;

auto uploadResourcesFinished = resourceUpload.End(m_commandQueue.Get());

uploadResourcesFinished.wait();

In Game.cpp, add to the TODO of CreateResources:

m_view = Matrix::CreateLookAt(Vector3(2.f, 2.f, 2.f),
    Vector3::Zero, Vector3::UnitY);
m_proj = Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f,
    float(backBufferWidth) / float(backBufferHeight), 0.1f, 10.f);

m_effect->SetView(m_view);
m_effect->SetProjection(m_proj);

In Game.cpp, add to the TODO of OnDeviceLost:

m_states.reset();
m_shape.reset();
m_effect.reset();
m_texture.Reset();
m_cubemap.Reset();
m_resourceDescriptors.reset();

In Game.cpp, add to the TODO of Render:

ID3D12DescriptorHeap* heaps[] = { m_resourceDescriptors->Heap(), m_states->Heap() };
m_commandList->SetDescriptorHeaps(static_cast<UINT>(std::size(heaps)), heaps);

m_effect->SetWorld(m_world);
m_effect->Apply(m_commandList.Get());

m_shape->Draw(m_commandList.Get());

In Game.cpp, add to the TODO of Update:

float time = float(timer.GetTotalSeconds());

m_world = Matrix::CreateRotationZ(cosf(time) * 2.f);

Build and run to see the teapot rendered with a fancy material.

Screenshot of teapot

In Game.cpp add the following to the TODO section of Update:

m_effect->SetFresnelFactor(cosf(time * 2.f));

Build and run to see the effect of animating the Fresnel factor.

Screenshot of teapot

Technical Notes

In versions of the tookit before August 2020, the creation of the environment map effect would be m_effect = std::make_unique<EnvironmentMapEffect>(m_d3dDevice.Get(), EffectFlags::Lighting, pd); or m_effect = std::make_unique<EnvironmentMapEffect>(m_d3dDevice.Get(), EffectFlags::Lighting, pd, true);. In current verions, the defaulted bool parameters have been replaced with EffectFlags::Fresnel and EffectFlags::Specular.

More to explore

  • The EnvironmentMapEffect also supports spherical environment maps (a DirectX 9 feature) and dual-parabolic environment maps.

  • The NormalMapEffect is similar to the BasicEffect with the addition of a normal texture map and an optional specular texture map.

  • PBREffect is a Disney-style Physically-Based Rendering effect which uses albedo maps, normal map, and roughness/metalness/ambient-occlusion map along with two cubemaps for Image-Based Lighting.

  • DualTextureEffect is used to render a material with two textures applied. This requires the input layout to contain a second set of texture coordinates. This does not perform vertex or per-pixel lighting, as the second texture is most often a lightmap with statically computed lighting information. .SDKMESH and the Content Exporter support exporting light-mapped models which utilize this effect (see -lightmaps).

  • The AlphaTestEffect is used to perform pixel rejection based on an alpha reference value and function selection. It's primarily to implement techniques that relied on legacy Direct3D 9 alpha testing render state. This effect is independent of the depth/stencil tests set in D3D12_DEPTH_STENCIL_DESC.DepthFunc and StencilFunc.

Next lessons: Using HDR rendering

Further reading

DirectX Tool Kit docs Effects, EffectPipelineStateDescription, RenderTargetState

For Use

  • Universal Windows Platform apps
  • Windows desktop apps
  • Windows 11
  • Windows 10
  • Xbox One
  • Xbox Series X|S

Architecture

  • x86
  • x64
  • ARM64

For Development

  • Visual Studio 2022
  • Visual Studio 2019 (16.11)
  • clang/LLVM v12 - v18
  • MinGW 12.2, 13.2
  • CMake 3.20

Related Projects

DirectX Tool Kit for DirectX 11

DirectXMesh

DirectXTex

DirectXMath

Tools

Test Suite

Model Viewer

Content Exporter

DxCapsViewer

See also

DirectX Landing Page

Clone this wiki locally