diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c index 0c6d25f..72e869e 100644 --- a/native/Ymir.Box3D/ymir_box3d_soa.c +++ b/native/Ymir.Box3D/ymir_box3d_soa.c @@ -17,6 +17,7 @@ #include "ymir_particles.h" #include "ymir_world_lock.h" +#include #include #include #include @@ -94,6 +95,9 @@ typedef struct ymir_box3d_soa_body_desc // weak grab hangs below its target. All six are finite and >= 0 and are ignored by the other kinds. // `ymir_box3d_soa_destroy_joint` releases a joint of any kind: its lane becomes a tombstone (kind REMOVED = 4, bodies -1, // every lane 0) that add_joint may reuse only once a step has completed since. +// `force_threshold` (N) and `torque_threshold` (N m) make the joint report an Overload fact in a step where its load reaches +// them; +inf (the usual value) is never, NaN or a negative value is refused. A threshold is a sensor: Ymir never removes a +// joint on it. typedef struct ymir_box3d_soa_joint_desc { uint32_t kind; @@ -111,6 +115,8 @@ typedef struct ymir_box3d_soa_joint_desc float angular_hertz; float angular_damping; float max_torque; + float force_threshold; + float torque_threshold; } ymir_box3d_soa_joint_desc; // Pointers first and in lane order, so the layout is the same on every 64-bit target. Lanes the caller @@ -189,6 +195,13 @@ typedef struct ymir_box3d_soa_view const float* joint_origin_x; const float* joint_origin_y; const float* joint_origin_z; + // The load the joint carries, world frame, from Box3D's constraint solution at the end of the last step (N and N m); a free lane reads 0. Sensors: a joint hanging a mass m at rest reads m g. + const float* joint_constraint_force_x; + const float* joint_constraint_force_y; + const float* joint_constraint_force_z; + const float* joint_constraint_torque_x; + const float* joint_constraint_torque_y; + const float* joint_constraint_torque_z; // Contact lanes, read-only, refreshed every step. contact_impulse is N s: the sum over the body's touching // contact manifold points of stepNormalImpulse, the normal impulse the contacts delivered to the body over // the whole step (0 for a body touching nothing). Exact, normal channel only: Box3D exposes no tangent @@ -338,6 +351,15 @@ typedef struct ymir_box3d_soa_hit_fact uint64_t material_b; } ymir_box3d_soa_hit_fact; +// A joint whose load reached its threshold in the step just taken, with the load Box3D reports for it after the step. The joint stays: Ymir never removes on a threshold. +typedef struct ymir_box3d_soa_overload_fact +{ + int32_t joint_lane; + uint32_t joint_generation; + float force[3]; + float torque[3]; +} ymir_box3d_soa_overload_fact; + // What Box3D reported for the step just taken, in Box3D's event order. The arrays are fixed for the // world's life and rewritten by every step: facts last one step. `dropped` counts facts past // `fact_capacity` that this step could not keep. @@ -354,6 +376,9 @@ typedef struct ymir_box3d_soa_facts const ymir_box3d_soa_touch_fact* begin; const ymir_box3d_soa_touch_fact* end; const ymir_box3d_soa_hit_fact* hit; + const ymir_box3d_soa_overload_fact* overload; // at most joint_capacity: Box3D reports a joint at most once per step + uint32_t overload_count; + uint32_t reserved2; } 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 @@ -374,7 +399,7 @@ typedef struct ymir_box3d_soa_ray_hit #define YMIR_SOA_CONTACT_IMPULSE_LANE (YMIR_SOA_STATE_LANES + YMIR_SOA_WRITE_LANES) #define YMIR_SOA_PARTICLE_IMPULSE_LANE (YMIR_SOA_CONTACT_IMPULSE_LANE + 1) // 3 lanes: x y z #define YMIR_SOA_BODY_FLOAT_LANES (YMIR_SOA_PARTICLE_IMPULSE_LANE + 3) -#define YMIR_SOA_JOINT_FLOAT_LANES 15 +#define YMIR_SOA_JOINT_FLOAT_LANES 21 typedef struct ymir_box3d_soa_world { @@ -408,6 +433,7 @@ typedef struct ymir_box3d_soa_world ymir_box3d_soa_touch_fact* begin_facts; ymir_box3d_soa_touch_fact* end_facts; ymir_box3d_soa_hit_fact* hit_facts; + ymir_box3d_soa_overload_fact* overload_facts; // `joint_capacity` entries b3ContactData* contact_scratch; // `capacity` entries: a body has one shape, so at most capacity - 1 contacts b3Vec3 gravity; ymir_particles* particles; // NULL when created without particle capacity: the step then runs exactly as ABI 8 @@ -430,6 +456,17 @@ static int ymir_soa_finite(float v) return isfinite(v); } +// A joint threshold: finite and >= 0, or +inf (never). Box3D asserts on inf, so +inf reaches it as FLT_MAX, its "never". +static int ymir_soa_threshold_ok(float v) +{ + return !isnan(v) && v >= 0.0f; +} + +static float ymir_soa_threshold(float v) +{ + return isinf(v) ? FLT_MAX : v; +} + static int ymir_soa_finite3(const float* v) { return ymir_soa_finite(v[0]) && ymir_soa_finite(v[1]) && ymir_soa_finite(v[2]); @@ -493,8 +530,11 @@ static void ymir_soa_refresh_joint(ymir_box3d_soa_world* world, int j) { angle = b3SphericalJoint_GetTwistAngle(world->joints[j]); } + b3Vec3 force = b3Joint_GetConstraintForce(world->joints[j]); + b3Vec3 torque = b3Joint_GetConstraintTorque(world->joints[j]); const float values[YMIR_SOA_JOINT_FLOAT_LANES] = { - angle, qa.v.x, qa.v.y, qa.v.z, qa.s, rel.v.x, rel.v.y, rel.v.z, rel.s, w.x, w.y, w.z, origin.x, origin.y, origin.z}; + angle, qa.v.x, qa.v.y, qa.v.z, qa.s, rel.v.x, rel.v.y, rel.v.z, rel.s, w.x, w.y, w.z, origin.x, origin.y, origin.z, + force.x, force.y, force.z, torque.x, torque.y, torque.z}; for (int lane = 0; lane < YMIR_SOA_JOINT_FLOAT_LANES; ++lane) { ymir_soa_joint_lane(world, lane)[j] = values[lane]; @@ -565,6 +605,7 @@ static void ymir_soa_free(ymir_box3d_soa_world* world) free(world->begin_facts); free(world->end_facts); free(world->hit_facts); + free(world->overload_facts); free(world->contact_scratch); ymir_particles_free(world->particles); free(world); @@ -629,6 +670,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( 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->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->contact_scratch = (b3ContactData*)calloc(n, sizeof(b3ContactData)); world->gravity = (b3Vec3){gravity_x, gravity_y, gravity_z}; if (particle_capacities != NULL && (particle_capacities->particles > 0 || particle_capacities->distances > 0 || particle_capacities->bends > 0 || @@ -642,7 +684,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create( } } if (world->contact_count == NULL || world->material_id == NULL || world->begin_facts == NULL || - world->end_facts == NULL || world->hit_facts == NULL || world->contact_scratch == NULL || + world->end_facts == NULL || world->hit_facts == NULL || world->overload_facts == NULL || world->contact_scratch == NULL || world->bodies == NULL || world->stable_id == NULL || world->kind == NULL || world->parent == NULL || world->limb == NULL || world->size == NULL || world->lanes == NULL || world->joints == NULL || world->joint_kind == NULL || world->joint_body_a == NULL || world->joint_body_b == NULL || world->joint_local_a == NULL || world->joint_local_origin_a == NULL || @@ -871,6 +913,16 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_joint_slots(const ymir_box3d_s return free_slots; } +// What every joint kind shares: the bodies, the thresholds and the lane + 1 user data a joint event resolves to its lane. +static void ymir_soa_joint_base(const ymir_box3d_soa_world* world, b3JointDef* base, int slot, const ymir_box3d_soa_joint_desc* d) +{ + base->bodyIdA = world->bodies[d->body_a]; + base->bodyIdB = world->bodies[d->body_b]; + base->forceThreshold = ymir_soa_threshold(d->force_threshold); + base->torqueThreshold = ymir_soa_threshold(d->torque_threshold); + base->userData = (void*)((uintptr_t)slot + 1u); +} + // Creates a joint between two existing bodies. The joint frame is built in world space (origin at the // anchor, z along the axis) and expressed in each body's local frame, so the creation pose is zero. YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint( @@ -883,7 +935,8 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint( !ymir_soa_finite(d->linear_hertz) || !ymir_soa_finite(d->linear_damping) || !ymir_soa_finite(d->max_force) || !ymir_soa_finite(d->angular_hertz) || !ymir_soa_finite(d->angular_damping) || !ymir_soa_finite(d->max_torque) || d->linear_hertz < 0.0f || d->linear_damping < 0.0f || d->max_force < 0.0f || d->angular_hertz < 0.0f || - d->angular_damping < 0.0f || d->max_torque < 0.0f) + d->angular_damping < 0.0f || d->max_torque < 0.0f || !ymir_soa_threshold_ok(d->force_threshold) || + !ymir_soa_threshold_ok(d->torque_threshold)) { return YMIR_SOA_INVALID_ARGUMENT; } @@ -908,10 +961,9 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint( if (d->kind == YMIR_SOA_JOINT_REVOLUTE) { b3RevoluteJointDef def = b3DefaultRevoluteJointDef(); - def.base.bodyIdA = world->bodies[d->body_a]; - def.base.bodyIdB = world->bodies[d->body_b]; def.base.localFrameA = local_a; def.base.localFrameB = local_b; + ymir_soa_joint_base(world, &def.base, slot, d); def.enableLimit = d->enable_limit != 0; def.lowerAngle = d->lower; def.upperAngle = d->upper; @@ -920,10 +972,9 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint( else if (d->kind == YMIR_SOA_JOINT_SPHERICAL) { b3SphericalJointDef def = b3DefaultSphericalJointDef(); - def.base.bodyIdA = world->bodies[d->body_a]; - def.base.bodyIdB = world->bodies[d->body_b]; def.base.localFrameA = local_a; def.base.localFrameB = local_b; + ymir_soa_joint_base(world, &def.base, slot, d); def.enableConeLimit = d->enable_limit != 0 && d->cone_angle > 0.0f; def.coneAngle = d->cone_angle; def.enableTwistLimit = d->enable_limit != 0; @@ -934,10 +985,9 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint( else if (d->kind == YMIR_SOA_JOINT_MOTOR) { b3MotorJointDef def = b3DefaultMotorJointDef(); - def.base.bodyIdA = world->bodies[d->body_a]; - def.base.bodyIdB = world->bodies[d->body_b]; def.base.localFrameA = local_a; def.base.localFrameB = local_b; + ymir_soa_joint_base(world, &def.base, slot, d); def.linearHertz = d->linear_hertz; def.linearDampingRatio = d->linear_damping; def.maxSpringForce = d->max_force; @@ -949,10 +999,9 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint( else { b3WeldJointDef def = b3DefaultWeldJointDef(); - def.base.bodyIdA = world->bodies[d->body_a]; - def.base.bodyIdB = world->bodies[d->body_b]; def.base.localFrameA = local_a; def.base.localFrameB = local_b; + ymir_soa_joint_base(world, &def.base, slot, d); joint = b3CreateWeldJoint(world->world_id, &def); } if (B3_IS_NULL(joint)) @@ -1012,6 +1061,21 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_joint(ymir_box3d_soa_world* return YMIR_SOA_OK; } +// Sets a live joint's thresholds (see the joint desc), named by lane and generation like destroy_joint. Refusals change nothing. +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_set_joint_thresholds( + ymir_box3d_soa_world* world, int32_t joint, uint32_t generation, float force_threshold, float torque_threshold) +{ + if (world == NULL || joint < 0 || joint >= world->joint_count || world->joint_kind[joint] > YMIR_SOA_JOINT_MOTOR || + world->joint_generation[joint] != generation || !ymir_soa_threshold_ok(force_threshold) || + !ymir_soa_threshold_ok(torque_threshold)) + { + return YMIR_SOA_INVALID_ARGUMENT; + } + b3Joint_SetForceThreshold(world->joints[joint], ymir_soa_threshold(force_threshold)); + b3Joint_SetTorqueThreshold(world->joints[joint], ymir_soa_threshold(torque_threshold)); + return YMIR_SOA_OK; +} + // Applies the caller's force and torque lanes to the dynamic bodies, then clears them: a lane holds one // step's intent, so a stale force is never applied twice. A non-finite value refuses the whole step // before any body is touched. @@ -1111,6 +1175,21 @@ static void ymir_soa_collect_facts(ymir_box3d_soa_world* world) ymir_box3d_soa_facts* f = &world->facts; f->begin_count = f->end_count = f->hit_count = 0; f->begin_dropped = f->end_dropped = f->hit_dropped = 0; + f->overload_count = 0; + b3JointEvents joint_events = b3World_GetJointEvents(world->world_id); + for (int i = 0; i < joint_events.count; ++i) + { + int j = (int)((uintptr_t)joint_events.jointEvents[i].userData) - 1; + if (j < 0 || j >= world->joint_count || world->joint_kind[j] == YMIR_SOA_JOINT_REMOVED) + { + continue; + } + b3Vec3 force = b3Joint_GetConstraintForce(world->joints[j]); + b3Vec3 torque = b3Joint_GetConstraintTorque(world->joints[j]); + world->overload_facts[f->overload_count++] = (ymir_box3d_soa_overload_fact){ + .joint_lane = j, .joint_generation = world->joint_generation[j], + .force = {force.x, force.y, force.z}, .torque = {torque.x, torque.y, torque.z}}; + } b3ContactEvents events = b3World_GetContactEvents(world->world_id); for (int i = 0; i < events.beginCount; ++i) { @@ -1577,6 +1656,12 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world .joint_origin_x = jb + 12 * m, .joint_origin_y = jb + 13 * m, .joint_origin_z = jb + 14 * m, + .joint_constraint_force_x = jb + 15 * m, + .joint_constraint_force_y = jb + 16 * m, + .joint_constraint_force_z = jb + 17 * m, + .joint_constraint_torque_x = jb + 18 * m, + .joint_constraint_torque_y = jb + 19 * m, + .joint_constraint_torque_z = jb + 20 * m, .contact_impulse = base + YMIR_SOA_CONTACT_IMPULSE_LANE * n, .contact_count = world->contact_count, .material_id = world->material_id, @@ -1687,5 +1772,6 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_facts(const ymir_box3d_soa_worl facts->begin = world->begin_facts; facts->end = world->end_facts; facts->hit = world->hit_facts; + facts->overload = world->overload_facts; return YMIR_SOA_OK; } diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs index 4259b89..048a91d 100644 --- a/src/Ymir.Box3D/Box3DSoaWorld.cs +++ b/src/Ymir.Box3D/Box3DSoaWorld.cs @@ -53,6 +53,7 @@ internal struct Box3DSoaJointDesc public float AxisX, AxisY, AxisZ; public float Lower, Upper, ConeAngle; public float LinearHertz, LinearDamping, MaxForce, AngularHertz, AngularDamping, MaxTorque; + public float ForceThreshold, TorqueThreshold; } /// Native layout of ymir_box3d_soa_ray_hit. @@ -295,6 +296,12 @@ internal unsafe struct Box3DSoaViewNative public float* JointOriginX; public float* JointOriginY; public float* JointOriginZ; + public float* JointConstraintForceX; + public float* JointConstraintForceY; + public float* JointConstraintForceZ; + public float* JointConstraintTorqueX; + public float* JointConstraintTorqueY; + public float* JointConstraintTorqueZ; public float* ContactImpulse; public int* ContactCount; public ulong* MaterialId; @@ -403,6 +410,19 @@ internal unsafe struct Box3DSoaFactsNative public Box3DSoaTouch* Begin; public Box3DSoaTouch* End; public Box3DSoaHit* Hit; + public Box3DSoaOverload* Overload; + public uint OverloadCount; + public uint Reserved2; +} + +/// A joint whose load reached its threshold in the step just taken, with the load (world frame; N and N m) Box3D reports for it after the step. The joint stays: Ymir never removes on a threshold. +[StructLayout(LayoutKind.Sequential)] +public readonly struct Box3DSoaOverload +{ + public readonly int JointLane; + public readonly uint JointGeneration; + public readonly float ForceX, ForceY, ForceZ; + public readonly float TorqueX, TorqueY, TorqueZ; } /// A begin or end of touch: the two bodies' lane indices and the two shapes' stable ids. @@ -461,6 +481,8 @@ public readonly unsafe ref struct Box3DSoaFacts public ReadOnlySpan Begin => Facts(_f.Begin, _f.BeginCount); public ReadOnlySpan End => Facts(_f.End, _f.EndCount); public ReadOnlySpan Hit => Facts(_f.Hit, _f.HitCount); + /// Joints that reached a force or torque threshold in the last step (at most once each), in Box3D's joint order. + public ReadOnlySpan Overloads => Facts(_f.Overload, _f.OverloadCount); public Box3DSoaDropped Dropped => new(_f.BeginDropped, _f.EndDropped, _f.HitDropped); public int Capacity => (int)_f.FactCapacity; } @@ -533,6 +555,10 @@ internal static unsafe partial class Box3DSoaNative [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] internal static partial int ymir_box3d_soa_destroy_joint(nint world, int joint, uint generation); + [LibraryImport(Library)] + [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static partial int ymir_box3d_soa_set_joint_thresholds(nint world, int joint, uint generation, float forceThreshold, float torqueThreshold); + [LibraryImport(Library)] [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] internal static partial int ymir_box3d_soa_free_joint_slots(nint world); @@ -701,6 +727,14 @@ public readonly unsafe struct Box3DSoaView /// World position of the joint frame origin on body A (the joint anchor); at creation it is the anchor add_joint was given. public ReadOnlySpan JointOriginX => Lane(_v.JointOriginX, JointCount); public ReadOnlySpan JointOriginY => Lane(_v.JointOriginY, JointCount); + /// The load the joint carries, world frame, from Box3D's constraint solution at the end of the last step (N); a removed lane reads 0. A joint hanging a mass m at rest reads m g. A sensor: Ymir never removes a joint on it. + public ReadOnlySpan JointConstraintForceX => Lane(_v.JointConstraintForceX, JointCount); + public ReadOnlySpan JointConstraintForceY => Lane(_v.JointConstraintForceY, JointCount); + public ReadOnlySpan JointConstraintForceZ => Lane(_v.JointConstraintForceZ, JointCount); + /// The torque (N m) the joint carries, as the force lanes. + public ReadOnlySpan JointConstraintTorqueX => Lane(_v.JointConstraintTorqueX, JointCount); + public ReadOnlySpan JointConstraintTorqueY => Lane(_v.JointConstraintTorqueY, JointCount); + public ReadOnlySpan JointConstraintTorqueZ => Lane(_v.JointConstraintTorqueZ, JointCount); public ReadOnlySpan JointOriginZ => Lane(_v.JointOriginZ, JointCount); // Particle lanes: read-only, changed only by Step and by the particle and constraint commands. Lanes are indexed up to @@ -971,7 +1005,8 @@ public sealed class Box3DSoaWorld : IDisposable /// public Box3DSoaJointHandle AddJoint( Box3DSoaJointKind kind, int bodyA, int bodyB, (float X, float Y, float Z) anchor, - (float X, float Y, float Z) axis, bool limit = false, float lower = 0f, float upper = 0f, float coneAngle = 0f) + (float X, float Y, float Z) axis, bool limit = false, float lower = 0f, float upper = 0f, float coneAngle = 0f, + float forceThreshold = float.PositiveInfinity, float torqueThreshold = float.PositiveInfinity) { ObjectDisposedException.ThrowIf(_handle == 0, this); var desc = new Box3DSoaJointDesc @@ -979,6 +1014,7 @@ public sealed class Box3DSoaWorld : IDisposable Kind = (uint)kind, BodyA = bodyA, BodyB = bodyB, EnableLimit = limit ? 1u : 0u, AnchorX = anchor.X, AnchorY = anchor.Y, AnchorZ = anchor.Z, AxisX = axis.X, AxisY = axis.Y, AxisZ = axis.Z, Lower = lower, Upper = upper, ConeAngle = coneAngle, + ForceThreshold = forceThreshold, TorqueThreshold = torqueThreshold, }; Check(Box3DSoaNative.ymir_box3d_soa_add_joint(_handle, desc, out var index)); return HandleOf(index); @@ -994,7 +1030,8 @@ public sealed class Box3DSoaWorld : IDisposable /// public Box3DSoaJointHandle AddMotorJoint( int bodyA, int bodyB, (float X, float Y, float Z) anchor, - (float Hertz, float Damping, float MaxForce) linear, (float Hertz, float Damping, float MaxTorque) angular) + (float Hertz, float Damping, float MaxForce) linear, (float Hertz, float Damping, float MaxTorque) angular, + float forceThreshold = float.PositiveInfinity, float torqueThreshold = float.PositiveInfinity) { ObjectDisposedException.ThrowIf(_handle == 0, this); var desc = new Box3DSoaJointDesc @@ -1003,6 +1040,7 @@ public sealed class Box3DSoaWorld : IDisposable AnchorX = anchor.X, AnchorY = anchor.Y, AnchorZ = anchor.Z, AxisZ = 1f, LinearHertz = linear.Hertz, LinearDamping = linear.Damping, MaxForce = linear.MaxForce, AngularHertz = angular.Hertz, AngularDamping = angular.Damping, MaxTorque = angular.MaxTorque, + ForceThreshold = forceThreshold, TorqueThreshold = torqueThreshold, }; Check(Box3DSoaNative.ymir_box3d_soa_add_joint(_handle, desc, out var index)); return HandleOf(index); @@ -1021,6 +1059,17 @@ public sealed class Box3DSoaWorld : IDisposable Check(Box3DSoaNative.ymir_box3d_soa_destroy_joint(_handle, joint.Lane, joint.Generation)); } + /// + /// Sets a live joint's thresholds: in a step where its force (N) or torque (N m) reaches one, the joint appears in + /// ; +inf is never. The joint is never removed on a threshold. Throws for NaN or a + /// negative value, a lane that is not a live joint, or a stale handle; a refusal changes nothing. + /// + public void SetJointThresholds(Box3DSoaJointHandle joint, float forceThreshold, float torqueThreshold) + { + ObjectDisposedException.ThrowIf(_handle == 0, this); + Check(Box3DSoaNative.ymir_box3d_soa_set_joint_thresholds(_handle, joint.Lane, joint.Generation, forceThreshold, torqueThreshold)); + } + private unsafe Box3DSoaJointHandle HandleOf(int lane) { Check(Box3DSoaNative.ymir_box3d_soa_get_view(_handle, out var v)); diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaJointTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaJointTests.cs index 641de17..b71ab43 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaJointTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaJointTests.cs @@ -274,4 +274,108 @@ public sealed class Box3DSoaJointTests Assert.True(first.AsSpan().SequenceEqual(Run())); Assert.Contains(first, b => b != 0); } + + private const float BobRadius = 0.1f, BobDensity = 1000f; + private static float BobMass => 4f / 3f * MathF.PI * BobRadius * BobRadius * BobRadius * BobDensity; + + /// A static box with a heavy sphere hung one metre below it by a joint of the given kind at the box's centre. + private static (Box3DSoaWorld World, int Bob, Box3DSoaJointHandle Joint) Hanging( + Box3DSoaJointKind kind, float forceThreshold = float.PositiveInfinity, float torqueThreshold = float.PositiveInfinity) + { + var world = new Box3DSoaWorld(capacity: 4, jointCapacity: 2); + var pin = world.AddStaticBox(1, (0f, 5f, 0f), (0.1f, 0.1f, 0.1f)); + var bob = world.AddSphere(2, (0f, 4f, 0f), BobRadius, BobDensity); + var joint = world.AddJoint(kind, pin, bob, (0f, 5f, 0f), (0f, 0f, 1f), forceThreshold: forceThreshold, torqueThreshold: torqueThreshold); + return (world, bob, joint); + } + + private static float Magnitude(Box3DSoaView v, int joint) => + MathF.Sqrt(v.JointConstraintForceX[joint] * v.JointConstraintForceX[joint] + v.JointConstraintForceY[joint] * v.JointConstraintForceY[joint] + + v.JointConstraintForceZ[joint] * v.JointConstraintForceZ[joint]); + + [Theory] + [InlineData(Box3DSoaJointKind.Spherical)] + [InlineData(Box3DSoaJointKind.Weld)] + public void Constraint_lanes_read_the_load(Box3DSoaJointKind kind) + { + var (world, _, joint) = Hanging(kind); + using var _ = world; + var view = world.View; + for (var i = 0; i < 120; i++) world.Step(Dt); + Assert.Equal(BobMass * 10f, Magnitude(view, joint), BobMass * 10f * 0.02f); // m g within 2% + world.DestroyJoint(joint); + Assert.Equal(0f, Magnitude(view, joint)); // a removed lane keeps no load + Assert.Equal(0f, view.JointConstraintTorqueZ[joint]); + } + + [Fact] + public void An_overload_is_reported_not_acted_on() + { + var (world, bob, joint) = Hanging(Box3DSoaJointKind.Spherical, forceThreshold: 200f); + using var _ = world; + var view = world.View; + var first = -1; + for (var i = 0; i < 400 && first < 0; i++) + { + view.ForceY[bob] = -2f * i; // a slow ramp of downward pull + world.Step(Dt); + var reached = Magnitude(view, joint) >= 198f; + var overloads = world.Facts.Overloads; + if (!reached) Assert.Equal(0, overloads.Length); // never before the load comes within 1% of the threshold + else if (overloads.Length > 0) first = i; + else + { + view.ForceY[bob] = -2f * (i + 1); + world.Step(Dt); // by the step after + var next = world.Facts.Overloads; + Assert.Equal(1, next.Length); + Assert.Equal(joint.Lane, next[0].JointLane); + Assert.Equal(joint.Generation, next[0].JointGeneration); + Assert.True(next[0].ForceY > 190f); // the load rides on the fact + first = i + 1; + } + } + Assert.True(first >= 0, "the ramp must reach the threshold"); + for (var i = 0; i < 10; i++) + { + view.ForceY[bob] = -400f; + world.Step(Dt); + } + Assert.Equal((uint)Box3DSoaJointKind.Spherical, view.JointKind[joint]); // the joint still holds: no removal on a threshold + Assert.Equal(joint.Generation, view.JointGeneration[joint]); + Assert.Equal(4f, view.PositionY[bob], 0.2f); + + world.DestroyJoint(joint); + for (var i = 0; i < 30; i++) world.Step(Dt); + Assert.True(view.PositionY[bob] < 3f, "DestroyJoint frees the child"); + } + + [Fact] + public void Thresholds_are_a_sensor_set_by_desc_or_command_and_refused_when_not_a_load() + { + var (world, bob, joint) = Hanging(Box3DSoaJointKind.Weld); + using var _ = world; + for (var i = 0; i < 5; i++) world.Step(Dt); + Assert.Equal(0, world.Facts.Overloads.Length); // +inf is never + + world.SetJointThresholds(joint, 10f, float.PositiveInfinity); // below the bob's weight + world.Step(Dt); + Assert.Equal(1, world.Facts.Overloads.Length); + world.SetJointThresholds(joint, float.PositiveInfinity, float.PositiveInfinity); + world.Step(Dt); + Assert.Equal(0, world.Facts.Overloads.Length); + + Assert.Throws(() => world.SetJointThresholds(joint, float.NaN, 1f)); + Assert.Throws(() => world.SetJointThresholds(joint, 1f, -1f)); + Assert.Throws(() => world.SetJointThresholds(new Box3DSoaJointHandle(joint.Lane, joint.Generation + 1), 1f, 1f)); + Assert.Throws(() => world.SetJointThresholds(new Box3DSoaJointHandle(1, 0), 1f, 1f)); + Assert.Throws(() => world.AddJoint(Box3DSoaJointKind.Spherical, 0, bob, (0f, 5f, 0f), (0f, 0f, 1f), forceThreshold: float.NaN)); + Assert.Throws(() => world.AddJoint(Box3DSoaJointKind.Spherical, 0, bob, (0f, 5f, 0f), (0f, 0f, 1f), torqueThreshold: -0.5f)); + Assert.Equal(1, world.View.JointCount); // the refusals added nothing + world.Step(Dt); + Assert.Equal(0, world.Facts.Overloads.Length); // and changed nothing + + world.DestroyJoint(joint); + Assert.Throws(() => world.SetJointThresholds(joint, 1f, 1f)); // a removed joint has none + } }