Commit graph

184 commits

Author SHA1 Message Date
Erik
fb5fba6229 test(phys): A6.P3 #98 — live ResolveWithTransition capture apparatus
Apparatus only — no fix attempt. Per the systematic-debugging skill's
"3+ failures = question architecture" rule, the 6 hypotheses we
tested speculatively on the harness's airborne-at-tick-1 bug all
failed because we kept guessing what state the harness lacks. This
commit ships the evidence-driven path: capture the EXACT player
ResolveWithTransition call (every input + body-before + body-after +
result) into a JSON Lines fixture, then a comparison test loads the
fixture and replays it against the test engine. The first per-field
divergence pinpoints the missing apparatus state — no more guessing.

Adds:
- src/AcDream.Core/Physics/PhysicsResolveCapture.cs — new static module
  with CapturePath (env var ACDREAM_CAPTURE_RESOLVE), PhysicsBodySnapshot
  record, JSON Lines writer (thread-safe, flushes per record), process-
  exit hook for clean shutdown.

- PhysicsEngine.ResolveWithTransition probe wiring: snapshot body at
  method entry, snapshot again before return, refactor the two returns
  into one path so the capture call site is single. Filtered to
  IsPlayer mover flag so NPC/remote DR calls don't pollute.

- CellarUpTrajectoryReplayTests.cs:
  • Capture_WritesJsonLinesRecordsWhenIsPlayerAndEnabled — drives 3
    ticks with capture on, reads file back, verifies round-trip of
    inputs + body-before/after snapshots.
  • Capture_SkipsNonPlayerCalls — drives 3 NPC-style ticks (no
    IsPlayer flag), confirms the file is not created.

Off by default. Set ACDREAM_CAPTURE_RESOLVE=<path> to a writable file
path; capture starts on the next player ResolveWithTransition call.

Test baseline: 1172 + 8 pre-existing failures + 2 new smoke tests
that pass = 1174 + 8. Verified by stashed-baseline comparison.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:41:11 +02:00
Erik
402ec10ec5 Revert "fix(phys): A6.P3 #98 — gate ContactPlane assignment by Normal.Z (Shape 1)"
This reverts commit 0cb4c59681.
2026-05-23 16:54:19 +02:00
Erik
0cb4c59681 fix(phys): A6.P3 #98 — gate ContactPlane assignment by Normal.Z (Shape 1)
Adds PhysicsGlobals.ContactPlaneFlatThreshold = 0.99f and uses it at
both BSPQuery.AdjustSphereToPlane call sites that previously set CP
unconditionally on any walkable polygon found by FindWalkableInternal.

Backed by the retail cdb capture in cellar_up_capture_1: across 161
set_contact_plane writes during 5 seconds of cellar-up climbing,
EVERY write lands on a flat (Normal.Z = 1.0) plane — cellar floor at
world Z=90.95 or cottage floor at world Z=94. The cellar ramp
(Normal.Z = 0.695, walkable per FloorZ but sloped ~46 degrees) is
never set as CP in retail.

Acdream's prior behavior of setting CP=ramp caused two cascading
issues at the top of the ramp:
1. AdjustOffset's slope-projection produced +Z gain per call (correct
   in isolation) but inflated step-up's responsibility to "find the
   next walkable below the lifted check position".
2. step-up's downward step-down probe found no walkable within 0.6m
   below the proposed check (cottage floor at Z=94 is ABOVE, not
   below), so step-down rejected, sphere rolled back. Infinite freeze
   at world Z ~= 92.80.

With CP only set on flat polygons, sloped surfaces drive collision
detection and walkable-poly tracking (via path.SetWalkable) but
don't override the resting CP. The sphere should now climb the ramp
via step-up over the ramp polygon, with CP staying on the flat
cellar floor until the sphere reaches the flat cottage floor.

Tests: 1167 + 8 baseline maintained. No regression. The Issue98
replay tests still pass — they document the failing-frame geometry
(sphere world Z=92.01 below cottage floor), which doesn't change;
the fix prevents the sphere from getting STUCK at that altitude in
the first place. Live visual verification required next.

If the live test shows new failure modes (sphere stuck somewhere
else, doesn't climb at all, climbs but slides off, etc), the
threshold (0.99) or the gating approach itself may need refining.
This is the conservative empirical version of Shape 1; the named-
decomp research did not conclusively prove the exact retail gate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 16:46:12 +02:00
Erik
8a232a3e6e diag(phys): A6.P3 #98 — [step-walk-adjust] probe inside AdjustOffset
Adds one log line per AdjustOffset call (gated by ACDREAM_PROBE_STEP_WALK)
naming the branch taken (no-cp / no-cp-slide / slide-degenerate /
slide-crease / into-plane / away-plane, optionally +safety-push) plus
zGain = output.Z - input.Z.

No math or control-flow changes — pure observability so the next capture
can disambiguate the three failure-mode hypotheses for the cellar-ramp
climb cap. Re-reading the existing capture (a6-issue98-negpoly-...log)
showed the sphere DOES climb 90.00 -> 92.79 (2.79 m gain), then caps,
contradicting the divergence comparison's "no altitude gain" framing.
The real question is what stops the climb at world Z ~= 92.79 with the
cottage floor still 1.21 m higher. Existing [step-walk] probes wrap
AdjustOffset; this new probe reveals which branch the projection takes.

Fix plan with the four-branch decision tree at
docs/superpowers/plans/2026-05-23-a6-p3-issue98-cellar-up-fix.md.

Test baseline maintained: 1167 + 8.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 16:16:42 +02:00
Erik
f62a873be3 feat(phys): A6.P3 #98 Step 2 — cell-dump probe + roundtrip test
Step 2 of the apparatus plan at
C:\Users\erikn\.claude\plans\i-did-some-work-sharded-acorn.md. Adds a
one-shot cell-dump probe so the issue #98 replay harness can load real
cellar / cottage geometry as JSON fixtures, eliminating live-client
iteration from every fix attempt.

Probe gate:
  ACDREAM_DUMP_CELLS=0xA9B40143,0xA9B40146,0xA9B40147
  ACDREAM_DUMP_CELLS_DIR=tests/AcDream.Core.Tests/Fixtures/issue98 (default)

When set, the first time PhysicsDataCache.CacheCellStruct sees a matching
envCellId, it serializes the resulting CellPhysics to
<dir>/0x<cellid>.json and prints one [cell-dump] line. Zero cost when
unset (gate is a static-readonly IReadOnlySet<uint>.Count check).

DTOs (CellDump.cs):
- CellDump: top-level record holding cell id, WorldTransform,
  InverseWorldTransform, resolved polygons, portal polygons, portal
  infos, visible cell ids.
- PolygonDump / PortalDump / Vector3Dto / PlaneDto / Matrix4x4Dto:
  System.Text.Json-friendly records with explicit From / To converters.

What is intentionally NOT dumped: the DAT-native PhysicsBSPTree and
CellBSPTree trees. The replay harness drives the leaf-level walkable
predicates (WalkableHitsSphere, FindCrossedEdge, PolygonHitsSpherePrecise)
directly on the resolved polygon list, which is enough to expose the
issue #98 rejection (poly 0x0004 in 0xA9B40143 reports
insideEdges=False / overlapsSphere=False at the failing-frame sphere).
If a future replay needs BSP traversal we can extend the DTO + Hydrate
together without breaking fixtures.

Tests (CellDumpRoundTripTests):
- Capture → Hydrate preserves WorldTransform / InverseWorldTransform /
  every polygon's plane + vertices + NumPoints + SidesType.
- Capture → Hydrate preserves portal list + visible cell ids.
- Write to disk → Read back → Hydrate preserves content.
- Hydrate leaves BSP / CellBSP null by design (replay uses leaf-level
  predicates).

