acdream/tests/AcDream.App.Tests/Rendering/ClipFrameLayoutTests.cs
Erik 89c4494d05 fix(render): S3 review round 1 — punch fans clipped by their own view, seal pin through the producer, dead per-cell clip machinery deleted, EC/OC transcript exact
F1 (BLOCKING, punch-fan view alignment). ClipFrameAssembler.
ReassembleOutsideViewFromWalk now keeps exactly ONE outside-view slice per
walk view, index-aligned with RetailFrameWalk.DrawBuilding's own
ActiveViewIndex (retail building_view = portal_view_num @0x0059f3bf): a
collapsed view (ClipPlaneSet.IsNothingVisible — retail polyClipFinish under
a degenerate view leaves <3 vertices, 0x59BDBC-0x59BDBF) now appends its
own ClipViewSlice.NothingVisible=true slot instead of being skipped, which
used to shift every later view's slice down by one. DrawWalkPunchFan draws
NOTHING for a NothingVisible slice and throws ArgumentOutOfRangeException
when activeViewIndex is out of range (fail-loud; never draws unclipped).
New tests: WalkOutsideViewReassemblyTests.
FirstViewCollapses_SecondSurvives_SlicesStayIndexAligned and
PunchLeaf_UsesIndexAlignedSlice_DrawsNothingForCollapsed_ThrowsOutOfRange.
MUTATION M1 (revert the append-nothing-on-skip fix, restoring the old
skip): both new tests fail with
  Assert.Equal() Failure: Values differ
  Expected: 2
  Actual:   1
MUTATION M2 (restore the old ": default" unclipped fallback in
DrawWalkPunchFan): the punch-leaf test fails with
  Assert.Equal() Failure: Values differ
  Expected: 0
  Actual:   1
(both restored; verified clean afterward).

F2 (major, exit-seal pin through the real producer + both overflow cases).
The exit-seal CPU/GPU equivalence pin moved from ClipFrameLayoutTests (which
drove ClipFrame.AppendSlot(ClipPlaneSet) via the zero-caller
ClipFrameAssembler.Assemble) to the new
tests/.../Walk/WalkFrameDriverClipSealTests.cs, which drives
WalkFrameDriver.BeginFrame + the real IWalkEventSink.OnInteriorFloodDrawTurn
hook — the SAME path RetailPViewPassExecutor.DrawExitPortalMask resolves
through via WalkFrameDriver.InteriorFloodViewClipPlanesAt. The new pin
compares WalkFrameDriver's captured planes EXACTLY (not just geometrically)
against ClipPlaneSet.From's independent CCW-normalized-perpendicular
computation, since AppendClipSlot's per-edge formula is bit-identical to
ClipPlaneSet's own. Two overflow cases added: a 9-vertex portal view exit-seals
to exactly the 4 conservative AABB planes containing every source vertex
(over-include, never under-include — AppendClipSlot's fallback for a view too
complex for the 8-plane budget); a 9-vertex OUTSIDE view (the punch-fan
sibling, WalkOutsideViewReassemblyTests.
NineVertexOutsideView_PunchSliceHasZeroPlanes_DrawsUnclipped_NotNothingVisible)
produces a zero-plane, NOT-NothingVisible slice — draws fully unclipped,
distinct from F1's "draw nothing" state.
MUTATION M1 (flip the winding selection, `ccw = area2 < 0f`):
  Assert.Equal() Failure: Values are not within 4 decimal places
  Expected: 0.9191 (rounded from 0.919144988)
  Actual:   0.8944 (rounded from 0.89442724)
MUTATION M2 (drop the normalize from the per-edge plane formula):
  Assert.Equal() Failure: Values are not within 4 decimal places
  Expected: 0.9191 (rounded from 0.919144988)
  Actual:   0.7 (rounded from 0.700000048)
