Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ add_executable(vkdriven
src/platform/file_watcher.h
src/platform/window.cpp
src/platform/window.h
src/render/image_based_lighting.cpp
src/render/image_based_lighting.h
src/render/scene_draws.cpp
src/render/scene_draws.h
src/render/scene_pass.cpp
Expand Down Expand Up @@ -101,6 +103,8 @@ add_executable(vkdriven
src/vk/image.h
src/vk/instance.cpp
src/vk/instance.h
src/vk/mip_chain.cpp
src/vk/mip_chain.h
src/vk/pipeline_cache.cpp
src/vk/pipeline_cache.h
src/vk/shader_compiler.cpp
Expand Down
2 changes: 1 addition & 1 deletion docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ Follow [LearnOpenGL](https://learnopengl.com/)'s *Advanced Lighting* and *PBR* c
- [x] Cook-Torrance BRDF: GGX NDF, Smith geometry term, Schlick Fresnel. Material gains metallic/roughness factors and the glTF metallic-roughness texture (blue = metallic, green = roughness); `FrameData` gains camera position and light color × intensity (*PBR → Lighting*)
- [x] Normal mapping with the glTF `TANGENT` attribute (Sponza ships it) and a flat-normal default texture (*Normal Mapping*)
- [x] Compute pipelines and a `VkPipelineCache` saved to disk (needed for IBL below; not in the tutorial)
- [ ] Image-based lighting: equirect→cubemap and diffuse irradiance convolution (*PBR → IBL → Diffuse irradiance*). The tutorial renders each cubemap face with a framebuffer; do it in a **compute shader** writing to a cube storage image instead.
- [x] Image-based lighting: equirect→cubemap and diffuse irradiance convolution (*PBR → IBL → Diffuse irradiance*). The tutorial renders each cubemap face with a framebuffer; do it in a **compute shader** writing to a cube storage image instead.
- [ ] Specular prefiltered environment map (per-mip roughness) and BRDF LUT, also in compute (*PBR → IBL → Specular IBL*)
- [x] Shadow mapping basics: single directional shadow map, depth bias, PCF (*Shadows → Shadow Mapping*). Remember reverse-Z flips the comparison.
- [x] **Cascaded shadow maps**: cascade splits, a layered depth image, cascade selection (*Guest Articles → Cascaded Shadow Mapping*). Beyond the tutorial: texel snapping to stop shimmering, and normal-offset bias.
Expand Down
5 changes: 5 additions & 0 deletions shaders/common.slang
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ public struct FrameData
public float normalOffset;
public uint showCascades;
public uint environmentTextureIndex;
public uint irradianceTextureIndex;
public uint showIrradiance;
public float environmentIntensity;
};

public struct Material
Expand Down Expand Up @@ -63,3 +66,5 @@ public struct DrawConstants
[[vk::push_constant]] public DrawConstants constants;

[[vk::binding(0, 0)]] public Sampler2D textures[];
// The same bindless array viewed as cubemaps: index it only at slots that hold a cube view.
[[vk::binding(0, 0)]] public SamplerCube cubeTextures[];
29 changes: 29 additions & 0 deletions shaders/cube.slang
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module cube;

// The direction through a point on a cube face, with uv in [-1, 1] and v pointing down the face.
// Faces are in the order Vulkan stores them: +X, -X, +Y, -Y, +Z, -Z.
public float3 cubeDirection(uint face, float2 uv)
{
switch (face)
{
case 0:
return float3(1.0, -uv.y, -uv.x);
case 1:
return float3(-1.0, -uv.y, uv.x);
case 2:
return float3(uv.x, 1.0, uv.y);
case 3:
return float3(uv.x, -1.0, -uv.y);
case 4:
return float3(uv.x, -uv.y, 1.0);
default:
return float3(-uv.x, -uv.y, -1.0);
}
}

// The direction through the center of texel `texel` on face `face` of a size × size cube.
public float3 cubeTexelDirection(uint3 texel, uint size)
{
float2 uv = (float2(texel.xy) + 0.5) / float(size) * 2.0 - 1.0;
return normalize(cubeDirection(texel.z, uv));
}
26 changes: 26 additions & 0 deletions shaders/equirect_to_cube.slang
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import cube;

static const float PI = 3.14159265359;

[[vk::binding(0, 0)]] Sampler2D equirect;
[[vk::binding(1, 0)]] [[vk::image_format("rgba16f")]] RWTexture2DArray<float4> environment;

// Longitude around the Y axis becomes u, latitude from straight up (v = 0) to straight down (v = 1) becomes v.
float2 equirectUV(float3 direction)
{
return float2(atan2(direction.z, direction.x) / (2.0 * PI) + 0.5, acos(clamp(direction.y, -1.0, 1.0)) / PI);
}

// One thread per cube texel: x and y pick the texel, z picks the face.
[shader("compute")]
[numthreads(8, 8, 1)]
void main(uint3 dispatchThreadID : SV_DispatchThreadID)
{
uint size, height, faceCount;
environment.GetDimensions(size, height, faceCount);
if (dispatchThreadID.x >= size || dispatchThreadID.y >= size)
return;

float3 direction = cubeTexelDirection(dispatchThreadID, size);
environment[dispatchThreadID] = float4(equirect.SampleLevel(equirectUV(direction), 0.0).rgb, 1.0);
}
50 changes: 50 additions & 0 deletions shaders/irradiance.slang
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import cube;

static const float PI = 3.14159265359;
// Angle between hemisphere samples, in radians: about 250 × 63 samples per texel.
static const float sampleDelta = 0.025;

[[vk::binding(0, 0)]] SamplerCube environment;
[[vk::binding(1, 0)]] [[vk::image_format("rgba16f")]] RWTexture2DArray<float4> irradiance;

// For each texel's direction N, sums the light arriving from the whole hemisphere around N, weighted by
// cos(theta): how much a diffuse surface facing N receives (LearnOpenGL, PBR -> IBL -> Diffuse irradiance).
[shader("compute")]
[numthreads(8, 8, 1)]
void main(uint3 dispatchThreadID : SV_DispatchThreadID)
{
uint size, height, faceCount;
irradiance.GetDimensions(size, height, faceCount);
if (dispatchThreadID.x >= size || dispatchThreadID.y >= size)
return;

float3 normal = cubeTexelDirection(dispatchThreadID, size);

// A tangent frame around the normal, so hemisphere samples can be written as angles relative to it.
float3 up = abs(normal.y) < 0.999 ? float3(0.0, 1.0, 0.0) : float3(0.0, 0.0, 1.0);
float3 right = normalize(cross(up, normal));
up = cross(normal, right);

// Each sample stands for about sampleDelta² steradians. Reading the mip whose texels are about that size
// averages small bright spots (the sun) in, instead of each sample either hitting or missing them.
uint environmentSize, environmentHeight, mipCount;
environment.GetDimensions(0, environmentSize, environmentHeight, mipCount);
float texelSolidAngle = 4.0 * PI / (6.0 * float(environmentSize * environmentSize));
float lod = 0.5 * log2(sampleDelta * sampleDelta / texelSolidAngle);

float3 sum = 0.0;
uint sampleCount = 0;
for (float phi = 0.0; phi < 2.0 * PI; phi += sampleDelta)
{
for (float theta = 0.0; theta < 0.5 * PI; theta += sampleDelta)
{
float3 tangentSample = float3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta));
float3 direction = tangentSample.x * right + tangentSample.y * up + tangentSample.z * normal;
// cos(theta): light from grazing angles spreads over more surface. sin(theta): rings of samples near
// the pole are smaller, so they count for less.
sum += environment.SampleLevel(direction, lod).rgb * cos(theta) * sin(theta);
sampleCount++;
}
}
irradiance[dispatchThreadID] = float4(PI * sum / float(sampleCount), 1.0);
}
16 changes: 14 additions & 2 deletions shaders/scene.slang
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ VSOutput main(VSInput input)
return output;
}

