acdream/src/AcDream.App/UI/Layout/ComponentBookTemplateFactory.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

189 lines
7.6 KiB
C#

using DatReaderWriter;
using AcDream.Content;
namespace AcDream.App.UI.Layout;
/// <summary>
/// Instantiates retail's category and component listbox templates from LayoutDesc
/// 0x21000033. This is the retained equivalent of
/// <c>UIElement_ListBox::AddItemFromTemplateList</c> used by
/// <c>gmSpellComponentUI::UpdateComponents @ 0x0048A910</c>.
/// </summary>
internal sealed class ComponentBookTemplateFactory
{
public const uint LayoutId = 0x21000033u;
public const uint CategoryTemplateId = 0x10000466u;
public const uint ComponentTemplateId = 0x10000467u;
public const uint IconId = 0x10000468u;
public const uint NameId = 0x10000469u;
public const uint OwnedCountId = 0x1000046Au;
public const uint DesiredCountId = 0x1000046Bu;
private const uint LocalStringTableId = 0x23000001u;
private const uint HighlightState = UiButtonStateMachine.Highlight;
private static readonly (string Key, string Fallback)[] CategoryStrings =
[
("ID_SpellComp_Category_Scarabs", "SCARABS"),
("ID_SpellComp_Category_Herbs", "HERBS"),
("ID_SpellComp_Category_Gems", "POWDERED GEMS"),
("ID_SpellComp_Category_Alchemical", "ALCHEMICAL SUBSTANCES"),
("ID_SpellComp_Category_Talismans", "TALISMANS"),
("ID_SpellComp_Category_Tapers", "TAPERS"),
("ID_SpellComp_Category_Peas", "PEAS"),
];
private readonly ElementInfo _categoryTemplate;
private readonly ElementInfo _componentTemplate;
private readonly Func<uint, (GpuTextureSlot tex, int w, int h)> _resolveSprite;
private readonly UiDatFont? _defaultFont;
private readonly IReadOnlyDictionary<uint, UiDatFont?> _fonts;
private readonly string[] _categoryNames;
public ComponentBookTemplateFactory(
ElementInfo categoryTemplate,
ElementInfo componentTemplate,
Func<uint, (GpuTextureSlot tex, int w, int h)> resolveSprite,
UiDatFont? defaultFont,
IReadOnlyDictionary<uint, UiDatFont?>? fonts = null,
IReadOnlyList<string>? categoryNames = null)
{
_categoryTemplate = categoryTemplate;
_componentTemplate = componentTemplate;
_resolveSprite = resolveSprite;
_defaultFont = defaultFont;
_fonts = fonts ?? new Dictionary<uint, UiDatFont?>();
_categoryNames = categoryNames?.ToArray()
?? CategoryStrings.Select(value => value.Fallback).ToArray();
}
/// <summary>
/// Loads and resolves the two template definitions while the caller holds the
/// shared DAT lock. Fonts and localized category strings are captured eagerly,
/// so later inventory refreshes instantiate rows without reading DAT files.
/// </summary>
public static ComponentBookTemplateFactory? TryLoad(
IDatReaderWriter dats,
Func<uint, (GpuTextureSlot tex, int w, int h)> resolveSprite,
UiDatFont? defaultFont,
Func<uint, UiDatFont?>? resolveFont)
{
ElementInfo? category = LayoutImporter.ImportInfos(
dats, LayoutId, CategoryTemplateId);
ElementInfo? component = LayoutImporter.ImportInfos(
dats, LayoutId, ComponentTemplateId);
if (category is null || component is null)
return null;
var fonts = new Dictionary<uint, UiDatFont?>();
CaptureFonts(category, resolveFont, fonts);
CaptureFonts(component, resolveFont, fonts);
var strings = new DatStringResolver(dats);
string[] categoryNames = CategoryStrings
.Select(value => strings.Resolve(
LocalStringTableId,
DatStringResolver.ComputeHash(value.Key))
?? value.Fallback)
.ToArray();
return new ComponentBookTemplateFactory(
category, component, resolveSprite, defaultFont, fonts, categoryNames);
}
public UiTemplateListSlot CreateCategoryRow(uint category)
{
ImportedLayout content = Build(_categoryTemplate);
if (content.Root is not UiText title)
throw new InvalidOperationException(
"Retail component category template did not resolve to UIElement_Text.");
string label = category < _categoryNames.Length
? _categoryNames[category]
: "OTHER COMPONENTS";
title.LinesProvider = () => [new UiText.Line(label, title.DefaultColor)];
return new UiTemplateListSlot(
content, uint.MaxValue, content.Root is IUiDatStateful stateful
? stateful.ActiveRetailStateId
: UiStateInfo.DirectStateId, selectedState: null);
}
public ComponentRow CreateComponentRow(
uint componentId,
GpuTextureSlot iconTexture,
string name,
int ownedCount,
uint desiredCount)
{
ImportedLayout content = Build(_componentTemplate);
UiElement iconHost = Required(content, IconId);
UiText nameText = Required<UiText>(content, NameId);
UiText ownedText = Required<UiText>(content, OwnedCountId);
UiField desiredField = Required<UiField>(content, DesiredCountId);
var icon = new UiTextureElement
{
Width = iconHost.Width,
Height = iconHost.Height,
Anchors = AnchorEdges.Left | AnchorEdges.Top
| AnchorEdges.Right | AnchorEdges.Bottom,
Texture = iconTexture,
};
iconHost.AddChild(icon);
nameText.LinesProvider = () => [new UiText.Line(name, nameText.DefaultColor)];
ownedText.LinesProvider = () =>
[new UiText.Line(ownedCount.ToString(System.Globalization.CultureInfo.InvariantCulture),
ownedText.DefaultColor)];
// NumberInputFilter + the 0..5000 validation are installed by the controller,
// matching gmSpellComponentUI::ListenToElementMessage @ 0x0048A420.
desiredField.ClearOnSubmit = false;
desiredField.RecordHistory = false;
desiredField.SelectAllOnFocus = true;
desiredField.CharacterFilter = char.IsAsciiDigit;
desiredField.SetText(desiredCount.ToString(
System.Globalization.CultureInfo.InvariantCulture));
uint normalState = content.Root is IUiDatStateful stateful
? stateful.ActiveRetailStateId
: UiStateInfo.DirectStateId;
var slot = new UiTemplateListSlot(
content, componentId, normalState, HighlightState);
return new ComponentRow(slot, desiredField);
}
private ImportedLayout Build(ElementInfo template)
=> LayoutImporter.Build(
template,
_resolveSprite,
_defaultFont,
did => _fonts.TryGetValue(did, out UiDatFont? font) ? font : _defaultFont);
private static T Required<T>(ImportedLayout content, uint id)
where T : UiElement
=> content.FindElement(id) as T
?? throw new InvalidOperationException(
$"Retail component template element 0x{id:X8} did not resolve to {typeof(T).Name}.");
private static UiElement Required(ImportedLayout content, uint id)
=> content.FindElement(id)
?? throw new InvalidOperationException(
$"Retail component template element 0x{id:X8} is missing.");
private static void CaptureFonts(
ElementInfo info,
Func<uint, UiDatFont?>? resolveFont,
Dictionary<uint, UiDatFont?> fonts)
{
if (info.FontDid != 0u && !fonts.ContainsKey(info.FontDid))
fonts[info.FontDid] = resolveFont?.Invoke(info.FontDid);
foreach (ElementInfo child in info.Children)
CaptureFonts(child, resolveFont, fonts);
}
internal readonly record struct ComponentRow(
UiTemplateListSlot Slot,
UiField DesiredField);
}