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

@ -1,27 +1,27 @@
using System.Numerics;
using System.Numerics;
using AcDream.App.UI;
namespace AcDream.App.Studio;
// ─────────────────────────────────────────────────────────────────────────────
// DumpLayout load a panel from the retail UI layout dump
// ─────────────────────────────────────────────────────────────────────────────
// DumpLayout — load a panel from the retail UI layout dump
//
// The dump stores every node's rect in ABSOLUTE screen coordinates (the
// panel's design position in the retail UI, not relative to its parent).
// Evidence: for the "inventory" panel, the root node is at x=500,y=138 and
// its direct children are also at x=500,y=161 the child y=161 is only
// its direct children are also at x=500,y=161 — the child y=161 is only
// 23 pixels below the parent y=138, which makes sense as a child offset
// (the header row), not as the raw rect. If the rects were parent-relative,
// (500,161) would place the child way off the window.
//
// DumpLayout converts absolute parent-relative by computing:
// DumpLayout converts absolute → parent-relative by computing:
// child.Left = child.Rect.X - parent.Rect.X
// child.Top = child.Rect.Y - parent.Rect.Y
//
// The root node (ParentTraversalIndex == null) is placed at (0,0) so the
// whole tree sits at the UiHost origin rather than at the panel's retail
// screen position.
// ─────────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
/// <summary>
/// Builds a static <see cref="UiElement"/> tree from the retail UI layout dump
@ -30,11 +30,11 @@ namespace AcDream.App.Studio;
/// node's <see cref="UiElement.EventId"/> set to the dump's element_id and
/// <see cref="UiElement.Name"/> set to the widget_kind string.
///
/// <para>This source is STATIC no controllers, no FixtureProvider, no live
/// <para>This source is STATIC — no controllers, no FixtureProvider, no live
/// game data. It is a build reference for the UI Studio showing any of the 26
/// retail windows without needing the production panel wired up.</para>
/// </summary>
public static class DumpLayout
internal static class DumpLayout
{
/// <summary>
/// Parse the dump at <paramref name="dumpPath"/>, find the panel whose slug
@ -42,7 +42,7 @@ public static class DumpLayout
///
/// <para>
/// <paramref name="resolve"/> maps a RenderSurface id (0x06xxxxxx) to a
/// (GL texture handle, native width, native height) triple pass
/// (GL texture handle, native width, native height) triple — pass
/// <c>RenderStack.ResolveChrome</c> from the studio, or a stub returning
/// (1,1,1) for tests.
/// </para>
@ -52,10 +52,10 @@ public static class DumpLayout
public static UiElement? Load(
string dumpPath,
string slug,
Func<uint, (uint, int, int)> resolve,
Func<uint, (GpuTextureSlot, int, int)> resolve,
out string? error)
{
// ── 1. Parse the dump JSON ────────────────────────────────────────
// ── 1. Parse the dump JSON ────────────────────────────────────────
var dump = UiDumpModel.Parse(dumpPath);
if (dump is null)
{
@ -63,7 +63,7 @@ public static class DumpLayout
return null;
}
// ── 2. Find the requested panel ───────────────────────────────────
// ── 2. Find the requested panel ───────────────────────────────────
var panel = dump.Panels.FirstOrDefault(
p => string.Equals(p.Slug, slug, StringComparison.OrdinalIgnoreCase));
if (panel is null)
@ -79,12 +79,12 @@ public static class DumpLayout
return null;
}
// ── 3. Build a traversal-index → node lookup ──────────────────────
// ── 3. Build a traversal-index → node lookup ──────────────────────
var byIndex = new Dictionary<int, DumpNode>(panel.Nodes.Count);
foreach (var n in panel.Nodes)
byIndex[n.TraversalIndex] = n;
// ── 4. Create UiElement objects for every node ────────────────────
// ── 4. Create UiElement objects for every node ────────────────────
var elements = new Dictionary<int, UiElement>(panel.Nodes.Count);
foreach (var node in panel.Nodes)
{
@ -92,7 +92,7 @@ public static class DumpLayout
elements[node.TraversalIndex] = el;
}
// ── 5. Wire parentchild relationships + set parent-relative coords ─
// ── 5. Wire parent–child relationships + set parent-relative coords ─
UiElement? root = null;
foreach (var node in panel.Nodes)
{
@ -100,7 +100,7 @@ public static class DumpLayout
if (node.ParentTraversalIndex is null)
{
// Root node place at (0,0) so the tree sits at the UiHost origin.
// Root node — place at (0,0) so the tree sits at the UiHost origin.
// The panel's absolute rect offset is discarded here (it was the
// retail design position inside the retail screen, which we don't need).
el.Left = 0f;
@ -109,7 +109,7 @@ public static class DumpLayout
}
else
{
// Non-root: convert absolute parent-relative by subtracting parent rect.
// Non-root: convert absolute → parent-relative by subtracting parent rect.
// child.Left = child.Rect.X - parent.Rect.X
// child.Top = child.Rect.Y - parent.Rect.Y
// This preserves the visual layout inside each group without placing the
@ -137,11 +137,11 @@ public static class DumpLayout
return root;
}
// ── Private helpers ───────────────────────────────────────────────────────
// ── Private helpers ───────────────────────────────────────────────────────
private static UiElement BuildElement(
DumpNode node,
Func<uint, (uint, int, int)> resolve)
Func<uint, (GpuTextureSlot, int, int)> resolve)
{
uint imageId = UiDumpModel.PickImageId(node);
var kind = node.WidgetKind ?? "Group";
@ -149,7 +149,7 @@ public static class DumpLayout
UiElement el;
if (imageId != 0 && !string.Equals(kind, "Group", StringComparison.OrdinalIgnoreCase))
{
// Sprite/Button/Scrollbar/Slider create a sprite-drawing element.
// Sprite/Button/Scrollbar/Slider — create a sprite-drawing element.
el = new DumpSpriteElement(imageId, resolve)
{
Name = kind,
@ -159,7 +159,7 @@ public static class DumpLayout
}
else
{
// Group (or sprite without an image) plain container, no own draw.
// Group (or sprite without an image) — plain container, no own draw.
el = new DumpGroupElement()
{
Name = kind,
@ -168,7 +168,7 @@ public static class DumpLayout
};
}
// EventId is set from the dump's element_id (cast to uint the decimal
// EventId is set from the dump's element_id (cast to uint — the decimal
// values in the JSON represent the same dat handle used at runtime).
el.EventId = (uint)node.ElementId;
el.Left = node.Rect.X; // overwritten by caller per root/child logic
@ -180,27 +180,27 @@ public static class DumpLayout
}
}
// ─────────────────────────────────────────────────────────────────────────────
// DumpSpriteElement minimal element that draws a single sprite
// ─────────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
// DumpSpriteElement — minimal element that draws a single sprite
// ─────────────────────────────────────────────────────────────────────────────
/// <summary>
/// Draws a single sprite at its native size tiled to fill <see cref="UiElement.Width"/>
/// × <see cref="UiElement.Height"/>. Used for Sprite/Button/Scrollbar/Slider nodes from
/// × <see cref="UiElement.Height"/>. Used for Sprite/Button/Scrollbar/Slider nodes from
/// the retail UI dump.
///
/// <para>We do NOT reuse <see cref="AcDream.App.UI.Layout.UiDatElement"/> here because
/// that class requires an <c>ElementInfo</c> with a populated <c>StateMedia</c>
/// dictionary — the dat-import plumbing — which is not needed for a static dump
/// dictionary — the dat-import plumbing — which is not needed for a static dump
/// preview. A minimal subclass keeps the code simpler and the dependency surface
/// smaller.</para>
/// </summary>
internal sealed class DumpSpriteElement : UiElement
{
private readonly uint _imageId;
private readonly Func<uint, (uint tex, int w, int h)> _resolve;
private readonly Func<uint, (GpuTextureSlot tex, int w, int h)> _resolve;
public DumpSpriteElement(uint imageId, Func<uint, (uint tex, int w, int h)> resolve)
public DumpSpriteElement(uint imageId, Func<uint, (GpuTextureSlot tex, int w, int h)> resolve)
{
_imageId = imageId;
_resolve = resolve;
@ -211,25 +211,25 @@ internal sealed class DumpSpriteElement : UiElement
if (_imageId == 0) return;
var (tex, tw, th) = _resolve(_imageId);
if (tex == 0 || tw == 0 || th == 0) return;
if (!tex.IsAssigned || tw == 0 || th == 0) return;
// Tile at native resolution (same as UiDatElement.OnDraw UV-repeat on both
// Tile at native resolution (same as UiDatElement.OnDraw — UV-repeat on both
// axes via GL_REPEAT, Width/tw and Height/th tile the texture).
ctx.DrawSprite(tex, 0, 0, Width, Height,
0, 0, Width / tw, Height / th, Vector4.One);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// DumpGroupElement pure container (Group nodes from the dump)
// ─────────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────────
// DumpGroupElement — pure container (Group nodes from the dump)
// ─────────────────────────────────────────────────────────────────────────────
/// <summary>
/// Container element for dump Group nodes no own draw, just hosts children.
/// Container element for dump Group nodes — no own draw, just hosts children.
/// Extending UiElement directly (no OnDraw override) gives transparent groups,
/// which matches Group nodes in the retail layout that have no background sprite.
/// </summary>
internal sealed class DumpGroupElement : UiElement
{
// No OnDraw completely transparent container.
// No OnDraw — completely transparent container.
}