diff --git a/CMakeLists.txt b/CMakeLists.txt index 626be45..97f7e2a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 @@ -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 diff --git a/docs/roadmap.md b/docs/roadmap.md index 885dbc1..93852be 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -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. diff --git a/shaders/common.slang b/shaders/common.slang index 43957ab..4bf8977 100644 --- a/shaders/common.slang +++ b/shaders/common.slang @@ -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 @@ -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[]; diff --git a/shaders/cube.slang b/shaders/cube.slang new file mode 100644 index 0000000..ed1aab7 --- /dev/null +++ b/shaders/cube.slang @@ -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)); +} diff --git a/shaders/equirect_to_cube.slang b/shaders/equirect_to_cube.slang new file mode 100644 index 0000000..133cbf0 --- /dev/null +++ b/shaders/equirect_to_cube.slang @@ -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 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); +} diff --git a/shaders/irradiance.slang b/shaders/irradiance.slang new file mode 100644 index 0000000..dc9b0d0 --- /dev/null +++ b/shaders/irradiance.slang @@ -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 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); +} diff --git a/shaders/scene.slang b/shaders/scene.slang index a46caa4..9804d0f 100644 --- a/shaders/scene.slang +++ b/shaders/scene.slang @@ -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. @@ -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) { @@ -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]; diff --git a/shaders/skybox.slang b/shaders/skybox.slang index 5e6ba38..5825d75 100644 --- a/shaders/skybox.slang +++ b/shaders/skybox.slang @@ -1,7 +1,5 @@ import common; -static const float PI = 3.14159265359; - struct VSOutput { float4 Pos : SV_POSITION; @@ -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) { @@ -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); } diff --git a/src/app.cpp b/src/app.cpp index db4d70f..3d3096f 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -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(scene_.textures().size()) + 3}, + bindlessTextures_{device_, static_cast(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", @@ -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()); @@ -129,6 +133,7 @@ void App::drawUi() drawLightPanel(light_); drawShadowPanel(shadowSettings_); drawTonemapPanel(tonemapSettings_); + drawEnvironmentPanel(environmentSettings_); } void App::drawFrame() @@ -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}); } diff --git a/src/app.h b/src/app.h index e8b3e5f..e37ed86 100644 --- a/src/app.h +++ b/src/app.h @@ -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" @@ -24,7 +25,6 @@ #include "vk/shader_compiler.h" #include "vk/surface.h" #include "vk/swapchain.h" -#include "vk/texture.h" #include #include @@ -67,6 +67,11 @@ class App return shadowMapTextureIndex() + 1; } + [[nodiscard]] uint32_t irradianceTextureIndex() const + { + return environmentTextureIndex() + 1; + } + Window window_; Instance instance_; Surface surface_; @@ -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_; @@ -92,6 +97,7 @@ class App DirectionalLight light_; ShadowSettings shadowSettings_; TonemapSettings tonemapSettings_; + EnvironmentSettings environmentSettings_; glm::vec2 mouseDelta_{}; bool viewportHovered_{false}; diff --git a/src/render/image_based_lighting.cpp b/src/render/image_based_lighting.cpp new file mode 100644 index 0000000..a271f82 --- /dev/null +++ b/src/render/image_based_lighting.cpp @@ -0,0 +1,218 @@ +#include "render/image_based_lighting.h" + +#include "util/expected.h" +#include "vk/allocator.h" +#include "vk/check.h" +#include "vk/command_pool.h" +#include "vk/compute_pipeline.h" +#include "vk/device.h" +#include "vk/mip_chain.h" +#include "vk/pipeline_cache.h" +#include "vk/shader_compiler.h" +#include "vk/sync.h" +#include "vk/texture.h" + +#include +#include + +namespace +{ + +constexpr uint32_t cubeFaceCount = 6; +constexpr uint32_t workgroupSize = 8; + +VkImageSubresourceRange cubeMipRange(uint32_t baseMip, uint32_t mipCount) +{ + return {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = baseMip, + .levelCount = mipCount, + .layerCount = cubeFaceCount}; +} + +Image createCube(const Allocator& allocator, uint32_t size, uint32_t mipLevels, VkImageUsageFlags usage) +{ + VkImageCreateInfo imageCI{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, + .imageType = VK_IMAGE_TYPE_2D, + .format = ImageBasedLighting::format, + .extent{.width = size, .height = size, .depth = 1}, + .mipLevels = mipLevels, + .arrayLayers = cubeFaceCount, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = usage, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; + return Image{allocator, imageCI, VK_IMAGE_ASPECT_COLOR_BIT}; +} + +// Compute writes a cube one mip at a time through a 2D array view (one layer per face); +// sampling by direction needs a cube view. +DeviceHandle createView(const Device& device, const Image& cube, VkImageViewType viewType, + uint32_t mipCount) +{ + VkImageViewCreateInfo viewCI{.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .image = cube.handle(), + .viewType = viewType, + .format = cube.format(), + .subresourceRange = cubeMipRange(0, mipCount)}; + VkImageView view{VK_NULL_HANDLE}; + chk(vkCreateImageView(device.handle(), &viewCI, nullptr, &view)); + return {device.handle(), view}; +} + +DeviceHandle createCubeSampler(const Device& device) +{ + VkSamplerCreateInfo samplerCI{.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, + .magFilter = VK_FILTER_LINEAR, + .minFilter = VK_FILTER_LINEAR, + .mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR, + .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .maxLod = VK_LOD_CLAMP_NONE}; + VkSampler sampler{VK_NULL_HANDLE}; + chk(vkCreateSampler(device.handle(), &samplerCI, nullptr, &sampler)); + return {device.handle(), sampler}; +} + +// Binding 0: the texture to read. Binding 1: the storage image to write. Pushed straight into the +// command buffer with vkCmdPushDescriptorSetKHR, so there's no pool or set to allocate. +DeviceHandle createReadWriteLayout(const Device& device) +{ + const auto bindings = std::to_array({ + {.binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}, + {.binding = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}, + }); + VkDescriptorSetLayoutCreateInfo layoutCI{.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR, + .bindingCount = static_cast(bindings.size()), + .pBindings = bindings.data()}; + VkDescriptorSetLayout layout{VK_NULL_HANDLE}; + chk(vkCreateDescriptorSetLayout(device.handle(), &layoutCI, nullptr, &layout)); + return {device.handle(), layout}; +} + +// Runs a read-one-texture, write-one-cube shader with one thread per texel of every face. +void dispatchToCube(VkCommandBuffer cb, const ComputePipeline& pipeline, const VkDescriptorImageInfo& input, + VkImageView output, uint32_t outputSize) +{ + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline.handle()); + + const VkDescriptorImageInfo outputInfo{.imageView = output, .imageLayout = VK_IMAGE_LAYOUT_GENERAL}; + const auto writes = std::to_array({ + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .pImageInfo = &input}, + {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, + .pImageInfo = &outputInfo}, + }); + vkCmdPushDescriptorSetKHR(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline.layout(), 0, + static_cast(writes.size()), writes.data()); + + const uint32_t groupCount = (outputSize + workgroupSize - 1) / workgroupSize; + vkCmdDispatch(cb, groupCount, groupCount, cubeFaceCount); +} + +} // namespace + +ImageBasedLighting::ImageBasedLighting(const Device& device, const Allocator& allocator, + const CommandPool& commandPool, const ShaderCompiler& shaderCompiler, + const PipelineCache& pipelineCache, const std::filesystem::path& equirectPath, + const std::filesystem::path& shaderDirectory) + : environment_{createCube(allocator, environmentSize, std::bit_width(environmentSize), + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)}, + environmentCubeView_{createView(device, environment_, VK_IMAGE_VIEW_TYPE_CUBE, environment_.mipLevels())}, + irradiance_{createCube(allocator, irradianceSize, 1, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)}, + irradianceCubeView_{createView(device, irradiance_, VK_IMAGE_VIEW_TYPE_CUBE, 1)}, + sampler_{createCubeSampler(device)} +{ + const Texture equirect = orThrow(Texture::loadHdr(device, allocator, commandPool, equirectPath)); + const DeviceHandle environmentMip0View = + createView(device, environment_, VK_IMAGE_VIEW_TYPE_2D_ARRAY, 1); + + const DeviceHandle setLayout = createReadWriteLayout(device); + const DeviceHandle equirectToCubeShader = + orThrow(shaderCompiler.compile(device, shaderDirectory / "equirect_to_cube.slang")); + const ComputePipeline equirectToCube{ + device, pipelineCache.handle(), equirectToCubeShader.get(), {.setLayout = setLayout.get()}}; + const DeviceHandle irradianceShader = + orThrow(shaderCompiler.compile(device, shaderDirectory / "irradiance.slang")); + const ComputePipeline convolveIrradiance{ + device, pipelineCache.handle(), irradianceShader.get(), {.setLayout = setLayout.get()}}; + + commandPool.submitImmediate( + [&](VkCommandBuffer cb) + { + // Nothing has used either cube yet. Storage image writes need GENERAL; the environment's + // lower mips are filled by blits later, so they start as blit destinations. + pipelineBarrier(cb, std::to_array({ + {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_NONE, + .srcAccessMask = VK_ACCESS_2_NONE, + .dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + .dstAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .image = environment_.handle(), + .subresourceRange = cubeMipRange(0, 1)}, + {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_NONE, + .srcAccessMask = VK_ACCESS_2_NONE, + .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .image = environment_.handle(), + .subresourceRange = cubeMipRange(1, environment_.mipLevels() - 1)}, + {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_NONE, + .srcAccessMask = VK_ACCESS_2_NONE, + .dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + .dstAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .image = irradiance_.handle(), + .subresourceRange = cubeMipRange(0, 1)}, + })); + + dispatchToCube(cb, equirectToCube, equirect.descriptorInfo(), environmentMip0View.get(), environmentSize); + + // Mip 0 is finished; the blits that build the other mips read it. + pipelineBarrier(cb, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + .srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_GENERAL, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .image = environment_.handle(), + .subresourceRange = cubeMipRange(0, 1)}); + recordMipChain(cb, environment_.handle(), {.width = environmentSize, .height = environmentSize}, + environment_.mipLevels(), cubeFaceCount); + + // recordMipChain left the whole environment readable by compute, so the convolution can sample it. + dispatchToCube(cb, convolveIrradiance, environmentDescriptorInfo(), irradiance_.view(), irradianceSize); + + pipelineBarrier(cb, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + .srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, + .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_GENERAL, + .newLayout = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL, + .image = irradiance_.handle(), + .subresourceRange = cubeMipRange(0, 1)}); + }); +} diff --git a/src/render/image_based_lighting.h b/src/render/image_based_lighting.h new file mode 100644 index 0000000..a9b853a --- /dev/null +++ b/src/render/image_based_lighting.h @@ -0,0 +1,62 @@ +#pragma once + +#include + +#include "vk/handle.h" +#include "vk/image.h" + +#include +#include + +class Allocator; +class CommandPool; +class Device; +class PipelineCache; +class ShaderCompiler; + +struct EnvironmentSettings +{ + // Scales the sky and the light it casts on the scene. + float intensity{0.2f}; + // Draws the irradiance cube as the sky instead of the environment. + bool showIrradiance{false}; +}; + +// The lighting environment, built once at load time by compute shaders: an equirectangular .hdr is converted +// into a mipmapped cubemap, which is then convolved into a small irradiance cubemap for diffuse lighting. +// Throws std::runtime_error if the image or a shader fails to load. +class ImageBasedLighting +{ + public: + static constexpr uint32_t environmentSize = 512; + static constexpr uint32_t irradianceSize = 32; + static constexpr VkFormat format = VK_FORMAT_R16G16B16A16_SFLOAT; + + ImageBasedLighting(const Device& device, const Allocator& allocator, const CommandPool& commandPool, + const ShaderCompiler& shaderCompiler, const PipelineCache& pipelineCache, + const std::filesystem::path& equirectPath, const std::filesystem::path& shaderDirectory); + + // The environment cubemap with all its mips, for a SamplerCube. + [[nodiscard]] VkDescriptorImageInfo environmentDescriptorInfo() const + { + return {.sampler = sampler_.get(), + .imageView = environmentCubeView_.get(), + .imageLayout = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL}; + } + + // The irradiance cubemap, for a SamplerCube: indexed by surface normal, it gives the light a diffuse + // surface facing that way receives from the whole environment. + [[nodiscard]] VkDescriptorImageInfo irradianceDescriptorInfo() const + { + return {.sampler = sampler_.get(), + .imageView = irradianceCubeView_.get(), + .imageLayout = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL}; + } + + private: + Image environment_; + DeviceHandle environmentCubeView_; + Image irradiance_; + DeviceHandle irradianceCubeView_; + DeviceHandle sampler_; +}; diff --git a/src/render/scene_pass.h b/src/render/scene_pass.h index ff2d8f0..8d98838 100644 --- a/src/render/scene_pass.h +++ b/src/render/scene_pass.h @@ -33,9 +33,12 @@ struct FrameData float normalOffset; uint32_t showCascades; uint32_t environmentTextureIndex; + uint32_t irradianceTextureIndex; + uint32_t showIrradiance; + float environmentIntensity; }; static_assert(ShadowPass::cascadeCount == 4, "cascadeSplitDepths and cascadeTexelSizes hold one float per cascade"); -static_assert(sizeof(FrameData) == 480); +static_assert(sizeof(FrameData) == 492); struct DrawConstants { diff --git a/src/ui/panels.cpp b/src/ui/panels.cpp index 6109032..af5fe55 100644 --- a/src/ui/panels.cpp +++ b/src/ui/panels.cpp @@ -2,6 +2,7 @@ #include +#include "render/image_based_lighting.h" #include "render/shadow_pass.h" #include "render/tonemap_pass.h" #include "scene/light.h" @@ -83,3 +84,11 @@ void drawTonemapPanel(TonemapSettings& settings) ImGui::SliderFloat("Exposure", &settings.exposure, 0.01f, 10.0f, "%.2f", ImGuiSliderFlags_Logarithmic); ImGui::End(); } + +void drawEnvironmentPanel(EnvironmentSettings& settings) +{ + ImGui::Begin(ICON_FA_CLOUD_SUN " Environment###Environment"); + ImGui::SliderFloat("Intensity", &settings.intensity, 0.0f, 10.0f, "%.2f"); + ImGui::Checkbox("Show irradiance as sky", &settings.showIrradiance); + ImGui::End(); +} diff --git a/src/ui/panels.h b/src/ui/panels.h index ae8d5a1..5acb417 100644 --- a/src/ui/panels.h +++ b/src/ui/panels.h @@ -9,6 +9,7 @@ class Scene; class ViewportTarget; struct DirectionalLight; +struct EnvironmentSettings; struct ShadowSettings; struct TonemapSettings; @@ -25,3 +26,4 @@ void drawStatsPanel(const Scene& scene, const ViewportTarget& viewport); void drawLightPanel(DirectionalLight& light); void drawShadowPanel(ShadowSettings& settings); void drawTonemapPanel(TonemapSettings& settings); +void drawEnvironmentPanel(EnvironmentSettings& settings); diff --git a/src/vk/device.cpp b/src/vk/device.cpp index e822a91..96aa17e 100644 --- a/src/vk/device.cpp +++ b/src/vk/device.cpp @@ -103,7 +103,8 @@ Device::Device(const Instance& instance, const Surface& surface) .queueCount = 1, .pQueuePriorities = &queuePriority}; - const auto deviceExtensions = std::to_array({VK_KHR_SWAPCHAIN_EXTENSION_NAME}); + const auto deviceExtensions = + std::to_array({VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME}); VkPhysicalDeviceVulkan12Features enabledVk12Features{.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, .descriptorIndexing = true, diff --git a/src/vk/mip_chain.cpp b/src/vk/mip_chain.cpp new file mode 100644 index 0000000..9e55d49 --- /dev/null +++ b/src/vk/mip_chain.cpp @@ -0,0 +1,80 @@ +#include "vk/mip_chain.h" + +#include "vk/sync.h" + +#include +#include + +namespace +{ + +VkImageSubresourceRange mipRange(uint32_t baseMip, uint32_t mipCount, uint32_t layerCount) +{ + return {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = baseMip, + .levelCount = mipCount, + .layerCount = layerCount}; +} + +VkOffset3D mipExtent(VkExtent2D extent, uint32_t mip) +{ + return {.x = static_cast(std::max(extent.width >> mip, 1u)), + .y = static_cast(std::max(extent.height >> mip, 1u)), + .z = 1}; +} + +} // namespace + +void recordMipChain(VkCommandBuffer cb, VkImage image, VkExtent2D extent, uint32_t mipLevels, uint32_t layerCount) +{ + for (uint32_t mip = 1; mip < mipLevels; mip++) + { + // The previous mip was just written (by the copy or the last blit); it becomes the blit source. + pipelineBarrier(cb, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .image = image, + .subresourceRange = mipRange(mip - 1, 1, layerCount)}); + + const VkImageBlit blit{.srcSubresource{.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = mip - 1, + .layerCount = layerCount}, + .srcOffsets{{}, mipExtent(extent, mip - 1)}, + .dstSubresource{.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = mip, + .layerCount = layerCount}, + .dstOffsets{{}, mipExtent(extent, mip)}}; + vkCmdBlitImage(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, + &blit, VK_FILTER_LINEAR); + } + + constexpr VkPipelineStageFlags2 shaderReadStages = + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; + // Every mip but the last was a blit source; the last was only ever written. + std::vector toShaderRead{{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = shaderReadStages, + .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL, + .image = image, + .subresourceRange = mipRange(mipLevels - 1, 1, layerCount)}}; + if (mipLevels > 1) + { + toShaderRead.push_back({.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .srcAccessMask = VK_ACCESS_2_NONE, + .dstStageMask = shaderReadStages, + .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL, + .image = image, + .subresourceRange = mipRange(0, mipLevels - 1, layerCount)}); + } + pipelineBarrier(cb, toShaderRead); +} diff --git a/src/vk/mip_chain.h b/src/vk/mip_chain.h new file mode 100644 index 0000000..c13a874 --- /dev/null +++ b/src/vk/mip_chain.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include + +// Records blits that fill mips 1 and up of every layer, each from the mip above it, then leaves every mip in +// READ_ONLY_OPTIMAL for fragment and compute shaders. Expects every mip in TRANSFER_DST_OPTIMAL, with mip 0 +// already written by a transfer (or made visible to the transfer stage by a barrier). +void recordMipChain(VkCommandBuffer cb, VkImage image, VkExtent2D extent, uint32_t mipLevels, uint32_t layerCount = 1); diff --git a/src/vk/texture.cpp b/src/vk/texture.cpp index 889cbca..2b7b21c 100644 --- a/src/vk/texture.cpp +++ b/src/vk/texture.cpp @@ -10,6 +10,7 @@ #include "vk/check.h" #include "vk/command_pool.h" #include "vk/device.h" +#include "vk/mip_chain.h" #include "vk/sync.h" #include @@ -42,13 +43,6 @@ VkImageSubresourceRange mipRange(uint32_t baseMip, uint32_t mipCount) return {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = baseMip, .levelCount = mipCount, .layerCount = 1}; } -VkOffset3D mipExtent(uint32_t width, uint32_t height, uint32_t mip) -{ - return {.x = static_cast(std::max(width >> mip, 1u)), - .y = static_cast(std::max(height >> mip, 1u)), - .z = 1}; -} - DeviceHandle createSampler(const Device& device, uint32_t mipLevels) { VkSamplerCreateInfo samplerCI{.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, @@ -95,10 +89,13 @@ std::expected Texture::loadHdr(const Device& device, const if (!pixels) return std::unexpected{std::format("Failed to load HDR image {}: {}", path.string(), stbi_failure_reason())}; + // The sun in an HDR sky can be brighter than the largest half float. Clamping keeps it finite: as infinity it + // would spread through mip blits and turn every sample of it into NaN. + static constexpr float maxHalf = 65504.0f; const auto channelCount = static_cast(width) * static_cast(height) * 4; std::vector halfPixels(channelCount); std::ranges::transform(std::span{pixels.get(), channelCount}, halfPixels.begin(), - [](float channel) { return glm::packHalf1x16(channel); }); + [](float channel) { return glm::packHalf1x16(std::min(channel, maxHalf)); }); return fromPixels(device, allocator, commandPool, static_cast(width), static_cast(height), std::as_bytes(std::span{halfPixels}), VK_FORMAT_R16G16B16A16_SFLOAT); @@ -153,51 +150,7 @@ std::expected Texture::fromPixels(const Device& device, co vkCmdCopyBufferToImage(cb, stagingBuffer.handle(), image.handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Region); - for (uint32_t mip = 1; mip < mipLevels; mip++) - { - // The previous mip was just written (by the copy or the last blit); it becomes the blit source. - pipelineBarrier(cb, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, - .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT, - .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - .image = image.handle(), - .subresourceRange = mipRange(mip - 1, 1)}); - - const VkImageBlit blit{ - .srcSubresource{.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .mipLevel = mip - 1, .layerCount = 1}, - .srcOffsets{{}, mipExtent(width, height, mip - 1)}, - .dstSubresource{.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .mipLevel = mip, .layerCount = 1}, - .dstOffsets{{}, mipExtent(width, height, mip)}}; - vkCmdBlitImage(cb, image.handle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image.handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); - } - - // Every mip but the last was a blit source; the last was only ever written. - std::vector toShaderRead{{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, - .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, - .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, - .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL, - .image = image.handle(), - .subresourceRange = mipRange(mipLevels - 1, 1)}}; - if (mipLevels > 1) - { - toShaderRead.push_back({.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .srcAccessMask = VK_ACCESS_2_NONE, - .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, - .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, - .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL, - .image = image.handle(), - .subresourceRange = mipRange(0, mipLevels - 1)}); - } - pipelineBarrier(cb, toShaderRead); + recordMipChain(cb, image.handle(), {.width = width, .height = height}, mipLevels); }); return Texture{std::move(image), createSampler(device, mipLevels)};