diff --git a/AGENTS.md b/AGENTS.md index 0effc8c9..0aa871e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,9 +47,10 @@ platform setup (Vulkan SDK, GLFW, etc.). `--exec direct|inline|threaded`, `--sim-hz N`, `--max-fps N` (0: no cap), `--vsync on|off` (on by default), `--interpolation on|off` (on by default), `--frustum-culling on|off` (on by default) and - `--occlusion-culling on|off` (on by default) override, as do - `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, - `FrustumCulling` and `OcclusionCulling` in + `--occlusion-culling on|off` (on by default) and `--gpu-blend on|off` (on by default; + the GPU makes the matrix of a mesh between two ticks, and needs occlusion culling) + override, as do `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, + `FrustumCulling`, `OcclusionCulling` and `GpuBlend` in `Config/EngineConf.ini`. A test that depends on a mode or a rate sets it. The startup log line `Run settings: ...` says each value and where it came from. The editor's GPU Options window (menu Windows; drawn in `--play` too) changes diff --git a/Assets/Shaders/Deferred/mrt.vert b/Assets/Shaders/Deferred/mrt.vert index 8e1f2cf8..435d7e7f 100644 --- a/Assets/Shaders/Deferred/mrt.vert +++ b/Assets/Shaders/Deferred/mrt.vert @@ -7,13 +7,20 @@ layout(location = 2) in vec3 inTangent; layout(location = 3) in vec3 inNormal; layout(location = 4) in vec2 inUV; -// Per object data. Only written when the object's transform changes. +// Per object data: the object's slot, written once when the object is made layout (binding = 0) uniform UBO { - mat4 model; - vec3 objPos; + uint slot; } ubo; +// The world matrix of every object, by slot. The CPU writes the matrix of an object that is +// still, or when the GPU blend is off; the cull compute shader writes the matrix of an object that +// moves between two ticks (Occlusion/cull.comp), before this shader runs. +layout (std430, binding = 6) readonly buffer WorldMatrices +{ + mat4 worlds[]; +} world; + // Camera data shared by every object, written once per frame layout (binding = 5) uniform CameraUBO { @@ -41,9 +48,10 @@ void main() // Currently just vertex color outColor = inColor; - outWorldPos = (ubo.model * vec4(inPos, 1.0)).rgb; - outNormal = mat3(ubo.model) * normalize(inNormal); + const mat4 model = world.worlds[ubo.slot]; + outWorldPos = (model * vec4(inPos, 1.0)).rgb; + outNormal = mat3(model) * normalize(inNormal); gl_Position = cam.projection * cam.view * vec4(outWorldPos, 1.0); - outTangent = normalize( inTangent * mat3(ubo.model) ); + outTangent = normalize( inTangent * mat3(model) ); } diff --git a/Assets/Shaders/Occlusion/cull.comp b/Assets/Shaders/Occlusion/cull.comp index ff803a95..77d3ce29 100644 --- a/Assets/Shaders/Occlusion/cull.comp +++ b/Assets/Shaders/Occlusion/cull.comp @@ -1,6 +1,10 @@ #version 450 // Occlusion culling of the G-buffer pass, two phases (see OcclusionCuller.h). +// Before the tests, each slot that moves between two ticks gets its world matrix here, from the +// two ends of its Transform and the frame's blend factor (the same as Interpolate::Blend and +// TransformUtil::LocalMatrix), and is tested against the view volume (Frustum::Intersects). +// The G-buffer vertex shader reads the matrices from the same buffer. // Phase 0: the meshes that were visible last frame and are in the view get the first draw. // Phase 1: every mesh in the view is tested against the depth pyramid of that first draw. A // mesh that is not hidden and was not drawn yet gets the second draw. @@ -10,11 +14,19 @@ layout(local_size_x = 64) in; struct Slot { - mat4 World; vec4 BoundsMin; vec4 BoundsMax; - // x: index count (0: nothing to draw), y: bit 0 in the view, bit 1 has bounds + // x: index count (0: nothing to draw) + // y: bit 0 in the view (decided by the CPU), bit 1 has bounds, bit 2 moves between two ticks (this + // shader makes the world matrix), bit 3 this shader decides if it is in the view uvec4 Info; + // The Transform at the two ticks: xyz position, a quaternion (x, y, z, w), xyz scale + vec4 FromPos; + vec4 FromRot; + vec4 FromScale; + vec4 ToPos; + vec4 ToRot; + vec4 ToScale; }; struct DrawCmd @@ -31,22 +43,118 @@ layout(std140, set = 0, binding = 0) uniform Params mat4 ViewProjection; // x: slot count uvec4 Counts; + // x: the blend factor of this frame, from 0 to 1 + vec4 Blend; + // The view volume: n pointing in, a point p is inside when dot(n, p) + d >= 0 (Frustum) + vec4 Planes[6]; } u; layout(std430, set = 0, binding = 1) readonly buffer Slots { Slot slots[]; }; layout(std430, set = 0, binding = 2) writeonly buffer Draw1 { DrawCmd draw1[]; }; layout(std430, set = 0, binding = 3) writeonly buffer Draw2 { DrawCmd draw2[]; }; layout(std430, set = 0, binding = 4) buffer Visible { uint visible[]; }; -layout(std430, set = 0, binding = 5) buffer Stats { uint occluded; } stats; +layout(std430, set = 0, binding = 5) buffer Stats { uint occluded; uint frustumCulled; } stats; layout(set = 0, binding = 6) uniform sampler2D uPyramid; +layout(std430, set = 0, binding = 7) buffer Worlds { mat4 worlds[]; }; layout(push_constant) uniform Phase { uint Value; } phase; const float DepthBias = 1.0e-5; -bool IsOccluded(const Slot slot) +const uint InViewBit = 1u; +const uint HasBoundsBit = 2u; +const uint BlendBit = 4u; +const uint TestFrustumBit = 8u; + +// Interpolate::Slerp: a at t <= 0, b at t >= 1, the shorter way around between them +vec4 SlerpQuat(vec4 a, vec4 b, float t) { - const mat4 mvp = u.ViewProjection * slot.World; + if (t <= 0.0) + { + return a; + } + if (t >= 1.0) + { + return b; + } + const vec4 sameSide = dot(a, b) < 0.0 ? -b : b; + const float cosTheta = dot(a, sameSide); + vec4 q; + if (cosTheta > 1.0 - 1.0e-6) + { + // glm::slerp: nearly the same rotation, a straight line + q = mix(a, sameSide, t); + } + else + { + const float angle = acos(cosTheta); + q = (sin((1.0 - t) * angle) * a + sin(t * angle) * sameSide) / sin(angle); + } + return normalize(q); +} + +// Interpolate::Lerp +vec3 LerpVec(vec3 a, vec3 b, float t) +{ + if (t <= 0.0) + { + return a; + } + if (t >= 1.0) + { + return b; + } + return a + (b - a) * t; +} + +// TransformUtil::LocalMatrix: translate * rotate * scale +mat4 LocalMatrix(vec3 position, vec4 q, vec3 scale) +{ + const float xx = q.x * q.x; + const float yy = q.y * q.y; + const float zz = q.z * q.z; + const float xy = q.x * q.y; + const float xz = q.x * q.z; + const float yz = q.y * q.z; + const float wx = q.w * q.x; + const float wy = q.w * q.y; + const float wz = q.w * q.z; + return mat4(vec4(1.0 - 2.0 * (yy + zz), 2.0 * (xy + wz), 2.0 * (xz - wy), 0.0) * scale.x, + vec4(2.0 * (xy - wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz + wx), 0.0) * scale.y, + vec4(2.0 * (xz + wy), 2.0 * (yz - wx), 1.0 - 2.0 * (xx + yy), 0.0) * scale.z, + vec4(position, 1.0)); +} + +mat4 BlendWorld(const Slot slot, float t) +{ + return LocalMatrix(LerpVec(slot.FromPos.xyz, slot.ToPos.xyz, t), + SlerpQuat(slot.FromRot, slot.ToRot, t), + LerpVec(slot.FromScale.xyz, slot.ToScale.xyz, t)); +} + +// Frustum::Intersects: the world box around the placed local box, against the six planes +bool InFrustum(const Slot slot, const mat4 world) +{ + const vec3 localCentre = (slot.BoundsMin.xyz + slot.BoundsMax.xyz) * 0.5; + const vec3 localExtents = (slot.BoundsMax.xyz - slot.BoundsMin.xyz) * 0.5; + const vec3 centre = (world * vec4(localCentre, 1.0)).xyz; + const vec3 extents = abs(world[0].xyz) * localExtents.x + abs(world[1].xyz) * localExtents.y + + abs(world[2].xyz) * localExtents.z; + for (uint i = 0; i < 6; ++i) + { + const vec3 n = u.Planes[i].xyz; + const float reach = dot(abs(n), extents); + if (dot(n, centre) + u.Planes[i].w + reach < 0.0) + { + return false; + } + } + return true; +} + +bool IsOccluded(const Slot slot, const mat4 world) +{ + const mat4 mvp = u.ViewProjection * world; vec2 uvMin = vec2(1.0e30); vec2 uvMax = vec2(-1.0e30); float nearest = 1.0e30; @@ -106,7 +214,21 @@ void main() const Slot slot = slots[s]; const uint indexCount = slot.Info.x; - const bool inView = (slot.Info.y & 1u) != 0u && indexCount != 0u; + const uint flags = slot.Info.y; + + // The matrix of a slot that moves is made once, in phase 0, and read in phase 1 and by the vertex shader + if (phase.Value == 0u && (flags & BlendBit) != 0u && indexCount != 0u) + { + worlds[s] = BlendWorld(slot, u.Blend.x); + } + + bool inView = (flags & InViewBit) != 0u; + if ((flags & TestFrustumBit) != 0u) + { + // A slot with no bounds is always in view (Frustum::Intersects) + inView = ((flags & HasBoundsBit) == 0u) || InFrustum(slot, worlds[s]); + } + inView = inView && indexCount != 0u; const bool drawnFirst = inView && visible[s] != 0u; if (phase.Value == 0u) @@ -118,7 +240,7 @@ void main() bool hidden = false; if (inView && (slot.Info.y & 2u) != 0u) { - hidden = IsOccluded(slot); + hidden = IsOccluded(slot, worlds[s]); } const bool shown = inView && !hidden; draw2[s] = DrawCmd(indexCount, (shown && !drawnFirst) ? 1u : 0u, 0u, 0, 0u); @@ -127,4 +249,9 @@ void main() { atomicAdd(stats.occluded, 1u); } + if (!inView && (flags & TestFrustumBit) != 0u && indexCount != 0u) + { + // Outside the view: the CPU counts the slots that it tests itself + atomicAdd(stats.frustumCulled, 1u); + } } diff --git a/Docs/occlusion-culling.md b/Docs/occlusion-culling.md index 45bdda42..d59380d8 100644 --- a/Docs/occlusion-culling.md +++ b/Docs/occlusion-culling.md @@ -41,6 +41,14 @@ texels), and a small bias (`Occlusion::DepthBias`). A box that reaches the camer hidden. Both phases write every slot's command, so the recorded draw calls do not change from frame to frame. A resize makes the pyramid again (`OffscreenSubpass::OnSwapchainResized`). +## Blending on the GPU + +The same compute pass makes the world matrix of a mesh that moves between two ticks +(`Plans/gpu-blend.md`). Its slot holds the two `Transform` values (`OcclusionSlot::From*`, `To*`) +and the frame's blend factor is in the parameters. Phase 0 writes the matrix into the world matrix +buffer, which the G-buffer vertex shader reads, and tests the mesh against the frustum, since the +CPU has no matrix for it. `--gpu-blend off`, or occlusion culling off, makes the CPU do it. + ## The CPU twin `Occlusion::ProjectBounds`, `Occlusion::IsOccluded` and `DepthPyramid` (`OcclusionTest.h`) do the diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 1ae94c6b..3ede446c 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -717,6 +717,7 @@ namespace Fling VulkanApp::Get().SetVSync(m_Controls->VSync()); VulkanApp::Get().SetFrustumCulling(m_Controls->FrustumCulling()); VulkanApp::Get().SetOcclusionCulling(m_Controls->OcclusionCulling()); + VulkanApp::Get().SetGpuBlend(m_Controls->GpuBlend()); FLING_PROFILE_SCOPE("Frame.Present"); VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage()); diff --git a/FlingEngine/Core/inc/LaunchOptions.h b/FlingEngine/Core/inc/LaunchOptions.h index 0a8ce922..b585ad3d 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -81,6 +81,8 @@ namespace Fling * --occlusion-culling on|off * Skip the meshes that other meshes hide (on) or draw every mesh * (off). Overrides [Engine] OcclusionCulling + * --gpu-blend on|off Blend the meshes that move between two ticks on the GPU (on) or on the CPU + * (off). Needs occlusion culling. Overrides [Engine] GpuBlend * --profile Time the FLING_PROFILE_SCOPE scopes and print a table of them at exit * --thread-jitter S:U --exec threaded only: sleep a random 0..U microseconds (seed S) before each wake * and after each publish on the game thread, and before each frame @@ -170,6 +172,9 @@ namespace Fling /** --occlusion-culling on or off. Empty: not on the command line. */ std::optional OcclusionCulling; + /** --gpu-blend on or off. Empty: not on the command line. */ + std::optional GpuBlend; + /** --thread-jitter: the seed and the longest sleep in microseconds. 0 microseconds means off. */ uint32 JitterSeed = 0; uint32 JitterMaxMicroseconds = 0; diff --git a/FlingEngine/Core/inc/RunSettings.h b/FlingEngine/Core/inc/RunSettings.h index 58235e3e..1217bda7 100644 --- a/FlingEngine/Core/inc/RunSettings.h +++ b/FlingEngine/Core/inc/RunSettings.h @@ -46,6 +46,7 @@ namespace Fling static constexpr const char* InterpolationKey = "Interpolation"; static constexpr const char* FrustumCullingKey = "FrustumCulling"; static constexpr const char* OcclusionCullingKey = "OcclusionCulling"; + static constexpr const char* GpuBlendKey = "GpuBlend"; String Exec; String SimHz; @@ -54,6 +55,7 @@ namespace Fling String Interpolation; String FrustumCulling; String OcclusionCulling; + String GpuBlend; /** * Each key's text from t_GetKey, which returns the text of one [Engine] key, or empty @@ -68,7 +70,8 @@ namespace Fling .VSync = t_GetKey(VSyncKey), .Interpolation = t_GetKey(InterpolationKey), .FrustumCulling = t_GetKey(FrustumCullingKey), - .OcclusionCulling = t_GetKey(OcclusionCullingKey)}; + .OcclusionCulling = t_GetKey(OcclusionCullingKey), + .GpuBlend = t_GetKey(GpuBlendKey)}; } }; @@ -87,6 +90,7 @@ namespace Fling * | Interpolation | [Engine] Interpolation | --interpolation | on | * | FrustumCulling | [Engine] FrustumCulling | --frustum-culling | on | * | OcclusionCulling | [Engine] OcclusionCulling | --occlusion-culling | on | + * | GpuBlend | [Engine] GpuBlend | --gpu-blend | on | * * The values here do not change after startup. The GPU Options window changes VSync, the * frame cap, the simulation rate, interpolation, frustum culling and occlusion culling while the game runs; @@ -139,6 +143,14 @@ namespace Fling bool OcclusionCulling = true; SettingSource OcclusionCullingSource = SettingSource::Default; + /** + * The renderer makes the matrix of a mesh that moves between two ticks on the GPU, in the + * occlusion culling pass (Plans/gpu-blend.md). It needs OcclusionCulling: with that off, the CPU blends. + * Presentation only: the simulation never reads it. + */ + bool GpuBlend = true; + SettingSource GpuBlendSource = SettingSource::Default; + /** The refresh rate of the window's monitor at startup (ResolveFrameCap). Empty when not known, and headless. */ std::optional MonitorHz; diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index d0463862..fc49e404 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -40,6 +40,7 @@ namespace Fling constexpr StringView InterpolationFlag = "interpolation"; constexpr StringView FrustumCullingFlag = "frustum-culling"; constexpr StringView OcclusionCullingFlag = "occlusion-culling"; + constexpr StringView GpuBlendFlag = "gpu-blend"; constexpr StringView ThreadJitterFlag = "thread-jitter"; /** * Flags that are refused with the name of the flag that does their job, so a script @@ -405,7 +406,8 @@ namespace Fling !ReadOptionalOnOff(t_CmdLine, VSyncFlag, t_Out.VSync, t_OutError) || !ReadOptionalOnOff(t_CmdLine, InterpolationFlag, t_Out.Interpolation, t_OutError) || !ReadOptionalOnOff(t_CmdLine, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError) || - !ReadOptionalOnOff(t_CmdLine, OcclusionCullingFlag, t_Out.OcclusionCulling, t_OutError)) + !ReadOptionalOnOff(t_CmdLine, OcclusionCullingFlag, t_Out.OcclusionCulling, t_OutError) || + !ReadOptionalOnOff(t_CmdLine, GpuBlendFlag, t_Out.GpuBlend, t_OutError)) { return false; } diff --git a/FlingEngine/Core/src/RunSettings.cpp b/FlingEngine/Core/src/RunSettings.cpp index 4c44ca06..19afcdcd 100644 --- a/FlingEngine/Core/src/RunSettings.cpp +++ b/FlingEngine/Core/src/RunSettings.cpp @@ -202,6 +202,12 @@ namespace Fling Keys::OcclusionCullingKey, t_Out.OcclusionCulling, t_Out.OcclusionCullingSource, + t_OutError) || + !PickOnOff(t_Options.GpuBlend, + t_Config.GpuBlend, + Keys::GpuBlendKey, + t_Out.GpuBlend, + t_Out.GpuBlendSource, t_OutError)) { return false; @@ -226,6 +232,10 @@ namespace Fling { t_Out.Ignored.push_back("--occlusion-culling does nothing with --null-render: nothing is drawn"); } + if (t_Options.NullRender && t_Options.GpuBlend) + { + t_Out.Ignored.push_back("--gpu-blend does nothing with --null-render: nothing is drawn"); + } return true; } @@ -275,7 +285,8 @@ namespace Fling "), vsync " + OnOffName(VSync) + " (" + SettingSourceName(VSyncSource) + "), interpolation " + OnOffName(Interpolation) + " (" + SettingSourceName(InterpolationSource) + "), frustum culling " + OnOffName(FrustumCulling) + " (" + SettingSourceName(FrustumCullingSource) + "), occlusion culling " + - OnOffName(OcclusionCulling) + " (" + SettingSourceName(OcclusionCullingSource) + ")"; + OnOffName(OcclusionCulling) + " (" + SettingSourceName(OcclusionCullingSource) + "), gpu blend " + + OnOffName(GpuBlend) + " (" + SettingSourceName(GpuBlendSource) + ")"; } uint32 LimiterFps(const uint32 t_MaxFps, diff --git a/FlingEngine/Editor/src/BaseEditor.cpp b/FlingEngine/Editor/src/BaseEditor.cpp index ea2a7a19..cfa2b3a6 100644 --- a/FlingEngine/Editor/src/BaseEditor.cpp +++ b/FlingEngine/Editor/src/BaseEditor.cpp @@ -461,6 +461,12 @@ namespace Fling m_ControlsError.clear(); Controls.SetOcclusionCulling(bOcclusionCulling); } + bool bGpuBlend = Controls.GpuBlend(); + if (ImGui::Checkbox("GPU blend (needs occlusion culling)", &bGpuBlend)) + { + m_ControlsError.clear(); + Controls.SetGpuBlend(bGpuBlend); + } const CullStats Culled = VulkanApp::Get().GetCullStats(); ImGui::TextDisabled("Last frame: %u meshes drawn, %u outside the view, %u occluded (hidden by other meshes)", Culled.Drawn, diff --git a/FlingEngine/Engine/inc/Interpolate.h b/FlingEngine/Engine/inc/Interpolate.h index 714a46cb..f837bd8e 100644 --- a/FlingEngine/Engine/inc/Interpolate.h +++ b/FlingEngine/Engine/inc/Interpolate.h @@ -117,19 +117,9 @@ namespace Fling::Interpolate } } - /** - * The world matrix of an entity between the two ticks of the frame's blend (ctx.BlendFrom - * and ctx.BlendTo): each Transform up its Parent chain is blended at t, then the matrices - * are composed. So a child of a rotating parent moves on the arc and stays rigid; a - * blend of world matrices or world positions would cut the chord. - * - * Returns false, and leaves out alone, when no Transform on the chain differs between - * the two ticks and the latest one: then the published LocalToWorld is the exact matrix, - * and the check is all it costs. t_Ctx is a frame system context with Read, - * ReadBlend and Read. - */ + /** BlendedWorld for a chain of any depth: one walk to check, one to blend. */ template - bool BlendedWorld(Ctx& t_Ctx, const Entity t_Entity, const float t, glm::mat4& out) + bool BlendedWorldDeep(Ctx& t_Ctx, const Entity t_Entity, const float t, glm::mat4& out) { bool Moved = false; ForEachUp(t_Ctx, @@ -154,4 +144,65 @@ namespace Fling::Interpolate out = World; return true; } + + /** + * The world matrix of an entity between the two ticks of the frame's blend (ctx.BlendFrom + * and ctx.BlendTo): each Transform up its Parent chain is blended at t, then the matrices + * are composed. So a child of a rotating parent moves on the arc and stays rigid; a + * blend of world matrices or world positions would cut the chord. + * + * Returns false, and leaves out alone, when no Transform on the chain differs between + * the two ticks and the latest one: then the published LocalToWorld is the exact matrix, + * and the check is all it costs. t_Ctx is a frame system context with Read, + * ReadBlend and Read. + */ + template + bool BlendedWorld(Ctx& t_Ctx, const Entity t_Entity, const float t, glm::mat4& out) + { + // One walk up the chain: look each level up once, note whether anything moved, and keep + // the two ends, so a moved entity does not walk the chain again to blend it + constexpr uint32 MaxLevels = 8; + const Transform* From[MaxLevels]; + const Transform* To[MaxLevels]; + uint32 Levels = 0; + bool Moved = false; + Entity At = t_Entity; + // HierarchyUtil refuses loops, and the limit keeps bad data from hanging + for (uint32 Depth = 0; Depth < 4096; ++Depth) + { + const Transform* Latest = t_Ctx.template TryGet(At); + if (Latest == nullptr) + { + break; + } + const Transform& A = t_Ctx.template BlendFrom(At); + const Transform& B = t_Ctx.template BlendTo(At); + Moved = Moved || !Same(A, B) || !Same(B, *Latest); + if (Levels == MaxLevels) + { + // A chain this deep is rare: the plain two walks, with no limit on the depth + return BlendedWorldDeep(t_Ctx, t_Entity, t, out); + } + From[Levels] = &A; + To[Levels] = &B; + ++Levels; + const Parent* Up = t_Ctx.template TryGet(At); + if (Up == nullptr) + { + break; + } + At = Up->Value; + } + if (!Moved) + { + return false; + } + glm::mat4 World = TransformUtil::LocalMatrix(Blend(*From[0], *To[0], t)); + for (uint32 i = 1; i < Levels; ++i) + { + World = TransformUtil::LocalMatrix(Blend(*From[i], *To[i], t)) * World; + } + out = World; + return true; + } } // namespace Fling::Interpolate diff --git a/FlingEngine/Engine/inc/RunControls.h b/FlingEngine/Engine/inc/RunControls.h index 9d6b8cc5..aeaf6a97 100644 --- a/FlingEngine/Engine/inc/RunControls.h +++ b/FlingEngine/Engine/inc/RunControls.h @@ -46,6 +46,7 @@ namespace Fling * - Interpolation: World::SetInterpolation, which holds it, on the next frame. * - FrustumCulling: Engine::Present gives it to VulkanApp::SetFrustumCulling, on the next frame. * - OcclusionCulling: Engine::Present gives it to VulkanApp::SetOcclusionCulling, on the next frame. + * - GpuBlend: Engine::Present gives it to VulkanApp::SetGpuBlend, on the next frame. * - SimHz: World::RequestSimHz, a SetRate clock command applied between two ticks, at the * next wake. The world holds the rate. * @@ -89,6 +90,10 @@ namespace Fling bool OcclusionCulling() const { return m_OcclusionCulling; } void SetOcclusionCulling(bool t_On); + /** Blend the meshes that move between two ticks on the GPU (RunSettings::GpuBlend). */ + bool GpuBlend() const { return m_GpuBlend; } + void SetGpuBlend(bool t_On); + /** * Ask for a new simulation rate (World::RequestSimHz, applied at the next tick * boundary). False, with the reason, for a rate that is not from 1 to 1000, or while @@ -146,6 +151,7 @@ namespace Fling bool m_VSync = true; bool m_FrustumCulling = true; bool m_OcclusionCulling = true; + bool m_GpuBlend = true; uint32 m_MaxFps = 0; /** True while the cap is the monitor's refresh rate and no one has set it. */ diff --git a/FlingEngine/Engine/src/Components/Transform.cpp b/FlingEngine/Engine/src/Components/Transform.cpp index a25be83f..3fc75d00 100644 --- a/FlingEngine/Engine/src/Components/Transform.cpp +++ b/FlingEngine/Engine/src/Components/Transform.cpp @@ -5,9 +5,15 @@ namespace Fling::TransformUtil { glm::mat4 LocalMatrix(const Transform& t_Transform) { - glm::mat4 Result = glm::translate(glm::mat4(1.0f), t_Transform.Position); - Result = Result * glm::mat4_cast(t_Transform.Rotation); - return glm::scale(Result, t_Transform.Scale); + // Translate * rotate * scale, written out: the same values as the three glm calls + // (no matrix products), and the draw loop makes one of these for each moving mesh each frame + const glm::mat3 Rotation = glm::mat3_cast(t_Transform.Rotation); + glm::mat4 Result; + Result[0] = glm::vec4(Rotation[0] * t_Transform.Scale.x, 0.0f); + Result[1] = glm::vec4(Rotation[1] * t_Transform.Scale.y, 0.0f); + Result[2] = glm::vec4(Rotation[2] * t_Transform.Scale.z, 0.0f); + Result[3] = glm::vec4(t_Transform.Position, 1.0f); + return Result; } glm::quat FromEulerDegrees(const glm::vec3& t_Degrees) diff --git a/FlingEngine/Engine/src/RunControls.cpp b/FlingEngine/Engine/src/RunControls.cpp index d1e207a7..5b89e3f2 100644 --- a/FlingEngine/Engine/src/RunControls.cpp +++ b/FlingEngine/Engine/src/RunControls.cpp @@ -33,6 +33,7 @@ namespace Fling m_VSync(t_Startup.VSync), m_FrustumCulling(t_Startup.FrustumCulling), m_OcclusionCulling(t_Startup.OcclusionCulling), + m_GpuBlend(t_Startup.GpuBlend), m_MaxFps(t_Startup.MaxFps), m_MaxFpsFollowsMonitor(t_Startup.MaxFpsSource == SettingSource::Monitor), m_MonitorHz(t_Startup.MonitorHz) @@ -66,6 +67,15 @@ namespace Fling } } + void RunControls::SetGpuBlend(const bool t_On) + { + if (t_On != m_GpuBlend) + { + m_GpuBlend = t_On; + F_LOG_TRACE("GPU blend {}", t_On ? "on" : "off"); + } + } + bool RunControls::SetMaxFps(const uint32 t_Fps, String& t_OutError) { t_OutError.clear(); diff --git a/FlingEngine/Graphics/inc/MeshCuller.h b/FlingEngine/Graphics/inc/MeshCuller.h index cda71233..8ec86c9f 100644 --- a/FlingEngine/Graphics/inc/MeshCuller.h +++ b/FlingEngine/Graphics/inc/MeshCuller.h @@ -58,11 +58,36 @@ namespace Fling * * @param t_Items The snapshot's meshes * @param t_ItemSlots The slot of each item (MeshProxyTable::SyncResult::ItemSlots) + * @param t_Worlds The world matrix of each item this frame (MeshDrawItem::ResolveWorld) * @param t_Frustum The camera's view volume. Null: no culling, every drawn slot is visible * @return True if a slot became visible or hidden since the last Cull */ - GRAPHICS_API bool - Cull(std::span t_Items, std::span t_ItemSlots, const Frustum* t_Frustum); + GRAPHICS_API bool Cull(std::span t_Items, + std::span t_ItemSlots, + std::span t_Worlds, + const Frustum* t_Frustum); + + /** Cull with the matrices of the items resolved at blend factor t_Alpha (their World when they do not blend). + */ + bool Cull(std::span t_Items, + std::span t_ItemSlots, + const Frustum* t_Frustum, + const float t_Alpha = 1.0f) + { + std::vector Worlds; + Worlds.reserve(t_Items.size()); + for (const MeshDrawItem& Item : t_Items) + { + Worlds.push_back(Item.ResolveWorld(t_Alpha)); + } + return Cull(t_Items, t_ItemSlots, Worlds, t_Frustum); + } + + /** + * On: an item with HasBlend has no matrix on the CPU (the GPU makes it and tests the view), + * so Cull counts its slot as visible and does not count it in the stats. + */ + void SetDeferBlended(const bool t_On) { m_DeferBlended = t_On; } /** True if the pass draws t_Slot this frame: it is drawn and in view, or culling is off. */ bool IsVisible(const uint32 t_Slot) const { return t_Slot < m_Slots.size() && m_Slots[t_Slot].Visible; } @@ -70,6 +95,8 @@ namespace Fling const CullStats& Stats() const { return m_Stats; } private: + bool m_DeferBlended = false; + struct SlotState { Aabb LocalBounds; diff --git a/FlingEngine/Graphics/inc/PreCullView.h b/FlingEngine/Graphics/inc/PreCullView.h new file mode 100644 index 00000000..b1672a41 --- /dev/null +++ b/FlingEngine/Graphics/inc/PreCullView.h @@ -0,0 +1,44 @@ +#pragma once + +#include "Frustum.h" +#include "GraphicsAPI.h" + +namespace Fling +{ + /** + * The view volume that the renderer culled with on its last frame, for Graphics.PublishSnapshot. + * The snapshot system runs before the renderer draws, so it has no view of its own: it + * uses this one to leave the blend out for a mesh that is far outside it (a blend costs + * a slerp and a matrix for each moving mesh each frame). + * + * The view is one frame old. A mesh that comes into view that frame is drawn at the + * latest tick's place instead of between the two ticks, for that frame only. A mesh is + * never left out of the draw because of this. Both calls are for the main thread, where the + * frame systems and the renderer run. + */ + class PreCullView + { + public: + /** The view of the frame that was just culled, or nullptr when it did no culling (no view is known). */ + static GRAPHICS_API void Set(const Frustum* t_View); + + /** The view, or nullptr when none is known: then nothing is left out. */ + static GRAPHICS_API const Frustum* Get(); + + /** + * True if a mesh at t_Position, up to t_Radius around it, is outside t_View by more than + * the radius on any side: a sphere test, loose on purpose. + */ + static bool IsFarOutside(const Frustum& t_View, const glm::vec3& t_Position, const float t_Radius) + { + for (const glm::vec4& Plane : t_View.Planes) + { + if (glm::dot(glm::vec3(Plane), t_Position) + Plane.w < -t_Radius) + { + return true; + } + } + return false; + } + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/inc/RenderSnapshot.h b/FlingEngine/Graphics/inc/RenderSnapshot.h index e1ba2d7b..c09e66e6 100644 --- a/FlingEngine/Graphics/inc/RenderSnapshot.h +++ b/FlingEngine/Graphics/inc/RenderSnapshot.h @@ -1,11 +1,14 @@ #pragma once +#include "Components/Transform.h" #include "Ecs/Component.h" #include "FlingMath.h" #include "FlingTypes.h" +#include "Interpolate.h" #include "Lighting/DirectionalLight.hpp" #include "Lighting/PointLight.hpp" #include "Strings/String.h" +#include "TransformUtil.h" #include #include @@ -22,10 +25,27 @@ namespace Fling String Mesh; String Material; + /** The world matrix. Not set when HasBlend is true: use ResolveWorld. */ glm::mat4 World{1.0f}; /** LocalToWorld::Version. 0 means there is no LocalToWorld yet, so the matrix is always written. */ uint32 WorldVersion = 0; + + /** + * True for a mesh that moved between the two ticks of the frame's blend and has no + * Parent: it is drawn at the blend of From and To by RenderSnapshot::BlendAlpha, and + * the renderer makes the matrix (the CPU, or the GPU). From and To are the Transform at + * the two ticks. A mesh that is still, or that has a Parent, has its World made here. + */ + bool HasBlend = false; + Transform From; + Transform To; + + /** The world matrix this frame: World, or the blend of From and To by t_Alpha (see Interpolate::Blend). */ + glm::mat4 ResolveWorld(const float t_Alpha) const + { + return HasBlend ? TransformUtil::LocalMatrix(Interpolate::Blend(From, To, t_Alpha)) : World; + } }; /** @@ -50,5 +70,8 @@ namespace Fling /** Goes up by one each time Graphics.PublishSnapshot runs. */ uint64 Frame = 0; + + /** The blend factor of this frame (RealFrameTime::BlendAlpha), for the items with HasBlend. */ + float BlendAlpha = 1.0f; }; } // namespace Fling diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 480fc7c8..0a879a8c 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -142,6 +142,13 @@ namespace Fling */ void SetOcclusionCulling(bool t_On); + /** + * GPU blend on or off (RunSettings::GpuBlend) for the next frame. On: the matrix of a mesh that moves + * between two ticks is made by the occlusion culling pass (so that needs to be on and supported); off: + * the CPU makes it. The mesh pass holds the value; Engine::Present calls it before every frame. + */ + void SetGpuBlend(bool t_On); + /** The meshes the last frame drew and culled. Zero before the first frame and under --null-render. */ CullStats GetCullStats() const; diff --git a/FlingEngine/Graphics/src/DebugSubpass.cpp b/FlingEngine/Graphics/src/DebugSubpass.cpp index bba34c4e..3dd376bf 100644 --- a/FlingEngine/Graphics/src/DebugSubpass.cpp +++ b/FlingEngine/Graphics/src/DebugSubpass.cpp @@ -55,7 +55,7 @@ namespace Fling } Fling::Model* Model = Mesh.MeshModel; - m_Ubo.Model = t_Snapshot.Meshes[i].World; + m_Ubo.Model = t_Snapshot.Meshes[i].ResolveWorld(t_Snapshot.BlendAlpha); memcpy(Mesh.Ubo->m_MappedMem, &m_Ubo, sizeof(m_Ubo)); vkCmdBindDescriptorSets(t_CmdBuf.GetHandle(), diff --git a/FlingEngine/Graphics/src/MeshCuller.cpp b/FlingEngine/Graphics/src/MeshCuller.cpp index cc9bb11b..50686a31 100644 --- a/FlingEngine/Graphics/src/MeshCuller.cpp +++ b/FlingEngine/Graphics/src/MeshCuller.cpp @@ -36,11 +36,12 @@ namespace Fling bool MeshCuller::Cull(const std::span t_Items, const std::span t_ItemSlots, + const std::span t_Worlds, const Frustum* t_Frustum) { bool bChanged = false; m_Stats = {}; - for (size_t i = 0; i < t_Items.size() && i < t_ItemSlots.size(); ++i) + for (size_t i = 0; i < t_Items.size() && i < t_ItemSlots.size() && i < t_Worlds.size(); ++i) { if (t_ItemSlots[i] >= m_Slots.size()) { @@ -51,7 +52,14 @@ namespace Fling { continue; } - const bool bVisible = t_Frustum == nullptr || t_Frustum->Intersects(Slot.LocalBounds, t_Items[i].World); + if (m_DeferBlended && t_Items[i].HasBlend) + { + // The GPU decides: the slot stays visible to the CPU (it is not skipped for its matrix) + bChanged |= !Slot.Visible; + Slot.Visible = true; + continue; + } + const bool bVisible = t_Frustum == nullptr || t_Frustum->Intersects(Slot.LocalBounds, t_Worlds[i]); bChanged |= bVisible != Slot.Visible; Slot.Visible = bVisible; ++(bVisible ? m_Stats.Drawn : m_Stats.Culled); diff --git a/FlingEngine/Graphics/src/OcclusionCuller.cpp b/FlingEngine/Graphics/src/OcclusionCuller.cpp index 653dd6f3..10a22360 100644 --- a/FlingEngine/Graphics/src/OcclusionCuller.cpp +++ b/FlingEngine/Graphics/src/OcclusionCuller.cpp @@ -27,6 +27,9 @@ namespace Fling { glm::mat4 ViewProjection{1.0f}; glm::uvec4 Counts{0u}; + /** x: the blend factor */ + glm::vec4 Blend{0.0f}; + glm::vec4 Planes[Frustum::Count] = {}; }; /** The push constant block of hiz_downsample.comp */ @@ -91,7 +94,7 @@ namespace Fling VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, MaxLevels + 2}, VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, MaxLevels}, VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, - VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5}}; + VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6}}; VkDescriptorPoolCreateInfo PoolInfo = {}; PoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; PoolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; @@ -196,7 +199,8 @@ namespace Fling Binding(3, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), Binding(4, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), Binding(5, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER), - Binding(6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)}, + Binding(6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER), + Binding(7, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)}, sizeof(uint32), m_CullSetLayout, m_CullPipelineLayout); @@ -394,19 +398,20 @@ namespace Fling void OcclusionCuller::WriteCullDescriptors() const { - if (m_Slots == nullptr || m_Draw1 == nullptr || m_PyramidAllLevels == VK_NULL_HANDLE) + if (m_Slots == nullptr || m_Draw1 == nullptr || m_Worlds == nullptr || m_PyramidAllLevels == VK_NULL_HANDLE) { return; } - const VkDescriptorBufferInfo Infos[6] = {{m_Params->GetVkBuffer(), 0, sizeof(CullParams)}, + const VkDescriptorBufferInfo Infos[7] = {{m_Params->GetVkBuffer(), 0, sizeof(CullParams)}, {m_Slots->GetVkBuffer(), 0, VK_WHOLE_SIZE}, {m_Draw1->GetVkBuffer(), 0, VK_WHOLE_SIZE}, {m_Draw2->GetVkBuffer(), 0, VK_WHOLE_SIZE}, {m_Visible->GetVkBuffer(), 0, VK_WHOLE_SIZE}, - {m_Stats->GetVkBuffer(), 0, VK_WHOLE_SIZE}}; + {m_Stats->GetVkBuffer(), 0, VK_WHOLE_SIZE}, + {m_Worlds->GetVkBuffer(), 0, VK_WHOLE_SIZE}}; const VkDescriptorImageInfo Pyramid = {m_Sampler, m_PyramidAllLevels, VK_IMAGE_LAYOUT_GENERAL}; - std::array Writes = {}; + std::array Writes = {}; for (uint32 i = 0; i < 6; ++i) { Writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; @@ -422,6 +427,12 @@ namespace Fling Writes[6].descriptorCount = 1; Writes[6].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; Writes[6].pImageInfo = &Pyramid; + Writes[7].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + Writes[7].dstSet = m_CullSet; + Writes[7].dstBinding = 7; + Writes[7].descriptorCount = 1; + Writes[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + Writes[7].pBufferInfo = &Infos[6]; vkUpdateDescriptorSets(m_Device->GetVkDevice(), static_cast(Writes.size()), Writes.data(), 0, nullptr); } @@ -435,12 +446,34 @@ namespace Fling return m_Stats != nullptr ? *static_cast(m_Stats->m_MappedMem) : 0; } - void OcclusionCuller::WriteParams(const glm::mat4& t_ViewProjection, const uint32 t_SlotCount) + uint32 OcclusionCuller::ReadFrustumCulledCount() const + { + return m_Stats != nullptr ? static_cast(m_Stats->m_MappedMem)[1] : 0; + } + + void OcclusionCuller::SetWorlds(Buffer* t_Worlds) + { + if (m_Worlds != t_Worlds) + { + m_Worlds = t_Worlds; + WriteCullDescriptors(); + } + } + + void OcclusionCuller::WriteParams(const glm::mat4& t_ViewProjection, + const Frustum& t_View, + const uint32 t_SlotCount, + const float t_BlendFactor) { m_SlotCount = t_SlotCount; CullParams Params; Params.ViewProjection = t_ViewProjection; Params.Counts = glm::uvec4(t_SlotCount, 0u, 0u, 0u); + Params.Blend = glm::vec4(t_BlendFactor, 0.0f, 0.0f, 0.0f); + for (uint32 i = 0; i < Frustum::Count; ++i) + { + Params.Planes[i] = t_View.Planes[i]; + } std::memcpy(m_Params->m_MappedMem, &Params, sizeof(Params)); } @@ -488,11 +521,13 @@ namespace Fling Dispatch(t_Cmd, 0); - // The first render pass reads the commands. Phase 1 reads the visible flags that this phase read. + // The first render pass reads the commands, and its vertex shader reads the world matrices that + // this phase made. Phase 1 reads the visible flags that this phase read, and the matrices. ComputeBarrier(t_Cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, - VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); } diff --git a/FlingEngine/Graphics/src/OcclusionCuller.h b/FlingEngine/Graphics/src/OcclusionCuller.h index 451dfde0..7781b3fc 100644 --- a/FlingEngine/Graphics/src/OcclusionCuller.h +++ b/FlingEngine/Graphics/src/OcclusionCuller.h @@ -3,6 +3,7 @@ #include "FlingMath.h" #include "FlingTypes.h" #include "FlingVulkan.h" +#include "Frustum.h" #include #include @@ -16,24 +17,38 @@ namespace Fling /** * What the cull shader reads about one proxy slot, written by the CPU each frame. The std430 * layout of Slot in Occlusion/cull.comp. + * + * The world matrix is not here: it is in the world matrix buffer (SetWorlds), which the + * G-buffer vertex shader reads too. For a slot with Blend, the shader makes it from From and To. */ struct alignas(16) OcclusionSlot { enum Flags : uint32 { - /** The slot passed the frustum test this frame */ + /** The CPU found the slot in the view this frame */ InView = 1u, /** BoundsMin and BoundsMax are known */ HasBounds = 2u, + /** The slot moves between two ticks: the shader makes its world matrix from From, To and the blend factor + */ + Blend = 4u, + /** The shader decides if the slot is in the view (the CPU has no matrix for it), and InView is not used */ + TestFrustum = 8u, }; - glm::mat4 World{1.0f}; glm::vec4 BoundsMin{0.0f}; glm::vec4 BoundsMax{0.0f}; /** x: index count (0: nothing to draw), y: Flags */ glm::uvec4 Info{0u}; + /** The Transform at the two ticks: xyz position, a quaternion (x, y, z, w), xyz scale */ + glm::vec4 FromPos{0.0f}; + glm::vec4 FromRot{0.0f, 0.0f, 0.0f, 1.0f}; + glm::vec4 FromScale{1.0f}; + glm::vec4 ToPos{0.0f}; + glm::vec4 ToRot{0.0f, 0.0f, 0.0f, 1.0f}; + glm::vec4 ToScale{1.0f}; }; - static_assert(sizeof(OcclusionSlot) == 112); + static_assert(sizeof(OcclusionSlot) == 144); /** * Occlusion culling of the G-buffer pass on the GPU (a Hi-Z depth pyramid), in two phases. @@ -90,8 +105,22 @@ namespace Fling /** The meshes the previous frame found hidden, read from the GPU's counter */ uint32 ReadOccludedCount() const; - /** Write this frame's parameters: the camera matrix and the slot count */ - void WriteParams(const glm::mat4& t_ViewProjection, uint32 t_SlotCount); + /** The slots with TestFrustum that the previous frame found outside the view */ + uint32 ReadFrustumCulledCount() const; + + /** + * Write this frame's parameters: the camera matrix, the view volume that the shader tests + * the slots with a TestFrustum flag against, the slot count and the blend factor. + */ + void + WriteParams(const glm::mat4& t_ViewProjection, const Frustum& t_View, uint32 t_SlotCount, float t_BlendFactor); + + /** + * The buffer of world matrices, one mat4 per slot, that the shader writes for the slots + * with Blend and reads for every test. Call it before EnsureCapacity, and again when the + * buffer is replaced. + */ + void SetWorlds(Buffer* t_Worlds); /** Record phase 0 (before the first render pass) */ void RecordFirstPhase(VkCommandBuffer t_Cmd) const; @@ -136,6 +165,7 @@ namespace Fling Buffer* m_Visible = nullptr; Buffer* m_Stats = nullptr; Buffer* m_Draw1 = nullptr; + Buffer* m_Worlds = nullptr; size_t m_Capacity = 0; uint32 m_SlotCount = 0; std::vector m_Retired; diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.cpp b/FlingEngine/Graphics/src/OffscreenSubpass.cpp index 72cd1a24..4ebb223c 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.cpp +++ b/FlingEngine/Graphics/src/OffscreenSubpass.cpp @@ -12,14 +12,22 @@ #include "Model.h" #include "OffscreenSubpass.h" #include "PhyscialDevice.h" +#include "PreCullView.h" #include "Profiler.h" #include "SwapChain.h" #include "UniformBufferObject.h" #include +#include namespace Fling { + namespace + { + /** The binding of the world matrix buffer in mrt.vert */ + constexpr uint32 WorldBufferBinding = 6; + } // namespace + OffscreenSubpass::OffscreenSubpass(const LogicalDevice* t_Dev, const Swapchain* t_Swap, FirstPersonCamera* t_Cam, @@ -98,6 +106,9 @@ namespace Fling delete m_DrawCommands; m_DrawCommands = nullptr; + + delete m_WorldBuffer; + m_WorldBuffer = nullptr; } void OffscreenSubpass::Draw(CommandBuffer& t_CmdBuf, @@ -121,6 +132,10 @@ namespace Fling } // The GPU counted the hidden meshes of the previous frame m_OccludedCount = bOcclusion ? m_Occlusion->ReadOccludedCount() : 0; + m_GpuFrustumCulled = bOcclusion ? m_Occlusion->ReadFrustumCulledCount() : 0; + const bool bGpuBlend = GpuBlendActive(); + // The culler leaves the meshes that the GPU blends to the GPU (it has no matrix for them) + m_Culler.SetDeferBlended(bGpuBlend); if (bOcclusion != m_RecordedOcclusion) { // The recordings hold either one pass or the two phase passes @@ -144,6 +159,10 @@ namespace Fling // The view volume of exactly the matrices the shader uses this frame m_CameraViewProjection = CameraUBO.Projection * CameraUBO.View; + { + FLING_PROFILE_SCOPE("Offscreen.ResolveWorlds"); + ResolveWorlds(t_Snapshot); + } { FLING_PROFILE_SCOPE("Offscreen.Cull"); CullMeshes(t_Snapshot); @@ -155,13 +174,16 @@ namespace Fling } if (bOcclusion) { + FLING_PROFILE_SCOPE("Offscreen.OcclusionSlots"); // The GPU writes the draw commands, from the slot data and this frame's camera + m_Occlusion->SetWorlds(m_WorldBuffer); if (m_Occlusion->EnsureCapacity(m_DrawCommandCapacity, m_DrawCommands)) { InvalidateCommandBuffers(); } WriteOcclusionSlots(t_Snapshot); - m_Occlusion->WriteParams(m_CameraViewProjection, static_cast(m_GpuMeshes.size())); + m_Occlusion->WriteParams( + m_CameraViewProjection, m_View, static_cast(m_GpuMeshes.size()), t_Snapshot.BlendAlpha); } else { @@ -184,6 +206,7 @@ namespace Fling MeshProxyTable::SyncResult Result = m_Proxies.Sync(t_Snapshot.Meshes); m_ItemSlots = std::move(Result.ItemSlots); m_GpuMeshes.resize(m_Proxies.Capacity()); + EnsureWorldCapacity(m_Proxies.Capacity()); // Removed first: a removed slot can be used again by an added mesh for (const uint32 Slot : Result.Removed) @@ -213,6 +236,10 @@ namespace Fling VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); Mesh.Ubo->MapMemory(BufferSize); } + // The slot never changes while the mesh lives: the vertex shader finds its matrix with it + OffscreenUBO MeshUBO = {}; + MeshUBO.Slot = Slot; + std::memcpy(Mesh.Ubo->m_MappedMem, &MeshUBO, sizeof(MeshUBO)); CreateMeshDescriptorSet(Mesh); Mesh.UploadedVersion = 0; // The same test the recording uses, so the culler counts only what gets a draw call @@ -250,17 +277,37 @@ namespace Fling t_Mesh = GpuMesh{}; } + void OffscreenSubpass::ResolveWorlds(const RenderSnapshot& t_Snapshot) + { + // A mesh between two ticks has no matrix yet: make it from its two ends and this frame's factor + // (With the GPU blend, the cull shader makes it: this keeps no matrix for that mesh.) + const bool bGpuBlend = GpuBlendActive(); + m_Worlds.resize(t_Snapshot.Meshes.size()); + for (size_t i = 0; i < t_Snapshot.Meshes.size(); ++i) + { + const MeshDrawItem& Item = t_Snapshot.Meshes[i]; + if (bGpuBlend && Item.HasBlend) + { + continue; + } + m_Worlds[i] = Item.ResolveWorld(t_Snapshot.BlendAlpha); + } + } + void OffscreenSubpass::CullMeshes(const RenderSnapshot& t_Snapshot) { // A change of the visible set needs no new recording: WriteDrawCommands gives each // recorded indirect draw its instance count (0 or 1) for this frame - const Frustum View = Frustum::FromViewProjection(m_CameraViewProjection); - m_Culler.Cull(t_Snapshot.Meshes, m_ItemSlots, m_FrustumCulling ? &View : nullptr); + const Frustum& View = m_View = Frustum::FromViewProjection(m_CameraViewProjection); + m_Culler.Cull(t_Snapshot.Meshes, m_ItemSlots, m_Worlds, m_FrustumCulling ? &View : nullptr); + // The next frame's Graphics.PublishSnapshot skips the blend of what is far outside this view + PreCullView::Set(m_FrustumCulling ? &View : nullptr); } void OffscreenSubpass::WriteOcclusionSlots(const RenderSnapshot& t_Snapshot) { OcclusionSlot* Slots = m_Occlusion->MappedSlots(); + const bool bGpuBlend = GpuBlendActive(); for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) { const GpuMesh& Mesh = m_GpuMeshes[Slot]; @@ -275,12 +322,30 @@ namespace Fling continue; } const Aabb& Bounds = Mesh.MeshModel->GetLocalBounds(); + const MeshDrawItem& Item = t_Snapshot.Meshes[i]; OcclusionSlot& Out = Slots[Slot]; - Out.World = t_Snapshot.Meshes[i].World; Out.BoundsMin = glm::vec4(Bounds.Min, 0.0f); Out.BoundsMax = glm::vec4(Bounds.Max, 0.0f); - Out.Info.y = (m_Culler.IsVisible(Slot) ? OcclusionSlot::InView : 0u) | - (Bounds.IsValid() ? OcclusionSlot::HasBounds : 0u); + uint32 Flags = Bounds.IsValid() ? OcclusionSlot::HasBounds : 0u; + if (bGpuBlend && Item.HasBlend) + { + // The shader makes the matrix from the two ends and the factor, and with frustum culling on it + // also finds out if the mesh is in the view (the CPU has no matrix for it) + Flags |= OcclusionSlot::Blend; + Flags |= m_FrustumCulling ? OcclusionSlot::TestFrustum : OcclusionSlot::InView; + Out.FromPos = glm::vec4(Item.From.Position, 0.0f); + Out.FromRot = + glm::vec4(Item.From.Rotation.x, Item.From.Rotation.y, Item.From.Rotation.z, Item.From.Rotation.w); + Out.FromScale = glm::vec4(Item.From.Scale, 0.0f); + Out.ToPos = glm::vec4(Item.To.Position, 0.0f); + Out.ToRot = glm::vec4(Item.To.Rotation.x, Item.To.Rotation.y, Item.To.Rotation.z, Item.To.Rotation.w); + Out.ToScale = glm::vec4(Item.To.Scale, 0.0f); + } + else if (m_Culler.IsVisible(Slot)) + { + Flags |= OcclusionSlot::InView; + } + Out.Info.y = Flags; } } @@ -289,8 +354,10 @@ namespace Fling // The depth is the last attachment of the offscreen frame buffer FrameBufferAttachment* Depth = m_OffscreenFrameBuf->GetAttachmentAtIndex(5); assert(Depth); - m_Occlusion->SetDepth( - Depth->GetViewHandle(), m_OffscreenFrameBuf->GetWidth(), m_OffscreenFrameBuf->GetHeight(), Depth->GetFormat()); + m_Occlusion->SetDepth(Depth->GetViewHandle(), + m_OffscreenFrameBuf->GetWidth(), + m_OffscreenFrameBuf->GetHeight(), + Depth->GetFormat()); } void OffscreenSubpass::EnsureDrawCommandCapacity() @@ -340,6 +407,8 @@ namespace Fling void OffscreenSubpass::UpdateMeshUniformBuffers(const RenderSnapshot& t_Snapshot) { + glm::mat4* Worlds = static_cast(m_WorldBuffer->m_MappedMem); + const bool bGpuBlend = GpuBlendActive(); for (size_t i = 0; i < t_Snapshot.Meshes.size() && i < m_ItemSlots.size(); ++i) { const MeshDrawItem& Item = t_Snapshot.Meshes[i]; @@ -350,6 +419,11 @@ namespace Fling { continue; } + // The cull shader makes the matrix of a mesh that moves between two ticks + if (bGpuBlend && Item.HasBlend) + { + continue; + } // Version 0 has no LocalToWorld yet, so its matrix can change on any frame if (Item.WorldVersion != 0 && Item.WorldVersion == Mesh.UploadedVersion) @@ -357,14 +431,60 @@ namespace Fling continue; } - OffscreenUBO MeshUBO = {}; - MeshUBO.Model = Item.World; - MeshUBO.ObjPos = glm::vec3(Item.World[3]); - memcpy(Mesh.Ubo->m_MappedMem, &MeshUBO, sizeof(MeshUBO)); + Worlds[Slot] = m_Worlds[i]; Mesh.UploadedVersion = Item.WorldVersion; } } + void OffscreenSubpass::EnsureWorldCapacity(const size_t t_Slots) + { + if (m_WorldBuffer != nullptr && m_WorldCapacity >= t_Slots) + { + return; + } + size_t Capacity = std::max(m_WorldCapacity, 64); + while (Capacity < t_Slots) + { + Capacity *= 2; + } + const VkDeviceSize Size = sizeof(glm::mat4) * Capacity; + Buffer* Bigger = new Buffer(Size, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + Bigger->MapMemory(Size); + std::memset(Bigger->m_MappedMem, 0, Size); + if (m_WorldBuffer != nullptr) + { + std::memcpy(Bigger->m_MappedMem, m_WorldBuffer->m_MappedMem, sizeof(glm::mat4) * m_WorldCapacity); + // The GPU is done with the last frame, but it is freed with the other retired buffers + m_RetiredUniformBuffers.emplace_back(m_WorldBuffer); + } + m_WorldBuffer = Bigger; + m_WorldCapacity = Capacity; + + // Every set that is made points at the buffer, so the ones that exist point at the new one + const VkDescriptorBufferInfo Info = {m_WorldBuffer->GetVkBuffer(), 0, VK_WHOLE_SIZE}; + for (const GpuMesh& Mesh : m_GpuMeshes) + { + if (Mesh.Set == VK_NULL_HANDLE) + { + continue; + } + VkWriteDescriptorSet Write = {}; + Write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + Write.dstSet = Mesh.Set; + Write.dstBinding = WorldBufferBinding; + Write.descriptorCount = 1; + Write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + Write.pBufferInfo = &Info; + vkUpdateDescriptorSets(m_Device->GetVkDevice(), 1, &Write, 0, nullptr); + } + if (m_Occlusion) + { + m_Occlusion->SetWorlds(m_WorldBuffer); + } + } + void OffscreenSubpass::RecordDraws(CommandBuffer& t_CmdBuf, const Buffer& t_Commands) { VkDeviceSize offsets[1] = {0}; @@ -419,8 +539,7 @@ namespace Fling { t_CmdBuf.SetViewport(0, {viewport}); t_CmdBuf.SetScissor(0, {scissor}); - vkCmdBindPipeline( - t_CmdBuf.GetHandle(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline->GetPipeline()); + vkCmdBindPipeline(t_CmdBuf.GetHandle(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline->GetPipeline()); }; t_CmdBuf.Begin(); @@ -467,6 +586,14 @@ namespace Fling } const PBRTextures& Textures = t_Mesh.MeshMaterial->GetPBRTextures(); + const VkDescriptorBufferInfo WorldInfo = {m_WorldBuffer->GetVkBuffer(), 0, VK_WHOLE_SIZE}; + VkWriteDescriptorSet WorldWrite = {}; + WorldWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + WorldWrite.dstSet = t_Mesh.Set; + WorldWrite.dstBinding = WorldBufferBinding; + WorldWrite.descriptorCount = 1; + WorldWrite.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + WorldWrite.pBufferInfo = &WorldInfo; std::vector writeDescriptorSets = { // 0: UBO Initializers::WriteDescriptorSetUniform(t_Mesh.Ubo, t_Mesh.Set, 0), @@ -481,7 +608,9 @@ namespace Fling // Any other PBR textures or other samplers go HERE and you add to the MRT shader // 5: Camera UBO - Initializers::WriteDescriptorSetUniform(m_CameraUboBuffer, t_Mesh.Set, 5)}; + Initializers::WriteDescriptorSetUniform(m_CameraUboBuffer, t_Mesh.Set, 5), + // 6: The world matrix of every mesh, by slot + WorldWrite}; vkUpdateDescriptorSets(m_Device->GetVkDevice(), static_cast(writeDescriptorSets.size()), diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.h b/FlingEngine/Graphics/src/OffscreenSubpass.h index 3e36c420..5c6b2a86 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.h +++ b/FlingEngine/Graphics/src/OffscreenSubpass.h @@ -1,6 +1,7 @@ #pragma once #include "FlingMath.h" +#include "Frustum.h" #include "GpuMesh.h" #include "MeshCuller.h" #include "MeshProxyTable.h" @@ -21,16 +22,17 @@ namespace Fling class Buffer; - /** UBO for mesh data. Written only when the mesh's transform changes. The std140 layout of mrt.vert's UBO. */ + /** + * UBO for mesh data: the slot of the mesh, written once when the mesh is made. The std140 layout of + * mrt.vert's UBO. The world matrix is in the world matrix buffer, by slot (m_WorldBuffer). + */ struct alignas(16) OffscreenUBO { - glm::mat4 Model; - glm::vec3 ObjPos; - /** std140 rounds the block to 16 bytes; GLM's vec3 is 12 on every platform. */ - float ObjPosPadding = 0.0f; + uint32 Slot = 0; + /** std140 rounds the block to 16 bytes */ + uint32 Padding[3] = {}; }; - static_assert(offsetof(OffscreenUBO, Model) == 0 && offsetof(OffscreenUBO, ObjPos) == 64 && - sizeof(OffscreenUBO) == 80); + static_assert(offsetof(OffscreenUBO, Slot) == 0 && sizeof(OffscreenUBO) == 16); /** UBO for camera data. All meshes share one, written once per frame. */ struct alignas(16) OffscreenCameraUBO @@ -90,11 +92,20 @@ namespace Fling */ void SetOcclusionCulling(const bool t_On) { m_OcclusionCulling = t_On; } + /** + * Blend the meshes that move between two ticks on the GPU (on) or on the CPU (off). On needs + * the occlusion culling pass to run: with that off, or not supported, the CPU blends. Takes + * effect on the next Draw. See Plans/gpu-blend.md. + */ + void SetGpuBlend(const bool t_On) { m_GpuBlend = t_On; } + /** What the last Draw drew and culled. */ CullStats GetCullStats() const { CullStats Stats = m_Culler.Stats(); Stats.Occluded = m_OccludedCount; + // The meshes that the GPU tested for the view are counted by it, one frame late + Stats.Culled += m_GpuFrustumCulled; return Stats; } @@ -116,12 +127,22 @@ namespace Fling /** Write the UBO of each mesh whose world matrix changed since its last upload */ void UpdateMeshUniformBuffers(const RenderSnapshot& t_Snapshot); + /** Make m_Worlds: the world matrix of each item of the snapshot this frame */ + void ResolveWorlds(const RenderSnapshot& t_Snapshot); + /** * Find the meshes in the camera's view (m_Culler), from this frame's camera and the * snapshot's world matrices. A change of the visible set does not record again. */ void CullMeshes(const RenderSnapshot& t_Snapshot); + /** True if this frame blends the moving meshes on the GPU (the setting is on and the cull pass runs) */ + bool GpuBlendActive() const { return m_GpuBlend && OcclusionActive(); } + + /** Make m_WorldBuffer hold t_Slots matrices. A new buffer keeps the old contents and is written into every set. + */ + void EnsureWorldCapacity(size_t t_Slots); + /** True if this frame runs the occlusion passes (the setting is on and the device can) */ bool OcclusionActive() const { return m_OcclusionCulling && m_Occlusion && m_Occlusion->IsSupported(); } @@ -204,11 +225,22 @@ namespace Fling /** The proxy slot of each snapshot mesh, from the last SyncProxies */ std::vector m_ItemSlots; + /** The world matrix of each snapshot item this frame (ResolveWorlds), in the order of the items */ + std::vector m_Worlds; + /** Which slots are in the camera's view, indexed by slot like m_GpuMeshes */ MeshCuller m_Culler; /** @see SetFrustumCulling */ bool m_FrustumCulling = true; + bool m_GpuBlend = true; + + /** The view volume of the last CullMeshes */ + Frustum m_View; + + /** The world matrix of every slot (a mat4 each), read by the vertex shader and the cull shader */ + Buffer* m_WorldBuffer = nullptr; + size_t m_WorldCapacity = 0; /** @see SetOcclusionCulling */ bool m_OcclusionCulling = true; @@ -222,6 +254,9 @@ namespace Fling /** Meshes the GPU found hidden in the previous frame */ uint32 m_OccludedCount = 0; + /** The meshes that the GPU found outside the view in the previous frame (the ones that move between ticks) */ + uint32 m_GpuFrustumCulled = 0; + /** * Descriptor sets of meshes that are gone. They are freed at the start of the next * Draw. The previous frame has finished on the GPU then, and every command buffer diff --git a/FlingEngine/Graphics/src/PreCullView.cpp b/FlingEngine/Graphics/src/PreCullView.cpp new file mode 100644 index 00000000..e1915b6c --- /dev/null +++ b/FlingEngine/Graphics/src/PreCullView.cpp @@ -0,0 +1,24 @@ +#include "PreCullView.h" + +namespace Fling +{ + namespace + { + Frustum g_View; + bool g_HasView = false; + } // namespace + + void PreCullView::Set(const Frustum* t_View) + { + g_HasView = t_View != nullptr; + if (t_View != nullptr) + { + g_View = *t_View; + } + } + + const Frustum* PreCullView::Get() + { + return g_HasView ? &g_View : nullptr; + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/Shader.cpp b/FlingEngine/Graphics/src/Shader.cpp index 1dcbdf20..09ac13c4 100644 --- a/FlingEngine/Graphics/src/Shader.cpp +++ b/FlingEngine/Graphics/src/Shader.cpp @@ -16,6 +16,8 @@ namespace Fling uint32 storageClass{}; uint32 binding{}; uint32 set{}; + /** A struct that a buffer block (std430 "buffer") is made of: a storage buffer, not a uniform buffer */ + bool bufferBlock{}; }; std::shared_ptr Shader::Create(const AssetPath& t_Path, LogicalDevice* t_Dev) @@ -159,6 +161,9 @@ namespace Fling assert(wordCount == 4); ids[id].binding = insn[3]; break; + case SpvDecorationBufferBlock: + ids[id].bufferBlock = true; + break; } } break; @@ -226,8 +231,12 @@ namespace Fling switch (typeKind) { case SpvOpTypeStruct: - // m_ResourceTypes[id.binding] = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - m_ResourceTypes[id.binding] = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + // A "buffer" block is a storage buffer: SPIR-V 1.0 marks the struct BufferBlock, 1.3 and + // later use the StorageBuffer storage class + m_ResourceTypes[id.binding] = (id.storageClass == SpvStorageClassStorageBuffer || + ids[id.typeId].bufferBlock || ids[ids[id.typeId].typeId].bufferBlock) + ? VK_DESCRIPTOR_TYPE_STORAGE_BUFFER + : VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; m_ResourceMask |= 1 << id.binding; break; diff --git a/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp b/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp index 00aecc25..d62ed8d0 100644 --- a/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp +++ b/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp @@ -1,5 +1,6 @@ #include "Interpolate.h" #include "Platform.h" +#include "PreCullView.h" #include "Profiler.h" #include "Systems/PublishSnapshotSystem.h" #include "TransformUtil.h" @@ -41,6 +42,67 @@ namespace Fling outVersion = 0; } + /** + * The latest world matrix of an entity that is far outside the last frame's view (see + * PreCullView): the blend is left out, and the published LocalToWorld is drawn. The + * radius is twice the largest scale of a unit mesh, plus one, so a big mesh whose + * centre is off screen is still blended. Returns false when the entity is near the + * view, or there is no view or no LocalToWorld yet. + */ + template + bool + LatestIfFarOutside(Ctx& ctx, const Frustum* view, const Entity entity, glm::mat4& outWorld, uint32& outVersion) + { + if (view == nullptr) + { + return false; + } + const LocalToWorld* world = ctx.template TryGet(entity); + if (world == nullptr) + { + return false; + } + const glm::mat4& m = world->Value; + const float scale = glm::max(glm::length(glm::vec3(m[0])), + glm::max(glm::length(glm::vec3(m[1])), glm::length(glm::vec3(m[2])))); + if (!PreCullView::IsFarOutside(*view, glm::vec3(m[3]), 2.0f * scale + 1.0f)) + { + return false; + } + outWorld = m; + outVersion = world->Version; + return true; + } + + /** + * The two ends of an entity that moved between the two ticks of the frame's blend and + * has no Parent: the renderer blends them (MeshDrawItem::HasBlend). False for an entity + * that did not move (its LocalToWorld is exact), and for a child (its matrix needs the + * blended chain: Interpolate::BlendedWorld). + */ + template + bool BlendPairOf(Ctx& ctx, const Entity entity, Transform& outFrom, Transform& outTo) + { + if (ctx.template TryGet(entity) != nullptr) + { + return false; + } + const Transform* latest = ctx.template TryGet(entity); + if (latest == nullptr) + { + return false; + } + const Transform& from = ctx.template BlendFrom(entity); + const Transform& to = ctx.template BlendTo(entity); + if (Interpolate::Same(from, to) && Interpolate::Same(to, *latest)) + { + return false; + } + outFrom = from; + outTo = to; + return true; + } + /** * The next item of the frame. Items are reused, not cleared, so their path strings keep * their buffers and a steady frame does not allocate. Every field is written. @@ -64,6 +126,8 @@ namespace Fling snapshot.PointLights.clear(); snapshot.DirectionalLights.clear(); ++snapshot.Frame; + snapshot.BlendAlpha = alpha; + const Frustum* view = PreCullView::Get(); for (auto [entity, transform, mesh] : ctx.Query()) { @@ -71,6 +135,18 @@ namespace Fling item.Key = entity.ToBits(); item.Mesh = mesh.Mesh; item.Material = mesh.Material; + item.HasBlend = false; + if (LatestIfFarOutside(ctx, view, entity, item.World, item.WorldVersion)) + { + continue; + } + if (BlendPairOf(ctx, entity, item.From, item.To)) + { + // The renderer makes the matrix: it changes every frame + item.HasBlend = true; + item.WorldVersion = 0; + continue; + } WorldOf(ctx, entity, transform, alpha, item.World, item.WorldVersion); } @@ -91,6 +167,7 @@ namespace Fling gizmo.Material = "Materials/White.mat"; gizmo.World = glm::scale(glm::translate(glm::mat4(1.0f), glm::vec3(world[3])), glm::vec3(0.1f)); gizmo.WorldVersion = version; + gizmo.HasBlend = false; #endif } diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index d5f5405c..6688a867 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -431,6 +431,14 @@ namespace Fling } } + void VulkanApp::SetGpuBlend(const bool t_On) + { + if (m_MeshPass != nullptr) + { + m_MeshPass->SetGpuBlend(t_On); + } + } + CullStats VulkanApp::GetCullStats() const { return m_MeshPass != nullptr ? m_MeshPass->GetCullStats() : CullStats{}; diff --git a/FlingTests/Core/RunSettingsTests.cpp b/FlingTests/Core/RunSettingsTests.cpp index 82111b6c..9217327a 100644 --- a/FlingTests/Core/RunSettingsTests.cpp +++ b/FlingTests/Core/RunSettingsTests.cpp @@ -156,16 +156,18 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins Settings, Error)); Settings.ResolveFrameCap(144u); - REQUIRE(Settings.Describe() == "tick rate 20 Hz (command line), exec inline (command line), frame cap 75 fps " - "(command line), vsync on (command line), interpolation on (command line), " - "frustum culling on (command line), occlusion culling on (command line)"); + REQUIRE(Settings.Describe() == + "tick rate 20 Hz (command line), exec inline (command line), frame cap 75 fps " + "(command line), vsync on (command line), interpolation on (command line), " + "frustum culling on (command line), occlusion culling on (command line), gpu blend on (default)"); // A key with no value is the default REQUIRE(Resolve({}, RunSettingsConfig{}, Settings, Error)); Settings.ResolveFrameCap(144u); - REQUIRE(Settings.Describe() == "tick rate 30 Hz (default), exec threaded (default), frame cap 144 fps (the " - "monitor's refresh rate), vsync on (default), interpolation on (default), " - "frustum culling on (default), occlusion culling on (default)"); + REQUIRE(Settings.Describe() == + "tick rate 30 Hz (default), exec threaded (default), frame cap 144 fps (the " + "monitor's refresh rate), vsync on (default), interpolation on (default), " + "frustum culling on (default), occlusion culling on (default), gpu blend on (default)"); } TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") diff --git a/FlingTests/Engine/BlendedWorldTests.cpp b/FlingTests/Engine/BlendedWorldTests.cpp new file mode 100644 index 00000000..08a846b6 --- /dev/null +++ b/FlingTests/Engine/BlendedWorldTests.cpp @@ -0,0 +1,151 @@ +#include "Components/Transform.h" +#include "Ecs/Entity.h" +#include "Interpolate.h" +#include "TransformUtil.h" + +#include +#include +#include + +// Interpolate::BlendedWorld walks the parent chain once, with a fixed table for the first +// levels, and falls back to BlendedWorldDeep (two walks, any depth) for a longer chain. These +// tests hold the two to the same answer at every depth around that limit, and +// TransformUtil::LocalMatrix to the glm products it replaced. + +using namespace Fling; + +namespace +{ + /** The calls of a frame system context that BlendedWorld uses, over plain maps. */ + struct FakeContext + { + std::map From; + std::map To; + std::map Latest; + std::map Parents; + + template + const T* TryGet(const Entity t_Entity) const; + + template + const Transform& BlendFrom(const Entity t_Entity) const + { + return From.at(t_Entity.ToBits()); + } + + template + const Transform& BlendTo(const Entity t_Entity) const + { + return To.at(t_Entity.ToBits()); + } + }; + + template <> + const Transform* FakeContext::TryGet(const Entity t_Entity) const + { + const auto It = Latest.find(t_Entity.ToBits()); + return It == Latest.end() ? nullptr : &It->second; + } + + template <> + const Parent* FakeContext::TryGet(const Entity t_Entity) const + { + const auto It = Parents.find(t_Entity.ToBits()); + return It == Parents.end() ? nullptr : &It->second; + } + + Transform MakeTransform(const float t_Seed) + { + Transform T; + T.Position = glm::vec3(t_Seed, t_Seed * 0.5f + 1.0f, -t_Seed); + T.Rotation = glm::angleAxis(glm::radians(10.0f * t_Seed), glm::normalize(glm::vec3(1.0f, 2.0f, 0.5f))); + T.Scale = glm::vec3(1.0f + 0.1f * t_Seed, 1.0f, 2.0f); + return T; + } + + /** + * A chain of t_Depth entities, the first is the child, the last has no parent. The level + * t_MovedLevel changes between the two ticks (-1: none moved). + */ + Entity BuildChain(FakeContext& t_Ctx, const uint32 t_Depth, const int t_MovedLevel) + { + for (uint32 Level = 0; Level < t_Depth; ++Level) + { + const Entity E{Level, 0}; + const Transform Base = MakeTransform(static_cast(Level) + 1.0f); + Transform To = Base; + if (static_cast(Level) == t_MovedLevel) + { + To = MakeTransform(static_cast(Level) + 1.7f); + } + t_Ctx.From[E.ToBits()] = Base; + t_Ctx.To[E.ToBits()] = To; + t_Ctx.Latest[E.ToBits()] = To; + if (Level + 1 < t_Depth) + { + t_Ctx.Parents[E.ToBits()] = Parent{Entity{Level + 1, 0}}; + } + } + return Entity{0, 0}; + } +} // namespace + +TEST_CASE("BlendedWorld gives what the two walk version gives, at every depth around its limit", "[interpolate]") +{ + for (const uint32 Depth : {1u, 2u, 4u, 7u, 8u, 9u, 12u}) + { + for (int Moved = -1; Moved < static_cast(Depth); ++Moved) + { + for (const float Alpha : {0.0f, 0.25f, 0.8f, 1.0f}) + { + FakeContext Ctx; + const Entity Child = BuildChain(Ctx, Depth, Moved); + + glm::mat4 Fast{-1.0f}; + glm::mat4 Reference{-1.0f}; + const bool FastMoved = Interpolate::BlendedWorld(Ctx, Child, Alpha, Fast); + const bool ReferenceMoved = Interpolate::BlendedWorldDeep(Ctx, Child, Alpha, Reference); + + INFO("depth " << Depth << " moved level " << Moved << " alpha " << Alpha); + REQUIRE(FastMoved == ReferenceMoved); + REQUIRE(FastMoved == (Moved >= 0)); + if (FastMoved) + { + REQUIRE(Fast == Reference); + } + else + { + // Nothing moved: the output is left alone + REQUIRE(Fast == glm::mat4{-1.0f}); + } + } + } + } +} + +TEST_CASE("BlendedWorld ends the chain at a parent that has no Transform", "[interpolate]") +{ + FakeContext Ctx; + const Entity Child = BuildChain(Ctx, 3, 0); + // Take the top of the chain away: the child's Parent still points at it + Ctx.Latest.erase(Entity{2, 0}.ToBits()); + + glm::mat4 Fast{1.0f}; + glm::mat4 Reference{1.0f}; + REQUIRE(Interpolate::BlendedWorld(Ctx, Child, 0.5f, Fast)); + REQUIRE(Interpolate::BlendedWorldDeep(Ctx, Child, 0.5f, Reference)); + REQUIRE(Fast == Reference); +} + +TEST_CASE("LocalMatrix is the translate, rotate, scale product", "[transform]") +{ + for (float Seed = -3.0f; Seed < 4.0f; Seed += 0.7f) + { + const Transform T = MakeTransform(Seed); + glm::mat4 Reference = glm::translate(glm::mat4(1.0f), T.Position); + Reference = Reference * glm::mat4_cast(T.Rotation); + Reference = glm::scale(Reference, T.Scale); + // == on a matrix compares each value, so a -0 equals a 0 + REQUIRE(TransformUtil::LocalMatrix(T) == Reference); + } +} diff --git a/FlingTests/Graphics/InterpolationTests.cpp b/FlingTests/Graphics/InterpolationTests.cpp index 4cb1820c..2244047e 100644 --- a/FlingTests/Graphics/InterpolationTests.cpp +++ b/FlingTests/Graphics/InterpolationTests.cpp @@ -288,6 +288,9 @@ namespace World& GetWorld() { return *m_World; } + /** The entities that the test game made at play start. */ + const InterpGame& Game() const { return *m_Game; } + /** The time of the frame that started play. */ int64 StartNs() const { return m_StartNs; } @@ -301,7 +304,7 @@ namespace { if (Item.Key == t_Entity.ToBits()) { - return Item.World; + return Item.ResolveWorld(t_Snapshot.BlendAlpha); } } FAIL("the snapshot has no mesh for the entity"); @@ -549,6 +552,56 @@ TEST_CASE("Interpolation: a stalled game thread does not stop the frames, and th CheckFramesFollowTheRule(Frames, At, Rig.StartNs()); } +namespace +{ + const MeshDrawItem& ItemOf(const RenderSnapshot& t_Snapshot, const Entity t_Entity) + { + for (const MeshDrawItem& Item : t_Snapshot.Meshes) + { + if (Item.Key == t_Entity.ToBits()) + { + return Item; + } + } + FAIL("the snapshot has no mesh for the entity"); + return t_Snapshot.Meshes.front(); + } +} // namespace + +TEST_CASE("The snapshot gives the two ends of a moving mesh, and a matrix for a child", "[graphics][interp]") +{ + const ExecMode Mode = GENERATE(ExecMode::Direct, ExecMode::Inline, ExecMode::Threaded); + const Rate At(30u); + INFO("exec mode " << ExecModeName(Mode)); + InterpWorld Rig(Mode, At.Hz); + Drawn Out; + for (int64 Frame = 0; Frame < 6 * FramesPerTick + 1; ++Frame) + { + Out = Rig.Frame(At.FrameTime(Frame), At.StepNs); + } + + const RenderSnapshot& Snapshot = Rig.GetWorld().GetPresentedStorage().Singleton(); + CHECK(Snapshot.BlendAlpha == Out.Alpha); + + // A mesh with no Parent that moved between the two ticks: its two Transform values, and no matrix + const MeshDrawItem& Slider = ItemOf(Snapshot, Rig.Game().Slider); + REQUIRE(Slider.HasBlend); + CHECK(Slider.WorldVersion == 0); + CHECK(Slider.To.Position.x - Slider.From.Position.x == Catch::Approx(SlidePerTick.x).margin(1e-5)); + CHECK(Slider.ResolveWorld(Snapshot.BlendAlpha) == Out.Slider); + CHECK(Slider.ResolveWorld(0.0f)[3].x == Catch::Approx(Slider.From.Position.x)); + CHECK(Slider.ResolveWorld(1.0f)[3].x == Catch::Approx(Slider.To.Position.x)); + + // The spinner crosses 0 degrees, so its ends are on opposite sides: it still blends the short way + const MeshDrawItem& Spinner = ItemOf(Snapshot, Rig.Game().Spinner); + CHECK(Spinner.HasBlend); + + // A child of a turning parent is made on the CPU from the whole chain: it has its matrix + const MeshDrawItem& Child = ItemOf(Snapshot, Rig.Game().Child); + CHECK_FALSE(Child.HasBlend); + CHECK(Child.World == Out.Child); +} + TEST_CASE("Interpolation: a pause holds the latest state, and the resume does not jump", "[graphics][interp]") { const ExecMode Mode = GENERATE(ExecMode::Direct, ExecMode::Inline, ExecMode::Threaded); diff --git a/FlingTests/Graphics/RenderProxyTests.cpp b/FlingTests/Graphics/RenderProxyTests.cpp index 9263d7ef..74c53377 100644 --- a/FlingTests/Graphics/RenderProxyTests.cpp +++ b/FlingTests/Graphics/RenderProxyTests.cpp @@ -223,7 +223,7 @@ TEST_CASE("Graphics.PublishSnapshot takes no memory from the global heap in a st CHECK(snapshot.Meshes[i].Key == before[i].Key); CHECK(snapshot.Meshes[i].Mesh == before[i].Mesh); CHECK(snapshot.Meshes[i].Material == before[i].Material); - CHECK(snapshot.Meshes[i].World == before[i].World); + CHECK(snapshot.Meshes[i].ResolveWorld(snapshot.BlendAlpha) == before[i].ResolveWorld(snapshot.BlendAlpha)); } CHECK(snapshot.PointLights.size() == 4); CHECK(snapshot.DirectionalLights.size() == 1); diff --git a/FlingTests/Resources/RunSettingsConfigTests.cpp b/FlingTests/Resources/RunSettingsConfigTests.cpp index e5af4a81..65fbebe0 100644 --- a/FlingTests/Resources/RunSettingsConfigTests.cpp +++ b/FlingTests/Resources/RunSettingsConfigTests.cpp @@ -26,8 +26,8 @@ TEST_CASE("Run settings: the [Engine] keys of an ini file reach the run settings RunSettings Settings; String Error; REQUIRE(RunSettings::Resolve(LaunchOptions{}, Config, Settings, Error)); - REQUIRE(Settings.Describe() == - "tick rate 60 Hz (config), exec inline (config), frame cap 90 fps (config), vsync " - "off (config), interpolation off (config), frustum culling off (config), occlusion culling off (config)"); + REQUIRE(Settings.Describe() == "tick rate 60 Hz (config), exec inline (config), frame cap 90 fps (config), vsync " + "off (config), interpolation off (config), frustum culling off (config), occlusion " + "culling off (config), gpu blend on (default)"); std::filesystem::remove(Path); } diff --git a/Plans/gpu-blend.md b/Plans/gpu-blend.md new file mode 100644 index 00000000..a5b4b32b --- /dev/null +++ b/Plans/gpu-blend.md @@ -0,0 +1,84 @@ +# Blending meshes on the GPU + +Status: stages 1 and 2 are built, on top of the occlusion culling pass (`Docs/occlusion-culling.md`). Stage 3 is next. + +## Why + +Between two ticks a moving mesh is drawn at a point between its two published transforms +(`Docs/threading-model.md`, "The two blend states"). `Graphics.PublishSnapshot` made that +matrix on the main thread for every moving mesh, every frame: a slerp, a matrix, and several +component lookups. In a Debug build the lighting test level (3,136 rotating spheres) spent +6.4 ms a frame on it, against 1.6 ms with the spheres still. + +Frustum tests on the CPU cut part of that (`PreCullView`), but occlusion is decided on the +GPU after the snapshot, with the blended matrices. The CPU cannot know which meshes are hidden, +so it cannot skip their blend. The way to stop paying for it is to not make the matrix on the CPU. + +## Design + +A mesh that moved between the two ticks, and has no `Parent`, goes into the snapshot as its two +`Transform` values (`MeshDrawItem::From` and `To`, `HasBlend`) and the frame's factor +(`RenderSnapshot::BlendAlpha`). Everything else keeps its matrix: a still mesh uses its +`LocalToWorld`, a mesh far outside the last view uses its latest `LocalToWorld`, and a child +of a moving parent is blended on the CPU as before (a chain needs the whole parent walk). + +The renderer then makes the world matrix: + +1. **CPU, always correct** (stage 1): `MeshDrawItem::ResolveWorld`. Used when the GPU path is + not running, and by passes that need a matrix on the CPU (debug meshes). +2. **GPU** (stage 2): the occlusion compute pass blends each slot that has a pair into a shared + world matrix buffer, tests the result against the frustum and the depth pyramid, and the + vertex shader reads the matrix from that buffer by slot. The CPU writes only the pairs + (and the matrices of still meshes, when their `LocalToWorld` version changes). + +The GPU path needs the occlusion compute pass, so it runs only when occlusion culling is on and +supported. With it off, the renderer resolves the matrices on the CPU (stage 1). + +## Stages + +1. Snapshot carries the pair; the renderer resolves it on the CPU. No picture change. +2. World matrix buffer, the blend and the frustum test in `cull.comp`, the vertex shader reads + the buffer. `--gpu-blend on|off`. +3. (Not built yet.) Snapshot rebuilt only when a tick arrives (the pairs do not change between ticks), so a frame + with no new tick does no per-mesh work on the CPU. + +## What was built (stages 1 and 2) + +- `MeshDrawItem::HasBlend`, `From`, `To` and `RenderSnapshot::BlendAlpha`. `PublishSnapshot` gives a + mesh the pair when it moved between the two ticks and has no `Parent`; a mesh far outside the + last view (`PreCullView`) or a child keeps a matrix. +- The G-buffer vertex shader (`mrt.vert`) reads its matrix from one storage buffer by slot + (`OffscreenSubpass::m_WorldBuffer`, binding 6). The per mesh UBO holds only the slot. The + CPU writes the matrix of a still mesh when its `LocalToWorld` version changes; with `--gpu-blend off` + (or with occlusion culling off) it also writes the blended matrices. +- `cull.comp` makes the matrix of each slot with `Blend` in phase 0 (`SlerpQuat`, `LocalMatrix`: the + same as `Interpolate::Blend` and `TransformUtil::LocalMatrix`) and decides the frustum test for it + (`InFrustum`: the same as `Frustum::Intersects`), because the CPU has no matrix for it. A barrier + makes the matrices visible to the vertex shader. +- Shader reflection (`Shader.cpp`) now tells a storage buffer from a uniform buffer. +- `--gpu-blend on|off`, `[Engine] GpuBlend`, a checkbox in GPU Options. On by default; it needs + occlusion culling to run, otherwise the CPU blends. + +## Measured + +Debug build, `--offscreen --exec threaded`, 3,136 rotating spheres, CPU ms per frame: + +| | CPU blend | GPU blend | +|---|---|---| +| everything in view (`--frustum-culling off`): `ResolveWorlds` | 0.43 | 0.01 | +| default view: `ResolveWorlds` + `Cull` | 0.14 + 2.34 | 0.02 + 1.57 | + +`PublishSnapshot` is 1.2 to 1.7 ms in both: that is the per mesh loop (stage 3). Before stage 1 it +was 6.4 ms with the spheres turning. Most of that was the lookups of the old blend (two walks of +the parent chain, several component lookups), not the slerp, so stage 1 gave most of the gain. + +The picture: GPU and CPU blend at the same tick differ by at most 3 of 255 on 1,697 of 2 million +pixels (float rounding), and both differ greatly from `--interpolation off`, so the check does +test the blend. No validation layer messages, with and without occlusion culling. + +## Checking it + +- `--offscreen --frames-per-tick N` puts several frames in one tick, so the factor goes through + 0..1. A screenshot with `--gpu-blend on` and `off` at the same tick must match (within + float rounding). +- `--profile`: `Graphics.PublishSnapshot` and `Offscreen.*` before and after. diff --git a/Sandbox/Gameplay/src/Systems/MotionProbeSystem.cpp b/Sandbox/Gameplay/src/Systems/MotionProbeSystem.cpp index de28921b..e33b05f9 100644 --- a/Sandbox/Gameplay/src/Systems/MotionProbeSystem.cpp +++ b/Sandbox/Gameplay/src/Systems/MotionProbeSystem.cpp @@ -23,7 +23,7 @@ namespace Sandbox for (size_t i = 0; i < snapshot.Meshes.size(); ++i) { const Fling::MeshDrawItem& item = snapshot.Meshes[i]; - const glm::vec3 axis = glm::normalize(glm::vec3(item.World[0])); + const glm::vec3 axis = glm::normalize(glm::vec3(item.ResolveWorld(snapshot.BlendAlpha)[0])); if (same && probe.Keys[i] == item.Key) { // The angle between the two axes, from the chord: precise for small angles