Skip to content
ImagineWorld

Advanced PBR Extensions

node_idnode-book_vulkan-3d-graphics-rendering-cookbook_chapter-07-advanced-pbr-extensions
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleAdvanced PBR Extensions
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we will delve into advanced glTF PBR extensions that build upon the base metallic-roughness model. While the base metallic-roughness model provides a starting point, it falls short of capturing the full spectrum of real-life materials. To address this, glTF incorporates additional material layers, each with specific parameters that define their unique behaviors. Our goal here is to guide you through implementing these layers from the ground up. We will introduce the concept of layers, break down some mathematical principles behind them, and then show you how to integrate each layer into the GLSL shader code.

Most of the C++ code provided in this chapter is applicable across all the recipes we will cover here and throughout the rest of our book.

In this chapter, you will learn the following recipes:

  • Introduction to glTF PBR extensions
  • Implementing the KHR_materials_clearcoat extension
  • Implementing the KHR_materials_sheen extension
  • Implementing the KHR_materials_transmission extension
  • Implementing the KHR_materials_volume extension
  • Implementing the KHR_materials_ior extension
  • Implementing the KHR_materials_specular extension
  • Implementing the KHR_materials_emissive_strength extension
  • Extending analytical lights support with KHR_lights_punctual Our GLSL shaders code is based on the official Khronos Sample Viewer and serves as an example implementation of these extensions.

In this recipe, we will explore the design approach for PBR Material extensions, offering plenty of context to help you implement various glTF PBR extensions. The actual code will be shared in subsequent recipes, with the chapter structure following the sequence in which Khronos developed these PBR extensions.

PBR specifications evolve rapidly, and the reader should be aware that some extensions may become deprecated or obsolete by the time of reading.

We assume our readers have some basic understanding of linear algebra and calculus. It is recommended to have the glTF 2.0 list of ratified extensions specification at hand which can be found at https://github.com/KhronosGroup/glTF/blob/main/extensions/README.md.

In the previous chapter, we explored the core Metallic-Roughness PBR model. This model is great for depicting many types of metallic and non-metallic materials, but the real world is much more complex.

To better capture that complexity, Khronos decided not to simply extend the Metallic-Roughness model. Instead, they introduced a layered approach, much like the layers of an onion. This method lets you gradually add complexity to the PBR material, similar to how layers are built up in Adobe Standard Surface https://github.com/Autodesk/standard-surface.

Layering mimics real-world material structures by stacking multiple layers, each with its own light-interacting properties. To maintain physical accuracy, the first layer, called the base layer, should be either fully opaque (like metallic surfaces) or completely transparent (like glass or skin). After that, additional layers, known as dielectric slabs, can be added on top of that one by one.

When light hits the boundary between two layers, it can reflect and bounce back in the opposite direction. However, our main concern here is the light that continues to move through the material stack. As this light passes through the lower layers, it may be absorbed by the material.

The mixing operation provides a unique method for material modeling. You can think of it as a statistically weighted blend of two different materials, where you combine a certain percentage of material A with a certain percentage of material B. While this technique is great for creating new materials, it is important to remember that not all combinations are physically realistic. For example, mixing oil and water wouldn’t produce a believable material.

When the mixing operation is done as a linear interpolation, it naturally follows the principle of energy conservation. This means that the total energy within the resulting material stays the same, consistent with the basic laws of physics.

Figure 7.1: glTF PBR layering and mixing

In the following recipes, we will dive into several advanced material layers: specular retro-reflection (sheen), coating specular reflection, and diffuse transmission. We will also explore how these layers can be combined to create a broader range of material appearances.

This chapter uses a single glTF viewer sample code for all the recipes. The main.cpp file varies across recipes in only two ways: they use different model files to demonstrate the specific glTF PBR extensions covered and the initial camera positions are adjusted to showcase the models attractively.

The source code for the glTF Viewer itself resides in the file shared/UtilsGLTF.cpp. The corresponding GLSL vertex and fragment shaders are located in the data/shaders/gltf/ folder.

Note

The structure of these GLSL shaders differs from those covered in the previous chapter. We will explore the specific implementation differences in each of the individual recipes.

