feat(render): Campaign V slice V4a - port TextRenderer/BitmapFont/DebugLineRenderer/TextureCache onto IGpuDevice

TextRenderer, BitmapFont, DebugLineRenderer, and TextureCache's UI-texture
upload path (GetOrUploadRenderSurface/UploadRgba8) now issue every draw and
resource creation through the pinned IGpuDevice/IGpuFrame/IGpuPassEncoder
RHI contract instead of raw GL. This is the RHI's first real production
consumer - V0-V3 only established the contract, GL backend skeleton, and a
shader-dialect migration with no live GL exercise. TextRenderer owns one
IGpuPipeline (ui_text shader, straight-alpha blend, depth disabled) and
allocates a per-bucket ring each Flush; BitmapFont's atlas texture is
created and uploaded via device.CreateTexture/.Upload; DebugLineRenderer
mirrors the same one-pipeline-per-Flush shape for its line-list draws.
World-path TextureCache methods (GetOrUpload, the raw-GL layer-array
upload) are untouched - still legacy GL, still out of scope.

Frame lifecycle: GpuDeviceFrameLifetime (RenderFrameOrchestrator.cs) wraps
IGpuDevice.BeginFrame()/IGpuFrame.End() inside the existing
IRenderFrameLifetime bracket HostInputCameraCompositionPhase already opens
per callback, additively - no frame-graph restructuring. Ported renderers
reach the frame via ICurrentGpuFrameSource, a plain interface (not a
delegate field) so WorldSceneDiagnosticsController keeps passing its
existing "no stored window/delegate" architectural-conformance test.

Two real bugs surfaced by actually exercising the RHI against a live GL
context (nothing here was previously reachable before this slice):

- GlGpuDevice.BeginFrame() now resets the render-state cache every frame.
  The cache assumes it is the sole writer of GL program/blend/depth/cull
  state, which was true while it had zero real consumers, but every
  still-legacy renderer (WbDrawDispatcher, terrain, particles, EnvCells)
  mutates that same GL state directly and never informs the cache. Once a
  legacy renderer ran between two RHI binds, the cache's belief about the
  current GL program went stale, so a later BindPipeline(text shader)
  skipped re-issuing glUseProgram and the following push-constant upload
  threw GL_INVALID_OPERATION against whatever program was actually bound.
  Reset() at the frame boundary is the same defensive move BeginPass
  already makes after a forced clear (see its comment); it costs one
  redundant state application on the frame's first bind.
- GL_MULTISAMPLE has no representation in the pinned contract. Added a
  GL-backend-internal Multisample field to GlRenderStateSnapshot/Changes,
  computed from GpuPipelineDescription.SampleCount at BindPipeline time -
  mirrors how Vulkan bakes MSAA into the pipeline instead of a separate
  toggle.

Collateral, scoped to keep the port real rather than a stub:

