Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ platform setup (Vulkan SDK, GLFW, etc.).
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), `--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
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
`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
Expand Down Expand Up @@ -112,6 +113,8 @@ platform setup (Vulkan SDK, GLFW, etc.).
[`Docs/time-and-ticks.md`](Docs/time-and-ticks.md). The game thread, the
published copy, exec modes and the determinism tests:
[`Docs/threading-model.md`](Docs/threading-model.md).
- Occlusion culling in the G-buffer pass (a two phase Hi-Z pass on the GPU, its CPU twin
and tests): [`Docs/occlusion-culling.md`](Docs/occlusion-culling.md).
- One self-contained guide to all of the above, written to be loaded as context
by an AI coding agent: [`Docs/agent-guide.md`](Docs/agent-guide.md). The
handoff for the original Fling authors (what changed since the first commit,
Expand Down
130 changes: 130 additions & 0 deletions Assets/Shaders/Occlusion/cull.comp
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
#version 450

// Occlusion culling of the G-buffer pass, two phases (see OcclusionCuller.h).
// 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.
// The test is the same as Occlusion::ProjectBounds and Occlusion::IsOccluded (OcclusionTest.cpp).

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
uvec4 Info;
};

struct DrawCmd
{
uint indexCount;
uint instanceCount;
uint firstIndex;
int vertexOffset;
uint firstInstance;
};

layout(std140, set = 0, binding = 0) uniform Params
{
mat4 ViewProjection;
// x: slot count
uvec4 Counts;
} 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(set = 0, binding = 6) uniform sampler2D uPyramid;

layout(push_constant) uniform Phase { uint Value; } phase;

const float DepthBias = 1.0e-5;

bool IsOccluded(const Slot slot)
{
const mat4 mvp = u.ViewProjection * slot.World;
vec2 uvMin = vec2(1.0e30);
vec2 uvMax = vec2(-1.0e30);
float nearest = 1.0e30;
for (uint i = 0; i < 8; ++i)
{
const vec3 corner = vec3(((i & 1u) != 0u) ? slot.BoundsMax.x : slot.BoundsMin.x,
((i & 2u) != 0u) ? slot.BoundsMax.y : slot.BoundsMin.y,
((i & 4u) != 0u) ? slot.BoundsMax.z : slot.BoundsMin.z);
const vec4 clip = mvp * vec4(corner, 1.0);
if (clip.w <= 1.0e-4)
{
return false;
}
const vec2 uv = clip.xy / clip.w * 0.5 + 0.5;
uvMin = min(uvMin, uv);
uvMax = max(uvMax, uv);
nearest = min(nearest, clip.z / clip.w);
}
uvMin = clamp(uvMin, vec2(0.0), vec2(1.0));
uvMax = clamp(uvMax, vec2(0.0), vec2(1.0));
nearest = max(nearest, 0.0);

const ivec2 size = textureSize(uPyramid, 0);
const ivec2 maxTexel = size - 1;
const ivec2 lo = clamp(ivec2(floor(uvMin * vec2(size))), ivec2(0), maxTexel);
const ivec2 hi = clamp(ivec2(floor(uvMax * vec2(size))), ivec2(0), maxTexel);

const int span = max(hi.x - lo.x, hi.y - lo.y) + 1;
const int levels = textureQueryLevels(uPyramid);
int level = 0;
while ((1 << level) < span && level + 1 < levels)
{
++level;
}

const ivec2 levelMax = textureSize(uPyramid, level) - 1;
const ivec2 a = min(lo >> level, levelMax);
const ivec2 b = min(hi >> level, levelMax);
float farthest = 0.0;
for (int y = a.y; y <= b.y; ++y)
{
for (int x = a.x; x <= b.x; ++x)
{
farthest = max(farthest, texelFetch(uPyramid, ivec2(x, y), level).r);
}
}
return nearest > farthest + DepthBias;
}

void main()
{
const uint s = gl_GlobalInvocationID.x;
if (s >= u.Counts.x)
{
return;
}

const Slot slot = slots[s];
const uint indexCount = slot.Info.x;
const bool inView = (slot.Info.y & 1u) != 0u && indexCount != 0u;
const bool drawnFirst = inView && visible[s] != 0u;

if (phase.Value == 0u)
{
draw1[s] = DrawCmd(indexCount, drawnFirst ? 1u : 0u, 0u, 0, 0u);
return;
}

bool hidden = false;
if (inView && (slot.Info.y & 2u) != 0u)
{
hidden = IsOccluded(slot);
}
const bool shown = inView && !hidden;
draw2[s] = DrawCmd(indexCount, (shown && !drawnFirst) ? 1u : 0u, 0u, 0, 0u);
visible[s] = shown ? 1u : 0u;
if (inView && hidden)
{
atomicAdd(stats.occluded, 1u);
}
}
47 changes: 47 additions & 0 deletions Assets/Shaders/Occlusion/hiz_downsample.comp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#version 450

// One level of the depth pyramid. Level 0 copies the depth image. Each later level holds the
// farthest depth of the texels below it. Keep in step with DepthPyramid::Build (OcclusionTest.cpp).

