feat(render): Campaign V slice V4t-1 — terrain crosses to GpuTextureSlot

V4t moves the world texture stack off the raw 64-bit ARB_bindless_texture
handle and onto GpuTextureSlot. This first commit does terrain only, because
terrain is the one branch of that stack whose producer and consumer are a
single pair — TerrainAtlas and TerrainModernRenderer — so it can carry the
new device seam on its own pixel gate before the mesh/composite/particle
retype lands on top of it.

Why the device's table can now be reached, when §5.2 said it could not.
That paragraph's reason was the flush: GlGpuDevice drains its dirty table
runs inside FlushBeforeDraw, which only an encoder-recorded draw reaches,
so a raw-GL renderer would sample a stale table. §5.5.6 then closed the GL
re-land of V4c/V4d, which means the world renderers stay raw GL through to
V10 — so "wait for the encoder" stopped being a plan and became an
indefinite block on V4t, which the Vulkan world arm cannot be written
without. The resolution is the smallest one that keeps the seam honest: the
drain is factored out as GlGpuDevice.FlushTextureTable, and a raw-GL
renderer calls it and binds TextureTableGlName at binding 9 itself,
immediately before its own draw — the same shape its retired private
GlBindlessHandleTable had, against a table that is now the device's. Nothing
else of the backend is exposed, and both members are deleted with the raw-GL
world path.

Residency ownership deliberately does NOT move. RegisterWorldTextureHandle
interns an already-resident handle and owns only the table entry; the atlas
still creates, makes resident and destroys its own textures. That is what
separates it from RegisterTexture, which owns the residency it creates, and
it is why this slice can retype the data model without also porting GL
texture creation onto IGpuTexture.

TerrainAtlas.GetBindlessHandles becomes GetTextureSlots(GlGpuDevice).
Registration is idempotent by handle, so the per-draw call is two dictionary
lookups — the cadence GetOrAdd already had. It is conditional on the handle
having changed because SetAnisotropic makes both textures non-resident and
re-acquires them: without that check a quality-preset change would strand a
slot holding a non-resident handle, so the superseded entry is retired in
the same step through the device's retirement queue.

Ordering is unaffected. Terrain's two slots travel as loose uniforms
(uTextureIndexA/B) and enter no sort and no bucket key, so a different slot
NUMBER changes nothing about what is drawn or in what order — only which
table index resolves to the same handle.

