Skip to content

Commit 2f59399

Browse files
committed
Merge branch 'deferred-direct-light'
2 parents 23fab5d + 51dbf12 commit 2f59399

12 files changed

Lines changed: 902 additions & 106 deletions

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ An interactive experimental pathtracer, implemented using WebGPU via the [Dawn](
3939
- [Sky Dome Appearance Project](https://cgg.mff.cuni.cz/projects/SkylightModelling/)
4040
- The original source of the sky and solar disk model
4141
- The following [Rust implementation](https://github.com/phoekz/hw-skymodel) serves as the basis of the much simplified C code used in this project.
42+
- Depth precision and reverse Z projection
43+
- [Depth Precision Visualized](https://www.reedbeta.com/blog/depth-precision-visualized/)
44+
- [Reverse Z (and why it's so awesome)](https://tomhultonharrop.com/mathematics/graphics/2023/08/06/reverse-z.html)
4245

4346
## Build
4447

‎src/common/camera.cpp‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -49,19 +49,4 @@ Ray generateCameraRay(const Camera& camera, const float u, const float v)
4949

5050
return Ray{.origin = origin, .direction = glm::normalize(direction)};
5151
}
52-
53-
glm::mat4 generateViewProjectionMatrix(
54-
glm::vec3 origin,
55-
glm::vec3 lookAt,
56-
Angle vfov,
57-
float aspectRatio)
58-
{
59-
const glm::vec3 forward = glm::normalize(lookAt - origin);
60-
const glm::vec3 worldUp = glm::vec3(0.0f, 1.0f, 0.0f);
61-
const glm::vec3 right = glm::normalize(glm::cross(forward, worldUp));
62-
const glm::vec3 up = glm::cross(right, forward);
63-
64-
return glm::perspective(vfov.asRadians(), aspectRatio, 0.1f, 1000.0f) *
65-
glm::lookAt(origin, lookAt, up);
66-
}
6752
} // namespace nlrs

‎src/common/camera.hpp‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,4 @@ Camera createCamera(
3232
// (u, v) are in [0, 1] range, where (0, 0) is the lower left corner and (1, 1) is the upper right
3333
// corner.
3434
Ray generateCameraRay(const Camera& camera, float u, float v);
35-
36-
glm::mat4 generateViewProjectionMatrix(
37-
glm::vec3 origin,
38-
glm::vec3 lookAt,
39-
Angle vfov,
40-
float aspectRatio);
4135
} // namespace nlrs

‎src/pt/deferred_renderer.cpp‎

Lines changed: 152 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "gpu_context.hpp"
2+
#include "gpu_limits.hpp"
23
#include "deferred_renderer.hpp"
34
#include "shader_source.hpp"
45
#include "webgpu_utils.hpp"
@@ -14,7 +15,7 @@ namespace nlrs
1415
{
1516
namespace
1617
{
17-
const WGPUTextureFormat DEPTH_TEXTURE_FORMAT = WGPUTextureFormat_Depth24Plus;
18+
const WGPUTextureFormat DEPTH_TEXTURE_FORMAT = WGPUTextureFormat_Depth32Float;
1819
const WGPUTextureFormat ALBEDO_TEXTURE_FORMAT = WGPUTextureFormat_BGRA8Unorm;
1920
const WGPUTextureFormat NORMAL_TEXTURE_FORMAT = WGPUTextureFormat_RGBA16Float;
2021

@@ -184,7 +185,13 @@ DeferredRenderer::DeferredRenderer(
184185
}
185186

186187
mDebugPass = DebugPass{gpuContext, mGbufferBindGroupLayout, rendererDesc.framebufferSize};
187-
mLightingPass = LightingPass{gpuContext, mGbufferBindGroupLayout};
188+
mLightingPass = LightingPass{
189+
gpuContext,
190+
mGbufferBindGroupLayout,
191+
rendererDesc.sceneBvhNodes,
192+
rendererDesc.scenePositionAttributes,
193+
rendererDesc.sceneVertexAttributes,
194+
rendererDesc.sceneBaseColorTextures};
188195
}
189196

190197
DeferredRenderer::~DeferredRenderer()
@@ -227,7 +234,7 @@ void DeferredRenderer::render(const GpuContext& gpuContext, const RenderDescript
227234
offsetof(TimestampsLayout, gbufferPassStart) / TimestampsLayout::MEMBER_SIZE);
228235
mGbufferPass.render(
229236
gpuContext,
230-
renderDesc.viewProjectionMatrix,
237+
renderDesc.viewReverseZProjectionMatrix,
231238
encoder,
232239
mDepthTextureView,
233240
mAlbedoTextureView,
@@ -242,8 +249,9 @@ void DeferredRenderer::render(const GpuContext& gpuContext, const RenderDescript
242249
mQuerySet,
243250
offsetof(TimestampsLayout, lightingPassStart) / TimestampsLayout::MEMBER_SIZE);
244251
{
245-
const glm::mat4 inverseViewProjectionMat = glm::inverse(renderDesc.viewProjectionMatrix);
246-
const Extent2f framebufferSize = Extent2f(renderDesc.framebufferSize);
252+
const glm::mat4 inverseViewProjectionMat =
253+
glm::inverse(renderDesc.viewReverseZProjectionMatrix);
254+
const Extent2f framebufferSize = Extent2f(renderDesc.framebufferSize);
247255
mLightingPass.render(
248256
gpuContext,
249257
mGbufferBindGroup,
@@ -498,13 +506,13 @@ DeferredRenderer::GbufferPass::GbufferPass(
498506
return buffers;
499507
}()),
500508
mBaseColorTextureIndices(
501-
rendererDesc.baseColorTextureIndices.begin(),
502-
rendererDesc.baseColorTextureIndices.end()),
509+
rendererDesc.modelBaseColorTextureIndices.begin(),
510+
rendererDesc.modelBaseColorTextureIndices.end()),
503511
mBaseColorTextures([&gpuContext, &rendererDesc]() -> std::vector<GpuTexture> {
504512
std::vector<GpuTexture> textures;
505513
std::transform(
506-
rendererDesc.baseColorTextures.begin(),
507-
rendererDesc.baseColorTextures.end(),
514+
rendererDesc.sceneBaseColorTextures.begin(),
515+
rendererDesc.sceneBaseColorTextures.end(),
508516
std::back_inserter(textures),
509517
[&gpuContext](const Texture& texture) -> GpuTexture {
510518
const auto dimensions = texture.dimensions();
@@ -713,7 +721,7 @@ DeferredRenderer::GbufferPass::GbufferPass(
713721
.nextInChain = nullptr,
714722
.format = DEPTH_TEXTURE_FORMAT,
715723
.depthWriteEnabled = true,
716-
.depthCompare = WGPUCompareFunction_Less,
724+
.depthCompare = WGPUCompareFunction_Greater,
717725
.stencilFront = DEFAULT_STENCIL_FACE_STATE,
718726
.stencilBack = DEFAULT_STENCIL_FACE_STATE,
719727
.stencilReadMask = 0, // stencil masks deactivated by setting to zero
@@ -842,14 +850,18 @@ DeferredRenderer::GbufferPass::~GbufferPass()
842850

843851
void DeferredRenderer::GbufferPass::render(
844852
const GpuContext& gpuContext,
845-
const glm::mat4& viewProjectionMat,
853+
const glm::mat4& viewReverseZProjectionMatrix,
846854
const WGPUCommandEncoder cmdEncoder,
847855
const WGPUTextureView depthTextureView,
848856
const WGPUTextureView albedoTextureView,
849857
const WGPUTextureView normalTextureView)
850858
{
851859
wgpuQueueWriteBuffer(
852-
gpuContext.queue, mUniformBuffer.ptr(), 0, &viewProjectionMat[0][0], sizeof(glm::mat4));
860+
gpuContext.queue,
861+
mUniformBuffer.ptr(),
862+
0,
863+
&viewReverseZProjectionMatrix[0][0],
864+
sizeof(glm::mat4));
853865

854866
const WGPURenderPassEncoder renderPassEncoder = [cmdEncoder,
855867
depthTextureView,
@@ -879,9 +891,9 @@ void DeferredRenderer::GbufferPass::render(
879891
.view = depthTextureView,
880892
.depthLoadOp = WGPULoadOp_Clear,
881893
.depthStoreOp = WGPUStoreOp_Store,
882-
.depthClearValue = 1.0f,
894+
.depthClearValue = 0.0f,
883895
.depthReadOnly = false,
884-
.stencilLoadOp = WGPULoadOp_Undefined, // ops must not be set if no stencil aspect
896+
.stencilLoadOp = WGPULoadOp_Undefined,
885897
.stencilStoreOp = WGPUStoreOp_Undefined,
886898
.stencilClearValue = 0,
887899
.stencilReadOnly = true,
@@ -1177,8 +1189,12 @@ void DeferredRenderer::DebugPass::render(
11771189
}
11781190

11791191
DeferredRenderer::LightingPass::LightingPass(
1180-
const GpuContext& gpuContext,
1181-
const GpuBindGroupLayout& gbufferBindGroupLayout)
1192+
const GpuContext& gpuContext,
1193+
const GpuBindGroupLayout& gbufferBindGroupLayout,
1194+
std::span<const BvhNode> sceneBvhNodes,
1195+
std::span<const PositionAttribute> scenePositionAttributes,
1196+
std::span<const VertexAttributes> sceneVertexAttributes,
1197+
std::span<const Texture> sceneBaseColorTextures)
11821198
: mCurrentSky{},
11831199
mVertexBuffer{
11841200
gpuContext.device,
@@ -1197,6 +1213,24 @@ DeferredRenderer::LightingPass::LightingPass(
11971213
GpuBufferUsage::Uniform | GpuBufferUsage::CopyDst,
11981214
sizeof(Uniforms)},
11991215
mUniformBindGroup{},
1216+
mBvhNodeBuffer{
1217+
gpuContext.device,
1218+
"BVH node buffer",
1219+
GpuBufferUsage::ReadOnlyStorage | GpuBufferUsage::CopyDst,
1220+
std::span<const BvhNode>(sceneBvhNodes)},
1221+
mPositionAttributesBuffer{
1222+
gpuContext.device,
1223+
"Position attribute buffer",
1224+
GpuBufferUsage::ReadOnlyStorage | GpuBufferUsage::CopyDst,
1225+
std::span<const PositionAttribute>(scenePositionAttributes)},
1226+
mVertexAttributesBuffer{
1227+
gpuContext.device,
1228+
"Vertex attribute buffer",
1229+
GpuBufferUsage::ReadOnlyStorage | GpuBufferUsage::CopyDst,
1230+
std::span<const VertexAttributes>(sceneVertexAttributes)},
1231+
mTextureDescriptorBuffer{},
1232+
mTextureBuffer{},
1233+
mBvhBindGroup{},
12001234
mPipeline(nullptr)
12011235
{
12021236
{
@@ -1227,13 +1261,96 @@ DeferredRenderer::LightingPass::LightingPass(
12271261
uniformBindGroupLayout.ptr(),
12281262
mUniformBuffer.bindGroupEntry(0)};
12291263

1264+
{
1265+
struct TextureDescriptor
1266+
{
1267+
std::uint32_t width, height, offset;
1268+
};
1269+
// Ensure matches layout of `TextureDescriptor` definition in shader.
1270+
std::vector<TextureDescriptor> textureDescriptors;
1271+
textureDescriptors.reserve(sceneBaseColorTextures.size());
1272+
1273+
std::vector<Texture::BgraPixel> textureData;
1274+
textureData.reserve((2 << 28) / sizeof(Texture::BgraPixel));
1275+
1276+
// Texture descriptors and texture data need to appended in the order of
1277+
// sceneBaseColorTextures. The vertex attribute's `textureIdx` indexes into that array, and
1278+
// we want to use the same indices to index into the texture descriptor array.
1279+
1280+
for (const Texture& baseColorTexture : sceneBaseColorTextures)
1281+
{
1282+
const auto dimensions = baseColorTexture.dimensions();
1283+
const auto pixels = baseColorTexture.pixels();
1284+
1285+
const std::uint32_t width = dimensions.width;
1286+
const std::uint32_t height = dimensions.height;
1287+
const std::uint32_t offset = static_cast<std::uint32_t>(textureData.size());
1288+
1289+
textureData.resize(textureData.size() + pixels.size());
1290+
std::memcpy(
1291+
textureData.data() + offset,
1292+
pixels.data(),
1293+
pixels.size() * sizeof(Texture::BgraPixel));
1294+
1295+
textureDescriptors.push_back({width, height, offset});
1296+
}
1297+
1298+
mTextureDescriptorBuffer = GpuBuffer(
1299+
gpuContext.device,
1300+
"texture descriptor buffer",
1301+
GpuBufferUsage::ReadOnlyStorage | GpuBufferUsage::CopyDst,
1302+
std::span<const TextureDescriptor>(textureDescriptors));
1303+
1304+
const std::size_t textureDataNumBytes = textureData.size() * sizeof(Texture::BgraPixel);
1305+
const std::size_t maxStorageBufferBindingSize =
1306+
static_cast<std::size_t>(REQUIRED_LIMITS.maxStorageBufferBindingSize);
1307+
if (textureDataNumBytes > maxStorageBufferBindingSize)
1308+
{
1309+
throw std::runtime_error(fmt::format(
1310+
"Texture buffer size ({}) exceeds "
1311+
"maxStorageBufferBindingSize ({}).",
1312+
textureDataNumBytes,
1313+
maxStorageBufferBindingSize));
1314+
}
1315+
1316+
mTextureBuffer = GpuBuffer(
1317+
gpuContext.device,
1318+
"texture buffer",
1319+
GpuBufferUsage::ReadOnlyStorage | GpuBufferUsage::CopyDst,
1320+
std::span<const Texture::BgraPixel>(textureData));
1321+
}
1322+
1323+
const GpuBindGroupLayout bvhBindGroupLayout{
1324+
gpuContext.device,
1325+
"Scene bind group layout",
1326+
std::array<WGPUBindGroupLayoutEntry, 5>{
1327+
mBvhNodeBuffer.bindGroupLayoutEntry(0, WGPUShaderStage_Fragment),
1328+
mPositionAttributesBuffer.bindGroupLayoutEntry(1, WGPUShaderStage_Fragment),
1329+
mVertexAttributesBuffer.bindGroupLayoutEntry(2, WGPUShaderStage_Fragment),
1330+
mTextureDescriptorBuffer.bindGroupLayoutEntry(3, WGPUShaderStage_Fragment),
1331+
mTextureBuffer.bindGroupLayoutEntry(4, WGPUShaderStage_Fragment),
1332+
}};
1333+
1334+
mBvhBindGroup = GpuBindGroup{
1335+
gpuContext.device,
1336+
"Lighting pass BVH bind group",
1337+
bvhBindGroupLayout.ptr(),
1338+
std::array<WGPUBindGroupEntry, 5>{
1339+
mBvhNodeBuffer.bindGroupEntry(0),
1340+
mPositionAttributesBuffer.bindGroupEntry(1),
1341+
mVertexAttributesBuffer.bindGroupEntry(2),
1342+
mTextureDescriptorBuffer.bindGroupEntry(3),
1343+
mTextureBuffer.bindGroupEntry(4),
1344+
}};
1345+
12301346
{
12311347
// Pipeline layout
12321348

12331349
const WGPUBindGroupLayout bindGroupLayouts[] = {
12341350
skyStateBindGroupLayout.ptr(),
12351351
uniformBindGroupLayout.ptr(),
1236-
gbufferBindGroupLayout.ptr()};
1352+
gbufferBindGroupLayout.ptr(),
1353+
bvhBindGroupLayout.ptr()};
12371354

12381355
const WGPUPipelineLayoutDescriptor pipelineLayoutDesc{
12391356
.nextInChain = nullptr,
@@ -1370,8 +1487,15 @@ DeferredRenderer::LightingPass::LightingPass(LightingPass&& other) noexcept
13701487
mSkyStateBindGroup = std::move(other.mSkyStateBindGroup);
13711488
mUniformBuffer = std::move(other.mUniformBuffer);
13721489
mUniformBindGroup = std::move(other.mUniformBindGroup);
1490+
mBvhNodeBuffer = std::move(other.mBvhNodeBuffer);
1491+
mPositionAttributesBuffer = std::move(other.mPositionAttributesBuffer);
1492+
mVertexAttributesBuffer = std::move(other.mVertexAttributesBuffer);
1493+
mTextureDescriptorBuffer = std::move(other.mTextureDescriptorBuffer);
1494+
mTextureBuffer = std::move(other.mTextureBuffer);
1495+
mBvhBindGroup = std::move(other.mBvhBindGroup);
13731496
mPipeline = other.mPipeline;
13741497
other.mPipeline = nullptr;
1498+
mFrameCount = other.mFrameCount;
13751499
}
13761500
}
13771501

@@ -1386,9 +1510,16 @@ DeferredRenderer::LightingPass& DeferredRenderer::LightingPass::operator=(
13861510
mSkyStateBindGroup = std::move(other.mSkyStateBindGroup);
13871511
mUniformBuffer = std::move(other.mUniformBuffer);
13881512
mUniformBindGroup = std::move(other.mUniformBindGroup);
1513+
mBvhNodeBuffer = std::move(other.mBvhNodeBuffer);
1514+
mPositionAttributesBuffer = std::move(other.mPositionAttributesBuffer);
1515+
mVertexAttributesBuffer = std::move(other.mVertexAttributesBuffer);
1516+
mTextureDescriptorBuffer = std::move(other.mTextureDescriptorBuffer);
1517+
mTextureBuffer = std::move(other.mTextureBuffer);
1518+
mBvhBindGroup = std::move(other.mBvhBindGroup);
13891519
renderPipelineSafeRelease(mPipeline);
13901520
mPipeline = other.mPipeline;
13911521
other.mPipeline = nullptr;
1522+
mFrameCount = other.mFrameCount;
13921523
}
13931524
return *this;
13941525
}
@@ -1398,7 +1529,7 @@ void DeferredRenderer::LightingPass::render(
13981529
const GpuBindGroup& gbufferBindGroup,
13991530
const WGPUCommandEncoder cmdEncoder,
14001531
const WGPUTextureView targetTextureView,
1401-
const glm::mat4& inverseViewProjectionMat,
1532+
const glm::mat4& inverseViewReverseZProjectionMatrix,
14021533
const glm::vec3& cameraPosition,
14031534
const Extent2f& fbsize,
14041535
const Sky& sky,
@@ -1414,11 +1545,11 @@ void DeferredRenderer::LightingPass::render(
14141545

14151546
{
14161547
const Uniforms uniforms{
1417-
inverseViewProjectionMat,
1548+
inverseViewReverseZProjectionMatrix,
14181549
glm::vec4(cameraPosition, 1.f),
14191550
glm::vec2(fbsize.x, fbsize.y),
14201551
exposure,
1421-
0.f};
1552+
mFrameCount++};
14221553
wgpuQueueWriteBuffer(
14231554
gpuContext.queue, mUniformBuffer.ptr(), 0, &uniforms, sizeof(Uniforms));
14241555
}
@@ -1453,6 +1584,7 @@ void DeferredRenderer::LightingPass::render(
14531584
wgpuRenderPassEncoderSetBindGroup(renderPass, 0, mSkyStateBindGroup.ptr(), 0, nullptr);
14541585
wgpuRenderPassEncoderSetBindGroup(renderPass, 1, mUniformBindGroup.ptr(), 0, nullptr);
14551586
wgpuRenderPassEncoderSetBindGroup(renderPass, 2, gbufferBindGroup.ptr(), 0, nullptr);
1587+
wgpuRenderPassEncoderSetBindGroup(renderPass, 3, mBvhBindGroup.ptr(), 0, nullptr);
14561588
wgpuRenderPassEncoderSetVertexBuffer(
14571589
renderPass, 0, mVertexBuffer.ptr(), 0, mVertexBuffer.byteSize());
14581590
wgpuRenderPassEncoderDraw(renderPass, 6, 1, 0, 0);

0 commit comments

Comments
 (0)