static const float ambientStrength = 0.03;
static const float minRoughness = 0.04;

// Moves the normal map's tangent-space normal into world space with the TBN basis.
Expand Down Expand Up @@ -135,6 +134,13 @@ float3 FresnelSchlick(float cosTheta, float3 F0)
return F0 + (1.0 - F0) * pow(saturate(1.0 - cosTheta), 5.0);
}

// Fresnel for light from the whole environment rather than one direction: there's no single half vector,
// so N·V stands in for it, and rough surfaces get less of the bright grazing-angle reflection.
float3 FresnelSchlickRoughness(float cosTheta, float3 F0, float roughness)
{
return F0 + (max(float3(1.0 - roughness), F0) - F0) * pow(saturate(1.0 - cosTheta), 5.0);
}

// diffuse = kD * albedo / PI
float3 Diffuse(float3 F, float3 albedo, float metallic)
{
Expand Down Expand Up @@ -190,7 +196,13 @@ float4 main(VSOutput input)
// The vertex normal, not the normal-mapped one: the offset has to follow the geometry the shadow map stored.
float3 Lo = (diffuse + specular) * radiance * NdotL * Shadow(input.WorldPos, vertexNormal, cascade);

float3 ambient = ambientStrength * albedo;
// Diffuse IBL: the irradiance map already holds the cosine-weighted light from the whole hemisphere
// around N, so one lookup replaces integrating the environment here. As with the sun, only the part
// that isn't reflected as specular (kD) is diffused, and metals don't diffuse at all.
float3 kS = FresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);
float3 kD = (1.0 - kS) * (1.0 - metallic);
float3 irradiance = cubeTextures[constants.frame->irradianceTextureIndex].SampleLevel(N, 0.0).rgb;
float3 ambient = kD * irradiance * albedo * constants.frame->environmentIntensity;
float3 color = ambient + Lo;
if (constants.frame->showCascades != 0 && cascade < cascadeCount)
color *= cascadeColors[cascade];
Expand Down
13 changes: 2 additions & 11 deletions shaders/skybox.slang
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import common;

