Soa world: the step publishes each touching body pair once as a fact span (ABI 20)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-26 08:44:42 +01:00
commit 81da81150b
5 changed files with 86 additions and 17 deletions

View file

@ -8,11 +8,11 @@ Box3D decides every physical outcome; Ymir creates bodies, steps the world and e
`ymir_box3d_session_*` (`ymir_box3d.c`) is the planar Aetheria session: gravity is zero, Y is locked,
only yaw rotates (`motionLocks.linearY/angularX/angularZ`), and state leaves by `copy_bodies` into an
array of structs. A body cannot fall or tumble there, and every read is a copy. The SoA world is a
separate native object (`ymir_box3d_soa.c`, ABI 19) so the Aetheria session's contract is untouched.
separate native object (`ymir_box3d_soa.c`, ABI 20) so the Aetheria session's contract is untouched.
## Contract
- Native (ABI 19): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) /
- Native (ABI 20): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) /
create_particles / destroy_particles / create_distances / create_bends / create_sensors / attach(n, desc*) / set_pinned(n, handles, pinned) / remove / set_material / free_slots /
add_body / add_joint / step / get_view / get_facts / set_anchor_target / destroy_joint / set_joint_thresholds / remove_body / free_joint_slots / free_body_slots / apply_impulse / cast_ray_closest / destroy`. `add_body` takes one descriptor (sphere, capsule, box, static box, anchor; position,
rotation, velocity, size, density, friction, restitution, rolling resistance, material id, parent, limb). Capacities are fixed at creation,
@ -55,7 +55,7 @@ separate native object (`ymir_box3d_soa.c`, ABI 19) so the Aetheria session's co
`step`, `ymir_box3d_soa_get_facts` returns pointers and counts into buffers fixed at create (`fact_capacity`
per kind, no allocation in the step): Begin and End `{lane_a, lane_b, stable_id_a, stable_id_b}` and Hit
those plus `point` xyz, `normal` xyz (A to B), `approach_speed` (a touch faster than `hit_threshold` m/s)
and `material_a`, `material_b`. Facts are in Box3D's event order and last one step: the next `step`
and `material_a`, `material_b`; Touching (`touching`) lists each pair touching after the step once, `lane_a < lane_b`, from the same per-body contact read as `ContactCount` (`touching_dropped` past `fact_capacity`). Facts are in Box3D's event order and last one step: the next `step`
rewrites them. `*_dropped` counts the facts a step could not keep past `fact_capacity`. The lane in a fact
is the body's user data (lane + 1) and the stable id is the shape's user data. The facts report; they
decide nothing.

View file

@ -62,7 +62,7 @@ enum
YMIR_SOA_JOINT_REMOVED = 4 // a retired joint's lane (destroy_joint): never accepted by add_joint
};
#define YMIR_SOA_ABI_VERSION 19u
#define YMIR_SOA_ABI_VERSION 20u
// A body to create. `size` by kind: sphere {radius}, capsule {radius, half_length} (segment along
// local Y), box and static box {half_x, half_y, half_z}. `parent` is the lane index of an earlier body
@ -425,6 +425,11 @@ typedef struct ymir_box3d_soa_facts
uint32_t joint_removed_count;
const ymir_box3d_soa_body_removed_fact* body_removed;
const ymir_box3d_soa_joint_removed_fact* joint_removed;
// The step's touching pairs, each once, lane_a < lane_b, in lane then Box3D contact order: the same per-body contact read that fills
// the contact lanes. `touching_dropped` counts pairs past `fact_capacity`.
uint32_t touching_count;
uint32_t touching_dropped;
const ymir_box3d_soa_touch_fact* touching;
} ymir_box3d_soa_facts;
// The closest hit of a ray. `hit` is 0 for a miss and every other field is then 0. `lane` and `stable_id` name
@ -481,6 +486,7 @@ typedef struct ymir_box3d_soa_world
ymir_box3d_soa_facts facts; // counts and dropped counters live here; the arrays below back its pointers
ymir_box3d_soa_touch_fact* begin_facts;
ymir_box3d_soa_touch_fact* end_facts;
ymir_box3d_soa_touch_fact* touching_facts;
ymir_box3d_soa_hit_fact* hit_facts;
ymir_box3d_soa_overload_fact* overload_facts; // `joint_capacity` entries
ymir_box3d_soa_body_removed_fact* body_removed_facts; // `capacity` entries: what the last step published
@ -664,6 +670,7 @@ static void ymir_soa_free(ymir_box3d_soa_world* world)
free(world->joint_lanes);
free(world->begin_facts);
free(world->end_facts);
free(world->touching_facts);
free(world->hit_facts);
free(world->overload_facts);
free(world->body_removed_facts);
@ -737,6 +744,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create(
world->fact_capacity = (uint32_t)fact_capacity;
world->begin_facts = (ymir_box3d_soa_touch_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_touch_fact));
world->end_facts = (ymir_box3d_soa_touch_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_touch_fact));
world->touching_facts = (ymir_box3d_soa_touch_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_touch_fact));
world->hit_facts = (ymir_box3d_soa_hit_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_hit_fact));
world->overload_facts = (ymir_box3d_soa_overload_fact*)calloc(m, sizeof(ymir_box3d_soa_overload_fact));
world->body_removed_facts = (ymir_box3d_soa_body_removed_fact*)calloc(n, sizeof(ymir_box3d_soa_body_removed_fact));
@ -757,7 +765,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create(
}
}
if (world->contact_count == NULL || world->material_id == NULL || world->mass == NULL || world->body_generation == NULL || world->body_removed_at == NULL || world->begin_facts == NULL ||
world->end_facts == NULL || world->hit_facts == NULL || world->overload_facts == NULL || world->contact_scratch == NULL ||
world->end_facts == NULL || world->touching_facts == NULL || world->hit_facts == NULL || world->overload_facts == NULL || world->contact_scratch == NULL ||
world->body_removed_facts == NULL || world->body_removed_pending == NULL || world->joint_removed_facts == NULL ||
world->joint_removed_pending == NULL || world->retired_shapes == NULL ||
world->bodies == NULL || world->stable_id == NULL || world->kind == NULL || world->parent == NULL ||
@ -1426,10 +1434,14 @@ static void ymir_soa_collect_facts(ymir_box3d_soa_world* world)
}
}
// Per body: the touching contacts' count and the normal impulse they delivered over the whole step.
// Per body: the touching contacts' count and the normal impulse they delivered over the whole step; the same read yields each
// touching pair once, from its lower lane (a static body's lane lists its contacts too).
static void ymir_soa_collect_contact_lanes(ymir_box3d_soa_world* world)
{
float* lane = ymir_soa_lane(world, YMIR_SOA_CONTACT_IMPULSE_LANE);
ymir_box3d_soa_facts* f = &world->facts;
f->touching_count = 0;
f->touching_dropped = 0;
for (int i = 0; i < world->count; ++i)
{
if (world->kind[i] == YMIR_SOA_KIND_REMOVED)
@ -1440,7 +1452,25 @@ static void ymir_soa_collect_contact_lanes(ymir_box3d_soa_world* world)
float impulse = 0.0f;
for (int c = 0; c < n; ++c)
{
impulse += ymir_soa_manifold_impulse(world->contact_scratch + c);
const b3ContactData* data = world->contact_scratch + c;
impulse += ymir_soa_manifold_impulse(data);
b3ShapeId mine = ymir_soa_shape_lane(data->shapeIdA) == i ? data->shapeIdA : data->shapeIdB;
b3ShapeId other = ymir_soa_shape_lane(data->shapeIdA) == i ? data->shapeIdB : data->shapeIdA;
int32_t other_lane = ymir_soa_shape_lane(other);
if (other_lane <= i)
{
continue;
}
if (f->touching_count >= world->fact_capacity)
{
f->touching_dropped += 1;
continue;
}
ymir_box3d_soa_touch_fact* t = world->touching_facts + f->touching_count++;
t->lane_a = i;
t->lane_b = other_lane;
t->stable_id_a = (uint64_t)(uintptr_t)b3Shape_GetUserData(mine);
t->stable_id_b = (uint64_t)(uintptr_t)b3Shape_GetUserData(other);
}
world->contact_count[i] = n;
lane[i] = impulse;
@ -2027,6 +2057,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_facts(const ymir_box3d_soa_worl
facts->fact_capacity = world->fact_capacity;
facts->begin = world->begin_facts;
facts->end = world->end_facts;
facts->touching = world->touching_facts;
facts->hit = world->hit_facts;
facts->overload = world->overload_facts;
facts->body_removed = world->body_removed_facts;

View file

@ -448,6 +448,9 @@ internal unsafe struct Box3DSoaFactsNative
public uint JointRemovedCount;
public Box3DSoaBodyRemoved* BodyRemoved;
public Box3DSoaJointRemoved* JointRemoved;
public uint TouchingCount;
public uint TouchingDropped;
public Box3DSoaTouch* Touching;
}
/// <summary>A body removed by RemoveBody since the previous step, published by the next one. The lane and generation are the dead handle's;
@ -484,7 +487,7 @@ public readonly struct Box3DSoaOverload
public readonly float TorqueX, TorqueY, TorqueZ;
}
/// <summary>A begin or end of touch: the two bodies' lane indices and the two shapes' stable ids.</summary>
/// <summary>A begin or end of touch, or a pair touching after the step: the two bodies' lane indices and the two shapes' stable ids.</summary>
[StructLayout(LayoutKind.Sequential)]
public readonly struct Box3DSoaTouch
{
@ -513,7 +516,7 @@ public readonly struct Box3DSoaHit
}
/// <summary>Facts past <see cref="Box3DSoaWorld"/>'s fact capacity that the last step could not keep.</summary>
public readonly record struct Box3DSoaDropped(uint Begin, uint End, uint Hit);
public readonly record struct Box3DSoaDropped(uint Begin, uint End, uint Hit, uint Touching);
/// <summary>
/// What Box3D reported for the step just taken, in Box3D's event order: spans over native buffers that
@ -539,6 +542,8 @@ public readonly unsafe ref struct Box3DSoaFacts
public ReadOnlySpan<Box3DSoaTouch> Begin => Facts(_f.Begin, _f.BeginCount);
public ReadOnlySpan<Box3DSoaTouch> End => Facts(_f.End, _f.EndCount);
/// <summary>Each pair of bodies touching after the step, once, <c>LaneA &lt; LaneB</c>, in lane then Box3D contact order: the read that fills <c>ContactCount</c>.</summary>
public ReadOnlySpan<Box3DSoaTouch> Touching => Facts(_f.Touching, _f.TouchingCount);
public ReadOnlySpan<Box3DSoaHit> Hit => Facts(_f.Hit, _f.HitCount);
/// <summary>Joints that reached a force or torque threshold in the last step (at most once each), in Box3D's joint order.</summary>
public ReadOnlySpan<Box3DSoaOverload> Overloads => Facts(_f.Overload, _f.OverloadCount);
@ -546,7 +551,7 @@ public readonly unsafe ref struct Box3DSoaFacts
public ReadOnlySpan<Box3DSoaBodyRemoved> BodiesRemoved => Facts(_f.BodyRemoved, _f.BodyRemovedCount);
/// <summary>Joints retired since the previous step, in removal order: every DestroyJoint and every joint a RemoveBody took.</summary>
public ReadOnlySpan<Box3DSoaJointRemoved> JointsRemoved => Facts(_f.JointRemoved, _f.JointRemovedCount);
public Box3DSoaDropped Dropped => new(_f.BeginDropped, _f.EndDropped, _f.HitDropped);
public Box3DSoaDropped Dropped => new(_f.BeginDropped, _f.EndDropped, _f.HitDropped, _f.TouchingDropped);
public int Capacity => (int)_f.FactCapacity;
}
@ -969,7 +974,7 @@ public readonly unsafe struct Box3DSoaView
/// </summary>
public sealed class Box3DSoaWorld : IDisposable
{
private const uint ExpectedAbi = 19;
private const uint ExpectedAbi = 20;
private nint _handle;
/// <summary>The gravity (m/s^2) this world was created with; native has no setter, so this copy cannot disagree.</summary>

View file

@ -127,6 +127,9 @@ public sealed class Box3DSoaContactTests
Assert.Equal(1u, facts.Dropped.Begin);
Assert.Equal(1u, facts.Dropped.Hit);
Assert.Equal(1, facts.Capacity);
for (var i = 0; i < 400 && world.Facts.Dropped.Touching == 0; i++) world.Step(Dt);
Assert.Equal(1, world.Facts.Touching.Length);
Assert.True(world.Facts.Dropped.Touching >= 1u);
Assert.Throws<InvalidOperationException>(() => new Box3DSoaWorld(capacity: 8, factCapacity: 0));
}
@ -141,7 +144,7 @@ public sealed class Box3DSoaContactTests
Assert.True(StepToFirstBegin(world));
Assert.Equal(1u, world.Facts.Dropped.Begin);
world.Step(Dt);
Assert.Equal(new Box3DSoaDropped(0, 0, 0), world.Facts.Dropped);
Assert.Equal(new Box3DSoaDropped(0, 0, 0, 1), world.Facts.Dropped); // the two resting spheres still touch the ground: one pair kept, one dropped, every step
}
private static Box3DSoaWorld Pile()
@ -169,7 +172,8 @@ public sealed class Box3DSoaContactTests
.Concat(MemoryMarshal.AsBytes(facts.Hit).ToArray())
.Concat(MemoryMarshal.AsBytes(view.ContactImpulse).ToArray())
.Concat(MemoryMarshal.AsBytes(view.ContactCount).ToArray())
.Concat(BitConverter.GetBytes(facts.Dropped.Begin + facts.Dropped.End + facts.Dropped.Hit))
.Concat(MemoryMarshal.AsBytes(facts.Touching).ToArray())
.Concat(BitConverter.GetBytes(facts.Dropped.Begin + facts.Dropped.End + facts.Dropped.Hit + facts.Dropped.Touching))
.ToArray();
}
@ -191,6 +195,35 @@ public sealed class Box3DSoaContactTests
Assert.Contains(a.View.ContactImpulse.ToArray(), f => f > 0f);
}
[Fact]
public void Touching_pairs_are_each_touch_once_and_agree_with_contact_counts()
{
using var world = Pile();
var pairsSeen = 0;
for (var step = 0; step < 300; step++)
{
world.Step(Dt);
var touching = world.Facts.Touching;
var contacts = world.View.ContactCount;
var count = new int[contacts.Length];
var seen = new HashSet<(int, int)>();
foreach (var t in touching)
{
Assert.True(t.LaneA < t.LaneB, $"pair {t.LaneA},{t.LaneB} is not ordered at step {step}");
Assert.True(seen.Add((t.LaneA, t.LaneB)), $"pair {t.LaneA},{t.LaneB} repeated at step {step}");
count[t.LaneA]++;
count[t.LaneB]++;
}
for (var lane = 0; lane < contacts.Length; lane++)
{
Assert.True(contacts[lane] == count[lane], $"lane {lane}: ContactCount {contacts[lane]} but {count[lane]} pairs at step {step}");
}
Assert.Equal(0u, world.Facts.Dropped.Touching);
pairsSeen += touching.Length;
}
Assert.True(pairsSeen > 50, "the pile touched, so agreement is not trivially empty");
}
[Fact]
public void A_steady_state_step_with_fact_reads_allocates_nothing()
{

View file

@ -167,10 +167,10 @@ public sealed class Box3DSoaGrabTests
[Fact]
public void The_managed_side_refuses_a_native_library_of_another_abi_in_either_direction()
{
Assert.Equal(19u, Box3DSoaNative.ymir_box3d_soa_get_abi_version());
Box3DSoaWorld.RequireNativeAbi(19);
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(18)); // an older native under this managed build
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(20)); // a newer one
Assert.Equal(20u, Box3DSoaNative.ymir_box3d_soa_get_abi_version());
Box3DSoaWorld.RequireNativeAbi(20);
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(19)); // an older native under this managed build
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(21)); // a newer one
}
[Fact]