acdream/tests/AcDream.App.Tests/Rendering/WalkOutsideViewReassemblyTests.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

411 lines
18 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Linq;
using System.Numerics;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Rendering.Gpu.Vk;
using AcDream.App.Rendering.Walk;
using AcDream.App.Tests.Rendering.Gpu;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Campaign FW4 slice 1 — <see cref="ClipFrameAssembler.ReassembleOutsideViewFromWalk"/>:
/// an interior root's outside-view slices come from the walk's OWN
/// <c>outside_view</c> (pixel screen points, origin top-left, +Y down),
/// converted to the assembler's standard-NDC <see cref="ViewPolygon"/>s.
/// </summary>
public class WalkOutsideViewReassemblyTests
{
private const float W = 1024f, H = 720f;
private sealed class StubRays : IWalkRayCaster
{
public Vector3 RayThrough(float screenX, float screenY) =>
Vector3.Normalize(new Vector3(screenX - W / 2f, screenY - H / 2f, 1000f));
}
private static WalkPortalView WalkViewOfPixelQuads(params Vector2[][] pixelQuads)
{
var view = new WalkPortalView();
var rays = new StubRays();
foreach (Vector2[] quad in pixelQuads)
{
var pts = new WalkScreenPoint[quad.Length];
for (int i = 0; i < quad.Length; i++)
pts[i] = new WalkScreenPoint(quad[i].X, quad[i].Y, 0f, 1f);
Assert.True(WalkCopyView.Append(view, pts, rays, Vector3.Zero));
}
return view;
}
private static ClipFrameAssembly AssembledWithOldOutside()
{
var pv = new PortalVisibilityFrame();
pv.OutsideView.Add(new ViewPolygon(new[]
{
new Vector2(-0.9f, -0.9f), new Vector2(0.9f, -0.9f),
new Vector2(0.9f, 0.9f), new Vector2(-0.9f, 0.9f),
}));
return ClipFrameAssembler.Assemble(ClipFrame.NoClip(), pv);
}
[Fact]
public void PixelDoorway_MapsToExpectedNdcAabbAndPlanes()
{
ClipFrameAssembly asm = AssembledWithOldOutside();
// Pixel quad x∈[256,512], y∈[180,360] → NDC x∈[-0.5,0], y∈[0,0.5]
// (yNdc = 1 2·py/H flips the axis: py=180 → +0.5, py=360 → 0).
WalkPortalView walkView = WalkViewOfPixelQuads(new[]
{
new Vector2(256f, 180f), new Vector2(512f, 180f),
new Vector2(512f, 360f), new Vector2(256f, 360f),
});
ClipFrameAssembler.ReassembleOutsideViewFromWalk(asm, walkView, W, H);
ClipViewSlice slice = Assert.Single(asm.OutsideViewSlices);
Assert.True(asm.OutdoorVisible);
Assert.Equal(4, asm.OutsidePlaneCount);
Assert.Equal(slice.Slot, asm.OutdoorSlot);
Assert.NotEqual(0, slice.Slot);
Assert.Equal(-0.5f, slice.NdcAabb.X, 3);
Assert.Equal(0f, slice.NdcAabb.Y, 3);
Assert.Equal(0f, slice.NdcAabb.Z, 3);
Assert.Equal(0.5f, slice.NdcAabb.W, 3);
Assert.Equal(slice.NdcAabb, asm.OutsideViewNdcAabb);
// Every corner of the doorway satisfies every inward plane
// (n·p + d >= 0), and a point far outside fails at least one.
Vector2[] ndcCorners =
{
new(-0.5f, 0f), new(0f, 0f), new(0f, 0.5f), new(-0.5f, 0.5f),
};
foreach (Vector2 corner in ndcCorners)
{
foreach (Vector4 plane in slice.Planes)
Assert.True(plane.X * corner.X + plane.Y * corner.Y + plane.W >= -1e-4f);
}
bool outsideFails = false;
foreach (Vector4 plane in slice.Planes)
outsideFails |= plane.X * 0.9f + plane.Y * -0.9f + plane.W < 0f;
Assert.True(outsideFails);
}
[Fact]
public void FullViewportWalkQuad_CoversFullNdc()
{
ClipFrameAssembly asm = AssembledWithOldOutside();
var walkView = new WalkPortalView();
Assert.True(WalkCopyView.AppendFullViewportQuad(
walkView, new StubRays(), Vector3.Zero, W, H));
ClipFrameAssembler.ReassembleOutsideViewFromWalk(asm, walkView, W, H);
ClipViewSlice slice = Assert.Single(asm.OutsideViewSlices);
Assert.Equal(new Vector4(-1f, -1f, 1f, 1f), slice.NdcAabb);
}
[Fact]
public void EmptyWalkView_YieldsSkipMode()
{
ClipFrameAssembly asm = AssembledWithOldOutside();
Assert.True(asm.OutdoorVisible); // the old view was visible pre-cutover
ClipFrameAssembler.ReassembleOutsideViewFromWalk(asm, new WalkPortalView(), W, H);
Assert.Empty(asm.OutsideViewSlices);
Assert.False(asm.OutdoorVisible);
Assert.False(asm.HasOutsideView);
Assert.Equal(0, asm.OutsidePlaneCount);
Assert.Equal(0, asm.OutdoorSlot);
}
/// <summary>
/// S3 review fix round 1 (F1, BLOCKING): a two-view walk whose FIRST
/// polygon collapses (all three points exactly collinear — zero area,
/// well under <c>ClipPlaneSet</c>'s <c>MinPolygonArea</c>) must still
/// produce a length-2 slice array, index-aligned with the walk's own
/// view count: slice[0] is the collapsed view (flagged
/// <see cref="ClipViewSlice.NothingVisible"/>), slice[1] is the SECOND
/// polygon's real edge planes — not the (nonexistent) first view's, and
/// not shifted down by one. Constructs the <see cref="WalkPortalView"/>
/// directly (bypassing <see cref="WalkCopyView.Append"/>'s own pixel-
/// space collinearity filter, which is not the same test as
/// <c>ClipPlaneSet</c>'s NDC-area gate) so the collapse is exact and
/// deterministic.
/// </summary>
[Fact]
public void FirstViewCollapses_SecondSurvives_SlicesStayIndexAligned()
{
ClipFrameAssembly asm = AssembledWithOldOutside();
var walkView = new WalkPortalView();
// View 0: three EXACTLY collinear pixel points -> zero-area triangle,
// collinear before and after the affine pixel->NDC transform.
walkView.View.Vertices.Add(new WalkViewVertex { Point = new Vector2(100f, 100f) });
walkView.View.Vertices.Add(new WalkViewVertex { Point = new Vector2(200f, 100f) });
walkView.View.Vertices.Add(new WalkViewVertex { Point = new Vector2(300f, 100f) });
walkView.View.Polys.Add(new WalkViewPoly(3, 0, 100f, 300f, 100f, 100f));
// View 1: a normal quad.
int secondBase = walkView.View.Vertices.Count;
Vector2[] secondQuad =
[
new(600f, 400f), new(900f, 400f), new(900f, 650f), new(600f, 650f),
];
foreach (Vector2 pixel in secondQuad)
walkView.View.Vertices.Add(new WalkViewVertex { Point = pixel });
walkView.View.Polys.Add(new WalkViewPoly(4, secondBase, 600f, 900f, 400f, 650f));
walkView.ViewCount = 2;
ClipFrameAssembler.ReassembleOutsideViewFromWalk(asm, walkView, W, H);
Assert.Equal(2, asm.OutsideViewSlices.Length);
ClipViewSlice collapsed = asm.OutsideViewSlices[0];
Assert.True(collapsed.NothingVisible);
Assert.Equal(0, collapsed.Slot);
Assert.Empty(collapsed.Planes);
Assert.Equal(default, collapsed.NdcAabb);
ClipViewSlice survivor = asm.OutsideViewSlices[1];
Assert.False(survivor.NothingVisible);
// The second polygon's own edge planes, converted from pixel space
// (px=600..900, py=400..650) into the assembler's standard NDC.
var expectedNdcVerts = new Vector2[secondQuad.Length];
for (int i = 0; i < secondQuad.Length; i++)
{
expectedNdcVerts[i] = new Vector2(
secondQuad[i].X / W * 2f - 1f,
1f - secondQuad[i].Y / H * 2f);
}
AssertEveryEdgeMidpointLiesOnSomeGpuPlane(expectedNdcVerts, survivor.Planes);
}
/// <summary>
/// F1's punch-leaf half: <c>RetailPViewPassExecutor.DrawWalkPunchFan</c>
/// reading the SAME index-aligned array produced above. Uses a recording
/// <see cref="RecordingGpuDevice"/> surface so the assertion inspects the
/// actual GPU submission (or its absence), not just the CPU slice.
/// activeViewIndex=1 (the survivor) submits a fan with the survivor's
/// planes; activeViewIndex=0 (the collapsed view) submits NOTHING;
/// activeViewIndex=2 (out of range) throws (fail-loud rule).
/// </summary>
[Fact]
public void PunchLeaf_UsesIndexAlignedSlice_DrawsNothingForCollapsed_ThrowsOutOfRange()
{
ClipFrameAssembly asm = AssembledWithOldOutside();
var walkView = new WalkPortalView();
walkView.View.Vertices.Add(new WalkViewVertex { Point = new Vector2(100f, 100f) });
walkView.View.Vertices.Add(new WalkViewVertex { Point = new Vector2(200f, 100f) });
walkView.View.Vertices.Add(new WalkViewVertex { Point = new Vector2(300f, 100f) });
walkView.View.Polys.Add(new WalkViewPoly(3, 0, 100f, 300f, 100f, 100f));
int secondBase = walkView.View.Vertices.Count;
Vector2[] secondQuad =
[
new(600f, 400f), new(900f, 400f), new(900f, 650f), new(600f, 650f),
];
foreach (Vector2 pixel in secondQuad)
walkView.View.Vertices.Add(new WalkViewVertex { Point = pixel });
walkView.View.Polys.Add(new WalkViewPoly(4, secondBase, 600f, 900f, 400f, 650f));
walkView.ViewCount = 2;
ClipFrameAssembler.ReassembleOutsideViewFromWalk(asm, walkView, W, H);
Assert.Equal(2, asm.OutsideViewSlices.Length);
using var device = new RecordingGpuDevice();
var frames = new GpuDeviceFrameLifetime(device);
var scope = new VulkanWorldPassScope(sampleCount: 1);
using var portalDepthMask = new PortalDepthMaskRenderer(device, frames, scope);
// DrawWalkPunchFan only reads _portalDepthMask, worldPolygon.Vertices,
// clipAssembly.OutsideViewSlices, and frame.ViewProjection — a bare
// (constructor-bypassed) executor with only that one field set
// exercises the real leaf without needing a full GL/DAT renderer
// graph. Same GetUninitializedObject pattern WorldRenderCompositionTests
// already uses for stubbing App-layer types.
var executor = (RetailPViewPassExecutor)System.Runtime.CompilerServices.RuntimeHelpers
.GetUninitializedObject(typeof(RetailPViewPassExecutor));
typeof(RetailPViewPassExecutor)
.GetField("_portalDepthMask", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
.SetValue(executor, portalDepthMask);
var worldPolygon = new WalkPolygon
{
Vertices = new[]
{
new Vector3(-1f, -1f, 0f), new Vector3(1f, -1f, 0f), new Vector3(0f, 1f, 0f),
},
};
RetailPViewFrameInput frame = new RetailPViewFrameInput().Reset(
rootCell: null!,
nearbyBuildingCells: null,
viewerEyePos: Vector3.Zero,
viewProjection: Matrix4x4.Identity,
cells: null!,
camera: null!,
cameraWorldPosition: Vector3.Zero,
frustum: null,
playerLandblockId: null,
animatedEntityIds: null,
renderCenterLbX: 0,
renderCenterLbY: 0,
renderRadius: 0,
landblockEntries: Array.Empty<(uint, Vector3, Vector3, IReadOnlyList<AcDream.Core.World.WorldEntity>, IReadOnlyDictionary<uint, AcDream.Core.World.WorldEntity>?)>(),
renderSky: false,
renderWeather: false,
dayFraction: 0f,
activeDayGroup: null,
skyKeyframe: default,
environOverrideActive: false,
viewerCellId: 0,
playerCellId: 0,
playerViewPosition: Vector3.Zero,
cameraView: Matrix4x4.Identity,
cameraCellResolution: default);
void RunDraw(int activeViewIndex)
{
frames.BeginFrame();
portalDepthMask.BeginFrame(frameSlot: 0);
using (IGpuPassEncoder pass = frames.CurrentFrame!.BeginPass(
GpuPassDescription.BackbufferClear(
"s3-f1-punch-leaf", Vector4.Zero, sampleCount: 1)))
using (scope.Publish(pass))
{
executor.DrawWalkPunchFan(frame, asm, worldPolygon, activeViewIndex);
}
frames.EndFrame();
}
// activeViewIndex = 0: the collapsed view. Draws nothing.
int drawsBefore = device.Calls.OfType<GpuRecordedDraw>().Count();
RunDraw(0);
int drawsAfterCollapsed = device.Calls.OfType<GpuRecordedDraw>().Count();
Assert.Equal(drawsBefore, drawsAfterCollapsed);
// activeViewIndex = 1: the surviving view. Submits exactly one fan draw.
RunDraw(1);
int drawsAfterSurvivor = device.Calls.OfType<GpuRecordedDraw>().Count();
Assert.Equal(drawsAfterCollapsed + 1, drawsAfterSurvivor);
// activeViewIndex = 2: out of range. Fails loud instead of drawing unclipped.
var ex = Assert.Throws<ArgumentOutOfRangeException>(() =>
{
frames.BeginFrame();
portalDepthMask.BeginFrame(frameSlot: 0);
using (IGpuPassEncoder pass = frames.CurrentFrame!.BeginPass(
GpuPassDescription.BackbufferClear(
"s3-f1-punch-leaf-oob", Vector4.Zero, sampleCount: 1)))
using (scope.Publish(pass))
{
executor.DrawWalkPunchFan(frame, asm, worldPolygon, 2);
}
});
Assert.Contains("activeViewIndex", ex.Message);
}
/// <summary>Same CPU/GPU equivalence check as
/// <c>ClipFrameLayoutTests.AssertEveryEdgeMidpointLiesOnSomeGpuPlane</c>
/// (private there, duplicated here): every edge midpoint of the source
/// NDC polygon must be non-negative under every plane and ~zero under at
/// least one (its own edge's plane).</summary>
private static void AssertEveryEdgeMidpointLiesOnSomeGpuPlane(
Vector2[] verts, System.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");
}
}
/// <summary>
/// S3 review fix round 1 (F2): the outside-view sibling of
/// <c>WalkFrameDriverClipSealTests.ExitSealPath_NineVertexView_...</c> —
/// a 9-vertex outside view is too complex for the &lt;=8-plane budget
/// (<see cref="ClipPlaneSet.IsPlaneOverflow"/>), but unlike the exit-seal
/// path (which falls back to a conservative 4-plane AABB) the outside
/// view/punch-fan path has NO scissor consumer at all (S3 chunk 4 fix
/// round 2, L2) — it draws fully UNCLIPPED: <see cref="ClipViewSlice.Slot"/>
/// stays 0 with an EMPTY <see cref="ClipViewSlice.Planes"/> array, and
/// critically <see cref="ClipViewSlice.NothingVisible"/> is FALSE — this
/// is the "draw unclipped" state F1 distinguishes from the "draw
/// nothing" collapsed-view state.
/// </summary>
[Fact]
public void NineVertexOutsideView_PunchSliceHasZeroPlanes_DrawsUnclipped_NotNothingVisible()
{
ClipFrameAssembly asm = AssembledWithOldOutside();
const int n = 9;
var verts = new Vector2[n];
for (int i = 0; i < n; i++)
{
float angle = i * MathF.Tau / n;
verts[i] = new Vector2(0.6f * MathF.Cos(angle), 0.6f * MathF.Sin(angle));
}
var pixelPoints = new WalkScreenPoint[n];
for (int i = 0; i < n; i++)
{
pixelPoints[i] = new WalkScreenPoint(
(verts[i].X + 1f) * W / 2f, (1f - verts[i].Y) * H / 2f, 0f, 1f);
}
var walkView = new WalkPortalView();
Assert.True(WalkCopyView.Append(walkView, pixelPoints, new StubRays(), Vector3.Zero));
// No collinear-merge stole a vertex.
Assert.Equal(n, walkView.View.Polys[0].VertexCount);
ClipFrameAssembler.ReassembleOutsideViewFromWalk(asm, walkView, W, H);
ClipViewSlice slice = Assert.Single(asm.OutsideViewSlices);
Assert.False(slice.NothingVisible);
Assert.Equal(0, slice.Slot);
Assert.Empty(slice.Planes);
}
[Fact]
public void TwoWalkViews_ProduceTwoSlicesWithDistinctSlots()
{
ClipFrameAssembly asm = AssembledWithOldOutside();
WalkPortalView walkView = WalkViewOfPixelQuads(
new[]
{
new Vector2(100f, 100f), new Vector2(300f, 100f),
new Vector2(300f, 300f), new Vector2(100f, 300f),
},
new[]
{
new Vector2(600f, 400f), new Vector2(900f, 400f),
new Vector2(900f, 650f), new Vector2(600f, 650f),
});
ClipFrameAssembler.ReassembleOutsideViewFromWalk(asm, walkView, W, H);
Assert.Equal(2, asm.OutsideViewSlices.Length);
Assert.NotEqual(asm.OutsideViewSlices[0].Slot, asm.OutsideViewSlices[1].Slot);
// The union AABB spans both doorways.
Assert.True(asm.OutsideViewNdcAabb.X < asm.OutsideViewSlices[0].NdcAabb.Z);
Assert.True(asm.OutsideViewNdcAabb.Z >= asm.OutsideViewSlices[1].NdcAabb.X);
}
}