layout(local_size_x = 8, local_size_y = 8) in;

layout(set = 0, binding = 0) uniform sampler2D uSrc;
layout(set = 0, binding = 1, r32f) uniform writeonly image2D uDst;

layout(push_constant) uniform Params
{
ivec2 SrcSize;
ivec2 DstSize;
int Copy;
} pc;

void main()
{
const ivec2 d = ivec2(gl_GlobalInvocationID.xy);
if (d.x >= pc.DstSize.x || d.y >= pc.DstSize.y)
{
return;
}

if (pc.Copy != 0)
{
imageStore(uDst, d, vec4(texelFetch(uSrc, d, 0).r));
return;
}

const ivec2 lo = d * 2;
ivec2 hi = lo + 1;
// The last row or column also covers the extra source row or column of an odd size
if (d.x == pc.DstSize.x - 1) hi.x = pc.SrcSize.x - 1;
if (d.y == pc.DstSize.y - 1) hi.y = pc.SrcSize.y - 1;

float farthest = 0.0;
for (int y = lo.y; y <= hi.y; ++y)
{
for (int x = lo.x; x <= hi.x; ++x)
{
farthest = max(farthest, texelFetch(uSrc, ivec2(x, y), 0).r);
}
}
imageStore(uDst, d, vec4(farthest));
}
1 change: 1 addition & 0 deletions Docs/agent-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,7 @@ flag or key. The startup line `Run settings: ...` names each value and its sourc
| 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 |
| Occlusion culling | `--occlusion-culling on\|off` | `OcclusionCulling` | 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
Expand Down
2 changes: 1 addition & 1 deletion Docs/architecture-overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ 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`, `--frustum-culling on\|off`; or the same keys in `[Engine]` of `Config/EngineConf.ini` (`Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, `FrustumCulling`) |
| 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`, `--occlusion-culling on\|off`; or the same keys in `[Engine]` of `Config/EngineConf.ini` (`Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`, `FrustumCulling`, `OcclusionCulling`) |
| 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
Expand Down
55 changes: 55 additions & 0 deletions Docs/occlusion-culling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Occlusion culling

The G-buffer pass does not draw a mesh that other meshes hide. It runs on the GPU, after the
frustum test ([`MeshCuller`](../FlingEngine/Graphics/inc/MeshCuller.h)), and it only removes
draws, so the picture is the same. Issue #252.

## Settings

| How | What |
| --- | --- |
| `--occlusion-culling on|off` | Run setting. On by default |
| `[Engine] OcclusionCulling` | The same, in `Config/EngineConf.ini` |
| Editor, GPU Options | A checkbox, and the count of hidden meshes (the value of the previous frame) |

The pass turns itself off when the compute shaders did not load, or the device cannot sample the
depth format or store `R32_SFLOAT` images. It works on a software driver (llvmpipe).

## How it works

Two phases in one command buffer (`OcclusionCuller`, `Assets/Shaders/Occlusion/`):

1. **Phase 0** (compute). Each slot that is in the view and was visible in the last frame gets an
indirect draw (`Draw1`).
2. The **first render pass** draws `Draw1` and clears the images as before.
3. A **depth pyramid** (`R32_SFLOAT`, each texel is the farthest depth below it) is built from
that depth (`hiz_downsample.comp`).
4. **Phase 1** (compute). Every slot in the view is tested against the pyramid. A slot that is not
hidden and was not drawn in step 2 gets a draw in `Draw2`. The slot's visible flag is saved for
the next frame, and the hidden slots are counted.
5. The **second render pass** (`FrameBuffer::GetLoadRenderPassHandle`, load ops, same frame buffer)
draws `Draw2`.

The pyramid comes from this frame's depth with this frame's camera and meshes, so a mesh is never
hidden by an old picture: no popping and no reprojection. A mesh that comes into view is not
visible in the last frame, so it is tested in phase 1 and drawn in the second pass. The first
frame (or a new buffer) draws everything in the second pass.

The test must never hide a visible mesh. It uses the nearest depth of the mesh's bounding box,
the farthest depth under the box's screen rectangle (a pyramid level that covers it with 2 x 2
texels), and a small bias (`Occlusion::DepthBias`). A box that reaches the camera's plane is never
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`).

## The CPU twin

`Occlusion::ProjectBounds`, `Occlusion::IsOccluded` and `DepthPyramid` (`OcclusionTest.h`) do the
same as the shaders. `FlingTests/Graphics/OcclusionCullingTests.cpp` runs them without a window,
including a randomized scene (rotated boxes, moving camera) that checks no visible box is hidden.
Keep the shaders and the CPU code in step.

## Check it

