fix(render): S3 chunk 4 round 2 — draw-gate condition pinned, scissor and terrain-clip stacks deleted, one outside-view slice constructor

Round-1 three-lens FAIL at d60ca4ea0 found: the K2 fix was right in
production but nothing pinned the draw side (restoring the pre-fix gate
left every lane green); a stale "still ends an active scissor" comment
asserted a mechanism the same round had already deleted; the sky.vert
comment claimed retail clips the sky when it draws unclipped; the K6
pin ran through ClipFrameAssembler.Assemble, which has zero production
callers, so it proved nothing about the producer that actually runs.
This round closes L1-L9.

L1 (BLOCKING) — draw-side weather-gate pin. Added
RetailPViewPassExecutorTests.DrawLandscapeDynamicsPhase_GatesDrawWeatherOnceOnWalkDriverWeatherTurnFired:
reads DrawLandscapeDynamicsPhase's compiled call graph and asserts (a)
the call immediately before DrawWeatherOnce is
WalkFrameDriver.get_WeatherTurnFired and (b) exactly one
brfalse/brfalse.s branch sits between that call and the draw, jumping
forward past it. Three mutations, each shown failing:

  M1 (restore `if (clipAssembly.OutsideViewSlices.Length != 0)`):
    Assert.Equal() Failure: Values differ
    Expected: typeof(AcDream.App.Rendering.Walk.WalkFrameDriver)
    Actual:   typeof(AcDream.App.Rendering.ClipFrameAssembly)

  M2 (drop the gate, unconditional call):
    Assert.Equal() Failure: Values differ
    Expected: typeof(AcDream.App.Rendering.Walk.WalkFrameDriver)
    Actual:   typeof(AcDream.App.Rendering.RetailPViewPassExecutor)

  M3 (invert to `if (!walkDriver.WeatherTurnFired)`):
    Assert.Single() Failure: The collection did not contain any matching items
    Expected:   (predicate expression)
    Collection: [CompiledBranch { Offset = 7, OpCode = brfalse.s, TargetOffset = 17 }, CompiledBranch { Offset = 24, OpCode = brtrue.s, TargetOffset = 33 }]

Corrected WalkFrameDriverTranscriptTests.cs's doc comment (the
Collect_WeatherTurnFiredMatchesThePrintedOcLineExactly block): it pins
the print half and the flag only, and now names the real draw-side pin
instead of falsely claiming to double as one.