Let’s go over the main differences between our glTF Viewer implementation from the previous chapter and the newly proposed unified version.

  1. We refactored the code and introduced a very basic structure in shared/UtilsGLTF.h to store all the necessary application data. This chapter will explain all the struct member fields.
    struct GLTFContext {
    explicit GLTFContext(VulkanApp& app_)
    : app(app_)
    , samplers(app_.ctx_)
    , envMapTextures(app_.ctx_) {}
    GLTFDataHolder glTFDataholder;
    MaterialsPerFrame matPerFrame;
    GLTFGlobalSamplers samplers;
    EnvironmentMapTextures envMapTextures;
    GLTFFrameData frameData;
    std::vector<GLTFTransforms> transforms;
    std::vector<GLTFNode> nodesStorage;
    std::vector<GLTFMesh> meshesStorage;
    std::vector<uint32_t> opaqueNodes;
    std::vector<uint32_t> transmissionNodes;
    std::vector<uint32_t> transparentNodes;
    Holder<BufferHandle> envBuffer;
    Holder<BufferHandle> perFrameBuffer;
    Holder<BufferHandle> transformBuffer;
    Holder<RenderPipelineHandle> pipelineSolid;
    Holder<RenderPipelineHandle> pipelineTransparent;
    Holder<ShaderModuleHandle> vert;
    Holder<ShaderModuleHandle> frag;
    Holder<BufferHandle> vertexBuffer;
    Holder<BufferHandle> indexBuffer;
    Holder<BufferHandle> matBuffer;
    Holder<TextureHandle> offscreenTex[3] = {};
    uint32_t currentOffscreenTex = 0;
    GLTFNodeRef root;
    VulkanApp& app;
    bool volumetricMaterial = false;
    bool isScreenCopyRequired() const {
    return volumetricMaterial;
    }
    };
  2. Let’s introduce a very basic loading and rendering API for it. The rebuildRenderList argument signals that model-to-world transformations of glTF nodes should be rebuilt:
    void loadglTF(GLTFContext& context,
    const char* gltfName, const char* glTFDataPath);
    void renderglTF(GLTFContext& context,
    const mat4& model, const mat4& view, const mat4& proj,
    bool rebuildRenderList = false);
  3. We expanded the GPU data structures to include the required material properties and added a new enum called MaterialType, which allows us to provide the material ID as needed. The previous Chapter 6 covered the old materials: unlit, metallic-roughness, and specular-glossiness. New materials will be covered here in this chapter in the subsequent recipes.
    enum MaterialType : uint32_t {
    MaterialType_Invalid = 0,
    MaterialType_Unlit = 0xF,
    MaterialType_MetallicRoughness = 0x1,
    MaterialType_SpecularGlossiness = 0x2,
    MaterialType_Sheen = 0x4,
    MaterialType_ClearCoat = 0x8,
    MaterialType_Specular = 0x10,
    MaterialType_Transmission = 0x20,
    MaterialType_Volume = 0x40,
    };
  4. We’ve added 3 different vector containers to keep lists of the glTF nodes: opaque, transparent and transmission. Here is the function buildTransformsList() to build node transformations and collect other nodes data:
    void buildTransformsList(GLTFContext& gltf) {
    gltf.transforms.clear();
    gltf.opaqueNodes.clear();
    gltf.transmissionNodes.clear();
    gltf.transparentNodes.clear();
  5. The body of our recursive traversal function is declared as a local C++ lambda. It collects all the transforms into gltf.transforms and adds opaque, transparent, and transmissive nodes to their corresponding containers:
    std::function<void(GLTFNodeRef gltfNode)> traverseTree =
    [&]([&](GLTFNodeRef nodeRef) {
    const GLTFNode& node = gltf.nodesStorage[nodeRef];
    for (GLTFNodeRef meshId : node.meshes) {
    const GLTFMesh& mesh = gltf.meshesStorage[meshId];
    gltf.transforms.push_back({
    .model = node.transform,
    .matId = mesh.matIdx,
    .nodeRef = nodeRef,
    .meshRef = meshId,
    .sortingType = mesh.sortingType });
  6. Push the index of the transform that was just added to gltf.transforms in the code block above.
    uint32_t lastTransformIndex = gltf.transforms.size() – 1;
    if (mesh.sortingType == SortingType_Transparent) {
    gltf.transparentNodes.push_back(lastTransformIndex);
    } else if (mesh.sortingType==SortingType_Transmission) {
    gltf.transmissionNodes.push_back(lastTransformIndex);
    } else {
    gltf.opaqueNodes.push_back(lastTransformIndex );
    }
    }
    for (GLTFNodeRef child : node.children)
    traverseTree(child);
    };
  7. Invoke the lambda to traverse the entire tree of glTF nodes starting from the root and store all the resulting transformations in a buffer:
    traverseTree(gltf.root);
    gltf.transformBuffer = gltf.app.ctx_->createBuffer({
    .usage = lvk::BufferUsageBits_Uniform,
    .storage = lvk::StorageType_HostVisible,
    .size = gltf.transforms.size() * sizeof(GLTFTransforms),
    .data = &gltf.transforms[0],
    .debugName = "Per Frame data" });
    };
  8. Let’s add a node-sorting function to correctly render glTF nodes in the right order to support transparency. We’re using a very simple algorithm that sorts nodes based on the distance from the camera to the node’s center. To properly render transparent nodes, they should be rendered last, from back to front.
    void sortTransparentNodes(
    GLTFContext& gltf, const vec3& cameraPos) {
    std::sort(
    gltf.transparentNodes.begin(),
    gltf.transparentNodes.end(),
    [&](uint32_t a, uint32_t b) {
    float sqrDistA = glm::length2(
    cameraPos-vec3(gltf.transforms[a].model[3]));
    float sqrDistB = glm::length2(
    cameraPos-vec3(gltf.transforms[b].model[3]));
    return sqrDistA < sqrDistB;
    });
    }

Now we have to change the actual rendering function renderGLTF() to accommodate all the changes mentioned above.

  1. First, we have to update the transforms list and sort glTF nodes based on the distance to the current camera.
    void renderGLTF(GLTFContext& gltf,
    const mat4& model, const mat4& view, const mat4& proj,
    bool rebuildRenderList)
    {
    auto& ctx = gltf.app.ctx_;
    const vec4 camPos = glm::inverse(view)[3];
    if (rebuildRenderList || gltf.transforms.empty()) {
    buildTransformsList(gltf);
    }
    sortTransparentNodes(gltf, camPos);
  2. Store per-frame camera parameters and prepare push constants with all necessary buffers and textures:
    gltf.frameData = {
    .model = model,
    .view = view,
    .proj = proj,
    .cameraPos = camPos,
    };
    struct PushConstants {
    uint64_t draw;
    uint64_t materials;
    uint64_t environments;
    uint64_t transforms;
    uint32_t envId;
    uint32_t transmissionFramebuffer;
    uint32_t transmissionFramebufferSampler;
    } pushConstants = {
    .draw = ctx->gpuAddress(gltf.perFrameBuffer),
    .materials = ctx->gpuAddress(gltf.matBuffer),
    .environments = ctx->gpuAddress(gltf.envBuffer),
    .transforms = ctx->gpuAddress(gltf.transformBuffer),
    .envId = 0,
    .transmissionFramebuffer = 0,
    .transmissionFramebufferSampler = gltf.samplers.clamp.index(),
    };
    ctx->upload(
    gltf.perFrameBuffer, &gltf.frameData, sizeof(GLTFFrameData));
    // …
  3. Let’s render all opaque nodes. For this pass, no transmission framebuffer is required:
    const lvk::RenderPass renderPass = {
    .color = { { .loadOp = lvk::LoadOp_Clear,
    .clearColor = { 1.0f, 1.0f, 1.0f, 1.0f } } },
    .depth = { .loadOp = lvk::LoadOp_Clear, .clearDepth = 1.0f },
    };
    const lvk::Framebuffer framebuffer = {
    .color = { { .texture = screenCopy ?
    gltf.offscreenTex[gltf.currentOffscreenTex] :
    ctx->getCurrentSwapchainTexture() } },
    .depthStencil = { .texture = gltf.app.getDepthTexture() },
    };
    buf.cmdBeginRendering(renderPass, framebuffer);
    buf.cmdBindVertexBuffer(0, gltf.vertexBuffer, 0);
    buf.cmdBindIndexBuffer(gltf.indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdBindRenderPipeline(gltf.pipelineSolid);
    buf.cmdPushConstants(pushConstants);
    for (uint32_t transformId : gltf.opaqueNodes) {
    GLTFTransforms transform = gltf.transforms[transformId];
    buf.cmdPushDebugGroupLabel(
    gltf.nodesStorage[transform.nodeRef].name.c_str(), 0xff0000ff);
    const GLTFMesh submesh = gltf.meshesStorage[transform.meshRef];
  4. We use the built-in GLSL variable gl_BaseInstance to pass the value of transformId into shaders. This way, we do not have to update push constants per each draw call. This is the most efficient way to do it.

Note

The firstInstance parameter of vkCmdDrawIndexed() is assigned to the built-in GLSL variable gl_BaseInstance. This allows you to pass an arbitrary per-draw-call uint32_t value into vertex shaders without involving any buffers or push constants. This is a very fast technique and should be used whenever possible.

vkCmdDrawIndexed(VkCommandBuffer commandBuffer,
uint32_t indexCount,
uint32_t instanceCount,
uint32_t firstIndex,
int32_t vertexOffset,
uint32_t firstInstance);
buf.cmdDrawIndexed(submesh.indexCount, 1,
submesh.indexOffset, submesh.vertexOffset, transformId);
buf.cmdPopDebugGroupLabel();
}
buf.cmdEndRendering();
// …
  1. Now, we should render transparent nodes on top of opaque ones. Some transparent nodes may require a screen copy to render various effects, such as volume or index-of-refraction. Here’s a very simple way to obtain it:
    if (screenCopy) {
    buf.cmdCopyImage(
    gltf.offscreenTex[gltf.currentOffscreenTex],
    ctx->getCurrentSwapchainTexture(),
    ctx->getDimensions(ctx->getCurrentSwapchainTexture()));
    buf.cmdGenerateMipmap(
    gltf.offscreenTex[gltf.currentOffscreenTex]);
    pushConstants.transmissionFramebuffer =
    gltf.offscreenTex[gltf.currentOffscreenTex].index();
    buf.cmdPushConstants(pushConstants);
    }
  2. As we start the next render pass and use the offscreen texture, we have to synchronize it properly:
    buf.cmdBeginRendering(renderPass, framebuffer, {
    .textures = { TextureHandle(
    gltf.offscreenTex[gltf.currentOffscreenTex]) } });
    buf.cmdBindVertexBuffer(0, gltf.vertexBuffer, 0);
    buf.cmdBindIndexBuffer(gltf.indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
  3. Now we render transmission nodes:
    buf.cmdBindRenderPipeline(gltf.pipelineSolid);
    for (uint32_t transformId : gltf.transmissionNodes) {
    const GLTFTransforms transform = gltf.transforms[transformId];
    buf.cmdPushDebugGroupLabel(
    gltf.nodesStorage[transform.nodeRef].name.c_str(), 0x00FF00ff);
    const GLTFMesh submesh = gltf.meshesStorage[transform.meshRef];
    buf.cmdDrawIndexed(submesh.indexCount, 1,
    submesh.indexOffset, submesh.vertexOffset, transformId);
    buf.cmdPopDebugGroupLabel();
    }
  4. Transparent nodes come last. The same gl_BaseInstance trick is used to pass the value of transformId for each glTF mesh:
    buf.cmdBindRenderPipeline(gltf.pipelineTransparent);
    for (uint32_t transformId : gltf.transparentNodes) {
    const GLTFTransforms transform = gltf.transforms[transformId];
    buf.cmdPushDebugGroupLabel(
    gltf.nodesStorage[transform.nodeRef].name.c_str(), 0x00FF00ff);
    const GLTFMesh submesh = gltf.meshesStorage[transform.meshRef];
    buf.cmdDrawIndexed(submesh.indexCount, 1,
    submesh.indexOffset, submesh.vertexOffset, transformId);
    buf.cmdPopDebugGroupLabel();
    }
  5. Once the command buffer is filled, we can submit it and use another offscreen texture in a round-robin manner.
    buf.cmdEndRendering();
    ctx->submit(buf, ctx->getCurrentSwapchainTexture());
    gltf.currentOffscreenTex = (gltf.currentOffscreenTex + 1) %
    LVK_ARRAY_NUM_ELEMENTS(gltf.offscreenTex);

This was a complete overview of our generic glTF rendering code. The real magic happens inside the GLSL shaders. In the next recipes, we will go through the shaders step by step to learn how to implement different glTF material extensions.

The Khronos 3D Formats Working Group is constantly working to improve PBR material capabilities by introducing new extension specifications. To stay up to date with the status of approved extensions, you can visit the Khronos GitHub page: https://github.com/KhronosGroup/glTF/blob/main/extensions/README.md

Implementing the KHR_materials_clearcoat extension

Section titled “Implementing the KHR_materials_clearcoat extension”

The KHR_materials_clearcoat extension improves glTF’s core physically based rendering (PBR) model by adding a clear, reflective layer on top of another material or surface. This layer reflects light both from itself and the layers underneath. Examples of this effect include the glossy finish on car paint or the shine of a well-polished shoe.

More information

Here is a link to the Khronos glTF PBR extension: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md

The following parameters are provided by the KHR_materials_clearcoat extension:

  • clearcoatFactor / clearcoatTexure: This parameter indicates the intensity of the coating. It can be set using a scalar factor or a texture. A value of 0 means no coating, while a value of 1 indicates the presence of the coating. In-between values should be used only along the boundary between coated and uncoated areas.
  • clearcoatNormalTexture: This parameter allows a normal map to be applied to the coating layer, introducing variations and details to the coating surface.
  • clearcoatRoughnessFactor / clearcoatRoughnessTexture: This parameter indicates the coating roughness. It can be set as a roughness scalar factor or a roughness texture. It works similarly to the roughness parameter of a base material but is applied to the coating layer.

The specular BRDF for the clearcoat layer uses the specular term from the glTF 2.0 Metallic-Roughness material. However, to maintain energy conservation within the material when using a simple layering function, a slight adjustment is applied.

The microfacet Fresnel term is calculated using the NdotV term instead of the VdotH term, effectively ignoring the microscopic surface orientation within the clearcoat layer. This simplification is justified because clearcoat layers usually have very low roughness, meaning the microfacets are mostly aligned with the normal direction.

As a result, NdotV becomes approximately equivalent to NdotL. This approach ensures energy conservation within the material through a simple layering function and keeps computations efficient by omitting the VdotH term.

As explained in Chapter 6, N represents the normal vector at the surface point, V is the vector pointing from the surface to the viewer, L is the vector pointing from the surface point to the light source, and H is the half-vector that lies exactly between the directions of the light source L and the viewer V.

The provided implementation of the clearcoat layer within the BRDF framework makes certain assumptions that neglect some real-world material properties. Here’s a breakdown of these limitations:

  • Infinitely Thin Layer: The clearcoat layer is treated as infinitely thin, disregarding its actual thickness.
  • Neglecting Refraction: Refraction, bending of light as it passes through the clearcoat layer, is not taken into account.
  • Independent Fresnel Terms: The refractive indices of the clearcoat and base layers are treated as independent, with their Fresnel terms calculated separately, without accounting for any interaction between them.
  • Omitted Scattering: The current model does not account for light scattering between the clearcoat layer and the base layer.
  • Diffraction Ignored: Diffraction effects, the slight bending of light around the edges of microscopic facets, are not taken into account.

Despite these limitations, the clearcoat BRDF is a valuable tool for simulating clear coat effects in material modeling. It strikes a good balance between computational efficiency and producing visually plausible results, especially for clearcoat layers with low roughness.

Important note

The clearcoat extension is designed to work with glTF’s core PBR shading model and is not compatible with other shading models like Unlit or Specular-glossiness. However, it can still be used alongside other PBR parameters, such as emissive materials, where the emitted light is influenced by the clearcoat layer.

The source code for this recipe can be found in Chapter07/01_Clearcoat/.

Let’s take a look at the C++ code in Chapter07/01_Clearcoat/src/main.cpp.

  1. First, let’s load a .gltf file using our new glTF API:
    VulkanApp app({
    .initialCameraPos = vec3(0.0f, -0.2f, -1.5f),
    .initialCameraTarget = vec3(0.0f, -0.5f, 0.0f),
    });
    GLTFContext gltf(app);
    loadGLTF(gltf,
    "deps/src/glTF-Sample-Assets/Models/ClearcoatWicker/
    glTF/ClearcoatWicker.gltf",
    "deps/src/glTF-Sample-Assets/Models/ClearcoatWicker/glTF/");
  2. Then we render it using the renderGLTF() function described in the previous recipe Introduction to glTF PBR extensions:
    const mat4 t = glm::translate(mat4(1.0f), vec3(0, -1, 0));
    app.run([&](uint32_t width, uint32_t height,
    float aspectRatio, float deltaSeconds)
    {
    const mat4 m = t * glm::rotate(
    mat4(1.0f), (float)glfwGetTime(), vec3(0.0f, 1.0f, 0.0f));
    const mat4 v = app.camera_.getViewMatrix();
    const mat4 p = glm::perspective(45.0f, aspectRatio, 0.01f, 100.0f);
    renderGLTF(gltf, m, v, p);
    });

To load clearcoat parameters from a .gltf file, we have to introduce some changes to our GLTF material loader. Let’s take a look at the steps required to do it.

  1. First, we should add some new member fields to the GLTFMaterialDataGPU structure in the file shared/UtilsGLTF.h to store scalar values and corresponding textures:
    struct GLTFMaterialDataGPU {
    // …
    vec4 clearcoatTransmissionThickness = vec4(1, 1, 1, 1);
    uint32_t clearCoatTexture = 0;
    uint32_t clearCoatTextureSampler = 0;
    uint32_t clearCoatTextureUV = 0;
    uint32_t clearCoatRoughnessTexture = 0;
    uint32_t clearCoatRoughnessTextureSampler = 0;
    uint32_t clearCoatRoughnessTextureUV = 0;
    uint32_t clearCoatNormalTexture = 0;
    uint32_t clearCoatNormalTextureSampler = 0;
    uint32_t clearCoatNormalTextureUV = 0;
    // …
    }
  2. Let’s load textures and properties using the Assimp library in shared/UtilsGLTF.cpp. Here we emphasize only the properties related to the clearcoat extension:
    GLTFMaterialDataGPU setupglTFMaterialData(
    const std::unique_ptr<lvk::IContext>& ctx,
    const GLTFGlobalSamplers& samplers,
    const aiMaterial* mtlDescriptor,
    const char* assetFolder,
    GLTFDataHolder& glTFDataholder,
    bool& useVolumetric)
    {
    // …
    // clearcoat
    loadMaterialTexture(mtlDescriptor, aiTextureType_CLEARCOAT,
    assetFolder, mat.clearCoatTexture, ctx, true, 0);
    loadMaterialTexture(mtlDescriptor, aiTextureType_CLEARCOAT,
    assetFolder, mat.clearCoatRoughnessTexture, ctx, false, 1);
    loadMaterialTexture(mtlDescriptor, aiTextureType_CLEARCOAT,
    assetFolder, mat.clearCoatNormalTexture, ctx, false, 2);
    // …
    bool useClearCoat = !mat.clearCoatTexture.empty() ||
    !mat.clearCoatRoughnessTexture.empty() ||
    !mat.clearCoatNormalTexture.empty();
    ai_real clearcoatFactor;
    if (mtlDescriptor->Get(AI_MATKEY_CLEARCOAT_FACTOR,
    clearcoatFactor) == AI_SUCCESS) {
    res.clearcoatTransmissionThickness.x = clearcoatFactor;
    useClearCoat = true;
    }
    ai_real clearcoatRoughnessFactor;
    if (mtlDescriptor->Get(AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR,
    clearcoatRoughnessFactor) == AI_SUCCESS) {
    res.clearcoatTransmissionThickness.y =
    clearcoatRoughnessFactor;
    useClearCoat = true;
    }
    if (assignUVandSampler(
    samplers, mtlDescriptor, aiTextureType_CLEARCOAT,
    res.clearCoatTextureUV,
    res.clearCoatNormalTextureSampler, 0)) {
    useClearCoat = true;
    }
    if (assignUVandSampler(
    samplers, mtlDescriptor, aiTextureType_CLEARCOAT,
    res.clearCoatRoughnessTextureUV,
    res.clearCoatRoughnessTextureSampler, 1)) {
    useClearCoat = true;
    }
    if (assignUVandSampler(
    samplers, mtlDescriptor, aiTextureType_CLEARCOAT,
    res.clearCoatNormalTextureUV,
    res.clearCoatNormalTextureSampler, 2)) {
    useClearCoat = true;
    }
    if (useClearCoat)
    res.materialTypeFlags |= MaterialType_ClearCoat;

Note

Please note that we only set the MaterialType_ClearCoat flag if the checks pass and the extension is present in the .gltf file. While it’s technically possible to enable the clearcoat layer all the time — since the default settings effectively disable it — doing so is highly inefficient. The clearcoat layer adds secondary BRDF sampling, which is computationally expensive. It is better to use only the expensive features that are actually needed!

That’s it for the C++ changes. Now, let’s look at the GLSL shader changes, where the actual rendering work takes place:

  1. Similar to the C++ changes for new parameters, we added GLSL utility functions to read clearcoat data from textures and input buffers in data/shaders/gltf/inputs.frag. The clearcoat factor and roughness are packed into a texture as r and g channels respectively:
    float getClearcoatFactor(InputAttributes tc,
    MetallicRoughnessDataGPU mat)
    {
    return textureBindless2D(mat.clearCoatTexture,
    mat.clearCoatTextureSampler,
    tc.uv[mat.clearCoatTextureUV]
    ).r * mat.clearcoatTransmissionThickness.x;
    }
    float getClearcoatRoughnessFactor(InputAttributes tc,
    MetallicRoughnessDataGPU mat)
    {
    return textureBindless2D(mat.clearCoatRoughnessTexture,
    mat.clearCoatRoughnessTextureSampler,
    tc.uv[mat.clearCoatRoughnessTextureUV]
    ).g * mat.clearcoatTransmissionThickness.y;
    }
  2. We calculate the clearcoat contribution as described in the beginning of this recipe. We use the GGX BRDF to perform an additional lookup and provide clearcoat roughness, reflectance clearcoatF0, and normal as inputs in data/shaders/gltf/main.frag. Please note that we use the IOR parameter, which will be covered later in the recipe Implementing the IOR extension:
    vec3 clearCoatContrib = vec3(0);
    if (isClearCoat) {
    pbrInputs.clearcoatFactor = getClearcoatFactor(tc, mat);
    pbrInputs.clearcoatRoughness =
    clamp(getClearcoatRoughnessFactor(tc, mat), 0.0, 1.0);
    pbrInputs.clearcoatF0 = vec3(pow((pbrInputs.ior - 1.0) /
    (pbrInputs.ior + 1.0), 2.0));
    pbrInputs.clearcoatF90 = vec3(1.0);
    if (mat.clearCoatNormalTextureUV > -1) {
    pbrInputs.clearcoatNormal = mat3(
    pbrInputs.t, pbrInputs.b, pbrInputs.ng) *
    sampleClearcoatNormal(tc, mat).rgb;
    } else {
    pbrInputs.clearcoatNormal = pbrInputs.ng;
    }
    clearCoatContrib = getIBLRadianceGGX(
    pbrInputs.clearcoatNormal, pbrInputs.v,
    pbrInputs.clearcoatRoughness,
    pbrInputs.clearcoatF0, 1.0, envMap);
    }
  3. We calculate the Fresnel term for the clearcoat layer using a similar approach. We apply the Schlick approximation, but with input data specific to the clearcoat:
    vec3 clearcoatFresnel = vec3(0);
    if (isClearCoat) {
    clearcoatFresnel = F_Schlick(
    pbrInputs.clearcoatF0,
    pbrInputs.clearcoatF90,
    clampedDot(pbrInputs.clearcoatNormal, pbrInputs.v));
    }
  4. Finally, at the very end of the fragment shader data/shaders/gltf/main.frag, we apply the clearcoat contribution on top of all layers, including emissive ones! Note the sheenColor value here, which will be covered in the next recipe Implementing the sheen material extension.
    vec3 color =
    specularColor + diffuseColor + emissiveColor + sheenColor;
    color = color * (1.0 - pbrInputs.clearcoatFactor * clearcoatFresnel) +
    clearCoatContrib;

This concludes all the necessary GLSL changes to implement the clearcoat extension. The demo app should look like the screenshot below:

Figure 7.2: KHR_materials_clearcoat example

Notice the glossy layer on top of the ball—this is the clearcoat! Congratulations, we’ve completed our first advanced PBR extension.

The Khronos glTF extensions repository includes a comprehensive list of references on clearcoat materials: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md#reference.

Implementing the KHR_materials_sheen extension

Section titled “Implementing the KHR_materials_sheen extension”

The KHR_materials_sheen extension improves the glTF 2.0 Metallic-Roughness material by adding a layer that simulates the sheen effect found on fabrics like satin or brushed metals. This enhancement creates more realistic and visually appealing sheen highlights.

Sheen BRDF sits on top of the glTF 2.0 Metallic-Roughness material. If the previous extension KHR_materials_clearcoat is also active, it is layered on top of the sheen effect.

The sheenColorFactor property controls the base intensity of the sheen effect, independent of the viewing angle. A value of 0 disables sheen entirely.

  • sheenColorTexture / sheenColorFactor: If the texture is defined, the sheen color is calculated by multiplying sheenColorFactor and the texture’s RGB value.
  • sheenRoughnessTexture / sheenRoughnessFactor: If defined, the sheen roughness is calculated by multiplying with the texture’s alpha channel value.

If no textures are specified, sheenColorFactor directly controls the sheen color, and sheenRoughnessFactor directly controls sheen roughness.

The sheen BRDF simulates how light scatters off velvet-like materials. It models how light bounces off tiny fibers that are oriented perpendicular to the surface. Sheen roughness controls how much these fibers deviate from that direction:

  • Lower sheen roughness: the fibers are more aligned, creating a sharper sheen highlight when light grazes the surface.
  • Higher sheen roughness: the fibers are more scattered, leading to a softer sheen highlight.

The sheen BRDF is mathematically based on an exponentiated sinusoidal distribution, derived from the microfacet theory (Conty & Kulla, 2017 https://blog.selfshadow.com/publications/s2017-shading-course/#course_content).). The roughness is mapped using r=sheenRoughness^2 for a more intuitive understanding of roughness changes.

Sheen roughness operates independently of the material’s base roughness. This makes it possible for a material to have a rough surface texture (high base roughness) while still displaying a sharp sheen effect (low sheen roughness).

Not all incoming light interacts with the microfibers. Some light may directly reach the base layer or bounce between the fibers before doing so. The behavior of this light is governed by the underlying glTF 2.0 PBR Metallic-Roughness material properties.

The source code for this recipe can be found in Chapter07/02_Sheen/.

Similar to the previous recipe Implementing the clear coat material extension, we introduce a bunch of new material parameters. Let’s take a look at the C++ code.

  1. Let’s load a .gltf file to demonstrate the effect Chapter07/02_Sheen/src/main.cpp:
    GLTFContext gltf(app);
    loadGLTF(gltf,
    "deps/src/glTF-Sample-Assets/Models/
    SheenChair/glTF/SheenChair.gltf",
    "deps/src/glTF-Sample-Assets/Models/SheenChair/glTF/");
  2. In the file shared/UtilsGLTF.h, we added new member fields to the GLTFMaterialDataGPU structure in:
    struct GLTFMaterialDataGPU {
    // …
    vec4 sheenFactors = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    uint32_t sheenColorTexture = 0;
    uint32_t sheenColorTextureSampler = 0;
    uint32_t sheenColorTextureUV = 0;
    uint32_t sheenRoughnessTexture = 0;
    uint32_t sheenRoughnessTextureSampler = 0;
    uint32_t sheenRoughnessTextureUV = 0;
  3. Let’s load new parameters via Assimp in shared/UtilsGLTF.cpp and store them into the sheen material. The sheen color texture is sRGB and has the index 0 and the roughness texture has the index of 1:
    loadMaterialTexture(mtlDescriptor, aiTextureType_SHEEN,
    assetFolder, mat.sheenColorTexture, ctx, true, 0);
    loadMaterialTexture(mtlDescriptor, aiTextureType_SHEEN,
    assetFolder, mat.sheenRoughnessTexture, ctx, false, 1);
    bool useSheen = !mat.sheenColorTexture.empty() ||
    !mat.sheenRoughnessTexture.empty();
    aiColor4D sheenColorFactor;
    if (mtlDescriptor->Get(AI_MATKEY_SHEEN_COLOR_FACTOR,
    sheenColorFactor) == AI_SUCCESS) {
    res.sheenFactors = vec4(sheenColorFactor.r,
    sheenColorFactor.g,
    sheenColorFactor.b,
    sheenColorFactor.a);
    useSheen = true;
    }
    ai_real sheenRoughnessFactor;
    if (mtlDescriptor->Get(AI_MATKEY_SHEEN_ROUGHNESS_FACTOR,
    sheenRoughnessFactor) == AI_SUCCESS) {
    res.sheenFactors.w = sheenRoughnessFactor;
    useSheen = true;
    }
    if (assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_SHEEN, res.sheenColorTextureUV,
    res.sheenColorTextureSampler, 0)) {
    useSheen = true;
    }
    if (assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_SHEEN, res.sheenRoughnessTextureUV,
    res.sheenRoughnessTextureSampler, 1)) {
    useSheen = true;
    }
    if (useSheen) res.materialTypeFlags |= MaterialType_Sheen;
    // …

As you can see, we follow the same pattern as with the clearcoat extension and set the flag MaterialType_Sheen only when we use this extension. This is it for the main C++ code.

The Sheen extension needs a different BRDF function, which was discussed in the recipe Precomputing BRDF look-up tables of Chapter 6. We recommend reviewing that recipe to refresh your understanding of how precomputed BRDF LUTs work and revisiting the implementation details.

Now let’s take a look at the GLSL shader code changes which follow a similar pattern:

  1. Let’s introduce some utility functions in data/shaders/gltf/inputs.frag. We can simplify these functions by pre-multiplying textures values by sheen factors. In the C++ code, we set sheenColorTexture and sheenRoughnessTexture to use a white 1x1 texture in case when no texture data is provided in the .gltf asset. In this case, it is always correct to multiply these values by identity factors. We still perform a texture lookup for this small texture, but the overhead is minimal. These small textures should always fit into the GPU’s fastest cache:
    vec4 getSheenColorFactor(
    InputAttributes tc, MetallicRoughnessDataGPU mat)
    {
    return vec4(mat.sheenFactors.xyz, 1.0f) *
    textureBindless2D(mat.sheenColorTexture,
    mat.sheenColorTextureSampler,
    tc.uv[mat.sheenColorTextureUV]);
    }
    float getSheenRoughnessFactor(
    InputAttributes tc, MetallicRoughnessDataGPU mat)
    {
    return mat.sheenFactors.a * textureBindless2D(
    mat.sheenRoughnessTexture,
    mat.sheenRoughnessTextureSampler,
    tc.uv[mat.sheenRoughnessTextureUV]).a;
    }
  2. The GLSL code of the sheen extension is scattered between the main fragment shader data/shaders/gltf/main.frag and the PBR module data/shaders/gltf/PBR.sp. In main.frag, we apply sheen parameters:
    // …
    if (isSheen) {
    pbrInputs.sheenColorFactor = getSheenColorFactor(tc, mat).rgb;
    pbrInputs.sheenRoughnessFactor = getSheenRoughnessFactor(tc, mat);
    }
    // …
  3. In the next step during IBL calculations, we accumulate the sheen contribution calculated using the Charlie distribution:
    vec3 sheenColor = vec3(0);
    if (isSheen) {
    sheenColor += getIBLRadianceCharlie(pbrInputs, envMap);
    }
  4. Let’s take a look at the implementation of getIBLRadianceCharlie() in the file data/shaders/gltf/PBR.sp. This function is similar to getIBLRadianceGGX() used for metallic-roughness, but is much simpler. The Sheen extension provides its own roughness value, so no perceptual adjustments are needed. All we have to do here is to multiply sheenRoughnessFactor by the total number of mip-levels mipCount to determine the correct mip-level, sample the precalculated environment map, and then multiply it by the BRDF and sheenColor.
    vec3 getIBLRadianceCharlie(PBRInfo pbrInputs,
    EnvironmentMapDataGPU envMap) {
    float sheenRoughness = pbrInputs.sheenRoughnessFactor;
    vec3 sheenColor = pbrInputs.sheenColorFactor;
    float mipCount = float(sampleEnvMapQueryLevels(envMap));
    float lod = sheenRoughness * float(mipCount - 1);
    vec3 reflection = normalize(reflect(-pbrInputs.v, pbrInputs.n));
    vec2 brdfSamplePoint = clamp(vec2(pbrInputs.NdotV,
    sheenRoughness), vec2(0.0, 0.0), vec2(1.0, 1.0));
    float brdf = sampleBRDF_LUT(brdfSamplePoint, envMap).b;
    vec3 sheenSample = sampleCharlieEnvMapLod(
    reflection.xyz, lod, envMap).rgb;
    return sheenSample * sheenColor * brdf;
    }
  5. Let’s go back to data/shaders/gltf/main.frag. We modify the sheen contribution based on the value of occlusionStrength. The calculation of lights_sheen will be covered in the last recipe Extend analytical lights support in this chapter. For now, assume it is just zero.
    vec3 lights_sheen = vec3(0);
    sheenColor = lights_sheen +
    mix(sheenColor, sheenColor * occlusion, occlusionStrength);

This is all the additional code required to implement the Sheen extension. The running demo app should look as in the following screenshot:

Figure 7.3: KHR_materials_sheen example

The Khronos glTF extensions repository provides a comprehensive list of papers on different sheen materials: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_sheen/README.md#reference.

Implementing the KHR_materials_transmission extension

Section titled “Implementing the KHR_materials_transmission extension”

The glTF 2.0 core specification uses a basic method for handling transparency called alpha-as-coverage. While this approach works well for simple materials like gauze or burlap, it doesn’t do a good job of representing more complex transparent materials like glass or plastic. These materials involve complicated light interactions—such as reflection, refraction, absorption, and scattering—that alpha-as-coverage can’t accurately simulate on its own.

Alpha-as-coverage basically decides if a surface is there or not. A value of 0 means nothing is visible, while a value of 1 means the surface is solid. This method works well for materials with holes or gaps that let light pass through without actually entering the material. However, for materials like glass, light interacts with the surface in more complex ways—like reflecting, refracting, or even being absorbed. Alpha-as-coverage can’t handle these kinds of interactions. Additionally, it affects how intense reflections are, making more transparent materials have weaker reflections. This is the opposite of what happens with real-world transparent materials, which often have strong reflections even when they’re see-through.

To overcome the limitations of alpha-as-coverage, the KHR_materials_transmission extension offers a more realistic way to render transparent materials in glTF. It allows for the simulation of materials that absorb, reflect, and transmit light depending on the angle of incidence and the light’s wavelength. This extension is especially useful for accurately representing thin-surface materials like plastic and glass.

The KHR_materials_transmission extension targets the simplest cases of optical transparency: infinitely thin materials without refraction, scattering, or dispersion. This simplification enables efficient calculations of refraction and absorption.

The KHR_materials_transmission extension adds new properties to define material’s transmission characteristics:

  • transmissionFactor: A scalar value between 0 and 1 that represents the material’s overall opacity. A value of 0 means the material is fully opaque, while a value of 1 means it is completely transparent.
  • transmissionFilter: A color value that alters the color of the light passing through the material.

The KHR_materials_transmission extension introduces a specular BTDF (Bidirectional Transmission Distribution Function) based on the microfacet model. It uses the same Trowbridge-Reitz distribution as the specular BRDF (Bidirectional Reflectance Distribution Function) but samples along the view vector instead of the reflection direction. This method simulates how microfacets act like tiny prisms, blurring the transmitted light.

The transmission process is modeled as two back-to-back surfaces, representing a thin material. This approach simplifies the process by avoiding the complexities of average refraction and instead focusing on refraction at the microfacet level. The roughness parameter affects both reflection and transmission since the microfacet distribution impacts both sides of the surface. Let’s take a look at how to implement this glTF extension.

The source code for this recipe can be found in Chapter07/03_Transmission/.

This is the most complex extension discussed in this chapter, requiring changes to the C++ code to handle the complexities of transparency rendering. In addition to updating the C++ rendering code, we need to implement a specular BTDF in the GLSL shader code and incorporate the blending of two layers to accurately represent a thin material.

Let’s start with C++ changes.

  1. First, we should load a corresponding .gltf sample model in Chapter07/03_Transmission/src/main.cpp:
    GLTFContext gltf(app);
    loadGLTF(gltf, "deps/src/glTF-Sample-Assets/Models/
    TransmissionRoughnessTest/glTF/
    TransmissionRoughnessTest.gltf",
    "deps/src/glTF-Sample-Assets/Models/
    TransmissionRoughnessTest/glTF/");
  2. The parameters parsing is in shared/UtilsGLTF.cpp and quite simple:
    loadMaterialTexture(mtlDescriptor, aiTextureType_TRANSMISSION,
    assetFolder, mat.transmissionTexture, ctx, true, 0);
    // …
    bool useTransmission = !mat.transmissionTexture.empty();
    ai_real transmissionFactor = 0.0f;
    if (mtlDescriptor->Get(AI_MATKEY_TRANSMISSION_FACTOR,
    transmissionFactor) == AI_SUCCESS) {
    res.clearcoatTransmissionThickness.z = transmissionFactor;
    useTransmission = true;
    }
    if (useTransmission) {
    res.materialTypeFlags |= MaterialType_Transmission;
    useVolumetric = true;
    }
    assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_TRANSMISSION, res.transmissionTextureUV,
    res.transmissionTextureSampler, 0);

Significant changes have been made to the rendering function renderGLTF(). We touched on some of these in the first recipe Introduction to glTF PBR extensions. Now, let’s take a closer look at these changes. To effectively render transparent and transmission surfaces, we need to follow these steps:

  1. Prepare lists of completely opaque, transmission, and transparent nodes, because these should be rendered in a particular order: opaque nodes first, then transmission, and then transparent.

Note

Keep in mind that rendering transmission nodes doesn’t automatically make them transparent! Instead, we need to use the result from rendering opaque nodes. To do this, we must create a copy of the rendered surface and use it as input for the transmission nodes.

  1. Pre-allocate an offscreen texture to store the rendered opaque nodes:
    if (gltf.offscreenTex[0].empty() || isSizeChanged) {
    const lvk::Dimensions res =
    ctx->getDimensions(ctx->getCurrentSwapchainTexture());
    for (Holder<TextureHandle>& holder : gltf.offscreenTex) {
    holder = ctx->createTexture({
    .type = lvk::TextureType_2D,
    .format = ctx->getSwapchainFormat(),
    .dimensions = {res.width, res.height},
    .usage = lvk::TextureUsageBits_Attachment |
    lvk::TextureUsageBits_Sampled,
    .numMipLevels = lvk::calcNumMipLevels(res.width, res.height),
    .debugName = "offscreenTex" });
    }
    }
  2. Create a screen copy when necessary and pass its handle as transmissionFramebuffer:
    const bool screenCopy = gltf.isScreenCopyRequired();
    if (screenCopy) {
    buf.cmdCopyImage(
    gltf.offscreenTex[gltf.currentOffscreenTex],],
    ctx->getCurrentSwapchainTexture(),
    ctx->getDimensions(ctx->getCurrentSwapchainTexture()));
    buf.cmdGenerateMipmap(
    gltf.offscreenTex[gltf.currentOffscreenTex]);
    pushConstants.transmissionFramebuffer =
    gltf.offscreenTex[gltf.currentOffscreenTex].index();
    buf.cmdPushConstants(pushConstants);
    }
  3. Now we can render transmission nodes using the screen copy as input. It’s important to note that we’re not using alpha blending for this pass. The nodes are still rendered as opaque, and we simulate transparency by sampling the screen copy. We also specify a texture dependency for LightweightVK here to ensure the correct Vulkan barriers are applied:
    buf.cmdBeginRendering(renderPass, framebuffer, { .textures = {
    TextureHandle(
    gltf.offscreenTex[gltf.currentOffscreenTex]) } });
    buf.cmdBindVertexBuffer(0, gltf.vertexBuffer, 0);
    buf.cmdBindIndexBuffer(gltf.indexBuffer, lvk::IndexFormat_UI32);
    buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,
    .isDepthWriteEnabled = true });
    buf.cmdBindRenderPipeline(gltf.pipelineSolid);
    for (uint32_t transformId : gltf.transmissionNodes) {
    const GLTFTransforms transform = gltf.transforms[transformId];
    const GLTFMesh submesh = gltf.meshesStorage[transform.meshRef];
    buf.cmdDrawIndexed(submesh.indexCount, 1,
    submesh.indexOffset, submesh.vertexOffset, transformId);
    }
  4. The next step is to render all transparent nodes in back-to-front order. We did not change push constants and these transparent nodes use the same offscreen texture as input:
    buf.cmdBindRenderPipeline(gltf.pipelineTransparent);
    for (uint32_t transformId : gltf.transparentNodes) {
    const GLTFTransforms transform = gltf.transforms[transformId];
    const GLTFMesh submesh = gltf.meshesStorage[transform.meshRef];
    buf.cmdDrawIndexed(submesh.indexCount, 1,
    submesh.indexOffset, submesh.vertexOffset, transformId);
    }}

This is it for the C++ changes. Let’s take a look at the GLSL shader changes now.

  1. First, we introduce a utility function in data/shaders/gltf/inputs.frag to read material inputs. The transmission factor is stored in the r channel of the texture:
    float getTransmissionFactor(
    InputAttributes tc, MetallicRoughnessDataGPU mat)
    {
    return mat.clearcoatTransmissionThickness.z *
    textureBindless2D(mat.transmissionTexture,
    mat.transmissionTextureSampler,
    tc.uv[mat.transmissionTextureUV]
    ).r;
    }
  2. Then, we populate inputs in data/shaders/gltf/main.frag if the transmission extension is enabled for this material:
    // ...
    if (isTransmission) {
    pbrInputs.transmissionFactor = getTransmissionFactor(tc, mat);
    }
  3. We calculate the transmission contribution. The volumetric part will be covered in detail in our next recipe for the KHR_materials_volume extension Implementing the volume extension. In a pure transmission implementation without the volume extension, the transmission part would be similar to GGX/Lambertian, but instead of using the reflection vector, we use the dot product NdotV. Implementing just the transmission extension without volume support is not practical, as the volume extension offers greater flexibility to represent effects like refraction, absorption, or scattering without adding excessive complexity on top of transmission:
    vec3 transmission = vec3(0,0,0);
    if (isTransmission) {
    transmission += getIBLVolumeRefraction(
    pbrInputs.n,
    pbrInputs.v,
    pbrInputs.perceptualRoughness,
    pbrInputs.diffuseColor,
    pbrInputs.reflectance0,
    pbrInputs.reflectance90,
    worldPos, getModel(), getViewProjection(),
    pbrInputs.ior,
    pbrInputs.thickness,
    pbrInputs.attenuation.rgb,
    pbrInputs.attenuation.a);
    }
  4. Finally, we add the calculated transmission value to the diffuse contribution scaled by transmissionFactor:
    if (isTransmission) {
    diffuseColor = mix(diffuseColor, transmission,
    pbrInputs.transmissionFactor);
    }

The resulting rendered 3D model should look as in the following screenshot:

Figure 7.4: KHR_materials_transmission example

Rendering transparent objects efficiently and accurately in real-time is challenging, particularly when dealing with overlapping transparent polygons. Issues such as order-dependent transparency and the need for separate blending operations for absorption and reflections add to the complexity. We will address some of these issues in Chapter 11.

The Khronos extensions repository provides comprehensive reference materials for the transmission extension: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_transmission/README.md#reference.

Implementing the KHR_materials_volume extension

Section titled “Implementing the KHR_materials_volume extension”

The KHR_materials_volume extension adds volumetric effects to the glTF 2.0 ecosystem, enabling the creation of materials with depth and internal structure. It’s crucial for accurately rendering materials such as smoke, fog, clouds, and translucent objects.

Volumetric effects are different from surface-based materials. While surface-based materials focus on how light interacts with a surface, volumetric materials describe how light moves through a medium. This includes simulating how light scatters and gets absorbed as it passes through the volume.

To create realistic volumetric effects, the KHR_materials_volume extension needs to work alongside other extensions that define light interactions with the material’s surface. The KHR_materials_transmission extension is key here, as it lets light rays pass through the surface and enter the volume. Once inside, the light’s interaction with the material is no longer affected by the surface properties. Instead, the light travels through the volume, undergoing refraction and attenuation. When it exits the volume, its direction is determined by the angle at which it leaves the volume boundary.

Let’s explore how to add this extension to our glTF renderer.

The KHR_materials_volume extension defines the following parameters to describe a volumetric material:

  • thicknessFactor: A scalar floating-point value that represents the base thickness of the volume. This value is multiplied by the thickness texture value (if available) to determine the final thickness at any point on the surface.
  • attenuationDistance: A floating-point value that indicates the distance over which the volume’s density decreases. This parameter controls how quickly the volume’s opacity fades as light passes through it.
  • attenuationColor: A color value representing the base color of the volume’s attenuation. This color influences how light is absorbed as it travels through the volume.
  • thicknessTexture: An optional texture that adds extra detail about the volume’s thickness. The values in the texture are multiplied by the thicknessFactor to determine the final thickness at each point on the surface.

Here’s how these parameters work together:

  • Thickness: The thicknessFactor and thicknessTexture are multiplied to define the volume’s depth. A higher thickness value results in a thicker volume.
  • Attenuation: The attenuationDistance and attenuationColor control how light is absorbed as it travels through the volume. A smaller value of attenuationDistance leads to quicker attenuation. The value of attenuationColor determines the color change due to absorption.

Note

The KHR_materials_volume extension currently assumes a homogeneous volume, where the material properties are uniform throughout. Future extensions may add support for heterogeneous volumes with varying properties.

The source code for this recipe can be found in Chapter07/04_Volume/. Please review the previous recipe Implementing the transmission extension, where we covered the transmission and volumetric C++ rendering flow.

This extension requires only a handful of changes across our existing C++ and GLSL shader code. This extension requires KHR_materials_transmission support and works only in conjunction with it.

Let’s explore how to create advanced volumetric effects such as refraction, absorption, or scattering, starting with the C++.++. code

  1. First, we load a corresponding .gltf model in Chapter07/04_Volume/main.cpp:
    GLTFContext gltf(app);
    loadGLTF(gltf, "deps/src/glTF-Sample-Assets/Models/
    DragonAttenuation/glTF/DragonAttenuation.gltf",
    "deps/src/glTF-Sample-Assets/Models/DragonAttenuation/glTF/");
  2. Parsing the volume parameters using Assimp in shared/UtilsGLTF.cpp:
    // …
    loadMaterialTexture(mtlDescriptor, aiTextureType_TRANSMISSION,
    assetFolder, mat.thicknessTexture, ctx, true, 1);
    bool useVolume = !mat.thicknessTexture.empty();
    ai_real thicknessFactor = 0.0f;
    if (mtlDescriptor->Get(AI_MATKEY_VOLUME_THICKNESS_FACTOR,
    thicknessFactor) == AI_SUCCESS) {
    res.clearcoatTransmissionThickness.w = thicknessFactor;
    useVolume = true;
    }
    ai_real attenuationDistance = 0.0f;
    if (mtlDescriptor->Get(AI_MATKEY_VOLUME_ATTENUATION_DISTANCE,
    attenuationDistance) == AI_SUCCESS) {
    res.attenuation.w = attenuationDistance;
    useVolume = true;
    }
    aiColor4D volumeAttenuationColor;
    if (mtlDescriptor->Get(AI_MATKEY_VOLUME_ATTENUATION_COLOR,
    volumeAttenuationColor) == AI_SUCCESS) {
    res.attenuation.x = volumeAttenuationColor.r;
    res.attenuation.y = volumeAttenuationColor.g;
    res.attenuation.z = volumeAttenuationColor.b;
    useVolume = true;
    }
    if (useVolume) {
    res.materialTypeFlags |= MaterialType_Transmission |
    MaterialType_Volume;
    useVolumetric = true;
    }
    assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_TRANSMISSION, res.thicknessTextureUV,
    res.thicknessTextureSampler, 1);
    // …

