feat(physics): Phase 2 — port CellTransit + wire into ResolveCellId

New CellTransit static class ports retail's portal-graph cell traversal:
- FindTransitCellsSphere — indoor portal-neighbour walk
- AddAllOutsideCells     — outdoor 24m grid expansion
- FindCellList           — top-level driver (BFS through portals;
                           PointInsideCellBsp for final containment)

PhysicsEngine.ResolveOutdoorCellId renamed to ResolveCellId. Body
rewritten: indoor seeds delegate to CellTransit.FindCellList (portal-
graph BFS + BSP containment test); outdoor seeds keep the landblock
terrain grid lookup from the original implementation (preserving the
L.2e prefix-preservation fix). Signature extended with sphereRadius
parameter (needed by the sphere-vs-portal-plane test). Three call
sites updated (PhysicsEngine x2, TransitionTypes x1).

BSPQuery.PointInsideCellBsp retyped from PhysicsBSPNode? to CellBSPNode?
— the function operates on the cell-BSP tree (CellPhysics.CellBSP.Root
is a CellBSPNode). The previous PhysicsBSPNode typing was dead code, so
retype is safe.

Deletes the Phase D ResolveOutdoorCellIdTests.cs file. New ResolveCellIdTests
covers the equivalent contracts (fallback zero, outdoor seed with no
landblock).

Outdoor->indoor entry (check_building_transit) is stubbed pending the
BuildingPhysics infrastructure landing in the next commit.

Spec: docs/superpowers/specs/2026-05-19-indoor-portal-cell-tracking-design.md
Plan: docs/superpowers/plans/2026-05-19-indoor-portal-cell-tracking.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-05-19 17:14:04 +02:00
parent 1969c55823
commit aad697602e
8 changed files with 472 additions and 182 deletions

View file