- GpuTextureSlot (Unassigned = uint.MaxValue, NOT 0) now flows through
  every consumer of TextureCache.GetOrUploadRenderSurface/UploadRgba8 and
  TextRenderer.DrawSprite - the entire retained UI layer, since a pervasive
  Func<uint,(uint,int,int)> sprite-resolve delegate threads through nearly
  every UI element/controller. Every prior `== 0` / `!= 0` "no texture"
  check became `.IsAssigned` / `!.IsAssigned`; slot 0 is a real assigned
  slot (the device's default white texture), so the old sentinel would
  have produced live visual regressions if left in place.
- GpuTextureSlot/IGpuDevice/IGpuFrame are internal, so ~270 previously
  public AcDream.App types that touched them (directly or transitively)
  are now internal too - safe, since AcDream.App is an exe with no
  external project references; only the two test projects consume it, via
  InternalsVisibleTo. A handful of unrelated types the sweep caught
  (ElementInfo/ImportedLayout's property-bag hierarchy, several enums used
  as public [Theory] parameters, CursorFeedbackSnapshot's DragAcceptState)
  were reverted back to public where making them internal would have
  either cascaded into unrelated files or broken xUnit's public-member
  discovery.
- ExternalViewportTextureBridge (new) registers the still-raw-GL FBO
  color textures PrivateEntityViewportRenderer/PaperdollViewportRenderer
  produce (V4g's scope) into the device's texture table for
  UiViewport.TextureHandle, via a temporary
  GlGpuDevice.RegisterExternalColorTexture escape hatch (internal, not
  part of IGpuDevice) deleted when V4g ports those viewports.
- TextRenderGlStateScope.cs and its test deleted: the pipeline description
  now bakes what it used to restore by hand.
- ResourceCleanupGroupTests/GlTextureOwnershipTests: the two source-text
  conformance tests keyed to TextRenderer's old multi-resource
  construction shape (Shader + per-flight FrameBufferSet array + white
  texture + tracked VAO/VBO, all via ResourceCleanupGroup) no longer apply
  - that shape is gone, replaced by one IGpuPipeline created through
    IGpuDevice. The construction-order test is deleted; the checked-commit
    texture-creation check now targets GlGpuTexture (which already used
    the same GlResourceCommand.CreateName primitive before this slice).

Gates:
- dotnet build -c Release: 0 warnings, 0 errors (AcDream.App has
  TreatWarningsAsErrors).
- dotnet test tests/AcDream.App.Tests -c Release: 3,840 passed / 3
  skipped (was 3,843/3 entering this slice - net 3 fewer tests:
  TextRendererFailureSafetyTests.cs deleted (2, tested the now-deleted
  TextRenderGlStateScope) plus the one retired ResourceCleanupGroupTests
  method). Full solution: 8,908 passed / 5 skipped across all nine test
  projects.
- Offline pixel gate (tools/run-offline-pixel-gate.ps1, parent ec414d60
  vs this commit): differing fraction 0.318% (1,791/563,200 compared
  pixels), above the 0.001 threshold. Investigated pixel-by-pixel rather
  than waved through: a diff heatmap plus 4x crops at the differing
  clusters show zero differences anywhere in the retained UI, terrain,
  scenery, or static meshes - every differing pixel sits on continuously-
  animated ambient content (flying-insect sprites over the swamp, foliage
  sparkle/dew glints) whose exact phase depends on elapsed wall-clock
  time, the same category the gate's own sky-masking rationale already
  documents and the campaign doc's coverage table explicitly excludes
  ("Not covered - particles"). Confirming evidence: two same-commit
  captures at HEAD compare clean against each other (0.0025%), and two
  same-commit captures at the parent compare clean against each other
  (0.0044%) - only base-vs-head is consistently elevated, which is what
  frame-pacing drift from genuinely new per-frame RHI work (BeginFrame,
  ring resets, the render-state reset above) would produce against a
  fixed wall-clock capture deadline, not a rendering defect. Recommend a
  quick user visual check of this capture pair alongside the automated
  result, matching how V2c's particle work was already handled in this
  campaign (flagged for user visual confirmation rather than blocked on
  an automated gate that cannot cover animated content).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-07-27 18:22:08 +02:00
parent ec414d60cd
commit ceec3bc440
334 changed files with 3660 additions and 3840 deletions

View file

@ -190,9 +190,26 @@ internal sealed class GlGpuDevice : IGpuDevice
string fragmentPath = Path.Combine(_shadersDirectory, $"{description.Shaders.Name}.frag");
string vertexSource = File.ReadAllText(vertexPath);
string fragmentSource = File.ReadAllText(fragmentPath);
// Every RHI-created pipeline gets the same common.glsl preamble the
// legacy Shader(gl, vert, frag, includeCommonPreamble: true) call
// sites already opt into (mesh_modern, terrain_modern): the set-0
// binding-9 texture-table buffer + ACDREAM_TEXTURE_HANDLE macro that
// slice V2 introduced. A pipeline whose shaders never reference the
// macro simply carries an unused SSBO declaration — harmless — so
// there is no reason for callers to opt in per pipeline.
string commonSource = CommonPreambleSource;
vertexSource = Shader.InjectPreamble(vertexSource, commonSource);
fragmentSource = Shader.InjectPreamble(fragmentSource, commonSource);
return new GlGpuPipeline(_gl, Retirement, description, vertexSource, fragmentSource);
}
private string? _commonPreambleSource;
private string CommonPreambleSource => _commonPreambleSource ??=
File.ReadAllText(Path.Combine(_shadersDirectory, "common.glsl"));
public IGpuRenderTarget CreateRenderTarget(in GpuRenderTargetDescription description)
{
ThrowIfDisposed();
@ -215,6 +232,33 @@ internal sealed class GlGpuDevice : IGpuDevice
return new GpuTextureSlot(slot);
}
/// <summary>
/// Registers an externally-created, externally-owned GL texture name
/// (a private-viewport FBO colour attachment) into the same texture table
/// <see cref="RegisterTexture"/> uses. Not part of <see cref="IGpuDevice"/>
/// — <c>PrivateEntityViewportRenderer</c>/<c>PaperdollViewportRenderer</c>
/// still allocate their own FBO textures directly on <c>GL</c> pre-V4g, so
/// their retained-UI consumers (<see cref="UiViewport"/>) need a bridge
/// that does not require the caller to own an <see cref="IGpuTexture"/>.
/// The caller keeps deleting the GL name itself; this only ever writes
/// the bindless handle into the table and returns the slot. Deleted with
/// the GL backend once slice V4g moves those renderers onto
/// <see cref="IGpuRenderTarget"/> and they can call
/// <see cref="RegisterTexture"/> like every other consumer.
/// </summary>
internal GpuTextureSlot RegisterExternalColorTexture(uint glTextureName, IGpuSampler sampler)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(sampler);
if (sampler is not GlGpuSampler glSampler)
throw new ArgumentException("The GL backend can only register a GL sampler.", nameof(sampler));
uint slot = _textureSlotAllocator.Allocate();
ulong handle = _bindless.GetResidentHandle(glTextureName, glSampler.GlName);
WriteHandle(slot, handle);
return new GpuTextureSlot(slot);
}
public void ReleaseTextureSlot(GpuTextureSlot slot)
{
ThrowIfDisposed();
@ -239,6 +283,17 @@ internal sealed class GlGpuDevice : IGpuDevice
long serial = ++_nextSerial;
int slot = _frameFlights.CurrentSlot;
_ringStates[slot].Reset();
// Campaign V slice V4a: during the migration, every still-legacy
// renderer (WbDrawDispatcher, terrain, particles, EnvCellRenderer, ...)
// mutates real GL program/blend/depth/cull state directly, outside this
// device's ApplyRenderState. _renderState has no way to observe those
// calls, so its cached "current" snapshot goes stale the moment any of
// them runs between two RHI binds. Resetting once per frame is the same
// defensive move BeginPass already makes after a forced clear (see the
// comment there) — it costs one redundant state application on the
// frame's first BindPipeline, in exchange for never diffing against a
// baseline the driver has since moved past.
_renderState.Reset();
return new GlGpuFrame(this, slot, serial);
}
@ -283,6 +338,17 @@ internal sealed class GlGpuDevice : IGpuDevice
_textureHandleTable.AsSpan(tableStart, tableEnd - tableStart));
_textureTableBuffer.Upload((long)tableStart * sizeof(ulong), bytes);
}
// Bind the device's own table to binding 9 immediately before every
// RHI-issued draw. Storage-buffer bindings are global GL context
// state, and the still-unmigrated legacy renderers (WbDrawDispatcher,
// EnvCellRenderer, TerrainModernRenderer, ParticleRenderer) rebind
// their OWN interim per-renderer table to the same binding right
// before their own draws (slice V2's documented pattern) — so this
// device must re-claim binding 9 before ITS draws too, or an RHI
// draw issued after a legacy draw in the same frame would read the
// wrong table.
_gl.BindBufferBase(GLEnum.ShaderStorageBuffer, GpuBindingModel.StorageTextureTable, _textureTableBuffer.GlName);
}
internal void BeginPass(GpuPassDescription description)
@ -395,6 +461,24 @@ internal sealed class GlGpuDevice : IGpuDevice
{
_gl.ColorMask(desired.ColorWrite, desired.ColorWrite, desired.ColorWrite, desired.ColorWrite);
}
if (changes.Multisample)
{
// Vulkan bakes multisample rasterization into the pipeline via its
// declared sample count — there is no separate enable bit. The GL
// backend mirrors that: GL_MULTISAMPLE tracks
// GpuPipelineDescription.SampleCount rather than being left at
// whatever the previous pass happened to leave it. This matters
// because the default framebuffer can itself be multisampled
// (QualitySettings MSAA): a single-sample UI pipeline binding
// while GL_MULTISAMPLE is still enabled from an earlier world
// pass converts each glyph's soft alpha edge into dithered MSAA
// coverage instead of a clean alpha blend (the pre-RHI
// TextRenderer explicitly disabled it for the same reason).
if (desired.Multisample)
_gl.Enable(EnableCap.Multisample);
else
_gl.Disable(EnableCap.Multisample);
}
GLHelpers.ThrowOnResourceError(_gl, "apply GL render state");
}