MUTATION M3 (delete the >8-plane AABB overflow branch — the per-edge loop
then indexes a fixed 8-plane stackalloc with a 9-edge polygon):
  System.IndexOutOfRangeException : Index was outside the bounds of the array.
    at WalkFrameDriver.AppendClipSlot(...) line 1915
    at WalkFrameDriver.CaptureViews(...) -> CaptureCellViews -> CaptureCellViewRoute
    -> EmitFloodTurns -> IWalkEventSink.OnInteriorFloodDrawTurn
(all three restored; verified clean afterward).

F3 (minor/major). RetailPViewPassExecutor.cs's false bracket comment
(neither KEEP clip — exit seals nor punch fans — ever called Enable/
DisableClipDistances; the six DisableClipDistances() call sites all sat
around the UNCLIPPED particle/weather draws, whose bodies are no-ops on the
only backend) is rewritten to the truth; the six no-op calls and the
private DisableClipDistances() wrapper are deleted.
IWorldPassSurface.EnableClipDistances/DisableClipDistances stay on the
INTERFACE — WorldScenePassExecutor (the separate flat-world path) still
calls them.

F4a (EC transcript exactness). WalkFrameDriver.EmitFloodTurns now prints one
"EC" line per LIVE VIEW of the flood cell (retail's setup_view/DrawEnvCell
loop, PView::DrawCells @0x005a4ab1-0x005a4acc, fires once per live portal_view
slice, not once per cell) via the captured route's own SliceCount — read
directly off _lookInTurns[viewRouteIndex] rather than through
InteriorFloodViewSliceCountAt's flood-index indirection, because this same
loop also serves a building's LOOK-IN flood (WalkDrawStage.LookInStatic),
whose cells never populate InteriorFloodCells (the interior ROOT flood only)
— indexing through that accessor threw ArgumentOutOfRangeException on a real
look-in turn during verification, fixed before landing. The actual CellShell
DRAW event is unchanged (the frame stamp still dedupes it to one submission).