`Sandbox --offscreen --unattended --frames 60 --seed 1 --screenshot a.png --occlusion-culling on`
and the same with `off` give the same picture. Set `EnableValidationLayers=true` in
`Config/EngineConf.ini` to run with the validation layers.
2 changes: 1 addition & 1 deletion Docs/threading-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ 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
on|off`, `[Engine] FrustumCulling` (and `--occlusion-culling on|off`, `[Engine] OcclusionCulling`) and the GPU Options window, which also shows
the meshes drawn and culled in the last frame. Tests: `GraphicsTests
"[culling]"` (`FrustumCullingTests.cpp`).

Expand Down
1 change: 1 addition & 0 deletions Docs/time-and-ticks.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ outside `--exec threaded` is an error.
| 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 |
| Occlusion culling | `--occlusion-culling on\|off` | `OcclusionCulling` | 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
Expand Down
1 change: 1 addition & 0 deletions FlingEngine/Application/src/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,7 @@ namespace Fling
// the swap chain again after this frame's present.
VulkanApp::Get().SetVSync(m_Controls->VSync());
VulkanApp::Get().SetFrustumCulling(m_Controls->FrustumCulling());
VulkanApp::Get().SetOcclusionCulling(m_Controls->OcclusionCulling());
VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage());

// Offscreen there is no window: no focus, no monitor, and no frame cap (headless)
Expand Down
6 changes: 6 additions & 0 deletions FlingEngine/Core/inc/LaunchOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ namespace Fling
* --frustum-culling on|off
* Skip the meshes outside the camera's view (on) or draw every mesh
* (off). Overrides [Engine] FrustumCulling
* --occlusion-culling on|off
* Skip the meshes that other meshes hide (on) or draw every mesh
* (off). Overrides [Engine] OcclusionCulling
* --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
*/
Expand Down Expand Up @@ -160,6 +163,9 @@ namespace Fling
/** --frustum-culling on or off. Empty: not on the command line. */
std::optional<bool> FrustumCulling;

/** --occlusion-culling on or off. Empty: not on the command line. */
std::optional<bool> OcclusionCulling;

/** --thread-jitter: the seed and the longest sleep in microseconds. 0 microseconds means off. */
uint32 JitterSeed = 0;
uint32 JitterMaxMicroseconds = 0;
Expand Down
19 changes: 15 additions & 4 deletions FlingEngine/Core/inc/RunSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,15 @@ namespace Fling
static constexpr const char* VSyncKey = "VSync";
static constexpr const char* InterpolationKey = "Interpolation";
static constexpr const char* FrustumCullingKey = "FrustumCulling";
static constexpr const char* OcclusionCullingKey = "OcclusionCulling";

String Exec;
String SimHz;
String MaxFps;
String VSync;
String Interpolation;
String FrustumCulling;
String OcclusionCulling;

/**
* Each key's text from t_GetKey, which returns the text of one [Engine] key, or empty
Expand All @@ -65,7 +67,8 @@ namespace Fling
.MaxFps = t_GetKey(MaxFpsKey),
.VSync = t_GetKey(VSyncKey),
.Interpolation = t_GetKey(InterpolationKey),
.FrustumCulling = t_GetKey(FrustumCullingKey)};
.FrustumCulling = t_GetKey(FrustumCullingKey),
.OcclusionCulling = t_GetKey(OcclusionCullingKey)};
}
};

Expand All @@ -83,11 +86,12 @@ namespace Fling
* | VSync | [Engine] VSync | --vsync | on |
* | Interpolation | [Engine] Interpolation | --interpolation | on |
* | FrustumCulling | [Engine] FrustumCulling | --frustum-culling | on |
* | OcclusionCulling | [Engine] OcclusionCulling | --occlusion-culling | on |
*
* The values here do not change after startup. The GPU Options window changes VSync, the
* 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.
* frame cap, the simulation rate, interpolation, frustum culling and occlusion 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.
*/
struct RunSettings
{
Expand Down Expand Up @@ -128,6 +132,13 @@ namespace Fling
bool FrustumCulling = true;
SettingSource FrustumCullingSource = SettingSource::Default;

/**
* The renderer does not draw a mesh that other meshes hide from the camera (the GPU
* occlusion test in Graphics). Presentation only: the simulation never reads it.
*/
bool OcclusionCulling = true;
SettingSource OcclusionCullingSource = SettingSource::Default;

/** The refresh rate of the window's monitor at startup (ResolveFrameCap). Empty when not known, and headless.
*/
std::optional<uint32> MonitorHz;
Expand Down
4 changes: 3 additions & 1 deletion FlingEngine/Core/src/LaunchOptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ namespace Fling
constexpr StringView VSyncFlag = "vsync";
constexpr StringView InterpolationFlag = "interpolation";
constexpr StringView FrustumCullingFlag = "frustum-culling";
constexpr StringView OcclusionCullingFlag = "occlusion-culling";
constexpr StringView ThreadJitterFlag = "thread-jitter";
/**
* Flags that are refused with the name of the flag that does their job, so a script
Expand Down Expand Up @@ -394,7 +395,8 @@ namespace Fling
!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, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError))
!ReadOptionalOnOff(t_CmdLine, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError) ||
!ReadOptionalOnOff(t_CmdLine, OcclusionCullingFlag, t_Out.OcclusionCulling, t_OutError))
{
return false;
}
Expand Down
Loading