Most of the magic is hidden in GLSL shaders. Let’s step inside data/shaders/gltf/PBR.sp and check important helper functions.

  1. The function getVolumeTransmissionRay() calculates the direction of refracted light refractionVector and uses the modelScale factor to get an actual lookup vector inside a volume. Note that the thickness factor is designed to be normalized to the actual scale of the mesh.
    vec3 getVolumeTransmissionRay(
    vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix)
    {
    vec3 refractionVector = refract(-v, n, 1.0 / ior);
  2. Compute rotation-independent scaling of the model matrix. The thickness factor is specified in local space:
    vec3 modelScale = vec3(length(modelMatrix[0].xyz),
    length(modelMatrix[1].xyz),
    length(modelMatrix[2].xyz));
    return
    normalize(refractionVector) * thickness * modelScale.xyz;
    }

Another helper function is getIBLVolumeRefraction(). This function has several important steps:

  1. The first step is to get a transmission ray transmissionRay and calculate the final refraction position:
    vec3 getIBLVolumeRefraction(vec3 n, vec3 v,
    float perceptualRoughness, vec3 baseColor, vec3 f0, vec3 f90,
    vec3 position, mat4 modelMatrix, mat4 viewProjMatrix,
    float ior, float thickness, vec3 attenuationColor,
    float attenuationDistance)
    {
    vec3 transmissionRay =
    getVolumeTransmissionRay(n, v, thickness, ior, modelMatrix);
    vec3 refractedRayExit = position + transmissionRay;
  2. We project the refracted vector onto the framebuffer, convert it to normalized device coordinates, and sample the color of the pixel where the refracted ray intersects the framebuffer. The refracted framebuffer coordinates should be transformed from the -1...+1 range into 0...1 and then flipped vertically:
    vec4 ndcPos = viewProjMatrix * vec4(refractedRayExit, 1.0);
    vec2 refractionCoords = ndcPos.xy / ndcPos.w;
    refractionCoords += 1.0;
    refractionCoords /= 2.0;
    refractionCoords.y = 1.0 - refractionCoords.y;
    vec3 transmittedLight = getTransmissionSample(
    refractionCoords, perceptualRoughness, ior);
  3. After that, we apply volume attenuation and sample GGX BRDF to get the specular component and modulate it by baseColor and attenuatedColor:
    vec3 attenuatedColor = applyVolumeAttenuation(transmittedLight,
    length(transmissionRay), attenuationColor, attenuationDistance);
    float NdotV = clampedDot(n, v);
    vec2 brdfSamplePoint = clamp(vec2(NdotV, perceptualRoughness),
    vec2(0.0, 0.0), vec2(1.0, 1.0));
    vec2 brdf = sampleBRDF_LUT(brdfSamplePoint,
    getEnvironmentMap(getEnvironmentId())).rg;
    vec3 specularColor = f0 * brdf.x + f90 * brdf.y;
    return (1.0 - specularColor) * attenuatedColor * baseColor;
    }
  4. Here’s the function getTransmissionSample(). We use a copy of the framebuffer as we explained in the previous recipe Implementing the transmission extension:
    vec3 getTransmissionSample(
    vec2 fragCoord, float roughness, float ior)
    {
    const ivec2 size =
    textureBindlessSize2D(perFrame.transmissionFramebuffer);
    const vec2 uv = fragCoord;
    float framebufferLod =
    log2(float(size.x)) * applyIorToRoughness(roughness, ior);
    vec3 transmittedLight = textureBindless2DLod(
    perFrame.transmissionFramebuffer,
    perFrame.transmissionFramebufferSampler,
    uv, framebufferLod).rgb;
    return transmittedLight;
    }
  5. The helper function applyVolumeAttenuation() looks as follows. The attenuation distance of 0 means the transmitted color is not attenuated at all. Light attenuation is computed using Beer-Lambert law https://en.wikipedia.org/wiki/Beer%E2%80%93Lambert_law:
    vec3 applyVolumeAttenuation(vec3 radiance,
    float transmissionDistance,
    vec3 attenuationColor,
    float attenuationDistance)
    {
    if (attenuationDistance == 0.0) return radiance;
    vec3 attenuationCoefficient =
    -log(attenuationColor) / attenuationDistance;
    vec3 transmittance =
    exp(-attenuationCoefficient * transmissionDistance);
    return transmittance * radiance;
    }
  6. Now we can go back to data/shaders/gltf/main.frag and use getIBLVolumeRefraction(), together with other helper functions as described in the previous recipe Implementing the transmission extension:
    // …
    vec3 transmission = vec3(0,0,0);
    if (isTransmission) {
    transmission += getIBLVolumeRefraction(
    pbrInputs.n, pbrInputs.v,
    pbrInputs.perceptualRoughness,
    pbrInputs.diffuseColor, pbrInputs.reflectance0,
    pbrInputs.reflectance90,
    worldPos, getModel(), getViewProjection(),
    pbrInputs.ior, pbrInputs.thickness,
    pbrInputs.attenuation.rgb, pbrInputs.attenuation.w);
    }