static const float PI = 3.14159265359;

struct VSOutput
{
float4 Pos : SV_POSITION;
Expand All @@ -20,12 +18,6 @@ VSOutput main(uint vertexID : SV_VulkanVertexID)
return output;
}

// Longitude around the Y axis becomes u, latitude from straight up (v = 0) to straight down (v = 1) becomes v.
float2 equirectUV(float3 direction)
{
return float2(atan2(direction.z, direction.x) / (2.0 * PI) + 0.5, acos(clamp(direction.y, -1.0, 1.0)) / PI);
}

[shader("fragment")]
float4 main(VSOutput input)
{
Expand All @@ -36,8 +28,7 @@ float4 main(VSOutput input)
float3 viewDirection = float3(input.NDC.x / frame->projection[0][0], input.NDC.y / frame->projection[1][1], -1.0);
float3 worldDirection = normalize(mul(viewDirection, (float3x3)frame->view));

// Mip 0 explicitly: at the u = 0/1 seam the UV derivatives jump, which would otherwise pick a tiny mip
// and draw a visible line down the sky.
float3 radiance = textures[frame->environmentTextureIndex].SampleLevel(equirectUV(worldDirection), 0.0).rgb;
uint cubeIndex = frame->showIrradiance != 0 ? frame->irradianceTextureIndex : frame->environmentTextureIndex;
float3 radiance = cubeTextures[cubeIndex].SampleLevel(worldDirection, 0.0).rgb * frame->environmentIntensity;
return float4(radiance, 1.0);
}
16 changes: 12 additions & 4 deletions src/app.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ App::App()
swapchain_{device_, surface_, window_}, commandPool_{device_},
frames_{device_, allocator_, commandPool_, sizeof(FrameData)},
scene_{orThrow(Scene::loadGltf(device_, allocator_, commandPool_, scenePath))},
environment_{orThrow(Texture::loadHdr(device_, allocator_, commandPool_, environmentPath))},
bindlessTextures_{device_, static_cast<uint32_t>(scene_.textures().size()) + 3},
bindlessTextures_{device_, static_cast<uint32_t>(scene_.textures().size()) + 4},
pipelineCache_{device_, pipelineCachePath}, shaderDirectory_{VKDRIVEN_SHADER_DIR},
imageBasedLighting_{device_, allocator_, commandPool_, shaderCompiler_, pipelineCache_, environmentPath,
shaderDirectory_},
shadowPass_{device_, allocator_, shaderCompiler_, pipelineCache_, bindlessTextures_,
shaderDirectory_ / "shadow.slang"},
scenePass_{device_, shaderCompiler_, pipelineCache_, bindlessTextures_, shaderDirectory_ / "scene.slang",
Expand All @@ -48,9 +49,12 @@ App::App()
const VkDescriptorImageInfo shadowMapInfo = shadowPass_.descriptorInfo();
bindlessTextures_.write(std::span{&shadowMapInfo, 1}, shadowMapTextureIndex());

const VkDescriptorImageInfo environmentInfo = environment_.descriptorInfo();
const VkDescriptorImageInfo environmentInfo = imageBasedLighting_.environmentDescriptorInfo();
bindlessTextures_.write(std::span{&environmentInfo, 1}, environmentTextureIndex());

const VkDescriptorImageInfo irradianceInfo = imageBasedLighting_.irradianceDescriptorInfo();
bindlessTextures_.write(std::span{&irradianceInfo, 1}, irradianceTextureIndex());

std::println("Loaded {}: {} meshes, {} primitives, {} vertices, {} indices, {} draws, {} transforms, {} textures",
scenePath, scene_.meshes().size(), scene_.primitives().size(), scene_.vertexCount(),
scene_.indexCount(), scene_.draws().size(), scene_.transforms().size(), scene_.textures().size());
Expand Down Expand Up @@ -129,6 +133,7 @@ void App::drawUi()
drawLightPanel(light_);
drawShadowPanel(shadowSettings_);
drawTonemapPanel(tonemapSettings_);
drawEnvironmentPanel(environmentSettings_);
}