F4b (transcript exactness, trailing weather OC).
WalkTraceConformanceTests.Recorder now implements IWalkEventSink.
OnWeatherTurn (the interface's silent no-op default previously left the
replay side of Signature8 blind to the weather turn's own "OC" line), and
WalkTraceReplayContext.Signature8(WalkOracleFrame) no longer excludes the
trailing per-frame weather ObjectCellTurn — every ObjectCellTurn now reads
literally, on both sides. Implementing OnWeatherTurn alone left
Still_fixture_first_frame_reproduces_exactly(terrace-edge.walk) diverging
ONLY on the newly-un-excluded trailing OC (EXPECTED ...OC:f4180104|
OC:f418000b vs ACTUAL ...OC:f4180104 — a length-12 tail, nothing else
differs across a 16.6k-char signature) because
WalkTraceReplayContext.WeatherGateOpen had always defaulted to false (the
harness never needed to fire the walk's weather hook before). Per the
review round's own instruction not to weaken the pin, the harness itself is
fixed instead: WalkTraceReplayContext now implements ViewerCellId (= the
harness's own WalkFrame cameraCellId argument, matching production's
RetailPViewFrameInput.ViewerCellId invariant) and WeatherGateOpen
(retail's own SmartBox::is_player_outside gate, (cellId & 0xFFFF) < 0x100,
with no App-level render-toggle concept to AND against). MUTATION (delete
Recorder.OnWeatherTurn): Still_fixture_first_frame_reproduces_exactly
(terrace-edge.walk) fails with EXPECTED ending "...OC:f4180104|OC:f418000b"
vs ACTUAL ending "...OC:f4180104" (the trailing OC missing) — restored;
verified clean afterward.
Fixture-row status (InstalledDat lane, WalkTraceConformanceTests, 14 rows):
13 pass, 1 fails — Oh_doorway_still_first_frame_diff, the PRE-EXISTING
[Trait("Status","KnownFailure")] #458 row (a documented block-plane
precision boundary at token index 165, LC/SC content, upstream of any
EC/OC — unaffected by and unrelated to this round's OC change). Every OTHER
row, including every eight-kind (Signature8) row that now compares the
weather OC literally, passes exactly.

F5 (major, dead per-cell clip machinery). WbDrawDispatcher.SetClipRouting
(the only writer of the per-instance routing-active flag) had ZERO
production callers; EnvCellRenderer.SetClipRouting was called only with
null (WorldScenePassExecutor's BeginFrame/AbortFrame) — no path could ever
arm the per-cell clip-region table, on the walk path OR the flat path (the
S3 landing-hygiene AD-17 correction's "live for the flat path" clause is
itself corrected here: dormant in every path, deleted). Deleted:
WbDrawDispatcher's SetClipRouting/ClearClipRouting and their four backing
fields; EnvCellRenderer's SetClipRouting and its backing field (its
RenderModernMDIInternal write now unconditionally clears instanceClipSlot);
the ProbeClipRouteEnabled-gated per-frame [clip-route-disp] dispatch probe
and its three backing fields (the OTHER two ACDREAM_PROBE_CLIPROUTE
producers, [clip-route] and [clip-route-scis] in WorldRenderDiagnostics.cs,
are untouched — a different, still-live mechanism); ResolveEntitySlot,
IsIndoorCellId and the ClipSlotCull sentinel; the ACDREAM_CLIP_DEBUG probe
(RenderingDiagnostics.ClipDebugNoShellTrim) and its docs/launch-options.md
row, since the "clip shells" branch it toggled between is gone.
ResolveSlotForFrame is simplified to a parameterless
`(uint Slot, bool Culled) ResolveSlotForFrame() => (0u, false)` per the
review's own framing ("it becomes slot 0, never culled") rather than
deleted outright, since its callers (WbDrawDispatcher.cs and
WbDrawDispatcher.WalkClassify.cs) still want the same two-value shape.
tests/.../Wb/WbDrawDispatcherClipSlotTests.cs (12 tests, all exercising the
deleted routing arm via ResolveEntitySlot/the active ResolveSlotForFrame
branch) is replaced with one pin on the new parameterless behavior.
Shaders: mesh_modern.vert, mesh_atmospheric.vert, mesh_detail.vert,
particle.vert and particle_mesh.vert each lose their CellClip struct +
binding=2 ClipRegionBuf fetch, gl_ClipDistance write loop, and gl_PerVertex
redeclaration (portal_depth.vert's own, separate gl_PerVertex/gl_ClipDistance
pair — the KEEP mechanism, its planes handed through the TerrainClip UBO at
binding=2 in the UBO namespace — is untouched; verified it never read the
deleted SSBO). Recompiled via tools/compile-shaders.ps1 (glslc backend
detected; managed shaderc path ran); 24/24 pairs compiled. Re-pinned in
VulkanShaderManifestTests.RetailOracleSpirvSha256 (the only three of the
five edited shaders that carry a byte-exact retail-oracle pin):
  mesh_modern.vert.spv    = f9ed4ee7140ccd136130559dbea68545f733f6022f52b085b6df4bcb787223c6
  particle.vert.spv       = 95ce6ecf834930a92da5c5fe9aef513b38b5ba104704b98c1606af71fe17eaf3
  particle_mesh.vert.spv  = 043482b97c2ed036511692f89c75a0a6c298aba48cb519e5e3aff7fe7ba6371b
(mesh_atmospheric.vert.spv / mesh_detail.vert.spv changed too but carry no
retail-oracle pin, so no re-pin was needed for them.)
tests/.../ParticleBindlessInstanceTests.cs's
Assert.Contains("clipRegions[aClipSlot]", vertex) — a real breakage the
grep sweep caught — is deleted with a note; the surrounding aClipSlot
attribute-declaration assertion stays.
Vertex-layout residue kept THIS round, fed 0 by the CPU, unread by any
shader (S5's instance-buffer-layout revisit): instanceClipSlot[] (binding=3
SSBO) in mesh_modern.vert/mesh_atmospheric.vert/mesh_detail.vert; aClipSlot
(a per-vertex attribute) in particle.vert/particle_mesh.vert.
Grep sweep — "SetClipRouting|_clipRoutingActive|ClearClipRouting|
BeginScissor|NdcScissorRect|SetTerrainClip|BindTerrainClip|TerrainBytes|
ScissorNdcAabb|UseScissorFallback" over src/ and tests/: EMPTY (also swept
and rewrote several PRE-EXISTING prose mentions of BeginScissor/
ClearClipRouting in RetailPViewPassExecutor.cs, RetailPViewRenderer.cs,
WorldPassSurface.cs and RetailPViewPassExecutorTests.cs that predate this
commit's own work, purely to satisfy the literal sweep). "clipRegions|
instanceClipSlot|aClipSlot": every remaining match is the vertex-layout
residue named above, or a comment/assertion describing that same residue.

Deviations from a fully literal reading of F5 (recorded here since none of
them cross the mandatory automated gates, all of which pass):
- The C#-side ClipRegions SSBO publish/bind pipeline
  (RhiWorldPassSurface.PrepareClipFrame's publish, WorldFrameSections.
  ClipRegions, and ClipFrame's internal std430 byte-packing —
  RegionBytes/RegionBytesForTest/CellClipStrideBytes) is NOT deleted this
  round; it is left as documented dead residue (verified zero shader
  readers) rather than rewritten. The mandatory grep sweep targets the
  shader-source identifier `clipRegions` (lowercase), which is fully clean;
  the C# publish machinery sits behind ~8 files (ClipFrame.cs,
  WorldPassSurface.cs, WbDrawDispatcher.Rhi.cs, WorldPassScope.cs,
  GpuBindingModel.cs, EnvCellRenderer.Rhi.cs, ParticleRenderer.Rhi.cs,
  WbDrawDispatcher.OrderedStream.cs, plus the ClipFrameLayoutTests std430
  pins) and CellClipPlanesOffset/MaxPlanes are the SAME constants
  portal_depth.vert's KEEP mechanism uses for its own, unrelated UBO layout
  — a full rewrite carried materially higher regression risk than this
  round's mandatory scope justified. ClipFrame.cs and WorldPassSurface.cs
  now both name this residue explicitly in their doc comments for a future
  round to finish.
- SetClipRegionSsbo/_sharedClipRegionSsbo in WbDrawDispatcher.cs (a
  pre-existing, already fully dead GL-era write-only field/method with zero
  callers, unrelated to per-instance clip-slot routing) is left untouched —
  outside F5's named scope and outside the mandatory grep sweep.
- WalkTraceReplayContext.ViewerCellId/WeatherGateOpen (F4b, detailed above)
  is an addition beyond the literal §12 text, made to keep the InstalledDat
  lane at exactly the four established known failures without weakening
  the newly-un-excluded OC pin.

Gates: dotnet build tests/AcDream.App.Tests/AcDream.App.Tests.csproj -c
Release and dotnet build src/AcDream.App/AcDream.App.csproj -c Release both
0 warnings/0 errors; dotnet build AcDream.slnx -c Release 0 warnings/0
errors; hermetic lane 6815/6815 passed; InstalledDat lane 243 passed / 4
failed / 1 skipped (exactly the four known failures: two #383 layout tests,
TowerAscentReplayTests, Oh_doorway_still_first_frame_diff #458);
VulkanShaderDescriptorContractTests/VulkanShaderManifestTests/
RenderPackSpirvValidatorTests/SkyVertexLayoutTests 34/34 passed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-03 20:15:29 +02:00

329 lines
15 KiB
C#

using System.Numerics;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Rendering.Walk;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Phase U.3: CPU-side proof that <see cref="ClipFrame"/> packs the mesh SSBO
/// clip-region table in the EXACT std430 byte layout mesh_modern.vert reads. A
/// silent layout drift here would mis-clip at U.4 with no build error — these
/// tests are the gate that catches it.
///
/// Layout under test (mesh CellClip, std430):
/// offset 0 : uint count
/// offset 4 : uint _p0 (pad)
/// offset 8 : uint _p1 (pad)
/// offset 12 : uint _p2 (pad)
/// offset 16 : vec4 planes[0] (16-byte vec4 stride)
/// ...
/// offset 16 + i*16 : vec4 planes[i]
/// stride 144 bytes per slot.
///
/// <see cref="ClipFrame.TerrainUboBytes"/>/<see cref="ClipFrame.TerrainClipUboBinding"/>
/// share this file only because they happen to reuse the identical std140
/// 144-byte shape for a DIFFERENT, still-live consumer — see their own doc
/// comments (S3 chunk 4 fix round 2, L3).
/// </summary>
public class ClipFrameLayoutTests
{
private static float ReadFloat(System.ReadOnlySpan<byte> b, int offset)
=> System.BitConverter.ToSingle(b.Slice(offset, 4));
private static uint ReadUInt(System.ReadOnlySpan<byte> b, int offset)
=> System.BitConverter.ToUInt32(b.Slice(offset, 4));
private static int ReadInt(System.ReadOnlySpan<byte> b, int offset)
=> System.BitConverter.ToInt32(b.Slice(offset, 4));
[Fact]
public void LayoutConstants_MatchShaderStruct()
{
// CellClip: 16 (count + 3 pad uints) + 8*16 (vec4 planes) = 144.
Assert.Equal(144, ClipFrame.CellClipStrideBytes);
Assert.Equal(16, ClipFrame.CellClipPlanesOffset);
Assert.Equal(8, ClipFrame.MaxPlanes);
Assert.Equal(144, ClipFrame.TerrainUboBytes);
// Binding contract: mesh clip regions on SSBO binding=2, PortalDepthMaskRenderer's
// exit-seal/punch-fan clip block on UBO binding=2. The mesh side's binding
// index moved off ClipFrame at Campaign V slice V11 — the RHI arm addresses
// it through GpuBindingModel.StorageClipRegions instead of a raw GL binding
// constant (see ClipFrame's BeginFrame doc comment); the portal-depth UBO
// binding is still genuinely shared, so it stays.
Assert.Equal(2u, GpuBindingModel.StorageClipRegions);
Assert.Equal(2u, ClipFrame.TerrainClipUboBinding);
}
[Fact]
public void NoClip_HasExactlyOneSlot_AllZeros_Count0()
{
var frame = ClipFrame.NoClip();
Assert.Equal(1, frame.SlotCount);
var bytes = frame.RegionBytesForTest;
Assert.Equal(ClipFrame.CellClipStrideBytes, bytes.Length); // 144 — exactly one slot
// count == 0 ⇒ shader passes every plane (no-clip).
Assert.Equal(0u, ReadUInt(bytes, 0));
// Every byte of the reserved no-clip slot is zero.
foreach (var b in bytes)
Assert.Equal(0, b);
}
[Fact]
public void AppendSlot_WritesCountAndPlanes_AtStd430Offsets()
{
var frame = ClipFrame.NoClip();
// Three distinct planes so each lands at a verifiable offset.
var p0 = new Vector4(1f, 0f, 0f, 0.5f);
var p1 = new Vector4(0f, 1f, 0f, 0.25f);
var p2 = new Vector4(-1f, 0f, 0f, -0.75f);
int slot = frame.AppendSlot(new[] { p0, p1, p2 });
Assert.Equal(1, slot); // slot 0 is the reserved no-clip; this is slot 1
Assert.Equal(2, frame.SlotCount);
var bytes = frame.RegionBytesForTest;
Assert.Equal(2 * ClipFrame.CellClipStrideBytes, bytes.Length); // two slots now
int baseOff = slot * ClipFrame.CellClipStrideBytes; // 144
// count == 3 at offset 0 of the slot; the 3 pad uints stay zero.
Assert.Equal(3u, ReadUInt(bytes, baseOff + 0));
Assert.Equal(0u, ReadUInt(bytes, baseOff + 4));
Assert.Equal(0u, ReadUInt(bytes, baseOff + 8));
Assert.Equal(0u, ReadUInt(bytes, baseOff + 12));
// planes[0..2] at offset 16, 32, 48 (vec4 stride 16).
AssertPlaneAt(bytes, baseOff + 16, p0);
AssertPlaneAt(bytes, baseOff + 32, p1);
AssertPlaneAt(bytes, baseOff + 48, p2);
// Slot 0 (the reserved no-clip) is untouched: still count 0.
Assert.Equal(0u, ReadUInt(bytes, 0));
}
[Fact]
public void GetSlotPlanes_BorrowsTheExactPackedClipRegion()
{
using ClipFrame frame = ClipFrame.NoClip();
Vector4[] expected =
[
new(1f, 2f, 3f, 4f),
new(-5f, 6f, -7f, 8f),
];
int slot = frame.AppendSlot(expected);
ReadOnlySpan<Vector4> actual = frame.GetSlotPlanes(checked((uint)slot));
Assert.Equal(expected.Length, actual.Length);
Assert.Equal(expected[0], actual[0]);
Assert.Equal(expected[1], actual[1]);
Assert.Equal(0, frame.GetSlotPlanes(0).Length);
}
[Fact]
public void AppendSlot_EmptyPlaneList_PacksNoClipSlot_Count0()
{
var frame = ClipFrame.NoClip();
int slot = frame.AppendSlot(System.ReadOnlySpan<Vector4>.Empty);
Assert.Equal(1, slot);
var bytes = frame.RegionBytesForTest;
Assert.Equal(0u, ReadUInt(bytes, slot * ClipFrame.CellClipStrideBytes)); // count 0
}
[Fact]
public void AppendSlot_ClampsToEightPlanes()
{
var frame = ClipFrame.NoClip();
var planes = new Vector4[12];
for (int i = 0; i < planes.Length; i++)
planes[i] = new Vector4(i, 0f, 0f, 0f);
int slot = frame.AppendSlot(planes);
var bytes = frame.RegionBytesForTest;
// Only MaxPlanes (8) are recorded in the count.
Assert.Equal((uint)ClipFrame.MaxPlanes, ReadUInt(bytes, slot * ClipFrame.CellClipStrideBytes));
}
[Fact]
public void AppendSlot_FromClipPlaneSet_AxisAlignedSquare_PacksFourPlanes()
{
// A unit square in NDC → ClipPlaneSet with 4 convex planes.
var cv = new CellView();
cv.Add(new ViewPolygon(new[]
{
new Vector2(-0.5f, -0.5f), new Vector2(0.5f, -0.5f),
new Vector2(0.5f, 0.5f), new Vector2(-0.5f, 0.5f),
}));
var cps = ClipPlaneSet.From(cv);
Assert.Equal(4, cps.Count);
var frame = ClipFrame.NoClip();
int slot = frame.AppendSlot(cps);
var bytes = frame.RegionBytesForTest;
int baseOff = slot * ClipFrame.CellClipStrideBytes;
Assert.Equal(4u, ReadUInt(bytes, baseOff + 0));
// Each packed plane must match the ClipPlaneSet's plane bit-for-bit.
for (int i = 0; i < 4; i++)
AssertPlaneAt(bytes, baseOff + ClipFrame.CellClipPlanesOffset + i * 16, cps.Planes[i]);
}
// S3 chunk 4 fix round 2 (L3): the walk's screen-space clip gate and its
// own std140 layout pin are deleted outright — no shader declares that
// block any more, so there is nothing left to pack or pin.
private static void AssertPlaneAt(System.ReadOnlySpan<byte> bytes, int offset, Vector4 expected)
{
Assert.Equal(expected.X, ReadFloat(bytes, offset + 0), 6);
Assert.Equal(expected.Y, ReadFloat(bytes, offset + 4), 6);
Assert.Equal(expected.Z, ReadFloat(bytes, offset + 8), 6);
Assert.Equal(expected.W, ReadFloat(bytes, offset + 12), 6);
}
// ── S3 chunk 4 (§10.2 KEEP): CPU/GPU clip-plane equivalence pins ────────
//
// Grepped first (per the chunk 4 contract): ClipPlaneSetTests.cs pins
// sign correctness (inside >= 0, just-outside < 0 on SOME plane) and
// AppendSlot_FromClipPlaneSet_AxisAlignedSquare_PacksFourPlanes pins
// bit-exact GPU packing of ClipPlaneSet's own output — neither asks
// whether a point ON an edge has ~0 distance under the planes actually
// read back through each KEEP item's real production accessor.
//
// KEEP item 1 — exit seals — moved to
// AcDream.App.Tests.Rendering.Walk.WalkFrameDriverClipSealTests
// (S3 review fix round 1, F2): the pin that used to live here drove
// ClipFrame.AppendSlot(ClipPlaneSet) directly through
// ClipFrameAssembler.Assemble's packed-byte round trip — an overload
// and a method with ZERO production callers (production interior roots
// never call Assemble; RetailPViewPassExecutor.DrawExitPortalMask
// reads its planes through WalkFrameDriver.InteriorFloodViewClipPlanesAt,
// which resolves through the driver's own CaptureViews/AppendClipSlot).
// The rewritten pin drives THAT real producer — it needs
// WalkFrameDriverTests' own DispatcherFixture/TestContext harness, so it
// lives alongside them rather than duplicating that machinery here.
//
// KEEP item 2 — punch fans stays below (it already drove the exact pair
// that runs: BeginWalkFrame + ReassembleOutsideViewFromWalk).
/// <summary>
/// KEEP item 2 — punch fans: <c>RetailPViewPassExecutor.DrawWalkPunchFan</c>
/// reads its clip planes through <c>clipAssembly.OutsideViewSlices
/// [activeViewIndex].Planes</c> — <see cref="ClipViewSlice"/>'s
/// <c>Planes</c> field. S3 chunk 4 fix round 2 (L4): a prior round's pin
/// here built the slice through <c>ClipFrameAssembler.Assemble</c> — but
/// <c>Assemble</c> has ZERO production callers (it exists only for
/// isolated research/replay tests, per this file's own class header);
/// production builds an interior root's outside-view slices through
/// <c>BeginWalkFrame</c> + <c>ReassembleOutsideViewFromWalk</c>
/// (<c>RetailPViewPassExecutor.cs</c>'s <c>BeginWalkFrame</c> call,
/// <c>RetailPViewRenderer.cs</c>'s <c>ReassembleOutsideViewFromWalk</c>
/// call), so a pin through <c>Assemble</c> proves nothing about the code
/// that actually runs. This pin now drives that EXACT pair: a synthetic
/// <see cref="WalkPortalView"/> holding one pixel-space polygon (built
/// the way <c>WalkCopyViewTests</c> builds views), fed through
/// <c>BeginWalkFrame(frame, outdoorRoot: false)</c> then
/// <c>ReassembleOutsideViewFromWalk</c> — both of which now call the
/// SAME shared <c>ClipFrameAssembler.AppendOutsideSlice</c> helper
/// <c>Assemble</c> would have (L4's own de-duplication), so this pin
/// exercises the helper through the producer that actually runs.
/// MUTATION: perturbing <c>planes[0].W</c> INSIDE that shared helper (the
/// one place both producers pack a plane) breaks this pin — see the
/// commit body for the recorded failing assertion text. The pin's own
/// source contains no <c>Assemble(</c> call (grep-checked in the commit
/// body). Same non-axis-aligned synthetic polygon as before, kept
/// distinct from the exit-seal pin's input.
/// </summary>
[Fact]
public void ClipViewSlicePlanes_PunchFanPath_EqualsCpuViewPolygonEdgePlanes_ForASyntheticView()
{
const float ViewportWidth = 640f, ViewportHeight = 480f;
Vector2[] verts =
[
new(0f, 0.6f), new(-0.6f, -0.4f), new(0.5f, -0.5f), new(0.7f, 0.2f),
];
// Pixel-space points (origin top-left, +Y down) that ReassembleOutsideViewFromWalk's
// own inverse transform (px = (ndc+1)*W/2, py = (1-ndc)*H/2) maps back to `verts`.
var pixelPoints = new WalkScreenPoint[verts.Length];
for (int i = 0; i < verts.Length; i++)
{
float px = (verts[i].X + 1f) * ViewportWidth / 2f;
float py = (1f - verts[i].Y) * ViewportHeight / 2f;
pixelPoints[i] = new WalkScreenPoint(px, py, 0f, 1f);
}
var walkView = new WalkPortalView();
Assert.True(WalkCopyView.Append(
walkView, pixelPoints, new SyntheticRayCaster(), Vector3.Zero));
// The EXACT production pair: BeginWalkFrame seeds an interior root's
// empty outside-view assembly; ReassembleOutsideViewFromWalk (the
// walk's real producer) fills it from the walk's own pixel-space
// view — the same two calls RetailPViewPassExecutor.cs and
// RetailPViewRenderer.cs make.
ClipFrameAssembly assembly = ClipFrameAssembler.BeginWalkFrame(
ClipFrame.NoClip(), outdoorRoot: false);
ClipFrameAssembler.ReassembleOutsideViewFromWalk(
assembly, walkView, ViewportWidth, ViewportHeight);
ClipViewSlice slice = Assert.Single(assembly.OutsideViewSlices);
Assert.True(slice.Planes.Length >= 3);
AssertEveryEdgeMidpointLiesOnSomeGpuPlane(verts, slice.Planes);
}
/// <summary>Trivial ray caster: only <c>WalkPortalView</c>'s stored pixel
/// points feed <see cref="ClipFrameAssembler.ReassembleOutsideViewFromWalk"/>
/// (via NDC conversion); the per-vertex plane a ray caster would seed is
/// unused by that path, so any non-degenerate direction works.</summary>
private sealed class SyntheticRayCaster : IWalkRayCaster
{
public Vector3 RayThrough(float screenX, float screenY) =>
Vector3.Normalize(new Vector3(screenX, screenY, 1000f));
}
/// <summary>
/// CPU/GPU equivalence: a point on a convex polygon's edge must sit
/// (a) non-negative under EVERY plane (still inside-or-on the region —
/// no plane clips it away) and (b) within <paramref name="verts"/>'s
/// own floating-point tolerance of ZERO under at least one plane (that
/// edge's own plane). MUTATION: perturbing any one GPU plane's offset
/// or normal after it left <see cref="ClipPlaneSet.From(CellView)"/>
/// (a packing/binding bug) breaks either (a) for a nearby edge or (b)
/// for its own edge, failing the corresponding assertion below.
/// </summary>
private static void AssertEveryEdgeMidpointLiesOnSomeGpuPlane(
Vector2[] verts, ReadOnlySpan<Vector4> gpuPlanes)
{
const float eps = 1e-4f;
for (int i = 0; i < verts.Length; i++)
{
Vector2 a = verts[i];
Vector2 b = verts[(i + 1) % verts.Length];
Vector2 mid = (a + b) / 2f;
var clip = new Vector4(mid.X, mid.Y, 0f, 1f);
float minAbsDistance = float.PositiveInfinity;
foreach (Vector4 plane in gpuPlanes)
{
float distance = Vector4.Dot(plane, clip);
Assert.True(
distance >= -eps,
$"edge {i} midpoint ({mid.X},{mid.Y}) must be inside-or-on every "
+ $"GPU plane; plane {plane} gave distance {distance}");
minAbsDistance = MathF.Min(minAbsDistance, MathF.Abs(distance));
}
Assert.True(
minAbsDistance < eps,
$"edge {i} midpoint ({mid.X},{mid.Y}) should lie ~on its OWN GPU plane; "
+ $"the closest plane was only {minAbsDistance} away");
}
}
}