diff --git a/editor/Resources/splash_images/Toasty1.jpg b/editor/Resources/splash_images/Toasty1.jpg new file mode 100644 index 000000000..5eb5e24e5 Binary files /dev/null and b/editor/Resources/splash_images/Toasty1.jpg differ diff --git a/editor/Resources/splash_images/Toasty2.jpg b/editor/Resources/splash_images/Toasty2.jpg new file mode 100644 index 000000000..3805879f2 Binary files /dev/null and b/editor/Resources/splash_images/Toasty2.jpg differ diff --git a/editor/Resources/splash_images/Toasty3.jpg b/editor/Resources/splash_images/Toasty3.jpg new file mode 100644 index 000000000..ee380dc54 Binary files /dev/null and b/editor/Resources/splash_images/Toasty3.jpg differ diff --git a/engine/assets/shaders/bloom.slang b/engine/assets/shaders/bloom.slang index c14f6a2e2..ca7a7a693 100644 --- a/engine/assets/shaders/bloom.slang +++ b/engine/assets/shaders/bloom.slang @@ -12,7 +12,10 @@ struct BloomParams float strength; - float2 _pad0; + /// Scale on the light behind glass so emissives the glass dims still bloom + float glassScale; + + float _pad0; }; [[vk::push_constant]] @@ -30,10 +33,12 @@ Sampler2D gGlassBackdrop; [[vk::binding(3,0)]] Sampler2D gGlassMask; +/// Where glass covers a pixel the brighter of the glass composite and the scaled light behind it float3 bloomSource(float2 uv) { - float m = gGlassMask.Sample(uv).r; - return lerp(gSource.Sample(uv).rgb, gGlassBackdrop.Sample(uv).rgb, m); + const float3 source = gSource.Sample(uv).rgb; + const float m = gGlassMask.Sample(uv).r; + return lerp(source, max(source, gGlassBackdrop.Sample(uv).rgb * gParams.glassScale), m); } typedef FullscreenVSOutput VSOutput; diff --git a/engine/assets/shaders/debris.slang b/engine/assets/shaders/debris.slang index 5996268a8..28ad88f0b 100644 --- a/engine/assets/shaders/debris.slang +++ b/engine/assets/shaders/debris.slang @@ -3,7 +3,6 @@ struct Params { float3 gravity; float dt; - float fadeIn; float restitution; float friction; float voxelSize; @@ -19,6 +18,7 @@ struct Params { uint pad0; uint pad1; uint pad2; + uint pad3; }; [[vk::push_constant]] @@ -34,7 +34,8 @@ struct DebrisParticle { uint albedo; float scale; uint glass; - uint pad0; + /// Palette emissive intensity + float emissive; uint pad1; }; @@ -58,7 +59,7 @@ struct DebrisSpawn { float lifetime; float scale; uint glass; - uint pad0; + float emissive; }; struct DebrisVolume { @@ -90,6 +91,9 @@ StructuredBuffer gVolumes; StructuredBuffer gRetires; [[vk::binding(8, 0)]] RWStructuredBuffer gGrid; +/// Opaque caster box min xyz and max xyz as ordered uints then changing pieces then the fastest speed bits +[[vk::binding(9, 0)]] +RWStructuredBuffer gShadowBounds; struct VolumeRecord { uint brickDimsX; @@ -125,7 +129,6 @@ static const uint kTagUniform = 1; static const uint kMaskBits = 0xFFu; static const uint kFlagAsleep = 1u << 24; static const uint kFlagGlass = 1u << 25; -static const float kSpawnScale = 0.4; // grows from this share of its size static const float kSleepSpeed = 0.2; // below this speed a piece may sleep static const uint kSleepSteps = 15; @@ -239,11 +242,10 @@ float pieceRadius(uint mask, float scale) { return gParams.voxelSize * scale * lerp(0.6, 1.0, float(countbits(mask & kMaskBits)) / 8.0); } -// Grows in after spawning and shrinks away before dying +// Shrinks away before dying float displayScale(DebrisMotion motion) { - float grow = lerp(kSpawnScale, 1.0, saturate(motion.age / max(gParams.fadeIn, 1e-4))); float shrink = smoothstep(0.0, max(gParams.fadeOut, 1e-4), motion.lifetime - motion.age); - return motion.baseScale * grow * shrink; + return motion.baseScale * shrink; } struct Contact { @@ -361,9 +363,46 @@ void appendVoxels(uint index, uint mask, bool glass) { } } +/// Sorts like the float it came from +uint orderedFloat(float value) { + uint bits = asuint(value); + return (bits & 0x80000000u) != 0u ? ~bits : bits | 0x80000000u; +} + +/// Feeds the shadow pass cull and cache, changing means its shadow moves this step +void addShadowCaster(DebrisParticle particle, DebrisMotion motion, bool changing) { + if ((particle.packed & kFlagGlass) != 0u) { + return; + } + // Two voxel wide box around the center at any rotation + const float radius = 1.74 * gParams.voxelSize * motion.baseScale; + const float3 low = particle.position - radius; + const float3 high = particle.position + radius; + InterlockedMin(gShadowBounds[0], orderedFloat(low.x)); + InterlockedMin(gShadowBounds[1], orderedFloat(low.y)); + InterlockedMin(gShadowBounds[2], orderedFloat(low.z)); + InterlockedMax(gShadowBounds[3], orderedFloat(high.x)); + InterlockedMax(gShadowBounds[4], orderedFloat(high.y)); + InterlockedMax(gShadowBounds[5], orderedFloat(high.z)); + const bool fading = motion.age > motion.lifetime - gParams.fadeOut; + if (changing || fading) { + InterlockedAdd(gShadowBounds[6], 1u); + } + // Positive floats sort as uints + InterlockedMax(gShadowBounds[7], asuint(length(particle.velocity))); +} + [shader("compute")] [numthreads(1, 1, 1)] void resetMain(uint3 id : SV_DispatchThreadID) { + gShadowBounds[0] = 0xFFFFFFFFu; + gShadowBounds[1] = 0xFFFFFFFFu; + gShadowBounds[2] = 0xFFFFFFFFu; + gShadowBounds[3] = 0u; + gShadowBounds[4] = 0u; + gShadowBounds[5] = 0u; + gShadowBounds[6] = 0u; + gShadowBounds[7] = 0u; gDrawArgs[0] = 36u; gDrawArgs[1] = 0u; gDrawArgs[2] = 0u; @@ -544,6 +583,7 @@ void integrateMain(uint3 id : SV_DispatchThreadID, uint3 groupThread : SV_GroupT gCurrent[i] = particle; gMotion[i] = motion; appendVoxels(i, mask, glass); + addShadowCaster(particle, motion, false); return; } particle.packed &= ~kFlagAsleep; @@ -695,6 +735,8 @@ void integrateMain(uint3 id : SV_DispatchThreadID, uint3 groupThread : SV_GroupT gCurrent[i] = particle; gMotion[i] = motion; appendVoxels(i, mask, glass); + // Falling asleep this step still moved it + addShadowCaster(particle, motion, true); } [shader("compute")] @@ -717,7 +759,7 @@ void spawnMain(uint3 id : SV_DispatchThreadID) { particle.velocity = spawn.velocity; particle.albedo = spawn.albedo; particle.glass = spawn.glass; - particle.pad0 = 0u; + particle.emissive = spawn.emissive; particle.pad1 = 0u; DebrisMotion motion; @@ -733,4 +775,5 @@ void spawnMain(uint3 id : SV_DispatchThreadID) { gCurrent[spawn.slot] = particle; appendVoxels(spawn.slot, spawn.packed & kMaskBits, (spawn.packed & kFlagGlass) != 0u); + addShadowCaster(particle, motion, true); } diff --git a/engine/assets/shaders/debris_draw.slang b/engine/assets/shaders/debris_draw.slang index 4ef2460a9..6718b7ed7 100644 --- a/engine/assets/shaders/debris_draw.slang +++ b/engine/assets/shaders/debris_draw.slang @@ -3,12 +3,18 @@ import voxel_gbuffer; import lighting; import gi_sample; import glass_common; +import glass_reflection; struct PushConstants { float extrapolation; float frameDelta; float voxelSize; uint listCapacity; + /// Screen march reach in meters and 0 leaves glass with the environment + float reflectionReach; + uint reflectionSteps; + float reflectionThickness; + float reflectionRoughness; }; [[vk::push_constant]] @@ -23,7 +29,8 @@ struct DebrisParticle { uint albedo; float scale; uint glass; - uint pad0; + /// Palette emissive intensity + float emissive; uint pad1; }; @@ -32,6 +39,12 @@ StructuredBuffer gParticles; [[vk::binding(1, 1)]] StructuredBuffer gDrawList; +/// Opaque scene colour and depth before anything blended, only read while reflectionReach is above 0 +[[vk::binding(0, 2)]] +Sampler2D gBackdrop; +[[vk::binding(1, 2)]] +Sampler2D gBackdropDepth; + static const float3 kDebrisBoxCorners[8] = { float3(0.0, 0.0, 0.0), float3(1.0, 0.0, 0.0), float3(1.0, 1.0, 0.0), float3(0.0, 1.0, 0.0), float3(0.0, 0.0, 1.0), float3(1.0, 0.0, 1.0), float3(1.0, 1.0, 1.0), float3(0.0, 1.0, 1.0), @@ -84,6 +97,9 @@ struct VSOutput { [[vk::location(9)]] nointerpolation float scale : TEXCOORD9; + + [[vk::location(10)]] + nointerpolation float emissive : TEXCOORD10; }; float3 debrisRotate(float4 q, float3 v) { @@ -108,6 +124,7 @@ VSOutput emptyVertex() { output.cameraLocal = float3(0.0, 0.0, 0.0); output.cellMin = float3(0.0, 0.0, 0.0); output.scale = 0.0; + output.emissive = 0.0; return output; } @@ -140,6 +157,7 @@ VSOutput debrisVertex(uint entry, uint vertexId) { output.cameraLocal = debrisRotate(inverse, gCamera.position - center) / max(worldScale, 1e-6); output.cellMin = cell - 1.0; output.scale = particle.scale; + output.emissive = particle.emissive; return output; } @@ -188,7 +206,7 @@ FSOutput fragmentMain(VSOutput input) { output.albedo = float4(debrisAlbedo(input.albedo), kGbufferLit); output.faceNormal = encodeFaceNormal(normalize(input.normal)); output.detailNormal = output.faceNormal; - output.material = float4(metallic, reflectivity, debrisRoughness(input.albedo), encodeEmissive(0.0)); + output.material = float4(metallic, reflectivity, debrisRoughness(input.albedo), encodeEmissive(input.emissive)); output.motion = float4((clip.xy / clip.w - previousClip.xy / previousClip.w) * 0.5, 0.0, 1.0); return output; } @@ -237,9 +255,19 @@ GlassShade shadeDebrisGlass(VSOutput input) { const float scatter = glassScatter(alpha, roughness); const float3 diffuse = max(lit.color - lit.specular, float3(0.0, 0.0, 0.0)); + float3 litSpecular = lit.specular; + float3 reflection; + // shortcut: mirror ray only so rough pieces below the cutoff reflect too sharp, upgrade to a GGX lobe sample with TAA + // Pieces past the reach are a few pixels and would only march to miss + if (gPush.reflectionReach > 0.0 && roughness <= gPush.reflectionRoughness && + distance(gCamera.position, input.worldPosition) <= gPush.reflectionReach && + glassScreenReflection(gBackdrop, gBackdropDepth, input.worldPosition, reflect(-view, normal), gPush.reflectionReach, + gPush.reflectionSteps, gPush.reflectionThickness, reflection)) { + litSpecular = glassReflectionSpecular(lit.specular, lit.ambientSpecular, reflection, normal, view, roughness); + } // Lighting assumes F0 0.04 so rescale by the Fresnel ratio - const float3 specular = lit.specular * fresnel / (0.04 + 0.96 * facing); - shade.color = diffuse * scatter + specular; + const float3 specular = litSpecular * fresnel / (0.04 + 0.96 * facing); + shade.color = diffuse * scatter + albedo * input.emissive * alpha + specular; // Front faces only so the exit face is the far slab of this voxel const float3 direction = normalize(input.boxLocal - input.cameraLocal); diff --git a/engine/assets/shaders/debris_shadow.slang b/engine/assets/shaders/debris_shadow.slang new file mode 100644 index 000000000..70a6dcca9 --- /dev/null +++ b/engine/assets/shaders/debris_shadow.slang @@ -0,0 +1,66 @@ +// Opaque debris voxels into the shadow maps as moving casters +import shadow_views; + +/// Mirrors renderer::ShadowPass::DebrisShadowPush +struct PushConstants { + float extrapolation; + float voxelSize; + uint listCapacity; + uint viewIndex; +}; + +[[vk::push_constant]] +PushConstants gPush; + +// Mirrors physics::DebrisSimulation::GpuParticle and the set 1 of debris_draw.slang so DebrisPass sets bind here +struct DebrisParticle { + float3 position; + uint packed; + float4 rotation; + float3 velocity; + uint albedo; + float scale; + uint glass; + float emissive; + uint pad1; +}; + +[[vk::binding(0, 1)]] +StructuredBuffer gParticles; +[[vk::binding(1, 1)]] +StructuredBuffer gDrawList; + +static const float3 kDebrisBoxCorners[8] = { + float3(0.0, 0.0, 0.0), float3(1.0, 0.0, 0.0), float3(1.0, 1.0, 0.0), float3(0.0, 1.0, 0.0), + float3(0.0, 0.0, 1.0), float3(1.0, 0.0, 1.0), float3(1.0, 1.0, 1.0), float3(0.0, 1.0, 1.0), +}; + +static const uint kDebrisBoxIndices[36] = { + 0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, + 3, 7, 6, 3, 6, 2, 0, 4, 7, 0, 7, 3, 1, 2, 6, 1, 6, 5, +}; + +float3 debrisRotate(float4 q, float3 v) { + const float3 t = 2.0 * cross(q.xyz, v); + return v + q.w * t + cross(q.xyz, t); +} + +[shader("vertex")] +float4 vertexMain(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID, uint viewId : SV_ViewID) : SV_Position { + if (instanceId >= gPush.listCapacity) { + return float4(0.0, 0.0, 0.0, 1.0); + } + const uint entry = gDrawList[instanceId]; + const DebrisParticle particle = gParticles[entry >> 3]; + const uint bit = entry & 7u; + if (((particle.packed >> bit) & 1u) == 0u || particle.scale <= 0.0) { + return float4(0.0, 0.0, 0.0, 1.0); + } + + // Same box as debrisVertex in debris_draw.slang + const float3 cell = float3(float(bit & 1u), float((bit >> 1) & 1u), float(bit >> 2)); + const float3 boxLocal = cell - 1.0 + kDebrisBoxCorners[kDebrisBoxIndices[vertexId]]; + const float3 center = particle.position + particle.velocity * gPush.extrapolation; + const float3 world = center + debrisRotate(particle.rotation, boxLocal * (gPush.voxelSize * particle.scale)); + return mul(gShadow.viewProjection[gPush.viewIndex + viewId], float4(world, 1.0)); +} diff --git a/engine/assets/shaders/gi_clip_fill.slang b/engine/assets/shaders/gi_clip_fill.slang index f6d75033e..536a92106 100644 --- a/engine/assets/shaders/gi_clip_fill.slang +++ b/engine/assets/shaders/gi_clip_fill.slang @@ -112,6 +112,49 @@ void clipSample(uint v, float3 world, float gap, uint index, inout ClipCell cell cell.emission += palette.albedo * palette.emissive; } +/// False when no solid coarse block of the volume touches the cell so all its samples would miss +bool clipCellReaches(uint v, float3 low, float cellSize) +{ + const VoxelInstance volume = gTraceVolumes[v]; + const VolumeRecord record = gVolumeRecords[volume.recordIndex]; + float3 lo = float3(kFloatMax, kFloatMax, kFloatMax); + float3 hi = -lo; + for (uint corner = 0u; corner < 8u; ++corner) + { + const float3 world = low + float3(corner & 1u, (corner >> 1) & 1u, corner >> 2) * cellSize; + const float3 voxel = mul(volume.worldToVoxel, float4(world, 1.0)).xyz; + lo = min(lo, voxel); + hi = max(hi, voxel); + } + const int3 dims = int3(record.brickDimsX, record.brickDimsY, record.brickDimsZ) * int(kBrickDim); + const int3 first = max(int3(floor(lo)), int3(0, 0, 0)) >> 5; + const int3 last = min(int3(floor(hi)), dims - 1) >> 5; + if (any(first > last)) + { + return false; + } + // A cell spanning many blocks is cheaper to just sample + const int3 count = last - first + 1; + if (count.x * count.y * count.z > 8) + { + return true; + } + for (int z = first.z; z <= last.z; ++z) + { + for (int y = first.y; y <= last.y; ++y) + { + for (int x = first.x; x <= last.x; ++x) + { + if (coarseSolid(record, int3(x, y, z))) + { + return true; + } + } + } + } + return false; +} + /// 16 bits of one z layer at x + 4 y uint clipLayer(ClipCell cell, uint z) { @@ -169,7 +212,7 @@ void fillMain(uint3 id : SV_DispatchThreadID) { const uint v = gTraceGrid[farBase + f]; const float4 bounds = gTraceBounds[v]; - if (distance(centre, bounds.xyz) > bounds.w + cellSize * 0.8661) + if (distance(centre, bounds.xyz) > bounds.w + cellSize * 0.8661 || !clipCellReaches(v, low, cellSize)) { continue; } diff --git a/engine/assets/shaders/gi_clip_inject.slang b/engine/assets/shaders/gi_clip_inject.slang index e1c598520..a20841ed3 100644 --- a/engine/assets/shaders/gi_clip_inject.slang +++ b/engine/assets/shaders/gi_clip_inject.slang @@ -63,6 +63,26 @@ void clipAddLight(inout ClipFaces faces, uint exposed, float3 L, float3 radiance } } +/// Centre of the open neighbour on the face most turned to the light and half a cell toward it +/// Starting off the face and not along the light keeps grazing rays out of the cells beside it which would shadow the +/// whole ring past some angle and make it jump a cell as the light moves +float3 clipLightOrigin(uint exposed, float3 centre, float3 L, float cellSize) +{ + float best = -2.0; + float3 normal = L; + for (uint face = 0u; face < kGiClipFaces; ++face) + { + const float3 direction = float3(giClipFace(face)); + const float facing = dot(direction, L); + if ((exposed & (1u << face)) != 0u && facing > best) + { + best = facing; + normal = direction; + } + } + return centre + normal * cellSize + L * (0.5 * cellSize); +} + [shader("compute")] [numthreads(4, 4, 4)] void injectMain(uint3 id : SV_DispatchThreadID) @@ -110,7 +130,7 @@ void injectMain(uint3 id : SV_DispatchThreadID) const float3 emission = gEmission.Load(int4(texel, 0)).rgb; const float3 centre = giClipCellCentre(frame, level, global); - // Past the cell and its direct neighbours so they never shadow it + // Kept clear of the lamp end so the cells holding it do not block it const float lift = 1.5 * cellSize; const float sunReach = 0.5 * float(resolution) * frame.levels[frame.size.y - 1u].w; ClipFaces faces; @@ -127,7 +147,7 @@ void injectMain(uint3 id : SV_DispatchThreadID) { continue; } - const float visibility = giClipVisibility(frame, centre + L * lift, L * sunReach); + const float visibility = giClipVisibility(frame, clipLightOrigin(exposed, centre, L, cellSize), L * sunReach); clipAddLight(faces, exposed, L, light.colorIntensity.rgb * (light.colorIntensity.a * visibility)); } @@ -137,13 +157,20 @@ void injectMain(uint3 id : SV_DispatchThreadID) const GpuLight light = gLights[li]; float3 L; float distance; - const float3 radiance = lightSampleRadiance(light, centre, light.worldPosRange.xyz, L, distance); + float3 radiance = lightSampleRadiance(light, centre, light.worldPosRange.xyz, L, distance); if (all(radiance <= 0.0) || clipFaceCosines(exposed, L) <= 0.0) { continue; } + // The cell stands for a whole cell of surface so the inverse square stops at a cell or cells next to the lamp + // swing by orders of magnitude with where it sits inside its cell and the bounce flares with them + const float nearest = max(distance, cellSize); + radiance *= (distance * distance) / (nearest * nearest); // Stops short of the lamp so the cells holding it do not block it - const float visibility = giClipVisibility(frame, centre + L * lift, L * max(distance - 2.0 * lift, 0.0)); + const float3 origin = clipLightOrigin(exposed, centre, L, cellSize); + const float3 toLight = light.worldPosRange.xyz - origin; + const float reach = max(length(toLight) - 2.0 * lift, 0.0); + const float visibility = reach > 0.0 ? giClipVisibility(frame, origin, normalize(toLight) * reach) : 1.0; clipAddLight(faces, exposed, L, radiance * visibility); } diff --git a/engine/assets/shaders/gi_sample.slang b/engine/assets/shaders/gi_sample.slang index 4358f3710..07e6a9df5 100644 --- a/engine/assets/shaders/gi_sample.slang +++ b/engine/assets/shaders/gi_sample.slang @@ -186,6 +186,8 @@ static const float kGiClipConeBias = 0.0; /// Cells of level 0 the cones start off the surface so its own cells do not shade it static const float kGiClipConeLift = 1.5; static const float kGiClipFaceWeight = 1e-4; +/// Highest level the cones read through the B-spline filter +static const uint kGiClipSmoothLevels = 1u; /// Premultiplied face radiance toward the ray and opacity along it where @p lod above 0 reads last level mips float4 giClipSample(GiClipFrame frame, uint level, float lod, float3 world, float3 direction) @@ -227,10 +229,10 @@ float4 giClipSmoothTap(float3 cell, float3 f, float cells, uint tap) } /// Rounds the creases trilinear leaves at 8 reads per texture and recomputes taps per read to save registers -float4 giClipSampleSmooth(GiClipFrame frame, float3 world, float3 direction) +float4 giClipSampleSmooth(GiClipFrame frame, uint level, float3 world, float3 direction) { const float cells = float(frame.size.x); - const float3 p = world / frame.levels[0].w; + const float3 p = world / frame.levels[level].w; const float3 cell = floor(p); // Offset from the centre of the cell holding the point in -0.5 to 0.5 const float3 f = p - cell - 0.5; @@ -239,7 +241,7 @@ float4 giClipSampleSmooth(GiClipFrame frame, float3 world, float3 direction) for (uint tap = 0u; tap < 8u; ++tap) { const float4 read = giClipSmoothTap(cell, f, cells, tap); - blocked += read.w * gGiClipOpacity[0].SampleLevel(read.xyz, 0.0).xyz; + blocked += read.w * gGiClipOpacity[NonUniformResourceIndex(level)].SampleLevel(read.xyz, 0.0).xyz; } const float3 weight = direction * direction; const float opacity = dot(weight, blocked); @@ -247,7 +249,8 @@ float4 giClipSampleSmooth(GiClipFrame frame, float3 world, float3 direction) { return float4(0.0, 0.0, 0.0, 0.0); } - const uint3 face = uint3(direction.x > 0.0 ? 1u : 0u, direction.y > 0.0 ? 3u : 2u, direction.z > 0.0 ? 5u : 4u); + const uint3 face = + level * kGiClipFaces + uint3(direction.x > 0.0 ? 1u : 0u, direction.y > 0.0 ? 3u : 2u, direction.z > 0.0 ? 5u : 4u); float3 radiance = float3(0.0, 0.0, 0.0); for (uint tap = 0u; tap < 8u; ++tap) { @@ -299,13 +302,14 @@ float4 giClipCone(GiClipFrame frame, float3 origin, float3 dir const uint fine = uint(floor(wanted)); const uint coarse = min(fine + 1u, uint(last)); const float blend = wanted - float(fine); - if (Smooth > 0 && fine == 0u && coarse != fine) + // Levels 0 and 1 since the mid distance blocks show at level 1 and coarser ones are far enough to blur + if (Smooth > 0 && fine <= kGiClipSmoothLevels && coarse != fine) { - // Level 1 reaches past the 27 cells so where it holds nothing they are empty and one read settles it + // The coarser level reaches past the 27 cells so where it holds nothing they are empty and one read settles it sample = float4(0.0, 0.0, 0.0, 0.0); if (giClipSolidShare(frame, coarse, point) > 0.0) { - sample = giClipSampleSmooth(frame, point, direction); + sample = giClipSampleSmooth(frame, fine, point, direction); if (blend > 0.0) { sample = lerp(sample, giClipSample(frame, coarse, 0.0, point, direction), blend); @@ -339,7 +343,8 @@ float giClipCellAt(GiClipFrame frame, float3 worldPosition) } /// xyz irradiance over pi and w the share of the hemisphere the cones left open -float4 giClipGather(GiClipFrame frame, float3 worldPosition, float3 normal, float turn, float base) +/// @p jitter in 0 to 1 starts the cones that share of a cell further out so a history averages away where steps land +float4 giClipGather(GiClipFrame frame, float3 worldPosition, float3 normal, float turn, float base, float jitter) { // Coarser levels thicken every surface so the cones start further off it there const float cell = frame.levels[0].w * exp2(base); @@ -350,20 +355,21 @@ float4 giClipGather(GiClipFrame frame, float3 worldPosition, float3 normal, floa const float3 tangent = float3(1.0 + side * normal.x * normal.x * a, side * b, -side * normal.x); const float3 bitangent = float3(b, side + normal.y * normal.y * a, -normal.y); - float4 cone = giClipCone<1>(frame, origin, normal, 0.0, base); + const float start = jitter * cell; + float4 cone = giClipCone<1>(frame, origin, normal, start, base); float4 gathered = 0.25 * float4(cone.rgb, 1.0 - cone.a); for (uint i = 0u; i < 5u; ++i) { const float angle = (float(i) + turn) * 1.25663706; const float3 direction = normal * 0.5 + (tangent * cos(angle) + bitangent * sin(angle)) * 0.8660254; - cone = giClipCone<1>(frame, origin, direction, 0.0, base); + cone = giClipCone<1>(frame, origin, direction, start, base); gathered += 0.15 * float4(cone.rgb, 1.0 - cone.a); } return gathered; } /// @p turn spins the side cones up to a fifth of a turn and lit pixels pass 0 since per frame noise flickers -bool sampleGiClipmap(float3 worldPosition, float3 normal, float turn, out float3 irradiance, out float sky) +bool sampleGiClipmap(float3 worldPosition, float3 normal, float turn, out float3 irradiance, out float sky, float jitter = 0.0) { irradiance = float3(0.0, 0.0, 0.0); sky = 0.0; @@ -379,12 +385,12 @@ bool sampleGiClipmap(float3 worldPosition, float3 normal, float turn, out float3 } const float last = float(frame.size.y - 1u); const float base = floor(min(soft, last)); - float4 gathered = giClipGather(frame, worldPosition, normal, turn, base); + float4 gathered = giClipGather(frame, worldPosition, normal, turn, base, jitter); // Near a level edge two gathers cross fade since sliding one start between levels draws strips const float fade = min(soft, last) - base; if (fade > 0.0) { - gathered = lerp(gathered, giClipGather(frame, worldPosition, normal, turn, base + 1.0), fade); + gathered = lerp(gathered, giClipGather(frame, worldPosition, normal, turn, base + 1.0, jitter), fade); } irradiance = gathered.rgb; sky = gathered.a; @@ -491,6 +497,13 @@ bool giHitIrradiance(float3 worldPosition, float3 normal, out float3 irradiance) return sampleRadianceCascades(worldPosition, normal, irradiance); } +/// Bounce intensity for lit surfaces only since gi_clip_bounce feeds sampleGiClipmap back into itself +float giIntensity() +{ + const GiClipFrame clip = gGiClipFrame[0]; + return clip.size.z != 0u ? clip.camera.w : gGiFrame[0].limits.w; +} + bool giClipCovers(float3 worldPosition) { const GiClipFrame frame = gGiClipFrame[0]; diff --git a/engine/assets/shaders/glass_reflection.slang b/engine/assets/shaders/glass_reflection.slang new file mode 100644 index 000000000..b1fde5b3c --- /dev/null +++ b/engine/assets/shaders/glass_reflection.slang @@ -0,0 +1,79 @@ +// Glass reflections against the opaque backdrop shared by voxel glass and glass debris +// The SSR and traced specular post passes read the opaque surface behind glass so glass reflects in its own shading +import lighting; +import depth_convention; + +/// View depth of an NDC depth whatever the projection handedness +float glassViewDepth(float ndcDepth) +{ + const float a = gCamera.projection[2][2]; + const float b = gCamera.projection[2][3]; + const float c = gCamera.projection[3][2]; + return c * b / (ndcDepth * c - a); +} + +/// Backdrop colour where @p position shows on screen and false when something else covers it +bool glassBackdropRadiance(Sampler2D backdrop, Sampler2D backdropDepth, float3 position, out float3 radiance) +{ + radiance = float3(0.0, 0.0, 0.0); + const float4 clip = mul(gCamera.jitteredViewProjection, float4(position, 1.0)); + if (clip.w <= 0.0 || any(abs(clip.xy / clip.w) >= 1.0)) + { + return false; + } + const float2 uv = clip.xy / clip.w * 0.5 + 0.5; + const float depth = backdropDepth.SampleLevel(uv, 0.0).r; + if (isFarDepth(depth) || abs(glassViewDepth(depth) - clip.w) > 0.05 + 0.02 * clip.w) + { + return false; + } + radiance = backdrop.SampleLevel(uv, 0.0).rgb; + return true; +} + +/// Linear march against the backdrop depth +// shortcut: no HiZ or edge fade, upgrade if glass reflections shimmer or cut off at screen edges +bool glassScreenReflection(Sampler2D backdrop, Sampler2D backdropDepth, float3 position, float3 direction, float reach, uint steps, + float thickness, out float3 radiance) +{ + radiance = float3(0.0, 0.0, 0.0); + if (steps == 0u) + { + return false; + } + const float stride = reach / float(steps); + for (uint step = 1u; step <= steps; ++step) + { + const float4 clip = mul(gCamera.jitteredViewProjection, float4(position + direction * (stride * float(step)), 1.0)); + if (clip.w <= 0.0 || any(abs(clip.xy / clip.w) >= 1.0)) + { + return false; + } + const float2 uv = clip.xy / clip.w * 0.5 + 0.5; + const float depth = backdropDepth.SampleLevel(uv, 0.0).r; + if (isFarDepth(depth)) + { + continue; + } + const float behind = clip.w - glassViewDepth(depth); + if (behind > 0.0) + { + if (behind > thickness + stride) + { + return false; + } + radiance = backdrop.SampleLevel(uv, 0.0).rgb; + return true; + } + } + return false; +} + +/// Specular a reflection carries weighted as lighting weights the F0 0.04 environment it replaces +float3 glassReflectionSpecular(float3 litSpecular, float3 ambientSpecular, float3 reflection, float3 normal, float3 view, float roughness) +{ + const float NdotV = saturate(dot(normal, view)); + const float2 split = environmentBRDF(roughness, NdotV); + const float3 weight = fresnelSchlickRoughness(NdotV, float3(0.04, 0.04, 0.04), roughness) * split.x + split.y; + return litSpecular + reflection * weight - ambientSpecular; +} diff --git a/engine/assets/shaders/glass_reflection.slang.meta b/engine/assets/shaders/glass_reflection.slang.meta new file mode 100644 index 000000000..d83290026 --- /dev/null +++ b/engine/assets/shaders/glass_reflection.slang.meta @@ -0,0 +1,4 @@ +uid = "G1assR3flct" +type = "shader" +created_at = "2026-11-17T00:00:00.0000000Z" +modified_at = "2026-11-17T00:00:00.0000000Z" diff --git a/engine/assets/shaders/hiz_reduce.slang b/engine/assets/shaders/hiz_reduce.slang index 988086a75..e4cb140c4 100644 --- a/engine/assets/shaders/hiz_reduce.slang +++ b/engine/assets/shaders/hiz_reduce.slang @@ -1,4 +1,4 @@ -// Every level of renderer::HiZPyramid in one dispatch where each texel keeps the farthest depth of the 2x2 texels under it +// Every level of renderer::HiZPyramid in one dispatch where each texel keeps the farthest or closest depth of the 2x2 texels under it // Groups reduce 32x32 tiles of level 0 to level 5 in shared memory and the last group to finish reduces the rest import depth_convention; @@ -13,6 +13,8 @@ struct ReducePush uint2 sourceSize; uint levelCount; uint groupCount; + /// 1 keeps the closest depth for ray marching and 0 the farthest for occlusion culling + uint closest; }; [[vk::push_constant]] @@ -40,12 +42,22 @@ uint2 levelSize(uint level) return (gReduce.sourceSize + ((1u << shift) - 1u)) >> shift; } -/// Missing texels are the near depth which no farther test ever keeps +/// Depth the reduction never keeps so missing texels drop out +float missingDepth() +{ + return gReduce.closest != 0u ? kFarDepth : kNearDepth; +} + +float reduceDepth(float a, float b) +{ + return gReduce.closest != 0u ? closerDepth(a, b) : fartherDepth(a, b); +} + float sourceDepth(uint2 pixel) { if (pixel.x >= gReduce.sourceSize.x || pixel.y >= gReduce.sourceSize.y) { - return kNearDepth; + return missingDepth(); } return gDepth.Load(int3(int2(pixel), 0)).x; } @@ -55,7 +67,7 @@ float levelDepth(uint level, uint2 texel) const uint2 size = levelSize(level); if (texel.x >= size.x || texel.y >= size.y) { - return kNearDepth; + return missingDepth(); } return gLevels[level][texel]; } @@ -80,8 +92,8 @@ void computeMain(uint3 group : SV_GroupID, uint index : SV_GroupIndex) const uint2 local = thread * 2u + uint2(corner & 1u, corner >> 1); const uint2 texel = group.xy * kTile + local; const uint2 pixel = texel * 2u; - float depth = fartherDepth(sourceDepth(pixel), sourceDepth(pixel + uint2(1u, 0u))); - depth = fartherDepth(depth, fartherDepth(sourceDepth(pixel + uint2(0u, 1u)), sourceDepth(pixel + uint2(1u, 1u)))); + float depth = reduceDepth(sourceDepth(pixel), sourceDepth(pixel + uint2(1u, 0u))); + depth = reduceDepth(depth, reduceDepth(sourceDepth(pixel + uint2(0u, 1u)), sourceDepth(pixel + uint2(1u, 1u)))); sDepth[local.y][local.x] = depth; storeLevel(0u, texel, depth); } @@ -92,12 +104,12 @@ void computeMain(uint3 group : SV_GroupID, uint index : SV_GroupIndex) const uint width = kTile >> level; const bool active = index < width * width; const uint2 local = uint2(index % width, index / width); - float depth = kNearDepth; + float depth = missingDepth(); if (active) { const uint2 child = local * 2u; - depth = fartherDepth(fartherDepth(sDepth[child.y][child.x], sDepth[child.y][child.x + 1u]), - fartherDepth(sDepth[child.y + 1u][child.x], sDepth[child.y + 1u][child.x + 1u])); + depth = reduceDepth(reduceDepth(sDepth[child.y][child.x], sDepth[child.y][child.x + 1u]), + reduceDepth(sDepth[child.y + 1u][child.x], sDepth[child.y + 1u][child.x + 1u])); } GroupMemoryBarrierWithGroupSync(); if (active) @@ -135,8 +147,8 @@ void computeMain(uint3 group : SV_GroupID, uint index : SV_GroupIndex) { const uint2 texel = uint2(i % size.x, i / size.x); const uint2 child = texel * 2u; - const float depth = fartherDepth(fartherDepth(levelDepth(level - 1u, child), levelDepth(level - 1u, child + uint2(1u, 0u))), - fartherDepth(levelDepth(level - 1u, child + uint2(0u, 1u)), + const float depth = reduceDepth(reduceDepth(levelDepth(level - 1u, child), levelDepth(level - 1u, child + uint2(1u, 0u))), + reduceDepth(levelDepth(level - 1u, child + uint2(0u, 1u)), levelDepth(level - 1u, child + uint2(1u, 1u)))); gLevels[level][texel] = depth; } diff --git a/engine/assets/shaders/lens_flare.slang b/engine/assets/shaders/lens_flare.slang index 038556475..2f4eba721 100644 --- a/engine/assets/shaders/lens_flare.slang +++ b/engine/assets/shaders/lens_flare.slang @@ -15,7 +15,7 @@ struct LensFlareParams float4 tint; // x anamorphic intensity y anamorphic tint amount z dirt intensity w 1 with a dirt texture float4 streak; - // x halo thickness y halo dispersion + // x halo thickness y halo dispersion z scale on the light behind glass float4 haloStyle; // rgb halo tint float4 haloTint; @@ -39,6 +39,21 @@ Sampler2D gStreak; [[vk::binding(4, 0)]] Sampler2D gDirtTexture; +/// Scene before anything blended and where glass covers it, only the threshold step reads them +[[vk::binding(5, 0)]] +Sampler2D gGlassBackdrop; + +[[vk::binding(6, 0)]] +Sampler2D gGlassMask; + +/// Where glass covers a pixel the brighter of the glass composite and the scaled light behind it so emissives the glass dims still flare +float3 flareSource(float2 uv) +{ + const float3 source = gSource.Sample(uv).rgb; + const float m = gGlassMask.Sample(uv).r; + return lerp(source, max(source, gGlassBackdrop.Sample(uv).rgb * gParams.haloStyle.z), m); +} + typedef FullscreenVSOutput VSOutput; [shader("vertex")] @@ -76,17 +91,17 @@ float4 fragmentThreshold(VSOutput input) : SV_Target0 const float2 uv = input.uv; float3 corners = float3(0.0, 0.0, 0.0); - corners += gSource.Sample(uv + float2(-1.0, 1.0) * texel).rgb; - corners += gSource.Sample(uv + float2(1.0, 1.0) * texel).rgb; - corners += gSource.Sample(uv + float2(-1.0, -1.0) * texel).rgb; - corners += gSource.Sample(uv + float2(1.0, -1.0) * texel).rgb; + corners += flareSource(uv + float2(-1.0, 1.0) * texel); + corners += flareSource(uv + float2(1.0, 1.0) * texel); + corners += flareSource(uv + float2(-1.0, -1.0) * texel); + corners += flareSource(uv + float2(1.0, -1.0) * texel); float3 grid = float3(0.0, 0.0, 0.0); for (int y = -1; y <= 1; ++y) { for (int x = -1; x <= 1; ++x) { - grid += gSource.Sample(uv + float2(float(x), float(y)) * 2.0 * texel).rgb; + grid += flareSource(uv + float2(float(x), float(y)) * 2.0 * texel); } } diff --git a/engine/assets/shaders/lighting.slang b/engine/assets/shaders/lighting.slang index 0ce04eff3..fcb3d127b 100644 --- a/engine/assets/shaders/lighting.slang +++ b/engine/assets/shaders/lighting.slang @@ -1519,7 +1519,7 @@ float4 evaluateDebugView(Surface surface, ClusterCell cluster) (gCamera.environmentParams.x >= 0.5 ? gIrradianceMap.SampleLevel(N, 0.0).rgb : float3(0.0, 0.0, 0.0)); if (giSurfaceIrradiance(cascadeIrradiance, cascadeSky)) { - return float4(cascadeIrradiance + cascadeSky * ambientIrradiance, 1.0); + return float4(cascadeIrradiance * giIntensity() + cascadeSky * ambientIrradiance, 1.0); } return float4(ambientIrradiance, 1.0); } @@ -1934,7 +1934,7 @@ ShadingResult evaluateLighting(Surface surface, ClusterC if (hasCascades) { // The clipmap leaves the open share of the hemisphere to the ambient above and the cascades leave none - irradiance = cascadeIrradiance + cascadeSky * irradiance; + irradiance = cascadeIrradiance * giIntensity() + cascadeSky * irradiance; result.contactReach = giContactReach(surface.worldPosition); } diff --git a/engine/assets/shaders/ssao.slang b/engine/assets/shaders/ssao.slang index 8292b2c0f..b517a7ed6 100644 --- a/engine/assets/shaders/ssao.slang +++ b/engine/assets/shaders/ssao.slang @@ -5,7 +5,7 @@ struct SsaoParams { float4x4 viewProjection; float4x4 inverseViewProjection; - // xy target size z frame index for the noise + // xy target size z frame index for the noise w 1 when gDenoisedIndirect holds this frame's voxel GI float4 screenSize; // x sample radius y strength z depth cutoff w sample count float4 tuning; @@ -32,8 +32,18 @@ Sampler2D gIndirectDiffuse; [[vk::binding(4, 0)]] Sampler2D gOcclusion; +/// Denoised voxel GI with alpha 1 where the voxel denoise composite wrote it +[[vk::binding(5, 0)]] +Sampler2D gDenoisedIndirect; + static const float kNoSurfaceDistance = 60000.0; +/// Share of the radius the closest samples sit at +static const float kNearestSample = 0.1; + +/// Cosine an occluder has to rise above the tangent plane so depth steps on flat or sloped ground do not occlude +static const float kAngleBias = 0.15; + typedef FullscreenVSOutput VSOutput; [shader("vertex")] @@ -56,7 +66,8 @@ float rotationNoise(float2 pixel) return frac(52.9829189 * frac(dot(shifted, float2(0.06711056, 0.00583715)))); } -float3 hemisphereSample(uint index, uint count, float rotation) +/// Cosine weighted direction scaled so samples crowd near the surface where contact shadows are +float3 hemisphereSample(uint index, uint count, float rotation, float shift) { float golden = 2.39996323; float angle = float(index) * golden + rotation; @@ -66,7 +77,9 @@ float3 hemisphereSample(uint index, uint count, float rotation) sincos(angle, s, c); float2 disk = float2(c, s) * radius; float height = sqrt(max(1.0 - dot(disk, disk), 0.0)); - return float3(disk, height); + // A unit direction alone puts every sample a full radius out and misses creases closer than that + const float along = frac((float(index) + shift) / float(count) * 7.0 + shift); + return float3(disk, height) * lerp(kNearestSample, 1.0, along * along); } [shader("fragment")] @@ -97,14 +110,15 @@ float4 aoMain(VSOutput input) : SV_Target0 float3 T = normalize(cross(helper, N)); float3 B = cross(N, T); - float rotation = rotationNoise(input.position.xy) * 6.2831853; + const float noise = rotationNoise(input.position.xy); + float rotation = noise * 6.2831853; float occlusion = 0.0; float validSamples = 0.0; for (uint i = 0; i < sampleCount; ++i) { - float3 hemisphere = hemisphereSample(i, sampleCount, rotation); + float3 hemisphere = hemisphereSample(i, sampleCount, rotation, noise); float3 offset = (T * hemisphere.x + B * hemisphere.y + N * hemisphere.z) * radius; float3 samplePosition = worldPosition + offset; @@ -134,12 +148,14 @@ float4 aoMain(VSOutput input) : SV_Target0 float3 toSample = scenePosition - worldPosition; float distanceToScene = length(toSample); - float rangeWeight = saturate(1.0 - distanceToScene / max(rangeCutoff, 1e-4)); + // Smooth so an occluder near the cutoff fades instead of popping and close ones weigh most + const float range = distanceToScene / max(rangeCutoff, 1e-4); + float rangeWeight = saturate(1.0 - range * range); if (distanceToScene > 1e-5) { float3 direction = toSample / distanceToScene; - float facing = saturate(dot(N, direction)); + float facing = saturate((dot(N, direction) - kAngleBias) / (1.0 - kAngleBias)); occlusion += facing * rangeWeight; } @@ -230,5 +246,11 @@ float4 compositeMain(VSOutput input) : SV_Target0 float3 sceneColor = gSceneColor.Sample(input.uv).rgb; // Clamped since blended surfaces scaled the opaque term by 1 - alpha float3 indirect = gIndirectDiffuse.Sample(input.uv).rgb; + // The colour holds the denoised voxel GI so the share taken back must be that one and not this frame's noisy one + if (gParams.screenSize.w > 0.5) + { + const float4 denoised = gDenoisedIndirect.Sample(input.uv); + indirect = denoised.a > 0.5 ? denoised.rgb : indirect; + } return float4(max(sceneColor - indirect + indirect * ao, float3(0.0, 0.0, 0.0)), 1.0); } diff --git a/engine/assets/shaders/ssr.slang b/engine/assets/shaders/ssr.slang index 2eaa741d9..ede211462 100644 --- a/engine/assets/shaders/ssr.slang +++ b/engine/assets/shaders/ssr.slang @@ -1,4 +1,4 @@ -// Stochastic SSR traced resolved and accumulated at half resolution then composited +// Stochastic SSR traced through a closest depth pyramid, resolved and accumulated at half resolution then composited import fullscreen; import depth_convention; import scene_normal; @@ -9,10 +9,12 @@ struct SsrParams float4x4 viewProjection; float4x4 inverseViewProjection; float4 cameraPosition; - // x intensity y max roughness z thickness w step count + // x intensity y max roughness z thickness w most pyramid steps a ray takes float4 tuning; // x reach in meters y render mode z 1 with a valid history w 1 when gPreviousColor holds last frame resolve float4 marching; + // x levels of gHiz + float4 pyramid; }; [[vk::push_constant]] @@ -48,6 +50,10 @@ Sampler2D gTemporal; [[vk::binding(8, 0)]] Sampler2D gPreviousColor; +/// renderer::HiZPyramid of gDepth keeping the closest depth, level k texel t covers pixels t << (k + 1) on +[[vk::binding(9, 0)]] +Sampler2D gHiz; + /// Below this a surface is a mirror and gets one ray with no reuse static const float kMirrorRoughness = 0.05; @@ -145,10 +151,28 @@ float planeWeight(SurfaceSample surface, float3 position) return exp(-abs(dot(surface.normal, position - surface.position)) / (0.005 * surface.linearDepth + 0.01)); } -bool marchScreen(float3 origin, float3 direction, float2 jitter, out float2 hitUv, out float travelled) +/// Full resolution check of the ray against gDepth at @p t, @p behind true when the ray went behind a surface too thick to hit +bool pixelHit(float2 p0, float2 d, float z0, float dz, float t, float2 size, out bool behind) +{ + behind = false; + const float2 uv = (p0 + d * t) / size; + const float depth = gDepth.SampleLevel(uv, 0.0).r; + if (isFarDepth(depth) || isCloserDepth(z0 + dz * t, depth)) + { + return false; + } + const float sceneDepth = linearDepth(uv, depth); + const float gap = linearDepth(uv, z0 + dz * t) - sceneDepth; + behind = gap > gParams.tuning.z * (1.0 + 0.025 * sceneDepth); + return !behind; +} + +/// Hi-Z march in screen space clipped to the screen and the reach so a ray goes as far as the screen shows +/// @p fade drops reach limited rays near their end so they fade out instead of cutting off +bool marchScreen(float3 origin, float3 direction, float jitter, out float2 hitUv, out float fade) { hitUv = float2(0.0, 0.0); - travelled = 0.0; + fade = 1.0; uint width; uint height; @@ -167,55 +191,74 @@ bool marchScreen(float3 origin, float3 direction, float2 jitter, out float2 hitU end = mul(gParams.viewProjection, float4(origin + direction * reach, 1.0)); } - const float k0 = 1.0 / start.w; - const float k1 = 1.0 / end.w; - const float2 uv0 = start.xy * k0 * 0.5 + 0.5; - const float2 uv1 = end.xy * k1 * 0.5 + 0.5; - - // At most one sample per pixel the ray crosses - const float pixels = max(abs(uv1.x - uv0.x) * size.x, abs(uv1.y - uv0.y) * size.y); - const uint steps = clamp(uint(pixels), 1u, uint(gParams.tuning.w)); - const float invSteps = 1.0 / float(steps); + const float2 p0 = (start.xy / start.w * 0.5 + 0.5) * size; + const float2 p1 = (end.xy / end.w * 0.5 + 0.5) * size; + const float z0 = start.z / start.w; + const float dz = end.z / end.w - z0; + const float2 d = p1 - p0; + const float pixels = length(d); + if (pixels < 1.0) + { + return false; + } - float previousT = 0.0; - float previousRayDepth = start.w; - for (uint i = 0u; i < steps; ++i) + // Clipped to the screen edge so the reach is only a cap + float tEnd = 1.0; + [unroll] + for (int axis = 0; axis < 2; ++axis) { - // Squared to crowd samples near the surface - const float x = (float(i) + jitter.x) * invSteps; - const float t = x * x; - const float2 uv = lerp(uv0, uv1, t); - if (!insideScreen(uv)) + if (abs(d[axis]) > 1e-6) { - return false; + tEnd = min(tEnd, ((d[axis] > 0.0 ? size[axis] - 0.5 : 0.5) - p0[axis]) / d[axis]); } + } + if (tEnd <= 0.0) + { + return false; + } + const bool reachLimited = tEnd >= 1.0; + + const float2 inverseD = float2(abs(d.x) > 1e-6 ? 1.0 / d.x : 1e30, abs(d.y) > 1e-6 ? 1.0 / d.y : 1e30); + const float2 forward = step(float2(0.0, 0.0), d); + const float tPixel = 1.0 / pixels; + const int topLevel = max(int(gParams.pyramid.x) - 1, 0); + const uint maxSteps = max(uint(gParams.tuning.w), 1u); - const float depth = gDepth.SampleLevel(uv, 0.0).r; - if (!isFarDepth(depth)) + float t = tPixel * (1.0 + jitter); + int level = 0; + for (uint i = 0u; i < maxSteps && t < tEnd; ++i) + { + const float2 p = p0 + d * t; + const float cellSize = float(2u << uint(level)); + const float2 cell = floor(p / cellSize); + const float cellDepth = gHiz.Load(int3(int2(cell), level)).r; + const float2 exits = ((cell + forward) * cellSize - p0) * inverseD; + // A hair past the boundary so the next cell is the one the ray enters + const float tCell = min(min(exits.x, exits.y) + 0.01 * tPixel, tEnd); + + if (!isCloserDepth(z0 + dz * t, cellDepth)) { - const float sceneInvW = max(dot(gParams.inverseViewProjection[3], float4(uv * 2.0 - 1.0, depth, 1.0)), 1e-8); - const float rayInvW = lerp(k0, k1, t); - // Behind the surface when the ray 1/w is below the scene 1/w - if (rayInvW < sceneInvW) + if (level > 0) + { + --level; + continue; + } + // The 2x2 cell holds something at least as close as the ray so test its pixels at full resolution + float previous = t - tPixel; + for (float x = t; x < tCell; x += tPixel) { - const float sceneDepth = 1.0 / sceneInvW; - const float rayDepth = 1.0 / max(rayInvW, 1e-8); - const float behind = rayDepth - sceneDepth; - // Never thinner than one step - const float thickness = max(gParams.tuning.z * (1.0 + 0.025 * sceneDepth), 1.5 * abs(rayDepth - previousRayDepth)); - if (behind > 0.0 && behind < thickness) + bool behind; + if (pixelHit(p0, d, z0, dz, x, size, behind)) { - float lo = previousT; - float hi = t; + float lo = max(previous, 0.0); + float hi = x; [unroll] - for (uint j = 0u; j < 5u; ++j) + for (uint j = 0u; j < 4u; ++j) { const float mid = 0.5 * (lo + hi); - const float2 midUv = lerp(uv0, uv1, mid); + const float2 midUv = (p0 + d * mid) / size; const float midDepth = gDepth.SampleLevel(midUv, 0.0).r; - const float midSceneInvW = max(dot(gParams.inverseViewProjection[3], float4(midUv * 2.0 - 1.0, midDepth, 1.0)), 1e-8); - const float midRayInvW = lerp(k0, k1, mid); - if (!isFarDepth(midDepth) && midRayInvW < midSceneInvW) + if (!isFarDepth(midDepth) && !isCloserDepth(z0 + dz * mid, midDepth)) { hi = mid; } @@ -224,14 +267,28 @@ bool marchScreen(float3 origin, float3 direction, float2 jitter, out float2 hitU lo = mid; } } - hitUv = lerp(uv0, uv1, hi); - travelled = hi; + hitUv = (p0 + d * hi) / size; + fade = reachLimited ? 1.0 - smoothstep(0.7, 1.0, hi) : 1.0; return true; } + previous = x; } + t = tCell; + continue; + } + + if (isCloserDepth(z0 + dz * tCell, cellDepth)) + { + // Wholly in front of everything in the cell + t = tCell; + level = min(level + 1, topLevel); + } + else + { + // Reaches the closest depth inside the cell so refine from there + t = max(t + 0.01 * tPixel, (cellDepth - z0) / dz); + level = max(level - 1, 0); } - previousT = t; - previousRayDepth = 1.0 / max(lerp(k0, k1, t), 1e-8); } return false; } @@ -277,8 +334,8 @@ float4 traceMain(VSOutput input) : SV_Target0 const float3 origin = surface.position + N * max(0.002 * surface.linearDepth, 0.01); float2 hitUv; - float travelled; - if (!marchScreen(origin, L, float2(noiseAt(input.position.xy), 0.0), hitUv, travelled)) + float fade; + if (!marchScreen(origin, L, noiseAt(input.position.xy), hitUv, fade)) { return float4(0.0, 0.0, pdf, 0.0); } @@ -286,7 +343,7 @@ float4 traceMain(VSOutput input) : SV_Target0 // A back face of what it hit means the ray went behind it const float4 hitEncoded = gNormalRoughness.SampleLevel(hitUv, 0.0); const float facing = dot(hitEncoded.xyz, hitEncoded.xyz) > 1e-4 ? -dot(normalize(hitEncoded.xyz), L) : 1.0; - const float confidence = screenEdgeFade(hitUv) * (1.0 - smoothstep(0.7, 1.0, travelled)) * step(0.0, facing); + const float confidence = screenEdgeFade(hitUv) * fade * step(0.0, facing); return float4(hitUv, pdf, confidence); } diff --git a/engine/assets/shaders/voxel_denoise.slang b/engine/assets/shaders/voxel_denoise.slang index 50f224b75..b74286158 100644 --- a/engine/assets/shaders/voxel_denoise.slang +++ b/engine/assets/shaders/voxel_denoise.slang @@ -50,6 +50,23 @@ Sampler2D gDiffuseCurrent; [[vk::binding(9, 0)]] Sampler2D gSpecularCurrent; +/// This frame's noisy clipmap GI voxel_lighting.slang left for SSAO which tells its share of the noisy diffuse +[[vk::binding(10, 0)]] +Sampler2D gSceneIndirect; + +struct CompositeOutput +{ + /// Additive into the scene colour + float4 color : SV_Target0; + /// The GI share of the denoised diffuse with alpha 1 so SSAO occludes it instead of the noisy one + float4 indirect : SV_Target1; +}; + +float luminance(float3 value) +{ + return dot(value, float3(0.2126, 0.7152, 0.0722)); +} + /// Blend floors so a settled pixel still follows changes static const float kDiffuseBlend = 0.1; static const float kSpecularBlend = 0.2; @@ -273,9 +290,8 @@ float noiseAt(float2 pixel) return frac(52.9829189 * frac(dot(pixel, float2(0.06711056, 0.00583715)))); } -/// Additive into the scene colour [shader("fragment")] -float4 compositeMain(VSOutput input) : SV_Target0 +CompositeOutput compositeMain(VSOutput input) { const int2 pixel = int2(input.position.xy); const float4 albedo = gAlbedo.Load(int3(pixel, 0)); @@ -300,6 +316,9 @@ float4 compositeMain(VSOutput input) : SV_Target0 float3 diffuse = gDiffuseCurrent.Load(int3(pixel, 0)).rgb; float weightSum = 1.0; + // GI and everything noisy over the same taps since a ratio of single noisy pixels flickers + float giSum = luminance(gSceneIndirect.Load(int3(pixel, 0)).rgb); + float noisySum = luminance(albedo.rgb * gNoisyDiffuse.Load(int3(pixel, 0)).rgb); float s, c; sincos(rotation, s, c); const float2 turn = float2(c, s) * radius; @@ -323,9 +342,18 @@ float4 compositeMain(VSOutput input) : SV_Target0 const float weight = valid ? exp(-plane / planeTolerance) * facing32 : 0.0; diffuse += tapDiffuse * weight; weightSum += weight; + if (weight > 0.0) + { + giSum += weight * luminance(gSceneIndirect.Load(int3(tap, 0)).rgb); + noisySum += weight * luminance(gAlbedo.Load(int3(tap, 0)).rgb * gNoisyDiffuse.Load(int3(tap, 0)).rgb); + } } diffuse /= weightSum; const float3 specular = gSpecularCurrent.Load(int3(pixel, 0)).rgb; - return float4(albedo.rgb * diffuse + specular, 0.0); + const float giShare = noisySum > 1e-6 ? saturate(giSum / noisySum) : 0.0; + CompositeOutput output; + output.color = float4(albedo.rgb * diffuse + specular, 0.0); + output.indirect = float4(albedo.rgb * diffuse * giShare, 1.0); + return output; } diff --git a/engine/assets/shaders/voxel_glass.slang b/engine/assets/shaders/voxel_glass.slang index 87d9cd98a..7374c3e7d 100644 --- a/engine/assets/shaders/voxel_glass.slang +++ b/engine/assets/shaders/voxel_glass.slang @@ -2,7 +2,12 @@ import voxel_dda; import lighting; import gi_sample; +import gi_common; +import scene_trace; +import trace_shading; import scene_normal; +import glass_reflection; +import fullscreen; import depth_convention; /// Instance index then brick grid index sorted far to near @@ -14,18 +19,56 @@ struct GlassPush { /// Run start in gGlassBricks since SV_InstanceID leaves out firstInstance uint first; - /// 0 when the backdrop was not captured this frame - float refraction; - /// Meters past which glass does not refract - float refractionDistance; - /// Voxels the glass run walk follows - uint refractionVoxels; /// Lit glass surfaces per brick and pixel past which layers only absorb uint litSurfaces; /// 1 when gBackdropDepth holds this frame opaque depth and the pipeline keeps only glass in front of it uint depthTest; + /// Meters a reflection ray travels + float reflectionReach; + /// Rougher surfaces keep the environment + float reflectionRoughness; + /// Screen march steps + uint reflectionSteps; + /// Meters behind the opaque depth a screen march still hits + float reflectionThickness; + /// Meters a traced hit sun ray travels before it counts as lit + float sunReach; + /// 1 draws only bricks holding the camera with back faces and 0 only the rest with front faces + uint inside; + /// 1 walks the run near to far so depth writing passes reject what is behind early + uint reverse; + /// Bricks in the run so reverse can index it + uint count; + /// 1 when gNearestGlassDepth holds this frame nearest glass surface + uint nearestValid; + /// 1 adds a cost heat colour instead of the glass, see blendGlass + uint costView; }; +/// Bit of the gGlassBricks instance word set for a brick the camera is inside +static const uint kGlassInsideBit = 0x80000000u; + +static const uint kReflectionNone = 0u; +/// One voxel ray since the traced specular post pass reads the opaque surface behind the glass +static const uint kReflectionTraced = 1u; +/// Screen march against the opaque backdrop since the ssr post pass reads the opaque surface behind the glass +static const uint kReflectionScreen = 2u; + +/// Mirrors renderer::VoxelPass glass variants: what replaces the environment specular of the first surface per brick +/// Specialized per pipeline so the driver drops the reflection paths a variant never takes and the shader keeps fewer registers +[[vk::constant_id(0)]] +const uint kSpecReflection = 0u; +/// 0 drops the debug views from the variants that draw a normal frame +[[vk::constant_id(1)]] +const uint kSpecDebugViews = 1u; + +/// Lit surfaces one brick fragment records, the most glass_lit_surfaces allows +static const uint kMaxLitSurfaces = 4u; +/// Below this share of its light reaching the camera a surface is left unlit +static const float kContributionCutoff = 0.02; +/// Below this share of reflected light reaching the camera a surface keeps the environment instead of tracing +static const float kReflectionCutoff = 0.01; + [[vk::push_constant]] GlassPush gGlassPush; @@ -36,14 +79,40 @@ Sampler2D gBackdrop; [[vk::binding(9, 1)]] Sampler2D gBackdropDepth; -/// Ratio blending reads a near black backdrop as a difference instead -static const float kRatioFloor = 0.02; -static const float kMaxRatio = 16.0; +/// Nearest glass surface depth over the opaque depth from the glass pre-pass +[[vk::binding(16, 1)]] +Sampler2D gNearestGlassDepth; + +/// Scene normal and motion of that surface so the surface copy skips the brick walk +[[vk::binding(17, 1)]] +Sampler2D gNearestGlassNormal; + +[[vk::binding(18, 1)]] +Sampler2D gNearestGlassMotion; + +/// r glass covers the pixel g share of light the nearest glass surface lets through +[[vk::binding(19, 1)]] +Sampler2D gGlassMask; + +/// Below this the front pane is a mirror and glass behind it is skipped +static const float kMirrorTransmittance = 0.02; + +/// The DDA hit is never closer than the front face so outside bricks keep early depth testing +#if TOAST_REVERSED_Z +#define GLASS_FARTHER_DEPTH SV_DepthLessEqual +#else +#define GLASS_FARTHER_DEPTH SV_DepthGreaterEqual +#endif + /// Below this nothing behind shows static const float kOpaqueTransmittance = 0.004; +static const float kVoxelSize = 0.1; +/// Voxels off the glass face a traced reflection starts +static const float kReflectionOffset = 0.6; + struct VSOutput { @@ -82,7 +151,16 @@ struct VSOutput [shader("vertex")] VSOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID) { - const uint2 entry = gGlassBricks[gGlassPush.first + instanceId]; + const uint run = gGlassPush.reverse != 0u ? gGlassPush.count - 1u - instanceId : instanceId; + const uint2 packed = gGlassBricks[gGlassPush.first + run]; + const uint2 entry = uint2(packed.x & ~kGlassInsideBit, packed.y); + if (((packed.x & kGlassInsideBit) != 0u) != (gGlassPush.inside != 0u)) + { + // Zero area so the other pipeline of this run draws it + VSOutput culled = (VSOutput)0; + culled.position = float4(0.0, 0.0, 0.0, 1.0); + return culled; + } const VoxelInstance instance = gVoxelInstances[entry.x]; const VolumeRecord record = gVolumeRecords[instance.recordIndex]; const uint3 brick = uint3(entry.y % record.brickDimsX, (entry.y / record.brickDimsX) % record.brickDimsY, @@ -127,13 +205,73 @@ struct GlassComposite float f0; float3 voxelPosition; - /// Backdrop uv the refracted ray lands on - bool refracted; - float2 refractedUv; + /// Share of light the entered surface lets through past its reflection and scatter + float frontTransmittance; + + /// Surfaces lit and whether one traced or marched a reflection, for the cost view + uint shaded; + bool reflected; }; -float3 shadeInterface(float3 hitWorld, float3 normal, float3 view, float2 pixel, PaletteSample palette, out float fresnel, - out bool debugView) +/// Radiance a voxel ray hits shaded as voxel_specular hitRadiance shades it +bool tracedReflection(float3 position, float3 normal, float3 direction, float2 pixel, out float3 radiance) +{ + radiance = float3(0.0, 0.0, 0.0); + const float3 origin = position + normal * (kReflectionOffset * kVoxelSize); + // A pixel wide cone so a far hit marches coarser levels than the mirror ray would + float2 size; + gBackdrop.GetDimensions(size.x, size.y); + const float pixelSlope = 2.0 / max(abs(gCamera.projection[1][1]) * size.y, 1.0); + const SceneHit hit = traceScene(origin, direction, 0.0, gGlassPush.reflectionReach, pixelSlope); + if (!hit.hit) + { + return false; + } + const float3 hitPosition = origin + direction * hit.t; + const float3 hitNormal = sceneHitNormal(hit, direction); + if (gGlassPush.depthTest != 0u && dot(hitNormal, gCamera.position - hitPosition) > 0.0 && + glassBackdropRadiance(gBackdrop, gBackdropDepth, hitPosition, radiance)) + { + return true; + } + const PaletteSample hitPalette = samplePalette(gTraceVolumes[hit.volume].recordIndex, hit.material); + float3 irradiance; + if (!giHitIrradiance(hitPosition, hitNormal, irradiance)) + { + irradiance = gCamera.ambientColorIntensity.rgb * gCamera.ambientColorIntensity.a; + if (gCamera.environmentParams.x >= 0.5) + { + irradiance += gIrradianceMap.SampleLevel(hitNormal, 0.0).rgb; + } + } + // shortcut: no local lights on an off screen hit, which voxel_specular samples with a loop over every light and a shadow ray, + // since GI already carries their bounce, upgrade if lamp lit walls look too dark in glass + radiance = hitPalette.albedo * (hitPalette.emissive + irradiance) + + traceSunLight(hitPosition, hitNormal, hitPalette.albedo, pixelSlope, gGlassPush.sunReach, pixel); + return true; +} + +/// SSR or traced radiance along the mirror direction and false keeps the environment +bool glassReflection(float3 position, float3 normal, float3 view, float roughness, float2 pixel, out float3 radiance) +{ + radiance = float3(0.0, 0.0, 0.0); + if (kSpecReflection == kReflectionNone || roughness > gGlassPush.reflectionRoughness) + { + return false; + } + // shortcut: mirror ray only so glass below the roughness cutoff reflects too sharp, upgrade to a GGX lobe sample with TAA + const float3 direction = reflect(-view, normal); + if (kSpecReflection == kReflectionTraced) + { + return tracedReflection(position, normal, direction, pixel, radiance); + } + return gGlassPush.depthTest != 0u && glassScreenReflection(gBackdrop, gBackdropDepth, position, direction, gGlassPush.reflectionReach, + gGlassPush.reflectionSteps, gGlassPush.reflectionThickness, radiance); +} + +/// @p reflects swaps the environment specular for glassReflection where it hits +float3 shadeInterface(float3 hitWorld, float3 normal, float3 view, float2 pixel, PaletteSample palette, bool reflects, + out float fresnel, out bool debugView) { Surface surface; surface.marchedShadows = false; @@ -157,167 +295,34 @@ float3 shadeInterface(float3 hitWorld, float3 normal, float3 view, float2 pixel, // Glass scatters a sliver of its diffuse light and a pixel can cross several panes gGiGathered = giCheap(hitWorld, normal); // One pass split into lobes since each pass resamples every shadow map - const ShadingResult lit = shadeSurfaceLighting(surface); + // Every layer gets every light or glass seen through glass looks unlit + ShadingResult lit; + if (kSpecDebugViews != 0u) + { + lit = shadeSurfaceLighting(surface); + } + else + { + NoShadowFilter none; + lit = evaluateLighting(surface, clusterCellAt(surface.viewSpaceZ, surface.pixel), none); + } debugView = lit.isDebugView; if (debugView) { return lit.color; } const float3 diffuse = max(lit.color - lit.specular, float3(0.0, 0.0, 0.0)); - // Lighting assumes F0 0.04 so rescale by the Fresnel ratio - const float3 specular = lit.specular * fresnel / (0.04 + 0.96 * facing); - return diffuse * glassScatter(palette.alpha, palette.roughness) + palette.albedo * palette.emissive * palette.alpha + specular; -} - - -/// First glass run of the camera ray across the whole volume -struct GlassRun -{ - float entryT; - float exitT; - int3 entryVoxel; - float3 entryNormal; - float3 exitNormal; - float ior; -}; - -float3 voxelFaceNormal(float4x4 worldToVoxel, int axis, float sign) -{ - float3 voxelNormal = float3(0.0, 0.0, 0.0); - voxelNormal[axis] = sign; - return normalize(mul(transpose((float3x3)worldToVoxel), voxelNormal)); -} - -/// False when an opaque voxel comes first or the camera starts inside glass -bool firstGlassRun(uint volume, VolumeRecord record, float4x4 worldToVoxel, float3 origin, float3 direction, float tMin, - out GlassRun run) -{ - run.entryT = 0.0; - run.exitT = 0.0; - run.entryVoxel = int3(0, 0, 0); - run.entryNormal = float3(0.0, 0.0, 0.0); - run.exitNormal = float3(0.0, 0.0, 0.0); - run.ior = kDefaultIor; - - const int3 dims = int3(record.brickDimsX, record.brickDimsY, record.brickDimsZ) * int(kBrickDim); - const RayHit hit = marchRayBox(volume, origin, direction, tMin, kFloatMax, int3(0, 0, 0), dims, false); - if (!hit.hit || hit.axis < 0 || !glassEntry(record, hit.material)) + float3 litSpecular = lit.specular; + float3 reflection; + if (reflects && glassReflection(hitWorld, normal, view, surface.roughness, pixel, reflection)) { - return false; - } - run.entryT = hit.t; - run.entryVoxel = hit.voxel; - run.entryNormal = voxelFaceNormal(worldToVoxel, hit.axis, direction[hit.axis] > 0.0 ? -1.0 : 1.0); - run.ior = samplePalette(record, hit.material).ior; - - int3 voxel = hit.voxel; - int3 stepSign; - float3 next; - float3 delta; - for (int a = 0; a < 3; ++a) - { - stepSign[a] = direction[a] > 0.0 ? 1 : (direction[a] < 0.0 ? -1 : 0); - delta[a] = stepSign[a] == 0 ? kFloatMax : abs(1.0 / direction[a]); - next[a] = stepSign[a] == 0 ? kFloatMax : (float(voxel[a] + (stepSign[a] > 0 ? 1 : 0)) - origin[a]) / direction[a]; - } - - // Parallel faces when the run is longer than the walk - run.exitT = hit.t; - run.exitNormal = -run.entryNormal; - int3 cachedBrick = int3(-1, -1, -1); - uint cachedEntry = 0u; - uint cachedMaterial = hit.material; - bool cachedGlass = true; - for (uint step = 0u; step < gGlassPush.refractionVoxels; ++step) - { - const int axis = next.x < next.y ? (next.x < next.z ? 0 : 2) : (next.y < next.z ? 1 : 2); - run.exitT = next[axis]; - voxel[axis] += stepSign[axis]; - next[axis] += delta[axis]; - bool glass = false; - if (all(voxel >= int3(0, 0, 0)) && all(voxel < dims)) - { - const int3 brick = voxel >> 3; - if (any(brick != cachedBrick)) - { - cachedBrick = brick; - cachedEntry = gridEntry(record, uint3(brick)); - } - const uint material = brickMaterialAt(cachedEntry, voxel); - if (material != cachedMaterial) - { - cachedMaterial = material; - cachedGlass = material != 0u && glassEntry(record, material); - } - glass = cachedGlass; - } - if (!glass) - { - run.exitNormal = voxelFaceNormal(worldToVoxel, axis, float(stepSign[axis])); - break; - } + litSpecular = glassReflectionSpecular(lit.specular, lit.ambientSpecular, reflection, normal, view, surface.roughness); } - return true; -} - -/// Camera distance of a backdrop texel -float backdropDistance(float2 uv, float depth) -{ - const float4 viewPosition = mul(gClusterParams.inverseProjection, float4(uv * 2.0 - 1.0, depth, 1.0)); - return length(viewPosition.xyz / viewPosition.w); + // Lighting assumes F0 0.04 so rescale by the Fresnel ratio + const float3 specular = litSpecular * fresnel / (0.04 + 0.96 * facing); + return diffuse * glassScatter(palette.alpha, palette.roughness) + palette.albedo * palette.emissive * palette.alpha + specular; } -/// Snell at entry and exit faces with a straight path inside -/// The bent ray goes as far past the glass as the straight one -float2 refractedBackdropUv(float3 camera, float3 worldDirection, float entryT, float exitT, float3 entryNormal, float3 exitNormal, - float ior, float2 pixel, out bool valid) -{ - valid = false; - float2 size; - gBackdrop.GetDimensions(size.x, size.y); - const float2 straightUv = pixel / size; - - const float rayLength = length(worldDirection); - const float3 direction = worldDirection / rayLength; - const float3 entryPoint = camera + worldDirection * entryT; - - const float3 inside = refract(direction, entryNormal, 1.0 / ior); - if (dot(inside, inside) < 1e-6) - { - return straightUv; - } - const float across = (exitT - entryT) * rayLength * max(dot(direction, -entryNormal), 1e-3); - const float3 exitPoint = entryPoint + inside * (across / max(dot(inside, -entryNormal), 1e-3)); - float3 bent = refract(inside, -exitNormal, ior); - // Total internal reflection keeps the inside direction - if (dot(bent, bent) < 1e-6) - { - bent = inside; - } - - const float straightDepth = gBackdropDepth.Load(int3(int2(pixel), 0)).r; - const float exitDistance = distance(camera, exitPoint); - const float remaining = isFarDepth(straightDepth) ? 1000.0 : max(backdropDistance(straightUv, straightDepth) - exitDistance, 0.0); - const float4 clip = mul(gCamera.jitteredViewProjection, float4(exitPoint + bent * remaining, 1.0)); - if (clip.w <= 1e-4) - { - return straightUv; - } - const float2 uv = lerp(straightUv, clip.xy / clip.w * 0.5 + 0.5, gGlassPush.refraction); - if (any(uv < float2(0.0, 0.0)) || any(uv > float2(1.0, 1.0))) - { - return straightUv; - } - - // Something in front of the glass never shows through it - const float bentDepth = gBackdropDepth.SampleLevel(uv, 0.0).r; - if (!isFarDepth(bentDepth) && backdropDistance(uv, bentDepth) < distance(camera, entryPoint)) - { - return straightUv; - } - valid = true; - return uv; -} /// Every glass layer front to back or with @p surfaceOnly the nearest entered surface unlit /// Surfaces reflect by Fresnel and scatter by glassScatter and the path filters by glassPathFilter @@ -333,16 +338,17 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) result.roughness = 1.0; result.f0 = 0.0; result.voxelPosition = float3(0.0, 0.0, 0.0); - result.refracted = false; - result.refractedUv = float2(0.0, 0.0); - if (isVoxelDebugMode(gCamera.renderModePad.x)) + result.frontTransmittance = 1.0; + result.shaded = 0u; + result.reflected = false; + if (kSpecDebugViews != 0u && isVoxelDebugMode(gCamera.renderModePad.x)) { return false; } const uint volume = input.volume; const VolumeRecord record = gVolumeRecords[volume]; - // Only surface normals and refraction read it + // Only surface normals read it const float4x4 worldToVoxel = gVoxelInstances[input.instanceIndex].worldToVoxel; const float3 camera = gCamera.position; @@ -415,13 +421,75 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) float firstT = t; uint litInterfaces = 0u; + // Surfaces the walk entered within the lit budget, shaded after it so the walk loop stays small + // Written by constant index so they stay in registers + float slotT[kMaxLitSurfaces]; + int slotAxis[kMaxLitSurfaces]; + uint slotMaterial[kMaxLitSurfaces]; + float3 slotWeight[kMaxLitSurfaces]; + float slotFresnel[kMaxLitSurfaces]; + [unroll] + for (uint k = 0u; k < kMaxLitSurfaces; ++k) + { + slotT[k] = 0.0; + slotAxis[k] = 0; + slotMaterial[k] = 0u; + slotWeight[k] = float3(0.0, 0.0, 0.0); + slotFresnel[k] = 0.0; + } + // A run of glass is nearly always one palette entry uint cachedMaterial = 0xFFFFFFFFu; bool cachedGlass = false; PaletteSample palette = {}; + const bool pooled = (input.brickEntry & 3u) >= kTagShared; for (uint step = 0u; step < 3u * kBrickDim; ++step) { + // Empty 4x4x4 sub-cells of a pooled brick are crossed in one step, which leaves a thin pane only a few steps + if (pooled) + { + const uint3 local = uint3(voxel & 7); + const uint subBase = ((input.brickEntry >> 2) << 4) + (((local.x >> 2) | ((local.y >> 2) << 1) | ((local.z >> 2) << 2)) << 1); + if ((gBrickOccupancy[subBase] | gBrickOccupancy[subBase + 1u]) == 0u) + { + const int3 low = voxel & int3(~3, ~3, ~3); + float tLeave = kFloatMax; + int leaveAxis = 0; + for (int a = 0; a < 3; ++a) + { + if (stepSign[a] != 0) + { + const float bound = float(low[a] + (stepSign[a] > 0 ? 4 : 0)); + const float ta = (bound - origin[a]) * inverse[a]; + if (ta < tLeave) + { + tLeave = ta; + leaveAxis = a; + } + } + } + if (tLeave >= tExit) + { + break; + } + inside = false; + t = tLeave; + axis = leaveAxis; + voxel = clamp(int3(floor(origin + direction * t)), low, low + 3); + voxel[leaveAxis] = stepSign[leaveAxis] > 0 ? low[leaveAxis] + 4 : low[leaveAxis] - 1; + if (any(voxel < boxMin) || any(voxel >= boxMax)) + { + break; + } + for (int a = 0; a < 3; ++a) + { + next[a] = stepSign[a] == 0 ? kFloatMax : (float(voxel[a] + (stepSign[a] > 0 ? 1 : 0)) - origin[a]) * inverse[a]; + } + continue; + } + } + // The march stays in its brick so one grid entry covers it const uint material = brickMaterialAt(input.brickEntry, voxel); const int nextAxis = next.x < next.y ? (next.x < next.z ? 0 : 2) : (next.y < next.z ? 1 : 2); @@ -461,6 +529,20 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) return false; } } + // Behind a front pane that reflects nearly everything nothing of this brick shows, so its lit layers would only add light + if (!surfaceOnly && gGlassPush.nearestValid != 0u) + { + const int3 texel = int3(int2(input.position.xy), 0); + const float2 mask = gGlassMask.Load(texel).rg; + if (mask.r > 0.5 && mask.g < kMirrorTransmittance) + { + const float entryW = mul(gCamera.viewProjection, float4(camera + worldDirection * t, 1.0)).w; + if (glassViewDepth(gNearestGlassDepth.Load(texel).r) < entryW - (0.01 + 0.002 * entryW)) + { + return false; + } + } + } } if (!inside && axis >= 0) @@ -468,10 +550,14 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) float3 voxelNormal = float3(0.0, 0.0, 0.0); voxelNormal[axis] = direction[axis] > 0.0 ? -1.0 : 1.0; const float3 normal = normalize(mul(transpose((float3x3)worldToVoxel), voxelNormal)); + // Every surface reflects whether or not it is lit, or past the lit budget glass would turn clear and show the lit layers behind + const float f0 = iorF0(palette.ior); + float fresnel = f0 + (1.0 - f0) * pow(1.0 - saturate(dot(normal, view)), 5.0); if (!result.entered) { result.entered = true; + result.frontTransmittance = (1.0 - fresnel) * (1.0 - glassScatter(palette.alpha, palette.roughness)); result.normal = normal; result.roughness = clamp(palette.roughness, 0.045, 1.0); result.f0 = iorF0(palette.ior); @@ -483,21 +569,21 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) } } - float fresnel = 0.0; - if (litInterfaces < gGlassPush.litSurfaces) + // Within the budget since every lit layer adds light and stacked glass would wash out + if (litInterfaces < min(gGlassPush.litSurfaces, kMaxLitSurfaces)) { - bool debugView = false; - const float3 light = shadeInterface(camera + worldDirection * t, normal, view, input.position.xy, palette, fresnel, - debugView); - if (debugView) + [unroll] + for (uint k = 0u; k < kMaxLitSurfaces; ++k) { - result.color = light; - result.transmittance = float3(0.0, 0.0, 0.0); - result.debugView = true; - firstT = t; - break; + if (k == litInterfaces) + { + slotT[k] = t; + slotAxis[k] = axis; + slotMaterial[k] = material; + slotWeight[k] = result.transmittance; + slotFresnel[k] = fresnel; + } } - result.color += result.transmittance * light; ++litInterfaces; } @@ -542,14 +628,51 @@ bool compositeGlass(VSOutput input, bool surfaceOnly, out GlassComposite result) const float4 clip = mul(gCamera.viewProjection, float4(camera + worldDirection * firstT, 1.0)); result.depth = clip.z / clip.w; - // Only the brick holding the entry voxel refracts - GlassRun run; - if (!surfaceOnly && !result.debugView && result.entered && gGlassPush.refraction > 0.0 && - firstT * length(worldDirection) <= gGlassPush.refractionDistance && - firstGlassRun(volume, record, worldToVoxel, origin, direction, tMin, run) && all((run.entryVoxel >> 3) == input.brick)) + // Layers behind the first in a brick that face the same way with the same palette entry lie under a brick apart so they share one lighting + bool lightCached = false; + int lightAxis = -1; + uint lightMaterial = 0u; + float3 cachedLight = float3(0.0, 0.0, 0.0); + // A real loop so the lighting is inlined once + [loop] + for (uint k = 0u; k < kMaxLitSurfaces; ++k) { - result.refractedUv = refractedBackdropUv(camera, worldDirection, run.entryT, run.exitT, run.entryNormal, run.exitNormal, run.ior, - input.position.xy, result.refracted); + // Weights only fall so nothing past a dim surface shows either + if (k >= litInterfaces || max(slotWeight[k].x, max(slotWeight[k].y, slotWeight[k].z)) < kContributionCutoff) + { + break; + } + if (lightCached && slotAxis[k] == lightAxis && slotMaterial[k] == lightMaterial) + { + result.color += slotWeight[k] * cachedLight; + continue; + } + + float3 voxelNormal = float3(0.0, 0.0, 0.0); + voxelNormal[slotAxis[k]] = direction[slotAxis[k]] > 0.0 ? -1.0 : 1.0; + const float3 normal = normalize(mul(transpose((float3x3)worldToVoxel), voxelNormal)); + // The first surface of each brick reflects so glass seen through glass shows the scene and not the bare sky, unless what + // it reflects is too dim to show past the glass in front + const bool reflects = k == 0u && max(slotWeight[k].x, max(slotWeight[k].y, slotWeight[k].z)) * slotFresnel[k] >= kReflectionCutoff; + float fresnel; + bool debugView = false; + const float3 light = shadeInterface(camera + worldDirection * slotT[k], normal, view, input.position.xy, + samplePalette(record, slotMaterial[k]), reflects, fresnel, debugView); + if (debugView) + { + result.color = light; + result.transmittance = float3(0.0, 0.0, 0.0); + result.debugView = true; + return true; + } + result.color += slotWeight[k] * light; + ++result.shaded; + result.reflected = result.reflected || (reflects && kSpecReflection != kReflectionNone); + // Never a reflecting surface whose reflection belongs to it alone + lightCached = !reflects; + lightAxis = slotAxis[k]; + lightMaterial = slotMaterial[k]; + cachedLight = light; } return true; } @@ -566,54 +689,104 @@ struct DualSourceOutput float4 transmittance : SV_Target1; }; -[shader("fragment")] -DualSourceOutput fragmentMain(VSOutput input, out float depth : SV_Depth) +bool blendGlass(VSOutput input, out DualSourceOutput output, out float depth) { + output = (DualSourceOutput)0; GlassComposite glass; if (!compositeGlass(input, false, glass)) { - discard; + depth = input.position.z; + return false; } depth = glass.depth; + output.color = float4(glass.color, 1.0); + output.transmittance = float4(glass.transmittance, 1.0); + if (gGlassPush.costView != 0u) + { + // Added on top of what is behind: green per brick fragment, red per lit surface, blue per reflection + output.color = float4(0.15 * float(glass.shaded), 0.04, glass.reflected ? 0.3 : 0.0, 1.0); + output.transmittance = float4(1.0, 1.0, 1.0, 1.0); + } + return true; +} - // The blend sees only the straight backdrop so the bent one scales or offsets it - float3 offset = float3(0.0, 0.0, 0.0); - float3 scale = glass.transmittance; - if (glass.refracted) +[shader("fragment")] +DualSourceOutput fragmentMain(VSOutput input, out float depth : SV_Depth) +{ + DualSourceOutput output; + if (!blendGlass(input, output, depth)) { - const float3 straight = gBackdrop.Load(int3(int2(input.position.xy), 0)).rgb; - const float3 bent = gBackdrop.SampleLevel(glass.refractedUv, 0.0).rgb; - [unroll] - for (int c = 0; c < 3; ++c) - { - if (straight[c] > kRatioFloor) - { - scale[c] *= min(bent[c] / straight[c], kMaxRatio); - } - else - { - offset[c] = scale[c] * (bent[c] - straight[c]); - } - } + discard; } + return output; +} +[shader("fragment")] +DualSourceOutput fragmentMainOutside(VSOutput input, out float depth : GLASS_FARTHER_DEPTH) +{ DualSourceOutput output; - output.color = float4(glass.color + offset, 1.0); - output.transmittance = float4(scale, 1.0); + if (!blendGlass(input, output, depth)) + { + discard; + } + // Slab entry can land a hair in front of the face + depth = fartherDepth(depth, input.position.z); + return output; +} + +/// Far outside bricks at a coarse shading rate, which drivers only honour without a depth export +/// The rasterized front face is closer than the glass and compositeGlass rejects glass behind the opaque depth itself +[shader("fragment")] +DualSourceOutput fragmentMainFar(VSOutput input) +{ + DualSourceOutput output; + float depth; + if (!blendGlass(input, output, depth)) + { + discard; + } return output; } /// Without dualSrcBlend the tint is lost and the background only fades +float4 premultipliedGlass(DualSourceOutput blend) +{ + return float4(blend.color.rgb, 1.0 - dot(blend.transmittance.rgb, float3(1.0, 1.0, 1.0)) / 3.0); +} + [shader("fragment")] float4 fragmentPremultiplied(VSOutput input, out float depth : SV_Depth) : SV_Target0 { - GlassComposite glass; - if (!compositeGlass(input, false, glass)) + DualSourceOutput output; + if (!blendGlass(input, output, depth)) { discard; } - depth = glass.depth; - return float4(glass.color, 1.0 - dot(glass.transmittance, float3(1.0, 1.0, 1.0)) / 3.0); + return premultipliedGlass(output); +} + +[shader("fragment")] +float4 fragmentPremultipliedFar(VSOutput input) : SV_Target0 +{ + DualSourceOutput output; + float depth; + if (!blendGlass(input, output, depth)) + { + discard; + } + return premultipliedGlass(output); +} + +[shader("fragment")] +float4 fragmentPremultipliedOutside(VSOutput input, out float depth : GLASS_FARTHER_DEPTH) : SV_Target0 +{ + DualSourceOutput output; + if (!blendGlass(input, output, depth)) + { + discard; + } + depth = fartherDepth(depth, input.position.z); + return premultipliedGlass(output); } // Mirrors the world stage attachment order with the scene colour masked off @@ -627,19 +800,20 @@ struct SurfaceOutput float4 motion : SV_Target3; }; -/// After every blended draw -[shader("fragment")] -SurfaceOutput fragmentSurface(VSOutput input, out float depth : SV_Depth) +bool surfaceGlass(VSOutput input, out SurfaceOutput output, out float depth, out float frontTransmittance) { + output = (SurfaceOutput)0; + frontTransmittance = 1.0; GlassComposite glass; if (!compositeGlass(input, true, glass)) { - discard; + depth = input.position.z; + return false; } depth = glass.depth; + frontTransmittance = glass.frontTransmittance; const VoxelInstance instance = gVoxelInstances[input.instanceIndex]; - SurfaceOutput output; output.color = float4(0.0, 0.0, 0.0, 0.0); output.normalRoughness = encodeSceneNormal(glass.normal, glass.roughness, glass.f0); output.indirectDiffuse = float4(0.0, 0.0, 0.0, 1.0); @@ -650,17 +824,98 @@ SurfaceOutput fragmentSurface(VSOutput input, out float depth : SV_Depth) const float4 previousClip = mul(gCamera.previousViewProjection, mul(instance.previousVoxelToWorld, float4(glass.voxelPosition, 1.0))); output.motion = float4((clip.xy / clip.w - previousClip.xy / previousClip.w) * 0.5, 0.0, 1.0); } + return true; +} + +/// After every blended draw +[shader("fragment")] +SurfaceOutput fragmentSurface(VSOutput input, out float depth : SV_Depth) +{ + SurfaceOutput output; + float frontTransmittance; + if (!surfaceGlass(input, output, depth, frontTransmittance)) + { + discard; + } return output; } [shader("fragment")] -float4 fragmentMask(VSOutput input, out float depth : SV_Depth) : SV_Target0 +SurfaceOutput fragmentSurfaceOutside(VSOutput input, out float depth : GLASS_FARTHER_DEPTH) { - GlassComposite glass; - if (!compositeGlass(input, true, glass)) + SurfaceOutput output; + float frontTransmittance; + if (!surfaceGlass(input, output, depth, frontTransmittance)) { discard; } - depth = glass.depth; - return float4(1.0, 1.0, 1.0, 1.0); + depth = fartherDepth(depth, input.position.z); + return output; +} + +/// Pre-pass of the nearest glass surface into its own depth, the bloom glass mask and the surface the copy writes later +struct NearestOutput +{ + float4 mask : SV_Target0; + float4 normalRoughness : SV_Target1; + float4 motion : SV_Target2; +}; + +NearestOutput nearestOutput(SurfaceOutput surface, float frontTransmittance) +{ + NearestOutput output; + output.mask = float4(1.0, frontTransmittance, 0.0, 1.0); + output.normalRoughness = surface.normalRoughness; + output.motion = surface.motion; + return output; +} + +[shader("fragment")] +NearestOutput fragmentNearest(VSOutput input, out float depth : SV_Depth) +{ + SurfaceOutput surface; + float frontTransmittance; + if (!surfaceGlass(input, surface, depth, frontTransmittance)) + { + discard; + } + return nearestOutput(surface, frontTransmittance); +} + +[shader("fragment")] +NearestOutput fragmentNearestOutside(VSOutput input, out float depth : GLASS_FARTHER_DEPTH) +{ + SurfaceOutput surface; + float frontTransmittance; + if (!surfaceGlass(input, surface, depth, frontTransmittance)) + { + discard; + } + depth = fartherDepth(depth, input.position.z); + return nearestOutput(surface, frontTransmittance); +} + +[shader("vertex")] +FullscreenVSOutput vertexFullscreen(uint vertexId : SV_VertexID) +{ + return fullscreenTriangle(vertexId); +} + +/// After every blended draw, writes what the pre-pass found where it found glass in front of the opaque depth +[shader("fragment")] +SurfaceOutput fragmentSurfaceCopy(FullscreenVSOutput input, out float depth : SV_Depth) +{ + const int3 texel = int3(int2(input.position.xy), 0); + // The mask is cleared everywhere each frame while the nearest depth is only copied where glass is + if (gGlassMask.Load(texel).r < 0.5) + { + discard; + } + depth = gNearestGlassDepth.Load(texel).r; + SurfaceOutput output; + output.color = float4(0.0, 0.0, 0.0, 0.0); + output.normalRoughness = gNearestGlassNormal.Load(texel); + output.indirectDiffuse = float4(0.0, 0.0, 0.0, 1.0); + output.motion = gNearestGlassMotion.Load(texel); + return output; } diff --git a/engine/assets/shaders/voxel_lighting.slang b/engine/assets/shaders/voxel_lighting.slang index bfb86a32c..d6c181e4d 100644 --- a/engine/assets/shaders/voxel_lighting.slang +++ b/engine/assets/shaders/voxel_lighting.slang @@ -418,6 +418,8 @@ static const uint kTracedSpecular = 16u; static const uint kGiGather = 32u; /// Mirrors VoxelPass k_gi_clipmap static const uint kGiClipmap = 64u; +/// Mirrors VoxelPass k_gi_denoise and set when voxel_denoise.slang filters the clipmap GI +static const uint kGiDenoise = 128u; static const float kGiGatherPlane = 0.15; /// Scene normal roughness of a pixel whose environment specular voxel_specular.slang replaces and SSR skips @@ -818,7 +820,10 @@ float4 fragmentGiGather(VSOutput input) : SV_Target0 } float3 irradiance; float sky; - if (!sampleGiClipmap(positionAt(pixel), normal, 0.0, irradiance, sky)) + // Side cones turn and start further out per pixel and frame and the denoiser history averages both + const float turn = (gPush.reuse.x & kGiDenoise) != 0u ? interleavedGradientNoise(float2(pixel)) : 0.0; + const float jitter = (gPush.reuse.x & kGiDenoise) != 0u ? interleavedGradientNoise(float2(pixel) + 17.0) : 0.0; + if (!sampleGiClipmap(positionAt(pixel), normal, turn, irradiance, sky, jitter)) { return none; } @@ -940,12 +945,14 @@ FSOutput fragmentMain(VSOutput input) output.color.rgb -= lit.ambientSpecular; } - // Traced AO replaces SSAO so ambient diffuse moves into the filtered term - if (gPush.lighting.z != 0u && gPush.reuse.w != 0u) + // Ambient diffuse moves into the filtered term when traced AO occludes it or clipmap GI needs the history + const bool tracedAo = gPush.lighting.z != 0u && gPush.reuse.w != 0u; + if (tracedAo || (gPush.reuse.x & kGiDenoise) != 0u) { output.color.rgb -= lit.indirectDiffuse; output.noisyDiffuse = float4(select(albedo.rgb > 1e-3, lit.indirectDiffuse / max(albedo.rgb, 1e-3), float3(0.0, 0.0, 0.0)), 0.0); - output.indirectDiffuse = float4(0.0, 0.0, 0.0, 1.0); + // Traced AO replaces SSAO and otherwise SSAO takes back its share of the filtered GI the denoiser adds to the colour + output.indirectDiffuse = float4(tracedAo ? float3(0.0, 0.0, 0.0) : lit.indirectDiffuse, 1.0); } return output; } diff --git a/engine/src/toast/physics/debris.hpp b/engine/src/toast/physics/debris.hpp index 8ce31db86..b55ed42d4 100644 --- a/engine/src/toast/physics/debris.hpp +++ b/engine/src/toast/physics/debris.hpp @@ -52,6 +52,7 @@ struct DebrisSpawn { bool glass = false; uint8_t alpha = 255; uint8_t ior = 0; + float emissive = 0.0f; float scale = 1.0f; }; diff --git a/engine/src/toast/physics/debris_simulation.cpp b/engine/src/toast/physics/debris_simulation.cpp index dedde5686..da98e8f8f 100644 --- a/engine/src/toast/physics/debris_simulation.cpp +++ b/engine/src/toast/physics/debris_simulation.cpp @@ -55,6 +55,7 @@ DebrisSimulation::DebrisSimulation(uint32_t max_particles) m_volumes = addHostBuffer(sizeof(GpuVolume) * k_max_volumes); m_retires = addHostBuffer(sizeof(uint32_t) * k_max_spawns_per_step); m_grid = addPersistentBuffer(sizeof(uint32_t) * k_grid_cells * k_grid_stride); + m_shadow_bounds = addRingBuffer(sizeof(ShadowBounds), true); setAcquireUsage(m_draw_args, renderer::sync::Usage::indirect_read); bind(0, m_particles, Copy::previous); @@ -66,6 +67,7 @@ DebrisSimulation::DebrisSimulation(uint32_t max_particles) bind(6, m_volumes); bind(7, m_retires); bind(8, m_grid); + bind(9, m_shadow_bounds); const auto section = [this](renderer::VoxelGpuStorage::Section which) { return [this, which]() -> vk::Buffer { @@ -118,6 +120,7 @@ void DebrisSimulation::spawn(std::span spawns) { .lifetime = std::max(lifetime, k_debris_min_lifetime), .scale = std::clamp(spawn.scale, 0.05f, 1.0f), .glass = static_cast(spawn.alpha) | (static_cast(spawn.ior) << 8u), + .emissive = spawn.emissive, } ); } @@ -143,7 +146,6 @@ void DebrisSimulation::step(uint32_t steps, double fixed_delta, std::shared_ptr< Params params { .gravity = settings.gravity, .dt = static_cast(total / static_cast(substeps)), - .fade_in = k_fade_in_seconds, .restitution = settings.debris_restitution, .friction = settings.debris_friction, .voxel_size = voxel::k_voxel_size, diff --git a/engine/src/toast/physics/debris_simulation.hpp b/engine/src/toast/physics/debris_simulation.hpp index 644947437..416efe8e2 100644 --- a/engine/src/toast/physics/debris_simulation.hpp +++ b/engine/src/toast/physics/debris_simulation.hpp @@ -36,11 +36,12 @@ class TOAST_API DebrisSimulation : public renderer::AsyncComputeTask { glm::vec4 rotation {0.0f, 0.0f, 0.0f, 1.0f}; glm::vec3 velocity {0.0f}; uint32_t albedo_roughness = 0; - /// Base scale times the spawn and death fades + /// Base scale times the death fade float scale = 0.0f; /// Alpha and ior byte << 8 and only read with k_flag_glass in packed uint32_t glass = 0; - std::array pad {}; + float emissive = 0.0f; + uint32_t pad = 0; }; struct GpuMotion { @@ -63,7 +64,7 @@ class TOAST_API DebrisSimulation : public renderer::AsyncComputeTask { float lifetime = 0.0f; float scale = 1.0f; uint32_t glass = 0; - uint32_t pad = 0; + float emissive = 0.0f; }; struct GpuVolume { @@ -81,12 +82,23 @@ class TOAST_API DebrisSimulation : public renderer::AsyncComputeTask { static_assert(sizeof(GpuSpawn) == 80, "GpuSpawn is mirrored by debris.slang"); static_assert(sizeof(GpuVolume) == 128, "GpuVolume is mirrored by debris.slang"); + /// Mirrors gShadowBounds in debris.slang, the box is in ordered uints and empty while min is above max + struct ShadowBounds { + std::array min {}; + std::array max {}; + /// Opaque pieces whose shadow moved in this step + uint32_t changing = 0; + /// Float bits of the fastest opaque piece + uint32_t max_speed = 0; + }; + + static_assert(sizeof(ShadowBounds) == 32, "ShadowBounds is mirrored by debris.slang"); + static constexpr uint32_t k_max_spawns_per_step = 4096; static constexpr uint32_t k_max_volumes = 512; static constexpr uint32_t k_voxels_per_particle = 8; /// Mirrors debris.slang where bits 0 to 7 are the voxel mask static constexpr uint32_t k_flag_glass = 1u << 25; - static constexpr float k_fade_in_seconds = 0.12f; static constexpr float k_fade_out_seconds = 0.6f; /// Slots past the cap so pieces shrinking away still have room static constexpr uint32_t k_cap_headroom_divisor = 4; @@ -137,11 +149,15 @@ class TOAST_API DebrisSimulation : public renderer::AsyncComputeTask { return m_draw_args; } + [[nodiscard]] + auto shadowBoundsId() const -> BufferId { + return m_shadow_bounds; + } + private: struct Params { glm::vec3 gravity {0.0f}; float dt = 0.0f; - float fade_in = 0.0f; float restitution = 0.0f; float friction = 0.0f; float voxel_size = 0.0f; @@ -154,7 +170,7 @@ class TOAST_API DebrisSimulation : public renderer::AsyncComputeTask { float fade_out = 0.0f; float max_speed = 0.0f; float max_spin = 0.0f; - std::array pad {}; + std::array pad {}; }; static_assert(sizeof(Params) == 80, "Params is mirrored by debris.slang"); @@ -188,6 +204,7 @@ class TOAST_API DebrisSimulation : public renderer::AsyncComputeTask { BufferId m_volumes = 0; BufferId m_retires = 0; BufferId m_grid = 0; + BufferId m_shadow_bounds = 0; std::deque m_pending; bool m_clear_pending = false; diff --git a/engine/src/toast/physics/manifold.cpp b/engine/src/toast/physics/manifold.cpp index 6a65d498e..9cc18b85b 100644 --- a/engine/src/toast/physics/manifold.cpp +++ b/engine/src/toast/physics/manifold.cpp @@ -2356,7 +2356,13 @@ auto classifyBoxVoxelSplit(const BoxVoxelPairView& view) -> BoxVoxelSplitInfo { const glm::vec3 local_world_extents = glm::abs(local_box.rotation[0]) * local_box.half_extents.x + glm::abs(local_box.rotation[1]) * local_box.half_extents.y + glm::abs(local_box.rotation[2]) * local_box.half_extents.z; - const AABB local_bounds {.min = local_box.center - local_world_extents, .max = local_box.center + local_world_extents}; + // Only the overlap with the volume can hold contacts, so a big ground box under a small body neither splits nor slabs the empty + // rest + const glm::vec3 volume_extent = glm::vec3(view.voxel_data.volume->voxelDims()) * voxel::k_voxel_size; + const AABB local_bounds { + .min = glm::max(local_box.center - local_world_extents, glm::vec3(0.0f)), + .max = glm::min(local_box.center + local_world_extents, volume_extent), + }; return {.local_bounds = local_bounds, .estimated_voxels = querySurfaceAreaInVoxels(local_bounds)}; } diff --git a/engine/src/toast/physics/manifold.hpp b/engine/src/toast/physics/manifold.hpp index f2138a905..ffe565ff3 100644 --- a/engine/src/toast/physics/manifold.hpp +++ b/engine/src/toast/physics/manifold.hpp @@ -225,7 +225,7 @@ struct BoxVoxelPairView { auto resolveBoxVoxelPair(CollisionWorldView world, BroadPhasePair pair) -> std::optional; struct BoxVoxelSplitInfo { - /// The box AABB in voxel local space safe to partition spatially across jobs + /// The box AABB in voxel local space clipped to the volume, safe to partition spatially across jobs AABB local_bounds {}; /// Cheap surface area estimate, not an actual walk, since queryVoxelSurface only visits surface voxels uint64_t estimated_voxels = 0; diff --git a/engine/src/toast/physics/simulator.cpp b/engine/src/toast/physics/simulator.cpp index 557d841fa..398ae3087 100644 --- a/engine/src/toast/physics/simulator.cpp +++ b/engine/src/toast/physics/simulator.cpp @@ -1149,6 +1149,7 @@ void Simulator::emitDebris( .glass = voxel::isGlass(look), .alpha = look.alpha, .ior = look.ior, + .emissive = voxel::emissiveIntensity(data->palette, cluster.material), .scale = scale, } ); @@ -1840,6 +1841,9 @@ auto Simulator::spawnStaticSplitBody(ShapeID source_shape_id, const DetachedComp glm::quat local_rotation = shape->voxel.local_rotation; voxel::Palette palette = data->palette; voxel::MaterialLibrary materials = data->materials; + const uint64_t palette_uid = data->palette_uid; + // The renderer only draws a fragment whose origin a node owns, so pieces broken off this split need the source origin + const BodyID origin = valid(data->fragment_origin) ? data->fragment_origin : shape->owner; const DensityTable densities = voxel::densityTable(palette, materials); auto extracted_fragment = [&] { @@ -1898,6 +1902,12 @@ auto Simulator::spawnStaticSplitBody(ShapeID source_shape_id, const DetachedComp restore_to_source(*owned_volume); return true; } + if (const Shape* stored = tryGetShape(split_shape)) { + if (VoxelShapeData* split_data = tryGetVoxelData(stored->voxel.data)) { + split_data->fragment_origin = origin; + split_data->palette_uid = palette_uid; + } + } shape = tryGetShape(source_shape_id); if (shape != nullptr) { @@ -1934,7 +1944,8 @@ void Simulator::despawnSettledFragments(float dt) { } const Body* body = tryGetBody(slot.shape.owner); - if (body == nullptr || not body->enabled || body->awake) { + // Static splits carry an origin too but stay anchored in the world + if (body == nullptr || not body->enabled || body->awake || body->type != BodyType::dynamic_body) { data->fragment_sleep_seconds = 0.0f; continue; } @@ -3178,8 +3189,45 @@ auto Simulator::generateManifoldsAsync(CollisionWorldView world, std::span(NarrowPhasePairType::box_voxel)]; - m_profile.narrow_pair_time_ms[static_cast(NarrowPhasePairType::box_voxel)] += - std::chrono::duration(std::chrono::steady_clock::now() - split_start).count(); + const double split_ms = std::chrono::duration(std::chrono::steady_clock::now() - split_start).count(); + m_profile.narrow_pair_time_ms[static_cast(NarrowPhasePairType::box_voxel)] += split_ms; + if (split_ms > 2.0) { + // diagnostic, remove; body type 0 static 1 dynamic 2 kinematic + const Body& box_body = split.view.box.body; + const Body& voxel_body = split.view.voxel.body; + const glm::vec3 box_size = split.view.box.shape.box.size; + const glm::uvec3 voxel_dims = split.view.voxel_data.volume->brickDims(); + size_t candidates = 0; + for (const VoxelPairPartial& partial : partials) { + for (const auto& per_normal : partial.candidates_per_normal) { + candidates += per_normal.size(); + } + } + TOAST_WARN( + "Physics", + "[box-voxel slow] {:.2f} ms, {} regions, {} candidates, local extent {:.1f}x{:.1f}x{:.1f} m | box type {} awake {} " + "size {:.1f}x{:.1f}x{:.1f} | " + "voxel type {} awake {} bricks {}x{}x{} solid {} fragment {}", + split_ms, + partials.size(), + candidates, + split.local_bounds.max.x - split.local_bounds.min.x, + split.local_bounds.max.y - split.local_bounds.min.y, + split.local_bounds.max.z - split.local_bounds.min.z, + static_cast(box_body.type), + box_body.awake, + box_size.x, + box_size.y, + box_size.z, + static_cast(voxel_body.type), + voxel_body.awake, + voxel_dims.x, + voxel_dims.y, + voxel_dims.z, + split.view.voxel_data.solid_voxel_count, + valid(split.view.voxel_data.fragment_origin) + ); + } merged.insert_range(merged.end(), std::move(queue.manifolds)); } } diff --git a/engine/src/toast/renderer/compute/async_compute.cpp b/engine/src/toast/renderer/compute/async_compute.cpp index 73a6f431c..0869c4124 100644 --- a/engine/src/toast/renderer/compute/async_compute.cpp +++ b/engine/src/toast/renderer/compute/async_compute.cpp @@ -105,9 +105,10 @@ auto AsyncCompute::submit(const std::function& record, submitLocked(std::move(slot)); } - if (!debug_name.empty()) { - TOAST_TRACE("Render", "Async compute job '{}' submitted as ticket {}", debug_name, ticket); - } + // shutup + // if (!debug_name.empty()) { + // TOAST_TRACE("Render", "Async compute job '{}' submitted as ticket {}", debug_name, ticket); + // } return ticket; } diff --git a/engine/src/toast/renderer/compute/async_compute_task.cpp b/engine/src/toast/renderer/compute/async_compute_task.cpp index af120bab5..22e9309c6 100644 --- a/engine/src/toast/renderer/compute/async_compute_task.cpp +++ b/engine/src/toast/renderer/compute/async_compute_task.cpp @@ -68,6 +68,18 @@ auto AsyncComputeTask::FrameView::buffer(BufferId id) const -> vk::Buffer { return *m_task->m_buffers[id].copies[m_slot]; } +auto AsyncComputeTask::FrameView::read(BufferId id, std::span out) const -> bool { + if (m_task == nullptr || id >= m_task->m_buffers.size() || !m_task->m_buffers[id].cpu_readback) { + return false; + } + // The copy is in the same submit as the step so the pinned slot holds it finished + const vma::raii::Buffer& readback = m_task->m_buffers[id].readbacks[m_slot]; + const vk::DeviceSize bytes = std::min(out.size(), m_task->m_buffers[id].size); + readback.getAllocation().invalidate(0, bytes); + std::memcpy(out.data(), readback.getAllocation().getInfo().pMappedData, bytes); + return true; +} + AsyncComputeTask::AsyncComputeTask(Config config) : m_config(std::move(config)), m_core(&getCore()) { ZoneScoped; m_frame_slot.fill(-1); diff --git a/engine/src/toast/renderer/compute/async_compute_task.hpp b/engine/src/toast/renderer/compute/async_compute_task.hpp index b2d646a25..7d0ec6826 100644 --- a/engine/src/toast/renderer/compute/async_compute_task.hpp +++ b/engine/src/toast/renderer/compute/async_compute_task.hpp @@ -107,6 +107,9 @@ class TOAST_API AsyncComputeTask { return m_step; } + /// CPU copy of a cpu_readback ring buffer from this same step + [[nodiscard]] auto read(BufferId id, std::span out) const -> bool; + private: friend class AsyncComputeTask; const AsyncComputeTask* m_task = nullptr; diff --git a/engine/src/toast/renderer/core/vulkan_common.hpp b/engine/src/toast/renderer/core/vulkan_common.hpp index 6f4e0b3c7..38008ea03 100644 --- a/engine/src/toast/renderer/core/vulkan_common.hpp +++ b/engine/src/toast/renderer/core/vulkan_common.hpp @@ -43,6 +43,8 @@ inline constexpr vk::Format k_voxel_face_normal_format = vk::Format::eA2B10G10R1 /// Marched and sampled light terms before voxel_denoise.slang and never negative inline constexpr vk::Format k_voxel_noisy_format = vk::Format::eB10G11R11UfloatPack32; +/// Alpha marks the pixels the voxel denoise composite wrote +inline constexpr vk::Format k_voxel_denoised_indirect_format = vk::Format::eR16G16B16A16Sfloat; /// Half resolution clipmap gather with a signed alpha marking pixels that gathered nothing inline constexpr vk::Format k_voxel_gi_format = vk::Format::eR16G16B16A16Sfloat; diff --git a/engine/src/toast/renderer/core/vulkan_core.cpp b/engine/src/toast/renderer/core/vulkan_core.cpp index fc7355f80..86f54b43c 100644 --- a/engine/src/toast/renderer/core/vulkan_core.cpp +++ b/engine/src/toast/renderer/core/vulkan_core.cpp @@ -413,6 +413,10 @@ VulkanCore::VulkanCore( // Layer settings are fixed at instance creation but ray query use is only known once a device is picked if (m_validation_enabled && probeRayQuery(m_physical_device).used()) { m_physical_device = nullptr; +#ifndef NDEBUG + // before the instance since destroying it after leaves the new messenger dead + m_debug_messenger = nullptr; +#endif m_instance = nullptr; createInstance(required_instance_extensions, true); pickPhysicalDevice(required_device_extensions); @@ -929,6 +933,26 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re } } + { + const auto available = m_physical_device.enumerateDeviceExtensionProperties(); + const bool extension_present = std::ranges::any_of(available, [](const vk::ExtensionProperties& ext) { + return std::string_view(ext.extensionName.data()) == VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME; + }); + if (extension_present) { + vk::PhysicalDeviceFeatures2 probe {}; + vk::PhysicalDeviceFragmentShadingRateFeaturesKHR rate_probe {}; + probe.pNext = &rate_probe; + (*m_physical_device).getFeatures2(&probe); + m_fragment_shading_rate_supported = rate_probe.pipelineFragmentShadingRate == VK_TRUE; + } + if (m_fragment_shading_rate_supported) { + device_extensions.push_back(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME); + TOAST_INFO("Render", "VK_KHR_fragment_shading_rate available; far glass shades at 2x2"); + } else { + TOAST_INFO("Render", "Pipeline fragment shading rate unavailable; far glass shades every pixel"); + } + } + vk::DeviceCreateInfo device_ci({}, queue_create_infos, {}, device_extensions, &enabled_features); vk::PhysicalDeviceMeshShaderFeaturesEXT mesh_shader_features {}; @@ -941,6 +965,9 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re vk::PhysicalDeviceRayQueryFeaturesKHR ray_query_features {}; ray_query_features.rayQuery = VK_TRUE; + vk::PhysicalDeviceFragmentShadingRateFeaturesKHR shading_rate_features {}; + shading_rate_features.pipelineFragmentShadingRate = VK_TRUE; + vk::PhysicalDeviceFrameBoundaryFeaturesEXT frame_boundary_features {}; frame_boundary_features.frameBoundary = VK_TRUE; vk::PhysicalDeviceVulkan12Features vulkan12_features {}; @@ -972,6 +999,10 @@ void VulkanCore::createLogicalDeviceAndAllocator(std::span re *chain_tail = &mesh_shader_features; chain_tail = &mesh_shader_features.pNext; } + if (m_fragment_shading_rate_supported) { + *chain_tail = &shading_rate_features; + chain_tail = &shading_rate_features.pNext; + } if (m_ray_tracing_supported) { *chain_tail = &acceleration_structure_features; acceleration_structure_features.pNext = &ray_query_features; @@ -1220,7 +1251,7 @@ auto VulkanCore::calculateDeviceScore(const vk::PhysicalDevice& device, std::spa } extension_score -= static_cast(required_missing_names.size()) * 100; - const std::vector optional_extensions = { + const std::vector optional_extensions = { VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME, @@ -1245,6 +1276,7 @@ auto VulkanCore::calculateDeviceScore(const vk::PhysicalDevice& device, std::spa case 0: version_score = 0; break; case 1: version_score = 25; break; case 2: version_score = 50; break; + case 3: version_score = 75; break; default: version_score = 100; break; } diff --git a/engine/src/toast/renderer/core/vulkan_core.hpp b/engine/src/toast/renderer/core/vulkan_core.hpp index 068da849f..10f6c6f93 100644 --- a/engine/src/toast/renderer/core/vulkan_core.hpp +++ b/engine/src/toast/renderer/core/vulkan_core.hpp @@ -134,6 +134,12 @@ class VulkanCore { return m_mesh_shader_supported; } + /// VK_KHR_fragment_shading_rate with a per pipeline rate, which always offers 2x2 + [[nodiscard]] + auto isFragmentShadingRateSupported() const noexcept -> bool { + return m_fragment_shading_rate_supported; + } + [[nodiscard]] auto isDepthClampSupported() const noexcept -> bool { return m_depth_clamp_supported; @@ -310,6 +316,7 @@ class VulkanCore { bool m_ray_tracing_supported = false; RayTracingMode m_ray_tracing_startup_mode {}; bool m_mesh_shader_supported = false; + bool m_fragment_shading_rate_supported = false; std::string_view m_ray_tracing_reason = "not probed"; uint32_t m_mesh_multiview_views = 0; diff --git a/engine/src/toast/renderer/debug/voxel_debug.cpp b/engine/src/toast/renderer/debug/voxel_debug.cpp index 6e6cc8131..016829425 100644 --- a/engine/src/toast/renderer/debug/voxel_debug.cpp +++ b/engine/src/toast/renderer/debug/voxel_debug.cpp @@ -167,10 +167,10 @@ auto voxelDebugMaterialsDrawn(const RenderFrame& frame) -> std::bitset(scene.records[proxy.record_index].palette_offset) * 4; + const size_t base = static_cast(scene.records[proxy.record_index].palette_offset) * voxel::gpu::k_palette_entry_words; for (uint32_t index = 1; index < voxel::k_palette_size; ++index) { - const size_t word = base + (static_cast(index) * 4); - if (word + 4 > scene.palettes.size()) { + const size_t word = base + (static_cast(index) * voxel::gpu::k_palette_entry_words); + if (word + voxel::gpu::k_palette_entry_words > scene.palettes.size()) { break; } voxel::PaletteEntry entry; @@ -413,8 +413,8 @@ auto probe(const RenderFrame& frame, glm::vec2 cursor) -> std::optional 0.0f ? -1 : 1; } - const size_t palette_word = (static_cast(record.palette_offset) + hit.material) * 4; - if (palette_word + 4 <= packed.scene.palettes.size()) { + const size_t palette_word = (static_cast(record.palette_offset) + hit.material) * voxel::gpu::k_palette_entry_words; + if (palette_word + voxel::gpu::k_palette_entry_words <= packed.scene.palettes.size()) { std::memcpy(&out.palette_entry, packed.scene.palettes.data() + palette_word, sizeof(voxel::PaletteEntry)); } result.hit = out; diff --git a/engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp b/engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp index b99984a16..80675f84f 100644 --- a/engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp +++ b/engine/src/toast/renderer/lighting/gi_dirty_boxes.cpp @@ -16,23 +16,40 @@ namespace renderer { -void GiDirtyBoxes::gather(const RenderFrame& frame, float motion_threshold) { - ZoneScoped; - const auto add = [&](glm::vec3 low, glm::vec3 high) { - if (m_boxes.size() < 2 * k_max_boxes) { - m_boxes.push_back(low); - m_boxes.push_back(high); - return; - } - auto last = m_boxes.end() - 2; - last[0] = glm::min(last[0], low); - last[1] = glm::max(last[1], high); +void addDirtyBox(std::vector& boxes, size_t max_boxes, glm::vec3 low, glm::vec3 high) { + if (boxes.size() < 2 * max_boxes) { + boxes.push_back(low); + boxes.push_back(high); + return; + } + const auto volume = [](glm::vec3 a, glm::vec3 b) { + const glm::vec3 size = glm::max(b - a, glm::vec3(0.0f)); + return size.x * size.y * size.z; }; + size_t best = 0; + float best_growth = std::numeric_limits::max(); + for (size_t i = 0; i + 1 < boxes.size(); i += 2) { + const float growth = volume(glm::min(boxes[i], low), glm::max(boxes[i + 1], high)) - volume(boxes[i], boxes[i + 1]); + if (growth < best_growth) { + best_growth = growth; + best = i; + } + } + boxes[best] = glm::min(boxes[best], low); + boxes[best + 1] = glm::max(boxes[best + 1], high); +} + +void GiDirtyBoxes::gather(const RenderFrame& frame, std::optional motion_threshold) { + ZoneScoped; + const auto add = [&](glm::vec3 low, glm::vec3 high) { addDirtyBox(m_boxes, k_max_boxes, low, high); }; Counts& counts = m_counts; - const float threshold = std::max(motion_threshold, 0.0f); + const float threshold = std::max(motion_threshold.value_or(0.0f), 0.0f); for (const auto& proxy : frame.voxel_instances) { + if (!motion_threshold.has_value()) { + break; + } if (proxy.has_previous && proxy.model == proxy.previous_model) { continue; } diff --git a/engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp b/engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp index 43cd692f7..b85ea4ff9 100644 --- a/engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp +++ b/engine/src/toast/renderer/lighting/gi_dirty_boxes.hpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -13,6 +14,9 @@ namespace renderer { struct RenderFrame; +/// Appends low then high, or once @p max_boxes are held grows the box that grows least so one blast does not swallow the rest +void addDirtyBox(std::vector& boxes, size_t max_boxes, glm::vec3 low, glm::vec3 high); + class GiDirtyBoxes { public: /// Past it every extra region grows the last box @@ -27,7 +31,8 @@ class GiDirtyBoxes { }; /// Every rendered frame so skipped updates still reach the next one - void gather(const RenderFrame& frame, float motion_threshold); + /// @param motion_threshold nullopt for edits only when the caller tracks bodies itself + void gather(const RenderFrame& frame, std::optional motion_threshold); /// Low then high per box [[nodiscard]] diff --git a/engine/src/toast/renderer/passes/debug/perf_window.cpp b/engine/src/toast/renderer/passes/debug/perf_window.cpp index dc8a67848..a32f1a969 100644 --- a/engine/src/toast/renderer/passes/debug/perf_window.cpp +++ b/engine/src/toast/renderer/passes/debug/perf_window.cpp @@ -9,6 +9,7 @@ #include "toast/renderer/compute/async_compute.hpp" #include "toast/renderer/core/vulkan_core.hpp" #include "toast/renderer/lighting/shadow_constants.hpp" +#include "toast/renderer/passes/lighting/gi_clipmap_pass.hpp" #include "toast/renderer/passes/lighting/gi_pass.hpp" #include "toast/renderer/settings/renderer_settings.hpp" #include "toast/renderer/shaders/shader_compiler.hpp" @@ -967,6 +968,44 @@ void PerfWindow::drawSceneTab() { ImGui::EndTable(); } + if (const GiClipmapPass* clipmap = VulkanRenderer::instance->giClipmapPass(); clipmap != nullptr && clipmap->isEnabled()) { + ImGui::SeparatorText("Radiance clipmap fill"); + const GiClipmapPass::Stats clip = clipmap->stats(); + const bool edits_full = clip.edit_boxes >= GiDirtyBoxes::k_max_boxes; + ImGui::Text( + "%u edits in %u of %u boxes, %u body boxes", clip.edits, clip.edit_boxes, GiDirtyBoxes::k_max_boxes, clip.body_boxes + ); + if (edits_full) { + ImGui::SameLine(); + ImGui::TextColored(k_perf_warn, "full, the rest merged into the last box"); + } + if (clip.history_lost) { + ImGui::TextColored(k_perf_warn, "Change history lost so every level refilled whole"); + } + if (ImGui::BeginTable("##perf_gi_clip", 5, ImGuiTableFlags_SizingFixedFit)) { + ImGui::TableSetupColumn("Level"); + ImGui::TableSetupColumn("Boxes"); + ImGui::TableSetupColumn("Cells"); + ImGui::TableSetupColumn("Largest box"); + ImGui::TableSetupColumn("Queued"); + ImGui::TableHeadersRow(); + for (uint32_t i = 0; i < clip.levels && i < GiClipmapPass::k_max_levels; ++i) { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("l%u%s", i, clip.whole[i] ? " whole" : ""); + ImGui::TableNextColumn(); + ImGui::Text("%u", clip.boxes[i]); + ImGui::TableNextColumn(); + ImGui::Text("%llu", static_cast(clip.cells[i])); + ImGui::TableNextColumn(); + ImGui::Text("%llu", static_cast(clip.largest[i])); + ImGui::TableNextColumn(); + ImGui::Text("%llu", static_cast(clip.queued[i])); + } + ImGui::EndTable(); + } + } + const GiPass* gi = VulkanRenderer::instance->giPass(); if (gi == nullptr || !gi->isEnabled()) { return; diff --git a/engine/src/toast/renderer/passes/game/game_pass.cpp b/engine/src/toast/renderer/passes/game/game_pass.cpp new file mode 100644 index 000000000..6fd935523 --- /dev/null +++ b/engine/src/toast/renderer/passes/game/game_pass.cpp @@ -0,0 +1,198 @@ +#include "toast/renderer/passes/game/game_pass.hpp" + +#include "toast/renderer/passes/render_pass_base.hpp" +#include "toast/renderer/shaders/shader_cache.hpp" +#include "toast/renderer/shaders/shader_layout.hpp" +#include "toast/renderer/shaders/vulkan_pipeline.hpp" +#include "toast/renderer/vulkan_renderer.hpp" + +#include +#include +#include +#include +#include +#include + +namespace renderer { + +class GamePass final : public IRenderPass { +public: + GamePass(const GamePassDesc& desc, std::shared_ptr shader) + : m_desc(desc), + m_name(desc.name != nullptr ? desc.name : "Game pass"), + m_shader(std::move(shader)) { + m_desc.name = nullptr; + m_desc.shader_uri = nullptr; + m_pending.resize(static_cast(m_desc.instance_stride) * m_desc.max_instances); + } + + [[nodiscard]] + auto stage() const -> RenderStage override { + return m_desc.stage == GamePassStage::overlay ? RenderStage::overlay : RenderStage::world; + } + + [[nodiscard]] + auto name() const -> std::string_view override { + return m_name; + } + + void setInstances(const void* data, uint32_t count) { + count = std::min(count, m_desc.max_instances); + const std::lock_guard lock(m_mutex); + if (count > 0 && data != nullptr) { + std::memcpy(m_pending.data(), data, static_cast(count) * m_desc.instance_stride); + } + m_count = data != nullptr ? count : 0; + } + + void update(uint32_t frame_index, float dt) override { + (void)frame_index; + (void)dt; + if (!m_built) { + m_built = true; + build(); + } + } + + void record(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t image_index) override { + (void)image_index; + if (!m_pipeline.isReady() || frame_index >= m_sets.size()) { + return; + } + + uint32_t count = 0; + { + const std::lock_guard lock(m_mutex); + count = m_count; + const size_t bytes = static_cast(count) * m_desc.instance_stride; + if (bytes > 0) { + const auto& allocation = m_instance_buffers[frame_index].getAllocation(); + std::memcpy(allocation.getInfo().pMappedData, m_pending.data(), bytes); + allocation.flush(0, bytes); + } + } + if (count == 0) { + return; + } + + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_pipeline.getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, *m_layout.getPipelineLayout(), 0, std::array {*m_sets[frame_index]}, {} + ); + cmd.draw(m_desc.vertices_per_instance, count, 0, 0); + } + +private: + void build() { + auto* renderer = VulkanRenderer::instance; + const auto& core = renderer->getCore(); + const auto& device = core.getDevice(); + + m_layout.rebuild(core, m_shader->reflection, m_name); + const auto& set_layouts = m_layout.getDescriptorSetLayouts(); + if (set_layouts.empty()) { + TOAST_ERROR("Render", "Game pass '{}' shader declares no descriptor set", m_name); + return; + } + + const bool world = m_desc.stage == GamePassStage::world; + VulkanPipeline::Config config; + config.debug_name = m_name; + config.color_format = world ? renderer->getSceneColorFormat() : renderer->getOutputTarget().getColorFormat(); + if (world) { + config.extra_color_formats = worldStageExtraColorFormats(); + config.write_extra_color = m_desc.reactive && m_desc.blend != GamePassBlend::opaque; + config.extra_blend_mask = config.write_extra_color ? 0b111u : 0u; + } + config.depth_format = VulkanRenderer::selectDepthFormat(core); + config.extent = renderer->renderExtent(); + config.shader_spirv = m_shader->spirv; + config.pipeline_layout = *m_layout.getPipelineLayout(); + config.cull_mode = vk::CullModeFlagBits::eNone; + config.depth_test = m_desc.depth_test; + config.depth_write = m_desc.depth_write; + config.blend_enable = m_desc.blend != GamePassBlend::opaque; + config.blend_preset = VulkanPipeline::BlendPreset::none; + if (m_desc.blend == GamePassBlend::additive) { + config.blend_preset = VulkanPipeline::BlendPreset::additive; + } else if (m_desc.blend == GamePassBlend::alpha) { + config.blend_preset = VulkanPipeline::BlendPreset::alpha; + } + m_pipeline.rebuild(core, config); + if (!m_pipeline.isReady()) { + TOAST_ERROR("Render", "Game pass '{}' pipeline failed to build", m_name); + return; + } + + const vk::DeviceSize buffer_size = std::max(m_pending.size(), 16); + const vk::DescriptorSetLayout set_layout = *set_layouts[0]; + const vk::DescriptorPool pool = renderer->getDescriptorPoolHandle(); + for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { + vk::BufferCreateInfo buffer_ci {}; + buffer_ci.size = buffer_size; + buffer_ci.usage = vk::BufferUsageFlagBits::eStorageBuffer; + vma::AllocationCreateInfo alloc_ci {}; + alloc_ci.usage = vma::MemoryUsage::eAuto; + alloc_ci.flags = vma::AllocationCreateFlagBits::eMapped | vma::AllocationCreateFlagBits::eHostAccessSequentialWrite; + m_instance_buffers.push_back(core.getAllocator().createBuffer(buffer_ci, alloc_ci)); + setDebugName(core, *m_instance_buffers.back(), std::format("{} instances[{}]", m_name, i)); + + auto allocated = device.allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &set_layout)); + m_sets.push_back(std::move(allocated[0])); + + const auto* frame_res = renderer->getFrameUBORes(i); + const vk::DescriptorBufferInfo camera_info(**frame_res->gpu_buffer, 0, sizeof(FrameUBO)); + const vk::DescriptorBufferInfo instance_info(*m_instance_buffers.back(), 0, buffer_size); + const std::array writes { + vk::WriteDescriptorSet(*m_sets.back(), 0, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &camera_info), + vk::WriteDescriptorSet(*m_sets.back(), 1, 0, 1, vk::DescriptorType::eStorageBuffer, nullptr, &instance_info), + }; + device.updateDescriptorSets(writes, {}); + } + TOAST_INFO("Render", "Game pass '{}' ready", m_name); + } + + GamePassDesc m_desc; + std::string m_name; + std::shared_ptr m_shader; + bool m_built = false; + + ShaderLayout m_layout; + VulkanPipeline m_pipeline; + std::vector m_sets; + std::vector m_instance_buffers; + + std::mutex m_mutex; + std::vector m_pending; + uint32_t m_count = 0; +}; + +auto createGamePass(const GamePassDesc& desc) -> GamePass* { + if (VulkanRenderer::instance == nullptr || desc.shader_uri == nullptr || desc.instance_stride == 0) { + return nullptr; + } + const auto uid = assets::resolveURI(desc.shader_uri); + auto shader = uid.has_value() ? ShaderCache::get().acquire(*uid) : nullptr; + if (!shader) { + TOAST_ERROR("Render", "Game pass shader {} unavailable", desc.shader_uri); + return nullptr; + } + auto pass = std::make_unique(desc, std::move(shader)); + GamePass* raw = pass.get(); + VulkanRenderer::instance->addRenderPass(std::move(pass)); + return raw; +} + +void setGamePassInstances(GamePass* pass, const void* data, uint32_t count) { + if (pass != nullptr) { + pass->setInstances(data, count); + } +} + +void destroyGamePass(GamePass* pass) { + if (pass != nullptr && VulkanRenderer::instance != nullptr) { + VulkanRenderer::instance->removeRenderPass(pass); + } +} + +} diff --git a/engine/src/toast/renderer/passes/game/game_pass.hpp b/engine/src/toast/renderer/passes/game/game_pass.hpp new file mode 100644 index 000000000..e5a9c1a0b --- /dev/null +++ b/engine/src/toast/renderer/passes/game/game_pass.hpp @@ -0,0 +1,86 @@ +/// @file game_pass.hpp +/// @author dario +/// @date 16/11/2026 + +#pragma once + +#include "toast/export.hpp" + +#include + +/** + * @brief Custom render passes from game code + * + * The engine owns the pipeline, descriptors and buffers. The game only gives a shader, a few plain settings and + * an array of instance structs each frame + * + * Each instance draws vertices_per_instance vertices with no vertex buffer, the vertex shader builds the geometry + * from SV_InstanceID and SV_VertexID + * + * Usage: + * @code + * struct Spark { glm::vec3 position; float size; }; + * + * // begin() + * m_pass = renderer::createGamePass({ + * .name = "Sparks", + * .shader_uri = "assets://Shaders/spark.slang", + * .instance_stride = sizeof(Spark), + * .max_instances = 512, + * }); + * + * // every tick, the last call stays drawn until the next one + * renderer::setGamePassInstances(m_pass, m_sparks.data(), static_cast(m_sparks.size())); + * + * // end(), also before the game module unloads + * renderer::destroyGamePass(std::exchange(m_pass, nullptr)); + * @endcode + */ + +namespace renderer { + +enum class GamePassStage : uint8_t { + /// HDR scene before TAA, bloom and tonemap + world, + /// After the tonemap at output resolution, use viewProjection + overlay, +}; + +enum class GamePassBlend : uint8_t { + opaque, + /// srcAlpha, 1 - srcAlpha + alpha, + /// one, one + additive, +}; + +struct GamePassDesc { + const char* name = "Game pass"; + const char* shader_uri = nullptr; + GamePassStage stage = GamePassStage::world; + GamePassBlend blend = GamePassBlend::additive; + bool depth_test = true; + bool depth_write = false; + /// World stage and blended only. Lets thin or short lived effects survive TAA: the shader also writes + /// SV_Target1-3 (normal, indirect, motion) blended onto the scene, zeros leave them untouched and motion z 1 + /// makes TAA show the pixel this frame + bool reactive = false; + /// sizeof the instance struct, required + uint32_t instance_stride = 0; + /// Extra instances passed to setGamePassInstances are dropped + uint32_t max_instances = 256; + /// 6 for a quad as two triangles + uint32_t vertices_per_instance = 6; +}; + +class GamePass; + +auto TOAST_API createGamePass(const GamePassDesc& desc) -> GamePass*; + +/// Any thread Copies the data. A count of 0 draws nothing +void TOAST_API setGamePassInstances(GamePass* pass, const void* data, uint32_t count); + +/// The GPU objects are freed once no frame in flight uses them +void TOAST_API destroyGamePass(GamePass* pass); + +} diff --git a/engine/src/toast/renderer/passes/geometry/debris_pass.cpp b/engine/src/toast/renderer/passes/geometry/debris_pass.cpp index 62a4de02e..19c562d41 100644 --- a/engine/src/toast/renderer/passes/geometry/debris_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/debris_pass.cpp @@ -1,5 +1,6 @@ #include "toast/renderer/passes/geometry/debris_pass.hpp" +#include "toast/renderer/core/descriptor_writer.hpp" #include "toast/renderer/core/gpu_sync.hpp" #include "toast/renderer/shaders/shader_cache.hpp" #include "toast/renderer/vulkan_renderer.hpp" @@ -15,6 +16,13 @@ constexpr uint32_t k_debris_scene_set = 0; constexpr uint32_t k_debris_set = 1; constexpr uint32_t k_debris_particles_binding = 0; constexpr uint32_t k_debris_list_binding = 1; +constexpr uint32_t k_debris_backdrop_set = 2; +constexpr uint32_t k_debris_backdrop_binding = 0; +constexpr uint32_t k_debris_backdrop_depth_binding = 1; + +/// Bounds and cache signature only, the rest comes from the push constants +auto shadowBoundsOf(const physics::DebrisSimulation& simulation, const AsyncComputeTask::FrameView& view, float extrapolation) + -> DebrisPass::ShadowDraw; } @@ -25,7 +33,7 @@ DebrisPass::DebrisPass( : m_core(&core), m_simulation(std::move(simulation)) { ZoneScoped; - static_assert(sizeof(PushConstants) == 16, "PushConstants is mirrored by debris_draw.slang"); + static_assert(sizeof(PushConstants) == 32, "PushConstants is mirrored by debris_draw.slang"); const auto uid = assets::resolveURI("core://shaders/debris_draw.slang"); const auto shader = uid.has_value() ? ShaderCache::get().acquire(*uid) : nullptr; @@ -85,6 +93,21 @@ DebrisPass::DebrisPass( setDebugName(core, *m_sets.back(), std::format("DebrisPass Set[{}]", i)); } m_bound.resize(VulkanRenderer::k_frames_in_flight); + + // Own set so the shadow pass can keep binding set 1 with its own layout + if (layouts.size() > k_debris_backdrop_set) { + m_backdrop_sampler = vk::raii::Sampler(core.getDevice(), linearClampSamplerInfo()); + setDebugName(core, *m_backdrop_sampler, "DebrisPass BackdropSampler"); + m_backdrop_depth_sampler = vk::raii::Sampler(core.getDevice(), nearestClampSamplerInfo()); + setDebugName(core, *m_backdrop_depth_sampler, "DebrisPass BackdropDepthSampler"); + const vk::DescriptorSetLayout backdrop_layout = *layouts[k_debris_backdrop_set]; + for (uint32_t i = 0; i < VulkanRenderer::k_frames_in_flight; ++i) { + auto sets = core.getDevice().allocateDescriptorSets(vk::DescriptorSetAllocateInfo(pool, 1, &backdrop_layout)); + m_backdrop_sets.push_back(std::move(sets[0])); + setDebugName(core, *m_backdrop_sets.back(), std::format("DebrisPass BackdropSet[{}]", i)); + } + m_bound_backdrop.resize(VulkanRenderer::k_frames_in_flight); + } } auto DebrisPass::prepare(vk::CommandBuffer cmd, uint32_t frame_index) -> bool { @@ -129,9 +152,52 @@ auto DebrisPass::prepare(vk::CommandBuffer cmd, uint32_t frame_index) -> bool { .voxel_size = voxel::k_voxel_size, .list_capacity = m_simulation->capacity() * physics::DebrisSimulation::k_voxels_per_particle, }; + m_shadow = shadowBoundsOf(*m_simulation, view, m_push.extrapolation); + m_shadow.extrapolation = m_push.extrapolation; + m_shadow.voxel_size = m_push.voxel_size; + m_shadow.list_capacity = m_push.list_capacity; return true; } +namespace { + +auto shadowBoundsOf(const physics::DebrisSimulation& simulation, const AsyncComputeTask::FrameView& view, float extrapolation) + -> DebrisPass::ShadowDraw { + DebrisPass::ShadowDraw draw; + physics::DebrisSimulation::ShadowBounds bounds; + if (!view.read(simulation.shadowBoundsId(), std::as_writable_bytes(std::span {&bounds, 1}))) { + // No readback so cast everywhere and redraw every frame + draw.bounds_radius = std::numeric_limits::max(); + return draw; + } + + const auto unordered = [](uint32_t bits) { + return std::bit_cast((bits & 0x80000000u) != 0u ? bits & 0x7FFFFFFFu : ~bits); + }; + const glm::vec3 low(unordered(bounds.min[0]), unordered(bounds.min[1]), unordered(bounds.min[2])); + const glm::vec3 high(unordered(bounds.max[0]), unordered(bounds.max[1]), unordered(bounds.max[2])); + if (bounds.min[0] > bounds.max[0]) { + // No opaque pieces, stable so their last shadow clears once + draw.signature = 0; + return draw; + } + + // The step is drawn moved by velocity times the extrapolation + const float drift = std::bit_cast(bounds.max_speed) * std::abs(extrapolation); + draw.bounds_center = (low + high) * 0.5f; + draw.bounds_radius = (glm::length(high - low) * 0.5f) + drift; + if (bounds.changing == 0) { + uint64_t hash = 0xCBF29CE484222325ull; + for (const uint32_t word : {bounds.min[0], bounds.min[1], bounds.min[2], bounds.max[0], bounds.max[1], bounds.max[2]}) { + hash = (hash ^ word) * 0x100000001B3ull; + } + draw.signature = hash; + } + return draw; +} + +} + void DebrisPass::record(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t image_index) { ZoneScoped; (void)image_index; @@ -156,9 +222,45 @@ void DebrisPass::recordGlass(vk::CommandBuffer cmd, uint32_t frame_index) { ZoneScoped; // Cleared here since prepare only runs on frames with a voxel scope const vk::Buffer args = std::exchange(m_args, nullptr); - if (!args || !m_glass_pipeline.isReady() || frame_index >= m_sets.size()) { + if (!args || !m_glass_pipeline.isReady() || frame_index >= m_sets.size() || frame_index >= m_backdrop_sets.size()) { + return; + } + + auto* renderer = VulkanRenderer::instance; + const std::array backdrop {renderer->getGlassBackdropView(), renderer->getGlassBackdropDepthView()}; + if (!backdrop[0] || !backdrop[1]) { return; } + // The set is first bound below so updating it here is safe + if (m_bound_backdrop.update(frame_index, backdrop)) { + DescriptorWriter writer; + writer.image( + *m_backdrop_sets[frame_index], + k_debris_backdrop_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_backdrop_sampler, + backdrop[0], + vk::ImageLayout::eShaderReadOnlyOptimal + ); + writer.image( + *m_backdrop_sets[frame_index], + k_debris_backdrop_depth_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_backdrop_depth_sampler, + backdrop[1], + vk::ImageLayout::eDepthReadOnlyOptimal + ); + writer.flush(m_core->getDevice()); + } + + PushConstants push = m_push; + if (renderer->ssrFrame() && renderer->glassBackdropCaptured()) { + const auto ssr = renderer->glassSsrSettings(); + push.reflection_reach = ssr.stride * static_cast(ssr.max_steps); + push.reflection_steps = ssr.max_steps; + push.reflection_thickness = ssr.thickness; + push.reflection_roughness = ssr.max_roughness; + } const vk::PipelineLayout layout = *m_layout.getPipelineLayout(); cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_glass_pipeline.getPipeline()); @@ -166,10 +268,10 @@ void DebrisPass::recordGlass(vk::CommandBuffer cmd, uint32_t frame_index) { vk::PipelineBindPoint::eGraphics, layout, k_debris_scene_set, - std::array {m_scene_sets.get(frame_index), *m_sets[frame_index]}, + std::array {m_scene_sets.get(frame_index), *m_sets[frame_index], *m_backdrop_sets[frame_index]}, {} ); - cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(PushConstants), &m_push); + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(PushConstants), &push); cmd.drawIndirect(args, sizeof(vk::DrawIndirectCommand), 1, sizeof(vk::DrawIndirectCommand)); } diff --git a/engine/src/toast/renderer/passes/geometry/debris_pass.hpp b/engine/src/toast/renderer/passes/geometry/debris_pass.hpp index 316b947a4..3bdb02955 100644 --- a/engine/src/toast/renderer/passes/geometry/debris_pass.hpp +++ b/engine/src/toast/renderer/passes/geometry/debris_pass.hpp @@ -13,7 +13,9 @@ #include "toast/renderer/shaders/vulkan_pipeline.hpp" #include +#include #include +#include #include #include @@ -49,12 +51,41 @@ class DebrisPass : public IRenderPass { return "Debris"; } + /// What the shadow pass needs to draw the opaque debris, args is null unless prepare() succeeded this frame + struct ShadowDraw { + vk::DescriptorSet set = nullptr; + vk::Buffer args = nullptr; + float extrapolation = 0.0f; + float voxel_size = 0.0f; + uint32_t list_capacity = 0; + /// Sphere around every opaque piece as drawn, radius below 0 when there are none + glm::vec3 bounds_center {0.0f}; + float bounds_radius = -1.0f; + /// Empty while a piece moves so its shadow must redraw, otherwise stable until one changes + std::optional signature; + }; + + [[nodiscard]] + auto shadowDraw(uint32_t frame_index) const -> ShadowDraw { + if (!m_args || frame_index >= m_sets.size()) { + return {}; + } + ShadowDraw draw = m_shadow; + draw.set = *m_sets[frame_index]; + draw.args = m_args; + return draw; + } + private: struct PushConstants { float extrapolation = 0.0f; float frame_delta = 0.0f; float voxel_size = 0.0f; uint32_t list_capacity = 0; + float reflection_reach = 0.0f; + uint32_t reflection_steps = 0; + float reflection_thickness = 0.0f; + float reflection_roughness = 0.0f; }; const VulkanCore* m_core = nullptr; @@ -68,6 +99,13 @@ class DebrisPass : public IRenderPass { DescriptorCache> m_bound; vk::Buffer m_args = nullptr; PushConstants m_push; + /// Glass backdrop colour and depth the SSR march of glass pieces reads + std::vector m_backdrop_sets; + DescriptorCache> m_bound_backdrop; + vk::raii::Sampler m_backdrop_sampler = nullptr; + vk::raii::Sampler m_backdrop_depth_sampler = nullptr; + /// Without the set and args which come per frame + ShadowDraw m_shadow; }; } diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp index 46ebbb0a1..fee167ade 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.cpp @@ -3,11 +3,14 @@ #include "toast/renderer/core/depth_convention.hpp" #include "toast/renderer/core/descriptor_writer.hpp" #include "toast/renderer/core/gpu_sync.hpp" +#include "toast/renderer/core/gpu_timer.hpp" +#include "toast/renderer/lighting/frustum.hpp" #include "toast/renderer/shaders/shader_cache.hpp" #include "toast/renderer/shaders/shader_compiler.hpp" #include "toast/renderer/voxel/voxel_gpu_storage.hpp" #include "toast/renderer/vulkan_renderer.hpp" +#include #include #include @@ -70,6 +73,27 @@ constexpr uint32_t k_ambient_grid_capacity = 65536; /// More cells than this goes to the global list constexpr uint64_t k_ambient_grid_max_cells = 125; +/// scene_trace.slang buffers of frame @p frame_index +void writeTraceSceneBuffers(DescriptorWriter& writer, vk::DescriptorSet set, uint32_t frame_index) { + const VoxelTraceScene* trace = VulkanRenderer::instance->voxelTraceScene(); + if (trace == nullptr) { + return; + } + writer.buffer(set, k_trace_volumes_binding, vk::DescriptorType::eStorageBuffer, trace->volumeBuffer(frame_index)); + writer.buffer(set, k_trace_bounds_binding, vk::DescriptorType::eStorageBuffer, trace->boundsBuffer(frame_index)); + writer.buffer(set, k_trace_grid_binding, vk::DescriptorType::eStorageBuffer, trace->gridBuffer(frame_index)); + if (ShaderCompiler::isRayQueryAvailable()) { + const VoxelBlasCache* bricks = VulkanRenderer::instance->voxelBlasCache(); + writer.buffer(set, k_trace_brick_bases_binding, vk::DescriptorType::eStorageBuffer, trace->brickBaseBuffer(frame_index)); + writer.buffer( + set, + k_trace_bricks_binding, + vk::DescriptorType::eStorageBuffer, + bricks != nullptr ? bricks->poolBuffer() : trace->brickBaseBuffer(frame_index) + ); + } +} + auto ambientGridHash(const glm::ivec3& cell) -> uint32_t { const glm::uvec3 u(cell); return ((u.x * 73856093u) ^ (u.y * 19349663u) ^ (u.z * 83492791u)) & (k_ambient_grid_buckets - 1u); @@ -94,6 +118,8 @@ constexpr uint32_t k_traced_specular = 16; constexpr uint32_t k_gi_gather = 32; /// Mirrors voxel_lighting.slang kGiClipmap constexpr uint32_t k_gi_clipmap = 64; +/// Mirrors voxel_lighting.slang kGiDenoise +constexpr uint32_t k_gi_denoise = 128; /// ReSTIR reuse of last frame's reservoir at the reprojected pixel and two around it constexpr uint32_t k_reused_reservoirs = 3; @@ -105,6 +131,13 @@ constexpr uint32_t k_glass_bricks_binding = 7; /// voxel_glass.slang gBackdrop and gBackdropDepth constexpr uint32_t k_backdrop_binding = 8; constexpr uint32_t k_backdrop_depth_binding = 9; +/// voxel_glass.slang gNearestGlassDepth +constexpr uint32_t k_nearest_glass_depth_binding = 16; +constexpr uint32_t k_nearest_glass_normal_binding = 17; +constexpr uint32_t k_nearest_glass_motion_binding = 18; +constexpr uint32_t k_glass_mask_binding = 19; +/// voxel_glass.slang kGlassInsideBit +constexpr uint32_t k_glass_inside_bit = 0x80000000u; /// Turns the denoiser pattern each frame for TAA to average constexpr float k_golden_ratio_conjugate = 0.61803398875f; @@ -545,32 +578,7 @@ void VoxelPass::createLighting(const VulkanCore& core, vk::Format scene_format, writer.buffer( *m_lighting_storage_sets.back(), k_ambient_grid_binding, vk::DescriptorType::eStorageBuffer, *m_ambient_grids.back() ); - if (const VoxelTraceScene* trace = VulkanRenderer::instance->voxelTraceScene(); trace != nullptr) { - writer.buffer( - *m_lighting_storage_sets.back(), k_trace_volumes_binding, vk::DescriptorType::eStorageBuffer, trace->volumeBuffer(i) - ); - writer.buffer( - *m_lighting_storage_sets.back(), k_trace_bounds_binding, vk::DescriptorType::eStorageBuffer, trace->boundsBuffer(i) - ); - writer.buffer( - *m_lighting_storage_sets.back(), k_trace_grid_binding, vk::DescriptorType::eStorageBuffer, trace->gridBuffer(i) - ); - if (ShaderCompiler::isRayQueryAvailable()) { - const VoxelBlasCache* bricks = VulkanRenderer::instance->voxelBlasCache(); - writer.buffer( - *m_lighting_storage_sets.back(), - k_trace_brick_bases_binding, - vk::DescriptorType::eStorageBuffer, - trace->brickBaseBuffer(i) - ); - writer.buffer( - *m_lighting_storage_sets.back(), - k_trace_bricks_binding, - vk::DescriptorType::eStorageBuffer, - bricks != nullptr ? bricks->poolBuffer() : trace->brickBaseBuffer(i) - ); - } - } + writeTraceSceneBuffers(writer, *m_lighting_storage_sets.back(), i); writer.flush(core.getDevice()); } @@ -606,7 +614,6 @@ void VoxelPass::createGlass(const VulkanCore& core, vk::Format scene_format, vk: } const bool dual_source = core.isDualSourceBlendSupported(); - m_glass_dual_source = dual_source; m_backdrop_sampler = vk::raii::Sampler(core.getDevice(), linearClampSamplerInfo()); setDebugName(core, *m_backdrop_sampler, "VoxelGlass BackdropSampler"); m_backdrop_depth_sampler = vk::raii::Sampler(core.getDevice(), nearestClampSamplerInfo()); @@ -624,34 +631,62 @@ void VoxelPass::createGlass(const VulkanCore& core, vk::Format scene_format, vk: config.pipeline_layout = *m_glass_layout.getPipelineLayout(); config.vertex_bindings = {}; config.vertex_attributes = {}; - config.fragment_entry = dual_source ? "fragmentMain" : "fragmentPremultiplied"; - // Back faces so a camera inside a brick still draws it - config.cull_mode = vk::CullModeFlagBits::eFront; config.depth_test = true; config.depth_write = false; config.depth_compare = depth::k_closer; config.blend_preset = dual_source ? VulkanPipeline::BlendPreset::dual_source : VulkanPipeline::BlendPreset::premultiplied; - m_glass_pipeline.rebuild(core, config); + // Outside bricks draw front faces so their conservative depth keeps early testing, a brick holding the camera draws back faces + const auto build_pair = [&](std::array& pipelines, const std::string& name, const std::string& entry) { + config.debug_name = name + " Outside"; + config.fragment_entry = entry + "Outside"; + config.cull_mode = vk::CullModeFlagBits::eBack; + pipelines[0].rebuild(core, config); + config.debug_name = name + " Inside"; + config.fragment_entry = entry; + config.cull_mode = vk::CullModeFlagBits::eFront; + pipelines[1].rebuild(core, config); + }; + // The driver drops the reflection paths and debug views a variant never takes so the shader keeps fewer registers + constexpr std::array k_variant_names {"", " Traced", " Screen", " Debug"}; + for (uint32_t variant = 0; variant < glass_variant_count; ++variant) { + const bool debug = variant == glass_variant_debug; + config.specialization_constants = {debug ? 0u : variant, debug ? 1u : 0u}; + build_pair( + m_glass_pipelines[variant], + std::format("VoxelGlass{}", k_variant_names[variant]), + dual_source ? "fragmentMain" : "fragmentPremultiplied" + ); + if (!debug && core.isFragmentShadingRateSupported()) { + config.debug_name = std::format("VoxelGlass Far{}", k_variant_names[variant]); + config.fragment_entry = dual_source ? "fragmentMainFar" : "fragmentPremultipliedFar"; + config.cull_mode = vk::CullModeFlagBits::eBack; + config.fragment_shading_rate = vk::Extent2D {2, 2}; + m_glass_far_pipelines[variant].rebuild(core, config); + config.fragment_shading_rate = vk::Extent2D {1, 1}; + } + } + // The passes below never light glass + config.specialization_constants.clear(); - config.debug_name = "VoxelGlass Surface"; - config.fragment_entry = "fragmentSurface"; config.blend_preset = VulkanPipeline::BlendPreset::none; config.write_color = false; config.write_extra_color = true; config.depth_write = true; - m_glass_surface_pipeline.rebuild(core, config); + build_pair(m_glass_surface_pipelines, "VoxelGlass Surface", "fragmentSurface"); + + config.debug_name = "VoxelGlass Surface Copy"; + config.vertex_entry = "vertexFullscreen"; + config.fragment_entry = "fragmentSurfaceCopy"; + config.cull_mode = vk::CullModeFlagBits::eNone; + m_glass_surface_copy_pipeline.rebuild(core, config); + config.vertex_entry = "vertexMain"; - config.debug_name = "VoxelGlass Mask"; - config.fragment_entry = "fragmentMask"; - config.color_format = vk::Format::eR8Unorm; - config.extra_color_formats.clear(); + // Own depth over a copy of the opaque depth so blended draws still test against the opaque depth + config.color_format = vk::Format::eR8G8Unorm; + config.extra_color_formats = {k_scene_normal_format, k_scene_motion_format}; config.write_color = true; - config.write_extra_color = false; - config.depth_test = true; - config.depth_write = false; - config.depth_compare = depth::k_closer_or_equal; - config.blend_preset = VulkanPipeline::BlendPreset::none; - m_glass_mask_pipeline.rebuild(core, config); + config.write_extra_color = true; + build_pair(m_glass_nearest_pipelines, "VoxelGlass Nearest", "fragmentNearest"); if (!dual_source) { TOAST_WARN("Render", "dualSrcBlend unsupported so voxel glass fades the background without tinting it"); @@ -682,6 +717,8 @@ void VoxelPass::createGlass(const VulkanCore& core, vk::Format scene_format, vk: DescriptorWriter writer; writer.buffer(*m_glass_sets.back(), k_instance_binding, vk::DescriptorType::eStorageBuffer, *m_instance_buffers[i]); writer.buffer(*m_glass_sets.back(), k_glass_bricks_binding, vk::DescriptorType::eStorageBuffer, *m_glass_buffers.back()); + // Glass traces its own reflections + writeTraceSceneBuffers(writer, *m_glass_sets.back(), i); writer.flush(core.getDevice()); } } @@ -951,7 +988,8 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { gi.enabled.load(std::memory_order_relaxed) && gi.backend.load(std::memory_order_relaxed) == GiSettings::k_backend_clipmap; // The gather target is sized for the main view so captures take the one cone path m_gi_gather = m_gi_clipmap && !capture && m_gi_gather_pipeline.isReady(); - m_denoise_active = (m_marched_lights || m_ambient_rays) && frame->render_mode == 0 && !capture && + // Clipmap GI goes through it too since its rotating cones only settle over frames + m_denoise_active = (m_marched_lights || m_ambient_rays || m_gi_clipmap) && frame->render_mode == 0 && !capture && m_denoise_temporal_pipeline.isReady() && m_denoise_composite_pipeline.isReady() && (frame_index * 2) + 1 < m_denoise_sets.size() && m_denoise_history[1][1].isReady(); if (!m_denoise_active) { @@ -995,11 +1033,16 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { prepareGlass(frame_index, *frame->voxel_storage, std::span(m_instance_scratch.data(), m_draws.size())); // Before any scope of this frame binds the glass set - const std::array backdrop { - VulkanRenderer::instance->getGlassBackdropView(), VulkanRenderer::instance->getGlassBackdropDepthView() + const std::array backdrop { + VulkanRenderer::instance->getGlassBackdropView(), + VulkanRenderer::instance->getGlassBackdropDepthView(), + VulkanRenderer::instance->getGlassNearestDepthView(), + VulkanRenderer::instance->getGlassNearestNormalView(), + VulkanRenderer::instance->getGlassNearestMotionView(), + VulkanRenderer::instance->getGlassMaskView() }; - if (frame_index < m_glass_sets.size() && frame_index < m_bound_backdrop.size() && backdrop[0] && backdrop[1] && - m_bound_backdrop.update(frame_index, backdrop)) { + if (frame_index < m_glass_sets.size() && frame_index < m_bound_backdrop.size() && + std::ranges::all_of(backdrop, std::identity {}) && m_bound_backdrop.update(frame_index, backdrop)) { DescriptorWriter writer; writer.image( *m_glass_sets[frame_index], @@ -1017,6 +1060,38 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { backdrop[1], vk::ImageLayout::eDepthReadOnlyOptimal ); + writer.image( + *m_glass_sets[frame_index], + k_nearest_glass_depth_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_backdrop_depth_sampler, + backdrop[2], + vk::ImageLayout::eDepthReadOnlyOptimal + ); + writer.image( + *m_glass_sets[frame_index], + k_nearest_glass_normal_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_backdrop_depth_sampler, + backdrop[3], + vk::ImageLayout::eShaderReadOnlyOptimal + ); + writer.image( + *m_glass_sets[frame_index], + k_nearest_glass_motion_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_backdrop_depth_sampler, + backdrop[4], + vk::ImageLayout::eShaderReadOnlyOptimal + ); + writer.image( + *m_glass_sets[frame_index], + k_glass_mask_binding, + vk::DescriptorType::eCombinedImageSampler, + *m_backdrop_depth_sampler, + backdrop[5], + vk::ImageLayout::eShaderReadOnlyOptimal + ); writer.flush(m_core->getDevice()); } @@ -1051,18 +1126,19 @@ auto VoxelPass::prepare(uint32_t frame_index) -> bool { } } - // Late survivors go after every other list and are at most the retest cells - m_occlusion_active = wanted && m_occlusion_mode == OcclusionMode::engaged; + // A probe face is one frame whose pyramid would come from another face, so captures draw every cell + m_occlusion_active = wanted && m_occlusion_mode == OcclusionMode::engaged && !capture; ensureCellCapacity(frame_index, m_occlusion_active ? 2 * m_total_cells : m_total_cells); m_cells_active = true; // A voxel covers at least this many pixels closer than near_voxels voxels whatever the volume scale + // Captures skip the quads since their buffer grows from the last frame and a probe face has no next frame to catch up const float raster_pixels = VulkanRenderer::instance->voxelRasterPixels(); const float height = static_cast(VulkanRenderer::instance->renderExtent().height); - m_near_voxels = - raster_pixels > 0.0f && m_mesh_pipeline.isReady() && m_quad_pipeline.isReady() && m_quad_depth_pipeline.isReady() - ? std::abs(frame->frame_data.projection[1][1]) * height / (2.0f * raster_pixels) - : 0.0f; + m_near_voxels = !capture && raster_pixels > 0.0f && m_mesh_pipeline.isReady() && m_quad_pipeline.isReady() && + m_quad_depth_pipeline.isReady() + ? std::abs(frame->frame_data.projection[1][1]) * height / (2.0f * raster_pixels) + : 0.0f; m_mesh_shading = m_near_voxels > 0.0f && VulkanRenderer::instance->voxelMeshShaders() && m_draw_mesh_tasks_indirect != nullptr && m_mesh_quad_pipeline.isReady(); } else if (const auto now = std::chrono::steady_clock::now(); now - m_last_limit_warning > std::chrono::seconds(5)) { @@ -1462,7 +1538,7 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: .reuse = glm::uvec4( (instance->voxelReservoirHistory() ? k_reuse_history : 0u) | (m_spatial_active ? k_reuse_spatial : 0u) | (m_scene_glass ? k_scene_glass : 0u) | (instance->voxelAmbientRayQuery() ? k_ambient_ray_query : 0u) | - (m_gi_gather ? k_gi_gather : 0u) | (m_gi_clipmap ? k_gi_clipmap : 0u) | traced_specular | + (m_gi_gather ? k_gi_gather : 0u) | (m_gi_clipmap ? k_gi_clipmap | k_gi_denoise : 0u) | traced_specular | (std::min(instance->voxelGlassShadowReach(), 0xFFFFu) << 16), k_reservoir_m_cap * instance->voxelLightCandidates(), k_reused_reservoirs, @@ -1508,83 +1584,173 @@ void VoxelPass::recordLighting(vk::CommandBuffer cmd, uint32_t frame_index, vk:: void VoxelPass::prepareGlass(uint32_t frame_index, const VoxelGpuStorage& storage, std::span instances) { ZoneScoped; - m_glass_draws.clear(); const auto* frame = VulkanRenderer::instance->renderingFrame(); - if (!m_glass_pipeline.isReady() || frame_index >= m_glass_buffers.size() || frame == nullptr) { + if (!m_glass_pipelines[glass_variant_plain][0].isReady() || frame_index >= m_glass_buffers.size() || frame == nullptr) { + m_glass_draws.clear(); + m_glass_count = 0; + m_glass_key.reset(); + m_glass_screen_bounds.reset(); return; } - const glm::vec3 camera = frame->frame_data.camera_position; - const float half_brick = 0.5f * static_cast(voxel::k_brick_dim); - for (uint32_t i = 0; i < instances.size(); ++i) { - const VoxelInstanceGpu& instance = instances[i]; - const std::span bricks = storage.glassBricks(instance.record_index); - if (bricks.empty()) { - continue; + // Same view, instances and glass bricks as last frame so its culled and sorted list stands + uint64_t key = 0xCBF29CE484222325ull; + const auto mix = [&key](std::span words) { + for (const uint32_t word : words) { + key = (key ^ word) * 0x100000001B3ull; } - const glm::uvec3 dims = storage.recordBrickDims(instance.record_index); - for (const uint32_t brick : bricks) { - const glm::uvec3 coord(brick % dims.x, (brick / dims.x) % dims.y, brick / (dims.x * dims.y)); - const glm::vec3 local = (glm::vec3(coord) * static_cast(voxel::k_brick_dim)) + half_brick; - const glm::vec3 delta = glm::vec3(instance.voxel_to_world * glm::vec4(local, 1.0f)) - camera; - m_glass_draws.push_back({.distance_squared = glm::dot(delta, delta), .instance = i, .brick = brick}); + }; + const auto mix_bytes = [&mix](const auto& value) { + std::array words {}; + std::memcpy(words.data(), &value, sizeof(value)); + mix(words); + }; + mix_bytes(frame->frame_data.view_projection); + mix_bytes(frame->near_plane); + for (const VoxelInstanceGpu& instance : instances) { + const std::span bricks = storage.glassBricks(instance.record_index); + mix_bytes(instance.voxel_to_world); + mix(std::array {instance.record_index, static_cast(bricks.size())}); + mix(bricks); + } + + if (key != m_glass_key) { + m_glass_key = key; + m_glass_draws.clear(); + // Sphere rects in NDC so the backdrop copy can skip what no glass covers + glm::vec4 bounds( + std::numeric_limits::max(), + std::numeric_limits::max(), + -std::numeric_limits::max(), + -std::numeric_limits::max() + ); + bool bounded = true; + const glm::mat4& view_projection = frame->frame_data.view_projection; + const float lens = std::max(std::abs(frame->frame_data.projection[0][0]), std::abs(frame->frame_data.projection[1][1])); + const glm::vec3 camera = frame->frame_data.camera_position; + const auto planes = extractFrustumPlanes(frame->frame_data.view_projection, depth::k_reversed_z); + const float half_brick = 0.5f * static_cast(voxel::k_brick_dim); + const auto largest_axis = [](const glm::mat4& m) { + return std::max({glm::length(glm::vec3(m[0])), glm::length(glm::vec3(m[1])), glm::length(glm::vec3(m[2]))}); + }; + for (uint32_t i = 0; i < instances.size(); ++i) { + const VoxelInstanceGpu& instance = instances[i]; + const std::span bricks = storage.glassBricks(instance.record_index); + if (bricks.empty()) { + continue; + } + const glm::uvec3 dims = storage.recordBrickDims(instance.record_index); + const float radius = half_brick * std::numbers::sqrt3_v * largest_axis(instance.voxel_to_world); + // Near plane in voxels as voxel::containsPoint pads it so a front face the near plane clips counts as inside + const glm::vec3 voxel_camera = glm::vec3(instance.world_to_voxel * glm::vec4(camera, 1.0f)); + const float guard = frame->near_plane * largest_axis(instance.world_to_voxel); + for (const uint32_t brick : bricks) { + const glm::uvec3 coord(brick % dims.x, (brick / dims.x) % dims.y, brick / (dims.x * dims.y)); + const glm::vec3 low = glm::vec3(coord) * static_cast(voxel::k_brick_dim); + const glm::vec3 centre = glm::vec3(instance.voxel_to_world * glm::vec4(low + half_brick, 1.0f)); + const bool inside = glm::all(glm::greaterThanEqual(voxel_camera, low - guard)) && + glm::all(glm::lessThanEqual(voxel_camera, low + static_cast(voxel::k_brick_dim) + guard)); + if (!inside && !sphereInFrustum(planes, centre, radius)) { + continue; + } + const glm::vec3 delta = centre - camera; + m_glass_draws.push_back({.distance_squared = glm::dot(delta, delta), .instance = i, .brick = brick, .inside = inside}); + const glm::vec4 clip = view_projection * glm::vec4(centre, 1.0f); + if (clip.w - radius <= frame->near_plane) { + bounded = false; + } else if (bounded) { + const glm::vec2 ndc = glm::vec2(clip) / clip.w; + const float reach = radius * lens / (clip.w - radius); + bounds = glm::vec4(glm::min(glm::vec2(bounds), ndc - reach), glm::max(glm::vec2(bounds.z, bounds.w), ndc + reach)); + } + } } - } - if (m_glass_draws.empty()) { - return; - } - // Far to near and the nearest kept when over the limit - std::ranges::sort(m_glass_draws, [](const GlassDraw& a, const GlassDraw& b) { - return a.distance_squared > b.distance_squared; - }); - size_t first = 0; - if (m_glass_draws.size() > k_max_glass_bricks) { - first = m_glass_draws.size() - k_max_glass_bricks; - if (const auto now = std::chrono::steady_clock::now(); now - m_last_glass_warning > std::chrono::seconds(5)) { - m_last_glass_warning = now; - TOAST_WARN("Render", "VoxelPass: {} glass bricks, only the nearest {} are drawn", m_glass_draws.size(), k_max_glass_bricks); + // Far to near and the nearest kept when over the limit + std::ranges::sort(m_glass_draws, [](const GlassDraw& a, const GlassDraw& b) { + return a.distance_squared > b.distance_squared; + }); + if (m_glass_draws.size() > k_max_glass_bricks) { + const size_t first = m_glass_draws.size() - k_max_glass_bricks; + if (const auto now = std::chrono::steady_clock::now(); now - m_last_glass_warning > std::chrono::seconds(5)) { + m_last_glass_warning = now; + TOAST_WARN( + "Render", "VoxelPass: {} glass bricks, only the nearest {} are drawn", m_glass_draws.size(), k_max_glass_bricks + ); + } + m_glass_draws.erase(m_glass_draws.begin(), m_glass_draws.begin() + static_cast(first)); } + m_glass_screen_bounds = bounded && !m_glass_draws.empty() ? std::optional(bounds) : std::nullopt; } + m_glass_count = 0; const auto& allocation = m_glass_buffers[frame_index].getAllocation(); auto* mapped = static_cast(allocation.getInfo().pMappedData); - if (mapped == nullptr) { + if (mapped == nullptr || m_glass_draws.empty()) { return; } - m_glass_draws.erase(m_glass_draws.begin(), m_glass_draws.begin() + static_cast(first)); + // Each frame slot has its own buffer so a reused list is still written m_glass_count = static_cast(m_glass_draws.size()); for (uint32_t i = 0; i < m_glass_count; ++i) { - mapped[i] = glm::uvec2(m_glass_draws[i].instance, m_glass_draws[i].brick); + mapped[i] = + glm::uvec2(m_glass_draws[i].instance | (m_glass_draws[i].inside ? k_glass_inside_bit : 0u), m_glass_draws[i].brick); } allocation.flush(0, sizeof(glm::uvec2) * m_glass_count); } void VoxelPass::recordGlass(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t first, uint32_t count) { ZoneScoped; - recordGlassBricks(cmd, frame_index, m_glass_pipeline, first, count); + // One name for every run so the timer sums the blended glass between the meshes + const GpuScope scope(VulkanRenderer::instance->gpuTimer(), frame_index, cmd, "Voxel glass blend"); + recordGlassBricks(cmd, frame_index, GlassStage::blend, first, count); } void VoxelPass::recordGlassSurfaces(vk::CommandBuffer cmd, uint32_t frame_index) { ZoneScoped; - recordGlassBricks(cmd, frame_index, m_glass_surface_pipeline, 0, m_glass_count); + // The pre-pass already walked the bricks for the nearest surface so a fullscreen copy writes it + if (m_nearest_glass_valid && m_glass_count > 0 && m_glass_surface_copy_pipeline.isReady() && + frame_index < m_glass_sets.size() && m_glass_scene_sets.get(frame_index)) { + const vk::PipelineLayout layout = *m_glass_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_glass_surface_copy_pipeline.getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, + layout, + k_scene_set, + std::array {m_glass_scene_sets.get(frame_index), *m_glass_sets[frame_index]}, + {} + ); + cmd.draw(3, 1, 0, 0); + return; + } + recordGlassBricks(cmd, frame_index, GlassStage::surface, 0, m_glass_count); } -void VoxelPass::recordGlassMask(vk::CommandBuffer cmd, uint32_t frame_index) { +void VoxelPass::recordGlassNearest(vk::CommandBuffer cmd, uint32_t frame_index) { ZoneScoped; - recordGlassBricks(cmd, frame_index, m_glass_mask_pipeline, 0, m_glass_count); + recordGlassBricks(cmd, frame_index, GlassStage::nearest, 0, m_glass_count); } -void VoxelPass::recordGlassBricks( - vk::CommandBuffer cmd, uint32_t frame_index, const VulkanPipeline& pipeline, uint32_t first, uint32_t count -) { - if (count == 0 || first + count > m_glass_count || !pipeline.isReady() || frame_index >= m_glass_sets.size() || - !m_glass_scene_sets.get(frame_index)) { +void VoxelPass::recordGlassBricks(vk::CommandBuffer cmd, uint32_t frame_index, GlassStage stage, uint32_t first, uint32_t count) { + const auto* renderer = VulkanRenderer::instance; + const bool lit = stage == GlassStage::blend; + // The SSR and traced specular post passes read the opaque surface behind glass so glass reflects in its own shading + const bool traced = lit && renderer->tracedSpecularFrame(); + const bool screen = lit && !traced && renderer->ssrFrame(); + const auto* rendering = renderer->renderingFrame(); + const bool debug_views = rendering != nullptr && rendering->render_mode != 0; + const GlassVariant variant = debug_views ? glass_variant_debug + : traced ? glass_variant_traced + : screen ? glass_variant_screen + : glass_variant_plain; + const std::array& pipelines = lit ? m_glass_pipelines[variant] + : stage == GlassStage::surface ? m_glass_surface_pipelines + : m_glass_nearest_pipelines; + if (count == 0 || first + count > m_glass_count || !pipelines[0].isReady() || !pipelines[1].isReady() || + frame_index >= m_glass_sets.size() || !m_glass_scene_sets.get(frame_index)) { return; } const vk::PipelineLayout layout = *m_glass_layout.getPipelineLayout(); - cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.getPipeline()); cmd.bindDescriptorSets( vk::PipelineBindPoint::eGraphics, layout, @@ -1593,29 +1759,60 @@ void VoxelPass::recordGlassBricks( {} ); // SV_InstanceID leaves out firstInstance so the run start is pushed - const auto* renderer = VulkanRenderer::instance; - const GlassPush push { + const auto ssr = renderer->glassSsrSettings(); + GlassPush push { .first = first, - .refraction = m_backdrop_captured && &pipeline == &m_glass_pipeline ? renderer->voxelGlassRefraction() : 0.0f, - .refraction_distance = renderer->voxelGlassRefractionDistance(), - .refraction_voxels = renderer->voxelGlassRefractionVoxels(), .lit_surfaces = renderer->voxelGlassLitSurfaces(), // Only the blended pass lights glass and it tests closer than the opaque depth - .depth_test = m_backdrop_depth_valid && &pipeline == &m_glass_pipeline ? 1u : 0u, + .depth_test = m_backdrop_depth_valid && lit ? 1u : 0u, + .reflection_reach = traced ? std::min(renderer->voxelSpecularReach(), renderer->voxelGlassReflectionReach()) + : ssr.stride * static_cast(ssr.max_steps), + .reflection_roughness = traced ? renderer->voxelSpecularRoughness() : ssr.max_roughness, + .reflection_steps = ssr.max_steps, + .reflection_thickness = ssr.thickness, + .sun_reach = static_cast(renderer->voxelSunReach()), + // Blending needs far to near and the depth writing passes reject the most early near to far + .reverse = lit ? 0u : 1u, + .count = count, + .nearest_valid = m_nearest_glass_valid ? 1u : 0u, + .cost_view = renderer->glassCostView() ? 1u : 0u, }; - cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(GlassPush), &push); - cmd.draw(36, count, 0, 0); -} + auto run = std::span(m_glass_draws).subspan(first, count); + + // Far to near so the far outside bricks are the front of the run, and only with the opaque depth the shader rejects against + const float coarse = renderer->voxelGlassCoarseDistance(); + const VulkanPipeline* far = variant < glass_variant_debug ? &m_glass_far_pipelines[variant] : nullptr; + if (lit && coarse > 0.0f && m_backdrop_depth_valid && far != nullptr && far->isReady()) { + const auto near = std::ranges::find_if(run, [coarse](const GlassDraw& draw) { + return draw.inside || draw.distance_squared < coarse * coarse; + }); + const auto far_count = static_cast(near - run.begin()); + if (far_count > 0) { + push.inside = 0; + push.count = far_count; + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, far->getPipeline()); + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(GlassPush), &push); + cmd.draw(36, far_count, 0, 0); + push.first += far_count; + push.count = count - far_count; + run = run.subspan(far_count); + } + } + if (run.empty()) { + return; + } -auto VoxelPass::refractsGlass() const -> bool { - const auto* renderer = VulkanRenderer::instance; - if (m_glass_count == 0 || !m_glass_dual_source || renderer->voxelGlassRefraction() <= 0.0f || !m_bound_backdrop.allCurrent()) { - return false; + const bool any_inside = std::ranges::any_of(run, &GlassDraw::inside); + // Inside bricks hold the camera so they are the nearest of the run and blend last + for (uint32_t inside = 0; inside < 2; ++inside) { + if (inside == 1u && !any_inside) { + break; + } + push.inside = inside; + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines[inside].getPipeline()); + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(GlassPush), &push); + cmd.draw(36, static_cast(run.size()), 0, 0); } - // Draws are far to near and a brick centre sits up to a diagonal past its voxels - constexpr float k_brick_reach = 2.0f; - const float reach = renderer->voxelGlassRefractionDistance() + k_brick_reach; - return m_glass_draws.back().distance_squared <= reach * reach; } void VoxelPass::writeFreshRegions(uint32_t frame_index, const VoxelGpuStorage& storage) { @@ -1693,6 +1890,10 @@ void VoxelPass::createDenoise(const VulkanCore& core, vk::Format scene_format, v config.write_color_alpha = false; config.fragment_entry = "compositeMain"; config.blend_preset = VulkanPipeline::BlendPreset::additive; + // Denoised clipmap GI for SSAO written over the cleared target and not blended + config.extra_color_formats = {k_voxel_denoised_indirect_format}; + config.write_extra_color = true; + config.extra_blend_mask = 0u; m_denoise_composite_pipeline.rebuild(core, config); m_linear_sampler = vk::raii::Sampler(core.getDevice(), linearClampSamplerInfo()); @@ -1739,6 +1940,7 @@ void VoxelPass::bindDenoise(vk::CommandBuffer cmd, uint32_t frame_index, const V m_denoise_history[1][read].view(), m_denoise_history[0][m_denoise_parity].view(), m_denoise_history[1][m_denoise_parity].view(), + renderer->getSceneIndirectView(), }; // Safe since the fence of this slot was waited on @@ -1910,6 +2112,7 @@ void VoxelPass::recordGiGather(vk::CommandBuffer cmd, uint32_t frame_index, vk:: const LightingPushConstants push { .inverse_view_projection = glm::inverse(frame->frame_data.jittered_view_projection), .viewport = glm::vec4(static_cast(viewport.width), static_cast(viewport.height), 0.0f, 0.0f), + .reuse = glm::uvec4(m_denoise_active ? k_gi_denoise : 0u, 0u, 0u, 0u), }; const vk::PipelineLayout layout = *m_lighting_layout.getPipelineLayout(); cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, m_gi_gather_pipeline.getPipeline()); diff --git a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp index a0c2ab24e..ba9ab0e21 100644 --- a/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp +++ b/engine/src/toast/renderer/passes/geometry/voxel_pass.hpp @@ -97,8 +97,16 @@ class VoxelPass : public IRenderPass { float distance_squared = 0.0f; uint32_t instance = 0; uint32_t brick = 0; + /// The camera is within the near plane of the brick so it draws back faces with exact depth + bool inside = false; }; + /// NDC rect around every glass brick drawn this frame, empty when one crosses the near plane and could cover anything + [[nodiscard]] + auto glassScreenBounds() const -> std::optional { + return m_glass_screen_bounds; + } + /// Far to near in the order recordGlass() indexes them and empty when no glass draws this frame [[nodiscard]] auto glassDraws() const -> std::span { @@ -111,16 +119,14 @@ class VoxelPass : public IRenderPass { /// After every blended draw void recordGlassSurfaces(vk::CommandBuffer cmd, uint32_t frame_index); - void recordGlassMask(vk::CommandBuffer cmd, uint32_t frame_index); - - /// Whether the backdrop must be copied before glass draws - [[nodiscard]] - auto refractsGlass() const -> bool; - - void setBackdropCaptured(bool captured) noexcept { m_backdrop_captured = captured; } + /// Nearest glass surface into its own depth and the glass mask, before any blended draw + void recordGlassNearest(vk::CommandBuffer cmd, uint32_t frame_index); void setBackdropDepthValid(bool valid) noexcept { m_backdrop_depth_valid = valid; } + /// Whether the nearest glass depth was written this frame so blended glass lights only its front layer fully + void setNearestGlassValid(bool valid) noexcept { m_nearest_glass_valid = valid; } + /// After prepare() whether the lighting scope writes denoised terms [[nodiscard]] auto denoiseActive() const -> bool { @@ -161,7 +167,7 @@ class VoxelPass : public IRenderPass { static constexpr uint32_t k_max_instances = 4096; - static constexpr uint32_t k_max_glass_bricks = 16384; + static constexpr uint32_t k_max_glass_bricks = 65536; private: /// Throttles the over limit warning @@ -298,9 +304,13 @@ class VoxelPass : public IRenderPass { void createDescriptors(const VulkanCore& core, const ShaderReflection& reflection); void createLighting(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent); void createGlass(const VulkanCore& core, vk::Format scene_format, vk::Format depth_format, vk::Extent2D extent); - void recordGlassBricks( - vk::CommandBuffer cmd, uint32_t frame_index, const VulkanPipeline& pipeline, uint32_t first, uint32_t count - ); + enum class GlassStage : uint8_t { + blend, + surface, + nearest + }; + /// Front faced outside bricks then back faced inside bricks of the run + void recordGlassBricks(vk::CommandBuffer cmd, uint32_t frame_index, GlassStage stage, uint32_t first, uint32_t count); /// Sorts the glass bricks of the instances written this frame far to near into the glass buffer void prepareGlass(uint32_t frame_index, const VoxelGpuStorage& storage, std::span instances); @@ -392,13 +402,12 @@ class VoxelPass : public IRenderPass { VulkanPipeline m_marched_composite_pipeline; bool m_spatial_active = false; bool m_scene_glass = false; - bool m_backdrop_captured = false; bool m_backdrop_depth_valid = false; - bool m_glass_dual_source = false; + bool m_nearest_glass_valid = false; vk::raii::Sampler m_backdrop_sampler = nullptr; vk::raii::Sampler m_backdrop_depth_sampler = nullptr; - /// Backdrop colour and depth each glass set was written with - DescriptorCache> m_bound_backdrop; + /// Backdrop colour and depth, the nearest glass depth, normal and motion and the glass mask each glass set was written with + DescriptorCache> m_bound_backdrop; /// The push the lighting draw used so the spatial draw matches it LightingPushConstants m_lighting_push; @@ -419,7 +428,7 @@ class VoxelPass : public IRenderPass { /// rgb filtered term a linear depth it was written at static constexpr vk::Format k_denoise_history_format = vk::Format::eR16G16B16A16Sfloat; /// Bindings of voxel_denoise.slang in order - static constexpr size_t k_denoise_bindings = 10; + static constexpr size_t k_denoise_bindings = 11; /// Change regions of a newly published storage that voxel.slang marks reactive void writeFreshRegions(uint32_t frame_index, const VoxelGpuStorage& storage); @@ -447,22 +456,42 @@ class VoxelPass : public IRenderPass { bool m_ambient_rays = false; bool m_denoise_active = false; - /// Mirrors voxel_glass.slang GlassPush /// Mirrors voxel_glass.slang GlassPush struct GlassPush { uint32_t first = 0; - /// 0 leaves the backdrop unread - float refraction = 0.0f; - float refraction_distance = 0.0f; - uint32_t refraction_voxels = 0; uint32_t lit_surfaces = 0; uint32_t depth_test = 0; + float reflection_reach = 0.0f; + float reflection_roughness = 0.0f; + uint32_t reflection_steps = 0; + float reflection_thickness = 0.0f; + float sun_reach = 0.0f; + uint32_t inside = 0; + uint32_t reverse = 0; + uint32_t count = 0; + uint32_t nearest_valid = 0; + uint32_t cost_view = 0; + }; + + /// Blended glass pipelines specialized by voxel_glass.slang kSpecReflection, the index matching kReflection*, then one with + /// the debug views for render modes other than 0 + enum GlassVariant : uint8_t { + glass_variant_plain = 0, + glass_variant_traced = 1, + glass_variant_screen = 2, + glass_variant_debug = 3, + glass_variant_count = 4, }; ShaderLayout m_glass_layout; - VulkanPipeline m_glass_pipeline; - VulkanPipeline m_glass_surface_pipeline; - VulkanPipeline m_glass_mask_pipeline; + /// Each indexed by GlassDraw::inside and the blended ones by GlassVariant first + std::array, glass_variant_count> m_glass_pipelines; + std::array m_glass_surface_pipelines; + std::array m_glass_nearest_pipelines; + /// Fullscreen copy of the pre-pass surface in place of the surface brick walk + VulkanPipeline m_glass_surface_copy_pipeline; + /// Outside bricks past VulkanRenderer::voxelGlassCoarseDistance at 2x2, only built with a pipeline shading rate + std::array m_glass_far_pipelines; SceneDescriptorSets m_glass_scene_sets; std::vector m_glass_sets; /// Instance index and brick grid index per drawn glass brick @@ -471,6 +500,10 @@ class VoxelPass : public IRenderPass { uint32_t m_glass_count = 0; /// Throttles the over limit warning std::chrono::steady_clock::time_point m_last_glass_warning; + /// Hash of what built m_glass_draws, empty when it must rebuild + std::optional m_glass_key; + /// Min xy max xy in NDC + std::optional m_glass_screen_bounds; }; } diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp index d2ae36dc9..95795d8e0 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.cpp @@ -13,6 +13,8 @@ #include "toast/renderer/voxel/voxel_trace_scene.hpp" #include "toast/renderer/vulkan_renderer.hpp" +#include +#include #include namespace renderer { @@ -65,6 +67,7 @@ constexpr uint32_t k_bounce_header = 4; /// Mirrors gi_clip_bounce bounceMain numthreads constexpr uint32_t k_bounce_group = 64; constexpr uint32_t k_inject_period = 8; +constexpr uint32_t k_near_bounce_period = 2; /// Mirrors gi_clip_fill numthreads constexpr int k_group = 4; @@ -100,6 +103,49 @@ struct FillPush { glm::ivec4 box_size {0}; }; +auto cellCount(const gi_clip::Box& box) -> int64_t { + const glm::i64vec3 size(box.max - box.min); + return size.x * size.y * size.z; +} + +/// Folds @p box into the first box where the union costs no more than both apart so overlaps fill once +void mergeInto(std::vector& boxes, const gi_clip::Box& box) { + for (gi_clip::Box& other : boxes) { + const gi_clip::Box both {.min = glm::min(other.min, box.min), .max = glm::max(other.max, box.max)}; + if (cellCount(both) <= cellCount(other) + cellCount(box)) { + other = both; + return; + } + } + boxes.push_back(box); +} + +/// Moves up to @p budget cells from the front of @p pending into @p out, splitting the last box into z layers +void takeBudget(std::vector& pending, int64_t budget, std::vector& out) { + size_t taken = 0; + for (; taken < pending.size() && budget > 0; ++taken) { + gi_clip::Box& box = pending[taken]; + const int64_t cells = cellCount(box); + if (cells <= budget) { + out.push_back(box); + budget -= cells; + continue; + } + // At least one layer so a box wider than the budget still progresses + const glm::i64vec3 size(box.max - box.min); + const int layers = static_cast(std::max(budget / (size.x * size.y), 1)); + gi_clip::Box slab = box; + slab.max.z = std::min(box.min.z + layers, box.max.z); + out.push_back(slab); + box.min.z = slab.max.z; + if (gi_clip::empty(box)) { + ++taken; + } + break; + } + pending.erase(pending.begin(), pending.begin() + static_cast(taken)); +} + } GiClipmapPass::GiClipmapPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent) @@ -589,36 +635,109 @@ void GiClipmapPass::createLevels(uint32_t resolution, uint32_t levels) { } void GiClipmapPass::gatherBodies(const RenderFrame& frame) { - const auto add = [&](glm::vec3 low, glm::vec3 high) { - if (m_body_boxes.size() < 2 * k_max_body_boxes) { - m_body_boxes.push_back(low); - m_body_boxes.push_back(high); - return; - } - auto last = m_body_boxes.end() - 2; - last[0] = glm::min(last[0], low); - last[1] = glm::max(last[1], high); + const auto sphere = [&](const glm::vec4& bounds) { + addDirtyBox(m_body_boxes, k_max_body_boxes, glm::vec3(bounds) - bounds.w, glm::vec3(bounds) + bounds.w); }; - const auto sphere = [&](const glm::vec4& bounds) { add(glm::vec3(bounds) - bounds.w, glm::vec3(bounds) + bounds.w); }; - m_bodies_next.clear(); + // Settled bodies still jitter so motion is measured against the last fill and only a real move refills + const float threshold = 0.25f * m_cell; + const auto motion = [](const Body& from, const Body& to) { + const glm::mat3 change = glm::mat3(to.model) - glm::mat3(from.model); + const float spread = + std::sqrt(glm::dot(change[0], change[0]) + glm::dot(change[1], change[1]) + glm::dot(change[2], change[2])); + const float scale = std::max(glm::length(glm::vec3(to.model[0])), 1e-6f); + return glm::distance(glm::vec3(from.bounds), glm::vec3(to.bounds)) + (spread * to.bounds.w / scale); + }; + + // Updated in place so a steady scene allocates nothing + const uint64_t gather = ++m_body_gather; + size_t seen = 0; for (const auto& proxy : frame.voxel_instances) { const Body body {.model = proxy.model, .bounds = glm::vec4(proxy.bounds_center, proxy.bounds_radius)}; - m_bodies_next.emplace(proxy.node_rid, body); - const auto found = m_bodies.find(proxy.node_rid); - if (found == m_bodies.end()) { + auto [found, inserted] = m_bodies.try_emplace(proxy.node_rid); + TrackedBody& tracked = found->second; + if (inserted) { + ++seen; sphere(body.bounds); - } else if (found->second.model != body.model) { - sphere(found->second.bounds); + tracked = TrackedBody {.filled = body, .seen = body, .gather = gather}; + continue; + } + if (tracked.gather == gather) { + continue; + } + ++seen; + tracked.gather = gather; + const bool drifted = tracked.filled.model != body.model && motion(tracked.filled, body) >= threshold; + // A fragment in flight refills once it lands, or every few frames if it never stops, instead of every frame + const bool flying = tracked.seen.model != body.model && motion(tracked.seen, body) >= threshold; + tracked.seen = body; + if (!drifted) { + tracked.flying = 0; + } else if (flying && ++tracked.flying < k_flying_refill_frames) { + // Waits with the old fill in place + } else { + sphere(tracked.filled.bounds); sphere(body.bounds); + tracked.filled = body; + tracked.flying = 0; } } - for (const auto& [rid, body] : m_bodies) { - if (!m_bodies_next.contains(rid)) { - sphere(body.bounds); + // Only walks the map when a body left + if (m_bodies.size() > seen) { + std::erase_if(m_bodies, [&](const auto& item) { + if (item.second.gather == gather) { + return false; + } + sphere(item.second.filled.bounds); + return true; + }); + } +} + +auto GiClipmapPass::gatherLightChanges(const RenderFrame& frame, std::vector& boxes) -> bool { + const FrameUBO& data = frame.frame_data; + const uint32_t suns = std::min(data.directional_light_count_pad.x, k_max_directional_lights); + bool suns_changed = suns != m_last_sun_count; + for (uint32_t i = 0; i < suns && !suns_changed; ++i) { + const DirectionalLightData& now = data.directional_lights[i]; + const DirectionalLightData& was = m_last_suns[i]; + suns_changed = now.direction != was.direction || now.color_intensity != was.color_intensity; + } + m_last_sun_count = suns; + m_last_suns = data.directional_lights; + + // World space fields only since the view space ones change with the camera and direction_pad.w is the shadow layer + const auto same = [](const GpuLight& a, const GpuLight& b) { + return a.world_pos_range == b.world_pos_range && a.color_intensity == b.color_intensity && + glm::vec3(a.direction_pad) == glm::vec3(b.direction_pad) && a.cone_angles == b.cone_angles && a.shape == b.shape; + }; + const auto sphere = [&](const GpuLight& light) { + const glm::vec3 centre(light.world_pos_range); + boxes.push_back(centre - light.world_pos_range.w); + boxes.push_back(centre + light.world_pos_range.w); + }; + const size_t count = std::min(frame.lights.size(), k_inject_lights); + for (size_t i = 0; i < std::max(count, m_last_lights.size()); ++i) { + const GpuLight* now = i < count ? &frame.lights[i] : nullptr; + const GpuLight* was = i < m_last_lights.size() ? &m_last_lights[i] : nullptr; + if (now != nullptr && was != nullptr && same(*now, *was)) { + continue; + } + if (was != nullptr) { + sphere(*was); + } + if (now != nullptr) { + sphere(*now); } } - std::swap(m_bodies, m_bodies_next); + m_last_lights.assign(frame.lights.begin(), frame.lights.begin() + static_cast(count)); + + // A reordered list or many moving lights cost more as boxes than one relight + if (boxes.size() > 2 * k_max_light_boxes) { + boxes.clear(); + return true; + } + return suns_changed; } auto GiClipmapPass::ambientViews() const -> std::array { @@ -673,6 +792,13 @@ void GiClipmapPass::unpublish(vk::CommandBuffer cmd) { m_published_valid = false; } +#if defined(TOAST_DEV_TOOLS) +auto GiClipmapPass::stats() const -> Stats { + std::scoped_lock lock(m_stats_mutex); + return m_stats; +} +#endif + void GiClipmapPass::markFull() { for (Level& level : m_levels) { level.needs_full = true; @@ -702,7 +828,7 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag gatherBodies(*frame); // Bodies are tracked above against the last fill so only edits and new bodies come from here - m_dirty_boxes.gather(*frame, std::numeric_limits::max()); + m_dirty_boxes.gather(*frame, std::nullopt); GiDirtyBoxes::Counts counts; const bool known = m_dirty_boxes.take(counts); @@ -752,8 +878,8 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag } // Before the fill so the clipmap is still the one lighting read last frame and its published frame addresses it - const int bounce_slab = std::max(static_cast(resolution) / static_cast(k_inject_period), 1); - const int bounce_phase = static_cast(m_frame % k_inject_period); + // The finest level bounces more often since it is what the camera sees up close and each bounce waits a full round + const auto bounce_period = [](uint32_t level) { return static_cast(level == 0 ? k_near_bounce_period : k_inject_period); }; if (m_published_valid && m_bounce_pipeline.isReady() && m_bounce_list_pipeline.isReady() && !m_bounce_scene_sets.empty() && !m_levels[0].needs_full) { const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "GI clip bounce"); @@ -776,10 +902,13 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag const int bounce_side = static_cast(resolution); for (uint32_t i = 0; i < level_count; ++i) { const glm::ivec3 origin = m_levels[i].origin; + const int period = bounce_period(i); + const int bounce_slab = std::max(bounce_side / period, 1); + const int bounce_phase = static_cast(m_frame % static_cast(period)); glm::ivec3 low = origin; glm::ivec3 size(bounce_side); low.z = origin.z + (bounce_phase * bounce_slab); - size.z = bounce_phase + 1 == static_cast(k_inject_period) ? (origin.z + bounce_side) - low.z : bounce_slab; + size.z = bounce_phase + 1 == period ? (origin.z + bounce_side) - low.z : bounce_slab; cmd.bindDescriptorSets( vk::PipelineBindPoint::eCompute, layout, @@ -810,11 +939,20 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag const glm::vec3 camera = frame->frame_data.camera_position; FrameData data { .inverse_view_projection = glm::inverse(frame->frame_data.view_projection), - .camera = glm::vec4(camera, 0.0f), + .camera = glm::vec4(camera, std::max(settings.intensity.load(relaxed), 0.0f)), .size = glm::uvec4(resolution, level_count, 1u, m_tail), }; const int side = static_cast(resolution); +#if defined(TOAST_DEV_TOOLS) + Stats stats { + .levels = level_count, + .edits = counts.edits, + .edit_boxes = static_cast(m_dirty_boxes.boxes().size() / 2), + .body_boxes = static_cast(m_body_boxes.size() / 2), + .history_lost = !known, + }; +#endif std::vector dirty = std::move(m_body_boxes); m_body_boxes.clear(); dirty.insert(dirty.end(), m_dirty_boxes.boxes().begin(), m_dirty_boxes.boxes().end()); @@ -831,23 +969,50 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag boxes[i].push_back({.min = origin, .max = origin + side}); whole[i] = true; scrolled_boxes[i] = 1; + level.pending.clear(); } else { std::array slabs; const uint32_t count = gi_clip::scrolled(level.origin, origin, side, slabs); boxes[i].assign(slabs.begin(), slabs.begin() + count); scrolled_boxes[i] = count; + // Queued cells that scrolled out are gone and the ones that scrolled in come with the slabs + std::erase_if(level.pending, [&](gi_clip::Box& box) { + box.min = glm::max(box.min, origin); + box.max = glm::min(box.max, origin + side); + return gi_clip::empty(box); + }); for (size_t b = 0; b + 1 < dirty.size(); b += 2) { const gi_clip::Box box = gi_clip::cells(dirty[b], dirty[b + 1], level_cell, origin, side); if (!gi_clip::empty(box)) { - boxes[i].push_back(box); + mergeInto(level.pending, box); } } + takeBudget(level.pending, k_fill_budget_cells, boxes[i]); } level.origin = origin; level.needs_full = false; any = any || !boxes[i].empty(); +#if defined(TOAST_DEV_TOOLS) + stats.boxes[i] = static_cast(boxes[i].size()); + stats.whole[i] = whole[i]; + for (const gi_clip::Box& box : boxes[i]) { + const glm::i64vec3 size(box.max - box.min); + const uint64_t box_cells = static_cast(size.x * size.y * size.z); + stats.cells[i] += box_cells; + stats.largest[i] = std::max(stats.largest[i], box_cells); + } + for (const gi_clip::Box& box : level.pending) { + stats.queued[i] += static_cast(cellCount(box)); + } +#endif } m_dirty_boxes.clear(); +#if defined(TOAST_DEV_TOOLS) + { + std::scoped_lock lock(m_stats_mutex); + m_stats = stats; + } +#endif const auto& allocation = m_frame_data[frame_index].getAllocation(); std::memcpy(allocation.getInfo().pMappedData, &data, sizeof(data)); @@ -902,6 +1067,9 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag } } + std::vector light_boxes; + const bool relight_near = gatherLightChanges(*frame, light_boxes); + std::array, k_max_levels> injected; if (m_inject_pipeline.isReady() && !m_inject_scene_sets.empty()) { const GpuScope scope(renderer->gpuTimer(), frame_index, cmd, "GI clip inject"); @@ -935,13 +1103,20 @@ auto GiClipmapPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag std::vector& inject = injected[i]; const glm::ivec3 origin = m_levels[i].origin; const gi_clip::Box level_box {.min = origin, .max = origin + side}; - if (whole[i]) { + if (whole[i] || (relight_near && i < k_relight_levels)) { inject.push_back(level_box); } else { // One cell wider since a changed cell changes which faces of its neighbours are exposed for (const gi_clip::Box& box : boxes[i]) { inject.push_back({.min = glm::max(box.min - 1, level_box.min), .max = glm::min(box.max + 1, level_box.max)}); } + // A light reaching more cells than the fill budget leaves this level to the round robin and the downsample + for (size_t b = 0; b + 1 < light_boxes.size(); b += 2) { + const gi_clip::Box box = gi_clip::cells(light_boxes[b], light_boxes[b + 1], data.levels[i].w, origin, side); + if (!gi_clip::empty(box) && cellCount(box) <= k_fill_budget_cells) { + inject.push_back(box); + } + } // The rest relights round robin so a far occluder change still arrives gi_clip::Box round = level_box; round.min.z = origin.z + (phase * slab); @@ -1144,9 +1319,7 @@ auto GiClipmapPass::recordDebug( } barriers.flush(cmd); - const std::array wanted { - source_view, **level.material_view, **level.emission_view, **level.faces[0].sampled_view - }; + const std::array wanted {source_view, **level.material_view, **level.emission_view, **level.faces[0].sampled_view}; if (m_debug_bound.update(frame_index, wanted)) { constexpr auto sampled = vk::DescriptorType::eCombinedImageSampler; constexpr auto read = vk::ImageLayout::eShaderReadOnlyOptimal; diff --git a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp index 17e6157b5..a615e6cd6 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/gi_clipmap_pass.hpp @@ -7,6 +7,8 @@ #include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/gpu_sync.hpp" #include "toast/renderer/core/vulkan_common.hpp" +#include "toast/renderer/gpu_types.hpp" +#include "toast/renderer/lighting/gi_clip_math.hpp" #include "toast/renderer/lighting/gi_dirty_boxes.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" #include "toast/renderer/resources/post_process_target.hpp" @@ -17,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -34,6 +37,27 @@ class GiClipmapPass : public IPostProcessPass { /// Mirrors gi_clip_common kGiClipFaces static constexpr uint32_t k_faces = 6; +#if defined(TOAST_DEV_TOOLS) + /// What the last fill refilled and why + struct Stats { + uint32_t levels = 0; + uint32_t edits = 0; + /// Of GiDirtyBoxes::k_max_boxes where a full list merges the rest into its last box + uint32_t edit_boxes = 0; + uint32_t body_boxes = 0; + bool history_lost = false; + std::array boxes {}; + std::array cells {}; + std::array largest {}; + /// Cells left over for later frames + std::array queued {}; + std::array whole {}; + }; + + [[nodiscard]] + auto stats() const -> Stats; +#endif + GiClipmapPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D extent); [[nodiscard]] @@ -103,14 +127,22 @@ class GiClipmapPass : public IPostProcessPass { std::array ambient; glm::ivec3 origin {0}; bool needs_full = true; + /// Dirty cells past the fill budget that later frames refill first + std::vector pending; }; + /// Dirty cells refilled per level each frame on top of the scroll so a blast spreads over frames + static constexpr int64_t k_fill_budget_cells = 16384; + auto createPipelines(const VulkanCore& core) -> bool; /// Waits for the device so no frame in flight still reads the old images void createLevels(uint32_t resolution, uint32_t levels); void markFull(); void unpublish(vk::CommandBuffer cmd); void gatherBodies(const RenderFrame& frame); + /// Range boxes of local lights that changed as low then high into @p boxes + /// @returns true when a sun changed or too many lights did so the near levels relight whole + auto gatherLightChanges(const RenderFrame& frame, std::vector& boxes) -> bool; auto recordDebug(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView source_view, uint32_t level, uint32_t mode) -> vk::ImageView; @@ -176,10 +208,35 @@ class GiClipmapPass : public IPostProcessPass { glm::vec4 bounds {0.0f}; }; + struct TrackedBody { + /// Where the clipmap last saw it + Body filled; + /// Where it was last frame + Body seen; + /// Frames it has moved since the last fill + uint32_t flying = 0; + /// Last gather that saw it so leavers are found without rebuilding the map + uint64_t gather = 0; + }; + static constexpr size_t k_max_body_boxes = 256; - std::unordered_map m_bodies; - std::unordered_map m_bodies_next; + static constexpr uint32_t k_flying_refill_frames = 8; + std::unordered_map m_bodies; + uint64_t m_body_gather = 0; std::vector m_body_boxes; + + /// Levels a sun change relights at once and coarser ones follow the round robin and the downsample + static constexpr uint32_t k_relight_levels = 2; + static constexpr size_t k_inject_lights = 64; + static constexpr size_t k_max_light_boxes = 16; + std::array m_last_suns {}; + uint32_t m_last_sun_count = 0; + std::vector m_last_lights; + +#if defined(TOAST_DEV_TOOLS) + mutable std::mutex m_stats_mutex; + Stats m_stats; +#endif }; } diff --git a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp index c5d8ef0c9..d9ee1a044 100644 --- a/engine/src/toast/renderer/passes/lighting/gi_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/gi_pass.cpp @@ -1095,7 +1095,7 @@ auto GiPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView s std::max(settings.max_ray_radiance.load(std::memory_order_relaxed), 0.01f), history >= 1.0f ? 0.0f : 2.0f / history, history_known ? 1.0f - (history / 8.0f) : 0.0f, - 0.0f + std::max(settings.intensity.load(std::memory_order_relaxed), 0.0f) ), }; for (uint32_t i = 0; i < k_max_cascades; ++i) { diff --git a/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp b/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp index 9f2e086f2..fb2cc28d4 100644 --- a/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/shadow_pass.cpp @@ -8,6 +8,7 @@ #include "toast/renderer/core/descriptor_writer.hpp" #include "toast/renderer/lighting/frustum.hpp" +#include "toast/renderer/passes/geometry/debris_pass.hpp" #include "toast/renderer/resources/vulkan_mesh.hpp" #include "toast/renderer/shaders/shader_cache.hpp" #include "toast/renderer/voxel/voxel_gpu_storage.hpp" @@ -36,6 +37,9 @@ auto cornerDrift(const glm::mat4& from, const glm::mat4& to, const glm::vec3& ex return drift; } +/// Mesh shader multiview limits the highest view bit so the second half gets its own view at mask 0x7 +constexpr uint32_t k_half_cube_faces = shadows::k_cube_faces / 2; + /// Mirrors kTaskGroupsPerCell in voxel_dda.slang constexpr uint32_t k_task_groups_per_cell = 2; @@ -146,6 +150,7 @@ ShadowPass::ShadowPass(const VulkanCore& core) : m_core(&core) { constexpr std::array view_masks { 1u, (1u << shadows::k_cube_faces) - 1u, + (1u << k_half_cube_faces) - 1u, }; static_assert(view_masks.size() == std::tuple_size_v, "one pipeline set per mask"); @@ -165,6 +170,7 @@ ShadowPass::ShadowPass(const VulkanCore& core) : m_core(&core) { createResources(core); createVoxelResources(core); + createDebrisResources(core); TOAST_INFO( "Render", @@ -250,6 +256,15 @@ void ShadowPass::createShadowMap( group.view.emplace(device, view_ci); setDebugName(core, **group.view, std::format("{} GroupView[{}..{}]", debug_name, base_layer, base_layer + count - 1)); + const uint32_t mesh_views = core.meshMultiviewViews(); + if (count == shadows::k_cube_faces && mesh_views >= k_half_cube_faces && mesh_views < count) { + for (uint32_t half = 0; half < group.halves.size(); ++half) { + view_ci.subresourceRange = shadowLayerRange(base_layer + (half * k_half_cube_faces), k_half_cube_faces); + group.halves[half].emplace(device, view_ci); + setDebugName(core, **group.halves[half], std::format("{} GroupView[{}] Half[{}]", debug_name, base_layer, half)); + } + } + map.groups.push_back(std::move(group)); base_layer += count; } @@ -552,6 +567,47 @@ void ShadowPass::createVoxelMeshResources(const VulkanCore& core) { ); } +void ShadowPass::createDebrisResources(const VulkanCore& core) { + ZoneScoped; + static_assert(sizeof(DebrisShadowPush) == 16, "DebrisShadowPush is mirrored by debris_shadow.slang"); + if (m_voxel_shadow_sets.empty()) { + return; + } + + const auto uid = assets::resolveURI("core://shaders/debris_shadow.slang"); + const auto shader = uid.has_value() ? ShaderCache::get().acquire(*uid) : nullptr; + if (!shader) { + TOAST_WARN("Render", "ShadowPass shader core://shaders/debris_shadow.slang unavailable, debris will not cast shadows"); + return; + } + m_debris_layout.rebuild(core, shader->reflection, "ShadowPass Debris"); + + VulkanPipeline::Config config; + config.pipeline_type = VulkanPipeline::PipelineType::graphics; + config.depth_only = true; + config.depth_format = m_format; + config.extent = vk::Extent2D {shadows::cascadeResolution(), shadows::cascadeResolution()}; + config.shader_spirv = shader->spirv; + config.pipeline_layout = *m_debris_layout.getPipelineLayout(); + config.vertex_bindings = {}; + config.vertex_attributes = {}; + config.topology = vk::PrimitiveTopology::eTriangleList; + config.depth_test = true; + config.depth_write = true; + config.depth_compare = vk::CompareOp::eLess; + config.depth_bias_constant = k_caster_bias_constant; + config.depth_bias_slope = k_caster_bias_slope; + config.depth_clamp = core.isDepthClampSupported(); + config.cull_mode = vk::CullModeFlagBits::eNone; + + for (size_t mask_index = 0; mask_index < m_debris_pipelines.size(); ++mask_index) { + VulkanPipeline::Config variant = config; + variant.view_mask = m_pipeline_sets[mask_index].view_mask; + variant.debug_name = std::format("ShadowPass Debris [viewMask {:#x}]", variant.view_mask); + m_debris_pipelines[mask_index].rebuild(core, variant); + } +} + auto ShadowPass::voxelMeshPipelineFor(uint32_t view_mask) const -> const VulkanPipeline* { for (size_t mask_index = 0; mask_index < m_voxel_mesh_pipelines.size(); ++mask_index) { if (m_voxel_pipeline_sets[mask_index].view_mask == view_mask && m_voxel_mesh_pipelines[mask_index].isReady()) { @@ -598,7 +654,6 @@ auto ShadowPass::prepareVoxels(uint32_t frame_index) -> uint32_t { ); } } - ++m_caster_frame; const float tolerance = shadows::casterTolerance(); m_caster_models.resize(count); m_caster_moving.resize(count); @@ -629,6 +684,49 @@ auto ShadowPass::prepareVoxels(uint32_t frame_index) -> uint32_t { return count; } +void ShadowPass::prepareMeshes(uint32_t frame_index) { + ZoneScoped; + const auto* frame = VulkanRenderer::instance->renderingFrame(); + const auto& proxies = frame->mesh_instances; + const size_t count = std::min(proxies.size(), frame->shadow_instance_data.size()); + const float tolerance = shadows::casterTolerance(); + const bool posed_buffer = VulkanRenderer::instance->getPosedVertexBuffer(frame_index) != nullptr; + m_mesh_models.resize(count); + m_mesh_moving.resize(count); + for (size_t i = 0; i < count; ++i) { + const auto& proxy = proxies[i]; + const uint64_t key = + proxy.node_rid ^ (static_cast(reinterpret_cast(proxy.mesh)) * 0x9E3779B97F4A7C15ull); + auto [it, inserted] = m_settled_meshes.try_emplace(key); + SettledMesh& settled = it->second; + + // Center travel plus how far the basis change swings the bounds edge + float drift = glm::distance(settled.bounds_center, proxy.bounds_center); + for (int column = 0; column < 3; ++column) { + const float length = glm::length(glm::vec3(proxy.model[column])); + drift += length > 0.0f ? proxy.bounds_radius * glm::length(glm::vec3(proxy.model[column] - settled.model[column])) / length + : 0.0f; + } + if (inserted || drift > tolerance) { + settled.model = proxy.model; + settled.bounds_center = proxy.bounds_center; + settled.moved_frame = m_caster_frame; + } + settled.seen_frame = m_caster_frame; + m_mesh_models[i] = settled.model; + + // A posed mesh changes shape without moving + const bool posed = posed_buffer && proxy.posed_vertex_offset != MeshInstanceProxy::k_no_posed_vertices; + m_mesh_moving[i] = posed || m_caster_frame - settled.moved_frame < k_caster_settle_frames ? 1u : 0u; + } + + if (m_caster_frame % k_caster_settle_frames == 0) { + std::erase_if(m_settled_meshes, [&](const auto& entry) { + return m_caster_frame - entry.second.seen_frame > k_caster_settle_frames; + }); + } +} + auto ShadowPass::voxelPipelineSetFor(uint32_t view_mask) const -> const VoxelPipelineSet* { if (!m_voxels_ready) { return nullptr; @@ -736,6 +834,25 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta // Without the cache every voxel caster draws with the moving ones into each slot const bool static_cache = shadows::staticCasterCache(); const auto voxel_moving = [&](size_t index) { return !static_cache || m_caster_moving[index] != 0; }; + const auto mesh_moving = [&](size_t index) { + return !static_cache || index >= m_mesh_moving.size() || m_mesh_moving[index] != 0; + }; + + /// Resting meshes reaching the group, summed like voxel_signature + const auto resting_mesh_signature = [&](const LayerGroup& group) -> uint64_t { + uint64_t sum = 0; + for (size_t index = 0; index < proxies.size() && index < instance_count; ++index) { + if (mesh_moving(index) || !eligible(group, index)) { + continue; + } + ShadowSignature caster; + caster.add(proxies[index].node_rid); + caster.add(static_cast(reinterpret_cast(proxies[index].mesh))); + caster.add(m_mesh_models[index]); + sum += caster.value; + } + return sum; + }; // Summed since voxel proxies are sorted by camera distance and a static light must not re-render as the camera moves const auto voxel_signature = [&](const LayerGroup& group, bool moving, std::vector* casters) -> uint64_t { @@ -765,14 +882,29 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta return signature.value; }; + const auto* debris_pass = VulkanRenderer::instance->getDebrisPass(); + const DebrisPass::ShadowDraw debris = + debris_pass != nullptr && !m_voxel_shadow_sets.empty() ? debris_pass->shadowDraw(frame_index) : DebrisPass::ShadowDraw {}; + const auto debris_reaches = [&](const LayerGroup& group) { + return debris.args && debris.bounds_radius >= 0.0f && reaches(group, debris.bounds_center, debris.bounds_radius); + }; + /// Empty while a posed mesh is eligible since its pose changes without its transform const auto moving_signature_of = [&](const LayerGroup& group, const LayerGroup& static_group) -> std::optional { ShadowSignature signature; + // Leaving or entering the reach changes the signature too so the old debris shadow clears once + if (debris_reaches(group)) { + if (!debris.signature.has_value()) { + return std::nullopt; + } + signature.add(*debris.signature); + } signature.add(*static_group.signature); signature.add(*static_group.caster_signature); signature.add(static_group.revision); + // Resting meshes are in the static copy which the caster signature already covers for (size_t index = 0; index < proxies.size() && index < instance_count; ++index) { - if (!eligible(group, index)) { + if (!mesh_moving(index) || !eligible(group, index)) { continue; } const auto& proxy = proxies[index]; @@ -784,6 +916,7 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta } uint64_t voxel_casters = 0; + m_voxel_eligible.clear(); for (size_t index = 0; index < m_voxel_instance_count; ++index) { if (!voxel_eligible(group, index)) { continue; @@ -847,7 +980,7 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta m_voxel_eligible.clear(); const uint64_t view_signature = view_signature_of(group); - const uint64_t caster_signature = voxel_signature(group, false, &m_voxel_eligible); + const uint64_t caster_signature = voxel_signature(group, false, &m_voxel_eligible) + resting_mesh_signature(group); const bool has_voxels = !m_voxel_eligible.empty(); if (static_group.signature != view_signature) { ++m_stats.static_views; @@ -894,9 +1027,30 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta cmd.setScissor(0, std::array {vk::Rect2D({0, 0}, vk::Extent2D {view_resolution, view_resolution})}); }; - const auto begin_group = [&](const ShadowMap& target, const LayerGroup& group, vk::AttachmentLoadOp load) { + /// A rendering scope over all or part of a group with views offset from the group base + struct Scope { + vk::ImageView view; + uint32_t view_mask = 1; + uint32_t view_offset = 0; + uint32_t view_count = 1; + }; + + // Halves only pay off when voxels mesh, otherwise the meshes would draw twice for nothing + const bool split_cubes = m_draw_mesh_tasks != nullptr && shadows::voxelMeshShadows(); + const auto scopes_of = [&](const LayerGroup& group) -> std::pair, uint32_t> { + if (split_cubes && group.halves[0].has_value() && group.halves[1].has_value()) { + return { + {Scope {**group.halves[0], (1u << k_half_cube_faces) - 1u, 0, k_half_cube_faces}, + Scope {**group.halves[1], (1u << k_half_cube_faces) - 1u, k_half_cube_faces, k_half_cube_faces}}, + 2 + }; + } + return {{Scope {**group.view, group.view_mask, 0, group.layer_count}}, 1}; + }; + + const auto begin_scope = [&](const ShadowMap& target, const Scope& scope, vk::AttachmentLoadOp load) { vk::RenderingAttachmentInfo depth_attachment {}; - depth_attachment.imageView = **group.view; + depth_attachment.imageView = scope.view; depth_attachment.imageLayout = vk::ImageLayout::eDepthAttachmentOptimal; depth_attachment.loadOp = load; depth_attachment.storeOp = vk::AttachmentStoreOp::eStore; @@ -906,17 +1060,18 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta rendering_info.renderArea = vk::Rect2D({0, 0}, vk::Extent2D {target.resolution, target.resolution}); // Ignored when viewMask is non zero rendering_info.layerCount = 1; - rendering_info.viewMask = group.view_mask; + rendering_info.viewMask = scope.view_mask; rendering_info.pDepthAttachment = &depth_attachment; cmd.beginRendering(rendering_info); ++m_stats.scopes; }; - const auto draw_meshes = [&](const LayerGroup& group, uint32_t view_index) { - const PipelineSet* pipelines = pipelineSetFor(group.view_mask); + const auto draw_meshes = [&](const LayerGroup& group, const Scope& scope, uint32_t view_index, bool moving) { + const PipelineSet* pipelines = pipelineSetFor(scope.view_mask); if (pipelines == nullptr || !pipelines->pipeline.isReady()) { return; } + const auto drawn = [&](size_t index) { return mesh_moving(index) == moving && eligible(group, index); }; cmd.bindDescriptorSets( vk::PipelineBindPoint::eGraphics, *m_shader_layout.getPipelineLayout(), @@ -928,7 +1083,7 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta constexpr uint32_t k_push_size = 2 * sizeof(uint32_t); for (size_t i = 0; i < proxies.size() && i < instance_count;) { - if (!eligible(group, i)) { + if (!drawn(i)) { ++i; continue; } @@ -938,7 +1093,7 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta size_t run = 1; if (!posed) { - while (i + run < proxies.size() && i + run < instance_count && eligible(group, i + run) && + while (i + run < proxies.size() && i + run < instance_count && drawn(i + run) && proxies[i + run].mesh == proxies[i].mesh && posed_offset_of(proxies[i + run]) == MeshInstanceProxy::k_no_posed_vertices) { ++run; @@ -947,7 +1102,7 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta const ShadowPushConstants push { .instance_base = static_cast(i), - .view_index = view_index, + .view_index = view_index + scope.view_offset, }; cmd.pushConstants(*m_shader_layout.getPipelineLayout(), vk::ShaderStageFlagBits::eAll, 0, k_push_size, &push); @@ -971,104 +1126,137 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta groups_x * coarse.y * coarse.z <= m_max_task_group_total; }; - const auto draw_voxels = [&](const LayerGroup& group, const ShadowView& view, uint32_t view_index, bool moving) { - const VoxelPipelineSet* voxel_pipelines = voxelPipelineSetFor(group.view_mask); - if (voxel_pipelines == nullptr || m_voxel_instance_count == 0) { - return; - } - const vk::PipelineLayout voxel_layout = *m_voxel_layout.getPipelineLayout(); - const vk::PipelineLayout mesh_layout = *m_voxel_mesh_layout.getPipelineLayout(); - const VulkanPipeline* mesh_pipeline = - m_draw_mesh_tasks != nullptr && shadows::voxelMeshShadows() ? voxelMeshPipelineFor(group.view_mask) : nullptr; - - const auto sets = std::array {*m_voxel_shadow_sets[frame_index], *m_voxel_storage_sets[frame_index]}; - - // Meshed first since their quads keep early depth for the marched volumes behind them - m_voxel_draw_order.clear(); - bool meshes_bound = false; - for (uint32_t index = 0; index < m_voxel_instance_count; ++index) { - if (voxel_moving(index) != moving || !voxel_eligible(group, index)) { - continue; - } - const auto& proxy = voxel_proxies[index]; - if (mesh_pipeline == nullptr || !meshes_volume(proxy)) { - m_voxel_draw_order.push_back(index); - continue; - } - - if (!meshes_bound) { - cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh_pipeline->getPipeline()); - cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh_layout, 0, sets, {}); - meshes_bound = true; + const auto draw_voxels = + [&](const LayerGroup& group, const Scope& scope, const ShadowView& view, uint32_t group_view_index, bool moving) { + const uint32_t view_index = group_view_index + scope.view_offset; + const VoxelPipelineSet* voxel_pipelines = voxelPipelineSetFor(scope.view_mask); + if (voxel_pipelines == nullptr || m_voxel_instance_count == 0) { + return; + } + const vk::PipelineLayout voxel_layout = *m_voxel_layout.getPipelineLayout(); + const vk::PipelineLayout mesh_layout = *m_voxel_mesh_layout.getPipelineLayout(); + const VulkanPipeline* mesh_pipeline = + m_draw_mesh_tasks != nullptr && shadows::voxelMeshShadows() ? voxelMeshPipelineFor(scope.view_mask) : nullptr; + + const auto sets = + std::array {*m_voxel_shadow_sets[frame_index], *m_voxel_storage_sets[frame_index]}; + + // Meshed first since their quads keep early depth for the marched volumes behind them + m_voxel_draw_order.clear(); + bool meshes_bound = false; + for (uint32_t index = 0; index < m_voxel_instance_count; ++index) { + if (voxel_moving(index) != moving || !voxel_eligible(group, index)) { + continue; + } + const auto& proxy = voxel_proxies[index]; + if (mesh_pipeline == nullptr || !meshes_volume(proxy)) { + m_voxel_draw_order.push_back(index); + continue; + } + + if (!meshes_bound) { + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, mesh_pipeline->getPipeline()); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, mesh_layout, 0, sets, {}); + meshes_bound = true; + } + const VoxelMeshShadowPush push { + .instance_index = index, + .view_index = view_index, + .view_count = scope.view_count, + .directional = directional ? 1u : 0u, + }; + cmd.pushConstants(mesh_layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(VoxelMeshShadowPush), &push); + const glm::uvec3 coarse = voxel::gpu::coarseDims(proxy.brick_dims); + m_draw_mesh_tasks(static_cast(cmd), coarse.x * k_task_groups_per_cell, coarse.y, coarse.z); + ++m_stats.draws; + ++m_stats.meshed_volumes; + } + if (m_voxel_draw_order.empty()) { + return; + } + + // Nearest to the light first by clip z which grows with distance under both projections + // Keys first so the sort does no matrix work per comparison + m_voxel_draw_keys.resize(m_voxel_instance_count); + for (const uint32_t index : m_voxel_draw_order) { + m_voxel_draw_keys[index] = (view.view_projection * glm::vec4(voxel_proxies[index].bounds_center, 1.0f)).z; + } + std::ranges::sort(m_voxel_draw_order, {}, [&](uint32_t index) { return m_voxel_draw_keys[index]; }); + + // A perspective near plane clips front faces so only exact back faces are safe and cascades clamp + const auto crosses_near_plane = [&](uint32_t index) { + if (directional && m_core->isDepthClampSupported()) { + return false; + } + const glm::vec3 extent = glm::vec3(voxel_proxies[index].brick_dims) * voxel::k_brick_size; + for (uint32_t i = 0; i < group.layer_count; ++i) { + const auto* member = layer_views[group.base_layer + i]; + if (member == nullptr) { + continue; + } + const glm::mat4 to_clip = member->view_projection * m_caster_models[index]; + for (uint32_t corner = 0; corner < 8; ++corner) { + const glm::vec3 local( + (corner & 1u) != 0 ? extent.x : 0.0f, (corner & 2u) != 0 ? extent.y : 0.0f, (corner & 4u) != 0 ? extent.z : 0.0f + ); + if ((to_clip * glm::vec4(local, 1.0f)).z < 0.0f) { + return true; + } + } + } + return false; + }; + + cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, voxel_layout, 0, sets, {}); + const VulkanPipeline* bound = nullptr; + for (const uint32_t index : m_voxel_draw_order) { + const auto& proxy = voxel_proxies[index]; + const bool inside = crosses_near_plane(index); + const bool cull_front = inside != proxy.mirrored; + const VulkanPipeline& pipeline = voxel_pipelines->pipelines[cull_front ? 1 : 0][inside ? 1 : 0]; + if (bound != &pipeline) { + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.getPipeline()); + bound = &pipeline; + } + + const VoxelShadowPush push { + .instance_index = index, + .view_index = view_index, + .constant_bias = m_voxel_constant_bias, + .directional = directional ? 1u : 0u, + }; + cmd.pushConstants(voxel_layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(VoxelShadowPush), &push); + cmd.draw(36, 1, 0, 0); + ++m_stats.draws; + ++m_stats.marched_volumes; + } + }; + + const auto draw_debris = [&](const LayerGroup& group, const Scope& scope, uint32_t view_index) { + const VulkanPipeline* pipeline = nullptr; + for (size_t mask_index = 0; mask_index < m_debris_pipelines.size(); ++mask_index) { + if (m_pipeline_sets[mask_index].view_mask == scope.view_mask && m_debris_pipelines[mask_index].isReady()) { + pipeline = &m_debris_pipelines[mask_index]; } - const VoxelMeshShadowPush push { - .instance_index = index, - .view_index = view_index, - .view_count = group.layer_count, - .directional = directional ? 1u : 0u, - }; - cmd.pushConstants(mesh_layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(VoxelMeshShadowPush), &push); - const glm::uvec3 coarse = voxel::gpu::coarseDims(proxy.brick_dims); - m_draw_mesh_tasks(static_cast(cmd), coarse.x * k_task_groups_per_cell, coarse.y, coarse.z); - ++m_stats.draws; - ++m_stats.meshed_volumes; } - if (m_voxel_draw_order.empty()) { + if (!debris_reaches(group) || pipeline == nullptr) { return; } - - // Nearest to the light first by clip z which grows with distance under both projections - std::ranges::sort(m_voxel_draw_order, {}, [&](uint32_t index) { - return (view.view_projection * glm::vec4(voxel_proxies[index].bounds_center, 1.0f)).z; - }); - - // A perspective near plane clips front faces so only exact back faces are safe and cascades clamp - const auto crosses_near_plane = [&](uint32_t index) { - if (directional && m_core->isDepthClampSupported()) { - return false; - } - const glm::vec3 extent = glm::vec3(voxel_proxies[index].brick_dims) * voxel::k_brick_size; - for (uint32_t i = 0; i < group.layer_count; ++i) { - const auto* member = layer_views[group.base_layer + i]; - if (member == nullptr) { - continue; - } - const glm::mat4 to_clip = member->view_projection * m_caster_models[index]; - for (uint32_t corner = 0; corner < 8; ++corner) { - const glm::vec3 local( - (corner & 1u) != 0 ? extent.x : 0.0f, (corner & 2u) != 0 ? extent.y : 0.0f, (corner & 4u) != 0 ? extent.z : 0.0f - ); - if ((to_clip * glm::vec4(local, 1.0f)).z < 0.0f) { - return true; - } - } - } - return false; + const vk::PipelineLayout layout = *m_debris_layout.getPipelineLayout(); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline->getPipeline()); + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, layout, 0, std::array {*m_voxel_shadow_sets[frame_index], debris.set}, {} + ); + const DebrisShadowPush push { + .extrapolation = debris.extrapolation, + .voxel_size = debris.voxel_size, + .list_capacity = debris.list_capacity, + .view_index = view_index + scope.view_offset, }; - - cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, voxel_layout, 0, sets, {}); - const VulkanPipeline* bound = nullptr; - for (const uint32_t index : m_voxel_draw_order) { - const auto& proxy = voxel_proxies[index]; - const bool inside = crosses_near_plane(index); - const bool cull_front = inside != proxy.mirrored; - const VulkanPipeline& pipeline = voxel_pipelines->pipelines[cull_front ? 1 : 0][inside ? 1 : 0]; - if (bound != &pipeline) { - cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.getPipeline()); - bound = &pipeline; - } - - const VoxelShadowPush push { - .instance_index = index, - .view_index = view_index, - .constant_bias = m_voxel_constant_bias, - .directional = directional ? 1u : 0u, - }; - cmd.pushConstants(voxel_layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(VoxelShadowPush), &push); - cmd.draw(36, 1, 0, 0); - ++m_stats.draws; - ++m_stats.marched_volumes; - } + cmd.pushConstants(layout, vk::ShaderStageFlagBits::eAll, 0, sizeof(DebrisShadowPush), &push); + // First command is the opaque run so glass debris casts no shadow + cmd.drawIndirect(debris.args, 0, 1, sizeof(vk::DrawIndirectCommand)); + ++m_stats.draws; }; if (any_static_render) { @@ -1079,10 +1267,15 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta } const auto& group = static_map.groups[g]; const auto& view = *layer_views[group.base_layer]; - begin_group(static_map, group, vk::AttachmentLoadOp::eClear); - bind_viewport(view, static_map.resolution); - draw_voxels(group, view, layer_view_indices[group.base_layer], false); - cmd.endRendering(); + const uint32_t view_index = layer_view_indices[group.base_layer]; + const auto [scopes, scope_count] = scopes_of(group); + for (uint32_t s = 0; s < scope_count; ++s) { + begin_scope(static_map, scopes[s], vk::AttachmentLoadOp::eClear); + bind_viewport(view, static_map.resolution); + draw_meshes(group, scopes[s], view_index, false); + draw_voxels(group, scopes[s], view, view_index, false); + cmd.endRendering(); + } } } @@ -1128,15 +1321,22 @@ void ShadowPass::recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& sta group.dirty = compose; group.signature = compose ? group_signatures[g] : std::nullopt; - begin_group(map, group, compose ? vk::AttachmentLoadOp::eLoad : vk::AttachmentLoadOp::eClear); - if (compose) { - const auto& view = *layer_views[group.base_layer]; - const uint32_t view_index = layer_view_indices[group.base_layer]; + if (!compose) { + begin_scope(map, Scope {**group.view, group.view_mask, 0, group.layer_count}, vk::AttachmentLoadOp::eClear); + cmd.endRendering(); + continue; + } + const auto& view = *layer_views[group.base_layer]; + const uint32_t view_index = layer_view_indices[group.base_layer]; + const auto [scopes, scope_count] = scopes_of(group); + for (uint32_t s = 0; s < scope_count; ++s) { + begin_scope(map, scopes[s], vk::AttachmentLoadOp::eLoad); bind_viewport(view, map.resolution); - draw_meshes(group, view_index); - draw_voxels(group, view, view_index, true); + draw_meshes(group, scopes[s], view_index, true); + draw_voxels(group, scopes[s], view, view_index, true); + draw_debris(group, scopes[s], view_index); + cmd.endRendering(); } - cmd.endRendering(); } // Bound in eShaderReadOnlyOptimal by the lighting descriptors @@ -1178,6 +1378,9 @@ void ShadowPass::recordPre(vk::CommandBuffer cmd, uint32_t frame_index, uint32_t } } + // Advances even without voxels so meshes settle + ++m_caster_frame; + prepareMeshes(frame_index); m_voxel_instance_count = prepareVoxels(frame_index); for (uint32_t index = 0; index < m_voxel_instance_count; ++index) { m_stats.moving_volumes += m_caster_moving[index]; diff --git a/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp b/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp index b425be1a1..8e09d7d71 100644 --- a/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/shadow_pass.hpp @@ -120,6 +120,14 @@ class ShadowPass : public IRenderPass { uint32_t directional = 0; }; + /// Mirrors debris_shadow.slang PushConstants + struct DebrisShadowPush { + float extrapolation = 0.0f; + float voxel_size = 0.0f; + uint32_t list_capacity = 0; + uint32_t view_index = 0; + }; + static constexpr uint32_t k_max_voxel_casters = 4096; /// Throttles the over limit warning std::chrono::steady_clock::time_point m_last_caster_limit_warning; @@ -133,6 +141,9 @@ class ShadowPass : public IRenderPass { std::optional view; + /// Cube groups split in two three layer views where mesh shader multiview stops short of six views + std::array, 2> halves; + bool dirty = true; std::optional signature; @@ -198,6 +209,9 @@ class ShadowPass : public IRenderPass { [[nodiscard]] auto voxelMeshPipelineFor(uint32_t view_mask) const -> const VulkanPipeline*; + /// Shares the voxel shadow set with the voxel casters and the debris set with DebrisPass + void createDebrisResources(const VulkanCore& core); + void recordMap(vk::CommandBuffer cmd, ShadowMap& map, ShadowMap& static_map, uint32_t frame_index, bool directional); [[nodiscard]] @@ -208,8 +222,8 @@ class ShadowPass : public IRenderPass { ShaderLayout m_shader_layout; - /// VulkanPipeline is not movable - std::array m_pipeline_sets; + /// One view, a cube and half a cube, VulkanPipeline is not movable + std::array m_pipeline_sets; Stats m_stats; std::vector m_voxel_eligible; @@ -220,7 +234,7 @@ class ShadowPass : public IRenderPass { StaticMaps m_static; ShaderLayout m_voxel_layout; - std::array m_voxel_pipeline_sets; + std::array m_voxel_pipeline_sets; std::vector m_voxel_shadow_sets; std::vector m_voxel_storage_sets; std::vector m_voxel_instance_buffers; @@ -240,20 +254,42 @@ class ShadowPass : public IRenderPass { }; std::unordered_map m_settled_casters; + + struct SettledMesh { + glm::mat4 model {1.0f}; + glm::vec3 bounds_center {0.0f}; + uint64_t moved_frame = 0; + uint64_t seen_frame = 0; + }; + + /// Keyed by node and mesh so submeshes of one node settle apart + std::unordered_map m_settled_meshes; + /// Per mesh proxy this frame, the settled model is what the static signatures hash + std::vector m_mesh_models; + std::vector m_mesh_moving; + + /// Resting meshes go to the static maps and moving or posed ones draw over them each compose + void prepareMeshes(uint32_t frame_index); uint64_t m_caster_frame = 0; std::vector m_caster_models; std::vector m_caster_moving; std::vector m_voxel_draw_order; + /// Light clip depth per voxel instance for the marched draw order + std::vector m_voxel_draw_keys; ShaderLayout m_voxel_mesh_layout; /// Matches m_voxel_pipeline_sets by index - std::array m_voxel_mesh_pipelines; + std::array m_voxel_mesh_pipelines; PFN_vkCmdDrawMeshTasksEXT m_draw_mesh_tasks = nullptr; std::array m_max_task_groups {}; uint32_t m_max_task_group_total = 0; std::vector m_static_copies; + + ShaderLayout m_debris_layout; + /// Matches m_pipeline_sets by index + std::array m_debris_pipelines; }; } diff --git a/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp b/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp index 8ed916fe9..ab0f3a286 100644 --- a/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/ssao_pass.cpp @@ -114,7 +114,8 @@ auto SsaoPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView const vk::ImageView depth_view = VulkanRenderer::instance->getDepthView(); const vk::ImageView normal_view = VulkanRenderer::instance->getSceneNormalView(); const vk::ImageView indirect_view = VulkanRenderer::instance->getSceneIndirectView(); - if (!depth_view || !normal_view || !indirect_view) { + const vk::ImageView denoised_view = VulkanRenderer::instance->getVoxelDenoisedIndirectView(); + if (!depth_view || !normal_view || !indirect_view || !denoised_view) { return source_view; } @@ -125,10 +126,11 @@ auto SsaoPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView vk::DescriptorImageInfo(*m_point_sampler, normal_view, vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_point_sampler, indirect_view, vk::ImageLayout::eShaderReadOnlyOptimal), // Point sampled since the upsample picks its own texels - vk::DescriptorImageInfo(*m_point_sampler, m_occlusion_target.view(), vk::ImageLayout::eShaderReadOnlyOptimal) + vk::DescriptorImageInfo(*m_point_sampler, m_occlusion_target.view(), vk::ImageLayout::eShaderReadOnlyOptimal), + vk::DescriptorImageInfo(*m_point_sampler, denoised_view, vk::ImageLayout::eShaderReadOnlyOptimal) }; - std::array writes {}; + std::array writes {}; for (uint32_t binding = 0; binding < writes.size(); ++binding) { writes[binding] = vk::WriteDescriptorSet( *m_descriptor_sets[frame_index], binding, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_infos[binding] @@ -156,7 +158,7 @@ auto SsaoPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView static_cast(size.width), static_cast(size.height), static_cast(frame != nullptr ? frame->sequence % 4096 : 0), - 0.0f + VulkanRenderer::instance->voxelDenoisedIndirectFrame() ? 1.0f : 0.0f ); target.beginScope(cmd); diff --git a/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp b/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp index 951eeb882..20fb9e7c9 100644 --- a/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp +++ b/engine/src/toast/renderer/passes/lighting/ssr_pass.cpp @@ -6,6 +6,8 @@ #include "toast/renderer/passes/lighting/ssr_pass.hpp" +#include "toast/renderer/core/gpu_sync.hpp" +#include "toast/renderer/core/gpu_timer.hpp" #include "toast/renderer/shaders/shader_cache.hpp" #include "toast/renderer/vulkan_renderer.hpp" @@ -17,7 +19,7 @@ SsrPass::SsrPass(const VulkanCore& core, vk::Format scene_format, vk::Extent2D e : m_core(&core), m_scene_format(scene_format) { ZoneScoped; - // Vulkan guarantees 128 bytes and this block is 176 + // Vulkan guarantees 128 bytes and this block is 192 const uint32_t push_constant_limit = core.getPhysicalDevice().getProperties().limits.maxPushConstantsSize; if (push_constant_limit < sizeof(Params)) { TOAST_ERROR( @@ -115,6 +117,9 @@ void SsrPass::createTargets(const VulkanCore& core, vk::Extent2D extent) { void SsrPass::onResize(vk::Extent2D extent) { if (m_core != nullptr) { createTargets(*m_core, extent); + for (HiZPyramid& hiz : m_hiz) { + hiz.create(*m_core, nullptr, {}); + } } } @@ -142,13 +147,25 @@ auto SsrPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView return m_target.view(); } + // Views only change on a resize after a wait for idle so recreating here never frees a pyramid in flight + HiZPyramid& hiz = m_hiz[depth_view == VulkanRenderer::instance->getDepthView() ? 0 : 1]; + const vk::Extent2D depth_extent = VulkanRenderer::instance->renderExtent(); + if (hiz.source() != depth_view) { + hiz.create(*m_core, depth_view, depth_extent, HiZPyramid::Reduction::closest); + } + if (!hiz.isReady()) { + return source_view; + } + const PostProcessTarget& history_write = m_history[m_parity]; const PostProcessTarget& history_read = m_history[1 - m_parity]; const uint32_t set_index = (frame_index * 2) + m_parity; const vk::DescriptorSet set = *m_descriptor_sets[set_index]; const vk::ImageView previous_view = VulkanRenderer::instance->previousResolvedColour(); - const std::array wanted {source_view, previous_view ? previous_view : source_view, depth_view, normal_view}; + const std::array wanted { + source_view, previous_view ? previous_view : source_view, depth_view, normal_view, hiz.view() + }; if (m_bound_views.update(set_index, wanted)) { // Point sampled except the colours since interpolated depth or normals invent surfaces const std::array image_infos { @@ -163,6 +180,7 @@ auto SsrPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView // Point sampled since the upsample picks its own texels vk::DescriptorImageInfo(*m_point_sampler, history_write.view(), vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_sampler, wanted[1], vk::ImageLayout::eShaderReadOnlyOptimal), + vk::DescriptorImageInfo(hiz.sampler(), hiz.view(), vk::ImageLayout::eShaderReadOnlyOptimal), }; std::array writes {}; @@ -177,16 +195,19 @@ auto SsrPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView if (!history_valid) { history_read.makeSampleable(cmd); } - auto settings = frame != nullptr ? frame->post_process.ssr : PostProcessSettings::Ssr {}; - // Non RT presets override the volume reach - if (const uint32_t steps = VulkanRenderer::instance->ssrOverrideSteps(); steps > 0) { - settings.max_steps = steps; - settings.stride = std::max(VulkanRenderer::instance->ssrOverrideReach(), 1.0f) / static_cast(steps); - } + const auto settings = VulkanRenderer::instance->ssrSettings(); // Jittered since depth was rasterized with it const glm::mat4 view_projection = frame != nullptr ? frame->frame_data.jittered_view_projection : glm::mat4(1.0f); + { + const GpuScope scope(VulkanRenderer::instance->gpuTimer(), frame_index, cmd, "SSR depth pyramid"); + hiz.record(cmd, depth_extent, view_projection); + sync::BarrierBatch barriers; + hiz.beforeFragmentRead(barriers); + barriers.flush(cmd); + } + Params params {}; params.view_projection = view_projection; params.inverse_view_projection = glm::inverse(view_projection); @@ -199,6 +220,7 @@ auto SsrPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageView history_valid ? 1.0f : 0.0f, previous_view ? 1.0f : 0.0f ); + params.pyramid = glm::vec4(static_cast(hiz.builtLevels()), 0.0f, 0.0f, 0.0f); const auto draw = [&](const PostProcessTarget& target, const VulkanPipeline& pipeline) { target.beginScope(cmd); diff --git a/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp b/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp index 44375a6d7..8b8bc0759 100644 --- a/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp +++ b/engine/src/toast/renderer/passes/lighting/ssr_pass.hpp @@ -9,6 +9,7 @@ #include "toast/renderer/core/descriptor_cache.hpp" #include "toast/renderer/core/vulkan_common.hpp" #include "toast/renderer/passes/post_process_pass_base.hpp" +#include "toast/renderer/resources/hiz_pyramid.hpp" #include "toast/renderer/resources/post_process_target.hpp" #include "toast/renderer/shaders/shader_layout.hpp" #include "toast/renderer/shaders/vulkan_pipeline.hpp" @@ -36,15 +37,17 @@ class SsrPass : public IPostProcessPass { void onResize(vk::Extent2D extent) override; private: - /// Mirrors ssr.slang SsrParams. 176 bytes so the constructor checks maxPushConstantsSize + /// Mirrors ssr.slang SsrParams. 192 bytes so the constructor checks maxPushConstantsSize struct Params { glm::mat4 view_projection {1.0f}; glm::mat4 inverse_view_projection {1.0f}; glm::vec4 camera_position {0.0f}; - /// x intensity y max roughness z thickness w step count + /// x intensity y max roughness z thickness w most pyramid steps a ray takes glm::vec4 tuning {0.0f}; /// x reach in meters y render mode z 1 with a valid history w 1 when binding 8 holds last frame resolve glm::vec4 marching {0.0f}; + /// x levels of the closest depth pyramid + glm::vec4 pyramid {0.0f}; }; /// xy hit uv z pdf w confidence in 32 bit since 16 bit cannot address wide screens @@ -53,7 +56,7 @@ class SsrPass : public IPostProcessPass { static constexpr vk::Format k_reflection_format = vk::Format::eR16G16B16A16Sfloat; /// Bindings of ssr.slang in order - static constexpr uint32_t k_binding_count = 9; + static constexpr uint32_t k_binding_count = 10; void createResources(const VulkanCore& core); void createTargets(const VulkanCore& core, vk::Extent2D extent); @@ -72,8 +75,11 @@ class SsrPass : public IPostProcessPass { /// Per frame in flight then per history parity std::vector m_descriptor_sets; - /// Source then previous resolve last written into each set - DescriptorCache> m_bound_views; + /// Source, previous resolve, depth, normal and pyramid last written into each set + DescriptorCache> m_bound_views; + + /// Closest depth pyramids of the scene depth and of the glass backdrop depth, whichever the frame reflects off + std::array m_hiz; PostProcessTarget m_hit_target; PostProcessTarget m_resolve_target; diff --git a/engine/src/toast/renderer/passes/post/bloom_pass.cpp b/engine/src/toast/renderer/passes/post/bloom_pass.cpp index 2ed4b3262..9f179eb50 100644 --- a/engine/src/toast/renderer/passes/post/bloom_pass.cpp +++ b/engine/src/toast/renderer/passes/post/bloom_pass.cpp @@ -234,6 +234,7 @@ auto BloomPass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::ImageVie params.knee = settings.knee; params.filter_radius = settings.filter_radius; params.strength = settings.strength; + params.glass_scale = VulkanRenderer::instance->glassGlowScale(); for (size_t i = 0; i < m_mips.size(); ++i) { const vk::Extent2D source_size = diff --git a/engine/src/toast/renderer/passes/post/bloom_pass.hpp b/engine/src/toast/renderer/passes/post/bloom_pass.hpp index 4d8854987..d8aad6665 100644 --- a/engine/src/toast/renderer/passes/post/bloom_pass.hpp +++ b/engine/src/toast/renderer/passes/post/bloom_pass.hpp @@ -46,7 +46,8 @@ class BloomPass : public IPostProcessPass { float knee = 0.5f; float filter_radius = 1.0f; float strength = 0.05f; - glm::vec2 pad0 {0.0f}; + float glass_scale = 1.0f; + float pad0 = 0.0f; }; struct Mip { diff --git a/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp b/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp index bdc613d58..749e193b1 100644 --- a/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp +++ b/engine/src/toast/renderer/passes/post/lens_flare_pass.cpp @@ -150,14 +150,18 @@ void LensFlarePass::writeDescriptor( vk::DescriptorSet set, vk::ImageView source, vk::ImageView scene, vk::ImageView glare, vk::ImageView streak, vk::ImageView dirt ) { - const std::array image_infos { + // Every set holds valid glass views since they share one layout, the source stands in when glass views are missing + const bool glass = m_glass_backdrop && m_glass_mask; + const std::array image_infos { vk::DescriptorImageInfo(*m_sampler, source, vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_sampler, scene ? scene : source, vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_sampler, glare ? glare : source, vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_sampler, streak ? streak : source, vk::ImageLayout::eShaderReadOnlyOptimal), vk::DescriptorImageInfo(*m_sampler, dirt ? dirt : source, vk::ImageLayout::eShaderReadOnlyOptimal), + vk::DescriptorImageInfo(*m_sampler, glass ? m_glass_backdrop : source, vk::ImageLayout::eShaderReadOnlyOptimal), + vk::DescriptorImageInfo(*m_sampler, glass ? m_glass_mask : source, vk::ImageLayout::eShaderReadOnlyOptimal), }; - std::array writes {}; + std::array writes {}; for (uint32_t binding = 0; binding < writes.size(); ++binding) { writes[binding] = vk::WriteDescriptorSet(set, binding, 0, 1, vk::DescriptorType::eCombinedImageSampler, &image_infos[binding]); @@ -233,7 +237,8 @@ auto LensFlarePass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag } } - if (sets.bound_scene != source_view || sets.bound_dirt != dirt_view) { + if (sets.bound_scene != source_view || sets.bound_dirt != dirt_view || sets.bound_backdrop != m_glass_backdrop || + sets.bound_mask != m_glass_mask) { const auto set = [&sets](Step step) { return *sets.sets[step]; }; writeDescriptor(set(step_threshold), source_view, source_view, source_view); writeDescriptor(set(step_glare), quarter_a, quarter_a, quarter_a); @@ -253,6 +258,8 @@ auto LensFlarePass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag writeDescriptor(set(step_mix), **m_flares.view, source_view, **m_glare_target.view, **m_streak[0].view, dirt_view); sets.bound_scene = source_view; sets.bound_dirt = dirt_view; + sets.bound_backdrop = m_glass_backdrop; + sets.bound_mask = m_glass_mask; } const auto inverse = [](vk::Extent2D size) { @@ -267,7 +274,9 @@ auto LensFlarePass::record(vk::CommandBuffer cmd, uint32_t frame_index, vk::Imag settings.glare_intensity, settings.glare_divider, static_cast(output.width) / static_cast(output.height), 0.0f ); params.tint = glm::vec4(1.0f, 1.0f, 1.0f, settings.intensity); - params.halo_style = glm::vec4(settings.halo_thickness, settings.halo_dispersion, 0.0f, 0.0f); + // Without glass views the mask stands in as the source so the scale must not apply + const float glass_scale = m_glass_backdrop && m_glass_mask ? VulkanRenderer::instance->glassGlowScale() : 0.0f; + params.halo_style = glm::vec4(settings.halo_thickness, settings.halo_dispersion, glass_scale, 0.0f); params.halo_tint = glm::vec4(settings.halo_tint_r, settings.halo_tint_g, settings.halo_tint_b, 1.0f); params.streak = glm::vec4(settings.anamorphic_intensity, settings.anamorphic_tint, settings.dirt_intensity, dirt_view ? 1.0f : 0.0f); @@ -321,4 +330,9 @@ void LensFlarePass::onResize(vk::Extent2D extent) { } } +void LensFlarePass::setGlassSources(vk::ImageView backdrop, vk::ImageView mask) { + m_glass_backdrop = backdrop; + m_glass_mask = mask; +} + } diff --git a/engine/src/toast/renderer/passes/post/lens_flare_pass.hpp b/engine/src/toast/renderer/passes/post/lens_flare_pass.hpp index 39d9af3e2..3afba7824 100644 --- a/engine/src/toast/renderer/passes/post/lens_flare_pass.hpp +++ b/engine/src/toast/renderer/passes/post/lens_flare_pass.hpp @@ -37,6 +37,8 @@ class LensFlarePass : public IPostProcessPass { void onResize(vk::Extent2D extent) override; + void setGlassSources(vk::ImageView backdrop, vk::ImageView mask) override; + private: /// Mirrors lens_flare.slang LensFlareParams struct Params { @@ -79,6 +81,8 @@ class LensFlarePass : public IPostProcessPass { std::vector sets; vk::ImageView bound_scene = nullptr; vk::ImageView bound_dirt = nullptr; + vk::ImageView bound_backdrop = nullptr; + vk::ImageView bound_mask = nullptr; }; void createTargets(const VulkanCore& core, vk::Extent2D extent); @@ -96,6 +100,8 @@ class LensFlarePass : public IPostProcessPass { const VulkanCore* m_core = nullptr; vk::Format m_format = vk::Format::eUndefined; + vk::ImageView m_glass_backdrop = nullptr; + vk::ImageView m_glass_mask = nullptr; ShaderLayout m_shader_layout; VulkanPipeline m_threshold_pipeline; diff --git a/engine/src/toast/renderer/resources/hiz_pyramid.cpp b/engine/src/toast/renderer/resources/hiz_pyramid.cpp index d7a086fdb..b5882f182 100644 --- a/engine/src/toast/renderer/resources/hiz_pyramid.cpp +++ b/engine/src/toast/renderer/resources/hiz_pyramid.cpp @@ -53,8 +53,10 @@ auto HiZPyramid::levelCount(vk::Extent2D extent) -> uint32_t { return std::min(1u + static_cast(std::bit_width(std::max({first.width, first.height, 1u}) - 1u)), k_max_levels); } -void HiZPyramid::create(const VulkanCore& core, vk::ImageView depth, vk::Extent2D depth_extent) { +void HiZPyramid::create(const VulkanCore& core, vk::ImageView depth, vk::Extent2D depth_extent, Reduction reduction) { ZoneScoped; + m_reduction = reduction; + m_source = depth; m_set.reset(); m_level_views.clear(); m_view.reset(); @@ -160,6 +162,10 @@ void HiZPyramid::beforeTaskRead(sync::BarrierBatch& barriers) { barriers.image(m_state, sync::Usage::task_sampled); } +void HiZPyramid::beforeFragmentRead(sync::BarrierBatch& barriers) { + barriers.image(m_state, sync::Usage::fragment_sampled); +} + void HiZPyramid::record(vk::CommandBuffer cmd, vk::Extent2D scene_extent, const glm::mat4& view_projection) { ZoneScoped; if (!isReady()) { @@ -184,6 +190,7 @@ void HiZPyramid::record(vk::CommandBuffer cmd, vk::Extent2D scene_extent, const .source_size = {scene_extent.width, scene_extent.height}, .level_count = levels, .group_count = groups_x * groups_y, + .closest = m_reduction == Reduction::closest ? 1u : 0u, }; const vk::PipelineLayout layout = *m_layout.getPipelineLayout(); diff --git a/engine/src/toast/renderer/resources/hiz_pyramid.hpp b/engine/src/toast/renderer/resources/hiz_pyramid.hpp index 806704a18..23aa601a1 100644 --- a/engine/src/toast/renderer/resources/hiz_pyramid.hpp +++ b/engine/src/toast/renderer/resources/hiz_pyramid.hpp @@ -15,11 +15,17 @@ namespace renderer { class VulkanCore; -/// Farthest depth pyramid where level k texel t covers pixels t << (k + 1) to ((t + 1) << (k + 1)) - 1 +/// Farthest or closest depth pyramid where level k texel t covers pixels t << (k + 1) to ((t + 1) << (k + 1)) - 1 class HiZPyramid { public: + /// Farthest for occlusion culling and closest for ray marching + enum class Reduction : uint8_t { + farthest, + closest + }; + /// After a wait for idle since an in flight frame may still read the previous pyramid - void create(const VulkanCore& core, vk::ImageView depth, vk::Extent2D depth_extent); + void create(const VulkanCore& core, vk::ImageView depth, vk::Extent2D depth_extent, Reduction reduction = Reduction::farthest); /// Depth in depth_sampled and only its top left @p scene_extent is reduced void record(vk::CommandBuffer cmd, vk::Extent2D scene_extent, const glm::mat4& view_projection); @@ -30,6 +36,14 @@ class HiZPyramid { /// Earlier writes land before a task or mesh shader samples view() void beforeTaskRead(sync::BarrierBatch& barriers); + /// Earlier writes land before a fragment shader samples view() + void beforeFragmentRead(sync::BarrierBatch& barriers); + + [[nodiscard]] + auto source() const -> vk::ImageView { + return m_source; + } + /// view() can be bound without it but only a ready pyramid is ever built [[nodiscard]] auto isReady() const -> bool { @@ -78,6 +92,7 @@ class HiZPyramid { glm::uvec2 source_size {0}; uint32_t level_count = 0; uint32_t group_count = 0; + uint32_t closest = 0; }; ShaderLayout m_layout; @@ -93,6 +108,8 @@ class HiZPyramid { bool m_counter_cleared = false; sync::ImageState m_state; uint32_t m_levels = 0; + Reduction m_reduction = Reduction::farthest; + vk::ImageView m_source = nullptr; vk::Extent2D m_built_extent {0, 0}; uint32_t m_built_levels = 0; diff --git a/engine/src/toast/renderer/settings/gi_settings.hpp b/engine/src/toast/renderer/settings/gi_settings.hpp index e12ea465a..36341e1a8 100644 --- a/engine/src/toast/renderer/settings/gi_settings.hpp +++ b/engine/src/toast/renderer/settings/gi_settings.hpp @@ -39,6 +39,8 @@ struct GiSettings { /// Meters a body has to move in a frame before GI treats it as a change and not physics jitter std::atomic motion_threshold {0.01f}; std::atomic max_ray_radiance {16.0f}; + /// Scales bounced light where surfaces are lit and not where GI feeds its own bounces so it cannot run away + std::atomic intensity {2.0f}; /// 0 off and otherwise 1 + the cascade drawn std::atomic debug_view {0}; /// Mirrors gi_debug.slang kGiDebug with 0 cells 1 interval radiance 2 coverage 3 irradiance 4 history depth 5 change diff --git a/engine/src/toast/renderer/settings/renderer_settings.cpp b/engine/src/toast/renderer/settings/renderer_settings.cpp index aa716a54b..ec60bdc30 100644 --- a/engine/src/toast/renderer/settings/renderer_settings.cpp +++ b/engine/src/toast/renderer/settings/renderer_settings.cpp @@ -37,6 +37,9 @@ struct PresetKnobs { float ssr_reach = 0.0f; uint32_t ssr_steps = 0; bool motion_blur = false; + uint32_t glass_lit_surfaces = 4; + /// Meters glass reflections reach, below the SSR and traced specular reach since only the front layer reflects + float glass_reflection_reach = 32.0f; }; /// Low Medium High Epic without ray tracing, then Low RT Medium RT High RT Epic RT @@ -58,7 +61,9 @@ constexpr std::array k_preset_tiers { .shadow_distance = 60.0f, .spot_budget = 4, .point_budget = 2, - .shadow_maps_only = true}, + .shadow_maps_only = true, + .glass_lit_surfaces = 1, + .glass_reflection_reach = 8.0f}, {.ssr = true, .ssao = true, .traced_specular = false, @@ -75,8 +80,10 @@ constexpr std::array k_preset_tiers { .spot_budget = 6, .point_budget = 3, .shadow_maps_only = true, - .ssr_reach = 12.0f, - .ssr_steps = 48}, + .ssr_reach = 50.0f, + .ssr_steps = 48, + .glass_lit_surfaces = 2, + .glass_reflection_reach = 12.0f}, {.ssr = true, .ssao = true, .traced_specular = false, @@ -93,9 +100,11 @@ constexpr std::array k_preset_tiers { .spot_budget = 10, .point_budget = 5, .shadow_maps_only = true, - .ssr_reach = 20.0f, + .ssr_reach = 100.0f, .ssr_steps = 64, - .motion_blur = true}, + .motion_blur = true, + .glass_lit_surfaces = 3, + .glass_reflection_reach = 16.0f}, {.ssr = true, .ssao = true, .traced_specular = false, @@ -112,9 +121,11 @@ constexpr std::array k_preset_tiers { .spot_budget = 16, .point_budget = 8, .shadow_maps_only = true, - .ssr_reach = 32.0f, + .ssr_reach = 200.0f, .ssr_steps = 96, - .motion_blur = true}, + .motion_blur = true, + .glass_lit_surfaces = 4, + .glass_reflection_reach = 24.0f}, // With ray tracing {.ssr = false, .ssao = false, @@ -128,7 +139,9 @@ constexpr std::array k_preset_tiers { .gi_quality = 0, .shadow_distance = 60.0f, .spot_budget = 4, - .point_budget = 2}, + .point_budget = 2, + .glass_lit_surfaces = 1, + .glass_reflection_reach = 8.0f}, {.ssr = true, .ssao = true, .traced_specular = false, @@ -141,7 +154,11 @@ constexpr std::array k_preset_tiers { .gi_quality = 1, .shadow_distance = 100.0f, .spot_budget = 8, - .point_budget = 4}, + .point_budget = 4, + .ssr_reach = 50.0f, + .ssr_steps = 48, + .glass_lit_surfaces = 2, + .glass_reflection_reach = 16.0f}, {.ssr = true, .ssao = true, .traced_specular = true, @@ -155,7 +172,11 @@ constexpr std::array k_preset_tiers { .shadow_distance = 150.0f, .spot_budget = 16, .point_budget = 8, - .motion_blur = true}, + .ssr_reach = 100.0f, + .ssr_steps = 64, + .motion_blur = true, + .glass_lit_surfaces = 3, + .glass_reflection_reach = 24.0f}, {.ssr = true, .ssao = true, .traced_specular = true, @@ -169,7 +190,11 @@ constexpr std::array k_preset_tiers { .shadow_distance = 250.0f, .spot_budget = shadows::k_max_spot_shadows, .point_budget = shadows::k_max_point_shadows, - .motion_blur = true}, + .ssr_reach = 200.0f, + .ssr_steps = 96, + .motion_blur = true, + .glass_lit_surfaces = 4, + .glass_reflection_reach = 32.0f}, } }; @@ -216,6 +241,8 @@ void applyPreset() { renderer.setVoxelLightCandidates(knobs.light_candidates); renderer.setVoxelAmbientRays(knobs.ambient_rays); renderer.setVoxelGlassShadows(knobs.glass_shadows); + renderer.setVoxelGlassLitSurfaces(knobs.glass_lit_surfaces); + renderer.setVoxelGlassReflectionReach(knobs.glass_reflection_reach); renderer.setVolumetricQuality(knobs.volumetric_quality); renderer.giSettings().quality.store(knobs.gi_quality, std::memory_order_relaxed); shadows::setShadowDistance(knobs.shadow_distance); @@ -230,7 +257,7 @@ struct DrivenSetting { Value (*get)(const PresetKnobs&); }; -const std::array k_driven { +const std::array k_driven { { {"renderer.voxels.shadow_maps_only", [](const PresetKnobs& k) { return Value {k.shadow_maps_only}; }}, {"renderer.quality.ssr_reach", [](const PresetKnobs& k) { return Value {static_cast(k.ssr_reach)}; }}, @@ -246,6 +273,10 @@ const std::array k_driven { {"renderer.voxels.light_candidates", [](const PresetKnobs& k) { return Value {static_cast(k.light_candidates)}; }}, {"renderer.voxels.ambient_rays", [](const PresetKnobs& k) { return Value {k.ambient_rays}; }}, {"renderer.voxels.glass_shadows", [](const PresetKnobs& k) { return Value {k.glass_shadows}; }}, + {"renderer.voxels.glass_lit_surfaces", + [](const PresetKnobs& k) { return Value {static_cast(k.glass_lit_surfaces)}; }}, + {"renderer.voxels.glass_reflection_reach", + [](const PresetKnobs& k) { return Value {static_cast(k.glass_reflection_reach)}; }}, {"renderer.volumetrics.quality", [](const PresetKnobs& k) { return Value {static_cast(k.volumetric_quality)}; }}, {"renderer.gi.enabled", [](const PresetKnobs& k) { return Value {k.gi_enabled}; }}, {"renderer.gi.quality", [](const PresetKnobs& k) { return Value {static_cast(k.gi_quality)}; }}, @@ -421,6 +452,19 @@ void registerQuality(VulkanRenderer& renderer) { true, "Ghosts, halo and glare streaks from the brightest pixels. Tuned on the post process volume." ); + toast::settings::declareFloat( + "renderer.quality.glass_glow_scale", + 1.0, + {.label = "Emissive behind glass", + .category = "Quality", + .description = "Scale on the light behind glass that bloom and lens flares see, so emissives the glass dims " + "still glow and flare. 0 lets glass dim them like everything else, 1 sees them as if the glass " + "were not there and higher boosts them. Lit surfaces behind glass are scaled too", + .min = 0.0, + .max = 16.0, + .step = 0.1} + ) + .onChange([&renderer](double v) { renderer.setGlassGlowScale(static_cast(v)); }); toast::settings::declareBool( "renderer.quality.ssr", true, @@ -485,9 +529,10 @@ void registerQuality(VulkanRenderer& renderer) { 0.0, {.label = "SSR reach", .category = "Quality", - .description = "Meters an SSR ray travels, with the steps below in place of the post process volume. Preset Custom only", + .description = "Most meters an SSR ray travels before the screen edge stops it, with the steps below in place of the " + "post process volume. Preset Custom only", .min = 0.0, - .max = 100.0, + .max = 500.0, .step = 1.0} ) .onChange(presetKnob(&PresetKnobs::ssr_reach, k_to_float)); @@ -497,7 +542,7 @@ void registerQuality(VulkanRenderer& renderer) { 0, {.label = "SSR steps", .category = "Quality", - .description = "Samples along each SSR ray. 0 keeps the post process volume values. Preset Custom only", + .description = "Most depth pyramid steps an SSR ray takes. 0 keeps the post process volume values. Preset Custom only", .min = 0.0, .max = 256.0} ) @@ -841,68 +886,44 @@ void registerVoxels(VulkanRenderer& renderer) { ) .onChange(presetKnob(&PresetKnobs::specular_reach, k_to_float)); - toast::settings::declareBool( - "renderer.voxels.glass_refraction_enabled", - true, - {.label = "Glass refraction", + toast::settings::declareInt( + "renderer.voxels.glass_lit_surfaces", + 4, + {.label = "Glass lit surfaces", .category = "Voxels", - .description = "Glass bends what is behind it by its IOR. Costs a copy of the scene colour and depth plus a " - "march through the volume for every glass pixel. Off draws glass straight through"} + .description = "Glass surfaces per brick and pixel that get full lighting and reflections. Layers past it " + "only tint what is behind them", + .min = 1.0, + .max = 4.0} ) - .onChange([&renderer](bool enabled) { renderer.setVoxelGlassRefractionEnabled(enabled); }); + .onChange(presetKnob(&PresetKnobs::glass_lit_surfaces, [](int64_t v) { + return static_cast(std::clamp(v, 1, 4)); + })); toast::settings::declareFloat( - "renderer.voxels.glass_refraction", - 1.0, - {.label = "Glass refraction strength", + "renderer.voxels.glass_reflection_reach", + 32.0, + {.label = "Glass reflection reach", .category = "Voxels", - .description = "How far glass bends what is behind it. 1 follows the IOR and higher exaggerates it", + .description = "Meters the SSR or traced reflection of the front glass layer reaches. Shorter is cheaper and " + "misses fall back to the environment", .min = 0.0, - .max = 4.0, - .step = 0.05} + .max = 128.0} ) - .onChange([&renderer](double v) { renderer.setVoxelGlassRefraction(static_cast(v)); }); + .onChange(presetKnob(&PresetKnobs::glass_reflection_reach, k_to_float)); toast::settings::declareFloat( - "renderer.voxels.glass_refraction_distance", - 60.0, - {.label = "Glass refraction distance", + "renderer.voxels.glass_coarse_distance", + 30.0, + {.label = "Glass coarse shading distance", .category = "Voxels", - .description = "Meters from the camera past which glass draws straight through. Far glass bends too little to " - "see and the scene copy is skipped when every glass brick is past it", - .min = 1.0, + .description = "Meters past which glass shades one lighting sample per 2x2 pixels on GPUs with variable rate " + "shading. 0 shades every pixel", + .min = 0.0, .max = 500.0, .step = 1.0} ) - .onChange([&renderer](double v) { renderer.setVoxelGlassRefractionDistance(static_cast(v)); }); - - toast::settings::declareInt( - "renderer.voxels.glass_refraction_depth", - 32, - {.label = "Glass refraction depth", - .category = "Voxels", - .description = "Voxels refraction follows through thick glass to find its far side. Past it the far side " - "counts as parallel to the near one", - .min = 1.0, - .max = 96.0} - ) - .onChange([&renderer](int64_t v) { - renderer.setVoxelGlassRefractionVoxels(static_cast(std::clamp(v, 1, 96))); - }); - - toast::settings::declareInt( - "renderer.voxels.glass_lit_surfaces", - 4, - {.label = "Glass lit surfaces", - .category = "Voxels", - .description = "Glass surfaces per brick and pixel that get full lighting and reflections. Layers past it " - "only tint what is behind them", - .min = 1.0, - .max = 4.0} - ) - .onChange([&renderer](int64_t v) { - renderer.setVoxelGlassLitSurfaces(static_cast(std::clamp(v, 1, 4))); - }); + .onChange([&renderer](double v) { renderer.setVoxelGlassCoarseDistance(static_cast(v)); }); toast::settings::declareBool( "renderer.voxels.glass_shadows", @@ -1183,6 +1204,16 @@ void registerDebug(VulkanRenderer& renderer) { "Off hides them in game and brings them back as they were in the editor. F3 in game flips it."} ) .onChange([&renderer](bool visible) { renderer.setDebugOverlayInGame(visible); }); + + toast::settings::declareBool( + "renderer.debug.glass_cost_view", + false, + {.label = "Glass cost view", + .category = "Debug", + .description = "Glass adds a colour for what each pixel cost instead of drawing itself. Green builds up per glass " + "brick drawn, red per lit glass surface and blue per reflection traced or marched"} + ) + .onChange([&renderer](bool enabled) { renderer.setGlassCostView(enabled); }); } #endif @@ -1422,6 +1453,19 @@ void registerGi(VulkanRenderer& renderer) { ) .onChange([&gi](double v) { gi.max_ray_radiance.store(static_cast(v), std::memory_order_relaxed); }); + toast::settings::declareFloat( + "renderer.gi.intensity", + 2.0, + {.label = "Bounce intensity", + .category = "Global illumination", + .description = "Multiplies the light GI bounces onto surfaces. 1 is physically based and higher makes colour bleed " + "and bounce stand out more", + .min = 0.0, + .max = 8.0, + .step = 0.1} + ) + .onChange([&gi](double v) { gi.intensity.store(static_cast(v), std::memory_order_relaxed); }); + toast::settings::declareInt( "renderer.gi.debug_view", 0, diff --git a/engine/src/toast/renderer/shaders/shader_compiler.cpp b/engine/src/toast/renderer/shaders/shader_compiler.cpp index 9f85e787e..0ec1a30ac 100644 --- a/engine/src/toast/renderer/shaders/shader_compiler.cpp +++ b/engine/src/toast/renderer/shaders/shader_compiler.cpp @@ -259,16 +259,22 @@ void logDiagnostics(const Slang::ComPtr& diagnostics, std::string_ const void* diag_ptr = diagnostics->getBufferPointer(); const size_t diag_size = diagnostics->getBufferSize(); if (diag_ptr && diag_size > 0) { - const char* diag_c = static_cast(diag_ptr); - const std::string diag_str(diag_c, diag_c + diag_size); + // the blob counts its null terminator + std::string_view diag_str(static_cast(diag_ptr), diag_size); + while (!diag_str.empty() && diag_str.back() == '\0') { + diag_str.remove_suffix(1); + } + // The row only shows the message so it carries the first error line and the details keep the full text logging::Severity severity = logging::Severity::warning; - - if (diag_str.contains(": error ")) { + std::string_view headline = logging::splitFirstLine(diag_str).first; + if (const size_t error_at = diag_str.find(": error "); error_at != std::string_view::npos) { severity = logging::Severity::error; + const size_t line_start = diag_str.rfind('\n', error_at); + headline = logging::splitFirstLine(diag_str.substr(line_start == std::string_view::npos ? 0 : line_start + 1)).first; } - TOAST_MESSAGE(severity, "Render", std::format("Slang diagnostics for '{}'", source_name), diag_str); + TOAST_MESSAGE(severity, "Render", std::format("Slang: {}", headline), diag_str); } } diff --git a/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp b/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp index fe2432e40..3626dac95 100644 --- a/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp +++ b/engine/src/toast/renderer/shaders/vulkan_pipeline.cpp @@ -52,6 +52,18 @@ auto createGraphicsPipelineImpl( ? spirv::resolveEntryPoint(fragment_spirv, spirv::ExecutionModel::fragment, config.fragment_entry, config.debug_name) : config.fragment_entry; + std::vector specialization_entries; + for (uint32_t i = 0; i < config.specialization_constants.size(); ++i) { + specialization_entries.emplace_back(i, static_cast(i * sizeof(uint32_t)), sizeof(uint32_t)); + } + const vk::SpecializationInfo specialization_info( + static_cast(specialization_entries.size()), + specialization_entries.data(), + config.specialization_constants.size() * sizeof(uint32_t), + config.specialization_constants.data() + ); + const vk::SpecializationInfo* specialization = specialization_entries.empty() ? nullptr : &specialization_info; + std::vector shader_stages; if (mesh) { if (!task_entry.empty()) { @@ -59,15 +71,24 @@ auto createGraphicsPipelineImpl( vk::PipelineShaderStageCreateFlags {}, vk::ShaderStageFlagBits::eTaskEXT, task_module != nullptr ? **task_module : *shader_module, - task_entry.c_str() + task_entry.c_str(), + specialization ); } shader_stages.emplace_back( - vk::PipelineShaderStageCreateFlags {}, vk::ShaderStageFlagBits::eMeshEXT, *shader_module, mesh_entry.c_str() + vk::PipelineShaderStageCreateFlags {}, + vk::ShaderStageFlagBits::eMeshEXT, + *shader_module, + mesh_entry.c_str(), + specialization ); } else { shader_stages.emplace_back( - vk::PipelineShaderStageCreateFlags {}, vk::ShaderStageFlagBits::eVertex, *shader_module, vertex_entry.c_str() + vk::PipelineShaderStageCreateFlags {}, + vk::ShaderStageFlagBits::eVertex, + *shader_module, + vertex_entry.c_str(), + specialization ); } if (has_fragment_stage) { @@ -75,7 +96,8 @@ auto createGraphicsPipelineImpl( vk::PipelineShaderStageCreateFlags {}, vk::ShaderStageFlagBits::eFragment, fragment_module != nullptr ? **fragment_module : *shader_module, - fragment_entry.c_str() + fragment_entry.c_str(), + specialization ); } @@ -236,6 +258,16 @@ auto createGraphicsPipelineImpl( ); } + // Keep combiners so only this pipeline rate applies + vk::PipelineFragmentShadingRateStateCreateInfoKHR shading_rate_ci {}; + shading_rate_ci.fragmentSize = config.fragment_shading_rate; + shading_rate_ci.combinerOps = + std::array {vk::FragmentShadingRateCombinerOpKHR::eKeep, vk::FragmentShadingRateCombinerOpKHR::eKeep}; + if (core.isFragmentShadingRateSupported() && + (config.fragment_shading_rate.width > 1 || config.fragment_shading_rate.height > 1)) { + rendering_ci.pNext = &shading_rate_ci; + } + vk::GraphicsPipelineCreateInfo pipeline_ci {}; pipeline_ci.pNext = &rendering_ci; pipeline_ci.stageCount = static_cast(shader_stages.size()); diff --git a/engine/src/toast/renderer/shaders/vulkan_pipeline.hpp b/engine/src/toast/renderer/shaders/vulkan_pipeline.hpp index 61d4d2c59..3d9701229 100644 --- a/engine/src/toast/renderer/shaders/vulkan_pipeline.hpp +++ b/engine/src/toast/renderer/shaders/vulkan_pipeline.hpp @@ -103,6 +103,12 @@ class VulkanPipeline { float depth_bias_slope = 0.0f; bool blend_enable = false; BlendPreset blend_preset = BlendPreset::none; + + /// Pixels one fragment shades, only applied with VulkanCore::isFragmentShadingRateSupported + vk::Extent2D fragment_shading_rate {1, 1}; + + /// Value of [[vk::constant_id(i)]] at index i for every stage so the driver strips the branches they turn off + std::vector specialization_constants; }; VulkanPipeline() = default; diff --git a/engine/src/toast/renderer/voxel/voxel_gpu_storage.cpp b/engine/src/toast/renderer/voxel/voxel_gpu_storage.cpp index bc2ee1d90..75612bba6 100644 --- a/engine/src/toast/renderer/voxel/voxel_gpu_storage.cpp +++ b/engine/src/toast/renderer/voxel/voxel_gpu_storage.cpp @@ -185,8 +185,22 @@ void VoxelGpuSections::recordPending(vk::CommandBuffer cmd, uint64_t up_to, std: barriers.flush(cmd); } +namespace { + +auto firstRecordOf(const std::vector& node_rids) -> std::unordered_map { + std::unordered_map records; + records.reserve(node_rids.size()); + for (uint32_t record = 0; record < node_rids.size(); ++record) { + records.try_emplace(node_rids[record], record); + } + return records; +} + +} + VoxelGpuStorage::VoxelGpuStorage(std::vector node_rids, std::vector brick_dims) : m_node_rids(std::move(node_rids)), + m_record_of(firstRecordOf(m_node_rids)), m_brick_dims(std::move(brick_dims)), m_sections(std::make_shared()), m_generation(g_voxel_storage_generation.fetch_add(1, std::memory_order_relaxed) + 1) { } @@ -195,6 +209,7 @@ VoxelGpuStorage::VoxelGpuStorage( std::vector node_rids, std::vector brick_dims, const VoxelGpuStorage& previous, uint64_t patch_sequence ) : m_node_rids(std::move(node_rids)), + m_record_of(firstRecordOf(m_node_rids)), m_brick_dims(std::move(brick_dims)), m_sections(previous.m_sections), m_patch_sequence(patch_sequence), @@ -244,11 +259,11 @@ void writeVoxelStorageDescriptors(const vk::raii::Device& device, vk::Descriptor } auto VoxelGpuStorage::recordIndexOf(uint64_t node_rid) const -> std::optional { - const auto found = std::ranges::find(m_node_rids, node_rid); - if (found == m_node_rids.end()) { + const auto found = m_record_of.find(node_rid); + if (found == m_record_of.end()) { return std::nullopt; } - return static_cast(found - m_node_rids.begin()); + return found->second; } auto VoxelGpuStorage::buffer(Section section) const -> vk::Buffer { diff --git a/engine/src/toast/renderer/voxel/voxel_gpu_storage.hpp b/engine/src/toast/renderer/voxel/voxel_gpu_storage.hpp index 9170a5ac0..c44d9e5da 100644 --- a/engine/src/toast/renderer/voxel/voxel_gpu_storage.hpp +++ b/engine/src/toast/renderer/voxel/voxel_gpu_storage.hpp @@ -16,6 +16,7 @@ #include #include #include +#include #include namespace renderer { @@ -162,6 +163,8 @@ class VoxelGpuStorage : public IVulkanResource { friend class VoxelSceneUpload; std::vector m_node_rids; + /// First record of each rid so recordIndexOf is not a scan per call + std::unordered_map m_record_of; std::vector m_brick_dims; std::shared_ptr m_sections; diff --git a/engine/src/toast/renderer/voxel/voxel_scene_patcher.cpp b/engine/src/toast/renderer/voxel/voxel_scene_patcher.cpp index 28a2cbb7a..e435c0e18 100644 --- a/engine/src/toast/renderer/voxel/voxel_scene_patcher.cpp +++ b/engine/src/toast/renderer/voxel/voxel_scene_patcher.cpp @@ -27,7 +27,7 @@ void VoxelScenePatcher::adopt(const voxel::gpu::PackedScene& scene, uint32_t poo } auto VoxelScenePatcher::paletteMatches(const voxel::gpu::VolumeRecord& record, const voxel::Palette& palette) const -> bool { - const size_t base = size_t {record.palette_offset} * 4u; + const size_t base = size_t {record.palette_offset} * voxel::gpu::k_palette_entry_words; return record.max_emissive == palette.max_emissive && base + voxel::gpu::k_palette_words <= m_scene.palettes.size() && std::memcmp(m_scene.palettes.data() + base, palette.entries.data(), voxel::gpu::k_palette_words * sizeof(uint32_t)) == 0; } @@ -36,13 +36,13 @@ auto VoxelScenePatcher::findOrAppendPalette(const voxel::Palette& palette) -> ui using voxel::gpu::k_palette_words; for (size_t base = 0; base + k_palette_words <= m_scene.palettes.size(); base += k_palette_words) { if (std::memcmp(m_scene.palettes.data() + base, palette.entries.data(), k_palette_words * sizeof(uint32_t)) == 0) { - return static_cast(base / 4u); + return static_cast(base / voxel::gpu::k_palette_entry_words); } } const size_t base = m_scene.palettes.size(); m_scene.palettes.resize(base + k_palette_words); std::memcpy(m_scene.palettes.data() + base, palette.entries.data(), k_palette_words * sizeof(uint32_t)); - return static_cast(base / 4u); + return static_cast(base / voxel::gpu::k_palette_entry_words); } auto VoxelScenePatcher::tryPatch( diff --git a/engine/src/toast/renderer/voxel/voxel_trace_scene.cpp b/engine/src/toast/renderer/voxel/voxel_trace_scene.cpp index ec0a5ccb8..e64823454 100644 --- a/engine/src/toast/renderer/voxel/voxel_trace_scene.cpp +++ b/engine/src/toast/renderer/voxel/voxel_trace_scene.cpp @@ -121,14 +121,34 @@ void VoxelTraceScene::writeGrid(FrameResources& frame, glm::vec3 camera_position const auto dim = static_cast(k_grid_dim); const glm::vec3 origin = (glm::floor(camera_position / cell) - glm::vec3(static_cast(dim / 2.0))) * cell; + // The grid only reads bounds, glass, the origin and the cell so the same inputs leave this slot's words as they are + uint64_t signature = 0xCBF29CE484222325ull; + const auto mix = [&signature](uint32_t word) { signature = (signature ^ word) * 0x100000001B3ull; }; + for (const float value : {origin.x, origin.y, origin.z, cell}) { + mix(std::bit_cast(value)); + } + mix(static_cast(m_volumes.size())); + for (const Volume& volume : m_volumes) { + for (int c = 0; c < 4; ++c) { + mix(std::bit_cast(volume.bounds[c])); + } + mix(volume.glass ? 1u : 0u); + } + if (frame.grid_signature == signature) { + return; + } + frame.grid_signature = signature; + struct Span { glm::ivec3 lo; glm::ivec3 hi; }; std::vector spans(m_volumes.size()); - std::vector far; - std::vector glass; + std::vector& far = m_far; + std::vector& glass = m_glass; + far.clear(); + glass.clear(); std::ranges::fill(m_cell_counts, 0u); const auto cell_index = [dim](int32_t x, int32_t y, int32_t z) { diff --git a/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp b/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp index 618da9e7c..8e80a6418 100644 --- a/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp +++ b/engine/src/toast/renderer/voxel/voxel_trace_scene.hpp @@ -85,6 +85,8 @@ class VoxelTraceScene { vma::raii::Buffer bounds = nullptr; vma::raii::Buffer grid = nullptr; vma::raii::Buffer brick_bases = nullptr; + /// What the grid buffer holds so an unchanged scene and camera cell skip rewriting it + std::optional grid_signature; }; void writeGrid(FrameResources& frame, glm::vec3 camera_position, float cell_size); @@ -95,6 +97,9 @@ class VoxelTraceScene { std::vector m_volumes; std::vector m_cell_counts; std::vector m_cell_cursor; + /// writeGrid scratch kept for its capacity + std::vector m_far; + std::vector m_glass; std::optional m_box_aabb; std::optional m_box_storage; diff --git a/engine/src/toast/renderer/vulkan_renderer.cpp b/engine/src/toast/renderer/vulkan_renderer.cpp index bc46e9ab8..b4e4efc54 100644 --- a/engine/src/toast/renderer/vulkan_renderer.cpp +++ b/engine/src/toast/renderer/vulkan_renderer.cpp @@ -164,6 +164,17 @@ auto VulkanRenderer::setPostProcessPassEnabled(std::string_view name, bool enabl return false; } +auto VulkanRenderer::ssrSettings() const -> PostProcessSettings::Ssr { + const auto* frame = renderingFrame(); + auto settings = frame != nullptr ? frame->post_process.ssr : PostProcessSettings::Ssr {}; + // Non RT presets override the volume reach + if (const uint32_t steps = ssrOverrideSteps(); steps > 0) { + settings.max_steps = steps; + settings.stride = std::max(ssrOverrideReach(), 1.0f) / static_cast(steps); + } + return settings; +} + auto VulkanRenderer::isPostProcessPassEnabled(std::string_view name) const -> bool { std::lock_guard lock(m_pass_mutex); for (const auto& pass : m_post_process_passes) { @@ -671,9 +682,20 @@ auto VulkanRenderer::applyResizeInternal(vk::Extent2D extent) -> void { } void VulkanRenderer::addRenderPass(std::unique_ptr pass) { + std::lock_guard lock(m_pass_mutex); m_render_passes.push_back(std::move(pass)); } +void VulkanRenderer::removeRenderPass(const IRenderPass* pass) { + std::lock_guard lock(m_pass_mutex); + const auto it = std::ranges::find(m_render_passes, pass, &std::unique_ptr::get); + if (it == m_render_passes.end()) { + return; + } + m_retiring_passes.emplace_back(it->release()); + m_render_passes.erase(it); +} + void VulkanRenderer::addPostProcessPass(std::unique_ptr pass) { std::lock_guard lock(m_pass_mutex); m_post_process_passes.push_back(std::move(pass)); diff --git a/engine/src/toast/renderer/vulkan_renderer.hpp b/engine/src/toast/renderer/vulkan_renderer.hpp index 3560394d8..005c509db 100644 --- a/engine/src/toast/renderer/vulkan_renderer.hpp +++ b/engine/src/toast/renderer/vulkan_renderer.hpp @@ -270,6 +270,9 @@ class VulkanRenderer { void addRenderPass(std::unique_ptr pass); + /// Thread safe and frees the pass once no frame in flight still uses it + void removeRenderPass(const IRenderPass* pass); + void addComputePass(std::unique_ptr pass); /// Runs in registration order @@ -280,6 +283,10 @@ class VulkanRenderer { [[nodiscard]] auto isPostProcessPassEnabled(std::string_view name) const -> bool; + /// Render thread SSR settings of the frame being rendered with the preset reach override applied + [[nodiscard]] + auto ssrSettings() const -> PostProcessSettings::Ssr; + [[nodiscard]] auto getSceneColorFormat() const noexcept -> vk::Format { return m_scene_color_format; @@ -359,6 +366,18 @@ class VulkanRenderer { return m_voxel_noisy_diffuse.view.has_value() ? **m_voxel_noisy_diffuse.view : vk::ImageView {}; } + /// Denoised clipmap GI the voxel composite wrote with alpha 1 and 0 where SSAO keeps reading the scene indirect + [[nodiscard]] + auto getVoxelDenoisedIndirectView() const noexcept -> vk::ImageView { + return m_voxel_denoised_indirect.view.has_value() ? **m_voxel_denoised_indirect.view : vk::ImageView {}; + } + + /// Whether this frame's voxel denoise composite wrote getVoxelDenoisedIndirectView + [[nodiscard]] + auto voxelDenoisedIndirectFrame() const noexcept -> bool { + return m_voxel_denoised_indirect_frame; + } + [[nodiscard]] auto getVoxelNoisySpecularView() const noexcept -> vk::ImageView { return m_voxel_noisy_specular.view.has_value() ? **m_voxel_noisy_specular.view : vk::ImageView {}; @@ -547,48 +566,58 @@ class VulkanRenderer { return m_voxel_specular_reach.load(std::memory_order_relaxed); } - /// 1 is Snell and 0 turns refraction off - void setVoxelGlassRefraction(float strength) noexcept { - m_voxel_glass_refraction.store(std::max(strength, 0.0f), std::memory_order_relaxed); + void setVoxelGlassLitSurfaces(uint32_t surfaces) noexcept { + m_voxel_glass_lit_surfaces.store(surfaces, std::memory_order_relaxed); } [[nodiscard]] - auto voxelGlassRefraction() const noexcept -> float { - return m_voxel_glass_refraction_enabled.load(std::memory_order_relaxed) - ? m_voxel_glass_refraction.load(std::memory_order_relaxed) - : 0.0f; + auto voxelGlassLitSurfaces() const noexcept -> uint32_t { + return m_voxel_glass_lit_surfaces.load(std::memory_order_relaxed); } - /// Off skips the backdrop copy and the volume march of every glass pixel - void setVoxelGlassRefractionEnabled(bool enabled) noexcept { - m_voxel_glass_refraction_enabled.store(enabled, std::memory_order_relaxed); + /// Scale bloom and lens flares put on the light behind glass so emissives the glass dims still glow + void setGlassGlowScale(float scale) noexcept { m_glass_glow_scale.store(std::max(scale, 0.0f), std::memory_order_relaxed); } + + [[nodiscard]] + auto glassGlowScale() const noexcept -> float { + return m_glass_glow_scale.load(std::memory_order_relaxed); } - void setVoxelGlassRefractionDistance(float meters) noexcept { - m_voxel_glass_refraction_distance.store(std::max(meters, 0.0f), std::memory_order_relaxed); + /// Meters past which outside glass bricks shade at 2x2 where the device supports a pipeline shading rate, 0 never + void setVoxelGlassCoarseDistance(float meters) noexcept { + m_voxel_glass_coarse_distance.store(std::max(meters, 0.0f), std::memory_order_relaxed); } [[nodiscard]] - auto voxelGlassRefractionDistance() const noexcept -> float { - return m_voxel_glass_refraction_distance.load(std::memory_order_relaxed); + auto voxelGlassCoarseDistance() const noexcept -> float { + return m_voxel_glass_coarse_distance.load(std::memory_order_relaxed); } - void setVoxelGlassRefractionVoxels(uint32_t voxels) noexcept { - m_voxel_glass_refraction_voxels.store(std::max(voxels, 1u), std::memory_order_relaxed); - } + /// Glass adds a heat colour per pixel for what it cost instead of drawing itself + void setGlassCostView(bool enabled) noexcept { m_glass_cost_view.store(enabled, std::memory_order_relaxed); } [[nodiscard]] - auto voxelGlassRefractionVoxels() const noexcept -> uint32_t { - return m_voxel_glass_refraction_voxels.load(std::memory_order_relaxed); + auto glassCostView() const noexcept -> bool { + return m_glass_cost_view.load(std::memory_order_relaxed); } - void setVoxelGlassLitSurfaces(uint32_t surfaces) noexcept { - m_voxel_glass_lit_surfaces.store(surfaces, std::memory_order_relaxed); + /// Meters glass SSR and traced reflections reach at most + void setVoxelGlassReflectionReach(float meters) noexcept { + m_voxel_glass_reflection_reach.store(std::max(meters, 0.0f), std::memory_order_relaxed); } [[nodiscard]] - auto voxelGlassLitSurfaces() const noexcept -> uint32_t { - return m_voxel_glass_lit_surfaces.load(std::memory_order_relaxed); + auto voxelGlassReflectionReach() const noexcept -> float { + return m_voxel_glass_reflection_reach.load(std::memory_order_relaxed); + } + + /// SSR settings for the linear glass march with the reach capped at voxelGlassReflectionReach and the steps spread over it + [[nodiscard]] + auto glassSsrSettings() const -> PostProcessSettings::Ssr { + auto settings = ssrSettings(); + const float reach = std::min(settings.stride * static_cast(settings.max_steps), voxelGlassReflectionReach()); + settings.stride = settings.max_steps > 0 ? reach / static_cast(settings.max_steps) : settings.stride; + return settings; } [[nodiscard]] @@ -693,7 +722,7 @@ class VulkanRenderer { return m_voxel_glass_shadow_reach.load(std::memory_order_relaxed); } - /// Scene colour and depth copied after the sky for glass to refract + /// Scene colour copied after the sky that glass reflections and bloom read behind glass [[nodiscard]] auto getGlassBackdropView() const noexcept -> vk::ImageView { return m_glass_backdrop.view ? **m_glass_backdrop.view : vk::ImageView {}; @@ -709,6 +738,22 @@ class VulkanRenderer { return m_glass_backdrop_depth.view ? **m_glass_backdrop_depth.view : vk::ImageView {}; } + /// Nearest voxel glass surface over the opaque depth, valid on frames the glass pre-pass ran + [[nodiscard]] + auto getGlassNearestDepthView() const noexcept -> vk::ImageView { + return m_glass_nearest_depth.view ? **m_glass_nearest_depth.view : vk::ImageView {}; + } + + [[nodiscard]] + auto getGlassNearestNormalView() const noexcept -> vk::ImageView { + return m_glass_nearest_normal.view ? **m_glass_nearest_normal.view : vk::ImageView {}; + } + + [[nodiscard]] + auto getGlassNearestMotionView() const noexcept -> vk::ImageView { + return m_glass_nearest_motion.view ? **m_glass_nearest_motion.view : vk::ImageView {}; + } + /// Depth before glass so GI and reflections see behind a pane and the final depth when no backdrop was copied [[nodiscard]] auto getOpaqueDepthView() const noexcept -> vk::ImageView { @@ -894,6 +939,11 @@ class VulkanRenderer { void setDebrisPass(DebrisPass* pass) noexcept { m_debris_pass = pass; } + [[nodiscard]] + auto getDebrisPass() const noexcept -> const DebrisPass* { + return m_debris_pass; + } + void setGiPass(GiPass* pass) noexcept { m_gi_pass = pass; } void setGiClipmapPass(GiClipmapPass* pass) noexcept { m_gi_clipmap_pass = pass; } @@ -918,6 +968,16 @@ class VulkanRenderer { return m_traced_specular_frame; } + [[nodiscard]] + auto ssrFrame() const noexcept -> bool { + return m_ssr_frame; + } + + [[nodiscard]] + auto glassBackdropCaptured() const noexcept -> bool { + return m_glass_backdrop_captured; + } + [[nodiscard]] auto giPass() const noexcept -> GiPass* { return m_gi_pass; @@ -1335,7 +1395,7 @@ class VulkanRenderer { /// @note Expects an open rendering scope with m_pass_mutex held /// Opaque meshes then the sky then blended meshes and voxel glass far to near - /// @p capture_backdrop ends the world scope copies the scene for refracting glass and resumes it + /// @p capture_backdrop ends the world scope copies the scene behind glass and resumes it void recordMeshScene( vk::CommandBuffer cmd, uint32_t image_index, bool voxel_glass, const std::function& capture_backdrop ); @@ -1433,6 +1493,7 @@ class VulkanRenderer { std::unique_ptr m_output_target; std::vector> m_render_passes; + std::vector> m_retiring_passes; std::vector> m_compute_passes; std::vector> m_post_process_passes; @@ -1475,6 +1536,7 @@ class VulkanRenderer { GiPass* m_gi_pass = nullptr; GiClipmapPass* m_gi_clipmap_pass = nullptr; bool m_glass_backdrop_captured = false; + bool m_glass_nearest_valid = false; mutable std::mutex m_detail_mutex; assets::Handle m_voxel_detail_project; @@ -1491,6 +1553,9 @@ class VulkanRenderer { TracedSpecularPass* m_traced_specular_pass = nullptr; TaaPass* m_taa_pass = nullptr; bool m_traced_specular_frame = false; + bool m_ssr_frame = false; + /// DebrisPass::prepare result, run before the shadow pass so both draw the same step + bool m_debris_prepared = false; std::atomic_bool m_probe_bake_requested {false}; std::atomic m_probe_stale_count {0}; @@ -1502,11 +1567,14 @@ class VulkanRenderer { /// Only below render scale 1 DepthResources m_output_depth; DepthResources m_glass_backdrop_depth; + DepthResources m_glass_nearest_depth; static constexpr vk::Format m_scene_color_format = vk::Format::eR16G16B16A16Sfloat; SceneColorResources m_scene_color; SceneColorResources m_glass_backdrop; SceneColorResources m_glass_mask; + SceneColorResources m_glass_nearest_normal; + SceneColorResources m_glass_nearest_motion; SceneColorResources m_glass_backdrop_normal; static constexpr vk::Format m_scene_normal_format = renderer::k_scene_normal_format; @@ -1523,6 +1591,8 @@ class VulkanRenderer { SceneColorResources m_voxel_face_normal; SceneColorResources m_voxel_detail_normal; SceneColorResources m_voxel_noisy_diffuse; + SceneColorResources m_voxel_denoised_indirect; + bool m_voxel_denoised_indirect_frame = false; /// Half the render extent SceneColorResources m_voxel_gi; SceneColorResources m_voxel_noisy_specular; @@ -1554,11 +1624,11 @@ class VulkanRenderer { std::atomic m_volumetric_distance {100.0f}; std::atomic m_voxel_specular_roughness {0.6f}; std::atomic m_voxel_specular_reach {32.0f}; - std::atomic m_voxel_glass_refraction {1.0f}; - std::atomic_bool m_voxel_glass_refraction_enabled {true}; - std::atomic m_voxel_glass_refraction_distance {60.0f}; - std::atomic m_voxel_glass_refraction_voxels {32}; std::atomic m_voxel_glass_lit_surfaces {4}; + std::atomic m_voxel_glass_reflection_reach {32.0f}; + std::atomic m_glass_glow_scale {1.0f}; + std::atomic m_voxel_glass_coarse_distance {30.0f}; + std::atomic_bool m_glass_cost_view {false}; std::atomic_bool m_voxel_glass_shadows {true}; std::atomic m_display_sdr_white {2.5375f}; std::atomic m_display_hdr_headroom {1.0f}; @@ -1729,10 +1799,37 @@ class VulkanRenderer { /// Describes the newest storage whether published or pending so a patch starts from it VoxelScenePatcher m_voxel_patcher; - std::unordered_map m_voxel_previous_models; + /// Stamped with the proxy frame so entries are rewritten in place instead of reallocated every frame + struct VoxelDrawnModel { + glm::mat4 model {1.0f}; + uint64_t frame = 0; + }; + + std::unordered_map m_voxel_previous_models; /// Swaps into m_voxel_previous_models unless this frame is a probe capture - std::unordered_map m_voxel_drawn_models; + std::unordered_map m_voxel_drawn_models; + + /// Per volume math reused while its model and dims hold + struct VoxelProxyMath { + glm::mat4 model {1.0f}; + glm::mat4 inverse {1.0f}; + glm::vec4 sphere {0.0f}; + glm::uvec3 dims {0}; + uint32_t record = 0; + bool mirrored = false; + uint64_t frame = 0; + }; + + std::unordered_map m_voxel_proxy_math; + /// Scratch for the camera distance order of the voxel proxies + std::vector m_voxel_sort_order; + std::vector m_voxel_sorted; + uint64_t m_voxel_proxy_frame = 0; + + /// What the published collision world was built from so a still scene keeps it + const VoxelGpuStorage* m_voxel_collision_storage = nullptr; + size_t m_voxel_collision_count = 0; std::unordered_map m_mesh_previous_models; bool m_voxel_upload_failed_warned = false; @@ -1779,6 +1876,8 @@ class VulkanRenderer { float radius = 0.0f; glm::vec3 light_direction {0.0f}; uint32_t resolution = 0; + /// Padding the anchor had over its slice when it was fit + float slack = 0.0f; }; std::array m_cascade_anchors {}; diff --git a/engine/src/toast/renderer/vulkan_renderer_lights.cpp b/engine/src/toast/renderer/vulkan_renderer_lights.cpp index 1e676d0a7..a804f7cbe 100644 --- a/engine/src/toast/renderer/vulkan_renderer_lights.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_lights.cpp @@ -243,23 +243,50 @@ void VulkanRenderer::fitShadowViews( const glm::vec3 light_direction = glm::normalize(shadow_caster_direction); const uint32_t resolution = shadows::cascadeResolution(); const float padding = shadows::cascadePadding(); - float split_near = m_camera->near_plane; - uint32_t cascades_refit = 0; + // Each refit re-renders that cascade's static casters so a moving camera refits early and one cascade a frame + constexpr float k_early_refit_slack = 0.3f; + std::array slices {}; + std::array refit {}; + std::optional early; + float early_used = 0.0f; + bool forced = false; + float slice_near = m_camera->near_plane; for (uint32_t cascade = 0; cascade < shadows::k_cascade_count; ++cascade) { - const BoundingSphere slice = frustumSliceSphere(*m_camera, aspect, split_near, splits[cascade]); + slices[cascade] = frustumSliceSphere(*m_camera, aspect, slice_near, splits[cascade]); + slice_near = splits[cascade]; + const BoundingSphere& slice = slices[cascade]; + const CascadeAnchor& anchor = m_cascade_anchors[cascade]; // A zoom that leaves the padding far too large refits too + const float reach = glm::distance(anchor.center, slice.center) + slice.radius; + refit[cascade] = anchor.resolution != resolution || glm::dot(anchor.light_direction, light_direction) <= 0.99999f || + reach > anchor.radius || slice.radius * (1.0f + (2.0f * padding)) < anchor.radius; + forced = forced || refit[cascade]; + + // Fraction of the padding used past which the cascade may refit ahead of need + const float used = anchor.slack > 0.0f ? 1.0f - ((anchor.radius - reach) / anchor.slack) : 1.0f; + if (!refit[cascade] && used > 1.0f - k_early_refit_slack && used > early_used) { + early = cascade; + early_used = used; + } + } + if (!forced && early.has_value()) { + refit[*early] = true; + } + + float split_near = m_camera->near_plane; + uint32_t cascades_refit = 0; + for (uint32_t cascade = 0; cascade < shadows::k_cascade_count; ++cascade) { CascadeAnchor& anchor = m_cascade_anchors[cascade]; - const bool holds = anchor.resolution == resolution && glm::dot(anchor.light_direction, light_direction) > 0.99999f && - glm::distance(anchor.center, slice.center) + slice.radius <= anchor.radius && - slice.radius * (1.0f + (2.0f * padding)) >= anchor.radius; - if (!holds) { + if (refit[cascade]) { ++cascades_refit; + const BoundingSphere& slice = slices[cascade]; anchor = CascadeAnchor { .center = slice.center, .radius = slice.radius * (1.0f + padding), .light_direction = light_direction, .resolution = resolution, + .slack = slice.radius * padding, }; } const auto fit = fitDirectionalCascade(anchor.center, anchor.radius, light_direction, resolution); diff --git a/engine/src/toast/renderer/vulkan_renderer_record.cpp b/engine/src/toast/renderer/vulkan_renderer_record.cpp index 3228fb38a..07f2f2b69 100644 --- a/engine/src/toast/renderer/vulkan_renderer_record.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_record.cpp @@ -284,6 +284,8 @@ void VulkanRenderer::updateVoxelTraceScene() { m_trace_volumes.push_back(volume); } } + // The index is the TLAS custom index so a camera dependent order would rebuild the TLAS whenever the camera moves + std::ranges::sort(m_trace_volumes, {}, [](const VoxelTraceScene::Volume& volume) { return volume.instance.record_index; }); } m_voxel_trace_scene->update(m_current_frame, m_trace_volumes, render_frame->frame_data.camera_position, voxelTraceCellSize()); } @@ -420,15 +422,18 @@ void VulkanRenderer::recordMeshScene( // Before anything blended so the backdrop holds only opaque and sky const bool has_glass = voxel_glass && m_voxel_pass != nullptr && !m_voxel_pass->glassDraws().empty() && capture_backdrop; - const bool refract = has_glass && m_voxel_pass->refractsGlass(); - m_glass_backdrop_captured = has_glass; - if (refract || m_glass_backdrop_captured) { + // shortcut: copies whenever debris draws with SSR on since glass pieces are only known on the GPU, track live glass spawns if + // the copy shows up in captures + const bool debris_reflects = m_debris_prepared && m_ssr_frame && capture_backdrop; + m_glass_backdrop_captured = has_glass || debris_reflects; + m_glass_nearest_valid = false; + if (m_glass_backdrop_captured) { const GpuScope scope(m_gpu_timer.get(), m_current_frame, cmd, "Glass backdrop"); capture_backdrop(); } if (m_voxel_pass != nullptr) { - m_voxel_pass->setBackdropCaptured(refract); m_voxel_pass->setBackdropDepthValid(m_glass_backdrop_captured); + m_voxel_pass->setNearestGlassValid(m_glass_nearest_valid); } { @@ -495,6 +500,7 @@ void VulkanRenderer::recordMeshScene( // Last so the glass depth it writes never rejects a blended draw behind the glass if (!glass.empty()) { + const GpuScope surfaces_scope(m_gpu_timer.get(), m_current_frame, cmd, "Glass surfaces"); m_voxel_pass->recordGlassSurfaces(cmd, m_current_frame); } } @@ -506,13 +512,15 @@ auto VulkanRenderer::recordVoxelScopes( ) -> bool { ZoneScoped; m_traced_specular_frame = false; - const bool targets_ready = m_depth_resources.view.has_value() && m_voxel_albedo.view.has_value() && - m_voxel_material.view.has_value() && m_voxel_face_normal.view.has_value() && - m_voxel_detail_normal.view.has_value() && m_scene_color.view.has_value() && - m_scene_normal.view.has_value() && m_scene_indirect.view.has_value() && - m_scene_motion.view.has_value() && m_voxel_noisy_diffuse.view.has_value() && - m_voxel_noisy_specular.view.has_value() && m_voxel_reservoirs[0].view.has_value() && - m_voxel_reservoirs[1].view.has_value() && m_voxel_candidate_reservoirs.view.has_value(); + m_ssr_frame = false; + m_voxel_denoised_indirect_frame = false; + const bool targets_ready = + m_depth_resources.view.has_value() && m_voxel_denoised_indirect.view.has_value() && m_voxel_albedo.view.has_value() && + m_voxel_material.view.has_value() && m_voxel_face_normal.view.has_value() && m_voxel_detail_normal.view.has_value() && + m_scene_color.view.has_value() && m_scene_normal.view.has_value() && m_scene_indirect.view.has_value() && + m_scene_motion.view.has_value() && m_voxel_noisy_diffuse.view.has_value() && m_voxel_noisy_specular.view.has_value() && + m_voxel_reservoirs[0].view.has_value() && m_voxel_reservoirs[1].view.has_value() && + m_voxel_candidate_reservoirs.view.has_value(); if (m_voxel_pass == nullptr || !m_voxel_pass->isEnabled() || !targets_ready || m_depth_resources.state.usage != sync::Usage::depth_attachment || !m_voxel_pass->prepare(m_current_frame)) { return false; @@ -523,6 +531,9 @@ auto VulkanRenderer::recordVoxelScopes( m_traced_specular_pass->isReady() && voxelTracedSpecular() && specular_frame != nullptr && specular_frame->render_mode == 0 && specular_frame->probe_capture_index < 0 && specular_frame->irradiance_capture_index < 0; + // Read here since glass records under m_pass_mutex + m_ssr_frame = specular_frame != nullptr && specular_frame->render_mode == 0 && specular_frame->probe_capture_index < 0 && + specular_frame->irradiance_capture_index < 0 && isPostProcessPassEnabled("SSR"); const vk::CommandBuffer cmd = *frame.command_buffer; { @@ -531,8 +542,7 @@ auto VulkanRenderer::recordVoxelScopes( m_voxel_pass->recordCellCull(cmd, m_current_frame, scissor.extent); } - const bool debris_drawn = - m_debris_pass != nullptr && m_debris_pass->isEnabled() && m_debris_pass->prepare(cmd, m_current_frame); + const bool debris_drawn = m_debris_prepared; sync::BarrierBatch barriers; const auto attachment = [](const SceneColorResources& target, vk::AttachmentLoadOp load, const vk::ClearValue& clear) { @@ -833,8 +843,14 @@ auto VulkanRenderer::recordVoxelScopes( } barriers.image(m_scene_color.state, sync::Usage::color_attachment); + barriers.image(m_scene_indirect.state, sync::Usage::fragment_sampled); + barriers.image(m_voxel_denoised_indirect.state, sync::Usage::color_attachment); barriers.flush(cmd); - const std::array composite_attachments {attachment(m_scene_color, vk::AttachmentLoadOp::eLoad, clear_scene)}; + // Cleared so SSAO keeps the scene indirect wherever no lit voxel wrote the denoised one + const std::array composite_attachments { + attachment(m_scene_color, vk::AttachmentLoadOp::eLoad, clear_scene), + attachment(m_voxel_denoised_indirect, vk::AttachmentLoadOp::eClear, clear_zero), + }; vk::RenderingInfo composite_info {}; composite_info.renderArea = scissor; composite_info.layerCount = 1; @@ -850,6 +866,9 @@ auto VulkanRenderer::recordVoxelScopes( m_voxel_pass->recordDenoiseComposite(cmd, m_current_frame); } cmd.endRendering(); + barriers.image(m_voxel_denoised_indirect.state, sync::Usage::fragment_sampled); + barriers.flush(cmd); + m_voxel_denoised_indirect_frame = true; } else if (m_voxel_pass->marchedCompositeActive()) { barriers.image(m_voxel_noisy_diffuse.state, sync::Usage::fragment_sampled); barriers.image(m_voxel_noisy_specular.state, sync::Usage::fragment_sampled); @@ -873,6 +892,9 @@ auto VulkanRenderer::recordVoxelScopes( cmd.endRendering(); } + // SSAO binds it every frame and only reads it when the denoise composite wrote it + barriers.image(m_voxel_denoised_indirect.state, sync::Usage::fragment_sampled); + // The world scope loads all of these so writes above must land first barriers.image(m_scene_normal.state, sync::Usage::color_attachment); barriers.image(m_scene_color.state, sync::Usage::color_attachment); @@ -927,8 +949,13 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex recordAccelerationStructureBuilds(frame); } + // Before the shadow pass which casts the debris it acquires + m_debris_prepared = + m_debris_pass != nullptr && m_debris_pass->isEnabled() && m_debris_pass->prepare(*frame.command_buffer, m_current_frame); + { const GpuScope offscreen_scope(m_gpu_timer.get(), m_current_frame, *frame.command_buffer, "Off-screen"); + std::lock_guard lock(m_pass_mutex); for (auto& pass : m_render_passes) { const GpuScope scope(m_gpu_timer.get(), m_current_frame, *frame.command_buffer, pass->name()); pass->recordPre(*frame.command_buffer, m_current_frame, image_index); @@ -965,6 +992,14 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex barriers.image(m_glass_backdrop.state, sync::Usage::fragment_sampled); barriers.image(m_glass_backdrop_depth.state, sync::Usage::depth_sampled); } + if (m_glass_nearest_depth.image && m_glass_nearest_normal.image && m_glass_nearest_motion.image) { + barriers.image(m_glass_nearest_depth.state, sync::Usage::depth_sampled); + barriers.image(m_glass_nearest_normal.state, sync::Usage::fragment_sampled); + barriers.image(m_glass_nearest_motion.state, sync::Usage::fragment_sampled); + } + if (m_glass_mask.image) { + barriers.image(m_glass_mask.state, sync::Usage::fragment_sampled); + } barriers.flush(*frame.command_buffer); const vk::ClearValue clear_color(vk::ClearColorValue(std::array {0.0f, 0.0f, 0.0f, 1.0f})); @@ -1068,6 +1103,9 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex } const vk::CommandBuffer cmd = *frame.command_buffer; cmd.endRendering(); + const bool nearest = m_voxel_pass != nullptr && !m_voxel_pass->glassDraws().empty() && m_glass_nearest_depth.image && + m_glass_mask.view.has_value() && m_glass_nearest_normal.view.has_value() && + m_glass_nearest_motion.view.has_value(); sync::BarrierBatch to_copy; to_copy.image(m_scene_color.state, sync::Usage::transfer_src); @@ -1076,17 +1114,45 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex to_copy.image(m_glass_backdrop_depth.state, sync::Usage::transfer_dst); to_copy.image(m_scene_normal.state, sync::Usage::transfer_src); to_copy.image(m_glass_backdrop_normal.state, sync::Usage::transfer_dst); + if (nearest) { + to_copy.image(m_glass_nearest_depth.state, sync::Usage::transfer_dst); + } to_copy.flush(cmd); const vk::Extent3D copy_extent {render_extent.width, render_extent.height, 1}; const vk::ImageSubresourceLayers color_layers(vk::ImageAspectFlagBits::eColor, 0, 0, 1); const vk::ImageSubresourceLayers depth_layers(vk::ImageAspectFlagBits::eDepth, 0, 0, 1); + + // What glass covers with a margin for the TAA jitter, the whole image when it is unbounded + vk::Offset3D glass_offset {0, 0, 0}; + vk::Extent3D glass_extent = copy_extent; + if (const auto bounds = m_voxel_pass != nullptr ? m_voxel_pass->glassScreenBounds() : std::nullopt; bounds.has_value()) { + constexpr int32_t k_margin = 2; + const auto to_pixel = [](float ndc, uint32_t size) { + return static_cast(std::floor((ndc * 0.5f + 0.5f) * static_cast(size))); + }; + const int32_t x0 = + std::clamp(to_pixel(bounds->x, scene_extent.width) - k_margin, 0, static_cast(scene_extent.width)); + const int32_t y0 = + std::clamp(to_pixel(bounds->y, scene_extent.height) - k_margin, 0, static_cast(scene_extent.height)); + const int32_t x1 = + std::clamp(to_pixel(bounds->z, scene_extent.width) + k_margin + 1, 0, static_cast(scene_extent.width)); + const int32_t y1 = + std::clamp(to_pixel(bounds->w, scene_extent.height) + k_margin + 1, 0, static_cast(scene_extent.height)); + if (x1 > x0 && y1 > y0) { + glass_offset = vk::Offset3D {x0, y0, 0}; + glass_extent = vk::Extent3D {static_cast(x1 - x0), static_cast(y1 - y0), 1}; + } + } + // Glass reflections, voxel or debris, read the backdrop colour anywhere on screen + const bool whole_color = m_traced_specular_frame || m_ssr_frame; cmd.copyImage( scene_image, vk::ImageLayout::eTransferSrcOptimal, **m_glass_backdrop.image, vk::ImageLayout::eTransferDstOptimal, - vk::ImageCopy(color_layers, {}, color_layers, {}, copy_extent) + whole_color ? vk::ImageCopy(color_layers, {}, color_layers, {}, copy_extent) + : vk::ImageCopy(color_layers, glass_offset, color_layers, glass_offset, glass_extent) ); cmd.copyImage( **m_depth_resources.image, @@ -1103,6 +1169,64 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex vk::ImageLayout::eTransferDstOptimal, vk::ImageCopy(color_layers, {}, color_layers, {}, copy_extent) ); + if (nearest) { + // Only glass pixels read it and the surface copy keys off the mask cleared everywhere + cmd.copyImage( + **m_depth_resources.image, + vk::ImageLayout::eTransferSrcOptimal, + **m_glass_nearest_depth.image, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageCopy(depth_layers, glass_offset, depth_layers, glass_offset, glass_extent) + ); + + // Nearest glass over the opaque depth, near to far with early depth testing, and the mask bloom reads + sync::BarrierBatch to_nearest; + to_nearest.image(m_glass_nearest_depth.state, sync::Usage::depth_attachment); + to_nearest.image(m_glass_mask.state, sync::Usage::color_attachment); + to_nearest.image(m_glass_nearest_normal.state, sync::Usage::color_attachment); + to_nearest.image(m_glass_nearest_motion.state, sync::Usage::color_attachment); + to_nearest.flush(cmd); + + vk::RenderingAttachmentInfo nearest_mask {}; + nearest_mask.imageView = **m_glass_mask.view; + nearest_mask.imageLayout = vk::ImageLayout::eColorAttachmentOptimal; + nearest_mask.loadOp = vk::AttachmentLoadOp::eClear; + nearest_mask.storeOp = vk::AttachmentStoreOp::eStore; + nearest_mask.clearValue = vk::ClearValue(vk::ClearColorValue(std::array {0.0f, 0.0f, 0.0f, 0.0f})); + // Zero where no glass so the copy only reads what the pre-pass wrote + vk::RenderingAttachmentInfo nearest_normal = nearest_mask; + nearest_normal.imageView = **m_glass_nearest_normal.view; + vk::RenderingAttachmentInfo nearest_motion = nearest_mask; + nearest_motion.imageView = **m_glass_nearest_motion.view; + const std::array nearest_colors {nearest_mask, nearest_normal, nearest_motion}; + vk::RenderingAttachmentInfo nearest_depth {}; + nearest_depth.imageView = **m_glass_nearest_depth.view; + nearest_depth.imageLayout = vk::ImageLayout::eDepthAttachmentOptimal; + nearest_depth.loadOp = vk::AttachmentLoadOp::eLoad; + nearest_depth.storeOp = vk::AttachmentStoreOp::eStore; + vk::RenderingInfo nearest_info {}; + nearest_info.renderArea = scene_scissor; + nearest_info.layerCount = 1; + nearest_info.colorAttachmentCount = static_cast(nearest_colors.size()); + nearest_info.pColorAttachments = nearest_colors.data(); + nearest_info.pDepthAttachment = &nearest_depth; + { + const GpuScope scope(m_gpu_timer.get(), m_current_frame, cmd, "Glass nearest"); + cmd.beginRendering(nearest_info); + cmd.setViewport(0, std::array {scene_viewport}); + cmd.setScissor(0, std::array {scene_scissor}); + m_voxel_pass->recordGlassNearest(cmd, m_current_frame); + cmd.endRendering(); + } + + sync::BarrierBatch after_nearest; + after_nearest.image(m_glass_nearest_depth.state, sync::Usage::depth_sampled); + after_nearest.image(m_glass_mask.state, sync::Usage::fragment_sampled); + after_nearest.image(m_glass_nearest_normal.state, sync::Usage::fragment_sampled); + after_nearest.image(m_glass_nearest_motion.state, sync::Usage::fragment_sampled); + after_nearest.flush(cmd); + m_glass_nearest_valid = true; + } sync::BarrierBatch resume; resume.image(m_scene_color.state, sync::Usage::color_attachment); @@ -1152,43 +1276,24 @@ auto VulkanRenderer::recordFrame(FrameContext& frame, uint32_t image_index) noex frame.command_buffer.endRendering(); - // Glass mask - sync::BarrierBatch to_mask; - to_mask.image(m_glass_mask.state, sync::Usage::color_attachment); - to_mask.image(m_depth_resources.state, sync::Usage::depth_attachment); - to_mask.flush(*frame.command_buffer); - - vk::RenderingAttachmentInfo mask_color {}; - mask_color.imageView = **m_glass_mask.view; - mask_color.imageLayout = vk::ImageLayout::eColorAttachmentOptimal; - mask_color.loadOp = vk::AttachmentLoadOp::eClear; - mask_color.storeOp = vk::AttachmentStoreOp::eStore; - mask_color.clearValue = vk::ClearValue(vk::ClearColorValue(std::array {0.0f, 0.0f, 0.0f, 0.0f})); - - vk::RenderingAttachmentInfo mask_depth {}; - mask_depth.imageView = **m_depth_resources.view; - mask_depth.imageLayout = vk::ImageLayout::eDepthAttachmentOptimal; - mask_depth.loadOp = vk::AttachmentLoadOp::eLoad; // keep the glass depth from the scene - mask_depth.storeOp = vk::AttachmentStoreOp::eStore; // must be store - - vk::RenderingInfo mask_info {}; - mask_info.renderArea = scene_scissor; - mask_info.layerCount = 1; - mask_info.colorAttachmentCount = 1; - mask_info.pColorAttachments = &mask_color; - mask_info.pDepthAttachment = &mask_depth; - - frame.command_buffer.beginRendering(mask_info); - frame.command_buffer.setViewport(0, std::array {scene_viewport}); - frame.command_buffer.setScissor(0, std::array {scene_scissor}); - if (m_voxel_pass != nullptr) { - m_voxel_pass->recordGlassMask(*frame.command_buffer, m_current_frame); + // Glass mask, cleared here when the glass pre-pass did not write it + if (!m_glass_nearest_valid) { + sync::transition(*frame.command_buffer, m_glass_mask.state, sync::Usage::color_attachment); + vk::RenderingAttachmentInfo mask_color {}; + mask_color.imageView = **m_glass_mask.view; + mask_color.imageLayout = vk::ImageLayout::eColorAttachmentOptimal; + mask_color.loadOp = vk::AttachmentLoadOp::eClear; + mask_color.storeOp = vk::AttachmentStoreOp::eStore; + mask_color.clearValue = vk::ClearValue(vk::ClearColorValue(std::array {0.0f, 0.0f, 0.0f, 0.0f})); + vk::RenderingInfo mask_info {}; + mask_info.renderArea = scene_scissor; + mask_info.layerCount = 1; + mask_info.colorAttachmentCount = 1; + mask_info.pColorAttachments = &mask_color; + frame.command_buffer.beginRendering(mask_info); + frame.command_buffer.endRendering(); + sync::transition(*frame.command_buffer, m_glass_mask.state, sync::Usage::fragment_sampled); } - frame.command_buffer.endRendering(); - - sync::BarrierBatch after_mask; - after_mask.image(m_glass_mask.state, sync::Usage::fragment_sampled); - after_mask.flush(*frame.command_buffer); // PROBE and Iradiance capture @@ -1603,6 +1708,11 @@ auto VulkanRenderer::drawFrame(RenderFrame& frame_data) -> bool { pass->update(m_current_frame, Time::renderDelta()); any_unbuilt_material = any_unbuilt_material || !pass->isValid(); } + // After this frame's fence wait so the frames still in flight finish before the pass is freed + for (auto& pass : m_retiring_passes) { + retire(std::move(pass)); + } + m_retiring_passes.clear(); for (auto& pass : m_render_passes) { pass->update(m_current_frame, Time::renderDelta()); } diff --git a/engine/src/toast/renderer/vulkan_renderer_resources.cpp b/engine/src/toast/renderer/vulkan_renderer_resources.cpp index 306ce78d3..e40fa4d7e 100644 --- a/engine/src/toast/renderer/vulkan_renderer_resources.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_resources.cpp @@ -257,9 +257,22 @@ auto VulkanRenderer::createDepthResources() -> void { setDebugName(*m_core, **m_glass_backdrop_depth.view, "VulkanRenderer GlassBackdropDepthView"); m_glass_backdrop_depth.state.reset(**m_glass_backdrop_depth.image, depthAttachmentRange(m_depth_format)); + m_glass_nearest_depth.view.reset(); + m_glass_nearest_depth.image.reset(); + vk::ImageCreateInfo nearest_ci = image_ci; + nearest_ci.usage = + vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst; + m_glass_nearest_depth.image.emplace(m_core->getAllocator().createImage(nearest_ci, allocation_ci)); + setDebugName(*m_core, **m_glass_nearest_depth.image, "VulkanRenderer GlassNearestDepthImage"); + vk::ImageViewCreateInfo nearest_view_ci = backdrop_view_ci; + nearest_view_ci.image = **m_glass_nearest_depth.image; + m_glass_nearest_depth.view.emplace(m_core->getDevice(), nearest_view_ci); + setDebugName(*m_core, **m_glass_nearest_depth.view, "VulkanRenderer GlassNearestDepthView"); + m_glass_nearest_depth.state.reset(**m_glass_nearest_depth.image, depthAttachmentRange(m_depth_format)); + auto depth_image = m_core->getAllocator().createImage(image_ci, allocation_ci); m_depth_resources.image.emplace(std::move(depth_image)); - setDebugName(*m_core, **m_depth_resources.image, "VulkanRenderer DepthImage"); + setDebugName(*m_core, **m_depth_resources.image, "VulkanRenderer FuckingDepthImage"); vk::ImageViewCreateInfo view_ci {}; view_ci.image = **m_depth_resources.image; @@ -329,7 +342,10 @@ void VulkanRenderer::createSceneColorResources() { create(m_scene_color, m_scene_color_format, "SceneColor", vk::ImageUsageFlagBits::eTransferSrc); create(m_glass_backdrop, m_scene_color_format, "GlassBackdrop", vk::ImageUsageFlagBits::eTransferDst); - create(m_glass_mask, vk::Format::eR8Unorm, "GlassMask"); + // r covered g share of light the nearest glass lets through + create(m_glass_mask, vk::Format::eR8G8Unorm, "GlassMask"); + create(m_glass_nearest_normal, m_scene_normal_format, "GlassNearestNormal"); + create(m_glass_nearest_motion, m_scene_motion_format, "GlassNearestMotion"); create(m_scene_normal, m_scene_normal_format, "SceneNormal", vk::ImageUsageFlagBits::eTransferSrc); create(m_glass_backdrop_normal, m_scene_normal_format, "GlassBackdropNormal", vk::ImageUsageFlagBits::eTransferDst); create(m_scene_indirect, m_scene_indirect_format, "SceneIndirect"); @@ -339,6 +355,7 @@ void VulkanRenderer::createSceneColorResources() { create(m_voxel_face_normal, k_voxel_face_normal_format, "VoxelFaceNormal"); create(m_voxel_detail_normal, k_voxel_face_normal_format, "VoxelDetailNormal"); create(m_voxel_noisy_diffuse, k_voxel_noisy_format, "VoxelNoisyDiffuse"); + create(m_voxel_denoised_indirect, k_voxel_denoised_indirect_format, "VoxelDenoisedIndirect"); create(m_voxel_noisy_specular, k_voxel_noisy_format, "VoxelNoisySpecular"); create(m_voxel_gi, k_voxel_gi_format, "VoxelGi", {}, 2); create(m_voxel_reservoirs[0], k_voxel_reservoir_format, "VoxelReservoirs0"); diff --git a/engine/src/toast/renderer/vulkan_renderer_scene.cpp b/engine/src/toast/renderer/vulkan_renderer_scene.cpp index 7cc3211e5..aa817b0d2 100644 --- a/engine/src/toast/renderer/vulkan_renderer_scene.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_scene.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -1340,9 +1341,18 @@ void VulkanRenderer::cullAndBuildInstances(RenderFrame& frame) { proxy.view_distance = std::max(glm::distance(eye, proxy.bounds_center) - proxy.bounds_radius, 0.0f); } - std::ranges::stable_sort(frame.voxel_instances, [](const VoxelVolumeProxy& a, const VoxelVolumeProxy& b) { - return a.view_distance < b.view_distance; - }); + // Proxies are big so the order is sorted as indices and applied in one gather, and a still camera skips it + if (!std::ranges::is_sorted(frame.voxel_instances, {}, &VoxelVolumeProxy::view_distance)) { + m_voxel_sort_order.resize(frame.voxel_instances.size()); + std::iota(m_voxel_sort_order.begin(), m_voxel_sort_order.end(), 0u); + std::ranges::stable_sort(m_voxel_sort_order, {}, [&](uint32_t index) { return frame.voxel_instances[index].view_distance; }); + m_voxel_sorted.clear(); + m_voxel_sorted.reserve(frame.voxel_instances.size()); + for (const uint32_t index : m_voxel_sort_order) { + m_voxel_sorted.push_back(frame.voxel_instances[index]); + } + frame.voxel_instances.swap(m_voxel_sorted); + } std::ranges::stable_sort(frame.mesh_instances, [](const MeshInstanceProxy& a, const MeshInstanceProxy& b) { if (a.root_material != b.root_material) { diff --git a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp index 54f6b9505..492a0d9d8 100644 --- a/engine/src/toast/renderer/vulkan_renderer_voxel.cpp +++ b/engine/src/toast/renderer/vulkan_renderer_voxel.cpp @@ -197,7 +197,10 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { const voxel::Volume* volume; const voxel::Palette* palette; glm::mat4 model; - std::string debug_name; + /// Node name and the suffix are only joined when a pack needs the debug rows + std::string_view debug_name; + std::string_view debug_suffix; + uint32_t fragment_slot = ~0u; bool data_only = false; uint64_t highlight_id = 0; const toast::VoxelNode* node = nullptr; @@ -251,7 +254,7 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { .volume = part.volume.get(), .palette = parts_palette, .model = *owner_transform * physics::Simulator::renderPoseDelta(part) * pose * part.localTransform(), - .debug_name = std::string{node->name()}, + .debug_name = node->name(), .node = node, .part_key = part.key, .outline_id = node->rid() @@ -283,7 +286,7 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { .volume = volume, .palette = palette, .model = *owner_transform * physics::Simulator::renderPoseDelta(*node) * node->getWorldTransform() * node->volumeLocalTransform(), - .debug_name = std::string{node->name()}, + .debug_name = node->name(), .node = node }); key.push_back({ @@ -312,7 +315,8 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { .volume = it->second, .palette = gathered[i].palette, .model = gathered[i].model, - .debug_name = gathered[i].debug_name + " highlight", + .debug_name = gathered[i].debug_name, + .debug_suffix = " highlight", .data_only = true, }); key.push_back( @@ -325,14 +329,35 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { } } + // Fragments of one blast share an origin and part entries repeat their node so each origin is checked once per node + std::vector> origin_owned; + const auto owned_by_gathered = [&](physics::BodyID origin) { + if (const auto known = std::ranges::find(origin_owned, origin, &std::pair::first); + known != origin_owned.end()) { + return known->second; + } + bool owned = false; + const toast::VoxelNode* checked = nullptr; + for (const Gathered& g : gathered) { + if (g.node == nullptr || g.node == checked) { + continue; + } + checked = g.node; + if (g.node->ownsBody(origin)) { + owned = true; + break; + } + } + origin_owned.emplace_back(origin, owned); + return owned; + }; + for (const physics::VoxelRenderRecord& record : physics::Simulator::voxelFragmentRecords()) { if (record.volume == nullptr) { continue; } - if (record.fragment_origin != physics::BodyID {} && std::ranges::none_of(gathered, [&](const Gathered& g) { - return g.node != nullptr && g.node->ownsBody(record.fragment_origin); - })) { + if (record.fragment_origin != physics::BodyID {} && !owned_by_gathered(record.fragment_origin)) { // do not leak voxel shit to other voxel shit continue; } @@ -341,7 +366,14 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { const uint64_t id = voxelFragmentRenderId(record.shape); const glm::mat4 drawn_transform = physics::Simulator::renderPoseDelta(record.body) * record.transform; - gathered.push_back({id, record.volume, palette, drawn_transform, "Voxel fragment " + std::to_string(record.shape.slot)}); + gathered.push_back( + {.id = id, + .volume = record.volume, + .palette = palette, + .model = drawn_transform, + .debug_name = "Voxel fragment ", + .fragment_slot = record.shape.slot} + ); key.push_back( {.node_rid = id, .revision = record.revision, @@ -392,7 +424,12 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { scene_volumes.push_back({.volume = entry.volume, .palette = entry.palette}); node_rids.push_back(entry.id); brick_dims.push_back(entry.volume->brickDims()); - debug.node_names.emplace_back(entry.debug_name); + std::string name {entry.debug_name}; + name += entry.debug_suffix; + if (entry.fragment_slot != ~0u) { + name += std::to_string(entry.fragment_slot); + } + debug.node_names.push_back(std::move(name)); } const auto pack_start = std::chrono::steady_clock::now(); @@ -509,6 +546,9 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { if (!m_voxel_storage) { m_voxel_previous_models.clear(); m_voxel_drawn_models.clear(); + m_voxel_proxy_math.clear(); + m_voxel_collision_storage = nullptr; + m_voxel_collision_count = 0; std::scoped_lock lock(m_voxel_collision_mutex); m_voxel_collision_world.reset(); return; @@ -520,9 +560,10 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { return record.has_value() ? *record + 1u : 0u; }; - std::unordered_map drawn_models; - drawn_models.reserve(gathered.size()); + // Existing keys are rewritten in place so a steady scene allocates nothing here + const uint64_t proxy_frame = ++m_voxel_proxy_frame; frame.voxel_instances.reserve(gathered.size()); + bool collision_changed = m_voxel_collision_storage != m_voxel_storage.get(); for (const Gathered& entry : gathered) { const uint64_t node_rid = entry.id; @@ -535,30 +576,58 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { } const glm::uvec3 dims = m_voxel_storage->recordBrickDims(*record); - const glm::mat4 model = entry.model; - const glm::vec4 sphere = voxel::worldBoundingSphere(model, dims); + const glm::mat4& model = entry.model; + auto [math_it, inserted] = m_voxel_proxy_math.try_emplace(node_rid); + VoxelProxyMath& math = math_it->second; + if (inserted || math.model != model || math.dims != dims || math.record != *record) { + math.model = model; + math.inverse = glm::inverse(model); + math.sphere = voxel::worldBoundingSphere(model, dims); + math.dims = dims; + math.record = *record; + math.mirrored = glm::determinant(model) < 0.0f; + collision_changed = true; + } + math.frame = proxy_frame; + const auto previous = m_voxel_previous_models.find(node_rid); const bool has_previous = previous != m_voxel_previous_models.end(); frame.voxel_instances.push_back( VoxelVolumeProxy { .model = model, - .inverse_model = glm::inverse(model), - .previous_model = has_previous ? previous->second : model, + .inverse_model = math.inverse, + .previous_model = has_previous ? previous->second.model : model, .node_rid = node_rid, .brick_dims = dims, .record_index = *record, - .bounds_center = glm::vec3(sphere), - .bounds_radius = sphere.w, + .bounds_center = glm::vec3(math.sphere), + .bounds_radius = math.sphere.w, .highlight_record = highlight_record_of(entry.highlight_id), .has_previous = has_previous, - .mirrored = glm::determinant(model) < 0.0f, + .mirrored = math.mirrored, .outlined = isOutlined(entry.outline_id != 0 ? entry.outline_id : node_rid), } ); - drawn_models.insert_or_assign(node_rid, model); + m_voxel_drawn_models.insert_or_assign(node_rid, VoxelDrawnModel {.model = model, .frame = proxy_frame}); } + // Only sweeps when something left since a full walk costs as much as the frame saved + const size_t drawn = frame.voxel_instances.size(); + if (m_voxel_drawn_models.size() > drawn) { + std::erase_if(m_voxel_drawn_models, [&](const auto& item) { return item.second.frame != proxy_frame; }); + } + if (m_voxel_proxy_math.size() > drawn) { + std::erase_if(m_voxel_proxy_math, [&](const auto& item) { return item.second.frame != proxy_frame; }); + } + + collision_changed = collision_changed || m_voxel_collision_count != drawn; + if (!collision_changed) { + return; + } + m_voxel_collision_storage = m_voxel_storage.get(); + m_voxel_collision_count = drawn; + auto collision = std::make_shared(); collision->storage = m_voxel_storage; collision->volumes.reserve(frame.voxel_instances.size()); @@ -587,12 +656,8 @@ void VulkanRenderer::buildVoxelProxies(RenderFrame& frame) { } ); } - { - std::scoped_lock lock(m_voxel_collision_mutex); - m_voxel_collision_world = std::move(collision); - } - - m_voxel_drawn_models = std::move(drawn_models); + std::scoped_lock lock(m_voxel_collision_mutex); + m_voxel_collision_world = std::move(collision); } } diff --git a/engine/src/toast/scripting/lua_event.cpp b/engine/src/toast/scripting/lua_event.cpp index e07dfb47c..0928a86a7 100644 --- a/engine/src/toast/scripting/lua_event.cpp +++ b/engine/src/toast/scripting/lua_event.cpp @@ -121,6 +121,15 @@ auto readEventPrimitive(lua_State* state, int index, toast::Box& ou out = {}; return true; } + // A script's `self` is a table bound to its node, accept it like signals do + if (lua_istable(state, index)) { + const NodeProxy node = nodeOfSelfTable(luabridge::LuaRef::fromStack(state, index)); + if (!node.exists()) { + return false; + } + out = node.box(); + return true; + } auto result = luabridge::Stack::get(state, index); if (!result) { return false; diff --git a/engine/src/toast/scripting/lua_state.cpp b/engine/src/toast/scripting/lua_state.cpp index 528a20a49..59133724a 100644 --- a/engine/src/toast/scripting/lua_state.cpp +++ b/engine/src/toast/scripting/lua_state.cpp @@ -702,8 +702,6 @@ void LuaState::registerApi(lua_State* state) noexcept { .addProperty("r", &Vec3FieldProxy::getX, &Vec3FieldProxy::setX) .addProperty("g", &Vec3FieldProxy::getY, &Vec3FieldProxy::setY) .addProperty("b", &Vec3FieldProxy::getZ, &Vec3FieldProxy::setZ) - // Lua looks up operator metamethods raw on the object's own metatable, so deriveClass doesn't inherit them from vec3 - // LuaBridge needs the first parameter to be the exact class; the base glm::vec3 is kept in sync by commit() .addFunction("__add", [](const Vec3FieldProxy& a, const glm::vec3& b) -> glm::vec3 { return glm::vec3(a) + b; }) .addFunction("__sub", [](const Vec3FieldProxy& a, const glm::vec3& b) -> glm::vec3 { return glm::vec3(a) - b; }) .addFunction( diff --git a/engine/src/toast/voxel/runtime_pool.hpp b/engine/src/toast/voxel/runtime_pool.hpp index 7f97b0193..64e9ceb1b 100644 --- a/engine/src/toast/voxel/runtime_pool.hpp +++ b/engine/src/toast/voxel/runtime_pool.hpp @@ -14,7 +14,7 @@ namespace voxel { -inline constexpr uint32_t k_runtime_brick_capacity = 1u << 16; +inline constexpr uint32_t k_runtime_brick_capacity = 1u << 18; /// @note Main thread only [[nodiscard]]