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 AcDream.App.Rendering;
@ -17,9 +17,9 @@ namespace AcDream.App.UI;
/// DBCache::GetDIDFromEnum (0x413940). Each layer is a 0x06 RenderSurface decoded
/// DIRECTLY (the D.2b RenderSurface-vs-Surface rule).
///
/// Layer order (bottom top), matching retail:
/// Layer order (bottom → top), matching retail:
/// 1. type-default underlay (OPAQUE backing; resolved via EnumIDMap 0x10000004 from
/// the portal MasterMap) <see cref="ResolveUnderlayDid"/>
/// the portal MasterMap) — <see cref="ResolveUnderlayDid"/>
/// 2. item custom underlay (e.g. "magic" tint strip)
/// 3. base icon
/// 4. item custom overlay (e.g. "enchanted" sparkle)
@ -31,28 +31,28 @@ namespace AcDream.App.UI;
///
/// Composited textures are cached by their (typeUnderlay, underlay, base, overlay) tuple.
/// </summary>
public sealed class IconComposer
internal sealed class IconComposer
{
private readonly IDatReaderWriter _dats;
private readonly TextureCache _cache;
private readonly Dictionary<(uint, uint, uint, uint, uint), uint> _byTuple = new();
private readonly Dictionary<(uint, uint, uint, uint, uint), GpuTextureSlot> _byTuple = new();
private readonly Dictionary<(uint, uint, uint), ComposedIcon> _dragByTuple = new();
private readonly Dictionary<uint, uint> _spellIcons = new();
private readonly Dictionary<uint, uint> _componentIcons = new();
private readonly Dictionary<uint, GpuTextureSlot> _spellIcons = new();
private readonly Dictionary<uint, GpuTextureSlot> _componentIcons = new();
private sealed record ComposedIcon(byte[] Rgba, int Width, int Height, uint Texture);
private sealed record ComposedIcon(byte[] Rgba, int Width, int Height, GpuTextureSlot Texture);
// ── type-default underlay resolve (EnumIDMap 0x10000004) ─────────────────
// Portal MasterMap (0x25000000) maps enum 0x10000004 submap DID (0x25000008).
// Submap maps index 0x06 RenderSurface DID. index = LSB(itemType)+1, or 0x21.
// Refs: IconData::RenderIcons 0058d2140058d22c; DBCache::GetDIDFromEnum 0x413940.
// ── type-default underlay resolve (EnumIDMap 0x10000004) ─────────────────
// Portal MasterMap (0x25000000) maps enum 0x10000004 → submap DID (0x25000008).
// Submap maps index → 0x06 RenderSurface DID. index = LSB(itemType)+1, or 0x21.
// Refs: IconData::RenderIcons 0058d214–0058d22c; DBCache::GetDIDFromEnum 0x413940.
private EnumIDMap? _underlaySubMap;
private bool _underlayResolveTried;
private readonly Dictionary<uint, uint> _underlayDidByIndex = new();
// ── effect overlay resolve (EnumIDMap 0x10000005) ────────────────────────
// Portal MasterMap (0x25000000) maps enum 0x10000005 submap DID (0x25000009).
// Submap maps index 0x06 RenderSurface DID. index = LSB(effects)+1, fallback 0x21.
// ── effect overlay resolve (EnumIDMap 0x10000005) ────────────────────────
// Portal MasterMap (0x25000000) maps enum 0x10000005 → submap DID (0x25000009).
// Submap maps index → 0x06 RenderSurface DID. index = LSB(effects)+1, fallback 0x21.
// Refs: IconData::RenderIcons 0x0058d180 (effect path); the effect tile is a
// ReplaceColor tint SOURCE, not a blit layer (see RESOLVED doc, divergence DR-1).
private EnumIDMap? _effectSubMap;
@ -68,13 +68,13 @@ public sealed class IconComposer
/// <summary>
/// Resolve the type-default underlay DID for <paramref name="itemType"/> via the
/// two-level EnumIDMap chain (retail: IconData::RenderIcons 0058d2140058d22c +
/// two-level EnumIDMap chain (retail: IconData::RenderIcons 0058d214–0058d22c +
/// DBCache::GetDIDFromEnum 0x413940).
///
/// <para>index = LowestSetBit(itemType) + 1, or 0x21 when itemType has no bits set.</para>
///
/// <para>NOTE: retail RenderIcons (407546) has a special paperdoll IsThePlayer case
/// that uses GetDIDByEnum(0x10000004, 7) + TYPE_CONTAINER for the player doll that
/// that uses GetDIDByEnum(0x10000004, 7) + TYPE_CONTAINER for the player doll — that
/// path is out of scope here (paperdoll phase).</para>
/// </summary>
internal uint ResolveUnderlayDid(ItemType itemType)
@ -97,7 +97,7 @@ public sealed class IconComposer
uint masterDid = (uint)_dats.Portal.Db.Header.MasterMapId; // = 0x25000000
if (masterDid == 0) return;
if (!_dats.Portal.TryGet<EnumIDMap>(masterDid, out var master)) return;
if (!master.ClientEnumToID.TryGetValue(0x10000004u, out var subDid)) return; // 0x25000008
if (!master.ClientEnumToID.TryGetValue(0x10000004u, out var subDid)) return; // → 0x25000008
if (_dats.Portal.TryGet<EnumIDMap>(subDid, out var sub)) _underlaySubMap = sub;
}
@ -105,7 +105,7 @@ public sealed class IconComposer
/// Resolve the effect-overlay DID for <paramref name="effects"/> via the EnumIDMap
/// 0x10000005 chain. index = LowestSetBit(effects)+1; if the entry is missing/zero,
/// retail falls back to index 0x21 (the solid-black tile). NOTE: the effect path has
/// NO lsb==-1 pre-check (unlike the type underlay), so effects==0 → index 0 → miss →
/// NO lsb==-1 pre-check (unlike the type underlay), so effects==0 → index 0 → miss →
/// fallback. (Retail IconData::RenderIcons 0x0058d180.)
/// </summary>
internal uint ResolveEffectDid(uint effects)
@ -129,16 +129,16 @@ public sealed class IconComposer
uint masterDid = (uint)_dats.Portal.Db.Header.MasterMapId; // = 0x25000000
if (masterDid == 0) return;
if (!_dats.Portal.TryGet<EnumIDMap>(masterDid, out var master)) return;
if (!master.ClientEnumToID.TryGetValue(0x10000005u, out var subDid)) return; // 0x25000009
if (!master.ClientEnumToID.TryGetValue(0x10000005u, out var subDid)) return; // → 0x25000009
if (_dats.Portal.TryGet<EnumIDMap>(subDid, out var sub)) _effectSubMap = sub;
}
/// <summary>
/// Retail <c>SurfaceWindow::ReplaceColor</c> SURFACE overload (0x004415b0): for every
/// pixel in <paramref name="dst"/> that equals pure-white-opaque (RGBAColor(1,1,1,1)
/// pixel in <paramref name="dst"/> that equals pure-white-opaque (RGBAColor(1,1,1,1) →
/// 0xFFFFFFFF), copy the SAME (x,y) pixel from the source effect tile. This preserves
/// the effect tile's texture/gradient (NOT a flat color). Retail requires the source to
/// cover the dest (it does both are 32x32); out-of-range pixels are left unchanged.
/// cover the dest (it does — both are 32x32); out-of-range pixels are left unchanged.
/// Mutates <paramref name="dst"/> in place.
/// </summary>
internal static void ReplaceWhiteFromSurface(byte[] dst, int dw, int dh, byte[] src, int sw, int sh)
@ -160,7 +160,7 @@ public sealed class IconComposer
/// <summary>
/// The decoded effect tile for <paramref name="effects"/> (enum 0x10000005). The tile is
/// a 32x32 textured RenderSurface whose pixels ARE the per-effect coloring (blue=Magical,
/// green=Poisoned, ; the 0x21 fallback is solid black). Retail copies it per-pixel into
/// green=Poisoned, …; the 0x21 fallback is solid black). Retail copies it per-pixel into
/// the icon's white pixels (gradient), so we need the whole tile, not a representative
/// color. Cached per DID.
/// </summary>
@ -224,27 +224,27 @@ public sealed class IconComposer
/// effects==0 resolves to the 0x21 solid-black fallback tile, so pure-white pixels become
/// black (matching retail); magical items take the per-effect hue instead.
/// </summary>
public uint GetIcon(ItemType itemType, uint iconId, uint underlayId, uint overlayId, uint effects)
public GpuTextureSlot GetIcon(ItemType itemType, uint iconId, uint underlayId, uint overlayId, uint effects)
{
if (iconId == 0) return 0;
if (iconId == 0) return GpuTextureSlot.Unassigned;
uint typeUnderlayDid = ResolveUnderlayDid(itemType);
var key = (typeUnderlayDid, iconId, underlayId, overlayId, effects);
if (_byTuple.TryGetValue(key, out var tex)) return tex;
// Stage 1 retail m_pDragIcon: base + custom overlay, then the effect recolor.
// Stage 1 — retail m_pDragIcon: base + custom overlay, then the effect recolor.
// RenderIcons retains this as a distinct Graphic because the cursor ghost must not
// carry the type/custom underlay that fills an inventory cell.
ComposedIcon? drag = GetOrCreateDragIcon(iconId, overlayId, effects);
// Stage 2 retail m_pIcon: type-default underlay (opaque) + custom underlay + drag.
// Stage 2 — retail m_pIcon: type-default underlay (opaque) + custom underlay + drag.
var layers = new List<(byte[] rgba, int w, int h)>();
AddLayer(layers, typeUnderlayDid);
AddLayer(layers, underlayId);
if (drag is not null) layers.Add((drag.Rgba, drag.Width, drag.Height));
if (layers.Count == 0) return 0;
if (layers.Count == 0) return GpuTextureSlot.Unassigned;
var (rgba, w, h) = Compose(layers);
uint handle = _cache.UploadRgba8(rgba, w, h, nearest: true);
GpuTextureSlot handle = _cache.UploadRgba8(rgba, w, h, nearest: true);
_byTuple[key] = handle;
return handle;
}
@ -255,13 +255,15 @@ public sealed class IconComposer
/// <c>UIElement_ItemList::PrepareDragIcon</c> obtains exactly this graphic through
/// <c>ACCWeenieObject::GetDragIcon</c> (0x004e2a50 / 0x0058d180).
/// </summary>
public uint GetDragIcon(ItemType itemType, uint iconId, uint underlayId, uint overlayId, uint effects)
public GpuTextureSlot GetDragIcon(ItemType itemType, uint iconId, uint underlayId, uint overlayId, uint effects)
{
// itemType/underlayId are deliberately unused: keeping the resolver signature identical
// to GetIcon lets every item-panel binding request the two retail siblings from one model.
_ = itemType;
_ = underlayId;
return iconId == 0 ? 0u : GetOrCreateDragIcon(iconId, overlayId, effects)?.Texture ?? 0u;
return iconId == 0
? GpuTextureSlot.Unassigned
: GetOrCreateDragIcon(iconId, overlayId, effects)?.Texture ?? GpuTextureSlot.Unassigned;
}
private ComposedIcon? GetOrCreateDragIcon(uint iconId, uint overlayId, uint effects)
@ -275,11 +277,11 @@ public sealed class IconComposer
if (dragLayers.Count == 0) return null;
var composed = Compose(dragLayers);
// Effect recolor ALWAYS, matching retail IconData::RenderIcons (0x0058d180):
// Effect recolor — ALWAYS, matching retail IconData::RenderIcons (0x0058d180):
// the effect tile (enum 0x10000005, lsb(effects)+1, fallback 0x21) is non-null
// even for effects==0 (the 0x21 SOLID-BLACK tile 0x060011C5). Retail's RenderIcons
// calls the SURFACE overload of SurfaceWindow::ReplaceColor (0x004415b0), copying
// the textured effect tile per-pixel into the icon's pure-white pixels so
// the textured effect tile per-pixel into the icon's pure-white pixels — so
// magical items take the tile's GRADIENT hue and mundane items go solid black.
// (Visually confirmed against retail 2026-06-17: the Energy Crystal's blue is a
// gradient, not a flat tint, and the no-mana scroll's edges are black.)
@ -287,7 +289,7 @@ public sealed class IconComposer
ReplaceWhiteFromSurface(composed.rgba, composed.w, composed.h,
tile.Rgba8, tile.Width, tile.Height);
uint texture = _cache.UploadRgba8(composed.rgba, composed.w, composed.h, nearest: true);
GpuTextureSlot texture = _cache.UploadRgba8(composed.rgba, composed.w, composed.h, nearest: true);
var created = new ComposedIcon(composed.rgba, composed.w, composed.h, texture);
_dragByTuple[key] = created;
return created;
@ -307,12 +309,12 @@ public sealed class IconComposer
/// Retail ClientMagicSystem::CompositeSpellIcon (0x00567550): power-level
/// backing, spell art, reversed/normal recolor, then self/fellow overlay.
/// </summary>
public uint GetSpellIcon(uint spellId)
public GpuTextureSlot GetSpellIcon(uint spellId)
{
if (_spellIcons.TryGetValue(spellId, out uint cached)) return cached;
if (_spellIcons.TryGetValue(spellId, out GpuTextureSlot cached)) return cached;
DatReaderWriter.DBObjs.SpellTable? table =
_dats.Get<DatReaderWriter.DBObjs.SpellTable>(0x0E00000Eu);
if (table is null || !table.Spells.TryGetValue(spellId, out var spell)) return 0u;
if (table is null || !table.Spells.TryGetValue(spellId, out var spell)) return GpuTextureSlot.Unassigned;
uint power = spell.Components.Count == 0
? 0u
@ -321,7 +323,7 @@ public sealed class IconComposer
var layers = new List<(byte[] rgba, int w, int h)>();
AddLayer(layers, powerBacking);
AddLayer(layers, spell.Icon);
if (layers.Count == 0) return 0u;
if (layers.Count == 0) return GpuTextureSlot.Unassigned;
var composed = Compose(layers);
uint tintIndex = (spell.Bitfield & DatReaderWriter.Enums.SpellIndex.Reversed) != 0
@ -344,7 +346,7 @@ public sealed class IconComposer
(overlay.Rgba8, overlay.Width, overlay.Height)]);
}
uint texture = _cache.UploadRgba8(composed.rgba, composed.w, composed.h, nearest: true);
GpuTextureSlot texture = _cache.UploadRgba8(composed.rgba, composed.w, composed.h, nearest: true);
_spellIcons[spellId] = texture;
return texture;
}
@ -353,11 +355,11 @@ public sealed class IconComposer
/// Retail ClientMagicSystem::CompositeSpellComponentIcon (0x00567720).
/// Components use their raw DAT art with pure white replaced by black.
/// </summary>
public uint GetSpellComponentIcon(uint iconId)
public GpuTextureSlot GetSpellComponentIcon(uint iconId)
{
if (iconId == 0u) return 0u;
if (_componentIcons.TryGetValue(iconId, out uint cached)) return cached;
if (!TryDecode(iconId, out DecodedTexture icon)) return 0u;
if (iconId == 0u) return GpuTextureSlot.Unassigned;
if (_componentIcons.TryGetValue(iconId, out GpuTextureSlot cached)) return cached;
if (!TryDecode(iconId, out DecodedTexture icon)) return GpuTextureSlot.Unassigned;
byte[] rgba = (byte[])icon.Rgba8.Clone();
for (int i = 0; i + 3 < rgba.Length; i += 4)
{
@ -365,7 +367,7 @@ public sealed class IconComposer
continue;
rgba[i] = rgba[i + 1] = rgba[i + 2] = 0;
}
uint texture = _cache.UploadRgba8(rgba, icon.Width, icon.Height, nearest: true);
GpuTextureSlot texture = _cache.UploadRgba8(rgba, icon.Width, icon.Height, nearest: true);
_componentIcons[iconId] = texture;
return texture;
}