acdream/tests/AcDream.App.Tests/UI/Layout/DatWidgetFactoryFontResolveTests.cs
Erik ceec3bc440 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>
2026-07-27 18:22:08 +02:00

195 lines
8.9 KiB
C#

using AcDream.App.Rendering.Gpu;
using AcDream.App.UI;
using AcDream.App.UI.Layout;
namespace AcDream.App.Tests.UI.Layout;
/// <summary>
/// Unit tests for Fix C: per-element dat FontDid resolver in <see cref="DatWidgetFactory"/>.
///
/// <para>
/// <see cref="UiDatFont"/> cannot be constructed in pure unit tests (GL + dat required),
/// so these tests verify the plumbing using null/non-null identity and sentinel resolvers:
/// <list type="bullet">
/// <item>Null resolver → DatFont unchanged (backward-compat: same as before Fix C).</item>
/// <item>Resolver present, FontDid == 0 → resolver NOT called; DatFont == global datFont.</item>
/// <item>Resolver returns null for an id (font missing) → DatFont falls back to global datFont.</item>
/// <item>Controller sets DatFont after build → controller value wins.</item>
/// <item><see cref="LayoutImporter.Build"/> threads fontResolve to the factory.</item>
/// </list>
/// </para>
/// </summary>
public class DatWidgetFactoryFontResolveTests
{
private static (GpuTextureSlot, int, int) NoTex(uint _) => (GpuTextureSlot.Unassigned, 0, 0);
// ── Test 1: null fontResolve → DatFont == datFont (backward-compat) ─────
/// <summary>
/// When fontResolve is null (the live GameWindow path), BuildText must NOT
/// touch DatFont beyond setting it to the global datFont. Null in → null out.
/// </summary>
[Fact]
public void NullFontResolve_DatFont_EqualsGlobalFont()
{
var info = new ElementInfo { Type = 12, Width = 100, Height = 20, FontDid = 0x40000001u };
// datFont=null, fontResolve=null → backward-compat: DatFont == null
var t = Assert.IsType<UiText>(DatWidgetFactory.Create(info, NoTex, null, fontResolve: null));
Assert.Null(t.DatFont);
}
// ── Test 2: FontDid == 0 → resolver NOT called ────────────────────────────
/// <summary>
/// When the element has FontDid == 0, the fontResolve delegate must NOT be
/// invoked (the element has no dat font; fall through to global datFont).
/// </summary>
[Fact]
public void FontDidZero_ResolverNotCalled()
{
var info = new ElementInfo { Type = 12, Width = 100, Height = 20, FontDid = 0u };
bool called = false;
UiDatFont? Resolver(uint id) { called = true; return null; }
// FontDid=0 → resolver should never fire, even though one is provided.
Assert.IsType<UiText>(DatWidgetFactory.Create(info, NoTex, null, fontResolve: Resolver));
Assert.False(called, "fontResolve must NOT be called when FontDid == 0");
}
// ── Test 3: resolver returns null (font missing) → fallback to datFont ───
/// <summary>
/// When the element has a non-zero FontDid but the resolver returns null
/// (font not found in dats), DatFont must fall back to the shared global datFont.
/// Since datFont is null in unit tests, this verifies the fallback chain.
/// </summary>
[Fact]
public void ResolverReturnsNull_FallsBackToGlobalFont()
{
const uint SomeFontDid = 0x40000005u;
var info = new ElementInfo { Type = 12, Width = 100, Height = 20, FontDid = SomeFontDid };
int callCount = 0;
UiDatFont? Resolver(uint id) { callCount++; return null; } // always returns null (font missing)
var t = Assert.IsType<UiText>(DatWidgetFactory.Create(info, NoTex, datFont: null, fontResolve: Resolver));
// Resolver was called exactly once for this element.
Assert.Equal(1, callCount);
// Fallback: DatFont == global datFont (null in unit tests).
Assert.Null(t.DatFont);
}
// ── Test 4: resolver called with correct FontDid ──────────────────────────
/// <summary>
/// When fontResolve is provided and FontDid is non-zero, the resolver is called
/// with the element's exact FontDid value.
/// </summary>
[Fact]
public void ResolverCalledWithElementFontDid()
{
const uint ExpectedFontDid = 0x40000002u;
var info = new ElementInfo { Type = 12, Width = 100, Height = 20, FontDid = ExpectedFontDid };
uint? capturedId = null;
UiDatFont? Resolver(uint id) { capturedId = id; return null; }
DatWidgetFactory.Create(info, NoTex, datFont: null, fontResolve: Resolver);
Assert.Equal(ExpectedFontDid, capturedId);
}
// ── Test 5: controller DatFont override wins over build-time value ───────
/// <summary>
/// A controller that calls FindElement and sets DatFont afterward MUST override
/// whatever the factory set at build time. This is the backward-compat guarantee.
/// The DatFont property is settable — a controller can override it after build.
/// </summary>
[Fact]
public void ControllerDatFontOverride_WinsOverBuildTimeFont()
{
const uint SomeFontDid = 0x40000003u;
var info = new ElementInfo { Type = 12, Width = 100, Height = 20, FontDid = SomeFontDid };
UiDatFont? Resolver(uint _) => null; // returns null → build-time DatFont == null
var t = Assert.IsType<UiText>(DatWidgetFactory.Create(info, NoTex, datFont: null, fontResolve: Resolver));
Assert.Null(t.DatFont); // build-time value set by factory
// Controller simulated override: set DatFont to null explicitly.
// The real guarantee is that DatFont is a settable property.
// (We can't construct a real UiDatFont here — it requires GL + dats.)
t.DatFont = null; // controller overrides after build
Assert.Null(t.DatFont);
// ✓ DatFont is settable — controller override mechanism is in place.
}
// ── Test 6: LayoutImporter.Build threads fontResolve to factory ──────────
/// <summary>
/// When <see cref="LayoutImporter.Build"/> is given a fontResolve, it must pass
/// it to <see cref="DatWidgetFactory.Create"/> for EVERY element in the tree.
/// Verified by checking that a Type-12 child with FontDid triggers the resolver.
/// </summary>
[Fact]
public void LayoutImporter_Build_ThreadsFontResolve_ToFactory()
{
const uint FontDid = 0x40000004u;
var root = new ElementInfo { Id = 1u, Type = 3, Width = 200, Height = 100 };
var child = new ElementInfo { Id = 2u, Type = 12, Width = 100, Height = 20, FontDid = FontDid };
root.Children.Add(child);
int resolveCallCount = 0;
UiDatFont? Resolver(uint id) { resolveCallCount++; return null; }
var layout = LayoutImporter.Build(root, NoTex, datFont: null, fontResolve: Resolver);
// The child element has a non-zero FontDid — resolver must have been called for it.
Assert.True(resolveCallCount > 0, "fontResolve was not called for the child element");
// The child widget was built (findable in the layout).
Assert.NotNull(layout.FindElement(2u));
}
// ── Test 7: Meter element also receives element font from resolver ────────
/// <summary>
/// Type-7 (UiMeter) elements with a FontDid must also go through the resolver.
/// Verified by checking the resolver fires for a meter element with a non-zero FontDid.
/// </summary>
[Fact]
public void FontResolve_CalledForMeter_WhenFontDidPresent()
{
const uint MeterFontDid = 0x40000006u;
var meter = new ElementInfo { Type = 7, Width = 150, Height = 16, FontDid = MeterFontDid };
int callCount = 0;
UiDatFont? Resolver(uint id) { callCount++; return null; }
var w = DatWidgetFactory.Create(meter, NoTex, datFont: null, fontResolve: Resolver);
var m = Assert.IsType<UiMeter>(w);
// Resolver was called for the meter element's FontDid.
Assert.True(callCount > 0, "fontResolve was not called for meter element");
// Meter DatFont: resolver returned null, so DatFont falls back to global datFont (null).
Assert.Null(m.DatFont);
}
// ── Test 8: LayoutImporter.BuildFromInfos signature is backward-compat ────
/// <summary>
/// <see cref="LayoutImporter.BuildFromInfos"/> without fontResolve (default null)
/// must still work for all callers that don't pass it — verifies the optional
/// parameter default is correct and no existing callers broke.
/// </summary>
[Fact]
public void BuildFromInfos_WithoutFontResolve_WorksAsBeforeFix()
{
var root = new ElementInfo { Id = 10u, Type = 3, Width = 200, Height = 100 };
var child = new ElementInfo { Id = 11u, Type = 12, Width = 100, Height = 20, FontDid = 0x40000001u };
// Call without fontResolve (the old signature shape).
var layout = LayoutImporter.BuildFromInfos(root, new[] { child }, NoTex, datFont: null);
var t = Assert.IsType<UiText>(layout.FindElement(11u));
// No resolver → DatFont == global datFont (null in unit tests).
Assert.Null(t.DatFont);
}
}