acdream/tests/AcDream.App.Tests/Physics/LiveEntityCollisionBuilderTests.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

442 lines
17 KiB
C#

using System.Numerics;
using AcDream.App.Physics;
using AcDream.App.World;
using AcDream.Core.Items;
using AcDream.Core.Net;
using AcDream.Core.Net.Messages;
using AcDream.Core.Physics;
using AcDream.Core.World;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Types;
namespace AcDream.App.Tests.Physics;
public sealed class LiveEntityCollisionBuilderTests
{
private const uint Guid = 0x70000100u;
private const uint Cell = 0x01010001u;
[Fact]
public void EffectivePartResolution_IsSetupAndVisualOptionIndependent()
{
uint[] resolved = LiveEntityCollisionBuilder.ResolveEffectivePartIdentities(
[0x01001000u, 0x01002000u],
id => id == 0x01001000u ? 0x01001001u : id);
Assert.Equal([0x01001001u, 0x01002000u], resolved);
}
/// <summary>
/// Re-hosts the state/flag/seed-cell coverage that used to ride on the
/// deleted Setup-radius fallback (AP-22). The old fixture was a Setup with
/// a radius and zero primitives, which cannot exist in client_portal.dat —
/// all 1,294 shapeless Setups have Radius exactly 0. This uses a
/// DAT-possible single-CylSphere Setup instead.
/// </summary>
[Fact]
public void Build_PropagatesExactStateFlagsScaleAndFullSeedCell()
{
var setup = new Setup();
setup.CylSpheres.Add(new CylSphere
{
Origin = Vector3.Zero,
Radius = 0.4f,
Height = 1.2f,
});
WorldSession.EntitySpawn spawn = Spawn(
scale: 2f,
itemType: (uint)ItemType.Creature,
descriptionFlags: 0x28u);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
record.FinalPhysicsState =
PhysicsStateFlags.Hidden | PhysicsStateFlags.Static;
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = Builder();
LiveEntityCollisionRegistration registration = Assert.IsType<LiveEntityCollisionRegistration>(
builder.Build(entity, setup, Array.Empty<uint>(), spawn, record, new Vector3(192f, -192f, 0f)));
ShadowShape shape = Assert.Single(registration.Shapes);
Assert.Equal(ShadowCollisionType.Cylinder, shape.CollisionType);
Assert.Equal(0.8f, shape.Radius);
Assert.Equal(2.4f, shape.CylHeight);
Assert.Equal((uint)record.FinalPhysicsState, registration.State);
Assert.True(registration.Flags.HasFlag(EntityCollisionFlags.HasWeenie));
Assert.True(registration.Flags.HasFlag(EntityCollisionFlags.IsCreature));
Assert.True(registration.Flags.HasFlag(EntityCollisionFlags.IsPlayer));
Assert.True(registration.Flags.HasFlag(EntityCollisionFlags.IsPK));
Assert.Equal(Cell, registration.LandblockId);
Assert.Equal(Cell, registration.SeedCellId);
Assert.Equal((192f, -192f), (registration.WorldOffsetX, registration.WorldOffsetY));
}
/// <summary>
/// AP-22: retail synthesizes no shape for a Setup with no primitives and
/// no physics-BSP part, whatever its summary Radius/Height say.
/// <c>CPhysicsObj::FindObjCollisions</c> (0x0050f050) branches to the
/// epilogue at <c>0x0050f22f je 0x50f31b</c> and returns the seeded
/// OK_TS; <c>CPartArray::GetRadius</c>/<c>GetHeight</c> are absent from
/// its call set. This is the direct inverse of the deleted
/// RadiusFallback fact.
/// </summary>
[Fact]
public void ShapelessSetupWithRadius_ProducesNoRegistration()
{
var setup = new Setup { Radius = 0.75f, Height = 2.5f };
WorldSession.EntitySpawn spawn = Spawn(scale: 2f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
Assert.Null(Builder().Build(
entity,
setup,
Array.Empty<uint>(),
spawn,
record,
new Vector3(192f, -192f, 0f)));
}
[Fact]
public void BspOnlyPart_UsesRealScaledPhysicsBoundingRadius()
{
const uint part = 0x0100ABCDu;
var setup = new Setup();
setup.Parts.Add(part);
WorldSession.EntitySpawn spawn = Spawn(scale: 1.5f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = new LiveEntityCollisionBuilder(
id => id == part,
id => id == part ? 3f : null,
PoseResolver());
LiveEntityCollisionRegistration registration = Assert.IsType<LiveEntityCollisionRegistration>(
builder.Build(entity, setup, [part], spawn, record, Vector3.Zero));
ShadowShape shape = Assert.Single(registration.Shapes);
Assert.Equal(ShadowCollisionType.BSP, shape.CollisionType);
Assert.Equal(4.5f, shape.Radius);
Assert.Equal(part, shape.GfxObjId);
}
/// <summary>
/// AP-152. Every other fixture in this file is primitive-only or BSP-only,
/// so nothing at the App layer used to exercise the CylSphere+BSP
/// combination — 73 of the 172 affected installed Setups.
/// Retail's <c>CPhysicsObj::FindObjCollisions</c> @0x0050f050 tests
/// <c>HAS_PHYSICS_BSP_PS</c> at 0x0050f165 and leaves the BSP branch
/// through the unconditional <c>0x0050f19d jmp 0x50f2b0</c>, past both the
/// CylSphere loop (0x50f1a2) and the Sphere loop (0x50f21d);
/// <c>calc_cross_cells</c> @0x00515230 dispatches identically at
/// 0x00515285. The CylSphere must not survive, and the surviving BSP shape
/// must still receive the real scaled bounding radius.
/// </summary>
[Fact]
public void CylSphereAndPhysicsBspPart_EmitsOnlyTheScaledBspShape()
{
const uint part = 0x0100AC01u;
var setup = new Setup();
setup.Parts.Add(part);
setup.CylSpheres.Add(new CylSphere
{
Origin = Vector3.Zero,
Radius = 0.4f,
Height = 1.2f,
});
WorldSession.EntitySpawn spawn = Spawn(scale: 1.5f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = new LiveEntityCollisionBuilder(
id => id == part,
id => id == part ? 3f : null,
PoseResolver());
LiveEntityCollisionRegistration registration =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity, setup, [part], spawn, record, Vector3.Zero));
ShadowShape shape = Assert.Single(registration.Shapes);
Assert.Equal(ShadowCollisionType.BSP, shape.CollisionType);
Assert.Equal(4.5f, shape.Radius); // 3 m physics-BSP radius * 1.5 scale
Assert.Equal(part, shape.GfxObjId);
}
[Fact]
public void EffectiveReplacementWithoutPhysicsBsp_RemovesBasePartCollision()
{
const uint basePart = 0x0100AB01u;
const uint replacement = 0x0100AB02u;
var setup = new Setup();
setup.Parts.Add(basePart);
WorldSession.EntitySpawn spawn = Spawn(scale: 1f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = new LiveEntityCollisionBuilder(
id => id == basePart,
_ => 1f,
PoseResolver());
Assert.Null(builder.Build(
entity,
setup,
[replacement],
spawn,
record,
Vector3.Zero));
}
[Fact]
public void EffectiveReplacementWithPhysicsBsp_AddsReplacementCollision()
{
const uint basePart = 0x0100AB11u;
const uint replacement = 0x0100AB12u;
var setup = new Setup();
setup.Parts.Add(basePart);
WorldSession.EntitySpawn spawn = Spawn(scale: 1f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = new LiveEntityCollisionBuilder(
id => id == replacement,
id => id == replacement ? 2.25f : null,
PoseResolver());
LiveEntityCollisionRegistration registration =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity,
setup,
[replacement],
spawn,
record,
Vector3.Zero));
ShadowShape shape = Assert.Single(registration.Shapes);
Assert.Equal(replacement, shape.GfxObjId);
Assert.Equal(2.25f, shape.Radius);
}
[Fact]
public void ReconcileAppearance_VisibleReplacementWithoutBspRemovesOldPayload()
{
const uint basePart = 0x0100AC01u;
const uint replacement = 0x0100AC02u;
var setup = new Setup();
setup.Parts.Add(basePart);
WorldSession.EntitySpawn spawn = Spawn(scale: 1f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = new LiveEntityCollisionBuilder(
id => id == basePart,
_ => 1f,
PoseResolver());
LiveEntityCollisionRegistration initial =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity, setup, [basePart], spawn, record, Vector3.Zero));
var registry = new ShadowObjectRegistry();
LiveEntityCollisionBuilder.Register(registry, initial);
LiveEntityCollisionRegistration? changed = builder.Build(
entity, setup, [replacement], spawn, record, Vector3.Zero,
retainEmptyPayload: true);
LiveEntityCollisionBuilder.ReconcileAppearance(
registry, entity.Id, changed, suspendIfNew: false);
Assert.Equal(1, registry.RetainedRegistrationCount);
Assert.DoesNotContain(
registry.GetObjectsInCell(Cell),
entry => entry.EntityId == entity.Id);
}
[Fact]
public void ReconcileAppearance_SuspendedReplacementRetainsNewPayloadUntilRestore()
{
const uint basePart = 0x0100AC11u;
const uint replacement = 0x0100AC12u;
var setup = new Setup();
setup.Parts.Add(basePart);
WorldSession.EntitySpawn spawn = Spawn(scale: 1f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = new LiveEntityCollisionBuilder(
id => id == basePart || id == replacement,
_ => 1f,
PoseResolver());
LiveEntityCollisionRegistration initial =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity, setup, [basePart], spawn, record, Vector3.Zero));
var registry = new ShadowObjectRegistry();
LiveEntityCollisionBuilder.Register(registry, initial);
Assert.True(registry.Suspend(entity.Id));
LiveEntityCollisionRegistration changed =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity, setup, [replacement], spawn, record, Vector3.Zero));
LiveEntityCollisionBuilder.ReconcileAppearance(
registry, entity.Id, changed, suspendIfNew: true);
Assert.Equal(1, registry.RetainedRegistrationCount);
Assert.Equal(1, registry.SuspendedRegistrationCount);
Assert.DoesNotContain(
registry.GetObjectsInCell(Cell),
entry => entry.EntityId == entity.Id);
LiveEntityCollisionRegistration empty =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity,
setup,
[0x0100AC13u],
spawn,
record,
Vector3.Zero,
retainEmptyPayload: true));
LiveEntityCollisionBuilder.ReconcileAppearance(
registry, entity.Id, empty, suspendIfNew: true);
LiveEntityCollisionBuilder.ReconcileAppearance(
registry, entity.Id, changed, suspendIfNew: true);
Assert.Equal(1, registry.RetainedRegistrationCount);
Assert.Equal(1, registry.SuspendedRegistrationCount);
registry.UpdatePosition(
entity.Id,
entity.Position,
entity.Rotation,
worldOffsetX: 0f,
worldOffsetY: 0f,
landblockId: Cell,
seedCellId: Cell);
ShadowEntry restored = Assert.Single(
registry.GetObjectsInCell(Cell),
entry => entry.EntityId == entity.Id);
Assert.Equal(replacement, restored.GfxObjId);
Assert.Equal(0, registry.SuspendedRegistrationCount);
}
[Fact]
public void ReconcileAppearance_ExistingMembershipDoesNotDependOnNewFlood()
{
const uint basePart = 0x0100AC21u;
const uint replacement = 0x0100AC22u;
var setup = new Setup();
setup.Parts.Add(basePart);
WorldSession.EntitySpawn spawn = Spawn(scale: 1f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
var builder = new LiveEntityCollisionBuilder(
id => id == basePart || id == replacement,
_ => 1f,
PoseResolver());
LiveEntityCollisionRegistration initial =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity, setup, [basePart], spawn, record, Vector3.Zero));
var registry = new ShadowObjectRegistry();
LiveEntityCollisionBuilder.Register(registry, initial);
LiveEntityCollisionRegistration changed =
Assert.IsType<LiveEntityCollisionRegistration>(builder.Build(
entity, setup, [replacement], spawn, record, Vector3.Zero))
with
{
LandblockId = 0u,
SeedCellId = 0u,
};
LiveEntityCollisionBuilder.ReconcileAppearance(
registry, entity.Id, changed, suspendIfNew: false);
ShadowEntry entry = Assert.Single(
registry.GetObjectsInCell(Cell),
candidate => candidate.EntityId == entity.Id);
Assert.Equal(replacement, entry.GfxObjId);
}
[Fact]
public void ShapelessSetup_ProducesNoRegistration()
{
WorldSession.EntitySpawn spawn = Spawn(scale: 1f);
var record = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
WorldEntity entity = Entity();
record.WorldEntity = entity;
Assert.Null(Builder().Build(
entity,
new Setup(),
Array.Empty<uint>(),
spawn,
record,
Vector3.Zero));
}
[Fact]
public void Build_RejectsDifferentRecordIncarnation()
{
WorldSession.EntitySpawn spawn = Spawn(scale: 1f);
var expected = LiveEntityTestFixture.CreateExactProjectionRecord(spawn);
var other = LiveEntityTestFixture.CreateExactProjectionRecord(
spawn with { InstanceSequence = 2 });
WorldEntity entity = Entity();
expected.WorldEntity = entity;
other.WorldEntity = entity;
Assert.Throws<InvalidOperationException>(() => Builder().Build(
entity,
new Setup { Radius = 1f },
Array.Empty<uint>(),
spawn,
other,
Vector3.Zero));
}
private static LiveEntityCollisionBuilder Builder() => new(
_ => false,
_ => null,
PoseResolver());
private static LiveEntityDefaultPoseResolver PoseResolver() => new(
_ => null,
new NullAnimationLoader(),
dumpMotion: false);
private static WorldEntity Entity() => new()
{
Id = 101u,
ServerGuid = Guid,
SourceGfxObjOrSetupId = 0x02000100u,
Position = new Vector3(4f, 5f, 6f),
Rotation = Quaternion.Identity,
MeshRefs = Array.Empty<MeshRef>(),
ParentCellId = Cell,
};
private static WorldSession.EntitySpawn Spawn(
float scale,
uint? itemType = null,
uint? descriptionFlags = null) =>
new(
Guid,
new CreateObject.ServerPosition(Cell, 4f, 5f, 6f, 1f, 0f, 0f, 0f),
0x02000100u,
Array.Empty<CreateObject.AnimPartChange>(),
Array.Empty<CreateObject.TextureChange>(),
Array.Empty<CreateObject.SubPaletteSwap>(),
BasePaletteId: null,
ObjScale: scale,
Name: "collision fixture",
ItemType: itemType,
MotionState: null,
MotionTableId: null,
PhysicsState: 0u,
ObjectDescriptionFlags: descriptionFlags,
InstanceSequence: 1);
private sealed class NullAnimationLoader : IAnimationLoader
{
public Animation? LoadAnimation(uint id) => null;
}
}