diff --git a/AGENTS.md b/AGENTS.md index 88c10f0f..6d371f9c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,13 +45,14 @@ platform setup (Vulkan SDK, GLFW, etc.). - Play runs threaded (a game thread for the ticks) at a fixed 30 Hz, with the main thread's frames capped at the monitor's refresh rate (no cap headless). `--exec direct|inline|threaded`, `--sim-hz N`, `--max-fps N` (0: no cap), - `--vsync on|off` (on by default) and `--interpolation on|off` (on by - default) override, as do `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync` and - `Interpolation` in + `--vsync on|off` (on by default), `--interpolation on|off` (on by + default) and `--frustum-culling on|off` (on by default) override, as do + `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation` and + `FrustumCulling` 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 - the rate, the cap, VSync and interpolation at run time. + the rate, the cap, VSync, interpolation and frustum culling at run time. Detail: [`Docs/time-and-ticks.md`](Docs/time-and-ticks.md) section 2. - See a run without a window: `--dump-state ` writes the simulation state as JSON at chosen ticks (works with `--null-render`), and `--offscreen diff --git a/Config/EngineConf.ini b/Config/EngineConf.ini index 5827f3a7..3f8badcb 100644 --- a/Config/EngineConf.ini +++ b/Config/EngineConf.ini @@ -25,13 +25,18 @@ DisplayVersionInfoInTitle=true ; Interpolation ; on (default): the renderer draws between the latest two ticks; off: the ; latest tick only. Presentation only. Flag: --interpolation +; FrustumCulling +; on (default): the renderer skips the meshes outside the camera's view; +; off: it draws every mesh. Presentation only. Flag: --frustum-culling ; Every key here is checked in every run, also when a flag overrides it. The editor's -; GPU Options window changes SimHz, MaxFps, VSync and Interpolation at run time. +; GPU Options window changes SimHz, MaxFps, VSync, Interpolation and FrustumCulling at +; run time. ;Exec=threaded ;SimHz=30 ;MaxFps= ;VSync=on ;Interpolation=on +;FrustumCulling=on ; resizes window to a small window [Windowed] diff --git a/Docs/agent-guide.md b/Docs/agent-guide.md index beec0e06..5d8105b2 100644 --- a/Docs/agent-guide.md +++ b/Docs/agent-guide.md @@ -768,6 +768,7 @@ flag or key. The startup line `Run settings: ...` names each value and its sourc | Frame cap | `--max-fps N` (0: none, max 1000) | `MaxFps` | monitor refresh rate, else 60 (`FallbackMaxFps`); none with `--null-render` | GPU Options | | VSync | `--vsync on\|off` | `VSync` | on | GPU Options (swap chain rebuilt) | | Interpolation | `--interpolation on\|off` | `Interpolation` | on | GPU Options | +| Frustum culling | `--frustum-culling on\|off` | `FrustumCulling` | on | GPU Options | | Thread jitter (tests) | `--thread-jitter S:U` (threaded only; an error otherwise) | none | off | no | Other flags: `--null-render` (no window or GPU, virtual clock), `--offscreen` (render diff --git a/Docs/architecture-overview.md b/Docs/architecture-overview.md index efa98477..2250baf3 100644 --- a/Docs/architecture-overview.md +++ b/Docs/architecture-overview.md @@ -385,8 +385,8 @@ must be started from there. With Ninja the program is | Dump ticks | `build\Sandbox\bin\Sandbox.exe --null-render --unattended --seed 1 --frames 120 --replay-input Sandbox/Tests/Input/look_camera_cuts.input.jsonl --dump-ticks ticks.txt` (a recording replays only at its rate: `look_camera_cuts_60hz.input.jsonl` needs `--sim-hz 60`) | | Windowed demo (look camera; threaded, 30 Hz, frames capped at the monitor's refresh rate) | `build\Sandbox\bin\Sandbox.exe --play` | | The same, unattended (the exit line has the average frame time) | `build\Sandbox\bin\Sandbox.exe --play --unattended --frames 300` (it runs until tick 300 is shown, so for about 10 s at 30 Hz) | -| Other settings | `--exec direct` or `inline`, `--sim-hz N` (1 to 1000), `--max-fps N` (0: no cap), `--vsync on\|off`, `--interpolation on\|off`; or the same keys in `[Engine]` of `Config/EngineConf.ini` (`Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`) | -| Change them while the game runs | The editor UI is drawn in `--play` too, and the Sandbox opens the "GPU Options" window at start in `--play` (menu Windows closes and opens it): VSync (On or Off, with the present mode in use), frame cap, simulation rate, render interpolation, with what the frame limiter does and the measured rates. Press M first if the cursor is hidden | +| Other settings | `--exec direct` or `inline`, `--sim-hz N` (1 to 1000), `--max-fps N` (0: no cap), `--vsync on\|off`, `--interpolation on\|off`, `--frustum-culling on\|off`; or the same keys in `[Engine]` of `Config/EngineConf.ini` (`Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, `FrustumCulling`) | +| Change them while the game runs | The editor UI is drawn in `--play` too, and the Sandbox opens the "GPU Options" window at start in `--play` (menu Windows closes and opens it): VSync (On or Off, with the present mode in use), frame cap, simulation rate, render interpolation, frustum culling (with the meshes drawn and culled), with what the frame limiter does and the measured rates. Press M first if the cursor is hidden | ## 11. Where to read more diff --git a/Docs/threading-model.md b/Docs/threading-model.md index ca9bd748..d3b730a9 100644 --- a/Docs/threading-model.md +++ b/Docs/threading-model.md @@ -210,6 +210,24 @@ lighting test: 42 224 bytes). The frame side copies nothing: it indexes the new tick of each packet it takes. The render snapshot does a blend and a matrix per moving entity, and only a compare per entity that did not move. +**Frustum culling** is on the frame side only, in the renderer, after the +snapshot: the packet and the snapshot still hold every mesh. The offscreen +(G-buffer) pass tests each mesh's world box (the model's local bounds, placed +by the item's drawn matrix) against the planes of this frame's camera +(`Frustum`, `MeshCuller` in `FlingEngine/Graphics/inc/`), and skips the draw +and the uniform buffer write of a mesh that is outside. A culled mesh +keeps its proxy slot and GPU resources, so it costs nothing to bring back. +Each mesh is recorded as an indirect draw; the CPU writes its instance count +(1 in view, 0 culled) every frame, so a moving camera never makes the command +buffers record again (they record only when the draw list changes). +The camera is only final in `VulkanApp::Update`, after the frame systems ran, +so the snapshot's blend and matrix work is not culled; a test against the last +frame's camera would not be conservative. Lights are not culled (the deferred +lighting pass is full screen), and there is no shadow pass. `--frustum-culling +on|off`, `[Engine] FrustumCulling` and the GPU Options window, which also shows +the meshes drawn and culled in the last frame. Tests: `GraphicsTests +"[culling]"` (`FrustumCullingTests.cpp`). + **Tests.** `EngineTests "[interp]"` (`EcsBlendTests.cpp`: each packet carries the latest two ticks of the marked types only; new, destroyed, changed and reused entities; after skipped packets `BlendFrom` is still the tick before diff --git a/Docs/time-and-ticks.md b/Docs/time-and-ticks.md index bf3e63b1..88a80c48 100644 --- a/Docs/time-and-ticks.md +++ b/Docs/time-and-ticks.md @@ -74,6 +74,7 @@ outside `--exec threaded` is an error. | Frame cap | `--max-fps N` (0: none, up to 1000) | `MaxFps` | the refresh rate of the window's monitor, else 60; none with `--null-render` | GPU Options, from the next frame | | VSync | `--vsync on\|off` | `VSync` | on | GPU Options, the swap chain is made again | | Interpolation | `--interpolation on\|off` | `Interpolation` | on | GPU Options, from the next frame | +| Frustum culling | `--frustum-culling on\|off` | `FrustumCulling` | on | GPU Options, from the next frame | | Thread jitter (tests) | `--thread-jitter S:U` (`--exec threaded` only) | none | off | no | `RunSettings` does not change after startup. The live values are in diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index eaf7d4e9..27c2f611 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -704,6 +704,7 @@ namespace Fling // During Inline or Threaded play the renderer reads the mirror. A VSync change makes // the swap chain again after this frame's present. VulkanApp::Get().SetVSync(m_Controls->VSync()); + VulkanApp::Get().SetFrustumCulling(m_Controls->FrustumCulling()); VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage()); // Offscreen there is no window: no focus, no monitor, and no frame cap (headless) diff --git a/FlingEngine/Core/inc/LaunchOptions.h b/FlingEngine/Core/inc/LaunchOptions.h index b285c7f2..378500ad 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -75,6 +75,9 @@ namespace Fling * --interpolation on|off * Draw between the latest two published ticks (on) or the latest tick * only. Overrides [Engine] Interpolation + * --frustum-culling on|off + * Skip the meshes outside the camera's view (on) or draw every mesh + * (off). Overrides [Engine] FrustumCulling * --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 */ @@ -154,6 +157,9 @@ namespace Fling /** --interpolation on or off. Empty: not on the command line. */ std::optional Interpolation; + /** --frustum-culling on or off. Empty: not on the command line. */ + std::optional FrustumCulling; + /** --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 dc4a1ccb..26aaf186 100644 --- a/FlingEngine/Core/inc/RunSettings.h +++ b/FlingEngine/Core/inc/RunSettings.h @@ -44,12 +44,14 @@ namespace Fling static constexpr const char* MaxFpsKey = "MaxFps"; static constexpr const char* VSyncKey = "VSync"; static constexpr const char* InterpolationKey = "Interpolation"; + static constexpr const char* FrustumCullingKey = "FrustumCulling"; String Exec; String SimHz; String MaxFps; String VSync; String Interpolation; + String FrustumCulling; /** * Each key's text from t_GetKey, which returns the text of one [Engine] key, or empty @@ -62,7 +64,8 @@ namespace Fling .SimHz = t_GetKey(SimHzKey), .MaxFps = t_GetKey(MaxFpsKey), .VSync = t_GetKey(VSyncKey), - .Interpolation = t_GetKey(InterpolationKey)}; + .Interpolation = t_GetKey(InterpolationKey), + .FrustumCulling = t_GetKey(FrustumCullingKey)}; } }; @@ -79,9 +82,10 @@ namespace Fling * | MaxFps | [Engine] MaxFps | --max-fps | monitor refresh, else 60; none headless. 0: no cap | * | VSync | [Engine] VSync | --vsync | on | * | Interpolation | [Engine] Interpolation | --interpolation | on | + * | FrustumCulling | [Engine] FrustumCulling | --frustum-culling | on | * * The values here do not change after startup. The GPU Options window changes VSync, the - * frame cap, the simulation rate and interpolation while the game runs; RunControls holds + * frame cap, the simulation rate, interpolation and frustum culling while the game runs; RunControls holds * those live values, starting from these. Edit mode in the editor always runs on one * thread, whatever Exec says. */ @@ -117,6 +121,13 @@ namespace Fling bool Interpolation = true; SettingSource InterpolationSource = SettingSource::Default; + /** + * The renderer does not draw a mesh whose bounds are outside the camera's view this + * frame (MeshCuller in Graphics). Presentation only: the simulation never reads it. + */ + bool FrustumCulling = true; + SettingSource FrustumCullingSource = SettingSource::Default; + /** The refresh rate of the window's monitor at startup (ResolveFrameCap). Empty when not known, and headless. */ std::optional MonitorHz; @@ -164,7 +175,7 @@ namespace Fling /** * One line for the startup log with each value and where it came from, for example * "tick rate 30 Hz (default), exec threaded (default), frame cap 144 fps (the monitor's refresh rate), - * vsync on (default), interpolation on (default)". + * vsync on (default), interpolation on (default), frustum culling on (default)". */ CORE_API String Describe() const; }; diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index f4dd412f..f0517fe1 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -37,6 +37,7 @@ namespace Fling constexpr StringView MaxFpsFlag = "max-fps"; constexpr StringView VSyncFlag = "vsync"; constexpr StringView InterpolationFlag = "interpolation"; + constexpr StringView FrustumCullingFlag = "frustum-culling"; constexpr StringView ThreadJitterFlag = "thread-jitter"; /** * Flags that are refused with the name of the flag that does their job, so a script @@ -392,7 +393,8 @@ namespace Fling if (!ReadOptionalUint32(t_CmdLine, SimHzFlag, t_Out.SimHz, t_OutError) || !ReadOptionalUint32(t_CmdLine, MaxFpsFlag, t_Out.MaxFps, t_OutError) || !ReadOptionalOnOff(t_CmdLine, VSyncFlag, t_Out.VSync, t_OutError) || - !ReadOptionalOnOff(t_CmdLine, InterpolationFlag, t_Out.Interpolation, t_OutError)) + !ReadOptionalOnOff(t_CmdLine, InterpolationFlag, t_Out.Interpolation, t_OutError) || + !ReadOptionalOnOff(t_CmdLine, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError)) { return false; } diff --git a/FlingEngine/Core/src/RunSettings.cpp b/FlingEngine/Core/src/RunSettings.cpp index d20f11a2..d55c5132 100644 --- a/FlingEngine/Core/src/RunSettings.cpp +++ b/FlingEngine/Core/src/RunSettings.cpp @@ -190,6 +190,12 @@ namespace Fling Keys::InterpolationKey, t_Out.Interpolation, t_Out.InterpolationSource, + t_OutError) || + !PickOnOff(t_Options.FrustumCulling, + t_Config.FrustumCulling, + Keys::FrustumCullingKey, + t_Out.FrustumCulling, + t_Out.FrustumCullingSource, t_OutError)) { return false; @@ -206,6 +212,10 @@ namespace Fling t_Out.Ignored.push_back(String("--vsync does nothing with ") + t_Out.HeadlessFlag + ": there is no swap chain"); } + if (t_Options.NullRender && t_Options.FrustumCulling) + { + t_Out.Ignored.push_back("--frustum-culling does nothing with --null-render: nothing is drawn"); + } return true; } @@ -253,7 +263,8 @@ namespace Fling return "tick rate " + std::to_string(SimHz) + " Hz (" + SettingSourceName(SimHzSource) + "), exec " + ExecModeName(Exec) + " (" + SettingSourceName(ExecSource) + "), frame cap " + Cap + " (" + CapSource + "), vsync " + OnOffName(VSync) + " (" + SettingSourceName(VSyncSource) + "), interpolation " + - OnOffName(Interpolation) + " (" + SettingSourceName(InterpolationSource) + ")"; + OnOffName(Interpolation) + " (" + SettingSourceName(InterpolationSource) + "), frustum culling " + + OnOffName(FrustumCulling) + " (" + SettingSourceName(FrustumCullingSource) + ")"; } uint32 LimiterFps(const uint32 t_MaxFps, diff --git a/FlingEngine/Editor/inc/BaseEditor.h b/FlingEngine/Editor/inc/BaseEditor.h index 510dac2e..fccaa642 100644 --- a/FlingEngine/Editor/inc/BaseEditor.h +++ b/FlingEngine/Editor/inc/BaseEditor.h @@ -86,7 +86,8 @@ namespace Fling /** * The GPU Options window: the device, VSync (with the present mode in use), the frame - * cap, the simulation rate and render interpolation, with what the frame limiter does + * cap, the simulation rate, render interpolation and frustum culling (with the meshes + * drawn and culled), with what the frame limiter does * and the measured rates, and a button that saves the next frame as a PNG * (Screenshot::Request). Each control * calls RunControls, which checks the request; a number box applies when its edit is diff --git a/FlingEngine/Editor/src/BaseEditor.cpp b/FlingEngine/Editor/src/BaseEditor.cpp index 83f92cc8..d965dd78 100644 --- a/FlingEngine/Editor/src/BaseEditor.cpp +++ b/FlingEngine/Editor/src/BaseEditor.cpp @@ -449,6 +449,15 @@ namespace Fling Controls.SetInterpolation(bInterpolation); } + bool bFrustumCulling = Controls.FrustumCulling(); + if (ImGui::Checkbox("Frustum culling", &bFrustumCulling)) + { + m_ControlsError.clear(); + Controls.SetFrustumCulling(bFrustumCulling); + } + const CullStats Culled = VulkanApp::Get().GetCullStats(); + ImGui::TextDisabled("Last frame: %u meshes drawn, %u outside the view", Culled.Drawn, Culled.Culled); + if (!m_ControlsError.empty()) { ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", m_ControlsError.c_str()); diff --git a/FlingEngine/Engine/inc/RunControls.h b/FlingEngine/Engine/inc/RunControls.h index 8bd86039..e3c655ec 100644 --- a/FlingEngine/Engine/inc/RunControls.h +++ b/FlingEngine/Engine/inc/RunControls.h @@ -34,8 +34,8 @@ namespace Fling /** * The live values of the run settings that change while the game runs: the ones a person - * sets in the editor's GPU Options window (VSync, the frame cap, the simulation rate and - * render interpolation), and the ones the window system reports (the monitor's refresh + * sets in the editor's GPU Options window (VSync, the frame cap, the simulation rate, + * render interpolation and frustum culling), and the ones the window system reports (the monitor's refresh * rate, and whether the window is in the background). They start from the RunSettings * that the engine resolved at startup, which do not change. Each setter checks its * request, so the window only draws and calls them. @@ -44,6 +44,7 @@ namespace Fling * on the resize path, after the next present. * - MaxFps: Engine::Present puts LimiterFps into the FrameLimiter, on the next frame. * - Interpolation: World::SetInterpolation, which holds it, on the next frame. + * - FrustumCulling: Engine::Present gives it to VulkanApp::SetFrustumCulling, on the next frame. * - SimHz: World::RequestSimHz, a SetRate clock command applied between two ticks, at the * next wake. The world holds the rate. * @@ -79,6 +80,10 @@ namespace Fling bool Interpolation() const; void SetInterpolation(bool t_On); + /** Frustum culling in the renderer (RunSettings::FrustumCulling). */ + bool FrustumCulling() const { return m_FrustumCulling; } + void SetFrustumCulling(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 @@ -134,6 +139,7 @@ namespace Fling uint32 m_InputTickRate = 0; bool m_VSync = true; + bool m_FrustumCulling = 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/RunControls.cpp b/FlingEngine/Engine/src/RunControls.cpp index 78933000..56749634 100644 --- a/FlingEngine/Engine/src/RunControls.cpp +++ b/FlingEngine/Engine/src/RunControls.cpp @@ -31,6 +31,7 @@ namespace Fling : m_World(t_World), m_InputTickRate(t_Startup.SimHz), m_VSync(t_Startup.VSync), + m_FrustumCulling(t_Startup.FrustumCulling), m_MaxFps(t_Startup.MaxFps), m_MaxFpsFollowsMonitor(t_Startup.MaxFpsSource == SettingSource::Monitor), m_MonitorHz(t_Startup.MonitorHz) @@ -46,6 +47,15 @@ namespace Fling } } + void RunControls::SetFrustumCulling(const bool t_On) + { + if (t_On != m_FrustumCulling) + { + m_FrustumCulling = t_On; + F_LOG_TRACE("Frustum culling {}", t_On ? "on" : "off"); + } + } + bool RunControls::SetMaxFps(const uint32 t_Fps, String& t_OutError) { t_OutError.clear(); diff --git a/FlingEngine/Graphics/inc/Frustum.h b/FlingEngine/Graphics/inc/Frustum.h new file mode 100644 index 00000000..0eead1f8 --- /dev/null +++ b/FlingEngine/Graphics/inc/Frustum.h @@ -0,0 +1,66 @@ +#pragma once + +#include "FlingMath.h" +#include "FlingTypes.h" +#include "GraphicsAPI.h" + +#include + +namespace Fling +{ + /** An axis-aligned box in a mesh's own space. A box with Min above Max on any axis is empty (not known). */ + struct Aabb + { + glm::vec3 Min{1.0f}; + glm::vec3 Max{-1.0f}; + + /** False for an empty box: nothing was added, so the bounds are not known. */ + bool IsValid() const { return Min.x <= Max.x && Min.y <= Max.y && Min.z <= Max.z; } + + /** Grow the box to hold t_Point. Adding to an empty box makes the box of that point alone. */ + GRAPHICS_API void Add(const glm::vec3& t_Point); + + /** The box around every point. Empty when there are none. */ + GRAPHICS_API static Aabb Of(std::span t_Points); + }; + + /** + * The six planes of a camera's view volume, in world space, for culling. Each plane is + * (n, d) with n pointing in: a point p is on the inside of the plane when dot(n, p) + d >= 0. + * + * The planes are those of the clip volume that Vulkan keeps: -w <= x <= w, -w <= y <= w and + * 0 <= z <= w. A y flip in the projection (Vulkan's y points down) only swaps the top and + * bottom planes, so the set is the same with or without it. + */ + struct Frustum + { + enum Side : uint32 + { + Left = 0, + Right, + Bottom, + Top, + Near, + Far, + Count + }; + + glm::vec4 Planes[Side::Count] = {}; + + /** + * The planes of t_ViewProjection (projection * view), the matrix that takes a world + * position to clip space. Each plane is normalized, so its distance is in world units. + */ + GRAPHICS_API static Frustum FromViewProjection(const glm::mat4& t_ViewProjection); + + /** + * True if any part of the box t_Local, placed in the world by t_World, can be inside the + * view volume. Conservative: it can say true for a box that is just outside a corner of + * the volume, never false for a box that is inside. An empty box is always visible. + */ + GRAPHICS_API bool Intersects(const Aabb& t_Local, const glm::mat4& t_World) const; + + /** True if any part of the world space box with centre t_Centre and half size t_Extents can be inside. */ + GRAPHICS_API bool IntersectsWorldBox(const glm::vec3& t_Centre, const glm::vec3& t_Extents) const; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/inc/MeshCuller.h b/FlingEngine/Graphics/inc/MeshCuller.h new file mode 100644 index 00000000..a5d38220 --- /dev/null +++ b/FlingEngine/Graphics/inc/MeshCuller.h @@ -0,0 +1,79 @@ +#pragma once + +#include "FlingTypes.h" +#include "Frustum.h" +#include "GraphicsAPI.h" +#include "RenderSnapshot.h" + +#include +#include + +namespace Fling +{ + /** What the last MeshCuller::Cull did, for the GPU Options window. */ + struct CullStats + { + /** Meshes the pass draws this frame. */ + uint32 Drawn = 0; + + /** Meshes the pass would draw, but that are outside the camera's view. */ + uint32 Culled = 0; + }; + + /** + * Frame side frustum culling for one render pass: which of its proxy slots (MeshProxyTable) + * are in the camera's view this frame. It holds no GPU data, so it can be tested without a + * device. The pass gives it each slot's local bounds when the slot's mesh is made, and calls + * Cull once a frame with the snapshot, after MeshProxyTable::Sync. + * + * The test uses the item's World matrix, the one the pass draws with (blended between the + * latest two ticks), and the camera of this frame. A slot whose bounds are not known is + * always visible. A culled mesh keeps its slot and its GPU resources: only its draw call + * and its uniform buffer write are skipped, so a mesh that comes back into view costs + * nothing to bring back. + */ + class MeshCuller + { + public: + /** + * A slot was made or changed. t_Drawn: the pass draws this slot's mesh at all (its + * material belongs to the pass). t_LocalBounds: the mesh's bounds in its own space. + */ + GRAPHICS_API void SetSlot(uint32 t_Slot, bool t_Drawn, const Aabb& t_LocalBounds); + + /** A slot was freed. */ + GRAPHICS_API void ClearSlot(uint32 t_Slot); + + /** Free every slot. */ + GRAPHICS_API void Clear(); + + /** + * Find the visible slots of this frame. + * + * @param t_Items The snapshot's meshes + * @param t_ItemSlots The slot of each item (MeshProxyTable::SyncResult::ItemSlots) + * @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); + + /** 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; } + + const CullStats& Stats() const { return m_Stats; } + + private: + struct SlotState + { + Aabb LocalBounds; + bool Drawn = false; + bool Visible = false; + }; + + SlotState& At(uint32 t_Slot); + + std::vector m_Slots; + CullStats m_Stats; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index df6de8d1..b320d2d7 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -2,6 +2,7 @@ #include "Ecs/EntityStorage.h" #include "FlingTypes.h" +#include "MeshCuller.h" #include "PresentMode.h" #include "Singleton.hpp" #include "Strings/String.h" @@ -51,6 +52,7 @@ namespace Fling class FirstPersonCamera; class DepthBuffer; class IDebugUI; + class OffscreenSubpass; class FrameCapturer; /** @@ -126,6 +128,16 @@ namespace Fling /** The present mode of the swap chain. */ PresentMode GetPresentMode() const; + /** + * Frustum culling on or off (RunSettings::FrustumCulling) for the next frame. On: the + * meshes outside the camera's view are not drawn (MeshCuller). The mesh pass holds the + * value, so it does nothing before Init; Engine::Present calls it before every frame. + */ + void SetFrustumCulling(bool t_On); + + /** The meshes the last frame drew and culled. Zero before the first frame and under --null-render. */ + CullStats GetCullStats() const; + /** What to draw to: a window or offscreen images, and the size. Call it before Init. */ void SetRenderSurface(const RenderSurfaceDesc& t_Desc) { m_SurfaceDesc = t_Desc; } @@ -199,6 +211,9 @@ namespace Fling /** @see SetVSync */ bool m_VSync = true; + /** The pass that draws the meshes, which culls them. Owned by m_RenderPipelines. */ + OffscreenSubpass* m_MeshPass = nullptr; + /** Keep a vector of command buffers that we want to use so that we can have one for each active frame */ std::vector m_DrawCmdBuffers; diff --git a/FlingEngine/Graphics/src/Frustum.cpp b/FlingEngine/Graphics/src/Frustum.cpp new file mode 100644 index 00000000..16a20039 --- /dev/null +++ b/FlingEngine/Graphics/src/Frustum.cpp @@ -0,0 +1,96 @@ +#include "Frustum.h" + +namespace Fling +{ + namespace + { + /** Row t_Row of a glm matrix (glm is column major: m[column][row]). */ + glm::vec4 Row(const glm::mat4& t_M, const int t_Row) + { + return glm::vec4(t_M[0][t_Row], t_M[1][t_Row], t_M[2][t_Row], t_M[3][t_Row]); + } + + glm::vec4 Normalized(const glm::vec4& t_Plane) + { + const float Length = glm::length(glm::vec3(t_Plane)); + return Length > 0.0f ? t_Plane / Length : t_Plane; + } + } // namespace + + void Aabb::Add(const glm::vec3& t_Point) + { + // Only the empty box starts again. A box made invalid by a NaN stays invalid, so it is never culled + if (Min.x > Max.x) + { + Min = t_Point; + Max = t_Point; + return; + } + Min = glm::min(Min, t_Point); + Max = glm::max(Max, t_Point); + } + + Aabb Aabb::Of(const std::span t_Points) + { + Aabb Box; + for (const glm::vec3& Point : t_Points) + { + Box.Add(Point); + } + return Box; + } + + Frustum Frustum::FromViewProjection(const glm::mat4& t_ViewProjection) + { + // A world point p is in the volume when its clip coordinates (row i . p) keep + // -w <= x <= w, -w <= y <= w and 0 <= z <= w (Gribb and Hartmann, with Vulkan's depth) + const glm::vec4 X = Row(t_ViewProjection, 0); + const glm::vec4 Y = Row(t_ViewProjection, 1); + const glm::vec4 Z = Row(t_ViewProjection, 2); + const glm::vec4 W = Row(t_ViewProjection, 3); + + Frustum Out; + Out.Planes[Left] = Normalized(W + X); + Out.Planes[Right] = Normalized(W - X); + Out.Planes[Bottom] = Normalized(W + Y); + Out.Planes[Top] = Normalized(W - Y); + Out.Planes[Near] = Normalized(Z); + Out.Planes[Far] = Normalized(W - Z); + return Out; + } + + bool Frustum::IntersectsWorldBox(const glm::vec3& t_Centre, const glm::vec3& t_Extents) const + { + for (const glm::vec4& Plane : Planes) + { + const glm::vec3 Normal(Plane); + // How far the box reaches toward the inside of the plane, from its centre + const float Reach = glm::dot(glm::abs(Normal), t_Extents); + // Strictly outside only: a box that touches the plane stays, and a NaN never culls + if (glm::dot(Normal, t_Centre) + Plane.w + Reach < 0.0f) + { + return false; + } + } + return true; + } + + bool Frustum::Intersects(const Aabb& t_Local, const glm::mat4& t_World) const + { + if (!t_Local.IsValid()) + { + return true; + } + // The world box around the placed local box: its centre moves with the matrix, and each + // world half size is the sum of the absolute linear parts (exact for an affine matrix) + const glm::vec3 LocalCentre = (t_Local.Min + t_Local.Max) * 0.5f; + const glm::vec3 LocalExtents = (t_Local.Max - t_Local.Min) * 0.5f; + const glm::vec3 Centre = glm::vec3(t_World * glm::vec4(LocalCentre, 1.0f)); + glm::vec3 Extents(0.0f); + for (int Axis = 0; Axis < 3; ++Axis) + { + Extents += glm::abs(glm::vec3(t_World[Axis])) * LocalExtents[Axis]; + } + return IntersectsWorldBox(Centre, Extents); + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/Instance.cpp b/FlingEngine/Graphics/src/Instance.cpp index faf89b56..39841604 100644 --- a/FlingEngine/Graphics/src/Instance.cpp +++ b/FlingEngine/Graphics/src/Instance.cpp @@ -32,7 +32,10 @@ namespace Fling { if (m_EnableValidationLayers && !CheckValidationLayerSupport()) { - F_LOG_WARN("Validation layers are requested, but not available!"); + // Asking for a layer that is not installed makes vkCreateInstance fail, so run without it + F_LOG_WARN("Validation layers are requested, but not available! Install the Vulkan SDK (or the " + "Khronos validation layer package). Running without validation."); + m_EnableValidationLayers = false; } // Basic app data that we can modify diff --git a/FlingEngine/Graphics/src/Instance.h b/FlingEngine/Graphics/src/Instance.h index ae425d87..607c2de2 100644 --- a/FlingEngine/Graphics/src/Instance.h +++ b/FlingEngine/Graphics/src/Instance.h @@ -104,8 +104,12 @@ namespace Fling void SetupDebugMessages(); #endif - /** The validation layers that we want to look for on this instance */ - const std::vector m_ValidationLayers = {"VK_LAYER_LUNARG_standard_validation"}; + /** + * The validation layers that we want to look for on this instance. VK_LAYER_KHRONOS_validation + * is the one validation layer of every Vulkan SDK since 1.1.106 (2019); it replaced + * VK_LAYER_LUNARG_standard_validation, which current SDKs do not have. + */ + const std::vector m_ValidationLayers = {"VK_LAYER_KHRONOS_validation"}; /** The device extensions to enable: VK_KHR_swapchain with a surface, none offscreen */ std::vector m_DeviceExtensions; diff --git a/FlingEngine/Graphics/src/MeshCuller.cpp b/FlingEngine/Graphics/src/MeshCuller.cpp new file mode 100644 index 00000000..cc9bb11b --- /dev/null +++ b/FlingEngine/Graphics/src/MeshCuller.cpp @@ -0,0 +1,61 @@ +#include "MeshCuller.h" + +namespace Fling +{ + MeshCuller::SlotState& MeshCuller::At(const uint32 t_Slot) + { + if (t_Slot >= m_Slots.size()) + { + m_Slots.resize(size_t{t_Slot} + 1); + } + return m_Slots[t_Slot]; + } + + void MeshCuller::SetSlot(const uint32 t_Slot, const bool t_Drawn, const Aabb& t_LocalBounds) + { + SlotState& Slot = At(t_Slot); + Slot.LocalBounds = t_LocalBounds; + Slot.Drawn = t_Drawn; + // Not visible until the next Cull decides, so a new mesh counts as a change there + Slot.Visible = false; + } + + void MeshCuller::ClearSlot(const uint32 t_Slot) + { + if (t_Slot < m_Slots.size()) + { + m_Slots[t_Slot] = SlotState{}; + } + } + + void MeshCuller::Clear() + { + m_Slots.clear(); + m_Stats = {}; + } + + bool MeshCuller::Cull(const std::span t_Items, + const std::span t_ItemSlots, + const Frustum* t_Frustum) + { + bool bChanged = false; + m_Stats = {}; + for (size_t i = 0; i < t_Items.size() && i < t_ItemSlots.size(); ++i) + { + if (t_ItemSlots[i] >= m_Slots.size()) + { + continue; + } + SlotState& Slot = m_Slots[t_ItemSlots[i]]; + if (!Slot.Drawn) + { + continue; + } + const bool bVisible = t_Frustum == nullptr || t_Frustum->Intersects(Slot.LocalBounds, t_Items[i].World); + bChanged |= bVisible != Slot.Visible; + Slot.Visible = bVisible; + ++(bVisible ? m_Stats.Drawn : m_Stats.Culled); + } + return bChanged; + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/Model.cpp b/FlingEngine/Graphics/src/Model.cpp index d1fa49cc..7b3ed4d3 100644 --- a/FlingEngine/Graphics/src/Model.cpp +++ b/FlingEngine/Graphics/src/Model.cpp @@ -92,6 +92,7 @@ namespace Fling static_cast(m_Verts.size()), m_Indices.data(), static_cast(m_Indices.size())); + CalculateLocalBounds(); CreateBuffers(); } @@ -149,9 +150,19 @@ namespace Fling m_Indices.data(), static_cast(m_Indices.size())); + CalculateLocalBounds(); CreateBuffers(); } + void Model::CalculateLocalBounds() + { + m_LocalBounds = Aabb{}; + for (const Vertex& Vert : m_Verts) + { + m_LocalBounds.Add(Vert.Pos); + } + } + void Model::CreateBuffers() { // Under --null-render there is no GPU device. Keep the CPU vertex and index data only. diff --git a/FlingEngine/Graphics/src/Model.h b/FlingEngine/Graphics/src/Model.h index 5af900fa..053c0833 100644 --- a/FlingEngine/Graphics/src/Model.h +++ b/FlingEngine/Graphics/src/Model.h @@ -1,6 +1,7 @@ #pragma once #include "Buffer.h" +#include "Frustum.h" #include "Resource.h" #include "Vertex.h" @@ -46,14 +47,23 @@ namespace Fling constexpr static VkIndexType GetIndexType() { return VK_INDEX_TYPE_UINT32; } + /** The box around every vertex, in the model's own space. Empty when the model has no vertices. */ + FORCEINLINE const Aabb& GetLocalBounds() const { return m_LocalBounds; } + private: void CreateBuffers(); + /** Set m_LocalBounds from m_Verts */ + void CalculateLocalBounds(); + static void CalculateVertexTangents(Vertex* verts, uint32 numVerts, uint32* indices, uint32 numIndices); std::vector m_Verts; std::vector m_Indices; + /** @see GetLocalBounds */ + Aabb m_LocalBounds; + Buffer* m_VertexBuffer = nullptr; Buffer* m_IndexBuffer = nullptr; diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.cpp b/FlingEngine/Graphics/src/OffscreenSubpass.cpp index d38a52c3..2988a694 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.cpp +++ b/FlingEngine/Graphics/src/OffscreenSubpass.cpp @@ -15,6 +15,8 @@ #include "SwapChain.h" #include "UniformBufferObject.h" +#include + namespace Fling { OffscreenSubpass::OffscreenSubpass(const LogicalDevice* t_Dev, @@ -83,6 +85,9 @@ namespace Fling delete m_CameraUboBuffer; m_CameraUboBuffer = nullptr; + + delete m_DrawCommands; + m_DrawCommands = nullptr; } void OffscreenSubpass::Draw(CommandBuffer& t_CmdBuf, @@ -109,7 +114,12 @@ namespace Fling CameraUBO.View = m_Camera->GetViewMatrix(); memcpy(m_CameraUboBuffer->m_MappedMem, &CameraUBO, sizeof(CameraUBO)); + // The view volume of exactly the matrices the shader uses this frame + m_CameraViewProjection = CameraUBO.Projection * CameraUBO.View; + CullMeshes(t_Snapshot); + UpdateMeshUniformBuffers(t_Snapshot); + WriteDrawCommands(); // The command buffer holds only draw calls and descriptor bindings, not // UBO data. Keep the last recording if the draw list did not change. @@ -130,6 +140,7 @@ namespace Fling for (const uint32 Slot : Result.Removed) { RetireGpuMesh(m_GpuMeshes[Slot]); + m_Culler.ClearSlot(Slot); } auto Prepare = [&](const uint32 Slot) @@ -141,6 +152,7 @@ namespace Fling { // Another pass draws it (a debug material), or there is no model RetireGpuMesh(Mesh); + m_Culler.SetSlot(Slot, false, Aabb{}); return; } @@ -154,6 +166,8 @@ namespace Fling } CreateMeshDescriptorSet(Mesh); Mesh.UploadedVersion = 0; + // The same test the recording uses, so the culler counts only what gets a draw call + m_Culler.SetSlot(Slot, IsDrawable(Mesh), Mesh.MeshModel->GetLocalBounds()); }; for (const uint32 Slot : Result.Added) @@ -171,6 +185,7 @@ namespace Fling { InvalidateCommandBuffers(); } + EnsureDrawCommandCapacity(); } void OffscreenSubpass::RetireGpuMesh(GpuMesh& t_Mesh) @@ -186,13 +201,68 @@ namespace Fling t_Mesh = GpuMesh{}; } + 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); + } + + void OffscreenSubpass::EnsureDrawCommandCapacity() + { + const size_t Needed = std::max(m_GpuMeshes.size(), 1); + if (m_DrawCommands != nullptr && m_DrawCommandCapacity >= Needed) + { + return; + } + // Grow by doubling. The recordings point at the old buffer, so they record again; it + // is deleted with the retired UBOs, once the GPU is done with the frame that used it + size_t Capacity = std::max(m_DrawCommandCapacity, 64); + while (Capacity < Needed) + { + Capacity *= 2; + } + if (m_DrawCommands != nullptr) + { + m_RetiredUniformBuffers.emplace_back(m_DrawCommands); + } + const VkDeviceSize Size = sizeof(VkDrawIndexedIndirectCommand) * Capacity; + m_DrawCommands = new Buffer(Size, + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + m_DrawCommands->MapMemory(Size); + m_DrawCommandCapacity = Capacity; + InvalidateCommandBuffers(); + } + + void OffscreenSubpass::WriteDrawCommands() + { + // One buffer is enough: each frame waits for the GPU to finish before the next frame + // writes it (as with the camera UBO) + auto* Commands = static_cast(m_DrawCommands->m_MappedMem); + for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) + { + const GpuMesh& Mesh = m_GpuMeshes[Slot]; + VkDrawIndexedIndirectCommand& Command = Commands[Slot]; + Command = {}; + if (IsDrawable(Mesh)) + { + Command.indexCount = Mesh.MeshModel->GetIndexCount(); + Command.instanceCount = m_Culler.IsVisible(Slot) ? 1 : 0; + } + } + } + void OffscreenSubpass::UpdateMeshUniformBuffers(const RenderSnapshot& t_Snapshot) { for (size_t i = 0; i < t_Snapshot.Meshes.size() && i < m_ItemSlots.size(); ++i) { const MeshDrawItem& Item = t_Snapshot.Meshes[i]; - GpuMesh& Mesh = m_GpuMeshes[m_ItemSlots[i]]; - if (!Mesh.Drawn || Mesh.Ubo == nullptr) + const uint32 Slot = m_ItemSlots[i]; + GpuMesh& Mesh = m_GpuMeshes[Slot]; + // A culled mesh keeps its last upload; its version shows that it is old when it is back in view + if (!Mesh.Drawn || Mesh.Ubo == nullptr || !m_Culler.IsVisible(Slot)) { continue; } @@ -234,9 +304,12 @@ namespace Fling VkDeviceSize offsets[1] = {0}; - for (const GpuMesh& Mesh : m_GpuMeshes) + for (uint32 Slot = 0; Slot < m_GpuMeshes.size(); ++Slot) { - if (!Mesh.Drawn || Mesh.MeshModel == nullptr || Mesh.Set == VK_NULL_HANDLE) + const GpuMesh& Mesh = m_GpuMeshes[Slot]; + // Every drawable slot is recorded, in view or not: its indirect command's instance + // count, written each frame, decides whether it draws + if (!IsDrawable(Mesh)) { continue; } @@ -256,7 +329,11 @@ namespace Fling vkCmdBindVertexBuffers(t_CmdBuf.GetHandle(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer( t_CmdBuf.GetHandle(), Model->GetIndexBuffer()->GetVkBuffer(), 0, Model->GetIndexType()); - vkCmdDrawIndexed(t_CmdBuf.GetHandle(), Model->GetIndexCount(), 1, 0, 0, 0); + vkCmdDrawIndexedIndirect(t_CmdBuf.GetHandle(), + m_DrawCommands->GetVkBuffer(), + sizeof(VkDrawIndexedIndirectCommand) * Slot, + 1, + sizeof(VkDrawIndexedIndirectCommand)); } t_CmdBuf.EndRenderPass(); @@ -438,6 +515,7 @@ namespace Fling RetireGpuMesh(Mesh); } m_GpuMeshes.clear(); + m_Culler.Clear(); m_Proxies.Clear(); m_ItemSlots.clear(); ReleaseRetiredMeshResources(); diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.h b/FlingEngine/Graphics/src/OffscreenSubpass.h index 805eb086..6156c0b5 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.h +++ b/FlingEngine/Graphics/src/OffscreenSubpass.h @@ -2,6 +2,7 @@ #include "FlingMath.h" #include "GpuMesh.h" +#include "MeshCuller.h" #include "MeshProxyTable.h" #include "Subpass.h" @@ -70,6 +71,17 @@ namespace Fling virtual void OnSwapchainResized() override final; + /** + * Frustum culling on or off (RunSettings::FrustumCulling). On: a mesh whose bounds are + * outside the camera's view is not drawn and its uniform buffer is not written. Takes + * effect on the next Draw. The pass holds the renderer's only copy: VulkanApp passes the + * value on, and Engine::Present sets it before every frame from RunControls. + */ + void SetFrustumCulling(const bool t_On) { m_FrustumCulling = t_On; } + + /** What the last Draw drew and culled. */ + const CullStats& GetCullStats() const { return m_Culler.Stats(); } + private: /** * Match the proxies to the snapshot: release the resources of meshes that are @@ -88,7 +100,28 @@ namespace Fling /** Write the UBO of each mesh whose world matrix changed since its last upload */ void UpdateMeshUniformBuffers(const RenderSnapshot& t_Snapshot); - /** Record the draw calls for every drawn proxy into the given command buffer */ + /** + * 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); + + /** Make m_DrawCommands hold one command per slot. A new buffer makes the recordings out of date. */ + void EnsureDrawCommandCapacity(); + + /** Write each slot's indirect draw for this frame: its index count, and 1 instance if visible, else 0 */ + void WriteDrawCommands(); + + /** True if the pass records a draw for the mesh: the pass draws it and it has its GPU resources */ + static bool IsDrawable(const GpuMesh& t_Mesh) + { + return t_Mesh.Drawn && t_Mesh.MeshModel != nullptr && t_Mesh.Set != VK_NULL_HANDLE; + } + + /** + * Record an indirect draw for every drawable proxy, visible or not, into the given + * command buffer. The recording changes only with the draw list, not with the camera. + */ void BuildOffscreenCommandBuffer(CommandBuffer& t_CmdBuf); /** Make each offscreen command buffer record again on its next use */ @@ -112,6 +145,19 @@ namespace Fling /** Camera UBO that every mesh descriptor set points to */ Buffer* m_CameraUboBuffer = nullptr; + /** Projection * view of this frame's camera UBO, for culling */ + glm::mat4 m_CameraViewProjection{1.0f}; + + /** + * One VkDrawIndexedIndirectCommand per proxy slot, which the recorded draws read. The + * CPU writes the instance counts each frame (WriteDrawCommands), so culling a mesh or + * bringing it back needs no new recording. + */ + Buffer* m_DrawCommands = nullptr; + + /** The number of commands m_DrawCommands holds */ + size_t m_DrawCommandCapacity = 0; + /** * Goes up by one each time the draw list changes. A command buffer records * again only when its recorded version is different from this value. @@ -130,6 +176,12 @@ namespace Fling /** The proxy slot of each snapshot mesh, from the last SyncProxies */ std::vector m_ItemSlots; + /** Which slots are in the camera's view, indexed by slot like m_GpuMeshes */ + MeshCuller m_Culler; + + /** @see SetFrustumCulling */ + bool m_FrustumCulling = true; + /** * 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 @@ -137,7 +189,10 @@ namespace Fling */ std::vector m_RetiredDescriptorSets; - /** UBOs of destroyed meshes. Deleted at the same time as m_RetiredDescriptorSets. */ + /** + * UBOs of destroyed meshes, and draw command buffers that were replaced by a larger one. + * Deleted at the same time as m_RetiredDescriptorSets. + */ std::vector m_RetiredUniformBuffers; }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Graphics/src/SwapChain.cpp b/FlingEngine/Graphics/src/SwapChain.cpp index 3ba398ce..7d91264c 100644 --- a/FlingEngine/Graphics/src/SwapChain.cpp +++ b/FlingEngine/Graphics/src/SwapChain.cpp @@ -35,7 +35,11 @@ namespace Fling PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, const bool t_VSync) - : m_VSync(t_VSync), m_Extents{t_Extent}, m_Device(t_Dev), m_PhysicalDevice(t_PhysDev), m_Surface(t_Surface) + : m_VSync(t_VSync), + m_Extents{t_Extent}, + m_Device(t_Dev), + m_PhysicalDevice(t_PhysDev), + m_Surface(t_Surface) { assert(m_Device && m_PhysicalDevice && m_Surface); Recreate(m_Extents); diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 7d6d68a0..6ce36e86 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -20,6 +20,7 @@ #include "PhyscialDevice.h" #include "RenderPipeline.h" #include "RenderSnapshot.h" +#include "Screenshot.h" #include "SkyboxSubpass.h" #include "Strings/String.h" #include "SwapChain.h" @@ -413,6 +414,19 @@ namespace Fling bSwapchainOutOfDate = true; } + void VulkanApp::SetFrustumCulling(const bool t_On) + { + if (m_MeshPass != nullptr) + { + m_MeshPass->SetFrustumCulling(t_On); + } + } + + CullStats VulkanApp::GetCullStats() const + { + return m_MeshPass != nullptr ? m_MeshPass->GetCullStats() : CullStats{}; + } + void VulkanApp::SetVSync(const bool t_VSync) { if (t_VSync == m_VSync) @@ -520,6 +534,7 @@ namespace Fling // These shaders do not have any vertex input and do the final processing to the screen OffscreenSubpass* Offscreen = static_cast(Subpasses[0].get()); assert(Offscreen); + m_MeshPass = Offscreen; FrameBuffer* OffscreenBuf = Offscreen->GetOffscreenFrameBuffer(); assert(OffscreenBuf); @@ -826,6 +841,7 @@ namespace Fling m_LogicalDevice->WaitForIdle(); // Cleanup render pipelines (created in BuildRenderPipelines) ----------------- + m_MeshPass = nullptr; for (RenderPipeline* pipeline : m_RenderPipelines) { if (pipeline) diff --git a/FlingEngine/Graphics/src/VulkanFunctions.inl b/FlingEngine/Graphics/src/VulkanFunctions.inl index 05818299..059fa01d 100644 --- a/FlingEngine/Graphics/src/VulkanFunctions.inl +++ b/FlingEngine/Graphics/src/VulkanFunctions.inl @@ -88,6 +88,7 @@ FLING_VK_DEVICE(vkCmdCopyBufferToImage) FLING_VK_DEVICE(vkCmdCopyImageToBuffer) FLING_VK_DEVICE(vkCmdDraw) FLING_VK_DEVICE(vkCmdDrawIndexed) +FLING_VK_DEVICE(vkCmdDrawIndexedIndirect) FLING_VK_DEVICE(vkCmdEndRenderPass) FLING_VK_DEVICE(vkCmdNextSubpass) FLING_VK_DEVICE(vkCmdPipelineBarrier) diff --git a/FlingTests/Core/RunSettingsTests.cpp b/FlingTests/Core/RunSettingsTests.cpp index ee2f5faa..5540403a 100644 --- a/FlingTests/Core/RunSettingsTests.cpp +++ b/FlingTests/Core/RunSettingsTests.cpp @@ -37,6 +37,8 @@ TEST_CASE("Run settings: the defaults are threaded play at 30 Hz with VSync and REQUIRE(Settings.VSyncSource == SettingSource::Default); REQUIRE(Settings.Interpolation); REQUIRE(Settings.InterpolationSource == SettingSource::Default); + REQUIRE(Settings.FrustumCulling); + REQUIRE(Settings.FrustumCullingSource == SettingSource::Default); REQUIRE(Settings.Ignored.empty()); REQUIRE(SimRate::StepNs(Settings.SimHz) == 33'333'333); REQUIRE(SimRate::StepNs(60) == 16'666'667); @@ -110,8 +112,12 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins { RunSettings Settings; String Error; - const RunSettingsConfig Config{ - .Exec = "direct", .SimHz = "60", .MaxFps = "120", .VSync = "off", .Interpolation = "off"}; + const RunSettingsConfig Config{.Exec = "direct", + .SimHz = "60", + .MaxFps = "120", + .VSync = "off", + .Interpolation = "off", + .FrustumCulling = "off"}; REQUIRE(Resolve({}, Config, Settings, Error)); REQUIRE(Settings.Exec == ExecMode::Direct); @@ -124,20 +130,35 @@ TEST_CASE("Run settings: the command line wins over the config file, which wins REQUIRE(Settings.VSyncSource == SettingSource::Config); REQUIRE_FALSE(Settings.Interpolation); REQUIRE(Settings.InterpolationSource == SettingSource::Config); + REQUIRE_FALSE(Settings.FrustumCulling); + REQUIRE(Settings.FrustumCullingSource == SettingSource::Config); - REQUIRE(Resolve({"--exec", "inline", "--sim-hz", "20", "--max-fps", "75", "--vsync", "on", "--interpolation", "on"}, + REQUIRE(Resolve({"--exec", + "inline", + "--sim-hz", + "20", + "--max-fps", + "75", + "--vsync", + "on", + "--interpolation", + "on", + "--frustum-culling", + "on"}, Config, 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)"); + "(command line), vsync on (command line), interpolation on (command line), " + "frustum culling on (command line)"); // 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)"); + "monitor's refresh rate), vsync on (default), interpolation on (default), " + "frustum culling on (default)"); } TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") @@ -147,6 +168,7 @@ TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") {"MaxFps", "90"}, {"VSync", "off"}, {"Interpolation", "off"}, + {"FrustumCulling", "off"}, {"PresentMode", "mailbox"}}; const RunSettingsConfig Config = RunSettingsConfig::Read( [&File](const char* t_Key) @@ -159,6 +181,7 @@ TEST_CASE("Run settings: every config key is read by its name", "[RunSettings]") REQUIRE(Config.MaxFps == "90"); REQUIRE(Config.VSync == "off"); REQUIRE(Config.Interpolation == "off"); + REQUIRE(Config.FrustumCulling == "off"); } TEST_CASE("Run settings: a bad value in a config key is an error, also when a flag wins over it", "[RunSettings]") @@ -193,6 +216,9 @@ TEST_CASE("Run settings: a bad value in a config key is an error, also when a fl Fails(Args({"--interpolation", "on"}), {.Interpolation = "1"}, "[Engine] Interpolation in EngineConf.ini must be on or off"); + Fails(Args({"--frustum-culling", "on"}), + {.FrustumCulling = "yes"}, + "[Engine] FrustumCulling in EngineConf.ini must be on or off"); } } @@ -240,6 +266,22 @@ TEST_CASE("Run settings: --vsync with --null-render does nothing, and says so", REQUIRE(Settings.Ignored.empty()); } +TEST_CASE("Run settings: --frustum-culling with --null-render does nothing, and says so; --offscreen draws", + "[RunSettings]") +{ + RunSettings Settings; + String Error; + REQUIRE(Resolve({"--null-render", "--frustum-culling", "off"}, {}, Settings, Error)); + REQUIRE_FALSE(Settings.FrustumCulling); + REQUIRE(Settings.Ignored == + std::vector{"--frustum-culling does nothing with --null-render: nothing is drawn"}); + REQUIRE(Resolve({"--offscreen", "--frustum-culling", "off"}, {}, Settings, Error)); + REQUIRE(Settings.Ignored.empty()); + LaunchOptions Options; + REQUIRE_FALSE(TestArgs::ParseLaunchArgs({"--frustum-culling", "maybe"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--frustum-culling")); +} + TEST_CASE("Run settings: the frame limiter keeps the lower of the cap and the display's refresh rate", "[RunSettings]") { SECTION("The display does not pace the frames (VSync off): the cap, whatever the display") diff --git a/FlingTests/Engine/RunControlsTests.cpp b/FlingTests/Engine/RunControlsTests.cpp index d1d20a63..12ef1af1 100644 --- a/FlingTests/Engine/RunControlsTests.cpp +++ b/FlingTests/Engine/RunControlsTests.cpp @@ -38,9 +38,11 @@ TEST_CASE("Run controls: the live values start from the startup settings, which ThreadedWorldHarness Harness(HarnessOptions{}); RunSettings Settings = OnMonitor(60); Settings.VSync = false; + Settings.FrustumCulling = false; const RunSettings Startup = Settings; RunControls Controls(Settings, Harness.GetWorld()); REQUIRE_FALSE(Controls.VSync()); + REQUIRE_FALSE(Controls.FrustumCulling()); REQUIRE(Controls.MaxFps() == 60); REQUIRE(Controls.MonitorHz() == 60u); @@ -48,10 +50,13 @@ TEST_CASE("Run controls: the live values start from the startup settings, which Controls.SetVSync(true); REQUIRE(Controls.SetMaxFps(90, Error)); Controls.SetInterpolation(false); + Controls.SetFrustumCulling(true); REQUIRE(Controls.VSync()); REQUIRE(Controls.MaxFps() == 90); + REQUIRE(Controls.FrustumCulling()); REQUIRE(Settings.Describe() == Startup.Describe()); REQUIRE_FALSE(Settings.VSync); + REQUIRE_FALSE(Settings.FrustumCulling); } TEST_CASE("Run controls: the frame cap takes 0 to 1000, and an error is cleared by the next good value", diff --git a/FlingTests/Graphics/FrustumCullingTests.cpp b/FlingTests/Graphics/FrustumCullingTests.cpp new file mode 100644 index 00000000..195499bb --- /dev/null +++ b/FlingTests/Graphics/FrustumCullingTests.cpp @@ -0,0 +1,417 @@ +#include "Components/Transform.h" +#include "Ecs/SystemRegistry.h" +#include "Ecs/SystemRunner.h" +#include "FlingMath.h" +#include "Frustum.h" +#include "MeshCuller.h" +#include "MeshProxyTable.h" +#include "MeshRenderer.h" +#include "RenderSnapshot.h" +#include "SimRandom.h" +#include "Systems/PublishSnapshotSystem.h" +#include "Systems/TransformSystem.h" + +#include +#include +#include +#include +#include + +using namespace Fling; + +namespace +{ + /** + * The renderer's matrices for a camera at t_Eye looking at t_Target: a 90 degree + * perspective, aspect 1, near 0.1, far 100, with Vulkan's y flip when t_FlipY (the + * offscreen pass flips it). + */ + glm::mat4 ViewProjection(const glm::vec3& t_Eye, const glm::vec3& t_Target, const bool t_FlipY = true) + { + glm::mat4 Projection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 100.0f); + if (t_FlipY) + { + Projection[1][1] *= -1.0f; + } + const glm::mat4 View = glm::lookAt(t_Eye, t_Target, glm::vec3(0.0f, 1.0f, 0.0f)); + return Projection * View; + } + + /** The default camera of these tests: at the origin, looking down -z. */ + glm::mat4 ForwardCamera(const bool t_FlipY = true) + { + return ViewProjection(glm::vec3(0.0f), glm::vec3(0.0f, 0.0f, -1.0f), t_FlipY); + } + + /** What the GPU keeps: the point's clip coordinates are in -w <= x, y <= w and 0 <= z <= w. */ + bool InClipVolume(const glm::mat4& t_ViewProjection, const glm::vec3& t_Point) + { + const glm::vec4 Clip = t_ViewProjection * glm::vec4(t_Point, 1.0f); + return Clip.w > 0.0f && -Clip.w <= Clip.x && Clip.x <= Clip.w && -Clip.w <= Clip.y && Clip.y <= Clip.w && + 0.0f <= Clip.z && Clip.z <= Clip.w; + } + + bool InsideAllPlanes(const Frustum& t_Frustum, const glm::vec3& t_Point) + { + for (const glm::vec4& Plane : t_Frustum.Planes) + { + if (glm::dot(glm::vec3(Plane), t_Point) + Plane.w < 0.0f) + { + return false; + } + } + return true; + } + + const Aabb UnitCube{glm::vec3(-0.5f), glm::vec3(0.5f)}; + + glm::mat4 At(const glm::vec3& t_Position) + { + return glm::translate(glm::mat4(1.0f), t_Position); + } + + float Uniform(SimRandom& t_Random, const float t_Min, const float t_Max) + { + return t_Random.Range(t_Min, t_Max); + } + + /** A world with only Engine.Transform and Graphics.PublishSnapshot, as the renderer sees it. */ + struct PublishHarness + { + EntityStorage Storage; + SystemRegistry Systems; + std::unique_ptr Runner; + + PublishHarness() + { + Systems.Add(); + Systems.Add(); + ScheduleResult schedule = Systems.BuildSchedule(); + REQUIRE(schedule.ErrorReport() == ""); + SystemRunnerConfig config; + config.OneTickPerFrame = true; + Runner = std::make_unique(Systems, std::move(schedule.Value), Storage, config); + Runner->Create(); + } + + ~PublishHarness() { Runner->Destroy(); } + + const RenderSnapshot& Frame() + { + Runner->RunTick(WorldRole::Play); + Runner->RunFrame(std::chrono::milliseconds(16), WorldRole::Play); + return Storage.Singleton(); + } + + Entity Mesh(const glm::vec3& t_Position) + { + const Entity Made = Storage.Create(); + Storage.Add(Made, Transform{t_Position}); + Storage.Add(Made, MeshRenderer("Models/cube.obj")); + return Made; + } + }; + + /** The renderer's per frame steps on the CPU side: sync the proxies, give new slots their bounds, cull. */ + struct PassHarness + { + MeshProxyTable Proxies; + MeshCuller Culler; + std::vector ItemSlots; + + bool Draw(const RenderSnapshot& t_Snapshot, const Frustum* t_Frustum) + { + MeshProxyTable::SyncResult Result = Proxies.Sync(t_Snapshot.Meshes); + for (const uint32 Slot : Result.Removed) + { + Culler.ClearSlot(Slot); + } + for (const uint32 Slot : Result.Added) + { + Culler.SetSlot(Slot, true, UnitCube); + } + ItemSlots = std::move(Result.ItemSlots); + return Culler.Cull(t_Snapshot.Meshes, ItemSlots, t_Frustum); + } + + bool Visible(const Entity t_Entity) const { return Culler.IsVisible(Proxies.SlotOf(t_Entity.ToBits())); } + }; +} // namespace + +TEST_CASE("Frustum: the planes keep exactly the points of Vulkan's clip volume", "[graphics][culling]") +{ + for (const bool bFlipY : {true, false}) + { + CAPTURE(bFlipY); + const glm::mat4 Matrix = ForwardCamera(bFlipY); + const Frustum View = Frustum::FromViewProjection(Matrix); + + // Each plane is normalized, and the near and far planes face along the view axis + for (const glm::vec4& Plane : View.Planes) + { + REQUIRE(glm::length(glm::vec3(Plane)) == Catch::Approx(1.0f)); + } + REQUIRE(View.Planes[Frustum::Near].z == Catch::Approx(-1.0f)); + REQUIRE(View.Planes[Frustum::Near].w == Catch::Approx(-0.1f)); + REQUIRE(View.Planes[Frustum::Far].z == Catch::Approx(1.0f)); + REQUIRE(View.Planes[Frustum::Far].w == Catch::Approx(100.0f)); + + REQUIRE(InsideAllPlanes(View, glm::vec3(0.0f, 0.0f, -1.0f))); + // Outside each of the six planes in turn + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(-2.0f, 0.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(2.0f, 0.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, -2.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, 2.0f, -1.0f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, 0.0f, -0.05f))); + REQUIRE_FALSE(InsideAllPlanes(View, glm::vec3(0.0f, 0.0f, -101.0f))); + + // The same answer as the clip test for points all around the camera + SimRandom Random(7, 1); + int Inside = 0; + for (int i = 0; i < 2000; ++i) + { + const glm::vec3 Point( + Uniform(Random, -60.0f, 60.0f), Uniform(Random, -60.0f, 60.0f), Uniform(Random, -120.0f, 10.0f)); + const glm::vec4 Clip = Matrix * glm::vec4(Point, 1.0f); + // Points within a hair of a plane can round either way + const float Margin = 1e-3f * glm::abs(Clip.w); + if (glm::abs(Clip.w - glm::abs(Clip.x)) < Margin || glm::abs(Clip.w - glm::abs(Clip.y)) < Margin || + glm::abs(Clip.z) < Margin || glm::abs(Clip.w - Clip.z) < Margin) + { + continue; + } + CAPTURE(Point.x, Point.y, Point.z); + const bool bInClip = InClipVolume(Matrix, Point); + REQUIRE(InsideAllPlanes(View, Point) == bInClip); + Inside += bInClip ? 1 : 0; + } + // Both answers were tested many times + REQUIRE(Inside > 100); + REQUIRE(Inside < 1900); + } +} + +TEST_CASE("Frustum: boxes inside, outside each plane, straddling, and behind the camera", "[graphics][culling]") +{ + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + + // At z = -5 the view is 5 wide on each side of the axis + REQUIRE(View.Intersects(UnitCube, At({0.0f, 0.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({-10.0f, 0.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({10.0f, 0.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, -10.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, 10.0f, -5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, 0.0f, -200.0f}))); + + // Behind the camera, also where the clip w is negative + REQUIRE_FALSE(View.Intersects(UnitCube, At({0.0f, 0.0f, 5.0f}))); + REQUIRE_FALSE(View.Intersects(UnitCube, At({3.0f, 3.0f, 5.0f}))); + + // The centre is outside the right plane, but the near left edge is inside + REQUIRE(View.Intersects(UnitCube, At({5.3f, 0.0f, -5.0f}))); + // The centre is past the far plane, but the near face is inside + REQUIRE(View.Intersects(UnitCube, At({0.0f, 0.0f, -100.3f}))); + // Across the near plane, around the camera + REQUIRE(View.Intersects(UnitCube, At({0.0f, 0.0f, 0.0f}))); + // A box much bigger than the view, around the camera + REQUIRE(View.Intersects(Aabb{glm::vec3(-1000.0f), glm::vec3(1000.0f)}, glm::mat4(1.0f))); + + // A box whose bounds are not known is never culled + REQUIRE_FALSE(Aabb{}.IsValid()); + REQUIRE(View.Intersects(Aabb{}, At({0.0f, 0.0f, 50.0f}))); +} + +TEST_CASE("Frustum: the world matrix places, turns and scales the box", "[graphics][culling]") +{ + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + + // A long thin box whose centre is outside the right plane at z = -5 (x = 7) + const Aabb Rod{glm::vec3(-4.0f, -0.1f, -0.1f), glm::vec3(4.0f, 0.1f, 0.1f)}; + REQUIRE(View.Intersects(Rod, At({7.0f, 0.0f, -5.0f}))); + // Turned to point along y, it no longer reaches across the right plane + const glm::mat4 Turned = glm::rotate(At({7.0f, 0.0f, -5.0f}), glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f)); + REQUIRE_FALSE(View.Intersects(Rod, Turned)); + + // A unit cube at x = 8 is outside; scaled by 6 it reaches back to z = -8, where the view is 8 wide + REQUIRE_FALSE(View.Intersects(UnitCube, At({8.0f, 0.0f, -5.0f}))); + REQUIRE(View.Intersects(UnitCube, glm::scale(At({8.0f, 0.0f, -5.0f}), glm::vec3(6.0f)))); +} + +TEST_CASE("Frustum: a turned camera culls by its own view", "[graphics][culling]") +{ + // At (0, 0, 10), looking along +x + const glm::vec3 Eye(0.0f, 0.0f, 10.0f); + const Frustum View = Frustum::FromViewProjection(ViewProjection(Eye, Eye + glm::vec3(1.0f, 0.0f, 0.0f))); + REQUIRE(View.Intersects(UnitCube, At(Eye + glm::vec3(5.0f, 0.0f, 0.0f)))); + REQUIRE_FALSE(View.Intersects(UnitCube, At(Eye + glm::vec3(-5.0f, 0.0f, 0.0f)))); + REQUIRE_FALSE(View.Intersects(UnitCube, At(Eye + glm::vec3(0.0f, 0.0f, -5.0f)))); + REQUIRE_FALSE(View.Intersects(UnitCube, At(glm::vec3(0.0f)))); + + // Looking down, a little turned: what is under the camera is in view, what is above is not + const Frustum Down = Frustum::FromViewProjection(ViewProjection(Eye, Eye + glm::vec3(0.1f, -1.0f, 0.2f))); + REQUIRE(Down.Intersects(UnitCube, At(Eye + glm::vec3(0.0f, -5.0f, 0.0f)))); + REQUIRE_FALSE(Down.Intersects(UnitCube, At(Eye + glm::vec3(0.0f, 5.0f, 0.0f)))); +} + +TEST_CASE("Frustum: a box with any point in the clip volume is never culled", "[graphics][culling]") +{ + // Random cameras and random turned, scaled boxes. A culled box must have no visible + // point: test its corners, its centre and a grid through it against the clip volume. + SimRandom Random(11, 1); + int Culled = 0; + int Kept = 0; + for (int i = 0; i < 400; ++i) + { + const glm::vec3 Eye(Uniform(Random, -5.0f, 5.0f), Uniform(Random, -5.0f, 5.0f), Uniform(Random, -5.0f, 5.0f)); + const glm::vec3 Look(Uniform(Random, -1.0f, 1.0f), Uniform(Random, -0.9f, 0.9f), Uniform(Random, -1.0f, 1.0f)); + if (glm::length(Look) < 0.1f) + { + continue; + } + const glm::mat4 Matrix = ViewProjection(Eye, Eye + Look); + const Frustum View = Frustum::FromViewProjection(Matrix); + + const glm::vec3 Half(Uniform(Random, 0.1f, 3.0f), Uniform(Random, 0.1f, 3.0f), Uniform(Random, 0.1f, 3.0f)); + const Aabb Box{-Half, Half}; + glm::mat4 World = At( + glm::vec3(Uniform(Random, -30.0f, 30.0f), Uniform(Random, -30.0f, 30.0f), Uniform(Random, -30.0f, 30.0f))); + World = + glm::rotate(World, + Uniform(Random, 0.0f, 6.28f), + glm::normalize(glm::vec3( + Uniform(Random, 0.1f, 1.0f), Uniform(Random, -1.0f, 1.0f), Uniform(Random, -1.0f, 1.0f)))); + World = glm::scale(World, glm::vec3(Uniform(Random, 0.5f, 2.0f))); + + if (View.Intersects(Box, World)) + { + ++Kept; + continue; + } + ++Culled; + constexpr int Steps = 6; + for (int x = 0; x <= Steps; ++x) + { + for (int y = 0; y <= Steps; ++y) + { + for (int z = 0; z <= Steps; ++z) + { + const glm::vec3 Local = Box.Min + (Box.Max - Box.Min) * glm::vec3(x, y, z) / float(Steps); + const glm::vec3 Point = glm::vec3(World * glm::vec4(Local, 1.0f)); + CAPTURE(i, Point.x, Point.y, Point.z); + REQUIRE_FALSE(InClipVolume(Matrix, Point)); + } + } + } + } + REQUIRE(Culled > 50); + REQUIRE(Kept > 20); +} + +TEST_CASE("Frustum culling: the pass draws a straddling mesh and skips an off-screen one", "[graphics][culling]") +{ + PublishHarness World; + const Entity InView = World.Mesh({0.0f, 0.0f, -5.0f}); + const Entity Behind = World.Mesh({0.0f, 0.0f, 5.0f}); + const Entity FarRight = World.Mesh({20.0f, 0.0f, -5.0f}); + // The centre is right of the view at z = -5 (x = 5); the left half is inside + const Entity Straddling = World.Mesh({5.3f, 0.0f, -5.0f}); + + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + PassHarness Pass; + const RenderSnapshot& Snapshot = World.Frame(); + // Culling is the renderer's: the snapshot still has every mesh, so no proxy is freed + REQUIRE(Snapshot.Meshes.size() == 4); + REQUIRE(Pass.Draw(Snapshot, &View)); + REQUIRE(Pass.Proxies.LiveCount() == 4); + + REQUIRE(Pass.Visible(InView)); + REQUIRE(Pass.Visible(Straddling)); + REQUIRE_FALSE(Pass.Visible(Behind)); + REQUIRE_FALSE(Pass.Visible(FarRight)); + REQUIRE(Pass.Culler.Stats().Drawn == 2); + REQUIRE(Pass.Culler.Stats().Culled == 2); + + // The same frame again changes nothing, so the recorded draw list stays + REQUIRE_FALSE(Pass.Draw(World.Frame(), &View)); + + // The mesh moves into view: a change, and it is drawn + World.Storage.Get(FarRight).Position = glm::vec3(1.0f, 0.0f, -5.0f); + REQUIRE(Pass.Draw(World.Frame(), &View)); + REQUIRE(Pass.Visible(FarRight)); + REQUIRE(Pass.Culler.Stats().Drawn == 3); + + // The camera turns around: what was behind it is in view, the rest is not + const Frustum Back = Frustum::FromViewProjection(ViewProjection(glm::vec3(0.0f), glm::vec3(0.0f, 0.0f, 1.0f))); + REQUIRE(Pass.Draw(World.Frame(), &Back)); + REQUIRE(Pass.Visible(Behind)); + REQUIRE_FALSE(Pass.Visible(InView)); + REQUIRE_FALSE(Pass.Visible(Straddling)); + REQUIRE_FALSE(Pass.Visible(FarRight)); + + // Culling off: every mesh is drawn + REQUIRE(Pass.Draw(World.Frame(), nullptr)); + REQUIRE(Pass.Culler.Stats().Drawn == 4); + REQUIRE(Pass.Culler.Stats().Culled == 0); + + // A destroyed mesh's slot is cleared, and a new mesh in it starts from its own test + World.Storage.Destroy(InView); + REQUIRE_FALSE(Pass.Draw(World.Frame(), nullptr)); + REQUIRE(Pass.Culler.Stats().Drawn == 3); +} + +TEST_CASE("Frustum culling: a slot the pass does not draw is neither drawn nor culled", "[graphics][culling]") +{ + MeshCuller Culler; + std::vector Items(2); + Items[0].World = At({0.0f, 0.0f, -5.0f}); + Items[1].World = At({0.0f, 0.0f, -5.0f}); + const std::vector Slots = {0, 1}; + Culler.SetSlot(0, true, UnitCube); + // Another pass draws slot 1 (a debug material) + Culler.SetSlot(1, false, UnitCube); + + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + REQUIRE(Culler.Cull(Items, Slots, &View)); + REQUIRE(Culler.IsVisible(0)); + REQUIRE_FALSE(Culler.IsVisible(1)); + REQUIRE(Culler.Stats().Drawn == 1); + REQUIRE(Culler.Stats().Culled == 0); + // A slot it never heard of is not visible + REQUIRE_FALSE(Culler.IsVisible(7)); +} + +TEST_CASE("Frustum: a box grows point by point, and a NaN point never makes it cullable", "[graphics][culling]") +{ + Aabb Box; + REQUIRE_FALSE(Box.IsValid()); + Box.Add({1.0f, 2.0f, 3.0f}); + REQUIRE(Box.IsValid()); + REQUIRE(Box.Min == glm::vec3(1.0f, 2.0f, 3.0f)); + REQUIRE(Box.Max == glm::vec3(1.0f, 2.0f, 3.0f)); + Box.Add({-1.0f, 5.0f, 0.0f}); + REQUIRE(Box.Min == glm::vec3(-1.0f, 2.0f, 0.0f)); + REQUIRE(Box.Max == glm::vec3(1.0f, 5.0f, 3.0f)); + + // Of is the same as adding each point + const std::vector Points = {{1.0f, 2.0f, 3.0f}, {-1.0f, 5.0f, 0.0f}}; + const Aabb Made = Aabb::Of(Points); + REQUIRE(Made.Min == Box.Min); + REQUIRE(Made.Max == Box.Max); + REQUIRE_FALSE(Aabb::Of({}).IsValid()); + + // A NaN point never lets the box lose a point in view, wherever it comes + const float NaN = std::numeric_limits::quiet_NaN(); + const Frustum View = Frustum::FromViewProjection(ForwardCamera()); + const glm::vec3 InView{0.0f, 0.0f, -5.0f}; + const glm::vec3 FarAway{1000.0f, 0.0f, -5.0f}; + for (const std::vector& Order : std::vector>{ + {glm::vec3(NaN), InView, FarAway}, {InView, glm::vec3(NaN), FarAway}, {InView, FarAway, glm::vec3(NaN)}}) + { + Aabb Mixed; + for (const glm::vec3& Point : Order) + { + Mixed.Add(Point); + } + REQUIRE(View.Intersects(Mixed, glm::mat4(1.0f))); + } +} diff --git a/FlingTests/Resources/RunSettingsConfigTests.cpp b/FlingTests/Resources/RunSettingsConfigTests.cpp index af11f077..89e4bfcf 100644 --- a/FlingTests/Resources/RunSettingsConfigTests.cpp +++ b/FlingTests/Resources/RunSettingsConfigTests.cpp @@ -15,7 +15,7 @@ TEST_CASE("Run settings: the [Engine] keys of an ini file reach the run settings const std::filesystem::path Path = std::filesystem::temp_directory_path() / "fling_run_settings_test.ini"; { std::ofstream File(Path, std::ios::trunc); - File << "[Engine]\nExec=inline\nSimHz=60\nMaxFps=90\nVSync=off\nInterpolation=off\n"; + File << "[Engine]\nExec=inline\nSimHz=60\nMaxFps=90\nVSync=off\nInterpolation=off\nFrustumCulling=off\n"; } REQUIRE(FlingConfig::Get().LoadConfigFile(Path.string())); @@ -26,6 +26,6 @@ TEST_CASE("Run settings: the [Engine] keys of an ini file reach the run 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)"); + "off (config), interpolation off (config), frustum culling off (config)"); std::filesystem::remove(Path); }