The resulting demo application should render a translucent dragon, similar to the screenshot below. You can move the camera around the dragon to observe how light interacts with the volume from different angles. This will allow you to see how the light passes through the medium and interacts with the volumetric material.

Figure 7.5: KHR_materials_volume example

After we explored a range of complex PBR glTF extensions, it is time to switch gears. Let’s take a look at something a bit more straightforward: implementing the Index-of-Refraction extension. This simpler extension is a great way to continue building your understanding while giving you a break from the more complex topics we have covered.

An alternative way to implement this extension could involve volume ray-casting or ray-tracing. We leave that as an exercise for our readers.

The Khronos extensions repository provides comprehensive reference materials for this extension: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md#overview.

Implementing the KHR_materials_ior extension

Section titled “Implementing the KHR_materials_ior extension”

The KHR_materials_ior extension for glTF 2.0 adds the concept of Index-of-Refraction (IOR) to materials, allowing for more accurate and realistic simulations of transparent objects. IOR is a key material property that dictates how light bends when it passes through a substance https://en.wikipedia.org/wiki/Refractive_index.

The IOR is a dimensionless number that shows the ratio of the speed of light in a vacuum to its speed in a particular medium. Different materials have different IOR values, which influence how light bends when it enters or exits the material. A higher IOR means more refraction. For instance, the IOR of air is nearly 1, water has an IOR of about 1.33, and glass has an IOR of around 1.5.

