acdream/tests/AcDream.Core.Tests/Physics/ShadowShapeBuilderShapeSourceTests.cs
Erik 4abd1b5eb7 fix(physics): AP-152 — dispatch collision shapes BSP-first, at emission and at the cell flood
The register row predicted "catching or stopping on a doorway sill". That
symptom could not have been occurring. `Transition.BspOnlyDispatch`
(TransitionTypes.cs:1348, landed 2026-05-25 as A6.P7) already skipped both
primitive branches (:3911, :3954) whenever the target's wire PhysicsState
carries HAS_PHYSICS_BSP_PS, and ACE sets that bit from CSetup.HasPhysicsBSP
for every affected Setup. The extra primitive was never tested for collision.

The live defect was CELL MEMBERSHIP. The same shape list feeds
`ShadowObjectRegistry.BuildFloodSpheres`, which had no such guard and
preferred Cylinders over everything whenever any Cylinder existed — retail's
SECOND priority applied ahead of its first. For the 73 CylSphere+BSP Setups
acdream therefore flooded shadow cells from the cylinder and never from the
slab: an object absent from cells it physically occupies, which is the
#98 / #168 symptom class, not the door-collision class the row named.

Retail, re-disassembled from the PDB-paired binary (v11.4186, CodeView GUID
9e847e2f-777c-4bd9-886c-22256bb87f32, check_exe_pdb.py MATCH) rather than
taken from Binary Ninja, which drops flag tests:

  CPhysicsObj::FindObjCollisions @0x0050f050
    0x0050f165  test dword [esi+0xa8], 0x10000
    0x0050f16f  je   0x50f1a2        ; clear -> primitive dispatch
    0x0050f18d  call 0x518180        ; CPartArray::FindObjCollisions
    0x0050f19d  jmp  0x50f2b0        ; UNCONDITIONAL, past BOTH primitive loops
                                     ; (CylSphere 0x50f1a2, Sphere 0x50f21d)
    0x0050f1d6  jae  0x50f317        ; CylSphere loop exhausted -> RETURN
    0x0050f22f  je   0x50f31b        ; zero Spheres -> RETURN seeded OK_TS

  CPhysicsObj::calc_cross_cells @0x00515230
    0x00515285  test dword [esi+0xa8], 0x10000
    0x0051528f  jne  0x515305 -> CPhysicsObj::find_bbox_cell_list @0x00510fc0
    0x005152d1  call 0x52b9f0        ; cylsphere branch, below the jump
    0x005152fb  call 0x52b990        ; sorting-sphere branch, below the jump

Priority at both consumers: BSP -> CylSphere -> Sphere -> nothing. BSP wins.
Every address above was resolved back to its symbol by exact lookup in
named-retail/symbols.json.

Changes:

* `ShadowShapeBuilder.FromSetup` gains a step-0 dispatch gate. Steps 1 and 2
  are skipped entirely when any part's EFFECTIVE GfxObj carries a physics
  BSP. The gate and step 3 now share one `EffectivePartGfxObjId` helper, so
  they cannot read different identities — a gate on `setup.Parts` would,
  after an ObjDesc swap, suppress the primitives while step 3 emitted
  nothing and `Build` returned null, deleting the entity's collision.
  Emission order is unchanged. This also removes acdream's undeclared
  reliance on the server sending the flag: the gate is derived from the
  parts, exactly as CPartArray::CacheHasPhysicsBSP @0x00518110 derives it.

* `ShadowObjectRegistry.BuildFloodSpheres` now applies calc_cross_cells'
  own order: BSP, else Cylinder, else everything. Given the gate above this
  is a no-op for every shape list acdream produces (FromSetup is now
  exclusive; both landblock-static publishers already emit homogeneous
  lists), so the measured membership delta remains attributable to the
  gate alone. It is kept for the same reason BspOnlyDispatch is kept: retail
  genuinely dispatches here, and it guards a future additive producer.

`Transition.BspOnlyDispatch` is deliberately untouched.