@ -928,16 +928,24 @@ public static class BSPQuery
// =========================================================================
/// <summary>
/// BSPNode.point_inside_cell_bsp — test if a 3D point is inside the cell BSP.
/// BSPNode.point_inside_cell_bsp — recursive cell-BSP point containment test.
///
/// <para>
/// Follows the front side of each splitting plane. A point is inside when it
/// reaches a front leaf or null PosNode (solid interior).
/// Indoor walking Phase 2 (2026-05-19): retyped from PhysicsBSPNode? to
/// CellBSPNode? — the function operates on the CellBSP tree (which is
/// distinct from the PhysicsBSP tree). The dead-code typing was wrong;
/// no callers existed, so the retype is safe.
/// </para>
///
/// <para>
/// Walks down the tree following splitting planes; returns true when the
/// point reaches a front leaf or null PosNode (solid interior). Behind
/// any splitting plane → outside.
/// </para>
///
/// <para>ACE: BSPNode.cs point_inside_cell_bsp.</para>
/// </summary>
public static bool PointInsideCellBsp(PhysicsBSPNode? node, Vector3 point)
public static bool PointInsideCellBsp(CellBSPNode? node, Vector3 point)
{
if (node is null) return true;
if (node.Type == BSPNodeType.Leaf) return true;

View file

@ -0,0 +1,243 @@
using System.Collections.Generic;
using System.Numerics;
using DatReaderWriter.Types;
namespace AcDream.Core.Physics;
/// <summary>
/// Indoor walking Phase 2 (2026-05-19). Portal-graph cell traversal,
/// ported from retail's <c>CObjCell::find_cell_list</c> family
/// (sphere variant for the player's single foot sphere).
///
/// <para>
/// Replaces Phase D's AABB containment. Uses the cell BSP for retail-
/// faithful point-in-cell tests via
/// <see cref="BSPQuery.PointInsideCellBsp"/>. Walks the portal graph
/// starting from a given current cell to find which cells a moving
/// sphere overlaps.
/// </para>
///
/// <para>
/// Reference pseudocode:
/// <c>docs/research/acclient_indoor_transitions_pseudocode.md</c>
/// (2026-04-13). Retail decomp: <c>CEnvCell::find_transit_cells</c>
/// (sphere variant) at <c>acclient_2013_pseudo_c.txt</c>.
/// </para>
/// </summary>
public static class CellTransit
{
/// <summary>
/// Small radius padding matching retail's <c>EPSILON</c> usage in the
/// sphere-plane distance test (research doc §"EnvCell.find_transit_cells").
/// </summary>
private const float EPSILON = 0.02f;
/// <summary>
/// Indoor portal-neighbour expansion. For each portal of
/// <paramref name="currentCell"/>, test whether the sphere overlaps
/// the portal polygon's plane in cell-local space. If so, add the
/// neighbour cell to <paramref name="candidates"/>.
///
/// <para>
/// Ported from <c>CEnvCell::find_transit_cells</c> (sphere variant)
/// per the pseudocode doc §"EnvCell.find_transit_cells (sphere variant)".
/// </para>
/// </summary>
public static void FindTransitCellsSphere(
PhysicsDataCache cache,
CellPhysics currentCell,
uint currentCellId,
Vector3 worldSphereCenter,
float sphereRadius,
HashSet<uint> candidates,
out bool exitOutside)
{
exitOutside = false;
if (currentCell.PortalPolygons is null) return;
uint lbPrefix = currentCellId & 0xFFFF0000u;
float rad = sphereRadius + EPSILON;
// Cell-local sphere center.
var localCenter = Vector3.Transform(worldSphereCenter, currentCell.InverseWorldTransform);
foreach (var portal in currentCell.Portals)
{
if (!currentCell.PortalPolygons.TryGetValue(portal.PolygonId, out var poly))
continue;
// Signed distance from sphere center to portal plane (cell-local).
float dist = Vector3.Dot(localCenter, poly.Plane.Normal) + poly.Plane.D;
if (portal.OtherCellId == 0xFFFF)
{
// Exit portal. Sphere must straddle the plane.
if (dist > -rad && dist < rad)
exitOutside = true;
continue;
}
uint otherId = lbPrefix | portal.OtherCellId;
// Conservative add: the sphere is near the portal plane and on the
// outward side (per PortalSide). This is the load-hint branch from
// the research doc. A more retail-faithful path would call
// CellBSP.sphere_intersects_cell on the neighbour — deferred.
if (portal.PortalSide ? dist > -rad : dist < rad)
candidates.Add(otherId);
}
}
/// <summary>
/// Outdoor neighbour expansion. Ported from
/// <c>CLandCell::add_all_outside_cells</c> (sphere variant) per the
/// pseudocode doc §"LandCell.add_all_outside_cells (sphere variant)".
///
/// <para>
/// The 24×24m landcell grid: a landblock is 8×8 cells. Cell index
/// within a landblock is computed from local X/Y mod 24. The sphere
/// adds the primary cell plus up to 3 neighbours when the radius
/// reaches a cell boundary.
/// </para>
/// </summary>
public static void AddAllOutsideCells(
Vector3 worldSphereCenter,
float sphereRadius,
uint currentCellId,
HashSet<uint> candidates)
{
const float CellSize = 24f;
uint lbPrefix = currentCellId & 0xFFFF0000u;
float lbXf = ((lbPrefix >> 24) & 0xFFu) * 192f;
float lbYf = ((lbPrefix >> 16) & 0xFFu) * 192f;
float localX = worldSphereCenter.X - lbXf;
float localY = worldSphereCenter.Y - lbYf;
float cellLocalX = localX % CellSize;
float cellLocalY = localY % CellSize;
float minRad = sphereRadius;
float maxRad = CellSize - sphereRadius;
int gridX = (int)(localX / CellSize);
int gridY = (int)(localY / CellSize);
if (gridX < 0 || gridX >= 8 || gridY < 0 || gridY >= 8) return;
AddOutsideCell(candidates, lbPrefix, gridX, gridY);
if (cellLocalX > maxRad)
{
AddOutsideCell(candidates, lbPrefix, gridX + 1, gridY);
if (cellLocalY > maxRad) AddOutsideCell(candidates, lbPrefix, gridX + 1, gridY + 1);
if (cellLocalY < minRad) AddOutsideCell(candidates, lbPrefix, gridX + 1, gridY - 1);
}
if (cellLocalX < minRad)
{
AddOutsideCell(candidates, lbPrefix, gridX - 1, gridY);
if (cellLocalY > maxRad) AddOutsideCell(candidates, lbPrefix, gridX - 1, gridY + 1);
if (cellLocalY < minRad) AddOutsideCell(candidates, lbPrefix, gridX - 1, gridY - 1);
}
if (cellLocalY > maxRad) AddOutsideCell(candidates, lbPrefix, gridX, gridY + 1);
if (cellLocalY < minRad) AddOutsideCell(candidates, lbPrefix, gridX, gridY - 1);
}
private static void AddOutsideCell(HashSet<uint> candidates, uint lbPrefix, int gridX, int gridY)
{
if (gridX < 0 || gridX >= 8 || gridY < 0 || gridY >= 8) return;
// Cell index within landblock: row-major (X * 8 + Y) + 1.
uint low = (uint)(gridX * 8 + gridY + 1);
candidates.Add(lbPrefix | low);
}
/// <summary>
/// Top-level cell-tracking driver, ported from retail's
/// <c>CObjCell::find_cell_list</c> (sphere variant).
///
/// <para>
/// Walks the portal graph from <paramref name="currentCellId"/>,
/// finds the cell whose <see cref="CellPhysics.CellBSP"/> contains
/// the sphere center, and returns its full id (landblock-prefixed).
/// Falls back to <paramref name="currentCellId"/> when no candidate
/// matches.
/// </para>
///
/// <para>
/// Pseudocode reference:
/// <c>docs/research/acclient_indoor_transitions_pseudocode.md</c>
/// §"Overall Driver: find_cell_list".
/// </para>
/// </summary>
public static uint FindCellList(
PhysicsDataCache cache,
Vector3 worldSphereCenter,
float sphereRadius,
uint currentCellId)
{
var candidates = new HashSet<uint>();
uint currentLow = currentCellId & 0xFFFFu;
if (currentLow >= 0x0100u)
{
// Indoor seed.
var currentCell = cache.GetCellStruct(currentCellId);
if (currentCell is null) return currentCellId;
candidates.Add(currentCellId);
// BFS the portal graph (one hop per pass — usually 1-2 passes is enough).
var pending = new Queue<uint>();
pending.Enqueue(currentCellId);
int maxIterations = 16; // hard cap; portal graphs are small
while (pending.Count > 0 && maxIterations-- > 0)
{
uint cellId = pending.Dequeue();
var cell = cache.GetCellStruct(cellId);
if (cell is null) continue;
var sizeBefore = candidates.Count;
FindTransitCellsSphere(
cache, cell, cellId, worldSphereCenter, sphereRadius,
candidates, out bool exitOutside);
if (candidates.Count > sizeBefore)
{
// Snapshot the new candidates to avoid mutating during iteration.
foreach (var c in candidates)
{
if (c != cellId) // skip seed
pending.Enqueue(c);
}
}
if (exitOutside)
{
// Add neighbour outdoor cells too.
AddAllOutsideCells(worldSphereCenter, sphereRadius, currentCellId, candidates);
}
}
}
else
{
// Outdoor seed.
AddAllOutsideCells(worldSphereCenter, sphereRadius, currentCellId, candidates);
// Outdoor→indoor entry (CheckBuildingTransit) wires in a follow-up commit.
}
// Containment test: for each candidate, transform worldSphereCenter to
// local and test PointInsideCellBsp.
foreach (uint candId in candidates)
{
var cand = cache.GetCellStruct(candId);
if (cand?.CellBSP?.Root is null) continue;
var local = Vector3.Transform(worldSphereCenter, cand.InverseWorldTransform);
if (BSPQuery.PointInsideCellBsp(cand.CellBSP.Root, local))
return candId;
}
// No cell contained the sphere center. Stay in the input cell.
return currentCellId;
}
}

View file

@ -230,39 +230,42 @@ public sealed class PhysicsEngine
}
/// <summary>
/// Resolve a position's CellId. Falls back to outdoor terrain landcell
/// resolution or trusts an already-indoor fallbackCellId.
/// Indoor walking Phase 2 (2026-05-19). Resolves the cell id for a
/// given world position via retail's portal-graph traversal for indoor
/// cells, or via terrain grid lookup for outdoor cells.
///
/// <para>
/// Phase D (2026-05-19) previously used an AABB containment check
/// (<c>TryFindContainingCell</c>) to promote the player into an indoor
/// EnvCell. Phase 2 (2026-05-19) removes that AABB shortcut; the
/// portal-graph <c>CellTransit</c> traversal (next subagent) replaces it
/// with retail-faithful BSP point-in-cell tests.
/// Indoor seed: delegates to <see cref="CellTransit.FindCellList"/> which
/// BFS-walks the portal graph and uses <see cref="BSPQuery.PointInsideCellBsp"/>
/// for containment. This replaces Phase D's AABB shortcut.
/// </para>
///
/// <para>
/// Also fixes a pre-existing prefix-preservation bug: the outdoor branch
/// now always applies the matched landblock's high-16 prefix even when
/// the input <paramref name="fallbackCellId"/> arrived bare-low-byte
/// (the L.2e finding from CLAUDE.md).
/// Outdoor seed: uses the registered landblock terrain grid to compute
/// the correct prefixed cell ID, preserving the pre-existing outdoor
/// resolution behavior (the L.2e prefix-preservation fix).
/// </para>
///
/// <para>
/// Design: <c>docs/superpowers/specs/2026-05-19-indoor-portal-cell-tracking-design.md</c>
/// </para>
/// </summary>
internal uint ResolveOutdoorCellId(Vector3 worldPos, uint fallbackCellId)
internal uint ResolveCellId(Vector3 worldPos, float sphereRadius, uint fallbackCellId)
{
if (fallbackCellId == 0)
return 0;
if (fallbackCellId == 0) return 0;
// Pre-existing: if the caller already passes an indoor CellId AND
// the player isn't in any cached EnvCell, trust the caller. This
// preserves behaviour for indoor cells whose physics hasn't been
// cached yet (rare; should be impossible in steady state).
uint fallbackLow = fallbackCellId & 0xFFFFu;
if (fallbackLow >= 0x0100u)
return fallbackCellId;
// Outdoor terrain resolution. Always applies the matched landblock's
// prefix — fixes the bare-low-byte preservation bug (L.2e).
if (fallbackLow >= 0x0100u)
{
// Indoor seed: use portal-graph traversal.
if (DataCache is null) return fallbackCellId;
return CellTransit.FindCellList(DataCache, worldPos, sphereRadius, fallbackCellId);
}
// Outdoor seed: use terrain grid to compute the prefixed cell id.
// Preserves the L.2e prefix-preservation fix (always apply the matched
// landblock's high-16 prefix even when fallbackCellId arrived bare-low-byte).
foreach (var kvp in _landblocks)
{
var lb = kvp.Value;
@ -743,7 +746,7 @@ public sealed class PhysicsEngine
return new ResolveResult(
sp.CheckPos,
ResolveOutdoorCellId(sp.CheckPos, sp.CheckCellId),
ResolveCellId(sp.CheckPos, sphereRadius, sp.CheckCellId),
onGround,
collisionNormalValid,
collisionNormal);
@ -761,7 +764,7 @@ public sealed class PhysicsEngine
uint partialCellId = sp.CheckCellId != 0 ? sp.CheckCellId : cellId;
return new ResolveResult(
sp.CheckPos,
ResolveOutdoorCellId(sp.CheckPos, partialCellId),
ResolveCellId(sp.CheckPos, sphereRadius, partialCellId),
partialOnGround,
collisionNormalValid,
collisionNormal);

View file

@ -1178,13 +1178,13 @@ public sealed class Transition
var sp = SpherePath;
var ci = CollisionInfo;
uint resolvedOutdoorCellId = engine.ResolveOutdoorCellId(sp.CheckPos, sp.CheckCellId);
if (resolvedOutdoorCellId != sp.CheckCellId)
sp.SetCheckPos(sp.CheckPos, resolvedOutdoorCellId);
Vector3 footCenter = sp.GlobalSphere[0].Origin;
float sphereRadius = sp.GlobalSphere[0].Radius;
uint resolvedOutdoorCellId = engine.ResolveCellId(sp.CheckPos, sphereRadius, sp.CheckCellId);
if (resolvedOutdoorCellId != sp.CheckCellId)
sp.SetCheckPos(sp.CheckPos, resolvedOutdoorCellId);
// ── Indoor cell BSP collision ────────────────────────────────────
// If the player is in an indoor cell (low 16 bits >= 0x0100),
// query the CellStruct's PhysicsBSP for wall/floor/ceiling collision.