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,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
@ -20,7 +20,7 @@ namespace AcDream.App.UI;
/// Display-only text remains click-through and cannot steal focus or window drag.
/// </para>
/// </summary>
public sealed class UiText : UiElement, IUiDatStateful
internal sealed class UiText : UiElement, IUiDatStateful
{
/// <summary>Optional base-element click notice used by authored text tabs.</summary>
public Action? OnClick { get; set; }
@ -30,11 +30,11 @@ public sealed class UiText : UiElement, IUiDatStateful
public uint ElementId { get; set; }
/// <summary>One display line: pre-formatted text + its colour.</summary>
public readonly record struct Line(string Text, Vector4 Color);
internal readonly record struct Line(string Text, Vector4 Color);
/// <summary>A caret position: a line index into the cached line list plus a
/// character index (0..line.Text.Length, i.e. a caret slot between glyphs).</summary>
public readonly record struct Pos(int Line, int Col);
internal readonly record struct Pos(int Line, int Col);
/// <summary>Provider of the lines to show, oldest-first. Polled each frame.</summary>
public Func<IReadOnlyList<Line>> LinesProvider { get; set; } = static () => Array.Empty<Line>();
@ -58,7 +58,7 @@ public sealed class UiText : UiElement, IUiDatStateful
/// otherwise white (<see cref="Vector4.One"/>).
///
/// <para>Controllers that supply a per-line color via <see cref="LinesProvider"/>
/// (e.g. <c>new UiText.Line(text, explicitColor)</c>) are unaffected they always
/// (e.g. <c>new UiText.Line(text, explicitColor)</c>) are unaffected — they always
/// win over this default. This property is only a convenience starting point for
/// controllers that want to read the dat color rather than hard-code it.</para>
/// </summary>
@ -84,7 +84,7 @@ public sealed class UiText : UiElement, IUiDatStateful
/// <summary>Resolves a dat RenderSurface id to (GL tex handle, pixel width, pixel height).
/// Required when <see cref="BackgroundSprite"/> is non-zero.</summary>
public Func<uint, (uint tex, int w, int h)>? SpriteResolve { get; set; }
public Func<uint, (GpuTextureSlot tex, int w, int h)>? SpriteResolve { get; set; }
/// <summary>Highlight colour painted behind a selected character span.</summary>
public Vector4 SelectionColor { get; set; } = new(0.25f, 0.45f, 0.85f, 0.5f);
@ -138,7 +138,7 @@ public sealed class UiText : UiElement, IUiDatStateful
/// <summary>Static right-aligned single-line mode: draws the FIRST line right-justified
/// within the element rect, vertically centered, with NO scroll/selection machinery.
/// Used for value labels in attribute/skill rows where the number must hug the right edge.
/// Mutually exclusive with <see cref="Centered"/> if both are true, Centered takes
/// Mutually exclusive with <see cref="Centered"/> — if both are true, Centered takes
/// precedence. Pair with <c>ClickThrough = true</c> for non-interactive labels.</summary>
public bool RightAligned { get; set; }
@ -146,20 +146,20 @@ public sealed class UiText : UiElement, IUiDatStateful
/// Vertical position of the text within the element rect in single-line mode
/// (<see cref="Centered"/> or <see cref="RightAligned"/>).
/// <list type="bullet">
/// <item><description><b>Center</b> (default) vertically centered, matching the original
/// <item><description><b>Center</b> (default) — vertically centered, matching the original
/// behavior of the centered/right-aligned paths.</description></item>
/// <item><description><b>Top</b> text is placed at <c>y = Padding</c> (top of the content
/// <item><description><b>Top</b> — text is placed at <c>y = Padding</c> (top of the content
/// area), so the text sits at the top of the element rather than centering in it.
/// Used for footer title elements whose dat box is the full footer height (55 px) but
/// the text should render near the top.</description></item>
/// <item><description><b>Bottom</b> text is placed at <c>y = Height - lineHeight - Padding</c>.</description></item>
/// <item><description><b>Bottom</b> — text is placed at <c>y = Height - lineHeight - Padding</c>.</description></item>
/// </list>
/// Only meaningful when <see cref="Centered"/> or <see cref="RightAligned"/> is true.
/// Has no effect on the scrollable multi-line path.
/// </summary>
public VJustify VerticalJustify { get; set; } = VJustify.Center;
/// <summary>The scroll model also read by the linked UiScrollbar.</summary>
/// <summary>The scroll model — also read by the linked UiScrollbar.</summary>
public UiScrollable Scroll { get; } = new();
/// <summary>
@ -179,7 +179,7 @@ public sealed class UiText : UiElement, IUiDatStateful
private const float WheelLines = 1f; // lines advanced per wheel notch (retail = 1 line per notch)
// ── Cached layout from the last OnDraw, so OnEvent hit-tests the SAME geometry ──
// ── Cached layout from the last OnDraw, so OnEvent hit-tests the SAME geometry ──
private IReadOnlyList<Line> _lastLines = Array.Empty<Line>();
private BitmapFont? _lastFont;
private UiDatFont? _lastDatFont;
@ -193,7 +193,7 @@ public sealed class UiText : UiElement, IUiDatStateful
private bool _drawTextAfterChildren;
private bool _honorDatVerticalJustification;
// ── Selection state ──────────────────────────────────────────────────
// ── Selection state ──────────────────────────────────────────────────
private Pos? _selAnchor; // where the drag started
private Pos? _selCaret; // where the drag currently is
private bool _selecting;
@ -325,7 +325,7 @@ public sealed class UiText : UiElement, IUiDatStateful
/// <summary>
/// Clamp a scroll offset to [0, max] where max = content-height - view-height
/// (never negative when everything fits, scroll is pinned to 0). Exposed for tests.
/// (never negative — when everything fits, scroll is pinned to 0). Exposed for tests.
/// </summary>
public static float ClampScroll(float scroll, float contentHeight, float viewHeight)
{
@ -340,14 +340,14 @@ public sealed class UiText : UiElement, IUiDatStateful
if (BackgroundSprite != 0 && SpriteResolve is { } sr)
{
var (tex, tw, th) = sr(BackgroundSprite);
if (tex != 0 && tw != 0 && th != 0)
if (tex.IsAssigned && tw != 0 && th != 0)
ctx.DrawSprite(tex, 0, 0, Width, Height, 0, 0, Width / tw, Height / th, Vector4.One);
}
// Background must draw UNDER the transcript text. DrawStringDat emits into the
// sprite bucket which flushes BEFORE rects, so a DrawRect background would wash
// over the text. DrawFill routes the background through the sprite bucket too,
// submitted first text on top.
// submitted first → text on top.
ctx.DrawFill(0, 0, Width, Height, BackgroundColor);
if (!_drawTextAfterChildren)
@ -520,7 +520,7 @@ public sealed class UiText : UiElement, IUiDatStateful
hx = lineX + bitmapFont!.MeasureWidth(text.Substring(0, c0));
hw = bitmapFont.MeasureWidth(text.Substring(c0, c1 - c0));
}
// Highlight sits BEHIND the line's text sprite bucket, submitted
// Highlight sits BEHIND the line's text → sprite bucket, submitted
// before this line's DrawStringDat.
ctx.DrawFill(hx, y, hw, lh, SelectionColor);
}
@ -572,7 +572,7 @@ public sealed class UiText : UiElement, IUiDatStateful
if (!Selectable && !WheelScrollEnabled) return false;
// Silk wheel +Y = scroll up = reveal older = toward the TOP = decrease ScrollY.
// ScrollByLines sign: +down/newer, -up/older.
// e.Data0 > 0 → wheel up → want older → ScrollByLines with negative lines.
// e.Data0 > 0 → wheel up → want older → ScrollByLines with negative lines.
Scroll.ScrollByLines((int)(-e.Data0 * WheelLines));
return true;
}
@ -616,7 +616,7 @@ public sealed class UiText : UiElement, IUiDatStateful
|| Keyboard.IsKeyPressed(Silk.NET.Input.Key.ControlRight));
if (ctrl && key == Silk.NET.Input.Key.C)
{
// Only touch the clipboard when there's a selection an empty
// Only touch the clipboard when there's a selection — an empty
// copy must NOT clobber what the user previously copied.
if (Keyboard is not null)
{
@ -636,7 +636,7 @@ public sealed class UiText : UiElement, IUiDatStateful
return false;
}
// ── Selection helpers ────────────────────────────────────────────────
// ── Selection helpers ────────────────────────────────────────────────
/// <summary>Select the entire cached transcript (Ctrl+A).</summary>
private void SelectAll()
@ -670,7 +670,7 @@ public sealed class UiText : UiElement, IUiDatStateful
return SelectedText(_lastLines, start, end);
}
// ── Pure, testable logic (no GL / no font texture) ───────────────────
// ── Pure, testable logic (no GL / no font texture) ───────────────────
/// <summary>
/// Compute the Y offset (local space) for a single line in the Centered/RightAligned
@ -731,7 +731,7 @@ public sealed class UiText : UiElement, IUiDatStateful
/// <paramref name="end"/> (inclusive of start.Col, exclusive of end.Col) from
/// <paramref name="lines"/>. Multi-line selections are joined with "\n":
/// the first line from start.Col to its end, whole middle lines, and the last
/// line up to end.Col. Pure unit-testable without GL.
/// line up to end.Col. Pure — unit-testable without GL.
/// </summary>
public static string SelectedText(IReadOnlyList<Line> lines, Pos start, Pos end)
{
@ -870,8 +870,8 @@ public sealed class UiText : UiElement, IUiDatStateful
/// The caret column for a horizontal position <paramref name="x"/> (already
/// adjusted for the left padding, so x=0 is the start of the text). Walks the
/// string accumulating each glyph's advance and snaps the caret to whichever
/// side of the glyph midpoint <paramref name="x"/> falls on natural
/// Windows-like caret placement. Pure unit-testable with a synthetic advance.
/// side of the glyph midpoint <paramref name="x"/> falls on — natural
/// Windows-like caret placement. Pure — unit-testable with a synthetic advance.
/// </summary>
/// <param name="text">The line text.</param>
/// <param name="advanceOf">Per-character advance (pixels) lookup.</param>
@ -888,6 +888,6 @@ public sealed class UiText : UiElement, IUiDatStateful
if (x < mid) return i; // caret sits before this glyph
cursor += adv;
}
return text.Length; // past the last glyph end caret
return text.Length; // past the last glyph → end caret
}
}