The KHR_materials_ior extension adds a single property to the glTF material definition:

ior: A floating-point value representing the index-of-refraction of the material.

This value is used in conjunction with the KHR_materials_transmission extension to calculate the refraction direction of light rays when passing through the material.

The source code for this recipe can be found in Chapter07/05_IOR/. Check out the recipe Implementing the transmission extension to recap how KHR_materials_transmission is implemented.

This extension requires only a handful of changes across C++ and GLSL shader code. Let’s start with C++.

  1. In Chapter07/05_IOR/main.cpp, load a corresponding .gltf model:
    GLTFContext gltf(app);
    loadGLTF(gltf,
    "deps/src/glTF-Sample-Assets/Models/
    MosquitoInAmber/glTF/MosquitoInAmber.gltf",
    "deps/src/glTF-Sample-Assets/Models/MosquitoInAmber/glTF/");
  2. Here is the code in shared/UtilsGLTF.cpp for parsing the IOR material parameter with Assimp. You will notice that we don’t set any material flag, it’s not needed. IOR is just a value and does not alter the functionality of shaders.
    ai_real ior;
    if (mtlDescriptor->Get(AI_MATKEY_REFRACTI, ior) == AI_SUCCESS) {
    res.ior = ior;
    }

Here goes the GLSL shader code. We need to modify a few values:

  1. The first value is in the PBR module data/shaders/gltf/PBR.sp in the function calculatePBRInputsMetallicRoughness(). The default index of refraction value, ior = 1.5, results in the f0 term being calculated as 0.04:
    PBRInfo calculatePBRInputsMetallicRoughness(InputAttributes tc,
    vec4 albedo, vec4 mrSample, MetallicRoughnessDataGPU mat) {
    PBRInfo pbrInputs;
    // …
    vec3 f0 = isSpecularGlossiness ?
    getSpecularFactor(mat) * mrSample.rgb :
    vec3(pow((pbrInputs.ior - 1)/( pbrInputs.ior + 1), 2));
  2. The second part is in data/shaders/gltf/main.frag and modifies the clearcoat reflectance value:
    if (isClearCoat) {
    // …
    pbrInputs.clearcoatF0 = vec3(
    pow((pbrInputs.ior - 1.0) / (pbrInputs.ior + 1.0), 2.0));
    // …
    }

That’s it! The application should now render a mosquito encased in a piece of amber, as shown in the following screenshot:

Figure 7.6: KHR_materials_ior example

The official extension specification includes a normative section that explains how this glTF extension KHR_material_ior interacts with other extensions: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_ior/README.md#interaction-with-other-extensions.

Implementing the KHR_materials_specular extension

Section titled “Implementing the KHR_materials_specular extension”

In the previous chapter, we discussed the Specular-Glossiness PBR model. One of its main issues is the lack of compatibility with most other extensions. This is because it introduces non-physically based material properties, including an unclear distinction between dielectrics and metals in specular-glossiness mode, which makes it impossible to combine with the metallic-roughness model or other extension properties.

As an alternative, Khronos proposed the KHR_materials_specular extension, which addresses these issues and offers the functionality of KHR_materials_pbrSpecularGlossiness without compromising the physical accuracy of the Metallic-Roughness PBR model. This makes it compatible with most glTF PBR extensions. At the time of writing, the KHR_materials_specular extension is only incompatible with the KHR_materials_pbrSpecularGlossiness and KHR_materials_unlit extensions.

The KHR_materials_specular extension allows for more precise control over specular reflections in glTF materials. While the core glTF specification includes a basic specular BRDF, this extension introduces additional parameters to better fine-tune the appearance of specular highlights.

The KHR_materials_specular extension introduces several parameters to enhance specular reflections:

  • specularFactor/specularTexture: A scalar value that scales the overall intensity of the specular reflection.
  • specularColorFactor/specularColorTexture: A color value that modifies the color of the specular reflection.

You can convert Specular-Glossiness materials to the Metallic-Roughness workflow using the KHR_materials_ior extension described in the previous recipe Implementing the index-of-refraction extension. By setting the IOR parameter to 0, the material is treated as a dielectric with the maximum specular reflection. The IOR parameter controls the upper limit of the specular reflection’s strength, and setting it to 0 maximizes this strength, allowing full control over specular reflection through the specularColorFactor. This method eliminates the need to classify materials as either dielectric or metallic. It’s important to note that materials using the KHR_materials_volume extension are incompatible with this conversion due to their non-zero IOR value. For new materials, it’s often better to use the Metallic-Roughness model directly.

The source code for this recipe can be found in Chapter07/06_Specular/. Reread two previous recipes Implementing the index-of-refraction extension and Implementing the volume extension as this extension interacts with them.

This extension doesn’t require any major changes to the C++ code, aside from reading the additional material properties via Assimp:

  1. Let’s load a new .gltf model in Chapter07/06_Specular/src/main.cpp:
    VulkanApp app({
    .initialCameraPos = vec3(0.0f, -0.5f, -1.0f),
    .initialCameraTarget = vec3(0.0f, -1.0f, 0.0f),
    });
    GLTFContext gltf(app);
    loadGLTF(gltf, "deps/src/glTF-Sample-Assets/Models/
    SpecularSilkPouf/glTF/SpecularSilkPouf.gltf",
    "deps/src/glTF-Sample-Assets/Models/SpecularSilkPouf/glTF/");
  2. To make this example more interesting, we added rotation to our 3D model:
    const bool rotateModel = true;
    const mat4 t = glm::translate(mat4(1.0f), vec3(0, -1, 0));
    app.run([&](uint32_t width, uint32_t height,
    float aspectRatio, float deltaSeconds)
    {
    const mat4 m = t * glm::rotate(mat4(1.0f),
    rotateModel ? (float)glfwGetTime() : 0.0f,
    vec3(0.0f, 1.0f, 0.0f));
    const mat4 p = glm::perspective(45.0f, aspectRatio, 0.01f, 100.0f);
    renderGLTF(gltf, m, app.camera_.getViewMatrix(), p);
    });
  3. Now, let’s load material properties in shared/UtilsGLTF.cpp:
    loadMaterialTexture(mtlDescriptor, aiTextureType_SPECULAR,
    assetFolder, mat.specularTexture, ctx, true, 0);
    loadMaterialTexture(mtlDescriptor, aiTextureType_SPECULAR,
    assetFolder, mat.specularColorTexture, ctx, true, 1);
    // …
    bool useSpecular = !mat.specularColorTexture.empty() ||
    !mat.specularTexture.empty();
    ai_real specularFactor;
    if (mtlDescriptor->Get(AI_MATKEY_SPECULAR_FACTOR,
    specularFactor) == AI_SUCCESS) {
    res.specularFactors.w = specularFactor;
    useSpecular = true;
    }
    assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_SPECULAR, res.specularTextureUV,
    res.specularTextureSampler, 0);
    aiColor4D specularColorFactor;
    if (mtlDescriptor->Get(AI_MATKEY_COLOR_SPECULAR,
    specularColorFactor) == AI_SUCCESS) {
    res.specularFactors = vec4(specularColorFactor.r,
    specularColorFactor.g,
    specularColorFactor.b,
    res.specularFactors.w);
    useSpecular = true;
    }
    assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_SPECULAR, res.specularColorTextureUV,
    res.specularColorTextureSampler, 1);
    if (useSpecular)
    res.materialTypeFlags |= MaterialType_Specular;
    }