Verification:
- dotnet build: green, 0 errors.
- dotnet test: 1160 passed + 8 pre-existing failed (was 1156 + 8 before
  this commit; +4 from CellDumpRoundTripTests). Same 8 pre-existing
  failures, no new regressions.

Next: capture the three cells from the live client (Step 2 acceptance),
then build the replay harness against the fixtures (Step 3).
2026-05-23 15:16:56 +02:00
Erik
35b37dfb5f chore(phys): A6.P3 #98 triage — revert neg-poly + bldg-check experiments
Triage step from the plan at C:\Users\erikn\.claude\plans\
i-did-some-work-sharded-acorn.md. Four sessions on issue #98 left the
worktree dirty with ~1352 LOC of mixed work. This commit splits the
work into "keep" (defensible + diagnostic) and "drop" (failed
experiments), then commits the keep set with the drops removed.

Plan asked for three commits (diag / fix / revert); consolidated to one
because the diagnostic emits in TransitionTypes.cs are tightly
interleaved with the multi-sphere CellTransit calls and the CellId
switch. Hunk-level splitting in those files for marginal bisect
granularity didn't justify the misclick risk.

Reverted entirely (failed experiments per slice 7 handoff):
- src/AcDream.Core/Physics/PhysicsDataCache.cs — neg-poly storage
  fields (Stippling, PosSurface, NegSurface, HasNegativeSide,
  IsNegativeSide, NegativeSide).
- src/AcDream.Core/Physics/ShadowObjectRegistry.cs — isBuilding flag
  propagation through Register / ShadowEntry.
- tests/AcDream.Core.Tests/Physics/BSPQueryTests.cs — 165 lines of
  PolygonWithNegativeSide_* tests.
- tests/AcDream.Core.Tests/Physics/ShadowObjectRegistryTests.cs —
  isBuilding propagation tests.
- src/AcDream.Core/World/WorldEntity.cs — IsLandblockBuilding field
  (no consumer once ShadowObjectRegistry.isBuilding is gone).
- src/AcDream.Core/World/LandblockLoader.cs — IsLandblockBuilding=true
  setter on building entities (kept BuildBuildingTerrainCells).
- src/AcDream.App/Rendering/GameWindow.cs — isBuilding: arg passed to
  ShadowObjects.Register.
- src/AcDream.Core/Physics/BSPQuery.cs — TryAdjustWalkableSide /
  IsWalkableAt helpers, their callers, the Path 5 / Path 6 neg-poly
  branch split, the BldgCheck-tied clearCell conditional, and the
  neg-poly ResolveCellPolygons writes.
- src/AcDream.Core/Physics/PhysicsDiagnostics.cs — neg-poly fields
  in the poly-dump format.
- src/AcDream.Core/Physics/TransitionTypes.cs — SpherePath.BldgCheck +
  SpherePath.HitsInteriorCell fields and every consumer, the
  savedBldgCheck try/finally around FindCollisions, and the neg-poly
  format additions to the dump-on-error helper.
- src/AcDream.Core/Physics/CellTransit.cs — FindCellSet overloads
  with hitsInteriorCell out-param and the BuildCellSetAndPickContaining
  out-param threading.

Kept (defensible correctness fixes + diagnostic infrastructure):
- src/AcDream.App/Rendering/GameWindow.cs — render-vs-physics cell
  origin split: the 0.02m render lift no longer leaks into physics
  BSP caching. lb.BuildingTerrainCells threaded into LandblockMesh.Build.
- src/AcDream.Core/World/LoadedLandblock.cs — BuildingTerrainCells
  record field.
- src/AcDream.Core/World/LandblockLoader.cs — BuildBuildingTerrainCells
  (cy*8+cx from LandBlockInfo.Buildings).
- src/AcDream.Core/Terrain/LandblockMesh.cs — hiddenTerrainCells
  param that collapses owned-cell triangles to a zero-area degenerate.
- src/AcDream.App/Streaming/{GpuWorldState,LandblockStreamer}.cs —
  mechanical BuildingTerrainCells threading through LoadedLandblock
  reconstructions.
- src/AcDream.Core/Physics/CellTransit.cs — multi-sphere
  FindTransitCellsSphere variant + multi-sphere AddAllOutsideCells +
  FindCellSet(IReadOnlyList<Sphere>, …) overload + the
  BSPQuery.SphereIntersectsCellBsp call for loaded neighbours. Matches
  retail CObjCell::find_cell_list / CEnvCell::find_transit_cells.
- src/AcDream.Core/Physics/TransitionTypes.cs — multi-sphere FindCellSet
  call site, retail-faithful CellId switch after CheckOtherCells, the
  outdoor-landcell terrain-walkable fallback in CheckOtherCells, and
  the full diagnostic suite ([step-walk], [walkable-nearest],
  [issue98-walkable-detail], [cell-set-summary], LastBspHitPoly
  emits).
- src/AcDream.Core/Physics/PhysicsDiagnostics.cs — ProbeStepWalkEnabled
  gate (ACDREAM_PROBE_STEP_WALK=1) + LogStepWalk helper + FormatVector
  / FormatPlane utilities. All emit-gated.
- src/AcDream.Core/Physics/BSPQuery.cs — diagnostic emits to
  LastBspHitPoly at four sites in SphereIntersectsPolyInternal /
  the placement adjustment path.
- Test files for the kept work: CellTransitFindCellSetTests,
  CellTransitFindTransitCellsSphereTests, PhysicsDiagnosticsTests,
  TransitionCheckOtherCellsTests, LandblockMeshTests,
  LandblockLoaderTests.

Verification:
- dotnet build: green, 0 errors, 3 pre-existing warnings.
- dotnet test: 1156 passed + 8 failed (baseline was 1148 + 8 pre-
  existing; the +8 passing are the new tests for the kept defensible
  work). Same 8 pre-existing failures, no new regressions.

Backup of pre-triage worktree state in stash@{0}.

A6.P3 #98 is still open; this is the apparatus-prep step, not a fix.
Next: cell-dump probe (Step 2 of the plan).
2026-05-23 15:11:49 +02:00
Erik
cf3deff7c2 feat(phys): A6.P3 slice 5 — [place-fail] probe + sharpened #98 diagnosis
Add ACDREAM_PROBE_PLACEMENT_FAIL gate + LogPlacementFail emitter +
side-channel polygon attribution in PhysicsDiagnostics. Wire into
BSPQuery.FindCollisions Path 1 (Placement/Ethereal) on Collided
returns; wire into Transition.DoStepDown after the placement_insert
TransitionalInsert(1) call; wire into Transition.FindObjCollisions
to emit per-static-object [place-fail-obj] lines.

Run scen4 cellar-up with the probe → 168 [place-fail] events. 80 of
81 BSPQuery Path 1 placement rejections cite polygon 0x0020 in
cellar cell 0xA9B40147's BSP: n=(0,0,-1) d=-0.2, world Z=93.82 —
the cellar ceiling (underside of cottage main floor thickness layer).
0 [place-fail-obj] lines, confirming the failure source is the cell
BSP not a static object.

The probe-driven evidence INVALIDATES the 2026-05-22 morning
handoff's "Path 5 vs Path 6 in BSPQuery.FindCollisions" diagnosis.
Retail's BP4 trace shows every find_collisions hit has collide=0 —
retail enters the same Contact branch we do, no outer-dispatcher
divergence. Retail's BP5 fires 17+ times on the cellar ramp polygon,
not "30 hits all on flat planes" as morning claimed.

The actual divergence is downstream in cell-promotion: retail's
check_cell transitions to cottage cell 0xA9B40146 during the ascent
(BP7 sets ContactPlane to the cottage main floor poly, which lives
in cottage cell's BSP not cellar's). Ours stays at cellar 0xA9B40147,
where the ceiling poly 0x0020 correctly rejects the lifted sphere.