Register: AP-152 RETIRED with its four false statements corrected — the risk
statement (the symptom was already inert); "small and centred at the part
origin" (max primitive is 6.714 m, and 0x0200086E's sphere origin is
(0.759, 0.165, 5.842)); the cottage door's "~14 cm base Sphere" (it is
0.100 m; 0.141 is Setup.Radius, which AP-22 proved is never collision
geometry); and naming one pinning test where two existed. AP-153/154/155
filed: retail's dispatch flag is cached once at InitPartArrayObject+0x7e
where acdream's gate is live; the query-time guard takes a client-derived
flag off the wire; and the static publishers emit Setup Spheres as
height-capped Cylinders while BuildFloodSpheres approximates retail's
bounding box with bounding spheres.

Tests. Both pinning tests corrected, neither deleted:
`FromSetup_DoorSetup_ProducesFourShapes` -> `..._EmitsBspPartsOnly`;
`FromSetup_DoorSetup_SphereAtExpectedLocalOffset` re-hosted on
`_ => false`, the DAT-real configuration for the 3,605 Sphere-only Setups.
`FromSetup_ScaleFactor_MultipliesAllRadiiAndOffsets` was the campaign's
eighth green test covering nothing — its assertions sat inside
`if (CollisionType == Cylinder)` on a fixture with zero CylSpheres, so only
`Scale == 2.0f` ever ran. Proved empirically: with the sphere radius scale
deleted, the old body passes and the corrected body fails. Three new facts:
the effective-identity gate, the App-layer CylSphere+BSP registration (no
App fixture combined the two before), and the flood-set dispatch. One new
installed-DAT sweep pins 172 affected Setups (73 CylSphere+BSP, 99
Sphere+BSP) behind external bucket controls, re-measured independently and
agreeing exactly with the filing commit's separate sweep.

All eight sabotages run and reported; every discriminating fact reddens in
the intended direction and only there. Clean Release build after deleting
every bin/obj: 0 errors. Complete suite 11,203 passed / 4 skipped / 0
failed, +5 on the 11,198 baseline at ec29a732 — exactly the five added
facts, no new skips.

Blast radius, corrected: the FromSetup half is graphical-only (its sole
production caller is LiveEntityCollisionBuilder in AcDream.App, which
AcDream.Headless cannot reference — Headless -> Runtime -> Core/Content).
The BuildFloodSpheres half lives in AcDream.Core and DOES execute in
Headless via LandblockPhysicsContentBuilder, but is behaviour-neutral there
because both of that builder's registrations pass homogeneous lists.
Headless suite green at 89/89.

NOT yet gated live: this changes shadow-cell membership for 22 Setups used
by 151 Door weenies and 38 stationary props. Needs a connected session.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-06 14:51:36 +02:00