GLSL shader changes are a bit more complex. The specularColor parameter introduces color variations into the specular reflection. It is integrated into the Fresnel term, influencing the specular reflectance at different viewing angles. At normal incidence, the specular color directly scales the base reflectance (F0), while at grazing angles, the reflectance approaches 1.0 regardless of the specular color. To maintain energy conservation, the maximum component of the specular color is used to calculate the scaling factor for the Fresnel term, preventing excessive energy in the specular reflection.

  1. First, we introduce some utility functions in data/shaders/gltf/inputs.frag:
    vec3 getSpecularColorFactor(
    InputAttributes tc, MetallicRoughnessDataGPU mat)
    {
    return mat.specularFactors.rgb *
    textureBindless2D(mat.specularColorTexture,
    mat.specularColorTextureSampler,
    tc.uv[mat.specularColorTextureUV]).rgb;
    }
    float getSpecularFactor(
    InputAttributes tc, MetallicRoughnessDataGPU mat)
    {
    return mat.specularFactors.a *
    textureBindless2D(mat.specularTexture,
    mat.specularTextureSampler,
    tc.uv[mat.specularTextureUV]).a;
    }
  2. We add a new field specularWeight to the PBRInfo structure in data/shaders/gltf/PBR.sp.
    struct PBRInfo {
    // …
    float specularWeight;
    };
  3. We modify the accessor function for obtaining the F0 reflectance and populate the specularWeight field in the calculatePBRInputsMetallicRoughness() function:
    PBRInfo calculatePBRInputsMetallicRoughness(InputAttributes tc,
    vec4 albedo, vec4 mrSample, MetallicRoughnessDataGPU mat) {
    // …
    if (isSpecular) {
    vec3 dielectricSpecularF0 =
    min(f0 * getSpecularColorFactor(tc, mat), vec3(1.0));
    f0 = mix(dielectricSpecularF0, pbrInputs.baseColor.rgb, metallic);
    pbrInputs.specularWeight = getSpecularFactor(tc, mat);
    }
    // …
    vec3 specularColor = isSpecularGlossiness ?
    f0 : mix(f0, pbrInputs.baseColor.rgb, metallic);
    float reflectance = max(
    max(specularColor.r, specularColor.g), specularColor.b);
    // …
  4. Now we can use these parameters in data/shaders/gltf/main.frag to calculate the specular and diffuse components of the IBL contribution:
    vec3 specularColor = getIBLRadianceContributionGGX(
    pbrInputs, pbrInputs.specularWeight, envMap);
    vec3 diffuseColor = getIBLRadianceLambertian(pbrInputs.NdotV,
    n, pbrInputs.perceptualRoughness, pbrInputs.diffuseColor,
    pbrInputs.reflectance0, pbrInputs.specularWeight, envMap);
  5. Here is how the specular contribution is calculated. Note that we multiply by specularWeight at the end of the getIBLRadianceContributionGGX() function:
    vec3 getIBLRadianceContributionGGX(PBRInfo pbrInputs,
    float specularWeight, EnvironmentMapDataGPU envMap) {
    vec3 n = pbrInputs.n;
    vec3 v = pbrInputs.v;
    vec3 reflection = normalize(reflect(-v, n));
    float mipCount = float(sampleEnvMapQueryLevels(envMap));
    float lod = pbrInputs.perceptualRoughness * (mipCount - 1);
    vec2 brdfSamplePoint = clamp(
    vec2(pbrInputs.NdotV, pbrInputs.perceptualRoughness),
    vec2(0.0, 0.0), vec2(1.0, 1.0));
    vec3 brdf = sampleBRDF_LUT(brdfSamplePoint, envMap).rgb;
    vec3 specularLight = sampleEnvMapLod(reflection.xyz, lod, envMap).rgb;
    vec3 Fr = max(vec3(1.0 - pbrInputs.perceptualRoughness),
    pbrInputs.reflectance0) - pbrInputs.reflectance0;
    vec3 k_S = pbrInputs.reflectance0 + Fr * pow(1.0-pbrInputs.NdotV, 5.0);
    vec3 FssEss = k_S * brdf.x + brdf.y;
    return specularWeight * specularLight * FssEss;
    }
  6. The diffuse contribution looks like this. We scale the Fresnel term and replace it with a vec3 RGB value to incorporate the specularColor contribution into F0:
    vec3 getIBLRadianceLambertian(float NdotV, vec3 n,
    float roughness, vec3 diffuseColor, vec3 F0,
    float specularWeight, EnvironmentMapDataGPU envMap) {
    vec2 brdfSamplePoint =
    clamp(vec2(NdotV, roughness), vec2(0., 0.), vec2(1., 1.));
    vec2 f_ab = sampleBRDF_LUT(brdfSamplePoint, envMap).rg;
    vec3 irradiance = sampleEnvMapIrradiance(n.xyz, envMap).rgb;
    vec3 Fr = max(vec3(1.0 - roughness), F0) - F0;
    vec3 k_S = F0 + Fr * pow(1.0 - NdotV, 5.0);
    vec3 FssEss = specularWeight * k_S * f_ab.x + f_ab.y;
    float Ems = (1.0 - (f_ab.x + f_ab.y));
    vec3 F_avg = specularWeight * (F0 + (1.0 - F0) / 21.0);
    vec3 FmsEms = Ems * FssEss * F_avg / (1.0 - F_avg * Ems);
    vec3 k_D = diffuseColor * (1.0 - FssEss + FmsEms);
    return (FmsEms + k_D) * irradiance;
    }
  7. Those are all the changes required to implement the KHR_materials_specular extension in our glTF renderer. The demo application should render a rotating torus as in the following screenshot:

Figure 7.7: KHR_materials_specular example

For further details on the motivation behind this approach, please refer to the Khronos specification https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_specular/README.md. This page provides detailed information about the extension, including explanations of the BRDF and insights into converting between different PBR models.

Implementing the KHR_materials_emissive_strength extension

Section titled “Implementing the KHR_materials_emissive_strength extension”

The metallic-roughness core model supports light emission, but before the introduction of the KHR_materials_emissive_strength extension, it was difficult to control the intensity of a material’s light emission. This made it challenging to create realistic glowing objects or materials that function as light sources in a scene.

The KHR_materials_emissive_strength extension overcomes this limitation by introducing a new property called emissiveStrength. This property allows for precise control over the intensity of a material’s emitted light. With values ranging from 0.0 for no emission to higher values for increased intensity, artists and designers gain more control over the lighting in their scenes.

The source code for this recipe can be found in Chapter07/07_EmissiveStrength/.

This extension is one of the simplest to implement. All it requires is loading an intensity value and applying it to the existing emissive value. Essentially, you only need to take the emissiveStrength property from Assimp, which determines how intense the material’s emitted light should be, and multiply it by the emissive color.

  1. Let’s load a new 3D model in Chapter07/07_EmissiveStrength/src/main.cpp to demonstrate this extension.
    VulkanApp app({
    .initialCameraPos = vec3(0.0f, 5.0f, -10.0f),
    });
    GLTFContext gltf(app);
    loadGLTF(gltf, "deps/src/glTF-Sample-Assets/Models/
    EmissiveStrengthTest/glTF/EmissiveStrengthTest.gltf",
    "deps/src/glTF-Sample-Assets/Models/
    EmissiveStrengthTest/glTF/");
  2. Here’s the C++ code in shared/UtilsGLTF.cpp to retrieve the material properties from Assimp:
    if (mtlDescriptor->Get(AI_MATKEY_COLOR_EMISSIVE,
    aiColor) == AI_SUCCESS) {
    res.emissiveFactorAlphaCutoff = vec4(aiColor.r,
    aiColor.g,
    aiColor.b, 0.5f);
    }
    assignUVandSampler(samplers, mtlDescriptor,
    aiTextureType_EMISSIVE,
    res.emissiveTextureUV,
    res.emissiveTextureSampler);
    ai_real emissiveStrength = 1.0f;
    if (mtlDescriptor->Get(AI_MATKEY_EMISSIVE_INTENSITY,
    emissiveStrength) == AI_SUCCESS) {
    res.emissiveFactorAlphaCutoff *= vec4(
    emissiveStrength, emissiveStrength, emissiveStrength, 1.0);
    }

The resulting demo app should render a set of five glowing cubes, as shown in the following screenshot:

Figure 7.8: KHR_materials_emissive_strength example

Now, let’s jump to the final recipe of this chapter, where we will dive into implementing support for glTF analytical lights.

Extend analytical lights support with KHR_lights_punctual

Section titled “Extend analytical lights support with KHR_lights_punctual”

This is the final recipe in this chapter, and we will add support for analytical light sources to our glTF viewer. In the next chapter, we will cover the KHR_lights_punctual extension, which will allow us to load lighting information directly from glTF assets. In this recipe, we will only be dealing with shader changes.

In the context of glTF PBR, the terms “analytical” and “punctual” lights are often used interchangeably to describe the same type of light source:

  • Analytical light: This refers to light sources defined by mathematical equations, enabling precise calculations of its effect on lighting.
  • Punctual light: This describes light sources that are infinitely small points that emit light in specific directions and intensities.

We will explore these concepts in more detail in the next chapter. In this recipe, fFor simplicity, we’ll use both terms interchangeably.

Let’s review the difference between Image-Based Lighting (IBL) and punctual lights.

IBL simulates indirect lighting from the environment using pre-captured or pre-computed environment maps. In glTF PBR, this environment map is filtered based on roughness and normal direction to approximate incoming radiance. The reflected light is calculated using BRDF (Bidirectional Reflectance Distribution Function) based on the surface material properties, with integration performed over the hemisphere to account for light coming from all directions. Punctual lights, on the other hand, represent specific light sources like point, spot, and directional lights. For each surface point, the direction and distance to the light are calculated, with attenuation applied based on how far the light source is. Shadows are also considered to check if the light reaches the surface. The BRDF is then used to calculate the reflected light based on the light direction, surface normal, and material properties. This method is more computationally expensive than IBL since it requires calculating lighting for each individual light source.

Let’s take a look at how to add glTF punctual lights to our viewer.

The source code for this recipe can be found in Chapter07/08_AnalyticalLight.

C++ code changes are pretty small and straightforward. We introduce additional structures to provide light information data.

  1. First, let’s load a corresponding .gltf model in Chapter07/08_AnalyticalLight/src/main.cpp.
    VulkanApp app({
    .initialCameraPos = vec3(0.0f, 3.5f, -5.0f),
    .initialCameraTarget = vec3(0.0f, 2.0f, 0.0f),
    });
    GLTFContext gltf(app);
    loadGLTF(gltf, "deps/src/glTF-Sample-Assets/Models/
    LightsPunctualLamp/glTF/LightsPunctualLamp.gltf",
    "deps/src/glTF-Sample-Assets/Models/
    LightsPunctualLamp/glTF/");
  2. Declare an enumeration for different light types in shared/UtilsGLTF.h:
    enum LightType : uint32_t {
    LightType_Directional = 0,
    LightType_Point = 1,
    LightType_Spot = 2,
    };
  3. Here’s a structure called LightDataGPU to store light information in GPU buffers. It has default values defining a dummy directional light:
    struct LightDataGPU {
    vec3 direction = vec3(0, 0, 1);
    float range = 10000.0;
    vec3 color = vec3(1, 1, 1);
    float intensity = 1.0;
    vec3 position = vec3(0, 0, -5);
    float innerConeCos = 0.0;
    float outerConeCos = 0.78;
    LightType type = LightType_Directional;
    int padding[2];
    };
    struct EnvironmentsPerFrame {
    EnvironmentMapDataGPU environments[kMaxEnvironments];
    LightDataGPU lights[kMaxLights];
    uint32_t lightCount;
    };
  4. We set up the light sources in shared/UtilsGLTF.cpp as a part of our per-frame constants:
    const EnvironmentsPerFrame envPerFrame = {
    .environments = { { … } },
    .lights = { LightDataGPU() },
    .lightCount = 1,
    };

The changes to the GLSL shader code are substantial. We need to reimplement the specular and diffuse contributions for Metallic-Roughness and other extensions, applying these calculations for each light source individually. In this recipe, we will not go too deep into the implementation details, but we strongly recommend reviewing the actual shaders and the reference materials provided in the comments to fully understand this topic. Here’s a brief glimpse of the changes.

  1. Let’s introduce a couple of utility functions in data/shaders/gltf/inputs.frag to conveniently access the light data:
    uint getLightsCount() {
    return perFrame.environments.lightsCount;
    }
    Light getLight(uint i) {
    return perFrame.environments.lights[i];
    }
  2. In data/shaders/gltf/main.frag, we introduce accumulation variables for each individual contribution component:
    vec3 lights_diffuse = vec3(0);
    vec3 lights_specular = vec3(0);
    vec3 lights_sheen = vec3(0);
    vec3 lights_clearcoat = vec3(0);
    vec3 lights_transmission = vec3(0);
    float albedoSheenScaling = 1.0;
  3. We iterate over all light sources, calculating the necessary terms for each one and checking if the light source is visible from the rendering point. Then we calculate the light intensity:
    for (int i = 0; i < getLightsCount(); ++i) {
    Light light = getLight(i);
    vec3 l = normalize(pointToLight);
    vec3 h = normalize(l + v);
    float NdotL = clampedDot(n, l);
    float NdotV = clampedDot(n, v);
    float NdotH = clampedDot(n, h);
    float LdotH = clampedDot(l, h);
    float VdotH = clampedDot(v, h);
    if (NdotL > 0.0 || NdotV > 0.0) {
    vec3 intensity = getLightIntensity(light, pointToLight);

Note

Evaluating all lights for every object can be quite costly. Alternatives like clustered or deferred shading can help improve performance in this situation.

  1. Then we calculate diffuse and specular contributions for this light:
    lights_diffuse += intensity * NdotL *
    getBRDFLambertian(pbrInputs.reflectance0,
    pbrInputs.reflectance90, pbrInputs.diffuseColor,
    pbrInputs.specularWeight, VdotH);
    lights_specular += intensity * NdotL *
    getBRDFSpecularGGX(pbrInputs.reflectance0,
    pbrInputs.reflectance90, pbrInputs.alphaRoughness,
    pbrInputs.specularWeight, VdotH, NdotL, NdotV, NdotH);
  2. The sheen contribution is now calculated as follows:
    if (isSheen) {
    lights_sheen += intensity *
    getPunctualRadianceSheen(pbrInputs.sheenColorFactor,
    pbrInputs.sheenRoughnessFactor, NdotL, NdotV, NdotH);
    albedoSheenScaling =
    min(1.0 - max3(pbrInputs.sheenColorFactor) *
    albedoSheenScalingFactor(NdotV,
    pbrInputs.sheenRoughnessFactor),
    1.0 - max3(pbrInputs.sheenColorFactor) *
    albedoSheenScalingFactor(NdotL, pbrInputs.sheenRoughnessFactor));
    }
  3. The new clearcoat contribution is calculated in a similar way. Transmission and volume contributions are skipped here for the sake of brevity:
    if (isClearCoat) {
    lights_clearcoat += intensity *
    getPunctualRadianceClearCoat(
    pbrInputs.clearcoatNormal, v, l, h, VdotH,
    pbrInputs.clearcoatF0, pbrInputs.clearcoatF90,
    pbrInputs.clearcoatRoughness);
    }
    // … transmission & volume effects are skipped for brevity
    }
    }
  4. We used a helper function getLightIntensity() which is declared in data/shaders/gltf/PBR.sp:
    vec3 getLightIntensity(Light light, vec3 pointToLight) {
    float rangeAttenuation = 1.0;
    float spotAttenuation = 1.0;
    if (light.type != LightType_Directional) {
    rangeAttenuation =
    getRangeAttenuation(light.range, length(pointToLight));
    }
    if (light.type == LightType_Spot) {
    spotAttenuation = getSpotAttenuation(pointToLight,
    light.direction, light.outerConeCos, light.innerConeCos);
    }
    return rangeAttenuation * spotAttenuation * light.intensity * light.color;
    }

Other helper functions, such as getBRDFLambertian(), getBRDFSpecularGGX(), getBRDFSpecularSheen(), getPunctualRadianceSheen(), and many others mentioned in the GLSL code earlier, are defined in data/shaders/gltf/PBR.sp. These functions contain the math for calculating the specific BRDF terms. For brevity, we do not include them here.

The running application should render a mesh illuminated by an analytical directional light, as shown in the screenshot below:

Figure 7.9: Analytical lights example

With this example, we wrap up our chapter on advanced glTF PBR extensions. We have delved into complex topics and extended our understanding of how to work with various lighting models and extensions. In the next chapter, Graphics Rendering Pipeline, we will shift our focus to the broader organization of 3D scenes. We will explore various data structures and strategies needed to efficiently manage and render multiple 3D models. This will involve a detailed look at how to structure and optimize data for rendering, ensuring smooth and effective visualization of complex scenes.