No fix attempted this session per CLAUDE.md discipline check
(3+ failed fixes = handoff). Full slice 5 evidence + concrete
next-session pickup steps at docs/research/2026-05-22-a6-p3-slice5-handoff.md.
ISSUES.md #98 updated with the corrected diagnosis.

Test baseline: 1148 + 8 pre-existing fail. Maintained.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:02:15 +02:00
Erik
bbd1df46e0 fix(phys): A6.P3 slice 4 — reset WalkInterp before placement_insert (issue #98)
Hypothesis-driven fix for issue #98 (cellar ascent stuck at top step).

Symptom (from polydump trace at scen4_cottage_cellar_polydump):
- Player walks up cellar ramp (real 46-degree slope per dat verification)
- Hits ramp polygon 0x0008 in cellar cell 0xA9B40147 270 times
- Each hit: sphere center lifted 0.75m onto ramp surface, all walk_interp
  consumed (winterp 1.0 -> 0.0)
- Step_up_slide fires 159+ times trying to recover
- Player physically stuck — never advances forward

Bug hypothesis: in DoStepDown, after the primary TransitionalInsert(5)
probe consumes WalkInterp down to 0 (the 0.75m lift), the placement_insert
call runs with WalkInterp=0. AdjustSphereToPlane's interp check
(`interp >= path.WalkInterp` where interp=0) then rejects any push-back
needed for the placement validation -> placement fails -> step_up returns
failure -> step_up_slide loop -> player stuck.

Fix: reset WalkInterp = 1.0 before the placement_insert call (mirrors
retail step_down's walk_interp = 1 reset at function entry, which is what
the placement_insert runs after in retail's flow).

Test suite: 1148 + 8 (baseline maintained).
Visual verification: pending user re-test of cellar-up walk.

If this fixes cellar-up, also likely improves other step-up-onto-slope
scenarios. If it doesn't fix cellar-up, the bug is elsewhere in the
step-up/step-down flow (separate investigation needed).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:07:06 +02:00
Erik
8bd311759e fix(phys): A6.P3 slice 3 v3 — REVERT stickiness; hypothesis-test cellar-up
Slice 3 v2 (point-in stickiness) closed the cell-resolver ping-pong
(data confirmed: scen4_cottage_cellar_slice3v2 capture shows 1 cell-
transit vs 20+ pre-fix). BUT user verification revealed: cellar-up
symptom transitioned from "stuck-at-top-ping-pong" (pre-slice-3) to
"never-reach-top-stuck-in-cellar" (post-slice-3). Stickiness was
holding player in cellar cell so aggressively that the legitimate
transition to the cottage main floor cell at the ramp top never
fired.

Reverting the stickiness check entirely. Trade-off:
- Inn doorway ping-pong returns (existed pre-slice-3; lesser evil)
- Player can again reach the top of the cellar ramp (per pre-slice-3
  user observation)
- Issue #98 cellar-up remains open — but with sharper diagnosis: it's
  not the cell resolver at all, it's deeper (BSP step-physics or
  AdjustOffset slope-projection at the cottage main floor boundary,
  per slice 4 polydump trace showing repeated push-back on the
  46-degree ramp polygon)

The slice 3 stickiness premise was correct but the implementation
shape was wrong. A future attempt needs either:
- A "near boundary" gate (only stick when sphere is deep inside cell)
- A retail-faithful per-cell hysteresis matching CObjCell::find_cell_list
  Position-variant (acclient_2013_pseudo_c.txt:308742-308783) more
  exactly than point-in
- OR address the underlying BSP step-physics bug first; then ping-pong
  may not even need a stickiness fix

Test suite: 1148 + 8 (baseline maintained).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:43:58 +02:00
Erik
319847289e diag(phys): A6.P3 slice 4 — extend [cell-cache] probe with portalTargets
Extends the existing [cell-cache] probe (gated by ACDREAM_PROBE_CELL_CACHE=1)
to also dump the list of portal targets per cell: which other cells
each portal connects to, the portal polygon id, and the flags.

Output format (appended to existing [cell-cache] line):
  portalTargets=[(cell=0xNNNN,poly=0xNNNN,flags=0xNNNN),...]

Purpose: investigating issue #98 (cellar-up stuck at top of ramp).
We now know the polygon geometry is correct (per slice 4 polydump
capture: the cellar is a real 46° ramp). Question is whether the
cellar cell has a portal to the cottage main floor cell, and where
that portal is. If portalTargets shows no connection to the expected
upstairs cell, that's the bug.

Test suite: unaffected (probe is gated off by default).
Build: green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:31:34 +02:00
Erik
0b449968a7 diag(phys): A6.P3 slice 4 — add [poly-dump] probe for #98 investigation
Adds a polygon-geometry dump probe that fires alongside [push-back]
whenever AdjustSphereToPlane lands a push-back. Gated by
ACDREAM_PROBE_POLY_DUMP=1.

Output format:
  [poly-dump] cell=0xA9B40147 polyId=0x0042 numPts=4 sides=Single
              n=(0.000,-0.719,0.695) d=-0.1007
              verts=[(x1,y1,z1),(x2,y2,z2),(x3,y3,z3),(x4,y4,z4)]

Purpose: investigate #98 (cellar-up stuck at top step). The push-back
trace shows the player hitting a sloped surface n=(0,-0.719,0.695) at
the cellar stair top. Two possibilities:
  1. The polygon really IS sloped 44° in the dat (genuine geometry).
  2. Our dat-read produces wrong vertices → wrong normal → wrong plane.

The dump lets us:
- Identify which dat polygon was hit (cell + poly ID)
- Compare our extracted vertices against WorldBuilder's straight-from-
  dat read for the same poly
- Or spawn the cell in ACViewer to visually verify the geometry

Changes:
- Added `ushort Id` property to ResolvedPolygon (defaults to 0 for test
  fixtures that don't care; production code in PhysicsDataCache.cs +
  BSPQuery.cs sets it from the dictionary key).
- Added ProbePolyDumpEnabled + LogPolyDump in PhysicsDiagnostics.
- Wired the dump into AdjustSphereToPlane's apply-branch (after the
  existing push-back log; same gating pattern).

Test suite: 1148 pass + 8 pre-existing fail (baseline maintained).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:17:47 +02:00
Erik
3e140cfe71 fix(phys): A6.P3 slice 3 v2 — point-in stickiness (was sphere-overlap)
Slice 3 v1 (8898166) used SphereIntersectsCellBsp for the stickiness
check. User verification showed: ping-pong WAS closed (3 cell-transit
events vs 20+ pre-fix) but user still couldn't walk up out of cellar
because the stickiness was OVER-CORRECTED — the sphere still partially
overlapped the cellar cell at the top of stairs, so stickiness held the
player in the cellar even when the center had transitioned to the
cottage main floor cell.

Fix: switch the stickiness check from SphereIntersectsCellBsp (sphere
overlap) to PointInsideCellBsp (center-in). Matches FindCellList's
own semantics for "which cell are you in." Player stays in fallback
only while center is still inside fallback's BSP volume.

Trade-off:
- More permissive transitions (good — cellar-up works)
- Less aggressive stickiness, so some boundary ping-ponging may return
  IF the sphere center oscillates across the boundary (rare; would
  require sub-mm Z drift across the boundary line)

If the trade-off bites (ping-pong returns somewhere), the fix is a
small geometric margin around the point-in check — but verify before
adding.

Test suite: 1148 pass + 8 pre-existing fail (baseline maintained).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:04:51 +02:00
Erik
88981669fe fix(phys): A6.P3 slice 3 — cell-resolver stickiness for ping-pong fix
Closes A6.P2 Finding 3 (cell-resolver instability) + issue #98 (cellar
ascent stuck at last step) + likely closes #97 (phantom collisions +
fall-through on 2nd floor; same instability family).