Gates. GL offline pixel gate vs cb2a70b8: 3.02e-05 (17 of 563,200 pixels),
exactly a same-commit control value and inside the documented 15-23 px /
<=4.1e-05 band. tools/run-repeat-connected-gate.ps1 -Runs 3: 3/3 RENDERED on
both the desktop witness and the client capture. One Vulkan composition-host
run with VK_LAYER_KHRONOS_validation proven inserted by the loader: zero
errors, zero warnings, empty validation log, converged ownership ledger. App
tests 4,075 / 3 skips (#250's zero-allocation test reran green singly).

One connected run of an earlier 3-run attempt died in the render loop with
"OpenGL returned unexpected fence wait status NoError (0x0)" from
GpuFrameFlightController.RetireFence. It did not reproduce in the following
three runs at this tree nor in three interleaved runs at cb2a70b8, and this
diff creates, deletes and waits on no fence. Filed as #251 rather than
attributed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-07-28 12:22:45 +02:00
parent cb2a70b867
commit b8bcaa3ef2
6 changed files with 228 additions and 83 deletions

View file

@ -1,5 +1,6 @@
using System.Numerics;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Rendering.Gpu.Gl;
using AcDream.App.Rendering.Wb;
using AcDream.Core.Terrain;
using Silk.NET.OpenGL;
@ -96,13 +97,13 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
// std140 packing and why it is vec4[9] rather than float[36].
private uint _tilingUbo;
// GL-only emulation of the eventual Vulkan global texture descriptor array
// (binding=9, GpuBindingModel.StorageTextureTable). Owns its own table —
// see GlBindlessHandleTable's doc comment and the campaign doc's §5.2 for
// why terrain doesn't share WbDrawDispatcher's/EnvCellRenderer's tables.
private readonly GlBindlessHandleTable _textureTable = new();
private uint _textureTableSsbo;
private int _textureTableSsboCapacityBytes;
// Campaign V slice V4t: the interim per-renderer GlBindlessHandleTable is
// retired. TerrainAtlas hands out GpuTextureSlots from the device's one
// table and this renderer flushes and binds that table at
// GpuBindingModel.StorageTextureTable itself, because it still submits
// through raw GL and so never reaches GlGpuDevice.FlushBeforeDraw. Null on
// a backend with no GL device, where this renderer is never constructed.
private readonly GlGpuDevice? _gpuDevice;
// Reusable per-frame buffers.
private readonly List<int> _visibleSlots = new();
@ -122,17 +123,19 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
public void BeginVisibilityFrame() => _visibleCellIds.Clear();
public TerrainModernRenderer(
internal TerrainModernRenderer(
GL gl,
BindlessSupport bindless,
Shader shader,
TerrainAtlas atlas,
GlGpuDevice? gpuDevice,
int initialSlotCapacity = 64)
: this(
gl,
bindless,
shader,
atlas,
gpuDevice,
ImmediateGpuResourceRetirementQueue.Instance,
initialSlotCapacity)
{
@ -143,6 +146,7 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
BindlessSupport bindless,
Shader shader,
TerrainAtlas atlas,
GlGpuDevice? gpuDevice,
IGpuResourceRetirementQueue resourceRetirement,
int initialSlotCapacity = 64)
{
@ -150,6 +154,7 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
_bindless = bindless;
_shader = shader;
_atlas = atlas;
_gpuDevice = gpuDevice;
ArgumentNullException.ThrowIfNull(resourceRetirement);
_retirementLedger = new GpuRetirementLedger(resourceRetirement);
_alloc = new GpuRetiredTerrainSlotAllocator(initialSlotCapacity, resourceRetirement);
@ -184,21 +189,6 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
BufferUsageARB.StaticDraw,
"allocating terrain tiling UBO");
// Campaign V slice V2b: binding=9 texture-table SSBO (GL-only
// emulation of the eventual Vulkan descriptor array).
_textureTableSsbo = TrackedGlResource.CreateBuffer(
_gl,
"creating terrain texture-table SSBO");
RetryableGpuResourceRelease textureTableRelease =
TrackedGlResource.CreateRetryableBufferDeletion(
_gl,
_textureTableSsbo,
() => _textureTableSsboCapacityBytes,
"rolling back terrain texture-table SSBO");
constructionResources.Add(
"terrain texture-table SSBO",
textureTableRelease.Run);
_globalVao = TrackedGlResource.CreateVertexArray(
_gl,
"creating terrain global VAO");
@ -542,16 +532,16 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
// the same product the visibility pass above already computed.
_shader.SetMatrix4("uViewProjection", viewProjection);
var (terrainHandle, alphaHandle) = _atlas.GetBindlessHandles();
// Campaign V slice V2b: pass each handle's binding=9 table slot
// Campaign V slice V2b: pass each texture's binding=9 table slot
// instead of the raw uvec2 handle. GLSL reconstructs
// sampler2DArray(ACDREAM_TEXTURE_HANDLE(uTextureIndexA)) at the use
// site — see terrain_modern.frag.
uint terrainSlot = _textureTable.GetOrAdd(terrainHandle);
uint alphaSlot = _textureTable.GetOrAdd(alphaHandle);
// site — see terrain_modern.frag. Slice V4t: the slots come from the
// device's one table rather than a table private to this renderer.
(GpuTextureSlot terrainSlot, GpuTextureSlot alphaSlot) =
_atlas.GetTextureSlots(GpuDevice);
FlushAndBindTextureTable();
_gl.ProgramUniform1(_shader.Program, _uTextureIndexALoc, terrainSlot);
_gl.ProgramUniform1(_shader.Program, _uTextureIndexBLoc, alphaSlot);
_gl.ProgramUniform1(_shader.Program, _uTextureIndexALoc, terrainSlot.Index);
_gl.ProgramUniform1(_shader.Program, _uTextureIndexBLoc, alphaSlot.Index);
// Phase U.3: bind the terrain clip UBO (binding=2). Shared ClipFrame UBO
// when wired, else the no-clip fallback (count 0 = ungated terrain).
@ -665,16 +655,6 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
"deleting terrain tiling UBO");
releases.Add(("tiling-ubo", release.Run));
}
if (_textureTableSsbo != 0)
{
RetryableGpuResourceRelease release =
TrackedGlResource.CreateRetryableBufferDeletion(
_gl,
_textureTableSsbo,
_textureTableSsboCapacityBytes,
"deleting terrain texture-table SSBO");
releases.Add(("texture-table", release.Run));
}
_disposeResources = new RetryableResourceReleaseLedger(releases);
}
@ -696,8 +676,6 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
_indirectCapacity = 0;
_dynamicFrameStarted = false;
_fallbackClipUbo = 0;
_textureTableSsbo = 0;
_textureTableSsboCapacityBytes = 0;
_disposeResources = null;
_disposed = true;
@ -762,43 +740,34 @@ public sealed unsafe class TerrainModernRenderer : IDisposable
}
/// <summary>
/// Campaign V slice V2b: uploads <see cref="_textureTable"/>'s handles to
/// <see cref="_textureTableSsbo"/> when a new one was registered since the
/// last flush, then (re)binds it at
/// <see cref="GpuBindingModel.StorageTextureTable"/>. Terrain registers at
/// most two handles per draw (the terrain and alpha atlases), so this is
/// dirty only on the atlas's first draw and stays clean afterward.
/// The GL device whose texture table this renderer samples through.
/// Campaign V slice V4t: a terrain renderer without one could not resolve a
/// single texture, so the failure names the composition that built it rather
/// than dereferencing null mid-draw.
/// </summary>
private unsafe void FlushAndBindTextureTable()
private GlGpuDevice GpuDevice => _gpuDevice ?? throw new InvalidOperationException(
"TerrainModernRenderer was constructed without a GL GPU device: its texture " +
"slots come from that device's table (Campaign V slice V4t).");
/// <summary>
/// Campaign V slice V4t: drains the device texture table's dirty runs and
/// (re)binds it at <see cref="GpuBindingModel.StorageTextureTable"/>.
/// Terrain registers at most two slots (the terrain and alpha atlases), so
/// the table is dirty only on the atlas's first draw — but the bind is
/// unconditional, because GL storage-buffer binding points are global and
/// another renderer's binding 9 sits there between two terrain draws.
/// Deleted with the raw-GL world path when the Vulkan world arm lands and
/// this renderer's draws go through the encoder, which binds the same table
/// on every pipeline bind.
/// </summary>
private void FlushAndBindTextureTable()
{
if (_textureTable.Dirty)
{
ReadOnlySpan<ulong> handles = _textureTable.Handles;
int byteCount = handles.Length * sizeof(ulong);
fixed (ulong* p = handles)
{
if (_textureTableSsboCapacityBytes < byteCount)
{
int grown = DynamicBufferCapacity.Grow(_textureTableSsboCapacityBytes, byteCount);
TrackedGlResource.AllocateBufferStorage(
_gl,
GLEnum.ShaderStorageBuffer,
_textureTableSsbo,
_textureTableSsboCapacityBytes,
grown,
GLEnum.DynamicDraw,
"growing terrain texture-table SSBO");
_textureTableSsboCapacityBytes = grown;
}
_gl.BindBuffer(GLEnum.ShaderStorageBuffer, _textureTableSsbo);
_gl.BufferSubData(GLEnum.ShaderStorageBuffer, 0, (nuint)byteCount, p);
}
_textureTable.MarkFlushed();
}
GlGpuDevice device = GpuDevice;
device.FlushTextureTable();
_gl.BindBufferBase(
GLEnum.ShaderStorageBuffer,
GpuBindingModel.StorageTextureTable,
_textureTableSsbo);
device.TextureTableGlName);
}
/// <summary>