using System.Collections.Generic; using System.Numerics; using DatReaderWriter.Types; namespace AcDream.Core.Physics; /// /// Indoor walking Phase 2 (2026-05-19). Portal-graph cell traversal, /// ported from retail's CObjCell::find_cell_list family /// (sphere variant for the player's path spheres). /// /// /// Replaces Phase D's AABB containment. Uses the cell BSP for retail- /// faithful point-in-cell tests via /// . Walks the portal graph /// starting from a given current cell to find which cells a moving /// sphere overlaps. /// /// /// /// Reference pseudocode: /// docs/research/acclient_indoor_transitions_pseudocode.md /// (2026-04-13). Retail decomp: CEnvCell::find_transit_cells /// (sphere variant) at acclient_2013_pseudo_c.txt. /// /// public static class CellTransit { /// /// Small radius padding matching retail's EPSILON usage in the /// sphere-plane distance test (research doc §"EnvCell.find_transit_cells"). /// private const float EPSILON = 0.02f; /// /// Indoor portal-neighbour expansion. For each portal of /// , test whether the sphere overlaps /// the portal polygon's plane in cell-local space. If so, add the /// neighbour cell to . /// /// /// Ported from CEnvCell::find_transit_cells (sphere variant) /// per the pseudocode doc §"EnvCell.find_transit_cells (sphere variant)". /// /// public static void FindTransitCellsSphere( PhysicsDataCache cache, CellPhysics currentCell, uint currentCellId, Vector3 worldSphereCenter, float sphereRadius, ICollection candidates, out bool exitOutside) { var spheres = new[] { new Sphere { Origin = worldSphereCenter, Radius = sphereRadius, }, }; FindTransitCellsSphere( cache, currentCell, currentCellId, spheres, spheres.Length, candidates, out exitOutside); } /// /// Multi-sphere form used by retail's CObjCell::find_cell_list: /// pass sphere_path.num_sphere and sphere_path.global_sphere. /// Any sphere can trigger a portal neighbor or outdoor exit. /// public static void FindTransitCellsSphere( PhysicsDataCache cache, CellPhysics currentCell, uint currentCellId, IReadOnlyList worldSpheres, int numSpheres, ICollection candidates, out bool exitOutside) { exitOutside = false; uint lbPrefix = currentCellId & 0xFFFF0000u; int sphereCount = EffectiveSphereCount(worldSpheres, numSpheres); if (currentCell.PortalPolygons is null || sphereCount == 0) return; foreach (var portal in currentCell.Portals) { if (!currentCell.PortalPolygons.TryGetValue(portal.PolygonId, out var poly)) continue; if (portal.OtherCellId == 0xFFFF) { // A6.P5 (2026-05-25): exit portals add outdoor cells // UNCONDITIONALLY, by topology — not by sphere-plane overlap. // // Retail's CObjCell::find_cell_list (acclient_2013_pseudo_c.txt // :308742-308869) walks vtable[0x80] on every cell already in // the array and adds reachable cells without testing the // sphere against each portal plane. The straddle check we // had here gated outdoor inclusion on the sphere physically // overlapping the EXIT portal — which fails to fire when: // a) the sphere is in a SIBLING indoor cell that BFS- // expanded to this one (sphere is geographically near // the doorway region, just not at THIS cell's exit // portal plane); OR // b) the per-tick target moves the sphere across the // portal plane on one tick but not the next, producing // intermittent visibility from the same position. // // Pre-fix bug: cottage doors at outdoor cells were invisible // from indoor cells during cell-crossing substeps (live // capture 2026-05-25; over-penetration test in // CellTransitTests.A6P5_BuildCellSetFromIndoorStart_...). // // Post-fix: any cell visited by BFS that has at least one // exit portal contributes exitOutside=true regardless of // sphere position. AddAllOutsideCells fires once per BFS // (deduped in BuildCellSetAndPickContaining). exitOutside = true; continue; } uint otherId = lbPrefix | portal.OtherCellId; // Retail CEnvCell::find_transit_cells first asks the loaded // neighbour cell whether the sphere intersects its CellBSP. // The portal-plane side test is only the unloaded-cell load hint. var otherCell = cache.GetCellStruct(otherId); if (otherCell?.CellBSP?.Root is not null) { for (int i = 0; i < sphereCount; i++) { var sphere = worldSpheres[i]; var otherLocalCenter = Vector3.Transform( sphere.Origin, otherCell.InverseWorldTransform); bool hit = BSPQuery.SphereIntersectsCellBsp( otherCell.CellBSP.Root, otherLocalCenter, sphere.Radius); if (hit) { candidates.Add(otherId); break; } } continue; } // Conservative unloaded-cell hint: the sphere is near the portal // plane and on the outward side (per PortalSide). for (int i = 0; i < sphereCount; i++) { var sphere = worldSpheres[i]; float rad = sphere.Radius + EPSILON; var localCenter = Vector3.Transform( sphere.Origin, currentCell.InverseWorldTransform); float dist = Vector3.Dot(localCenter, poly.Plane.Normal) + poly.Plane.D; bool hit = portal.PortalSide ? dist > -rad : dist < rad; if (hit) { candidates.Add(otherId); break; } } } } /// /// Outdoor neighbour expansion. Ported from /// CLandCell::add_all_outside_cells (sphere variant, /// pc:317499 @0x00533630) per /// docs/research/2026-06-09-landdefs-outside-cells-pseudocode.md. /// /// /// Retail runs this in the GLOBAL landcell grid ( /// lcoords, 0..2039 across the whole map): adjust_to_outside re-seats /// the (cell, position) pair onto the landcell actually under the sphere — /// crossing landblock boundaries when floor(local/24) leaves the /// current block's 8×8 grid — and check_add_cell_boundary adds up to /// 3 neighbour cells (strict >/< against the sphere radius), each id /// re-derived from its own global lcoord. Issue #106: the pre-fix port /// clamped everything to the current landblock's grid, so the candidate set /// emptied the moment the player stepped over a boundary and membership /// froze on the last in-block cell. /// /// /// /// is in the floating world frame /// (anchor landblock at origin — the convention every physics caller uses); /// is the current cell's landblock /// world origin (SW corner; ), /// which converts it to retail's block-local frame. Pass /// when the current block IS the anchor — the /// pre-#106 behavior, and what the A6.P4 (2026-05-24) "landblock-local /// coords" convention actually meant. /// /// /// /// False when adjust_to_outside rejects the position (map edge / /// invalid cell id) — retail breaks out of the sphere loop on that. /// public static bool AddAllOutsideCells( Vector3 worldSphereCenter, float sphereRadius, uint currentCellId, Vector3 currentBlockOrigin, ICollection candidates) { // Retail's position is block-local to the current cell's landblock. var center = worldSphereCenter - currentBlockOrigin; uint cellId = currentCellId; if (!LandDefs.AdjustToOutside(ref cellId, ref center)) return false; if (!LandDefs.GidToLcoord(cellId, out int lx, out int ly)) return false; AddOutsideCell(candidates, lx, ly); // check_add_cell_boundary (pc:317229 @0x00533260): the point within the // 24 m cell, from the adjust_to_outside-normalized block-local center // (always [0, 192) post-adjust; floor-mod for safety). Strict >/< — // a sphere exactly tangent to a boundary does NOT add the neighbour. float pointX = center.X - MathF.Floor(center.X / LandDefs.CellLength) * LandDefs.CellLength; float pointY = center.Y - MathF.Floor(center.Y / LandDefs.CellLength) * LandDefs.CellLength; float minRad = sphereRadius; float maxRad = LandDefs.CellLength - sphereRadius; if (pointX > maxRad) { AddOutsideCell(candidates, lx + 1, ly); if (pointY > maxRad) AddOutsideCell(candidates, lx + 1, ly + 1); if (pointY < minRad) AddOutsideCell(candidates, lx + 1, ly - 1); } if (pointX < minRad) { AddOutsideCell(candidates, lx - 1, ly); if (pointY > maxRad) AddOutsideCell(candidates, lx - 1, ly + 1); if (pointY < minRad) AddOutsideCell(candidates, lx - 1, ly - 1); } if (pointY > maxRad) AddOutsideCell(candidates, lx, ly + 1); if (pointY < minRad) AddOutsideCell(candidates, lx, ly - 1); return true; } /// /// Multi-sphere outdoor expansion. Retail's sphere variant loops every /// path sphere and adds the outdoor landcells touched by any of them; /// an adjust_to_outside failure BREAKS the loop (pc:533699). /// public static void AddAllOutsideCells( IReadOnlyList worldSpheres, int numSpheres, uint currentCellId, Vector3 currentBlockOrigin, ICollection candidates) { int sphereCount = EffectiveSphereCount(worldSpheres, numSpheres); for (int i = 0; i < sphereCount; i++) { var sphere = worldSpheres[i]; if (!AddAllOutsideCells(sphere.Origin, sphere.Radius, currentCellId, currentBlockOrigin, candidates)) break; } } private static void AddOutsideCell(ICollection candidates, int lx, int ly) { // CLandCell::add_outside_cell (pc:317056 @0x00532ec0): map-bounds check, // then lcoord_to_gid — NO same-block filter (ACE's add_cell_block // "FIXME!" guard is an ACE divergence, not retail). The block id is // re-derived from the global lcoord, so neighbour-landblock cells come // out with the neighbour's prefix. uint gid = LandDefs.LcoordToGid(lx, ly); if (gid != 0u) candidates.Add(gid); } /// /// Outdoor→indoor entry path. Ported from retail's /// BuildingObj::find_building_transit_cells + /// EnvCell::check_building_transit. For each portal of the /// outdoor building, look up the destination interior cell and test /// whether the sphere overlaps it via /// . If so, add the /// interior cell to . /// /// /// Issue #89 closed (2026-05-20): uses retail's radius-aware /// CCellStruct::sphere_intersects_cell /// (acclient_2013_pseudo_c.txt:317666) ported as /// . Promotes CellId to /// the interior cell the moment ANY part of the foot-sphere crosses /// the cell boundary — matches retail entry timing exactly and /// closes the login-inside-inn classification race where the player /// would briefly be classified outdoor and walk through walls. /// /// public static void CheckBuildingTransit( PhysicsDataCache cache, BuildingPhysics building, Vector3 worldSphereCenter, float sphereRadius, ICollection candidates) { foreach (var portal in building.Portals) { var otherCell = cache.GetCellStruct(portal.OtherCellId); if (otherCell?.CellBSP?.Root is null) { if (PhysicsDiagnostics.ProbeIndoorBspEnabled) { string reason = otherCell is null ? "cell not cached" : "CellBSP null"; Console.WriteLine(System.FormattableString.Invariant( $"[check-bldg] portal->0x{portal.OtherCellId:X8} skipped: {reason}")); } continue; } // Sphere center in the OTHER cell's local space. // Issue #89 closed (2026-05-20): use radius-aware sphere-overlap // (matches retail's CCellStruct::sphere_intersects_cell at // acclient_2013_pseudo_c.txt:317666) instead of point-only. This // promotes the player's CellId to the interior cell the moment // ANY part of the foot-sphere crosses the cell boundary — the // entry-side counterpart to issue #90's sticky-stay fix. Without // it, login-inside-the-inn keeps the player classified outdoor // until they walk further in (sphere center crosses), letting // them run through exterior walls on the way out. var localCenter = Vector3.Transform(worldSphereCenter, otherCell.InverseWorldTransform); bool inside = BSPQuery.SphereIntersectsCellBsp(otherCell.CellBSP.Root, localCenter, sphereRadius); if (PhysicsDiagnostics.ProbeIndoorBspEnabled) { Console.WriteLine(System.FormattableString.Invariant( $"[check-bldg] portal->0x{portal.OtherCellId:X8} wpos=({worldSphereCenter.X:F3},{worldSphereCenter.Y:F3},{worldSphereCenter.Z:F3}) lpos=({localCenter.X:F3},{localCenter.Y:F3},{localCenter.Z:F3}) r={sphereRadius:F3} inside={inside}")); } if (inside) { candidates.Add(portal.OtherCellId); } } } /// /// Verbatim port of CEnvCell::find_visible_child_cell /// (acclient_2013_pseudo_c.txt:311397). Returns the cell whose cell-BSP /// point_in_cell contains , checking the /// start cell first (:311402), then — when is /// true (retail arg3 != 0, :311444) — the start's stab_list /// (), else (arg3 == 0, :311411) /// its direct portal neighbours. Returns 0 when no cell contains the point /// (retail return 0 at :311469). /// /// /// Sibling of (retail find_cell_list) — both /// resolve membership from the cell graph via . /// Used by CPhysicsObj::AdjustPosition (pc:280028, arg5 = 1 → /// stab-list mode) to seat the camera sweep's start cell at the head-pivot. /// /// /// /// acdream adaptation (matches at line 518): a cell /// with no hydrated cannot run /// point_in_cell, so it is treated as NOT containing the point (skipped), /// rather than letting 's null-node /// "inside" default make it spuriously claim every point. /// /// public static uint FindVisibleChildCell( PhysicsDataCache cache, uint startCellId, Vector3 worldPoint, bool useStabList) { var start = cache.GetCellStruct(startCellId); if (start is null) return 0u; // this->point_in_cell(point) → return this (:311402-311405) if (PointInCell(start, worldPoint)) return startCellId; if (useStabList) { // arg3 != 0 → iterate stab_list, GetVisible + point_in_cell (:311444-311465) foreach (uint id in start.VisibleCellIds) if (PointInCell(cache.GetCellStruct(id), worldPoint)) return id; } else { // arg3 == 0 → iterate direct portals, GetOtherCell + point_in_cell (:311411-311434) foreach (var portal in start.Portals) if (PointInCell(cache.GetCellStruct(portal.OtherCellId), worldPoint)) return portal.OtherCellId; } return 0u; } /// /// CEnvCell::point_in_cell (cell-BSP vtable[0x84]) against a world point: /// transform to the cell's local frame, then . /// A cell with no hydrated returns false (see /// 's adaptation note). /// private static bool PointInCell(CellPhysics? cell, Vector3 worldPoint) { if (cell?.CellBSP?.Root is null) return false; var local = Vector3.Transform(worldPoint, cell.InverseWorldTransform); return BSPQuery.PointInsideCellBsp(cell.CellBSP.Root, local); } /// /// Top-level cell-tracking driver, ported from retail's /// CObjCell::find_cell_list (sphere variant). /// /// /// Walks the portal graph from , /// finds the cell whose contains /// the sphere center, and returns its full id (landblock-prefixed). /// Falls back to when no candidate /// matches. The candidate set built internally is discarded; use /// to recover it. /// /// /// /// Pseudocode reference: /// docs/research/acclient_indoor_transitions_pseudocode.md /// §"Overall Driver: find_cell_list". /// /// public static uint FindCellList( PhysicsDataCache cache, Vector3 worldSphereCenter, float sphereRadius, uint currentCellId) { return FindCellSet(cache, worldSphereCenter, sphereRadius, currentCellId, out _); } /// /// Phase A4 (2026-05-20). Same portal-graph traversal as /// but additionally returns the full /// candidate set built during traversal. Used by /// to iterate every cell /// the sphere overlaps for per-cell BSP collision. /// /// /// Retail oracle: CTransition::check_other_cells at /// acclient_2013_pseudo_c.txt:272717-272798 calls /// CObjCell::find_cell_list(&this->cell_array, &var_4c, ...) /// which fills both the cell_array (set) and var_4c (containing cell). /// /// public static uint FindCellSet( PhysicsDataCache cache, Vector3 worldSphereCenter, float sphereRadius, uint currentCellId, out IReadOnlyCollection cellSet) { var spheres = new[] { new Sphere { Origin = worldSphereCenter, Radius = sphereRadius, }, }; return FindCellSet(cache, spheres, spheres.Length, currentCellId, out cellSet); } /// /// Multi-sphere form of . /// Containment still uses sphere 0's center, matching retail's /// CObjCell::find_cell_list loop after the transit set is built. /// public static uint FindCellSet( PhysicsDataCache cache, IReadOnlyList worldSpheres, int numSpheres, uint currentCellId, out IReadOnlyCollection cellSet) { var containing = BuildCellSetAndPickContaining( cache, worldSpheres, numSpheres, currentCellId, out var candidates); cellSet = candidates; return containing; } private static uint BuildCellSetAndPickContaining( PhysicsDataCache cache, IReadOnlyList worldSpheres, int numSpheres, uint currentCellId, out CellArray candidates) { // Ordered, deduped candidate array — retail CELLARRAY (add_cell @701036). // The ORDER is load-bearing: the current cell is added at index 0 and the // pick iterates in order with interior-wins-break, so the current cell wins // a boundary straddle and the membership does not ping-pong (the R1 flap). candidates = new CellArray(); int sphereCount = EffectiveSphereCount(worldSpheres, numSpheres); if (sphereCount == 0) return currentCellId; Vector3 worldSphereCenter = worldSpheres[0].Origin; float sphereRadius = worldSpheres[0].Radius; uint currentLow = currentCellId & 0xFFFFu; // #106: the current block's world origin converts the world-frame sphere // coords into retail's block-local frame for the LandDefs lcoord math. // Unregistered terrain (tests; pre-stream) falls back to Vector3.Zero — // the legacy anchor-block assumption (world frame == block-local frame). cache.CellGraph.TryGetTerrainOrigin(currentCellId, out var blockOrigin); if (currentLow >= 0x0100u) { // Indoor seed: the CURRENT cell is added at INDEX 0 (retail // CObjCell::find_cell_list add_cell @ pseudo_c:308766). Index 0 is what // makes the pick current-cell-first — the hysteresis that stops the flap. var currentCell = cache.GetCellStruct(currentCellId); if (currentCell is null) return currentCellId; candidates.Add(currentCellId); // EXPAND — a single forward walk over the GROWING array, mirroring // retail's `for (i=0; i(candidates.OrderedIds); foreach (uint landcellId in landcellSnapshot) { var building = cache.GetBuilding(landcellId); if (building is null) continue; CheckBuildingTransit(cache, building, worldSphereCenter, sphereRadius, candidates); } } if (PhysicsDiagnostics.ProbeCellSetEnabled) PhysicsDiagnostics.LogCellSetBuild(currentCellId, worldSphereCenter, candidates); // THE PICK — verbatim CObjCell::find_cell_list containing-cell pick // (pseudo_c:308788-308825): iterate the array IN ORDER from index 0; for each // cell, point_in_cell; set the running result on ANY containing cell; // INTERIOR-WINS-BREAK. The current cell is at index 0, so if the sphere centre // is still inside it, it wins and the search stops — the retail hysteresis. // (Replaces the 5ca2f44 current-first pre-check, which approximated this for // the indoor-current case only; the ordered array now delivers it for every // seed by construction.) // // #106: the outdoor containing cell is the GLOBAL XY-column under the sphere // centre (LandDefs.AdjustToOutside from the current block's frame — retail // subtracts get_block_offset per candidate before point_in_cell, pc:308804; // landcells are disjoint columns so identity-compare is equivalent). The // pre-fix [0,8)-clamped, current-prefix-only computation could never match a // neighbour-block cell, freezing membership at landblock boundaries. uint containingOutdoorId = 0u; { var pickPos = worldSphereCenter - blockOrigin; uint pickCell = currentCellId; if (LandDefs.AdjustToOutside(ref pickCell, ref pickPos)) containingOutdoorId = pickCell; } uint outdoorResult = 0u; foreach (uint candId in candidates.OrderedIds) { if ((candId & 0xFFFFu) >= 0x0100u) { // Interior candidate — point_in_cell via the cell BSP (vtable[0x84]). 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; // interior-wins, stop (pseudo_c:308819) } else if (outdoorResult == 0u && containingOutdoorId != 0u) { // Outdoor candidate — CLandCell::point_in_cell is the XY-column the // sphere is over (acdream landcells have no BSP point_in_cell; the // documented adaptation). Record as the running result but DO NOT // break — an interior cell later in the array can still win. if (candId == containingOutdoorId) outdoorResult = candId; } } // No interior cell contained the centre. Return the outdoor XY-column cell if // it was a candidate, else stay on the current cell (retail leaves *result // null → caller keeps curr_cell). if (outdoorResult != 0u) return outdoorResult; // ── #106 gate-2 escape hatch: bogus-indoor-claim recovery ────────── // Restores the #83/A1.7 + #90 verification that lived in // PhysicsEngine.ResolveCellId before the collide-then-pick rewrite // moved membership here: an INDOOR current cell that IS hydrated but // whose CellBSP no longer overlaps ANY part of the foot sphere is a // bogus claim — a corrupt server save pairing an indoor cell with a // position far outside it, or the player walked out through an // unblocked gap. Keeping it wedges everything downstream: the BFS // can't reach an exit portal from a cell the sphere isn't in (no // candidates → frozen), ShadowObjectRegistry's #98 gate reads // "indoor primary" (no object collision anywhere), and there's no // wall BSP and no terrain (void fall). Demote to the outdoor column // under the sphere centre (LandDefs global math — cross-block safe). // // Sphere-overlap (BSPQuery.SphereIntersectsCellBsp, // pseudo_c:317666→:323267), NOT point-in: a doorway push-back leaves // the centre a few cm outside while the sphere still overlaps — that // must NOT demote (#90's ping-pong). A cell with no hydrated CellBSP // cannot be verified — trust the claim (stale beats null while // streaming hydrates). if (currentLow >= 0x0100u && containingOutdoorId != 0u) { var cur = cache.GetCellStruct(currentCellId); if (cur?.CellBSP?.Root is not null) { var curLocal = Vector3.Transform(worldSphereCenter, cur.InverseWorldTransform); if (!BSPQuery.SphereIntersectsCellBsp(cur.CellBSP.Root, curLocal, sphereRadius)) return containingOutdoorId; } } return currentCellId; } private static int EffectiveSphereCount(IReadOnlyList worldSpheres, int numSpheres) { if (numSpheres <= 0 || worldSpheres.Count == 0) return 0; return numSpheres < worldSpheres.Count ? numSpheres : worldSpheres.Count; } }