Adds a cell-stickiness check at the top of ResolveCellId's indoor
branch: before re-resolving via FindCellList, check if the fallback
(previous-tick) CellId's BSP still validly contains the sphere. If
yes, return fallbackCellId immediately — preserves cell membership
when the sphere is at a boundary where multiple cells overlap.

The bug: at cell boundaries (cellar last step, indoor doorways,
between two adjacent indoor cells), the sphere overlaps multiple
cells geometrically. FindCellList's candidate-iteration order
(HashSet, implementation-defined) determines which cell wins. That
order may shift tick-to-tick → CellId ping-pong → AdjustOffset
operates against a different cell's geometry each tick → player
can't accumulate forward motion → stuck.

Evidence: scen3_inn_2nd_floor_slice2v2 capture shows the ping-pong
chain at the cellar boundary:
  0xA9B4014B → 0xA9B4014A → 0xA9B4013F → 0xA9B4014A → 0xA9B4014B
  (Z stable ~96.4; CellId oscillates every tick; reason=resolver)

Retail oracle: cell-array hysteresis pattern from
CObjCell::find_cell_list Position-variant at
acclient_2013_pseudo_c.txt:308742-308783. Retail preserves cell
membership when sphere is close to (but slightly past) cell
boundaries.

Implementation: 9 lines added (sphere-overlap check against
fallbackCellId's CellBSP before falling through to FindCellList).
Existing #90 workaround at line 299-300 (post-FindCellList sphere-
overlap check) is now redundant in the common case but kept for
safety; deferred to A6.P4 removal after visual verification.

Test suite: 1148 pass + 8 pre-existing fail (baseline maintained).
Visual verification: pending — user happy-test will confirm cellar-
up walk succeeds + no ping-pong in cell-transit log.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 12:01:28 +02:00
Erik
f8d669be88 fix(phys): A6.P3 slice 2 v2 — revert seed removal + add no-op guard
First slice 2 attempt at commit 892019b removed PhysicsEngine.cs L622
per-tick CP seed entirely. User happy-test surfaced a regression: BSP
step_up at the last step of stairs failed because sub-step 1's
AdjustOffset had no ContactPlane to compute the lift direction (the
seed was load-bearing for step_up correctness).

Revert + better fix:
  1. Re-add the L622 seed (PhysicsEngine.cs:620-626).
  2. Add no-op-if-unchanged guard inside CollisionInfo.SetContactPlane
     (TransitionTypes.cs:259-279). When called with values identical
     to current state, early-return without incrementing
     ContactPlaneWriteCount or rewriting fields.

When the player stands on the same plane tick after tick, the L622
seed re-calls SetContactPlane with identical args — these now no-op
instead of inflating the counter and re-writing the same values.
Only actual state changes (e.g. landing on a new step's plane, cell
crossing) increment the counter.

Verification (post-rebuild, pre-this-commit slice 2 first attempt):
- scen3 walk produced 2,690 cp-writes (down from 30,420 = 91%
  reduction from L622-seed presence)
- BUT user could not pass the last step of stairs — step_up regression
- Test suite: 1148 + 8 pre-existing fail baseline maintained but
  physical behavior broke

Post-this-commit expectations:
- Test suite: 1148 + 8 (unchanged, no behavioral change in fixtures
  because the seed value is what the fixtures already expect)
- Stair-walking: works (seed restored)
- CP-write count: significantly reduced (most seeds are no-ops because
  body.CP doesn't change tick-over-tick on stable footing)
- Issues #96 / #97: re-test in re-capture; #96 should be largely
  closed via the guard; #97 (fall-through + stuck-in-falling) was
  observed pre-slice-2 too, so unrelated to the seed

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:32:23 +02:00
Erik
892019bc9a fix(phys): A6.P3 slice 2 — remove L622 per-tick CP seed (issue #96)
Closes issue #96 (per-tick PhysicsEngine.ResolveWithTransition CP seed
contributing 99.3% of post-slice-1 CP writes). Matches retail's
CTransition::init at acclient_2013_pseudo_c.txt:271954 which explicitly
clears contact_plane_valid = 0 at transition start.

Cross-tick CP retention now flows entirely via retail-faithful
mechanisms:
  - Mechanism A: BSPQuery.FindCollisions Path-6 land write
  - Mechanism B: Transition.ValidateTransition LKCP restore (slice 1)
  - Body persist at transition end (already existed)

Cost (deliberate): AdjustOffset on sub-step 1 of each tick takes the
'no contact plane' path. Slope-snap loss is imperceptible (sub-steps
are small, sub-steps 2+ pick up CP normally).

Likely closes issue #97 (phantom collisions + fall-through) as
side-effect — hypothesis was stale-CP slope-snap from body.ContactPlane
of a previous cell. To be verified post-commit via re-capture + user
happy-test.

Verification this commit:
- Test suite: 1148 pass + 8 pre-existing fail (baseline maintained)
- scen3 re-capture pending (separate commit)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 10:19:48 +02:00
Erik
5f7722a3a4 fix(phys): A6.P3 slice 1 step 2 — strip indoor walkable synthesis
Closes A6.P2 Finding 2 (ContactPlane resynthesis blowup, 250x to ∞x
more CP writes than retail). Indoor branch of Transition.FindEnvCollisions
now matches retail's CEnvCell::find_env_collisions tiny shape (decomp
line 309573): call BSPTREE::find_collisions, return OK. No synthesis,
no per-frame ValidateWalkable call, no per-frame ContactPlane write.

Cross-frame CP retention now flows via:
  - Mechanism A: BSPQuery.FindCollisions Path-3 step-down write on
    grounded movers (retail-faithful: BSPTREE::step_sphere_down at
    acclient_2013_pseudo_c.txt:323711 always writes contact_plane when
    it finds a walkable surface — only fires if sphere penetrates floor).
  - Mechanism B: per-transition LKCP restore in ValidateTransition
    (added in 5aba071) for the Collided/Adjusted/Slid result cases.
  - PhysicsEngine.RunTransitionResolve body persist (unchanged).

TryFindIndoorWalkablePlane definition retained for now; deleted in
A6.P4 alongside the #90 sphere-overlap workaround.

Test fix: IndoorContactPlaneRetentionTests sphere position corrected
from 5 cm below the floor (pre-fix arrangement to trigger synthesis)
to exactly on the floor (worldPosZ = floorZ). A grounded sphere at
its natural position does not penetrate the floor polygon, so BSP
Path 5 finds no intersection and returns OK immediately — zero
additional CP writes in 60 frames. Previously the below-floor position
was causing Path 5 → StepSphereUp → DoStepDown → SetContactPlane
every frame (60 writes), not the synthesis path.

Verification:
- IndoorContactPlaneRetentionTests: PASS (was the 9th expected fail;
  back to 1148 pass + 8 pre-existing fail).
- Full suite: 1148+420 pass, 8 fail (baseline maintained +1 pass).
- Re-capture verification (scen1/3/5) deferred to Task 6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 09:12:45 +02:00
Erik
5aba071aec feat(phys): A6.P3 slice 1 step 1 — add Mechanism B (LKCP restore)
Restores CollisionInfo.ContactPlane from LastKnownContactPlane when:
  - LKCP is valid
  - the sphere's current center is geometrically close to the LKCP
    plane (|dot(global_curr_center, N) + d| <= radius + EPSILON)

Matches retail's validate_transition LKCP-restore at
acclient_2013_pseudo_c.txt:272577 (CTransition::validate_transition,
address 0050aa70, lines 272565-272582). Slice 1 step 1 of the
A6.P3 indoor CP retention fix. Step 2 (Task 5) strips the
TryFindIndoorWalkablePlane synthesis from FindEnvCollisions.