View file

@ -51,7 +51,8 @@ internal sealed class GlGpuPassEncoder : IGpuPassEncoder
description.Cull,
description.FrontFace,
description.AlphaToCoverage,
description.ColorWrite);
description.ColorWrite,
Multisample: description.SampleCount > 1);
_device.ApplyRenderState(desired);
_gl.BindVertexArray(p.GlVertexArray);

View file

@ -15,7 +15,8 @@ internal readonly record struct GlRenderStateSnapshot(
GpuCullMode Cull,
GpuFrontFace FrontFace,
bool AlphaToCoverage,
bool ColorWrite);
bool ColorWrite,
bool Multisample);
/// <summary>Which GL state calls are needed to move from the previous snapshot to the new one.</summary>
internal readonly record struct GlRenderStateChanges(
@ -27,14 +28,15 @@ internal readonly record struct GlRenderStateChanges(
bool Cull,
bool FrontFace,
bool AlphaToCoverage,
bool ColorWrite)
bool ColorWrite,
bool Multisample)
{
public bool AnyChange =>
Program || Blend || DepthTest || DepthWrite || DepthCompare
|| Cull || FrontFace || AlphaToCoverage || ColorWrite;
|| Cull || FrontFace || AlphaToCoverage || ColorWrite || Multisample;
/// <summary>Every dimension reported changed — used for the first apply after a reset.</summary>
internal static GlRenderStateChanges All { get; } = new(true, true, true, true, true, true, true, true, true);
internal static GlRenderStateChanges All { get; } = new(true, true, true, true, true, true, true, true, true, true);
}
/// <summary>
@ -68,7 +70,8 @@ internal sealed class GlRenderStateCache
p.Cull != desired.Cull,
p.FrontFace != desired.FrontFace,
p.AlphaToCoverage != desired.AlphaToCoverage,
p.ColorWrite != desired.ColorWrite);
p.ColorWrite != desired.ColorWrite,
p.Multisample != desired.Multisample);
}
/// <summary>Discards the cached baseline — the next <see cref="Apply"/> reports every dimension changed.</summary>