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,11 +1,11 @@
// CellVisibility.cs — portal-based interior cell visibility system.
// CellVisibility.cs — portal-based interior cell visibility system.
//
// Stage 3 (2026-06-02): FindCameraCell + grace-frame AABB fallback deleted.
// The physics membership answer (CellGraph.CurrCell) is now the mandatory root;
// ComputeVisibilityFromRoot(null, ) returns null (outdoor root) rather than
// ComputeVisibilityFromRoot(null, …) returns null (outdoor root) rather than
// falling back to an independent AABB position resolve. This matches retail's
// CellManager::ChangePosition (0x004559B0) which does not re-derive the cell
// from a static position it reads the swept transition-owned CurrCell.
// from a static position — it reads the swept transition-owned CurrCell.
//
// This file is intentionally free of GL / rendering types. It depends only on
// System.Numerics so it can be unit-tested without a GPU context.
@ -23,7 +23,7 @@ namespace AcDream.App.Rendering;
/// A loaded EnvCell with portal connectivity and spatial data, used by
/// <see cref="CellVisibility"/> for portal-traversal visibility decisions.
/// </summary>
public sealed class LoadedCell
internal sealed class LoadedCell
{
/// <summary>Full 32-bit cell ID, e.g. 0xA9B40105.</summary>
public uint CellId;
@ -87,7 +87,7 @@ public sealed class LoadedCell
public uint? BuildingId { get; internal set; }
/// <summary>
/// Phase U.4c: the stab_list PVS as full (landblock-prefixed) cell ids retail
/// Phase U.4c: the stab_list PVS as full (landblock-prefixed) cell ids — retail
/// CEnvCell.stab_list (acclient.h ~30925), the stable set of cells potentially
/// visible from this cell, precomputed by the AC content tools. Refreshed only at
/// hydration (= retail's per-cell-entry grab_visible_cells, decomp:311878).
@ -98,7 +98,7 @@ public sealed class LoadedCell
public IReadOnlyList<uint> VisibleCells = System.Array.Empty<uint>();
/// <summary>
/// Phase U.4c: retail CEnvCell.seen_outside (acclient.h ~30925) this cell sees
/// Phase U.4c: retail CEnvCell.seen_outside (acclient.h ~30925) — this cell sees
/// the exterior (an exit portal is reachable from it). Retail gates the landscape
/// data + draw decision on the camera cell's value (RenderNormalMode decomp:92649,
/// grab_visible_cells decomp:311878). The stable anchor for the terrain-draw test.
@ -107,7 +107,7 @@ public sealed class LoadedCell
/// <summary>
/// Render unification (2026-06-07): true for the synthetic OUTDOOR cell node built by
/// <see cref="OutdoorCellNode.Build"/> the outdoor world modelled as a flood-graph cell whose
/// <see cref="OutdoorCellNode.Build"/> — the outdoor world modelled as a flood-graph cell whose
/// shell is the landscape. <see cref="PortalVisibilityBuilder.Build"/> seeds OutsideView
/// full-screen when the root carries this flag (so terrain/sky/scenery draw as the node's shell).
/// An explicit flag, not a cell-id heuristic: interior EnvCell ids are >= 0x100 in production but
@ -123,19 +123,19 @@ public sealed class LoadedCell
/// <see cref="OtherPortalId"/> is the dat's reciprocal back-link: the index of
/// the portal WITHIN the neighbour cell's portal list that points back through
/// this same opening. Retail indexes the reciprocal directly via this field
/// (<c>arg2-&gt;other_portal_id</c>, decomp:433557) rather than scanning which
/// (<c>arg2-&gt;other_portal_id</c>, decomp:433557) rather than scanning — which
/// is what lets a cell with TWO portals to the same neighbour resolve each
/// opening against its OWN reciprocal polygon instead of the first match.
/// </para>
/// </summary>
public readonly record struct CellPortalInfo(
internal readonly record struct CellPortalInfo(
ushort OtherCellId, ushort PolygonId, ushort Flags, ushort OtherPortalId);
/// <summary>
/// Clip plane derived from a portal polygon, in cell-local space.
/// Plane equation: Normal.X*x + Normal.Y*y + Normal.Z*z + D = 0.
/// </summary>
public struct PortalClipPlane
internal struct PortalClipPlane
{
/// <summary>Plane normal (cell-local space, unit length).</summary>
public Vector3 Normal;
@ -146,8 +146,8 @@ public struct PortalClipPlane
/// <summary>
/// Which half-space is "inside" this cell (the side from which you look outward
/// through the portal):
/// 0 camera dot-product must be >= 0 (positive half-space is inside)
/// 1 camera dot-product must be &lt;= 0 (negative half-space is inside)
/// 0 → camera dot-product must be >= 0 (positive half-space is inside)
/// 1 → camera dot-product must be &lt;= 0 (negative half-space is inside)
/// Determined from cell centroid position relative to the portal plane.
/// Ported from ACME EnvCellManager.cs ~line 404.
/// </summary>
@ -155,12 +155,12 @@ public struct PortalClipPlane
}
/// <summary>
/// Phase U.4c flap probe (diagnostic OBSOLETE as of Stage 3). Previously tracked
/// Phase U.4c flap probe (diagnostic — OBSOLETE as of Stage 3). Previously tracked
/// which branch of FindCameraCell (now deleted) resolved the camera cell. Retained
/// for binary compatibility with the [flap-cam] probe log site in GameWindow.cs that
/// still prints <see cref="LastCameraCellResolution"/> (always None post-Stage 3).
/// </summary>
public enum CameraCellResolution
internal enum CameraCellResolution
{
/// <summary>No cell contains the eye (outdoors), or not yet resolved.</summary>
None,
@ -171,14 +171,14 @@ public enum CameraCellResolution
/// <summary>The eye is inside a cell found by the full brute-force scan.</summary>
BruteForce,
/// <summary>The eye is inside NO cell, but the previous cell is kept alive for a
/// few grace frames the "stale root" case the flap probe watches for.</summary>
/// few grace frames — the "stale root" case the flap probe watches for.</summary>
Grace,
}
/// <summary>
/// Result of a portal-based visibility BFS from the camera cell.
/// </summary>
public sealed class VisibilityResult
internal sealed class VisibilityResult
{
/// <summary>Full cell IDs (e.g. 0x01D90105) that should be rendered this frame.</summary>
public HashSet<uint> VisibleCellIds { get; init; } = new();
@ -207,7 +207,7 @@ public sealed class VisibilityResult
/// Ported faithfully from ACME's EnvCellManager.cs portal-visibility region.
/// Constants and control flow match the ACME implementation.
/// </summary>
public sealed class CellVisibility
internal sealed class CellVisibility
{
// ------------------------------------------------------------------
// Constants (ACME ground-truth values)
@ -234,7 +234,7 @@ public sealed class CellVisibility
public VisibilityResult? LastVisibilityResult { get; private set; }
/// <summary>
/// Stage 3 (2026-06-02): always <see cref="CameraCellResolution.None"/> the FindCameraCell
/// Stage 3 (2026-06-02): always <see cref="CameraCellResolution.None"/> — the FindCameraCell
/// AABB grace-frame resolver was deleted; the physics membership answer is the sole root.
/// Retained for the [flap-cam] probe log line in GameWindow.cs.
/// </summary>
@ -292,7 +292,7 @@ public sealed class CellVisibility
/// <summary>
/// Phase A8 (2026-05-28): enumerates the loaded cells that belong to a
/// landblock prefix. Used by <c>LandblockRenderPublisher</c> when building
/// the per-landblock <c>BuildingRegistry</c> the per-frame
/// the per-landblock <c>BuildingRegistry</c> — the per-frame
/// <c>drainedCells</c> dict misses cells loaded on prior frames, so the
/// stamping loop in <see cref="Wb.BuildingLoader.Build"/> needs access to
/// every cell currently in the landblock to ensure <c>BuildingId</c> is set.
@ -356,15 +356,15 @@ public sealed class CellVisibility
/// <summary>
/// UCG W2/Stage 3: compute visibility from a supplied root cell (the physics membership
/// answer). When <paramref name="root"/> is null (pre-spawn, or player outside all indoor
/// cells), returns <c>null</c> the caller interprets null as the outdoor root (no portal
/// cells), returns <c>null</c> — the caller interprets null as the outdoor root (no portal
/// frame, everything slot 0, terrain ungated). The legacy AABB FindCameraCell fallback is
/// deleted as of Stage 3; <see cref="CellGraph.CurrCell"/> is the sole authority.
/// Retail anchor: CellManager::ChangePosition @ 0x004559B0 reads the transition-owned
/// curr_cell it does NOT re-derive from a static position.
/// curr_cell — it does NOT re-derive from a static position.
/// </summary>
/// <param name="root">
/// The render-registered <see cref="LoadedCell"/> that physics determined the player is inside,
/// or null when pre-spawn or the player is in an outdoor landcell. Null outdoor root path.
/// or null when pre-spawn or the player is in an outdoor landcell. Null → outdoor root path.
/// </param>
/// <param name="fallbackPos">
/// Used as the viewer position for the portal-side test in the BFS when root is non-null.
@ -389,13 +389,13 @@ public sealed class CellVisibility
}
// ------------------------------------------------------------------
// FindCameraCell DELETED in Stage 3 (2026-06-02)
// FindCameraCell — DELETED in Stage 3 (2026-06-02)
// ------------------------------------------------------------------
// The AABB + grace-frame camera-cell resolver was removed. Production code
// now exclusively uses ComputeVisibilityFromRoot(root, ) where root is the
// now exclusively uses ComputeVisibilityFromRoot(root, …) where root is the
// transition-owned CellGraph.CurrCell (set by ResolveCellId/Stage 2 physics).
// Retail anchor: CellManager::ChangePosition (0x004559B0) reads curr_cell
// from the sweep it never re-derives from a static position.
// from the sweep — it never re-derives from a static position.
//
// GetVisibleCells (used by ComputeVisibility below for test compatibility)
// still uses the brute-force AABB scan internally.
@ -471,12 +471,12 @@ public sealed class CellVisibility
/// <summary>
/// UCG W2: BFS visibility traversal from a pre-resolved root cell.
/// The root is the correct membership answer (supplied by the caller
/// The root is the correct membership answer (supplied by the caller —
/// physics CurrCell via <see cref="ComputeVisibilityFromRoot"/>, or AABB
/// scan via <see cref="GetVisibleCells"/> for test compat).
///
/// The BFS body is byte-identical to the original GetVisibleCells
/// implementation only root acquisition was extracted out.
/// implementation — only root acquisition was extracted out.
/// </summary>
private VisibilityResult? GetVisibleCellsFromRoot(LoadedCell cameraCell, Vector3 cameraPos)
{
@ -499,7 +499,7 @@ public sealed class CellVisibility
{
var portal = cell.Portals[i];
// Exit portal outdoor terrain should be visible.
// Exit portal → outdoor terrain should be visible.
if (portal.OtherCellId == 0xFFFF)
{
result.HasExitPortalVisible = true;
@ -522,8 +522,8 @@ public sealed class CellVisibility
var localCam = Vector3.Transform(cameraPos, cell.InverseWorldTransform);
float dot = Vector3.Dot(plane.Normal, localCam) + plane.D;
// InsideSide == 0 → inside is positive half-space; reject if dot < -ε.
// InsideSide == 1 → inside is negative half-space; reject if dot > ε.
// InsideSide == 0 → inside is positive half-space; reject if dot < -ε.
// InsideSide == 1 → inside is negative half-space; reject if dot > ε.
// Source: ACME EnvCellManager.cs lines 1458-1459.
if (plane.InsideSide == 0 && dot < -PointInCellEpsilon)
continue;