Also fixes the proximity-check sphere: was using
sp.GlobalSphere[0].Origin (start sphere); now uses
sp.GlobalCurrCenter[0].Origin (current center) per retail
(acclient_2013_pseudo_c.txt:272568).

Tests: 1147 pass, 9 fail (8 pre-existing + 1 IndoorContactPlaneRetention
from T3 — expected; T5 lands the actual synthesis-strip fix).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 08:58:03 +02:00
Erik
869edd93b0 test(phys): A6.P3 slice 1 — add CollisionInfo.ContactPlaneWriteCount
Internal test-only counter incremented by SetContactPlane. Required
by IndoorContactPlaneRetentionTests to assert CP retention works
post-Finding-2 fix (A6.P2).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 08:23:56 +02:00
Erik
642734dcd0 feat(physics): A6.P1 — instrument CheckOtherCells with [push-back-cell]
Wires LogPushBackCellTransit into the multi-cell BSP iteration loop
just before ApplyOtherCellResult halts. Captures primary/other
cell ids + BSP result for direct comparison to retail's
CTransition::check_other_cells loop (already ported as A4).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:38:03 +02:00
Erik
66ee757926 feat(physics): A6.P1 — add LogPushBackCellTransit helper
One-line per-iteration emission helper for the CheckOtherCells
multi-cell BSP loop. Captures primary/other cell ids, BSP result,
and halted flag for direct comparison to retail's
CTransition::check_other_cells loop.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:36:42 +02:00
Erik
35631d1ec0 feat(physics): A6.P1 — instrument FindCollisions with [push-back-disp]
Wires LogPushBackDispatch into the modern FindCollisions overload
at the entry block (after path/collisions/obj locals + movement
computed). Legacy overload at line ~1895 delegates to modern, so
single instrumentation site covers all dispatches.

returnState=-1 sentinel marks "entry log" — A6.P2 analysis pairs
each entry with subsequent [push-back] adjust-sphere lines and
the eventual return state.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:34:55 +02:00
Erik
2d1f27d647 feat(physics): A6.P1 — add LogPushBackDispatch helper
One-line per-call emission helper for the FindCollisions dispatcher
instrumentation site. Captures path-selection state (collide flag,
insertType, objState) + walk-interp + return state for direct
comparison to retail's BSPTREE::find_collisions breakpoint.
Output uses the [push-back-disp] tag to disambiguate from
[push-back] adjust-sphere events.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:32:37 +02:00
Erik
eb8a3186e7 feat(physics): A6.P1 — instrument AdjustSphereToPlane with [push-back]
Wires the LogPushBackAdjust helper into all three return paths
of AdjustSphereToPlane (early-return on no-movement, early-return
on interp out-of-window, and the applied path). Probe is gated by
ProbePushBackEnabled so it's zero-cost when off.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:30:46 +02:00
Erik
3a173b9616 feat(physics): A6.P1 — add LogPushBackAdjust helper
One-line per-call emission helper for the AdjustSphereToPlane
instrumentation site. Direct field-for-field paired comparison to
retail's CPolygon::adjust_sphere_to_plane breakpoint.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:28:20 +02:00
Erik
ad6c89de33 fix(physics): A6.P1 — drop unresolvable <see cref> to private method
BSPQuery.AdjustSphereToPlane is private; <see cref> from outside the
class can't resolve and emits CS1574. Switched to <c>...</c> code
span. Other two cross-refs (FindCollisions public, CheckOtherCells
internal-same-assembly) keep their <see cref> form.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:27:00 +02:00
Erik
ace9e62213 feat(physics): A6.P1 — add ProbePushBackEnabled toggle
New PhysicsDiagnostics flag gates the [push-back] probe shipping
in subsequent tasks. Env-var ACDREAM_PROBE_PUSH_BACK=1 + DebugVM
mirror, matching the existing probe-toggle pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:24:22 +02:00
Erik
7ac8f544a7 fix(physics): #89 — sphere-overlap in CheckBuildingTransit closes login-inside-inn classification race
Outdoor→indoor entry path used PointInsideCellBsp (point-only) for the
building-portal containment test. When the player logs in INSIDE a
building and the foot-sphere center is just past the destination cell's
CellBSP boundary, the point-only check failed → CellId stuck as
outdoor → indoor BSP queries never ran → walls passable. User-reported
symptom: "logged in in the inn, at start ran through exterior walls,
ran back in and they block now."