L2 (MAJOR) — scissor stack deleted, K4 comment corrected. Deleted
IWorldPassSurface.BeginScissor/EndScissor and their RhiWorldPassSurface
bodies, the scissor call inside ClearInteriorDepth, NdcScissorRect.cs +
NdcScissorRectTests.cs (BeginScissor had zero remaining callers, and
RhiWorldPassSurface.BeginScissor was NdcScissorRect.ToPixels' only
production caller). This left RhiWorldPassSurface's 4th constructor
parameter (IRetailPViewFramebufferSource) and RetailPViewPassExecutor.cs's
RetailPViewFramebufferSize/IRetailPViewFramebufferSource/
SilkRetailPViewFramebufferSource types entirely dead (framebuffer size
was needed only for the scissor's NDC-to-pixel conversion) — removed
them and their one call site in FrameRootComposition.cs. Rewrote
RetailPViewPassExecutor.cs's K4 comment: it no longer asserts a live
scissor mechanism; it states that VulkanGpuPassEncoder's constructor
sets the full-attachment scissor once, at pass begin
(VulkanGpuPassEncoder.cs:87), and nothing narrows it after that. KEPT
per the round-1 verdict: ScissorFallbacks, OutsidePlaneCount,
OutsideViewNdcAabb, HasOutsideView, OutdoorVisible, OutdoorSlot,
ClipViewSlice.NdcAabb (the >8-edge zero-plane slice case the punch fans
still consume) and the VulkanViewportMapping.ScissorToVulkan pass-begin
path (IGpuPassEncoder.SetScissor stays). Also deleted
ClipFrameAssembly.TerrainMode/TerrainScissorNdcAabb and their writers
in ClipFrameAssembler.cs (both Assemble and ReassembleOutsideViewFromWalk);
OutsidePlaneCount's formula reduces to `outsideHasScissorFallback ? 0 :
outsideMaxPlaneCount` without needing the deleted TerrainClipMode
comparison (a scissor-fallback slice can only exist when outdoorVisible
is already true, so the three original cases collapse identically).
Deleted the two "terrain=" / "outMode=" diagnostic reads in
WorldRenderDiagnostics.cs (:345, :409) and the now-vestigial
EmitClipRouteProbe "ubo: n=..." segment that read ClipFrame's deleted
terrain bytes.

DEVIATION from L2's literal text: kept the TerrainClipMode enum type
itself — WorldSceneRenderer.cs's flat-world safety path (explicitly
"out of this chunk's scope" per K4's own round-1 comment) still uses it
for an unrelated "did the flat terrain draw" diagnostic flag, with its
own WorldSceneDiagnosticsController/WorldRenderDiagnostics/test
consumers. Deleting the type would require rewriting files outside
every round's declared file list. Reworded its doc comment to state
this plainly.

L3 (MAJOR, completes K3) — dead TerrainClip UBO deleted from the sky
and terrain shaders. Deleted the block, both gl_ClipDistance loops, and
the gl_PerVertex redeclaration (nothing else needs it) from sky.vert,
terrain_modern.vert, terrain_atmospheric.vert. Recompiled via
tools/compile-shaders.ps1 (glslc via the Vulkan SDK, managed shaderc
fallback also runs) — 24/24 pairs compiled; only sky.vert.spv,
terrain_atmospheric.vert.spv and terrain_modern.vert.spv changed.
Re-pinned VulkanShaderManifestTests.cs's frozen retail-oracle hashes
for sky.vert.spv (7d67a9e3624d198b370d402b5c12e4ce925bf9b8e646ef5123636a86d5985ab5)
and terrain_modern.vert.spv (8a73d89ef0e51e550327b9ff8c24857e309103b1d491030cf0d4d8594b45068c)
with dated comments, matching the existing re-pin convention.

Deleted WorldFrameSectionBinding.BindTerrainClip and
WorldFrameSections.TerrainClip (+ its Reset) with its two callers
(SkyRenderer.Rhi.cs:258, TerrainModernRenderer.Rhi.cs:259). DEVIATION
from L3's literal text: kept the shared Zeroed(...) helper in
WorldPassScope.cs — it is also called by BindSceneLighting and
BindClipRegions, both of which stay; deleting it would have broken
those two live bindings. Deleted IWorldPassSurface.BindTerrainClip
(no-op interface method + RhiWorldPassSurface body) and
WorldScenePassExecutor.cs's two calls to it (:121, :235).

Deleted ClipFrame's _terrainBytes field, TerrainBytes/TerrainBytesForTest
properties, Reset's Array.Clear(_terrainBytes), and the stale
header/K3 comment paragraphs. DEVIATION from L3's literal text: kept
ClipFrame.TerrainUboBytes and ClipFrame.TerrainClipUboBinding —
PortalDepthMaskRenderer.Rhi.cs (:140, :187) is a live production
consumer of both constants for the KEPT exit-seal/punch-fan clip block,
which was never in scope for deletion (portal_depth.vert's own
TerrainClip UBO declaration is the KEEP block, untouched). Reworded
both constants' doc comments (ClipFrame.cs, VulkanPipelineLayouts.cs's
UniformTerrainClip) to say only the portal-depth clip block uses
binding 2 now, and corrected the two GpuBindingModel.cs comments that
explained why terrain-tiling/sky-params bindings are 3/4 by naming "the
terrain clip block". Updated VulkanShaderDescriptorContractTests.cs's
TerrainVertexShaderDeclaresItsClipBlockInTheUniformSet (renamed
TerrainVertexShaderDeclaresOnlySceneLightingInTheUniformSet):
terrain_modern.vert's uniform set is now {SceneLighting} only. Deleted
ClipFrameLayoutTests.NoClip_TerrainBytes_Count0_AllZeros and its K3
comment; corrected the class doc comment and LayoutConstants_MatchShaderStruct's
"terrain UBO"/binding-contract comments to describe the portal-depth
consumer instead.

REQUIRED L3 fact (declared-but-never-bound dynamic uniform binding):
VulkanFrameBindings's constructor seeds EVERY declared uniform binding
(0..UniformBindingCount-1, including binding 2) with the shared dummy
buffer's range before any renderer runs (VulkanFrameBindings.cs:128-130,
`_arena.SeedUniform(binding, dummy.Handle.Handle, dummyUniformRange)`
in a loop over every binding) — "Every binding is always bound, whether
a renderer uses it or not... unused ones point at a shared dummy range"
(VulkanFrameBindings.cs:27-31). So after this round, when the sky or
terrain pipeline draws, set 1's shared descriptor layout still declares
binding 2 (portal_depth.vert's own declaration keeps
IsDeclaredUniformBinding(2) true), and its descriptor still points at a
valid (dummy) range from that seed — vkCmdBindDescriptorSets stays
legal even though neither shader statically uses binding 2 any more.
No SPIR-V-side change was needed to keep this legal.

L4 (MAJOR) — one outside-view slice constructor. Extracted
ClipFrameAssembler.AppendOutsideSlice (frame, ViewPolygon,
outsideSlicesList, ref maxPlaneCount, ref hasScissorFallback, ref
scissorFallbacks) — the exact ClipPlaneSet.From/AppendSlot/
ClipViewSlice-construction body — and call it from both Assemble's
outside_view loop and ReassembleOutsideViewFromWalk's outside_view
loop. Rewrote ClipFrameLayoutTests's K6 pin
(ClipViewSlicePlanes_PunchFanPath_EqualsCpuViewPolygonEdgePlanes_ForASyntheticView):
builds a synthetic WalkPortalView from pixel-space points (the
WalkCopyViewTests pattern) via a trivial IWalkRayCaster, runs
BeginWalkFrame(frame, outdoorRoot: false) then
ReassembleOutsideViewFromWalk(assembly, walkView, 640, 480), and reads
assembly.OutsideViewSlices[0].Planes — the exact production pair
RetailPViewPassExecutor.cs's BeginWalkFrame call and
RetailPViewRenderer.cs's ReassembleOutsideViewFromWalk call make.
Mutation (perturbed planes[0].W inside the shared helper, right after
`planes = cps.PlaneArray;`):

  edge 0 midpoint (-0.3,0.10000001) should lie ~on its OWN GPU plane; the closest plane was only 0.5251073 away

The pin's own source contains no `Assemble(` call — grep-checked by
extracting the method body and searching it for the literal text; no
match.

L5 — shader comments corrected. sky.vert/terrain_modern.vert/
terrain_atmospheric.vert now state retail draws the sky once
(LScape::draw @0x00506330 -> GameSky::Draw(sky,0) @0x0050633c, before
draw_check_blocks) and the landscape is view-culled per cell, never
GPU-clipped (RenderDeviceD3D::DrawBlock @0x005a17c0). The "Phase W
Stage 4"/"U.3 default" clip narratives are deleted along with the
blocks they described.

L6 — grep sweep. `grep -rn "<token>" src tests docs/architecture`
returns nothing for SetTerrainClip, BeginDoorwayScissor,
BindTerrainClip, TerrainBytes, "active scissor", and NdcScissorRect —
confirmed after this commit (docs/plans and docs/research keep the
historical record, untouched). TerrainClipMode is the one deliberate
exception (see the L2 deviation note above); every one of its 9
remaining hits is a live, non-stale reference (the enum declaration,
WorldSceneRenderer's flat-path local, or their diagnostic/test
plumbing), not a stale mention of a deleted mechanism.

L7 — Issue130DoorwayStripTests. Deleted AnySliceAdmitsScissor,
worstScissorGapPx and its PIN 1 assertion, the header's scissor
sentences, and the scissorGap half of MeasureTopEdgeGap (dropped the
fbW parameter it alone needed). Rewrote the header: the scissor
mechanism is retired (the sky and landscape draw unclipped; aperture
exactness comes from the depth clear, the exit seals and the interior
repaint). The remaining plane-gap half (the canary PIN,
`worstPlaneGapPx <= 1.2f`) still pins something production reads:
AnySliceAdmitsPlanes walks slice.Planes from the SAME ProjectToClip ->
ClipToRegion -> ClipPlaneSet.From pipeline
RetailPViewPassExecutor.DrawWalkPunchFan reads through
clipAssembly.OutsideViewSlices[activeViewIndex].Planes — so the test
was kept, not deleted.

L8 — DrawWalkSky loop-shape pin. Added
DrawWalkSky_RenderSkyCallSiteHasNoEnclosingBackwardBranch (same
backward-branch-span shape as K1's DrawWeatherOnce pin), plus a note in
both pins that CompiledCallGraph.ReadBranches does not decode a
compiled switch jump table, but no C# loop construct compiles to one.
Mutation (wrapped the RenderSky call in `for (int i = 0; i < 2; i++)`):

  Assert.DoesNotContain() Failure: Filter matched in collection
  Collection: [..., CompiledBranch { Offset = 20, OpCode = brtrue.s, TargetOffset = 25 }, CompiledBranch { Offset = 23, OpCode = br.s, TargetOffset = 66 }, CompiledBranch { Offset = 72, OpCode = blt.s, TargetOffset = 13 }, CompiledBranch { Offset = 80, OpCode = brfalse.s, TargetOffset = 116 }, CompiledBranch { Offset = 88, OpCode = brfalse.s, TargetOffset = 116 }]

(the Offset=72 -> TargetOffset=13 entry is the injected loop's backward
branch spanning the call).

L9 — this message.

Gates: dotnet build 0 warnings / 0 errors. Hermetic filter
(Lane!=InstalledDat&...&Status!=KnownFailure): 6827 passed, 0 failed.
InstalledDat lane against a real DAT directory: 244 passed, 4 failed —
exactly the four known failures (LayoutImporterMediaBearingChildSweepTests
+ LayoutImporterInvisibleSweepTests, both #383; TowerAscentReplayTests,
KnownFailure; WalkTraceConformanceTests.Oh_doorway_still_first_frame_diff,
#458 KnownFailure). No register row added (every deletion here removes
an acdream-only rule; the KEEP items already had their equivalence
pins from round 1). No new flag/probe.

OWED: the lead's ACDREAM_DEVTOOLS=1 four-pose visual self-gate against
the running client is not run by this agent — CLAUDE.md and this
task's own instructions forbid launching the graphical client from
here; that visual/validation-layer pass remains the user's to run
before this round is accepted.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-09-03 15:11:21 +02:00
parent ff607a1e04
commit 7df0b94c9f
32 changed files with 832 additions and 991 deletions

View file

@ -368,15 +368,12 @@ internal sealed class FrameRootCompositionPhase
d.RenderDiagnosticLog);
IRenderFrameGlState worldFrameGlState = NullRenderFrameGlState.Instance;
IWorldPassScope? worldPassScope = d.Graphics.WorldPassScope;
var worldFramebufferSource =
new SilkRetailPViewFramebufferSource(d.Window);
IWorldPassSurface worldPassSurface = new RhiWorldPassSurface(
worldPassScope
?? throw new InvalidOperationException(
"The graphics backend must publish a world pass scope."),
host.GpuFrameLifetime,
live.ClipFrame,
worldFramebufferSource);
live.ClipFrame);
var worldFrameEnvironment =
new RuntimeWorldFrameEnvironmentPreparation(
d.Options,

View file

@ -1,39 +1,38 @@
// ClipFrame.cs
//
// Phase U.3: the per-frame container for the SHARED per-frame clip data
// consumed by mesh_modern.vert (SSBO binding=2) and terrain_modern.vert (UBO
// binding=2). This is the "shared" half of the U.3 clip mechanism; the
// per-instance slot index buffer (SSBO binding=3) is PER-RENDERER and owned by
// each renderer (WbDrawDispatcher / EnvCellRenderer), parallel to its instance
// buffer — it is NOT here.
// Phase U.3: the per-frame container for the mesh SSBO clip-region table
// (binding=2) that mesh_modern.vert reads. The per-instance slot index
// buffer (SSBO binding=3) is PER-RENDERER and owned by each renderer
// (WbDrawDispatcher / EnvCellRenderer), parallel to its instance buffer —
// it is NOT here.
//
// === The contract (both shader sides obey) ===================================
// === The contract (the shader side obeys) =====================================
// binding=2 mesh SSBO holds an array of CellClip, one per "slot":
// struct CellClip { uint count; uint _p0; uint _p1; uint _p2; vec4 planes[8]; };
// std430 layout: count at byte 0, three pad uints at 4/8/12, planes[8] at 16
// (vec4 stride 16) → 144 bytes per slot. Slot 0 is RESERVED = no-clip (count 0).
// binding=2 terrain UBO holds the single OutsideView region:
// layout(std140) { int uTerrainClipCount; vec4 uTerrainClipPlanes[8]; };
// std140 layout: count at byte 0 (padded to 16), planes[8] at 16 → 144 bytes.
//
// In U.3 a ClipFrame is built via NoClip(): one slot (slot 0, count 0) and a
// terrain count of 0. Everything renders exactly as before. U.4 populates real
// slots from a PortalVisibilityFrame (one CellClip per visible cell) and sets the
// terrain OutsideView planes, then points each renderer's per-instance slot
// buffer at the right slots.
// In U.3 a ClipFrame is built via NoClip(): one slot (slot 0, count 0).
// Everything renders exactly as before. U.4 populates real slots from a
// PortalVisibilityFrame (one CellClip per visible cell), then points each
// renderer's per-instance slot buffer at the right slots.
//
// The one CONSUMER outside the mesh path that still reads a slot's packed
// bytes directly is PortalDepthMaskRenderer's exit-seal/punch-fan draw
// (S3 §8/§10 KEEP): it shares the SAME std140 144-byte layout
// (TerrainUboBytes) and binding (TerrainClipUboBinding = 2) the walk's own
// screen-space clip gate used to occupy before S3 chunk 4 fix round 2 (L3)
// deleted that gate outright — the terrain and sky shaders no longer declare
// any block at that binding.
//
// Pure CPU byte-packing. The GL upload machinery this file used to carry
// alongside the packing (a per-flight-slot region SSBO + terrain UBO arena,
// alongside the packing (a per-flight-slot region SSBO arena,
// reservation/upload-once bookkeeping, and their disposal) was deleted at
// Campaign V slice V11: the RHI arm (see RhiWorldPassSurface.PrepareClipFrame
// in WorldPassSurface.cs) reads RegionBytes below and copies it into a frame
// ring allocation instead, so nothing here owns a GPU resource anymore. S3
// chunk 4 fix round 1 (K3) deleted SetTerrainClip (its only writer) — the
// terrain UBO half of PrepareClipFrame's publication is gone with it;
// WorldFrameSectionBinding.BindTerrainClip's existing zeroed-ring fallback
// binds TerrainBytes's permanent all-zero state instead. The byte layout is
// asserted by ClipFrameLayoutTests so a silent std430/std140 drift can't
// reach the GPU.
// ring allocation instead, so nothing here owns a GPU resource anymore. The
// byte layout is asserted by ClipFrameLayoutTests so a silent std430 drift
// can't reach the GPU.
using System;
using System.Numerics;
using System.Runtime.InteropServices;
@ -41,15 +40,15 @@ using System.Runtime.InteropServices;
namespace AcDream.App.Rendering;
/// <summary>
/// Per-frame container for the SHARED clip data: the binding=2 mesh SSBO (one
/// <c>CellClip</c> per slot, slot 0 reserved no-clip) and the binding=2 terrain
/// UBO (the single OutsideView region). See the file header for the exact
/// std430 / std140 byte layout. Per-instance slot buffers (binding=3) are owned by
/// each renderer, not here.
/// Per-frame container for the mesh SSBO clip-region table (binding=2, one
/// <c>CellClip</c> per slot, slot 0 reserved no-clip). See the file header for
/// the exact std430 byte layout and for <see cref="TerrainUboBytes"/>/
/// <see cref="TerrainClipUboBinding"/>'s separate remaining purpose.
/// Per-instance slot buffers (binding=3) are owned by each renderer, not here.
/// </summary>
public sealed class ClipFrame : IDisposable
{
// ---- Layout constants (mirror mesh_modern.vert + terrain_modern.vert) ----
// ---- Layout constants (mirror mesh_modern.vert) ----
/// <summary>Max planes per clip region — matches the shader's <c>planes[8]</c>
/// and GL's guaranteed <c>GL_MAX_CLIP_DISTANCES &gt;= 8</c>.</summary>
@ -63,17 +62,24 @@ public sealed class ClipFrame : IDisposable
/// count + 3 pad uints).</summary>
public const int CellClipPlanesOffset = 16;
/// <summary>std140 size of the terrain UBO block: int count padded to 16, then
/// 8 × 16 (vec4 planes) = 144 bytes. Same number as the SSBO stride by
/// coincidence of the 16-byte vec4 rule, but a DIFFERENT layout family.</summary>
/// <summary>std140 size of <c>PortalDepthMaskRenderer</c>'s exit-seal/punch-fan
/// clip block: int count padded to 16, then 8 × 16 (vec4 planes) = 144
/// bytes. Same number as the mesh SSBO stride by coincidence of the
/// 16-byte vec4 rule, but a DIFFERENT layout family. S3 chunk 4 fix round 2
/// (L3) retired this constant's other former use — the walk's own
/// screen-space clip gate, which terrain_modern.vert and sky.vert used to
/// declare at the same binding before the gate itself was deleted.</summary>
public const int TerrainUboBytes = 16 + MaxPlanes * 16; // 144
/// <summary>UBO binding index for the terrain OutsideView clip region
/// (terrain_modern.vert binding=2). Read directly by both the RHI world-pass
/// section binder (<c>WorldFrameSectionBinding.BindTerrainClip</c>) and
/// <c>PortalDepthMaskRenderer</c>, so unlike the mesh SSBO binding (which the
/// RHI arm addresses through its own <c>GpuBindingModel.StorageClipRegions</c>
/// instead) this one is still genuinely shared.</summary>
/// <summary>UBO binding index for <c>PortalDepthMaskRenderer</c>'s
/// exit-seal/punch-fan clip block (<c>portal_depth.vert</c> binding=2) — the
/// one production consumer left at this binding after S3 chunk 4 fix
/// round 2 (L3) deleted the walk's own screen-space clip gate (which used
/// to share this same binding number in terrain_modern.vert and
/// sky.vert). Unlike the mesh SSBO binding (which the RHI arm addresses
/// through its own <c>GpuBindingModel.StorageClipRegions</c> instead) this
/// one stays a restated raw constant — see
/// <c>VulkanPipelineLayouts.UniformTerrainClip</c>'s matching doc.</summary>
public const uint TerrainClipUboBinding = 2;
// ---- CPU-side state ------------------------------------------------------
@ -82,9 +88,6 @@ public sealed class ClipFrame : IDisposable
private byte[] _regionBytes;
private int _slotCount;
// Packed std140 bytes for the terrain UBO (always TerrainUboBytes long).
private readonly byte[] _terrainBytes = new byte[TerrainUboBytes];
/// <summary>
/// The GL arm's per-flight-slot region/terrain buffer rings this used to
/// report on were deleted at Campaign V slice V11: every publication now
@ -98,14 +101,12 @@ public sealed class ClipFrame : IDisposable
{
_regionBytes = regionBytes;
_slotCount = slotCount;
// Terrain defaults to count 0 (ungated). _terrainBytes is already all
// zeros, which encodes count=0 + zeroed (unused) planes.
}
/// <summary>
/// The U.3 default frame: exactly slot 0 (no-clip, count 0) and a terrain
/// count of 0. The whole scene renders ungated — identical to pre-U.3. U.4
/// replaces this with a frame built from real portal visibility.
/// The U.3 default frame: exactly slot 0 (no-clip, count 0). The whole
/// scene renders ungated — identical to pre-U.3. U.4 replaces this with a
/// frame built from real portal visibility.
/// </summary>
public static ClipFrame NoClip()
{
@ -120,10 +121,10 @@ public sealed class ClipFrame : IDisposable
/// <summary>
/// Phase U.4: reset this frame back to the NoClip state — exactly slot 0
/// (no-clip, count 0) and a terrain count of 0 — WITHOUT allocating a new
/// frame. The single long-lived <c>_clipFrame</c> in GameWindow is reset +
/// re-packed every frame by <see cref="ClipFrameAssembler"/>, then published
/// through one frame-ring allocation per section (see
/// (no-clip, count 0) — WITHOUT allocating a new frame. The single
/// long-lived <c>_clipFrame</c> in GameWindow is reset + re-packed every
/// frame by <see cref="ClipFrameAssembler"/>, then published through one
/// frame-ring allocation per section (see
/// <c>RhiWorldPassSurface.PrepareClipFrame</c>).
/// </summary>
public void Reset()
@ -136,9 +137,6 @@ public sealed class ClipFrame : IDisposable
EnsureRegionCapacity(CellClipStrideBytes);
Array.Clear(_regionBytes, 0, CellClipStrideBytes);
_slotCount = 1;
// Terrain back to count 0 (ungated) until SetTerrainClip is called again.
Array.Clear(_terrainBytes);
}
/// <summary>
@ -230,18 +228,13 @@ public sealed class ClipFrame : IDisposable
count * sizeof(float) * 4));
}
// S3 chunk 4 fix round 1 (K3): SetTerrainClip (the terrain OutsideView
// writer) is deleted — no production caller has written a non-empty
// terrain clip since S3 chunk 4's original round deleted the walk's
// per-outside-view-slice sky/terrain-clip loop, and fix round 1's K4
// deletes the sky loop's own now-dead SetTerrainClip wrapper too. Every
// KEEP clip (exit seals, punch fans) already read their planes through
// GetSlotPlanes above / ClipViewSlice.Planes directly, never through
// this terrain-specific slot. _terrainBytes therefore stays at its
// NoClip/Reset default (count 0, all zero) for the life of a frame —
// see WorldPassSurface.cs's PrepareClipFrame for how the TerrainClip
// UBO section still gets bound as that all-zero disabled block even
// with nothing left to publish it.
// S3 chunk 4 fix round 2 (L3): the walk's screen-space clip gate is gone
// — terrain_modern.vert and sky.vert no longer declare a block at this
// binding, and the last CPU-side publisher of one was already removed a
// round earlier. Every KEEP clip (exit seals, punch fans) reads its
// planes through GetSlotPlanes above / ClipViewSlice.Planes directly,
// never through a terrain-specific slot — this class carries no terrain
// state at all any more.
/// <summary>
/// No-op: this container owns no GPU resource of its own on the RHI arm —
@ -308,15 +301,9 @@ public sealed class ClipFrame : IDisposable
internal ReadOnlySpan<byte> RegionBytes =>
_regionBytes.AsSpan(0, _slotCount * CellClipStrideBytes);
/// <summary>The packed std140 terrain-clip block. See <see cref="RegionBytes"/>.</summary>
internal ReadOnlySpan<byte> TerrainBytes => _terrainBytes;
// ---- Test seams ----------------------------------------------------------
/// <summary>Test seam: the packed std430 region bytes (slot 0..SlotCount-1).
/// Read-only snapshot used by ClipFrameLayoutTests to assert the byte layout.</summary>
internal ReadOnlySpan<byte> RegionBytesForTest => RegionBytes;
/// <summary>Test seam: the packed std140 terrain UBO bytes.</summary>
internal ReadOnlySpan<byte> TerrainBytesForTest => TerrainBytes;
}

View file

@ -19,7 +19,15 @@ using System.Numerics;
namespace AcDream.App.Rendering;
/// <summary>
/// How the landscape-through-outside_view pass should be interpreted.
/// S3 chunk 4 fix round 2 (L2): retired from the walk's own clip assembly —
/// <see cref="ClipFrameAssembly"/> no longer tracks a terrain clip mode at
/// all, because the walk draws the sky, terrain and weather unclipped, one
/// call each, matching retail (<c>LScape::draw</c> never installs a view
/// before any of the three). The type stays only because
/// <see cref="WorldSceneRenderer"/>'s separate flat-world safety path still
/// uses it for its own unrelated "did the flat terrain draw this frame"
/// diagnostic flag (<c>Planes</c> = drew, <c>Skip</c> = the PView walk ran
/// instead; that path never produces <c>Scissor</c>).
/// </summary>
public enum TerrainClipMode
{
@ -61,8 +69,6 @@ public sealed class ClipFrameAssembly
public int OutdoorSlot { get; internal set; }
public bool OutdoorVisible { get; internal set; }
public TerrainClipMode TerrainMode { get; internal set; }
public Vector4 TerrainScissorNdcAabb { get; internal set; }
public bool HasOutsideView { get; internal set; }
public Vector4 OutsideViewNdcAabb { get; internal set; }
@ -279,8 +285,6 @@ public static class ClipFrameAssembler
assembly.SetOutsideViewSlices(assembly.CopySlices(slices));
assembly.OutdoorSlot = 0;
assembly.OutdoorVisible = true;
assembly.TerrainMode = TerrainClipMode.Scissor;
assembly.TerrainScissorNdcAabb = fullScreen;
assembly.HasOutsideView = true;
assembly.OutsideViewNdcAabb = fullScreen;
assembly.OutsidePlaneCount = 0;
@ -290,8 +294,6 @@ public static class ClipFrameAssembler
{
assembly.OutdoorSlot = 0;
assembly.OutdoorVisible = false;
assembly.TerrainMode = TerrainClipMode.Skip;
assembly.TerrainScissorNdcAabb = Vector4.Zero;
assembly.HasOutsideView = false;
assembly.OutsideViewNdcAabb = Vector4.Zero;
assembly.OutsidePlaneCount = 0;
@ -370,53 +372,36 @@ public static class ClipFrameAssembler
foreach (var poly in pvFrame.OutsideView.Polygons)
{
var cps = ClipPlaneSet.From(poly);
if (cps.IsNothingVisible)
continue;
int slot;
Vector4[] planes;
if (cps.Count > 0)
{
planes = cps.PlaneArray;
slot = frame.AppendSlot(planes);
if (cps.Count > outsideMaxPlaneCount)
outsideMaxPlaneCount = cps.Count;
}
else
{
planes = System.Array.Empty<Vector4>();
slot = 0;
outsideHasScissorFallback = true;
scissorFallbacks++;
}
outsideSlicesList.Add(new ClipViewSlice(slot, AabbOf(poly), planes));
AppendOutsideSlice(
frame,
poly,
outsideSlicesList,
ref outsideMaxPlaneCount,
ref outsideHasScissorFallback,
ref scissorFallbacks);
}
ClipViewSlice[] outsideViewSlices = assembly.CopySlices(outsideSlicesList);
bool outdoorVisible = outsideViewSlices.Length > 0;
int outdoorSlot = outdoorVisible ? outsideViewSlices[0].Slot : 0;
TerrainClipMode terrainMode = !outdoorVisible
? TerrainClipMode.Skip
: (outsideHasScissorFallback ? TerrainClipMode.Scissor : TerrainClipMode.Planes);
Vector4 outsideViewNdcAabb = outdoorVisible
? new Vector4(pvFrame.OutsideView.MinX, pvFrame.OutsideView.MinY,
pvFrame.OutsideView.MaxX, pvFrame.OutsideView.MaxY)
: Vector4.Zero;
Vector4 terrainScissor = terrainMode == TerrainClipMode.Scissor
? outsideViewNdcAabb
: Vector4.Zero;
assembly.SetOutsideViewSlices(outsideViewSlices);
assembly.OutdoorSlot = outdoorSlot;
assembly.OutdoorVisible = outdoorVisible;
assembly.TerrainMode = terrainMode;
assembly.TerrainScissorNdcAabb = terrainScissor;
assembly.HasOutsideView = outdoorVisible;
assembly.OutsideViewNdcAabb = outsideViewNdcAabb;
assembly.OutsidePlaneCount = terrainMode == TerrainClipMode.Planes ? outsideMaxPlaneCount : 0;
// S3 chunk 4 fix round 2 (L2): equivalent to the deleted
// terrainMode == TerrainClipMode.Planes gate without needing
// TerrainClipMode at all — a scissor-fallback slice can only exist
// when outdoorVisible is already true (both branches above append a
// slice), so this reduces to the same three cases (no slices -> 0;
// any scissor fallback -> 0; all-planes -> outsideMaxPlaneCount).
assembly.OutsidePlaneCount = outsideHasScissorFallback ? 0 : outsideMaxPlaneCount;
assembly.ScissorFallbacks = scissorFallbacks;
return assembly;
}
@ -509,55 +494,82 @@ public static class ClipFrameAssembler
if (poly.MaxY > unionMaxY) unionMaxY = poly.MaxY;
}
var cps = ClipPlaneSet.From(poly);
if (cps.IsNothingVisible)
continue;
int slot;
Vector4[] planes;
if (cps.Count > 0)
{
planes = cps.PlaneArray;
slot = frame.AppendSlot(planes);
if (cps.Count > outsideMaxPlaneCount)
outsideMaxPlaneCount = cps.Count;
}
else
{
planes = System.Array.Empty<Vector4>();
slot = 0;
outsideHasScissorFallback = true;
scissorFallbacks++;
}
outsideSlicesList.Add(new ClipViewSlice(slot, AabbOf(poly), planes));
AppendOutsideSlice(
frame,
poly,
outsideSlicesList,
ref outsideMaxPlaneCount,
ref outsideHasScissorFallback,
ref scissorFallbacks);
}
ClipViewSlice[] outsideViewSlices = assembly.CopySlices(outsideSlicesList);
bool outdoorVisible = outsideViewSlices.Length > 0;
int outdoorSlot = outdoorVisible ? outsideViewSlices[0].Slot : 0;
TerrainClipMode terrainMode = !outdoorVisible
? TerrainClipMode.Skip
: (outsideHasScissorFallback ? TerrainClipMode.Scissor : TerrainClipMode.Planes);
Vector4 outsideViewNdcAabb = outdoorVisible
? new Vector4(unionMinX, unionMinY, unionMaxX, unionMaxY)
: Vector4.Zero;
Vector4 terrainScissor = terrainMode == TerrainClipMode.Scissor
? outsideViewNdcAabb
: Vector4.Zero;
assembly.SetOutsideViewSlices(outsideViewSlices);
assembly.OutdoorSlot = outdoorSlot;
assembly.OutdoorVisible = outdoorVisible;
assembly.TerrainMode = terrainMode;
assembly.TerrainScissorNdcAabb = terrainScissor;
assembly.HasOutsideView = outdoorVisible;
assembly.OutsideViewNdcAabb = outsideViewNdcAabb;
assembly.OutsidePlaneCount = terrainMode == TerrainClipMode.Planes ? outsideMaxPlaneCount : 0;
// S3 chunk 4 fix round 2 (L2): see Assemble's matching comment — the
// same reduction applies here.
assembly.OutsidePlaneCount = outsideHasScissorFallback ? 0 : outsideMaxPlaneCount;
assembly.ScissorFallbacks = scissorFallbacks;
}
/// <summary>
/// S3 chunk 4 fix round 2 (L4): the ONE place a single outside_view
/// <see cref="ViewPolygon"/> becomes an appended clip slot plus its
/// <see cref="ClipViewSlice"/> — both <see cref="Assemble"/>'s
/// outside_view loop and <see cref="ReassembleOutsideViewFromWalk"/>'s
/// outside_view loop call this instead of each carrying its own copy of
/// the plane/scissor-fallback bookkeeping (a prior round's three-lens
/// review found the duplication let a CPU/GPU equivalence pin exercise
/// one copy while production ran the other — see <c>ClipFrameLayoutTests</c>'
/// punch-fan pin). A polygon entirely outside every plane
/// (<see cref="ClipPlaneSet.IsNothingVisible"/>) appends nothing and
/// returns false; the caller's own loop simply moves to the next
/// polygon either way, so the return value only matters to a caller that
/// needs to know.
/// </summary>
private static bool AppendOutsideSlice(
ClipFrame frame,
in ViewPolygon poly,
List<ClipViewSlice> outsideSlicesList,
ref int maxPlaneCount,
ref bool hasScissorFallback,
ref int scissorFallbacks)
{
var cps = ClipPlaneSet.From(poly);
if (cps.IsNothingVisible)
return false;
int slot;
Vector4[] planes;
if (cps.Count > 0)
{
planes = cps.PlaneArray;
slot = frame.AppendSlot(planes);
if (cps.Count > maxPlaneCount)
maxPlaneCount = cps.Count;
}
else
{
planes = System.Array.Empty<Vector4>();
slot = 0;
hasScissorFallback = true;
scissorFallbacks++;
}
outsideSlicesList.Add(new ClipViewSlice(slot, AabbOf(poly), planes));
return true;
}
private static Vector4 AabbOf(ViewPolygon poly) =>
new(poly.MinX, poly.MinY, poly.MaxX, poly.MaxY);

View file

@ -93,7 +93,8 @@ internal static class GpuBindingModel
/// is 144 bytes: too large for the 96-byte push-constant block (and for
/// Vulkan's guaranteed 128-byte ceiling), and there is no RHI verb for setting
/// a uniform array. A small uniform buffer is the Vulkan-legal home. Binding 2
/// is taken by the terrain clip block, so this is 3.
/// is taken by <c>PortalDepthMaskRenderer</c>'s exit-seal/punch-fan clip block
/// (<see cref="VulkanPipelineLayouts.UniformTerrainClip"/>), so this is 3.
/// </summary>
public const uint UniformTerrainTiling = 3;
@ -107,8 +108,8 @@ internal static class GpuBindingModel
/// block, so a loose <c>uniform mat4 uSkyView;</c> is unspellable, and this
/// set is 256 bytes in std140 — three matrices alone are twice the entire
/// 96-byte push-constant block. A uniform buffer is the only legal home.
/// Bindings 1, 2 and 3 are taken by SceneLighting, the terrain clip block
/// and terrain tiling, so this is 4.
/// Bindings 1, 2 and 3 are taken by SceneLighting, PortalDepthMaskRenderer's
/// clip block and terrain tiling, so this is 4.
/// </summary>
public const uint UniformSkyParams = 4;

View file

@ -371,13 +371,17 @@ internal static unsafe class VulkanPipelineLayouts
}
/// <summary>
/// The terrain screen-space clip block's uniform binding.
/// <c>PortalDepthMaskRenderer</c>'s exit-seal/punch-fan clip block's uniform
/// binding (<c>portal_depth.vert</c>).
///
/// <para><see cref="GpuBindingModel"/> does not name this number — it only
/// records, twice, that "binding 2 is taken by the terrain clip block" while
/// explaining why terrain tiling is 3 and sky params are 4. The number itself
/// has been pinned by <c>terrain_modern.vert</c> and <c>sky.vert</c> since
/// Phase U.3. Restating it here rather than promoting it into the frozen
/// records that binding 2 is taken here while explaining why terrain tiling
/// is 3 and sky params are 4. Pinned since Phase U.3; S3 chunk 4 fix round 2
/// (L3) deleted the walk's OWN screen-space clip gate, which used to share
/// this exact binding number in <c>terrain_modern.vert</c> and
/// <c>sky.vert</c> — neither shader declares a block at this binding any
/// more, leaving <c>portal_depth.vert</c> the one production consumer.
/// Restating the number here rather than promoting it into the frozen
/// binding model keeps slice V6i-2 out of the pinned contract; a later slice
/// entitled to change §3.3 should move it.</para>
/// </summary>

View file

@ -38,11 +38,13 @@ namespace AcDream.App.Rendering.Gpu.Vk;
/// <para><b>Scissor does NOT flip with the viewport.</b> The V3 audit called
/// this out as a concrete acceptance item (plan §4.10, item 1):
/// <c>vkCmdSetScissor</c> is always top-left-origin regardless of viewport sign,
/// and <c>NdcScissorRect.ToPixels</c> emits GL bottom-left rectangles. So the
/// scissor rectangle needs an explicit Y flip against the attachment height,
/// while the viewport needs none. Getting this wrong shows up as a doorway
/// aperture clipped from the wrong edge — visible, but only in a scene that has
/// one.</para>
/// while every caller of <see cref="ScissorToVulkan"/> passes a GL-convention
/// bottom-left rectangle (the pass encoder's own full-attachment default,
/// set once at pass begin — S3 chunk 4 fix round 2 deleted the one caller that
/// used to pass anything narrower). So the scissor rectangle needs an explicit
/// Y flip against the attachment height, while the viewport needs none.
/// Getting this wrong shows up as a doorway aperture clipped from the wrong
/// edge — visible, but only in a scene that has one.</para>
///
/// <para>Clip space itself needs nothing. acdream's cameras already build
/// projections with <c>Matrix4x4.CreatePerspectiveFieldOfView</c>, which is the

View file

@ -1,45 +0,0 @@
// NdcScissorRect.cs
//
// NDC AABB → framebuffer-pixel scissor box, CONSERVATIVE (outer bound).
// The scissor that brackets a landscape/doorway slice is a fallback BOUND on
// the slice's view region (AD-17 in the divergence register): it must CONTAIN
// every fragment the per-fragment plane clip would keep. Under-inclusion is
// the bug class — the #130 doorway top-edge background strip was this box
// computed as Floor(origin) + Ceiling(size), whose far edge
// floor(min)+ceil(maxmin) lands up to one pixel SHORT of the true max edge
// at unlucky fractional alignments, scissoring away the aperture's top/right
// pixel row for the whole slice (sky, terrain, statics, weather) while the
// seal still stamps it — a strip of clear color no later pass can fill.
//
// Correct outer bound: floor both mins, ceil both maxes, width = difference.
// A fragment at pixel (i,j) rasterizes iff its CENTER (i+0.5, j+0.5) lies in
// the region ⊆ the NDC box [X0,X1]×[Y0,Y1] (pixel units). Center-inside ⇒
// i ≥ X00.5 ⇒ i ≥ floor(X0) and i ≤ X10.5 ⇒ i < ceil(X1). So
// [floor(X0), ceil(X1)) admits every center-inside pixel, over-including by
// at most one pixel per edge — safe per AD-17's doctrine (the wall shell /
// plane clip repaints or kills the surplus).
using System;
using System.Numerics;
namespace AcDream.App.Rendering;
public static class NdcScissorRect
{
/// <summary>Convert an NDC AABB (minX, minY, maxX, maxY in [-1,1]) to a
/// framebuffer-pixel scissor box that CONTAINS it. Inputs are clamped to
/// the screen so a region extending past an edge still yields a valid box.
/// Width/height are at least 1.</summary>
public static (int X, int Y, int Width, int Height) ToPixels(
Vector4 ndcAabb, int fbWidth, int fbHeight)
{
float nx0 = Math.Clamp(ndcAabb.X, -1f, 1f);
float ny0 = Math.Clamp(ndcAabb.Y, -1f, 1f);
float nx1 = Math.Clamp(ndcAabb.Z, -1f, 1f);
float ny1 = Math.Clamp(ndcAabb.W, -1f, 1f);
int px0 = (int)MathF.Floor((nx0 * 0.5f + 0.5f) * fbWidth);
int py0 = (int)MathF.Floor((ny0 * 0.5f + 0.5f) * fbHeight);
int px1 = (int)MathF.Ceiling((nx1 * 0.5f + 0.5f) * fbWidth);
int py1 = (int)MathF.Ceiling((ny1 * 0.5f + 0.5f) * fbHeight);
return (px0, py0, Math.Max(1, px1 - px0), Math.Max(1, py1 - py0));
}
}

View file

@ -6,29 +6,14 @@ using AcDream.App.Rendering.Wb;
using AcDream.Core.Rendering;
using AcDream.Core.Vfx;
using AcDream.Core.World;
using Silk.NET.Windowing;
namespace AcDream.App.Rendering;
internal readonly record struct RetailPViewFramebufferSize(int Width, int Height);
internal interface IRetailPViewFramebufferSource
{
RetailPViewFramebufferSize Capture();
}
internal sealed class SilkRetailPViewFramebufferSource(IWindow window) :
IRetailPViewFramebufferSource
{
private readonly IWindow _window = window
?? throw new ArgumentNullException(nameof(window));
public RetailPViewFramebufferSize Capture()
{
var size = _window.FramebufferSize;
return new RetailPViewFramebufferSize(size.X, size.Y);
}
}
// S3 chunk 4 fix round 2 (L2): RetailPViewFramebufferSize / IRetailPViewFramebufferSource
// / SilkRetailPViewFramebufferSource are deleted — their only consumer was
// RhiWorldPassSurface.BeginScissor's NDC-to-pixel conversion, and BeginScissor
// itself is deleted in the same round (no producer of a narrowed scissor
// rectangle remains anywhere in the walk).
internal sealed class RetailPViewCellSource : IRetailPViewCellSource
{
@ -184,9 +169,10 @@ public RetailPViewPassExecutor(
/// <c>arg2==1</c> runs AFTER <c>LScape::draw</c>'s landblock loop
/// finishes (@0x00506396), not once per active landscape view. This call
/// is UNCLIPPED and sets no scissor — S3 chunk 4 (§10.2) deleted the
/// former per-outside-view-slice loop (<c>SetTerrainClip</c> +
/// <c>ClearClipRouting</c> + the old <c>DrawLandscapeSliceLate</c> leaf,
/// one call per active landscape view) that used to run before this
/// former per-outside-view-slice loop (the walk's own screen-space
/// terrain-clip writer, <c>ClearClipRouting</c>, and the old
/// <c>DrawLandscapeSliceLate</c> leaf, one call per active landscape
/// view) that used to run before this
/// call and re-submit the rain mesh once per doorway aperture; this is
/// now the ONLY weather call site, matching retail's ONE unclipped
/// <c>GameSky::Draw(sky,1)</c>.
@ -447,16 +433,28 @@ public RetailPViewPassExecutor(
return submitted;
}
// S3 chunk 4 fix round 1 (K4): BeginDoorwayScissor and the
// EnableClipDistances wrapper are deleted — their only caller was
// DrawWalkSky's per-outside-view-slice loop (RetailPViewPassExecutor.
// WalkLeaf.cs), itself deleted by the same fix (retail draws the sky
// ONCE, unclipped, exactly like the terrain and the weather — see
// DrawWalkSky's own doc comment). _surface.BeginScissor/EndScissor and
// IWorldPassSurface.EnableClipDistances stay: RhiWorldPassSurface.
// ClearInteriorDepth still ends an active scissor, and
// WorldScenePassExecutor (the separate flat-world path, out of this
// chunk's scope) still calls EnableClipDistances directly.
// S3 chunk 4 fix round 1 (K4): the sky's own doorway-scissor bracket and
// the EnableClipDistances wrapper around it are deleted — their only
// caller was DrawWalkSky's per-outside-view-slice loop
// (RetailPViewPassExecutor.WalkLeaf.cs), itself deleted by the same fix
// (retail draws the sky ONCE, unclipped, exactly like the terrain and
// the weather — see DrawWalkSky's own doc comment).
//
// S3 chunk 4 fix round 2 (L2): round 1's own comment here asserted that
// the interior depth clear still had a live scissor to end at that
// point — a mechanism that no longer existed ANYWHERE by then (K4 had
// already deleted the sky's own scissor bracket, the last production
// producer of a narrowed rectangle). IWorldPassSurface.BeginScissor/
// EndScissor and their RhiWorldPassSurface bodies are deleted outright
// in this round; the interior depth clear no longer ends anything
// because nothing narrows a rectangle any more — the pass encoder sets
// the full-attachment scissor once, at pass begin
// (VulkanGpuPassEncoder.cs:87), and it stays that way for the life of
// the pass. IWorldPassSurface.EnableClipDistances/DisableClipDistances
// stay: WorldScenePassExecutor (the separate flat-world path, out of
// this chunk's scope) still calls EnableClipDistances directly, and the
// KEEP clips (exit seals, punch fans) bracket their own draws with
// Enable/DisableClipDistances below.
private void DisableClipDistances() => _surface.DisableClipDistances();
}

View file

@ -639,8 +639,9 @@ internal sealed class RetailPViewRenderer
}
// S3 chunk 4 (§10.2): the former per-outside-view-slice loop
// (SetTerrainClip + ClearClipRouting + DrawLandscapeSliceLate, one
// call per active landscape view) is DELETED — retail draws the
// (the walk's own screen-space terrain-clip writer + ClearClipRouting
// + DrawLandscapeSliceLate, one call per active landscape view) is
// DELETED — retail draws the
// weather mesh and its rain particles ONCE, unclipped, after
// LScape::draw's whole landblock loop (GameSky::Draw(sky,1)
// @0x00506ff0), never once per doorway aperture. DrawWeatherOnce

View file

@ -85,32 +85,18 @@ layout(std140, ACDREAM_UBO_SET binding = 1) uniform SceneLighting {
vec4 uCameraAndTime;
};
// === Phase W Stage 4: sky/weather portal clip (the OutsideView region) ========
// The sky + weather (rain cylinder) meshes are "the outside seen through a
// doorway" — retail draws them as part of LScape, clipped to the exit-portal
// region (PView::DrawCells @ 0x005a4840). acdream gates them with the SAME
// binding=2 TerrainClip UBO the terrain shader reads (ClipFrame.SetTerrainClip →
// the OutsideView convex planes). The planes are SCREEN-SPACE (NDC) half-spaces
// encoded as clip-space planes (nx, ny, 0, dw) with the test
// dot(plane, gl_Position) >= 0. After the perspective divide that reduces to
// nx*ndcX + ny*ndcY + dw >= 0 — INDEPENDENT of the projection matrix. So the same
// plane set clips the sky correctly even though the sky uses its OWN dome
// projection (uSkyProjection / uSkyView, translation-zeroed) rather than the
// camera view-proj. uTerrainClipCount == 0 (outdoor / no exit portal visible)
// ungates the sky entirely (the second loop sets all 8 distances to +1.0 ⇒
// full-screen sky, bit-identical to pre-Stage-4). Host enables GL_CLIP_DISTANCE0..7
// only around the sky/weather draws.
layout(std140, ACDREAM_UBO_SET binding = 2) uniform TerrainClip {
int uTerrainClipCount;
vec4 uTerrainClipPlanes[8];
};
// Core profile: redeclare gl_PerVertex so writing gl_ClipDistance[] is legal
// (mirrors terrain_modern.vert). Sized 8 to match GL_MAX_CLIP_DISTANCES >= 8.
out gl_PerVertex {
vec4 gl_Position;
float gl_ClipDistance[8];
};
// Retail draws the sky ONCE per frame, UNCLIPPED (LScape::draw @0x00506330
// -> GameSky::Draw(sky,0) @0x0050633c, before draw_check_blocks — no view is
// ever installed for it, and the landscape itself is view-CULLED per cell,
// never GPU-clipped, RenderDeviceD3D::DrawBlock @0x005a17c0). S3 chunk 4 fix
// round 2 (L3/L5) deletes the screen-space clip UBO and gl_ClipDistance
// writes this shader used to declare at binding=2 to gate the sky/weather to
// a doorway aperture — that mechanism's only CPU-side writer was already
// deleted at fix round 1's K3, and its own doorway scissor bracket at fix
// round 1's K4; an interior root's aperture exactness comes from the depth
// clear, the exit seals, and the interior repaint instead (WalkFrameDriver's
// interior turn draws the real cell geometry back over whatever the
// unclipped sky/terrain painted through the doorway).
out vec2 vTex;
out vec3 vTint;
@ -165,17 +151,4 @@ void main() {
float fogEnd = uFogParams.y;
float span = max(fogEnd - fogStart, 1e-3);
vFogFactor = clamp((fogEnd - dist) / span, 0.0, 1.0);
// Phase W Stage 4: clip the sky/weather to the OutsideView (doorway) region.
// With uTerrainClipCount == 0 (outdoor / no exit portal in view) the first loop
// is skipped and the second sets all 8 distances to +1.0 ⇒ no clipping ⇒
// full-screen sky. Indoors with an exit portal visible, the OutsideView planes
// confine the sky to the doorway opening — exactly, per-fragment, matching the
// terrain (no scissor approximation). plane.z is 0 (a screen-space slab), so the
// sky's depth / dome radius is irrelevant. gl_Position here is the sky's own
// dome-projected clip position; the NDC-plane test is projection-independent.
for (int i = 0; i < uTerrainClipCount; ++i)
gl_ClipDistance[i] = dot(uTerrainClipPlanes[i], gl_Position);
for (int i = uTerrainClipCount; i < 8; ++i)
gl_ClipDistance[i] = 1.0;
}

View file

@ -311,7 +311,7 @@
"stages": [
{
"stage": "vert",
"sourceSha256": "9102b156bd4fd667831353640b2feee2ddde66e88579a4e425566c9b67304b64",
"sourceSha256": "51b42232202cd005439e95c50fd325a3849359b3357ab7550af9a4bb404279e4",
"compiled": true
},
{
@ -327,7 +327,7 @@
"stages": [
{
"stage": "vert",
"sourceSha256": "882979f63c858760e977ecafb708416ab01f7adabe4bb38c0630020c087f1c28",
"sourceSha256": "42d1dbd0dbd950862e8672f79a3f429f771bae55fd2b5721c3e551a0ea9563b6",
"compiled": true
},
{
@ -343,7 +343,7 @@
"stages": [
{
"stage": "vert",
"sourceSha256": "a3f8592d482793622f7a69c08f8ba828a4e071f2fb5e1763f865be84797bceb7",
"sourceSha256": "faf6855222cb2b09da6697c93a93f35cbc57c27bbc124055a6d235c72ef1a23a",
"compiled": true
},
{

View file

@ -40,33 +40,15 @@ layout(std140, ACDREAM_UBO_SET binding = 1) uniform SceneLighting {
vec4 uCameraAndTime;
};
// === Phase U.3: terrain screen-space clip gate (OutsideView region) ===========
// Terrain is a single global region (the OutsideView), so it needs one set of
// clip planes, not a per-instance slot table like the mesh shader. A std140 UBO
// at binding=2 carries it. The UBO binding namespace is distinct from the SSBO
// binding namespace, so this does NOT collide with the mesh shader's SSBO
// binding=2 — and within THIS shader binding=1 (SceneLighting) is the only other
// UBO, leaving binding=2 free. uTerrainClipCount == 0 (the U.3 default) ungates
// terrain entirely (the second loop sets all 8 distances to +1.0). Uploaded by
// ClipFrame.UploadShared each frame; TerrainModernRenderer binds it before draw.
//
// Campaign V slice V6i-2: ACDREAM_UBO_SET is what puts this in set 1 under the
// Vulkan dialect and expands to nothing under GL. Omitting it left the block at
// set 0 binding 2, which the storage layout declares as a STORAGE buffer — see
// plan §5.5.12 finding 2, measured on the committed SPIR-V rather than inferred.
// sky.vert declares the SAME block correctly and is the precedent.
layout(std140, ACDREAM_UBO_SET binding = 2) uniform TerrainClip {
int uTerrainClipCount;
vec4 uTerrainClipPlanes[8];
};
// Core profile: redeclare gl_PerVertex so writing gl_ClipDistance[] is legal.
// Sized 8 to match GL_MAX_CLIP_DISTANCES >= 8. Host enables GL_CLIP_DISTANCE0..7
// once at startup; unused planes are set to +1.0 below so they pass everything.
out gl_PerVertex {
vec4 gl_Position;
float gl_ClipDistance[8];
};
// Retail never view-clips terrain — LScape::draw draws whole landblocks, and
// the walk's own CellInView admission already decided which cells reach here
// (RenderDeviceD3D::DrawBlock @0x005a17c0; S3 chunk 3's own findings). S3
// chunk 4 fix round 2 (L3/L5) deletes the Phase U.3 terrain screen-space clip
// gate this shader used to declare at binding=2 along with its
// gl_ClipDistance writes — that mechanism's only CPU-side writer was already
// deleted at fix round 1's K3; an interior root's aperture exactness comes
// from the depth clear, the exit seals, and the interior repaint instead
// (WalkFrameDriver's interior turn).
out vec2 vBaseUV;
out vec3 vWorldNormal;
@ -199,12 +181,4 @@ void main() {
// Closes issue #100; supersedes the hiddenTerrainCells cell-collapse hack.
vec3 terrainPos = vec3(aPos.xy, aPos.z - 0.01);
gl_Position = uViewProjection * vec4(terrainPos, 1.0);
// Phase U.3: terrain clip gate against the single OutsideView region. With
// uTerrainClipCount == 0 (U.3 default) the first loop is skipped and the
// second sets all 8 distances to +1.0 ⇒ no clipping ⇒ identical terrain.
for (int i = 0; i < uTerrainClipCount; ++i)
gl_ClipDistance[i] = dot(uTerrainClipPlanes[i], gl_Position);
for (int i = uTerrainClipCount; i < 8; ++i)
gl_ClipDistance[i] = 1.0;
}

View file

@ -38,33 +38,15 @@ layout(std140, ACDREAM_UBO_SET binding = 1) uniform SceneLighting {
vec4 uCameraAndTime;
};
// === Phase U.3: terrain screen-space clip gate (OutsideView region) ===========
// Terrain is a single global region (the OutsideView), so it needs one set of
// clip planes, not a per-instance slot table like the mesh shader. A std140 UBO
// at binding=2 carries it. The UBO binding namespace is distinct from the SSBO
// binding namespace, so this does NOT collide with the mesh shader's SSBO
// binding=2 — and within THIS shader binding=1 (SceneLighting) is the only other
// UBO, leaving binding=2 free. uTerrainClipCount == 0 (the U.3 default) ungates
// terrain entirely (the second loop sets all 8 distances to +1.0). Uploaded by
// ClipFrame.UploadShared each frame; TerrainModernRenderer binds it before draw.
//
// Campaign V slice V6i-2: ACDREAM_UBO_SET is what puts this in set 1 under the
// Vulkan dialect and expands to nothing under GL. Omitting it left the block at
// set 0 binding 2, which the storage layout declares as a STORAGE buffer — see
// plan §5.5.12 finding 2, measured on the committed SPIR-V rather than inferred.
// sky.vert declares the SAME block correctly and is the precedent.
layout(std140, ACDREAM_UBO_SET binding = 2) uniform TerrainClip {
int uTerrainClipCount;
vec4 uTerrainClipPlanes[8];
};
// Core profile: redeclare gl_PerVertex so writing gl_ClipDistance[] is legal.
// Sized 8 to match GL_MAX_CLIP_DISTANCES >= 8. Host enables GL_CLIP_DISTANCE0..7
// once at startup; unused planes are set to +1.0 below so they pass everything.
out gl_PerVertex {
vec4 gl_Position;
float gl_ClipDistance[8];
};
// Retail never view-clips terrain — LScape::draw draws whole landblocks, and
// the walk's own CellInView admission already decided which cells reach here
// (RenderDeviceD3D::DrawBlock @0x005a17c0; S3 chunk 3's own findings). S3
// chunk 4 fix round 2 (L3/L5) deletes the Phase U.3 terrain screen-space clip
// gate this shader used to declare at binding=2 along with its
// gl_ClipDistance writes — that mechanism's only CPU-side writer was already
// deleted at fix round 1's K3; an interior root's aperture exactness comes
// from the depth clear, the exit seals, and the interior repaint instead
// (WalkFrameDriver's interior turn).
out vec2 vBaseUV;
out vec3 vWorldNormal;
@ -180,12 +162,4 @@ void main() {
// Closes issue #100; supersedes the hiddenTerrainCells cell-collapse hack.
vec3 terrainPos = vec3(aPos.xy, aPos.z - 0.01);
gl_Position = uViewProjection * vec4(terrainPos, 1.0);
// Phase U.3: terrain clip gate against the single OutsideView region. With
// uTerrainClipCount == 0 (U.3 default) the first loop is skipped and the
// second sets all 8 distances to +1.0 ⇒ no clipping ⇒ identical terrain.
for (int i = 0; i < uTerrainClipCount; ++i)
gl_ClipDistance[i] = dot(uTerrainClipPlanes[i], gl_Position);
for (int i = uTerrainClipCount; i < 8; ++i)
gl_ClipDistance[i] = 1.0;
}

View file

@ -255,7 +255,6 @@ public sealed unsafe partial class SkyRenderer
SkyParams.SizeInBytes);
WorldFrameSectionBinding.BindSceneLighting(encoder, scope.Sections, frame);
WorldFrameSectionBinding.BindTerrainClip(encoder, scope.Sections, frame);
encoder.DrawIndexed((uint)sub.IndexCount, 1, 0, 0, 0);
}

View file

@ -256,7 +256,6 @@ public sealed unsafe partial class TerrainModernRenderer
encoder.BindIndexBuffer(RequireIndexStore(), 0, GpuIndexType.UInt32);
BindTilingTable(encoder);
WorldFrameSectionBinding.BindSceneLighting(encoder, scope.Sections, frame);
WorldFrameSectionBinding.BindTerrainClip(encoder, scope.Sections, frame);
// Campaign VM VM6 review fix round 4 (item 4): bind on BINDABLE,
// not Enabled — same rule as WbDrawDispatcher.BindDirectionalShadowReceiver.
// TryGetCurrentFrameBinding now returns true for a disabled-content

View file

@ -21,16 +21,20 @@ internal readonly record struct GpuBufferSection(
}
/// <summary>
/// Campaign V slice V6j: the three sections GL binds frame-globally and Vulkan
/// Campaign V slice V6j: the sections GL binds frame-globally and Vulkan
/// cannot.
///
/// <para>On GL the SceneLighting UBO (set 1 binding 1), the per-cell clip regions
/// (set 0 binding 2) and the terrain clip block (set 1 binding 2) are each bound
/// once, to a global binding point, and every consumer inherits them. Vulkan has
/// no global binding points: a descriptor set is bound per draw, and a renderer
/// that binds its own buffers selects the descriptor scope those sections have to
/// land in (plan §5.5.14 item 2). So the writers PUBLISH here and each renderer
/// binds them inside the pass, after its own binds.</para>
/// <para>On GL the SceneLighting UBO (set 1 binding 1) and the per-cell clip
/// regions (set 0 binding 2) are each bound once, to a global binding point,
/// and every consumer inherits them. Vulkan has no global binding points: a
/// descriptor set is bound per draw, and a renderer that binds its own
/// buffers selects the descriptor scope those sections have to land in (plan
/// §5.5.14 item 2). So the writers PUBLISH here and each renderer binds them
/// inside the pass, after its own binds. S3 chunk 4 fix round 2 (L3) deleted
/// the third section this class used to carry (the terrain screen-space clip
/// block, set 1 binding 2) — no shader declares it any more, and the
/// unrelated KEEP clip block that still uses binding 2 (the exit-seal/punch
/// fan clip) is fed directly by its own renderer, not through here.</para>
///
/// <para>Borrowed for the frame that publishes it — the sections are ring slices
/// and die when the frame retires.</para>
@ -43,14 +47,10 @@ internal sealed class WorldFrameSections
/// <summary>Set 0 binding 2 — the per-cell <c>CellClip</c> table.</summary>
public GpuBufferSection ClipRegions { get; set; }
/// <summary>Set 1 binding 2 — <c>TerrainClip</c>.</summary>
public GpuBufferSection TerrainClip { get; set; }
public void Reset()
{
SceneLighting = default;
ClipRegions = default;
TerrainClip = default;
}
}
@ -135,7 +135,10 @@ internal interface IWorldPassScope
/// <para>Each helper falls back to a zeroed ring slice when nothing published the
/// section. That is the same rule the GL arm already states for its own bindings
/// — bind at least one element so the shader never reads an unbound buffer —
/// applied to the three sections whose publisher runs outside the renderer.</para>
/// applied to the two sections whose publisher runs outside the renderer. S3
/// chunk 4 fix round 2 (L3) deleted the third helper this used to carry —
/// the terrain screen-space clip block's binder — with its last two callers;
/// no shader declares that block any more.</para>
/// </summary>
internal static class WorldFrameSectionBinding
{
@ -182,27 +185,6 @@ internal static class WorldFrameSectionBinding
section.SizeBytes);
}
internal static void BindTerrainClip(
IGpuPassEncoder encoder,
WorldFrameSections sections,
IGpuFrame frame)
{
GpuBufferSection section = sections.TerrainClip;
if (!section.IsValid)
{
section = Zeroed(
frame,
ClipFrame.TerrainUboBytes,
GpuRingUsage.Uniform);
}
encoder.BindUniformBuffer(
ClipFrame.TerrainClipUboBinding,
section.Buffer!,
section.OffsetBytes,
section.SizeBytes);
}
private static GpuBufferSection Zeroed(
IGpuFrame frame,
int byteCount,

View file

@ -1,4 +1,3 @@
using System.Numerics;
using AcDream.App.Rendering.Gpu;
namespace AcDream.App.Rendering;
@ -39,30 +38,16 @@ internal interface IWorldPassSurface
/// RHI arm ignores it: a ring allocation is distinct memory by construction
/// and lives until the frame retires.</para>
///
/// <para>S3 chunk 4 fix round 1 (K3): this no longer also publishes the
/// terrain clip block — <c>ClipFrame.SetTerrainClip</c>, its only
/// writer, is deleted, so <see cref="ClipFrame.TerrainBytes"/> stays at
/// its permanent NoClip/Reset default (count 0, all zero) for the life of
/// a frame. The terrain/sky shaders still declare the <c>TerrainClip</c>
/// UBO (binding=2), so <see cref="WorldFrameSectionBinding.BindTerrainClip"/>'s
/// existing zeroed-ring fallback (used whenever nothing published the
/// section) now binds that all-zero disabled block on every frame instead
/// of only when something raced the publish — the observable result is
/// identical either way, since a zeroed publish and a zeroed fallback are
/// the same bytes.</para>
/// <para>S3 chunk 4 fix round 1 (K3) deleted the walk's per-frame terrain
/// screen-space clip publish this used to also carry — its only writer
/// was retired along with the per-outside-view-slice terrain/sky/weather
/// clip loop — and fix round 2 (L3) deleted the terrain/sky shaders' own
/// declaration of that clip block along with the section binder that used
/// to re-assert it, so this contract now publishes exactly one section,
/// the per-cell clip-region table.</para>
/// </summary>
void PrepareClipFrame(int terrainUploadCount);
/// <summary>
/// Re-asserts the terrain clip block at its binding.
///
/// <para>GL needs this because binding points are global and the sky and mesh
/// shaders read the same uniform binding between two terrain slices. On the
/// RHI arm every consumer binds the published section inside the pass, so
/// there is no ambient binding to re-assert and this is a no-op.</para>
/// </summary>
void BindTerrainClip();
/// <summary>
/// Enables every <c>gl_ClipDistance</c> slot.
///
@ -77,15 +62,6 @@ internal interface IWorldPassSurface
/// <summary>Disables every <c>gl_ClipDistance</c> slot. See <see cref="EnableClipDistances"/>.</summary>
void DisableClipDistances();
/// <summary>
/// Scissors to a doorway slice's screen-space bounding box. Returns whether a
/// scissor is now active, so the caller can pair it with <see cref="EndScissor"/>.
/// </summary>
bool BeginScissor(Vector4 ndcAabb);
/// <summary>Restores the full drawable rectangle.</summary>
void EndScissor();
/// <summary>
/// Retail's interior depth clear, between the landscape slice and the
/// interior cells (<c>PView::DrawCells @ 0x005A4840</c>). Retail gates it
@ -108,18 +84,15 @@ internal sealed class RhiWorldPassSurface : IWorldPassSurface
private readonly IWorldPassScope _scope;
private readonly ICurrentGpuFrameSource _frames;
private readonly ClipFrame _clipFrame;
private readonly IRetailPViewFramebufferSource _framebuffer;
public RhiWorldPassSurface(
IWorldPassScope scope,
ICurrentGpuFrameSource frames,
ClipFrame clipFrame,
IRetailPViewFramebufferSource framebuffer)
ClipFrame clipFrame)
{
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
_frames = frames ?? throw new ArgumentNullException(nameof(frames));
_clipFrame = clipFrame ?? throw new ArgumentNullException(nameof(clipFrame));
_framebuffer = framebuffer ?? throw new ArgumentNullException(nameof(framebuffer));
}
public void PrepareClipFrame(int terrainUploadCount)
@ -131,17 +104,6 @@ internal sealed class RhiWorldPassSurface : IWorldPassSurface
_scope.Sections.ClipRegions = Publish(
_clipFrame.RegionBytes,
GpuRingUsage.Storage);
// S3 chunk 4 fix round 1 (K3): the terrain-clip publish half is
// deleted — SetTerrainClip (its only writer) is gone, so publishing
// ClipFrame.TerrainBytes here would only ever republish permanent
// zero bytes. WorldFrameSectionBinding.BindTerrainClip's existing
// zeroed-ring fallback (for when nothing published the section)
// binds that same all-zero disabled block instead.
}
/// <summary>No-op: there is no ambient binding to re-assert. See the interface.</summary>
public void BindTerrainClip()
{
}
/// <summary>No-op: Vulkan activates every declared clip distance. See the interface.</summary>
@ -154,33 +116,17 @@ internal sealed class RhiWorldPassSurface : IWorldPassSurface
{
}
public bool BeginScissor(Vector4 ndcAabb)
{
RetailPViewFramebufferSize framebuffer = _framebuffer.Capture();
var box = NdcScissorRect.ToPixels(
ndcAabb,
framebuffer.Width,
framebuffer.Height);
// GL convention on the way in; the backend performs its own Y flip.
_scope.RequireEncoder().SetScissor(box.X, box.Y, box.Width, box.Height);
return true;
}
public void EndScissor() =>
_scope.RequireEncoder().SetScissor(
0,
0,
_scope.AttachmentWidth,
_scope.AttachmentHeight);
public void ClearInteriorDepth()
{
// The GL arm drops the scissor before clearing so the clear covers the
// whole target; vkCmdClearAttachments takes its own rectangle and is not
// scissored, so the same coverage comes for free — but the scissor still
// has to come off, because the interior cells drawn after it are not
// confined to the doorway slice that was active.
EndScissor();
// S3 chunk 4 fix round 2 (L2): BeginScissor/EndScissor are deleted —
// no producer of a narrowed scissor rectangle remains anywhere in the
// walk (K4 deleted the doorway scissor that used to bracket the sky;
// fix round 1 already deleted the terrain/weather per-slice scissor
// loop). VulkanGpuPassEncoder's constructor sets the full-attachment
// scissor exactly once, at pass begin (VulkanGpuPassEncoder.cs:87),
// and nothing narrows it after that any more, so
// vkCmdClearAttachments's own unscissored clear and every draw after
// it already cover the whole target with no bracket needed here.
_scope.ClearInteriorDepth();
}

View file

@ -243,14 +243,10 @@ internal sealed class WorldRenderDiagnostics
$" ssbo[{slice.Slot}]: OUT-OF-RANGE len={regionBytes.Length}"));
}
ReadOnlySpan<byte> terrainBytes = clipFrame.TerrainBytesForTest;
int terrainCount = BitConverter.ToInt32(terrainBytes[..4]);
float p0 = BitConverter.ToSingle(terrainBytes.Slice(16, 4));
float p1 = BitConverter.ToSingle(terrainBytes.Slice(20, 4));
float p2 = BitConverter.ToSingle(terrainBytes.Slice(24, 4));
float p3 = BitConverter.ToSingle(terrainBytes.Slice(28, 4));
text.Append(FormattableString.Invariant(
$" ubo: n={terrainCount} p0=({p0:F3},{p1:F3},{p2:F3},{p3:F3})"));
// S3 chunk 4 fix round 2 (L3): the "ubo: n=... p0=..." segment this
// used to append read ClipFrame's own screen-space clip gate bytes,
// deleted along with that gate — no shader declares the block any
// more, so there is nothing left here to read.
string signature = text.ToString();
_clipRouteSequence++;
@ -342,7 +338,11 @@ internal sealed class WorldRenderDiagnostics
+ $"playerInRoot={(playerInRoot ? "Y" : "n")} "
+ $"eye=({cameraPosition.X:F2},{cameraPosition.Y:F2},{cameraPosition.Z:F2}) "
+ $"player=({playerPosition.X:F2},{playerPosition.Y:F2},{playerPosition.Z:F2}) "
+ $"terrain={result.ClipAssembly.TerrainMode} "
// S3 chunk 4 fix round 2 (L2): the "terrain=" field read
// ClipFrameAssembly.TerrainMode, deleted along with the
// walk's own terrain-clip-mode tracking (the walk draws
// terrain unclipped, one call, matching retail — there is no
// longer a mode to report here).
+ $"outVisible={result.ClipAssembly.OutdoorVisible}");
}
}
@ -402,15 +402,17 @@ internal sealed class WorldRenderDiagnostics
text.Append(" skyFrame=").Append(drawSkyThisFrame ? 'Y' : 'n');
text.Append(" zclear=").Append(depthClear ? 'Y' : 'n');
text.Append(" sceneParticles=").Append(sceneParticles);
// S3 chunk 4 fix round 2 (L2): "outMode=" read
// ClipFrameAssembly.TerrainMode, deleted with the walk's own
// terrain-clip-mode tracking.
if (clipAssembly is not null)
{
text.Append(" outSlices=").Append(clipAssembly.OutsideViewSlices.Length);
text.Append(" outPolys=").Append(clipAssembly.OutsideViewSlices.Length);
text.Append(" outMode=").Append(clipAssembly.TerrainMode);
}
else
{
text.Append(" outSlices=0 outPolys=0 outMode=none");
text.Append(" outSlices=0 outPolys=0");
}
text.Append(" ids=").Append(FormatIds(visibleCells, false));

View file

@ -1,240 +1,238 @@
using AcDream.App.Rendering.Sky;
using AcDream.App.Rendering.Wb;
using AcDream.Core.Rendering;
using AcDream.Core.Vfx;
using AcDream.Core.World;
namespace AcDream.App.Rendering;
internal interface IWorldScenePassExecutor
{
HashSet<uint>? TerrainVisibleCellIds { get; }
void BeginFrame();
void PrepareFlatWorldClip();
void DrawFlatSky(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction);
void DrawFlatTerrain(in WorldCameraFrame camera, uint? playerLandblockId);
void DrawFlatEntities(
in WorldCameraFrame camera,
IEnumerable<(uint LandblockId, System.Numerics.Vector3 AabbMin,
System.Numerics.Vector3 AabbMax,
IReadOnlyList<WorldEntity> Entities,
IReadOnlyDictionary<uint, WorldEntity>? AnimatedById)> entries,
uint? playerLandblockId,
HashSet<uint> animatedEntityIds);
string DrawPostWorldParticles(
LoadedCell? clipRoot,
ClipFrameAssembly? clipAssembly,
in WorldCameraFrame camera,
string currentSignature);
void DrawFlatWeather(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction);
void DisableClipDistances();
void AbortFrame();
}
/// <summary>
/// Concrete leaf for the flat-world safety path and the post-world particle
/// and weather passes. Retail PView frames remain owned by
/// <see cref="RetailPViewRenderer"/> and <see cref="RetailPViewPassExecutor"/>.
///
/// <para>Campaign V slice V6j: backend-neutral. Everything it does is either
/// delegation to a renderer or one of the four concerns
/// <see cref="IWorldPassSurface"/> owns, so one implementation serves both
/// backends and the retail ordering is written once.</para>
/// </summary>
internal sealed class WorldScenePassExecutor : IWorldScenePassExecutor
{
private readonly IWorldPassSurface _surface;
private readonly IRenderFrameGlState _frameGlState;
private readonly ClipFrame _clipFrame;
private readonly WbDrawDispatcher _entities;
private readonly EnvCellRenderer _environmentCells;
private readonly TerrainModernRenderer? _terrain;
private readonly TerrainDrawDiagnosticsController _terrainDiagnostics;
private readonly SkyRenderer? _sky;
using AcDream.Core.Rendering;
using AcDream.Core.Vfx;
using AcDream.Core.World;
namespace AcDream.App.Rendering;
internal interface IWorldScenePassExecutor
{
HashSet<uint>? TerrainVisibleCellIds { get; }
void BeginFrame();
void PrepareFlatWorldClip();
void DrawFlatSky(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction);
void DrawFlatTerrain(in WorldCameraFrame camera, uint? playerLandblockId);
void DrawFlatEntities(
in WorldCameraFrame camera,
IEnumerable<(uint LandblockId, System.Numerics.Vector3 AabbMin,
System.Numerics.Vector3 AabbMax,
IReadOnlyList<WorldEntity> Entities,
IReadOnlyDictionary<uint, WorldEntity>? AnimatedById)> entries,
uint? playerLandblockId,
HashSet<uint> animatedEntityIds);
string DrawPostWorldParticles(
LoadedCell? clipRoot,
ClipFrameAssembly? clipAssembly,
in WorldCameraFrame camera,
string currentSignature);
void DrawFlatWeather(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction);
void DisableClipDistances();
void AbortFrame();
}
/// <summary>
/// Concrete leaf for the flat-world safety path and the post-world particle
/// and weather passes. Retail PView frames remain owned by
/// <see cref="RetailPViewRenderer"/> and <see cref="RetailPViewPassExecutor"/>.
///
/// <para>Campaign V slice V6j: backend-neutral. Everything it does is either
/// delegation to a renderer or one of the four concerns
/// <see cref="IWorldPassSurface"/> owns, so one implementation serves both
/// backends and the retail ordering is written once.</para>
/// </summary>
internal sealed class WorldScenePassExecutor : IWorldScenePassExecutor
{
private readonly IWorldPassSurface _surface;
private readonly IRenderFrameGlState _frameGlState;
private readonly ClipFrame _clipFrame;
private readonly WbDrawDispatcher _entities;
private readonly EnvCellRenderer _environmentCells;
private readonly TerrainModernRenderer? _terrain;
private readonly TerrainDrawDiagnosticsController _terrainDiagnostics;
private readonly SkyRenderer? _sky;
private readonly ParticleSystem? _particles;
private readonly ParticleRenderer? _particleRenderer;
private readonly HashSet<uint> _visibleParticleOwners = [];
private readonly HashSet<uint> _noExcludedParticleOwners = [];
public WorldScenePassExecutor(
IWorldPassSurface surface,
IRenderFrameGlState frameGlState,
ClipFrame clipFrame,
WbDrawDispatcher entities,
EnvCellRenderer environmentCells,
TerrainModernRenderer? terrain,
private readonly HashSet<uint> _visibleParticleOwners = [];
private readonly HashSet<uint> _noExcludedParticleOwners = [];
public WorldScenePassExecutor(
IWorldPassSurface surface,
IRenderFrameGlState frameGlState,
ClipFrame clipFrame,
WbDrawDispatcher entities,
EnvCellRenderer environmentCells,
TerrainModernRenderer? terrain,
TerrainDrawDiagnosticsController terrainDiagnostics,
SkyRenderer? sky,
ParticleSystem? particles,
ParticleRenderer? particleRenderer)
{
_surface = surface ?? throw new ArgumentNullException(nameof(surface));
_frameGlState = frameGlState
?? throw new ArgumentNullException(nameof(frameGlState));
_clipFrame = clipFrame ?? throw new ArgumentNullException(nameof(clipFrame));
_entities = entities ?? throw new ArgumentNullException(nameof(entities));
_environmentCells = environmentCells
?? throw new ArgumentNullException(nameof(environmentCells));
_terrain = terrain;
_terrainDiagnostics = terrainDiagnostics
?? throw new ArgumentNullException(nameof(terrainDiagnostics));
_sky = sky;
{
_surface = surface ?? throw new ArgumentNullException(nameof(surface));
_frameGlState = frameGlState
?? throw new ArgumentNullException(nameof(frameGlState));
_clipFrame = clipFrame ?? throw new ArgumentNullException(nameof(clipFrame));
_entities = entities ?? throw new ArgumentNullException(nameof(entities));
_environmentCells = environmentCells
?? throw new ArgumentNullException(nameof(environmentCells));
_terrain = terrain;
_terrainDiagnostics = terrainDiagnostics
?? throw new ArgumentNullException(nameof(terrainDiagnostics));
_sky = sky;
_particles = particles;
_particleRenderer = particleRenderer;
}
public HashSet<uint>? TerrainVisibleCellIds => _terrain?.VisibleCellIds;
public void BeginFrame()
{
_visibleParticleOwners.Clear();
_clipFrame.Reset();
_entities.ClearClipRouting();
_environmentCells.SetClipRouting(null);
}
public void PrepareFlatWorldClip() => _surface.PrepareClipFrame(1);
public void DrawFlatSky(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction)
{
_surface.BindTerrainClip();
_surface.EnableClipDistances();
Exception? drawFailure = null;
try
{
_sky?.RenderSky(
camera.Camera,
camera.Position,
dayFraction,
activeDayGroup,
foundation.Sky,
foundation.EnvironOverrideActive);
}
catch (Exception error)
{
drawFailure = error;
throw;
}
finally
{
try
{
DisableClipDistances();
}
catch (Exception closeFailure) when (drawFailure is not null)
{
throw new AggregateException(
"Sky drawing failed and its clip-distance bracket could not be closed.",
drawFailure,
closeFailure);
}
}
if (_particles is not null && _particleRenderer is not null)
{
_particleRenderer.Draw(
camera.Camera,
camera.Position,
ParticleRenderPass.SkyPreScene);
}
}
public void DrawFlatTerrain(
in WorldCameraFrame camera,
uint? playerLandblockId)
{
_surface.EnableClipDistances();
_terrainDiagnostics.Begin();
_terrain?.Draw(
camera.Camera,
camera.Frustum,
neverCullLandblockId: playerLandblockId);
_terrainDiagnostics.Complete();
}
public void DrawFlatEntities(
in WorldCameraFrame camera,
IEnumerable<(uint LandblockId, System.Numerics.Vector3 AabbMin,
System.Numerics.Vector3 AabbMax,
IReadOnlyList<WorldEntity> Entities,
IReadOnlyDictionary<uint, WorldEntity>? AnimatedById)> entries,
uint? playerLandblockId,
HashSet<uint> animatedEntityIds) =>
_entities.Draw(
camera.Camera,
entries,
camera.Frustum,
neverCullLandblockId: playerLandblockId,
visibleCellIds: null,
animatedEntityIds: animatedEntityIds);
public string DrawPostWorldParticles(
LoadedCell? clipRoot,
ClipFrameAssembly? clipAssembly,
in WorldCameraFrame camera,
string currentSignature)
{
if (_particles is null || _particleRenderer is null)
return currentSignature;
if (clipRoot is null)
{
if (clipAssembly is not null)
{
_particleRenderer.DrawForOwners(
camera.Camera,
camera.Position,
ParticleRenderPass.Scene,
_visibleParticleOwners,
includeUnattached: true,
excludedAttachedOwnerIds: _noExcludedParticleOwners);
return AppendSignature(currentSignature, "filtered");
}
_particleRenderer.Draw(
camera.Camera,
camera.Position,
ParticleRenderPass.Scene);
return AppendSignature(currentSignature, "global");
}
// Every PView root, including the outdoor sentinel, now submits scene
// particles inside LScape::draw. Replaying them here is both a duplicate
// and too late: it occurs after nested building cells, allowing exterior
// waterfall/foliage alpha to repaint an indoor/outdoor transition.
return currentSignature;
}
public void DrawFlatWeather(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction)
{
_surface.BindTerrainClip();
_surface.EnableClipDistances();
Exception? drawFailure = null;
}
public HashSet<uint>? TerrainVisibleCellIds => _terrain?.VisibleCellIds;
public void BeginFrame()
{
_visibleParticleOwners.Clear();
_clipFrame.Reset();
_entities.ClearClipRouting();
_environmentCells.SetClipRouting(null);
}
public void PrepareFlatWorldClip() => _surface.PrepareClipFrame(1);
public void DrawFlatSky(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction)
{
_surface.EnableClipDistances();
Exception? drawFailure = null;
try
{
_sky?.RenderSky(
camera.Camera,
camera.Position,
dayFraction,
activeDayGroup,
foundation.Sky,
foundation.EnvironOverrideActive);
}
catch (Exception error)
{
drawFailure = error;
throw;
}
finally
{
try
{
DisableClipDistances();
}
catch (Exception closeFailure) when (drawFailure is not null)
{
throw new AggregateException(
"Sky drawing failed and its clip-distance bracket could not be closed.",
drawFailure,
closeFailure);
}
}
if (_particles is not null && _particleRenderer is not null)
{
_particleRenderer.Draw(
camera.Camera,
camera.Position,
ParticleRenderPass.SkyPreScene);
}
}
public void DrawFlatTerrain(
in WorldCameraFrame camera,
uint? playerLandblockId)
{
_surface.EnableClipDistances();
_terrainDiagnostics.Begin();
_terrain?.Draw(
camera.Camera,
camera.Frustum,
neverCullLandblockId: playerLandblockId);
_terrainDiagnostics.Complete();
}
public void DrawFlatEntities(
in WorldCameraFrame camera,
IEnumerable<(uint LandblockId, System.Numerics.Vector3 AabbMin,
System.Numerics.Vector3 AabbMax,
IReadOnlyList<WorldEntity> Entities,
IReadOnlyDictionary<uint, WorldEntity>? AnimatedById)> entries,
uint? playerLandblockId,
HashSet<uint> animatedEntityIds) =>
_entities.Draw(
camera.Camera,
entries,
camera.Frustum,
neverCullLandblockId: playerLandblockId,
visibleCellIds: null,
animatedEntityIds: animatedEntityIds);
public string DrawPostWorldParticles(
LoadedCell? clipRoot,
ClipFrameAssembly? clipAssembly,
in WorldCameraFrame camera,
string currentSignature)
{
if (_particles is null || _particleRenderer is null)
return currentSignature;
if (clipRoot is null)
{
if (clipAssembly is not null)
{
_particleRenderer.DrawForOwners(
camera.Camera,
camera.Position,
ParticleRenderPass.Scene,
_visibleParticleOwners,
includeUnattached: true,
excludedAttachedOwnerIds: _noExcludedParticleOwners);
return AppendSignature(currentSignature, "filtered");
}
_particleRenderer.Draw(
camera.Camera,
camera.Position,
ParticleRenderPass.Scene);
return AppendSignature(currentSignature, "global");
}
// Every PView root, including the outdoor sentinel, now submits scene
// particles inside LScape::draw. Replaying them here is both a duplicate
// and too late: it occurs after nested building cells, allowing exterior
// waterfall/foliage alpha to repaint an indoor/outdoor transition.
return currentSignature;
}
public void DrawFlatWeather(
in WorldCameraFrame camera,
in RenderFrameFoundation foundation,
DayGroupData? activeDayGroup,
float dayFraction)
{
_surface.EnableClipDistances();
Exception? drawFailure = null;
try
{
_sky?.RenderWeather(
@ -244,63 +242,63 @@ internal sealed class WorldScenePassExecutor : IWorldScenePassExecutor
activeDayGroup,
foundation.Sky,
foundation.EnvironOverrideActive);
}
catch (Exception error)
{
drawFailure = error;
throw;
}
finally
{
try
{
DisableClipDistances();
}
catch (Exception closeFailure) when (drawFailure is not null)
{
throw new AggregateException(
"Weather drawing failed and its clip-distance bracket could not be closed.",
drawFailure,
closeFailure);
}
}
if (_particles is not null && _particleRenderer is not null)
{
_particleRenderer.Draw(
camera.Camera,
camera.Position,
ParticleRenderPass.SkyPostScene);
}
}
}
catch (Exception error)
{
drawFailure = error;
throw;
}
finally
{
try
{
DisableClipDistances();
}
catch (Exception closeFailure) when (drawFailure is not null)
{
throw new AggregateException(
"Weather drawing failed and its clip-distance bracket could not be closed.",
drawFailure,
closeFailure);
}
}
if (_particles is not null && _particleRenderer is not null)
{
_particleRenderer.Draw(
camera.Camera,
camera.Position,
ParticleRenderPass.SkyPostScene);
}
}
public void DisableClipDistances() => _surface.DisableClipDistances();
public void AbortFrame()
{
List<Exception>? failures = null;
TryAbort(_frameGlState.RestoreFrameDefaults);
TryAbort(_clipFrame.Reset);
TryAbort(_entities.ClearClipRouting);
TryAbort(_entities.AbortCurrentRenderSceneObserverFrame);
TryAbort(() => _environmentCells.SetClipRouting(null));
_visibleParticleOwners.Clear();
if (failures is { Count: > 0 })
throw new AggregateException("World scene pass abort failed.", failures);
void TryAbort(Action operation)
{
try
{
operation();
}
catch (Exception error)
{
(failures ??= []).Add(error);
}
}
}
private static string AppendSignature(string current, string value) =>
current == "none" ? value : current + "+" + value;
}
public void AbortFrame()
{
List<Exception>? failures = null;
TryAbort(_frameGlState.RestoreFrameDefaults);
TryAbort(_clipFrame.Reset);
TryAbort(_entities.ClearClipRouting);
TryAbort(_entities.AbortCurrentRenderSceneObserverFrame);
TryAbort(() => _environmentCells.SetClipRouting(null));
_visibleParticleOwners.Clear();
if (failures is { Count: > 0 })
throw new AggregateException("World scene pass abort failed.", failures);
void TryAbort(Action operation)
{
try
{
operation();
}
catch (Exception error)
{
(failures ??= []).Add(error);
}
}
}
private static string AppendSignature(string current, string value) =>
current == "none" ? value : current + "+" + value;
}