void App::drawFrame()
Expand Down Expand Up @@ -199,7 +204,10 @@ void App::updateFrameData(Frame& frame) const
.shadowMapTextureIndex = shadowMapTextureIndex(),
.normalOffset = shadowSettings_.normalOffset,
.showCascades = shadowSettings_.showCascades ? 1u : 0u,
.environmentTextureIndex = environmentTextureIndex()};
.environmentTextureIndex = environmentTextureIndex(),
.irradianceTextureIndex = irradianceTextureIndex(),
.showIrradiance = environmentSettings_.showIrradiance ? 1u : 0u,
.environmentIntensity = environmentSettings_.intensity};
frame.shaderData.write(std::span{&frameData, 1});
}

Expand Down
10 changes: 8 additions & 2 deletions src/app.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

#include "platform/file_watcher.h"
#include "platform/window.h"
#include "render/image_based_lighting.h"
#include "render/scene_pass.h"
#include "render/shadow_pass.h"
#include "render/tonemap_pass.h"
Expand All @@ -24,7 +25,6 @@
#include "vk/shader_compiler.h"
#include "vk/surface.h"
#include "vk/swapchain.h"
#include "vk/texture.h"

#include <cstdint>
#include <filesystem>
Expand Down Expand Up @@ -67,6 +67,11 @@ class App
return shadowMapTextureIndex() + 1;
}

[[nodiscard]] uint32_t irradianceTextureIndex() const
{
return environmentTextureIndex() + 1;
}

Window window_;
Instance instance_;
Surface surface_;
Expand All @@ -76,11 +81,11 @@ class App
CommandPool commandPool_;
FrameResources frames_;
Scene scene_;
Texture environment_;
BindlessTextures bindlessTextures_;
ShaderCompiler shaderCompiler_;
PipelineCache pipelineCache_;
std::filesystem::path shaderDirectory_;
ImageBasedLighting imageBasedLighting_;
ShadowPass shadowPass_;
ScenePass scenePass_;
TonemapPass tonemapPass_;
Expand All @@ -92,6 +97,7 @@ class App
DirectionalLight light_;
ShadowSettings shadowSettings_;
TonemapSettings tonemapSettings_;
EnvironmentSettings environmentSettings_;
glm::vec2 mouseDelta_{};
bool viewportHovered_{false};

Expand Down
Loading
Loading