Fix: swap PointInsideCellBsp for SphereIntersectsCellBsp (the radius-
aware port from #90). Promotes CellId to the interior cell the moment
ANY part of the foot-sphere crosses the destination cell boundary —
matches retail's CCellStruct::sphere_intersects_cell timing at
acclient_2013_pseudo_c.txt:317666 exactly.

The sphereRadius parameter was already plumbed through CheckBuildingTransit
per #89's documented "future upgrade" note from 2026-05-19 (which is
exactly today's symptom). Closes #89.

1147 + 8 baseline maintained.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 09:12:30 +02:00
Erik
c0d84057cb fix(physics): #91 — query indoor cell shadows in FindObjCollisions
Interior items (fireplaces, tables, chests) registered via A1.5's
ShadowObjectRegistry.Register `cellScope` parameter (commit 4d3bf6f)
are stored under their ParentCellId key (e.g. 0xA9B40121). But
GetNearbyObjects's broad-phase only iterates outdoor 24m landcell
keys (0xA9B40029 etc) and never looks up indoor cell keys, so
interior shadows were registered but unreachable. User-visible
symptom: tables/boxes/fireplaces don't block movement, while walls
DO block (the indoor BSP path is separate).

Fix: GetNearbyObjects accepts an optional indoorCellIds parameter
and additionally queries _cells[indoorCellId] for each entry with
low-byte >= 0x0100u. FindObjCollisions computes the set via
CellTransit.FindCellSet (same set A4 uses for multi-cell BSP
iteration) and passes it through. Outdoor seeds typically produce
sets containing only outdoor land-cells which the new branch filters
out, so the outdoor-only behavior is preserved.

1147 + 8 baseline maintained. Closes the user-reported regression
"walls block now correct but interior items such as tables and boxes
or fireplaces do not block."

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 09:03:51 +02:00
Erik
4ca35966f8 fix(physics): #90 — sphere-overlap cell stickiness at doorway threshold
ResolveCellId's indoor-seed fall-through was point-only: when the indoor
BSP push-back moved the foot-sphere CENTER a few cm outside the indoor
CellBSP volume, the resolver flipped CellId back to outdoor. Next tick
re-promoted via CheckBuildingTransit. The ping-pong caused most ticks
to be classified outdoor, bypassing indoor BSP wall checks entirely
and producing the user-reported "walls walk through everywhere in the
inn" symptom.

Fix: port retail's BSPTREE::sphere_intersects_cell_bsp
(acclient_2013_pseudo_c.txt:323267 → BSPNODE variant at :325546) as
BSPQuery.SphereIntersectsCellBsp(node, center, radius). Replace the
point-only check at PhysicsEngine.ResolveCellId:285 with the radius-
aware overlap test. Player stays classified indoor as long as ANY
part of the foot-sphere still overlaps the indoor cell volume; only
flips to outdoor when the sphere is FULLY outside.

Retail uses a 0.01 m epsilon on the radius (acclient :325551); ported
verbatim. 8 new unit tests cover null/leaf/inside/on-plane/straddling/
fully-outside/tangent-boundary cases plus a regression-anchor test
that proves the old PointInsideCellBsp would have returned false for
the same straddling input.

1147 + 8 baseline maintained (was 1139 + 8 before #90 fix). Closes #90.
A4 multi-cell iteration (shipped earlier today) should now actually
exercise in production since the player can stably remain in indoor
cells.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 20:30:36 +02:00
Erik
691493e579 Reapply "feat(physics): A4 — wire CheckOtherCells into FindEnvCollisions"
This reverts commit 3add110449.
2026-05-20 20:06:14 +02:00
Erik
3add110449 Revert "feat(physics): A4 — wire CheckOtherCells into FindEnvCollisions"
This reverts commit 967d065141.
2026-05-20 18:50:26 +02:00
Erik
967d065141 feat(physics): A4 — wire CheckOtherCells into FindEnvCollisions
After the primary cell's BSP returns OK, query every other cell the
foot-sphere overlaps via CellTransit.FindCellSet + Transition.CheckOtherCells.
Closes the Holtburg inn vestibule wall walk-through: the vestibule
(cell 0xA9B40164) has only 4 BSP polys; walls live in the adjacent
interior cell (0xA9B40157). Without A4 the adjacent cell's BSP was
never queried.

End-to-end test reduces the real Holtburg bug to a minimal synthetic
two-cell fixture: empty vestibule BSP + interior cell with the
existing BSPStepUpFixtures.TallWall (the same fixture B2 uses to
prove a grounded mover can't scale a 5m wall). Pre-A4: returns OK
(walks through). Post-A4: returns Slid (the wall halts the
transition).

FindEnvCollisions visibility tightened from private → internal so
the integration test can call it directly without going through
FindTransitionalPosition's sub-step iteration.

Retail oracle: acclient_2013_pseudo_c.txt:272717-272798
(CTransition::check_other_cells).

Spec: docs/superpowers/specs/2026-05-20-phase-a4-multi-cell-bsp-design.md
Plan: docs/superpowers/plans/2026-05-20-phase-a4-multi-cell-bsp.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 16:23:00 +02:00
Erik
493c5e5ff6 feat(physics): A4 — Transition.CheckOtherCells + ApplyOtherCellResult
Port of retail's CTransition::check_other_cells at
acclient_2013_pseudo_c.txt:272717-272798. Iterates every non-primary
cell in a candidate set, runs BSPQuery.FindCollisions per cell with
that cell's WorldTransform-derived rotation + origin, halts on first
Collided/Adjusted/Slid.

ApplyOtherCellResult is the combine-semantics helper extracted for
unit testability — it pins the retail switch:
  - Collided/Adjusted → CollidedWithEnvironment = true (gated on
    !Contact), halt.
  - Slid              → ContactPlaneValid + ContactPlaneIsWater = false,
                        halt.
  - OK                → continue.

Not yet wired into FindEnvCollisions — see next commit. Probe gated
on PhysicsDiagnostics.ProbeIndoorBspEnabled (ACDREAM_PROBE_INDOOR_BSP).

Six new unit tests: five against the pure combine helper for each halt
case + one direct CheckOtherCells call exercising the null-BSP guard.

Spec: docs/superpowers/specs/2026-05-20-phase-a4-multi-cell-bsp-design.md
Plan: docs/superpowers/plans/2026-05-20-phase-a4-multi-cell-bsp.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 16:14:05 +02:00
Erik
e6369e266f feat(physics): A4 — CellTransit.FindCellSet overload exposes candidate set
Refactors FindCellList to delegate to a private helper
(BuildCellSetAndPickContaining) that returns BOTH the containing cell
id AND the full candidate HashSet. Public surface gains a new
FindCellSet overload; existing FindCellList behavior is unchanged.

Used by the upcoming Transition.CheckOtherCells (Phase A4) to iterate
every cell the sphere overlaps for per-cell BSP collision. Mirrors
retail's CObjCell::find_cell_list filling both cell_array AND var_4c
at acclient_2013_pseudo_c.txt:272725.

Three new unit tests cover sphere-fully-inside-primary,
sphere-straddling-portal, and outdoor-seed-neighbour-landcells cases.

Spec: docs/superpowers/specs/2026-05-20-phase-a4-multi-cell-bsp-design.md
Plan: docs/superpowers/plans/2026-05-20-phase-a4-multi-cell-bsp.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 16:11:31 +02:00
Erik
4679134d66 fix(physics): fall through to outdoor cell when indoor BSP doesn't contain player (A1.7)
ISSUES #83 Phase A1.7. CellTransit.FindCellList returns currentCellId
when no candidate cell's CellBSP contains the sphere center — but
this also fires when the player has walked OUTSIDE the entire
portal-connected indoor graph (e.g., breached a missing wall poly,
walked through a doorway gap). The player's CellId stays stuck on
the old indoor cell whose BSP is now far away, NodeIntersects fails
at the BSP root for every collision query, and no walls block in
their actual location.

Probe evidence (launch-stairs.utf8.log, A1.6 verify):
- Cell 0xA9B40164: 646 indoor-bsp queries, 644 returned OK (99.7%).
  No walls firing.
- Player local positions in cell 0xA9B40164 ranged X[-0.66..33.18],
  Y[10.68..63.53] — a 34x53m envelope. The player was geometrically
  ~62m from the cell's world origin while CellId never updated.

Compare to adjacent cells where collision works:
- Cell 0xA9B4015A: 230 queries, 32% hit rate
- Cell 0xA9B40157: 131 queries, 38% hit rate

Fix: after CellTransit.FindCellList returns, verify the resolved
cell's CellBSP actually contains the sphere center via
BSPQuery.PointInsideCellBsp. If not, fall through to the existing
outdoor cell resolution branch (terrain grid + CheckBuildingTransit
for re-entry into a different building).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 14:25:20 +02:00
Erik
4d3bf6fe37 fix(physics): scope interior cell shadows to ParentCellId (Phase A1.5)
ISSUES #83 Phase A1.5. ShadowObjectRegistry.Register() assigned each
entity to the outdoor landcell grid (8x8 cells, 24m square) based on
its XY position. For interior EnvCell statics (fireplace, furniture,
sign) hydrated by BuildInteriorEntitiesForStreaming with
ParentCellId = envCellId (a high-cellId interior cell like
0xA9B40121), this meant the shadow got stamped into the OUTDOOR
landcell whose XY they overlapped (e.g., 0xA9B40029).

When the player was OUTSIDE the building in 0xA9B40029, the indoor
chair/fireplace shadow fired collisions in "thin air" outdoors. The
user reported this on Holtburg cottage exteriors after the Phase A1
landblock-stab fallback fix.

Fix: add optional cellScope parameter to Register(). When non-zero
(passed as entity.ParentCellId ?? 0u from the 5 entity-loop call
sites in GameWindow), skip the XY-based landcell loop and register
the shadow ONLY in that cell. Live server-spawn registration at
GameWindow.cs:3137 keeps the XY-based behavior (live entities move
between cells).

Probe evidence (launch-a1-verify.utf8.log, post-A1 capture):
- 71 hits on 0x40B50054 (interior static) in OUTDOOR cell 0xA9B40029.
- 47 hits on 0xA9B47C00 (other Holtburg cottage BSP — legitimate).
- 31 hits on 0x40B50048 / 15 on 0x40B50018 (interior statics).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 11:54:29 +02:00
Erik
a2e7a87c25 feat(physics): [walk-miss] + [floor-polys] diagnostic emissions
Wires the WalkMissDiagnostic aggregator + flag into the two emission
sites per docs/superpowers/specs/2026-05-21-indoor-walk-miss-probe-design.md.

- [walk-miss] (per-frame, MISS branch of TryFindIndoorWalkablePlane):
  foot world+local position, nearest walkable poly with XY-containment
  flag and vertical gap, and LandCell terrain probe at the same XY.
- [floor-polys] (one-shot per cell at cache time): walkable poly id,
  normal Z, local-XY bbox, plane Z at bbox center.

Both gated on ACDREAM_PROBE_WALK_MISS=1. No physics behavior changes.
The live capture at the Holtburg cottage doorway + inn 2nd floor +
cellar descent disambiguates H1 (multi-cell iteration), H2 (probe
distance), H3 (poly absent / walkable_hits_sphere rejection) for
ISSUES #83.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:38:53 +02:00
Erik
31da57c94c feat(physics): WalkMissDiagnostic aggregator for ISSUES #83 probe spike
Pure-function aggregator that, given a CellPhysics.Resolved dict and
a foot local position, picks the nearest walkable-eligible polygon
(normal Z >= FloorZ) and reports XY-containment + signed vertical gap.
Also enumerates walkable polys with local-XY bboxes for the one-shot
[floor-polys] cell-load dump.

Pure-function, no behavior change. Wiring to emission sites lands in
the next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:31:39 +02:00
Erik
27c728484d feat(physics): ProbeWalkMissEnabled flag for ISSUES #83 H-disambiguation
Adds a new diagnostic flag for the indoor-walking walk-miss probe
spike per docs/superpowers/specs/2026-05-21-indoor-walk-miss-probe-design.md.
Env var ACDREAM_PROBE_WALK_MISS=1, runtime-toggleable via property.
No DebugPanel mirror — spike-only. Following commits wire the
[walk-miss] and [floor-polys] emissions to this flag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:23:00 +02:00
Erik
0a7ce8fd58 Revert "fix(physics): remove per-frame indoor walkable-plane synthesis"
This reverts commit 9f874f4650.
2026-05-20 09:17:24 +02:00
Erik
9f874f4650 fix(physics): remove per-frame indoor walkable-plane synthesis
The indoor branch of FindEnvCollisions called Transition.TryFindIndoorWalkablePlane
every frame to re-synthesize the ContactPlane after BSP returned OK.
The synthesis routed through BSPQuery.FindWalkableSphere ->
walkable_hits_sphere, which correctly rejects tangent contact via
|dist| > radius - epsilon. For a grounded player standing on or
brushing a floor, the foot sphere is tangent: 99.87% MISS rate per
the 2026-05-20 [cp-write] probe (3150 MISS / 3154 calls). Each MISS
fell through to outdoor terrain backstop, writing a ContactPlane
that's below the indoor floor by ~0.02m (the render Z-bump),
marking the player airborne and triggering the falling-animation
stuck symptom user-reported on 2nd-floor walks.

Fix: delete the synthesis + outdoor-fallthrough from the indoor OK
path. ContactPlane is retained from the prior tick's seed
(PhysicsEngine.ResolveWithTransition:583, init_contact_plane
equivalent) or refreshed by BSP Path 3 (step_sphere_down) / Path 4
(land-on-surface) during the same tick. Matches retail's
BSPTREE::find_collisions OK path (acclient_2013_pseudo_c.txt:323938).

Also deletes:
- Transition.TryFindIndoorWalkablePlane (~104 lines incl. doc-comment)
- INDOOR_WALKABLE_PROBE_DISTANCE constant
- [indoor-walkable] probe log line
- IndoorWalkablePlaneTests.cs (8 tests, the helper's coverage)
- TransitionTypesTests.cs (1 test, also tested the helper)

Net: -491 lines. BSPQuery.FindWalkableSphere + its 5 unit tests
retained as the underlying retail-faithful walkable-finder API
(reachable for spawn-placement / teleport-verification / future
debug needs; its doc-comment is updated to reflect the change).

Closes Bug A in the indoor ContactPlane retention phase.
Spec: docs/superpowers/specs/2026-05-20-indoor-walkable-synthesis-removal-design.md.
Plan: docs/superpowers/plans/2026-05-20-indoor-walkable-synthesis-removal.md.
Predecessor: de8ffde (Bug B, BSP world-origin fix).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:11:04 +02:00
Erik
de8ffde4ca fix(physics): pass cell world-transform to indoor BSP collision
Indoor cell BSP queries at TransitionTypes.cs:1442 were calling
BSPQuery.FindCollisions with Quaternion.Identity + defaulted
Vector3.Zero worldOrigin. Inside the BSP, Path 3 (step_sphere_down)
and Path 4 (land-on-surface) use those params to build the
world-space ContactPlane. Result: planes written with D ~ 0 instead
of the cell's world floor Z (e.g. -94.02 for Holtburg cottages).
320 corrupt CP writes per Holtburg session per the [cp-write] probe.

Fix: decompose cellPhysics.WorldTransform once at the call site,
pass the rotation as localToWorld and the translation as
worldOrigin. Mirrors the existing correct pattern at :1808
(FindObjCollisions, passes obj.Rotation + obj.Position).

Retail oracle: BSPTREE::find_collisions (acclient_2013_pseudo_c.txt:323924)
calls Plane::localtoglobal at :323921 before set_contact_plane.
Our TransformNormal + TransformVertices + BuildWorldPlane chain is
the equivalent — it just needs the right rotation + origin.

Spec: docs/superpowers/specs/2026-05-20-indoor-bsp-worldorigin-fix-design.md.
Plan: docs/superpowers/plans/2026-05-20-indoor-bsp-worldorigin-fix.md.
Evidence: launch-cp-probe.log capture 2026-05-20, [cp-write] probe.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 08:00:16 +02:00
Erik
66de00d09a feat(physics): [cp-write] probe for ContactPlane retention spike
Spike for the next phase of indoor-walking work: confirm/refute the
hypothesis that FindEnvCollisions's indoor branch rewrites the player's
ContactPlane every frame instead of retaining it across frames (retail's
actual behavior). The previous session shipped 6 commits on a wrong
diagnosis; this probe captures the data BEFORE designing the fix.

Two pieces:

1. Add PhysicsDiagnostics.ProbeContactPlaneEnabled flag, gated on
   ACDREAM_PROBE_CONTACT_PLANE=1 (also runtime-toggleable). Helper
   methods LogCpBoolWrite / LogCpPlaneWrite / LogCpCellIdWrite emit one
   [cp-write] line per CP/LKCP field mutation with caller (walked from
   the stack with file+line info) when the value actually changes.

2. Convert the 8 ContactPlane group + LastKnownContactPlane group
   fields on CollisionInfo from public fields to public properties
   with backing fields. Setters call the diagnostic helpers when the
   probe is on; getters/setters are inlined when the flag is off.
   Storage layout unchanged. No call site changes — grep confirmed no
   ref/out passing or sub-field writes.

Build green; tests green at the existing 8-failure baseline (2 BSPStepUp,
6 MotionInterpreter — all unrelated, pre-existing).

Capture command:
  ACDREAM_PROBE_CONTACT_PLANE=1 ACDREAM_PROBE_INDOOR_BSP=1 ACDREAM_DEVTOOLS=1

Spike-only — remove when the retention fix lands and the diagnostic
value is captured in the next phase's spec.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 07:22:55 +02:00
Erik
f845b2241a feat(physics): add [indoor-walkable] probe line
Extends the existing [indoor-bsp] probe surface in FindEnvCollisions
with a per-call [indoor-walkable] line gated on
PhysicsDiagnostics.ProbeIndoorBspEnabled (no new flag). Logs the
synthesized contact plane, the polyId hit, and the signed Z gap (dz)
between foot and plane.

Lets the visual-verification step distinguish "FindWalkableSphere
picked the right polygon" from "FindWalkableSphere returned a miss
and we fell through to outdoor-terrain backstop", which is critical
for triaging any remaining indoor collision oddities after the BSP
port lands.

Runtime-toggleable via the existing DebugPanel "Indoor BSP probe"
checkbox; zero cost when disabled.

Spec: docs/superpowers/specs/2026-05-19-indoor-walkable-plane-bsp-port-design.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 22:02:06 +02:00
Erik
7c516edd7b fix(physics): document adjustedCenter discard + restore wall-poly test
Code review feedback on Task 3 commit 91b29d1:

- TryFindIndoorWalkablePlane: comment explaining why FindWalkableSphere's
  adjustedCenter out param is intentionally discarded (ValidateWalkable
  recomputes contact geometry from plane + foot position, consistent
  with the outdoor terrain path).
- IndoorWalkablePlaneTests: new TryFindIndoorWalkablePlane_WallPolyInBsp_ReturnsFalse
  restores integration-level coverage that the renamed NoBsp_ReturnsFalse
  lost. Verifies WalkableAllowance gate rejects a wall polygon in the
  cell BSP. Steep-poly rejection is also covered at the BSPQuery layer
  by FindWalkableSphere_SteepPoly_RejectedByWalkableAllowance.

No behavior change. Build clean; all related tests pass; same 8
pre-existing failures.

Spec: docs/superpowers/specs/2026-05-19-indoor-walkable-plane-bsp-port-design.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 21:58:53 +02:00
Erik
91b29d1a89 fix(physics): route indoor walkable-plane synthesis through retail BSP walker
TryFindIndoorWalkablePlane (Phase 2 commit eb0f772) used a linear
first-match XY scan of cellPhysics.Resolved with no Z-proximity test.
For any cell with two walkable polys overlapping in XY at different Z
(cellars, 2nd floors, balconies, stairs spanning floors), it returned
whichever polygon came first in dictionary order — typically the upper
floor when descending, causing the player to be reported below the
synthesized plane → ValidateWalkable fails → falling-stuck. Symptoms
reported by user 2026-05-19: cannot descend into cellar; cannot walk
on 2nd floor; "invisible obstacles at certain spots" (suspected
cascade from wrong-Z ContactPlane misrouting the resolver state).

Fix: route through BSPQuery.FindWalkableSphere (added previous commit),
which wraps the existing retail-faithful FindWalkableInternal
(BSPNODE::find_walkable + BSPLEAF::find_walkable port). Adds a
sphereRadius parameter to TryFindIndoorWalkablePlane so the foot
sphere is built with the actual entity radius rather than a guess.
WalkableAllowance is save/restored via try/finally so the slope
threshold used by walkable_hits_sphere doesn't leak back to the
resolver. Method becomes an instance method (was static) to access
this.SpherePath.

Deletes the now-dead PointInPolygonXY helper.

Updates IndoorWalkablePlaneTests.cs: all TryFindIndoorWalkablePlane
test fixtures now include a PhysicsBSPTree leaf node (required by
the new routing path), calls pass sphereRadius, and the PointInPolygonXY
tests are removed (method deleted). Adds TransitionTypesTests.cs with
an integration test covering two-overlapping-floors selection AND
WalkableAllowance preservation.

Closes (pending visual verification): ISSUES #83.
Spec: docs/superpowers/specs/2026-05-19-indoor-walkable-plane-bsp-port-design.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 21:47:49 +02:00
Erik
86ecdf9ee1 fix(physics): tighten FindWalkableSphere test assertions + header
Code review feedback on Task 2 commit 7f55e14:

- Tests 1 and 2 now assert on adjustedCenter.Z (was the wrapper's
  primary behavioral contract — sphere placed on polygon plane —
  but it was unverified). Math derived from AdjustSphereToPlane:
  iDist = (dpPos - radius) / dpMove; new center = center - movement * iDist.
- Test 2 also gains the hitPoly.Plane.Normal.Z assertion that
  Test 1 already had.
- Test 4 comment slope-angle clarification.
- BSPQuery.cs FindWalkableSphere section header now notes this is
  not a direct retail port (it wraps BSPNODE::find_walkable +
  BSPLEAF::find_walkable via the existing FindWalkableInternal).

No behavior change. Build clean; 4/4 tests pass; same 8 pre-existing
failures.

Spec: docs/superpowers/specs/2026-05-19-indoor-walkable-plane-bsp-port-design.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 21:41:13 +02:00
Erik
7f55e14cd7 feat(physics): add BSPQuery.FindWalkableSphere wrapper
Thin public wrapper over the existing retail-faithful
FindWalkableInternal (BSPNODE::find_walkable + BSPLEAF::find_walkable
port). Probes downward by probeDistance along up, returns the closest
walkable polygon the sphere would rest on plus the adjusted center.

Will replace Transition.TryFindIndoorWalkablePlane's linear first-match
scan (next commit). The wrapper is callable from any "stand here, find
my floor" use case; current intent is indoor walkable-plane synthesis.

4 unit tests covering: two-floors-foot-between (sphere overlapping lower
floor), only-upper-floor-foot-above (sphere overlapping upper floor),
no-walkable-in-probe-range (sphere out of overlap distance for all
polygons), steep-poly-rejected-by-WalkableAllowance. Note: find_walkable
requires sphere to overlap the polygon plane (|dist| <= radius);
the tests use geometry that exercises this correctly, unlike the spec's
illustrative values which assumed a "nearest below" scan.

Spec: docs/superpowers/specs/2026-05-19-indoor-walkable-plane-bsp-port-design.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 21:33:27 +02:00
Erik
ff548b962c refactor(physics): expose hitPolyId from FindWalkableInternal
Adds a ref ushort hitPolyId parameter to FindWalkableInternal so callers
can identify which polygon was hit. The leaf branch already iterates
foreach (ushort polyId in node.Polygons); this surfaces it.

No behavior change. Existing callers (StepSphereDown, Path 4 Collide)
pass a discard local. The new BSPQuery.FindWalkableSphere wrapper
(next commit) will consume it.

Prep for indoor walkable-plane BSP port — see spec
docs/superpowers/specs/2026-05-19-indoor-walkable-plane-bsp-port-design.md
2026-05-19 21:22:40 +02:00
Erik
eb0f772f0f fix(physics): Phase 2 — synthesize indoor walkable plane from cell floor
When the indoor cell-BSP query returns OK (no wall collision), the player
is standing on a floor poly inside the cell. Previously the code fell
through to outdoor terrain (SampleTerrainWalkable + ValidateWalkable),
which used the OUTDOOR terrain plane — below the indoor floor due to the
+0.02f Z-bump applied for render z-fight prevention. ValidateWalkable
saw the player 0.5m above the outdoor plane → marked them as airborne
→ walkable=False → falling animation, never recovers.

Adds TryFindIndoorWalkablePlane (internal static for testability): scans
the cell's resolved physics polys for a walkable floor poly (normal.Z >=
0.6664, walkable-slope threshold matching retail) under the player's XY,
transforms its plane + vertices to world space via WorldTransform, and
calls ValidateWalkable with the indoor plane. Adds PointInPolygonXY
(ray-casting even-odd rule, ignores Z). Both are wired just after the
BSP OK branch in FindEnvCollisions; outdoor terrain remains a defensive
backstop if no floor poly is found under the player indoors (rare).

Matches retail's CEnvCell::find_env_collisions behavior: no fall-through
to terrain when the cell BSP successfully completes a query.

Evidence: launch-phase2-verify5.log captured 12,141 walkable=False
events during an indoor session where the player never managed to walk
back outdoor through a door — they got stuck against the indoor wall
and the resolver never re-established a walkable contact plane.

Adds 13 unit tests in IndoorWalkablePlaneTests.cs covering:
- player over floor poly (returns true, plane normal up, plane at correct Z)
- player outside poly XY (returns false)
- no walkable polys (returns false)
- empty Resolved dict (returns false)
- cell with world translation (plane + vertices in world space)
- PointInPolygonXY cases (centre, near corner, on boundary, outside, Z ignored)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:13:13 +02:00