132 lines
5.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Numerics;
using AcDream.Core.Physics;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Enums;
using DatReaderWriter.Types;
using Xunit;
namespace AcDream.Core.Tests.Physics;
/// <summary>
/// Guards the DAT-only shape-source rule (Slice 1 of the unified
/// collision-inclusion phase, 2026-06-24).
///
/// <para>
/// Retail oracle: <c>CPartArray::InitParts@0x00517F40</c> (parts come from
/// the Setup list only), <c>CGfxObj::Serialize@0x00534970</c> (physics_bsp
/// gated on serialized-flags bit-0), <c>CPhysicsPart::find_obj_collisions@0x0050D8D0</c>
/// (returns OK / passable when <c>physics_bsp == null</c>). Render-mesh bounds
/// never enter collision.
/// </para>
/// </summary>
public class ShadowShapeBuilderShapeSourceTests
{
// Retail: an object with no DAT physics shape (no CylSphere, no Sphere,
// no part with a PhysicsBSP) emits NO collision shape and is passable.
// CPhysicsPart::find_obj_collisions@0x0050D8D0 returns OK when physics_bsp==null.
[Fact]
public void Setup_WithNoCylSpheres_NoSpheres_NoPhysicsBspParts_YieldsEmptyShapeList()
{
var setup = new Setup
{
CylSpheres = new List<CylSphere>(),
Spheres = new List<Sphere>(),
Parts = { 0x01000ABCu },
PlacementFrames = new Dictionary<Placement, AnimationFrame>(),
};
var shapes = ShadowShapeBuilder.FromSetup(setup, entScale: 1f, hasPhysicsBsp: _ => false);
Assert.Empty(shapes);
}
// D4+W1 (2026-06-24) — BSP-only furniture weenie guard.
//
// A Setup with no CylSpheres, no Spheres, no Radius, but whose Part has a
// PhysicsBSP (e.g. a candle holder or floor candelabra) MUST produce a BSP
// ShadowShape. The premature `if (!hasCyl && !hasSphere && !hasRadius) return`
// gate in GameWindow.RegisterLiveEntityCollision was dropped because it fired
// BEFORE ShadowShapeBuilder ran and discarded these entities entirely.
//
// Retail oracle: CPhysicsPart::find_obj_collisions@0x0050D8D0 -- when
// physics_bsp is non-null the part IS tested, and the outer loop in
// CPartArray::FindObjCollisions@0x00518180 iterates ALL parts.
// ShadowShapeBuilder.FromSetup mirrors this by emitting one BSP shape per
// part that `hasPhysicsBsp` returns true for.
//
// AP-152 correction (2026-08-06): that "regardless of CylSpheres/Spheres"
// used to be stated here and was then used to justify emitting the BSP
// shapes IN ADDITION TO the primitives. It does not support that. The
// per-part loop is reached only from the BSP branch of
// CPhysicsObj::FindObjCollisions@0x0050f050, which is entered on
// HAS_PHYSICS_BSP_PS (0x0050f165 test / 0x0050f16f je) and left by the
// UNCONDITIONAL 0x0050f19d jmp 0x50f2b0 — past both primitive loops. The
// dispatch is exclusive and BSP wins; this fixture's Setup simply has no
// primitive to lose.
[Fact]
public void Setup_WithBspPart_NoCylSpheres_EmitsBspShape()
{
// hasPhysicsBsp predicate returns true for 0x0100AAAAu, simulating a
// GfxObj that has a PhysicsBSP but no CylSpheres/Spheres.
const uint BspGfxObjId = 0x0100AAAAu;
var setup = new Setup
{
CylSpheres = new List<CylSphere>(),
Spheres = new List<Sphere>(),
Parts = { BspGfxObjId },
PlacementFrames = new Dictionary<Placement, AnimationFrame>(),
};
var shapes = ShadowShapeBuilder.FromSetup(setup, entScale: 1f,
hasPhysicsBsp: id => id == BspGfxObjId);
Assert.Contains(shapes, s => s.CollisionType == ShadowCollisionType.BSP);
}
// Complementary regression guard: a Setup with no CylSpheres, no Spheres,
// and a Part that has NO PhysicsBSP must still produce an empty shape list.
// The premature gate removal does not accidentally register shapeless entities.
[Fact]
public void Setup_WithPartButNoBsp_NoCylSpheres_YieldsEmptyShapeList()
{
const uint NoBspGfxObjId = 0x0100BBBBu;
var setup = new Setup
{
CylSpheres = new List<CylSphere>(),
Spheres = new List<Sphere>(),
Parts = { NoBspGfxObjId },
PlacementFrames = new Dictionary<Placement, AnimationFrame>(),
};
var shapes = ShadowShapeBuilder.FromSetup(setup, entScale: 1f,
hasPhysicsBsp: _ => false);
Assert.Empty(shapes);
}
// 2026-07-07 — the PREMISE of the player-vs-monster crowd-collision fix (the
// CSphere family port): a humanoid Setup carries body Spheres and NO
// CylSpheres, so FromSetup emits Sphere-type shadows → collision runs through
// Transition.SphereCollision (the retail CSphere::intersects_sphere family),
// NOT the cylinder path. Mirrors the human Setup 0x02000001 (two body spheres
// at 0.475 / 1.350, r=0.48 — TS-46 / the physics digest). If this ever flips
// to CylSphere-first, the crowd fix would be aimed at the wrong dispatcher.
[Fact]
public void Setup_WithBodySpheres_NoCylSpheres_EmitsSphereShapes()
{
var setup = new Setup
{
CylSpheres = new List<CylSphere>(),
Spheres = new List<Sphere>
{
new Sphere { Origin = new Vector3(0f, 0f, 0.475f), Radius = 0.48f },
new Sphere { Origin = new Vector3(0f, 0f, 1.350f), Radius = 0.48f },
},
Parts = new List<QualifiedDataId<GfxObj>>(),
PlacementFrames = new Dictionary<Placement, AnimationFrame>(),
};
var shapes = ShadowShapeBuilder.FromSetup(setup, entScale: 1f, hasPhysicsBsp: _ => false);
Assert.Equal(2, shapes.Count);
Assert.All(shapes, s => Assert.Equal(ShadowCollisionType.Sphere, s.CollisionType));
}
}