Ragdoll builds a BodyPlan; Limb, Muscle, Region and the hard-coded Build are deleted

ReadRegions becomes ReadSensePoints; strength and target arrays index by plan joint ordinal.
Ymir limb lane is now the plan part ordinal, so HandTests.BaseHash is re-pinned (the only pin moved).
Proof, BaseCreationHash with the Limb term removed, seed 1, Ymir cdf79b1:
  Lodur d7a626b: 0x65216f91ffc63d24   this cut: 0x65216f91ffc63d24   (equal)
Full function: d7a626b 0xccf5cedb0df1b2e8 (old pin) -> this cut 0xbbcc7aff6c088398 (new pin).
Tests: Core 182/182, Lodur.Tests 46/46; the connected pain box replay is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-25 00:03:21 +01:00
commit d9a721611b
8 changed files with 311 additions and 265 deletions

View file

@ -14,7 +14,8 @@ are not coded.
Entry points: `src/Lodur.Core/Actor.cs` (one character's nervous state, one tick per
physics step), `src/Lodur.Core/PdMuscle.cs` (engine-free PD law, strength per muscle),
`src/Lodur.Body.Ymir/HumanoidRagdoll.cs` (the ragdoll, `Drive` and `ReadRegions`),
`src/Lodur.Core/BodyPlan.cs` (a body as data: parts, joints that are the tree, sense points),
`src/Lodur.Body.Ymir/Ragdoll.cs` (builds a `BodyPlan` into a Ymir world; `Drive` and `ReadSensePoints`),
`tests/Lodur.Core.Tests` (the layers and parity with the pain box; builds without Ymir),
`tests/Lodur.Tests` (stand, fall, rest, same-seed-same-hash, and the connected pain box:
`ConnectedPainBoxTests`). The map this was cut from is

View file

@ -9,7 +9,7 @@ Ymir's structure-of-arrays world. Nothing above layer 5 exists yet.
joint: the child's rotation relative to the parent and their relative angular velocity in, a torque out.
Strength is a multiplier on every gain; zero is limp and returns exactly zero, except that a muscle with `Passive` keeps that fraction of its damping (tissue viscosity). Swing (joint frame x, y) and
twist (z) have separate gains.
- `Lodur.Body.Ymir` (`net8.0`, references Ymir.Box3D): `HumanoidRagdoll` builds 19 bodies (palm, thumb and fingers per arm) and 18 joints in a
- `Lodur.Body.Ymir` (`net8.0`, references Ymir.Box3D): `Ragdoll` builds a `BodyPlan` (here `BodyPlans.Humanoid`: 19 bodies, palm, thumb and fingers per arm, and 18 joints) in a
caller-owned `Box3DSoaWorld`: capsule limbs, box pelvis, torso and feet, a sphere head, ball joints at
spine, neck, shoulders and hips, hinges at elbows, knees and ankles. `Drive(strengths, targets)` writes
each muscle's torque onto the world's torque lanes (equal and opposite on child and parent). The strength

View file

@ -3,162 +3,98 @@ using Ymir.Box3D;
namespace Lodur.Body.Ymir
{
/// <summary>The ragdoll's joints, in strength-array and target-array order.</summary>
public enum Muscle
{
Spine, Neck, ShoulderL, ShoulderR, ElbowL, ElbowR, HipL, HipR, KneeL, KneeR, AnkleL, AnkleR,
WristL, WristR, ThumbL, ThumbR, FingersL, FingersR
}
/// <summary>The body regions perception senses at, in the order of the point arrays <see cref="HumanoidRagdoll.ReadRegions"/> fills.</summary>
public enum Region
{
HandL, HandR, Head
}
/// <summary>The ragdoll's bodies, also the limb label written into the world's limb lane.</summary>
public enum Limb
{
Pelvis, Torso, Head, UpperArmL, UpperArmR, LowerArmL, LowerArmR, ThighL, ThighR, ShinL, ShinR, FootL, FootR,
PalmL, PalmR, ThumbL, ThumbR, FingersL, FingersR
}
/// <summary>
/// A 19-body humanoid built in a caller-owned Ymir SoA world (invariant one-physics-world): capsule limbs,
/// box pelvis, torso, feet and palms, a sphere head, a thumb capsule and a fingers box per hand, 18 joints: spherical at
/// spine, neck, shoulders, hips, wrists and thumbs, hinges at elbows, knees, ankles and knuckles. Facing +z, left is +x, standing on y = 0 at the creation pose, which is also
/// every joint's zero. The game owns the physics world: Build adds bodies to the caller's world and Lodur never creates or steps one. <see cref="Drive"/> is the muscle layer: it turns caller-owned strengths and target
/// rotations into torques on the world's torque lanes and does nothing else to the physics.
/// A <see cref="BodyPlan"/> built in a caller-owned Ymir SoA world (invariant one-physics-world): parts in plan order, then joints
/// in plan order, the stable id firstStableId + part ordinal, the limb lane the part ordinal, the parent lane the lane of the part's
/// parent in the plan. The game owns the physics world: Build adds bodies to the caller's world and Lodur never creates or steps one.
/// <see cref="Drive"/> is the muscle layer: it turns caller-owned strengths and target rotations into torques on the world's
/// torque lanes and does nothing else to the physics. The binding holds no body numbers; the plan owns them.
/// </summary>
public sealed class HumanoidRagdoll
public sealed class Ragdoll
{
public const int MuscleCount = 18;
public const int LimbCount = 19;
public const int RegionCount = 3;
private const float Density = 1000f;
private const float Friction = 0.8f;
/// <summary>The fingers' creation curl at the knuckle, radians: the relaxed resting hand (question hand-rest-curl).</summary>
private const float RestCurl = 0.35f;
private const float Thumb30 = 30f * MathF.PI / 180f; // the thumb's metacarpal, out of the palm plane
private const float HeadRolling = 0.1f; // a bare sphere on the ground rolls on, so the fallen head never settles
private readonly Box3DSoaWorld _world;
private readonly int[] _bodyLane = new int[LimbCount];
private readonly int[] _jointLane = new int[MuscleCount];
private readonly MuscleGains[] _gains = new MuscleGains[MuscleCount];
private readonly int[] _bodyLane;
private readonly int[] _jointLane;
private readonly MuscleGains[] _gains;
private HumanoidRagdoll(Box3DSoaWorld world) => _world = world;
/// <summary>World lane index of a limb's body.</summary>
public int BodyLane(Limb limb) => _bodyLane[(int)limb];
/// <summary>World lane index of a muscle's joint.</summary>
public int JointLane(Muscle muscle) => _jointLane[(int)muscle];
/// <summary>Body and joint capacity a world needs to hold one ragdoll (plus whatever else the caller adds).</summary>
public static (int Bodies, int Joints) Needs => (LimbCount, MuscleCount);
/// <summary>Builds the ragdoll standing with its feet on y = 0 at <paramref name="origin"/> (x, z used). Stable ids are firstStableId.. + 18.</summary>
public static HumanoidRagdoll Build(Box3DSoaWorld world, (float X, float Z) origin, ulong firstStableId)
private Ragdoll(Box3DSoaWorld world, BodyPlan plan)
{
var r = new HumanoidRagdoll(world);
_world = world;
Plan = plan;
_bodyLane = new int[plan.Parts.Count];
_jointLane = new int[plan.Joints.Count];
_gains = new MuscleGains[plan.Joints.Count];
}
/// <summary>The plan this ragdoll was built from.</summary>
public BodyPlan Plan { get; }
/// <summary>World lane index of a part's body, by plan part ordinal.</summary>
public int BodyLane(int part) => _bodyLane[part];
/// <summary>World lane index of a joint, by plan joint ordinal.</summary>
public int JointLane(int joint) => _jointLane[joint];
/// <summary>Body and joint capacity a world needs to hold one ragdoll of <paramref name="plan"/> (plus whatever else the caller adds).</summary>
public static (int Bodies, int Joints) Needs(BodyPlan plan) => (plan.Parts.Count, plan.Joints.Count);
/// <summary>Builds <paramref name="plan"/> at <paramref name="origin"/> (x, z used). Stable ids are firstStableId + part ordinal.</summary>
public static Ragdoll Build(Box3DSoaWorld world, BodyPlan plan, (float X, float Z) origin, ulong firstStableId)
{
var r = new Ragdoll(world, plan);
var ox = origin.X;
var oz = origin.Z;
ulong id = firstStableId;
int Box(Limb limb, int parent, float x, float y, float z, float hx, float hy, float hz) =>
r._bodyLane[(int)limb] = world.AddBox(id++, (ox + x, y, oz + z), (hx, hy, hz), Density,
friction: Friction, parent: parent, limb: (int)limb);
int Capsule(Limb limb, int parent, float x, float y, float radius, float half) =>
r._bodyLane[(int)limb] = world.AddCapsule(id++, (ox + x, y, oz), radius, half, Density,
friction: Friction, parent: parent, limb: (int)limb);
var pelvis = Box(Limb.Pelvis, -1, 0f, 1.11f, 0f, 0.15f, 0.08f, 0.09f);
var torso = Box(Limb.Torso, pelvis, 0f, 1.41f, 0f, 0.15f, 0.22f, 0.09f);
var head = r._bodyLane[(int)Limb.Head] = world.AddSphere(id++, (ox, 1.74f, oz), 0.11f, Density,
friction: Friction, parent: torso, limb: (int)Limb.Head, rollingResistance: HeadRolling);
foreach (var (side, sx) in new[] { (0, 1f), (1, -1f) })
for (var i = 0; i < plan.Parts.Count; i++)
{
var upperArm = Capsule(Limb.UpperArmL + side, torso, sx * 0.21f, 1.395f, 0.045f, 0.11f);
var lowerArm = Capsule(Limb.LowerArmL + side, upperArm, sx * 0.21f, 1.10f, 0.04f, 0.10f);
var thigh = Capsule(Limb.ThighL + side, pelvis, sx * 0.09f, 0.79f, 0.07f, 0.18f);
var shin = Capsule(Limb.ShinL + side, thigh, sx * 0.09f, 0.31f, 0.06f, 0.17f);
Box(Limb.FootL + side, shin, sx * 0.09f, 0.04f, 0.05f, 0.05f, 0.04f, 0.12f);
var p = plan.Parts[i];
var id = firstStableId + (ulong)i;
var position = (ox + p.Position.X, p.Position.Y, oz + p.Position.Z);
var parent = plan.ParentOf(i) < 0 ? -1 : r._bodyLane[plan.ParentOf(i)];
switch (p.Shape)
{
case PartShape.Box:
r._bodyLane[i] = world.AddBox(id, position, p.Size, p.Density, (p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W),
friction: p.Friction, parent: parent, limb: i);
break;
case PartShape.Capsule:
r._bodyLane[i] = world.AddCapsule(id, position, p.Size.X, p.Size.Y, p.Density, (p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W),
friction: p.Friction, parent: parent, limb: i, rollingResistance: p.RollingResistance);
break;
default:
r._bodyLane[i] = world.AddSphere(id, position, p.Size.X, p.Density,
friction: p.Friction, parent: parent, limb: i, rollingResistance: p.RollingResistance);
break;
}
}
// Hands, appended after the base bodies. The palm faces -sx with the thumb forward (+z); the thumb capsule
// lies along its metacarpal axis, 30 degrees out of the palm plane; the fingers are created at the rest curl.
var cmcAxis = (0f, -MathF.Cos(Thumb30), MathF.Sin(Thumb30));
foreach (var (side, sx) in new[] { (0, 1f), (1, -1f) })
for (var j = 0; j < plan.Joints.Count; j++)
{
var lowerArm = r._bodyLane[(int)Limb.LowerArmL + side];
var palm = Box(Limb.PalmL + side, lowerArm, sx * 0.21f, 0.930f, 0f, 0.014f, 0.045f, 0.040f);
var thumbSpin = Quat.FromAxisAngle(1f, 0f, 0f, -Thumb30);
r._bodyLane[(int)Limb.ThumbL + side] = world.AddCapsule(id++,
(ox + sx * 0.206f + 0.05f * cmcAxis.Item1, 0.955f + 0.05f * cmcAxis.Item2, oz + 0.03f + 0.05f * cmcAxis.Item3),
0.011f, 0.03f, Density, (thumbSpin.X, thumbSpin.Y, thumbSpin.Z, thumbSpin.W),
friction: Friction, parent: palm, limb: (int)Limb.ThumbL + side);
var curl = Quat.FromAxisAngle(0f, 0f, sx, -RestCurl);
r._bodyLane[(int)Limb.FingersL + side] = world.AddBox(id++,
(ox + sx * 0.21f - sx * MathF.Sin(RestCurl) * 0.0425f, 0.885f - MathF.Cos(RestCurl) * 0.0425f, oz),
(0.011f, 0.0425f, 0.038f), Density, (curl.X, curl.Y, curl.Z, curl.W),
friction: Friction, parent: palm, limb: (int)Limb.FingersL + side);
var d = plan.Joints[j];
var kind = d.Kind == JointKind.Spherical ? Box3DSoaJointKind.Spherical : Box3DSoaJointKind.Revolute;
r._jointLane[j] = world.AddJoint(kind, r._bodyLane[d.Parent], r._bodyLane[d.Child],
(ox + d.Anchor.X, d.Anchor.Y, oz + d.Anchor.Z), d.Axis, limit: true, lower: d.Lower, upper: d.Upper, coneAngle: d.Cone);
r._gains[j] = d.Gains;
}
void Joint(Muscle m, Box3DSoaJointKind kind, Limb parent, Limb child, float x, float y, float z,
(float, float, float) axis, MuscleGains gains, float lower = 0f, float upper = 0f, float cone = 0f)
{
r._jointLane[(int)m] = world.AddJoint(kind, r._bodyLane[(int)parent], r._bodyLane[(int)child],
(ox + x, y, oz + z), axis, limit: true, lower: lower, upper: upper, coneAngle: cone);
r._gains[(int)m] = gains;
}
var up = (0f, 1f, 0f);
var across = (1f, 0f, 0f);
// Gains are tuned against measured stand/fall runs at 120 Hz (see the tests), not derived: explicit PD on
// light limbs is stable only while damping * dt stays under the inertia it acts on.
Joint(Muscle.Spine, Box3DSoaJointKind.Spherical, Limb.Pelvis, Limb.Torso, 0f, 1.19f, 0f, up, new MuscleGains(500f, 4f, 200f, 8f), -0.4f, 0.4f, 0.5f);
Joint(Muscle.Neck, Box3DSoaJointKind.Spherical, Limb.Torso, Limb.Head, 0f, 1.63f, 0f, up, new MuscleGains(30f, 0.8f, 20f, 0.6f), -0.6f, 0.6f, 0.6f);
for (var side = 0; side < 2; side++)
{
var sx = side == 0 ? 1f : -1f;
Joint(Muscle.ShoulderL + side, Box3DSoaJointKind.Spherical, Limb.Torso, Limb.UpperArmL + side, sx * 0.21f, 1.55f, 0f, up, new MuscleGains(20f, 1.5f, 1f, 0.02f), -1f, 1f, 1.5f); // damping carries the hand's mass (hands-gains: 1 and 0.6 before)
Joint(Muscle.ElbowL + side, Box3DSoaJointKind.Revolute, Limb.UpperArmL + side, Limb.LowerArmL + side, sx * 0.21f, 1.24f, 0f, across, new MuscleGains(0f, 0f, 12f, 0.9f), -2.4f, 0f);
Joint(Muscle.HipL + side, Box3DSoaJointKind.Spherical, Limb.Pelvis, Limb.ThighL + side, sx * 0.09f, 1.04f, 0f, up, new MuscleGains(600f, 3f, 10f, 0.15f), -0.5f, 0.5f, 1.2f);
Joint(Muscle.KneeL + side, Box3DSoaJointKind.Revolute, Limb.ThighL + side, Limb.ShinL + side, sx * 0.09f, 0.54f, 0f, across, new MuscleGains(0f, 0f, 300f, 8f), 0f, 2.4f);
Joint(Muscle.AnkleL + side, Box3DSoaJointKind.Revolute, Limb.ShinL + side, Limb.FootL + side, sx * 0.09f, 0.08f, 0f, across, new MuscleGains(0f, 0f, 100f, 0.5f), -0.6f, 0.6f);
}
// Hand gains are bounded by each body's own inertia, not the arm subtree's (explicit PD is stable only while
// damping * dt stays under the inertia it acts on; a wrist kd sized for the arm limit-cycles at once), and
// every hand joint keeps passive damping when limp so loose hands settle instead of ringing.
for (var side = 0; side < 2; side++)
{
var sx = side == 0 ? 1f : -1f;
Joint(Muscle.WristL + side, Box3DSoaJointKind.Spherical, Limb.LowerArmL + side, Limb.PalmL + side, sx * 0.21f, 0.975f, 0f, up, new MuscleGains(1f, 0.012f, 0.3f, 0.005f, 1f), -1.2f, 1.2f, 1.0f);
Joint(Muscle.ThumbL + side, Box3DSoaJointKind.Spherical, Limb.PalmL + side, Limb.ThumbL + side, sx * 0.206f, 0.955f, 0.03f, cmcAxis, new MuscleGains(0.06f, 0.001f, 0f, 0f, 1f), 0f, 0f, 0.7f); // twist locked: a free thumb spins
Joint(Muscle.FingersL + side, Box3DSoaJointKind.Revolute, Limb.PalmL + side, Limb.FingersL + side, sx * 0.21f, 0.885f, 0f, (0f, 0f, sx), new MuscleGains(0f, 0f, 0.3f, 0.004f, 1f), -1.6f + RestCurl, 0.35f + RestCurl);
}
return r;
}
/// <summary>
/// Writes this tick's muscle torques onto the world's torque lanes: for each joint a PD torque toward
/// <paramref name="targets"/>[joint] (the child's rotation relative to the parent in the joint frame, whose z axis is a hinge's axis; a hinge has no swing gains, so it takes torque about that axis only) scaled by <paramref name="strengths"/>[joint], applied to the child
/// and, equal and opposite, to the parent. Both arrays are the caller's, one entry per <see cref="Muscle"/>;
/// and, equal and opposite, to the parent. Both arrays are the caller's, one entry per plan joint;
/// nothing is copied or retained. Allocates nothing. Call once per step, before <c>world.Step</c>; the
/// world clears the lanes when it applies them.
/// </summary>
public void Drive(ReadOnlySpan<float> strengths, ReadOnlySpan<Quat> targets)
{
if (strengths.Length != MuscleCount || targets.Length != MuscleCount)
if (strengths.Length != _gains.Length || targets.Length != _gains.Length)
{
throw new ArgumentException($"strengths and targets need {MuscleCount} entries, one per muscle.");
throw new ArgumentException($"strengths and targets need {_gains.Length} entries, one per plan joint.");
}
var v = _world.View;
for (var m = 0; m < MuscleCount; m++)
for (var m = 0; m < _gains.Length; m++)
{
var j = _jointLane[m];
var rotation = new Quat(v.JointRotationX[j], v.JointRotationY[j], v.JointRotationZ[j], v.JointRotationW[j]);
@ -174,29 +110,27 @@ namespace Lodur.Body.Ymir
}
/// <summary>
/// Writes each <see cref="Region"/>'s world point into the caller's arrays, one entry per region: a hand is its
/// palm body's centre, the head the head body's centre. Allocates nothing.
/// Writes each plan sense point's world position into the caller's arrays, one entry per sense point: its part's position plus
/// the part's rotation applied to the point's offset. Allocates nothing.
/// </summary>
public void ReadRegions(Span<float> x, Span<float> y, Span<float> z)
public void ReadSensePoints(Span<float> x, Span<float> y, Span<float> z)
{
if (x.Length != RegionCount || y.Length != RegionCount || z.Length != RegionCount)
var points = Plan.SensePoints;
if (x.Length != points.Count || y.Length != points.Count || z.Length != points.Count)
{
throw new ArgumentException($"x, y and z need {RegionCount} entries, one per region.");
throw new ArgumentException($"x, y and z need {points.Count} entries, one per sense point.");
}
var v = _world.View;
for (var r = 0; r < (int)Region.Head; r++)
for (var s = 0; s < points.Count; s++)
{
var i = _bodyLane[(int)(r == (int)Region.HandL ? Limb.PalmL : Limb.PalmR)];
x[r] = v.PositionX[i];
y[r] = v.PositionY[i];
z[r] = v.PositionZ[i];
var i = _bodyLane[points[s].Part];
var o = points[s].Offset;
new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]).Rotate(o.X, o.Y, o.Z, out var rx, out var ry, out var rz);
x[s] = v.PositionX[i] + rx;
y[s] = v.PositionY[i] + ry;
z[s] = v.PositionZ[i] + rz;
}
var head = _bodyLane[(int)Limb.Head];
x[(int)Region.Head] = v.PositionX[head];
y[(int)Region.Head] = v.PositionY[head];
z[(int)Region.Head] = v.PositionZ[head];
}
}
}

View file

@ -18,30 +18,37 @@ internal sealed class ConnectedPainBox : IDisposable
public static readonly (float X, float Y, float Z) Box = (-0.210f, 1.116f, 0.441f);
public readonly Box3DSoaWorld World;
public readonly HumanoidRagdoll Ragdoll;
public readonly BodyPlan Plan = BodyPlans.Humanoid();
public readonly Ragdoll Ragdoll;
public readonly Actor Actor;
public readonly BoxStimulus[] Sources = { new BoxStimulus(Box.X, Box.Y, Box.Z, BoxHalf, BoxHalf, BoxHalf) };
public readonly float[] X = new float[HumanoidRagdoll.RegionCount], Y = new float[HumanoidRagdoll.RegionCount], Z = new float[HumanoidRagdoll.RegionCount];
public readonly float[] Strength = new float[HumanoidRagdoll.MuscleCount];
public readonly Quat[] Target = new Quat[HumanoidRagdoll.MuscleCount];
public readonly float[] X, Y, Z;
public readonly float[] Strength;
public readonly Quat[] Target;
private readonly int _handR;
private SplitMix64 _rng;
public ConnectedPainBox(ulong seed, HoldParameters? hold = null, DriveParameters? driveTunables = null)
{
World = new Box3DSoaWorld(capacity: HumanoidRagdoll.LimbCount + 2, jointCapacity: HumanoidRagdoll.MuscleCount + 1);
var (bodies, joints) = Ragdoll.Needs(Plan);
X = new float[Plan.SensePoints.Count]; Y = new float[Plan.SensePoints.Count]; Z = new float[Plan.SensePoints.Count];
Strength = new float[Plan.Joints.Count];
Target = new Quat[Plan.Joints.Count];
_handR = Plan.SenseIndex("Hand", Side.Right);
World = new Box3DSoaWorld(capacity: bodies + 2, jointCapacity: joints + 1);
World.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
var stool = World.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f);
Ragdoll = HumanoidRagdoll.Build(World, (0f, 0f), firstStableId: 100);
World.AddJoint(Box3DSoaJointKind.Weld, stool, Ragdoll.BodyLane(Limb.Pelvis), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
Ragdoll = Ragdoll.Build(World, Plan, (0f, 0f), firstStableId: 100);
World.AddJoint(Box3DSoaJointKind.Weld, stool, Ragdoll.BodyLane(Plan.PartIndex("Pelvis")), (0f, 1.11f, -0.09f), (0f, 1f, 0f));
var holdPose = new Quat[HumanoidRagdoll.MuscleCount];
var withdrawPose = new Quat[HumanoidRagdoll.MuscleCount];
var holdPose = new Quat[Plan.Joints.Count];
var withdrawPose = new Quat[Plan.Joints.Count];
Array.Fill(holdPose, Quat.Identity);
Array.Fill(withdrawPose, Quat.Identity);
holdPose[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, -1.0f);
holdPose[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -0.6f);
withdrawPose[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
withdrawPose[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -2.0f);
holdPose[Plan.JointIndex("Shoulder", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, -1.0f);
holdPose[Plan.JointIndex("Elbow", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, -0.6f);
withdrawPose[Plan.JointIndex("Shoulder", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
withdrawPose[Plan.JointIndex("Elbow", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, -2.0f);
_rng = new SplitMix64(seed);
var gain = 1.0 + 0.2 * _rng.NextSigned();
@ -69,7 +76,7 @@ internal sealed class ConnectedPainBox : IDisposable
},
},
};
Actor = new Actor(Dt, HumanoidRagdoll.RegionCount, new NerveParameters { Gain = gain }, new WithdrawalParameters(),
Actor = new Actor(Dt, Plan.SensePoints.Count, new NerveParameters { Gain = gain }, new WithdrawalParameters(),
(driveTunables ?? new DriveParameters()) with { DrainTrait = drain }, brain);
}
@ -78,7 +85,7 @@ internal sealed class ConnectedPainBox : IDisposable
/// <summary>Right hand point now.</summary>
public (float X, float Y, float Z) Hand
{
get { Ragdoll.ReadRegions(X, Y, Z); return (X[(int)Region.HandR], Y[(int)Region.HandR], Z[(int)Region.HandR]); }
get { Ragdoll.ReadSensePoints(X, Y, Z); return (X[_handR], Y[_handR], Z[_handR]); }
}
public bool HandInBox => Sources[0].Contains(Hand.X, Hand.Y, Hand.Z);
@ -89,7 +96,7 @@ internal sealed class ConnectedPainBox : IDisposable
var tick = Actor.TickCount;
var ramp = Math.Min(1.0, tick * Dt / 2.0);
Sources[0].Intensity = Math.Max(0.0, 0.8 * ramp * (1.0 + 0.1 * _rng.NextSigned()));
Ragdoll.ReadRegions(X, Y, Z);
Ragdoll.ReadSensePoints(X, Y, Z);
var events = Actor.Tick(X, Y, Z, Sources, Strength, Target);
Ragdoll.Drive(Strength, Target);
World.Step((float)Dt, 4);
@ -105,29 +112,29 @@ public sealed class ConnectedPainBoxTests
MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y) + (a.Z - b.Z) * (a.Z - b.Z));
[Fact]
public void ReadRegions_puts_the_hands_at_the_palms_at_the_creation_pose()
public void ReadSensePoints_puts_the_hands_at_the_palms_at_the_creation_pose()
{
using var s = new RagdollScenario(seed: 1);
var x = new float[HumanoidRagdoll.RegionCount]; var y = new float[HumanoidRagdoll.RegionCount]; var z = new float[HumanoidRagdoll.RegionCount];
s.Ragdoll.ReadRegions(x, y, z);
Assert.Equal(0.21f, x[(int)Region.HandL], 3);
Assert.Equal(-0.21f, x[(int)Region.HandR], 3);
Assert.Equal(0.93f, y[(int)Region.HandR], 3);
Assert.Equal(0f, z[(int)Region.HandR], 3);
Assert.Equal(0f, x[(int)Region.Head], 3); // the head body's centre, within a millimetre
Assert.Equal(1.74f, y[(int)Region.Head], 3);
Assert.Equal(0f, z[(int)Region.Head], 3);
Assert.Throws<ArgumentException>(() => s.Ragdoll.ReadRegions(new float[1], y, z));
var x = new float[3]; var y = new float[3]; var z = new float[3];
s.Ragdoll.ReadSensePoints(x, y, z);
Assert.Equal(0.21f, x[s.Plan.SenseIndex("Hand", Side.Left)], 3);
Assert.Equal(-0.21f, x[s.Plan.SenseIndex("Hand", Side.Right)], 3);
Assert.Equal(0.93f, y[s.Plan.SenseIndex("Hand", Side.Right)], 3);
Assert.Equal(0f, z[s.Plan.SenseIndex("Hand", Side.Right)], 3);
Assert.Equal(0f, x[s.Plan.SenseIndex("Head")], 3); // the head body's centre, within a millimetre
Assert.Equal(1.74f, y[s.Plan.SenseIndex("Head")], 3);
Assert.Equal(0f, z[s.Plan.SenseIndex("Head")], 3);
Assert.Throws<ArgumentException>(() => s.Ragdoll.ReadSensePoints(new float[1], y, z));
}
[Fact]
public void ReadRegions_allocates_nothing()
public void ReadSensePoints_allocates_nothing()
{
using var s = new RagdollScenario(seed: 1);
var x = new float[HumanoidRagdoll.RegionCount]; var y = new float[HumanoidRagdoll.RegionCount]; var z = new float[HumanoidRagdoll.RegionCount];
s.Ragdoll.ReadRegions(x, y, z);
var x = new float[3]; var y = new float[3]; var z = new float[3];
s.Ragdoll.ReadSensePoints(x, y, z);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++) s.Ragdoll.ReadRegions(x, y, z);
for (var i = 0; i < 1000; i++) s.Ragdoll.ReadSensePoints(x, y, z);
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
}

View file

@ -6,7 +6,8 @@ namespace Lodur.Tests;
public sealed class HandTests
{
private static readonly Limb[] HandBodies = { Limb.PalmL, Limb.PalmR, Limb.ThumbL, Limb.ThumbR, Limb.FingersL, Limb.FingersR };
private static int[] HandBodies(RagdollScenario s) =>
new[] { "Palm", "Thumb", "Fingers" }.SelectMany(l => new[] { s.Plan.PartIndex(l, Side.Left), s.Plan.PartIndex(l, Side.Right) }).ToArray();
/// <summary>FNV-1a 64 over the creation lanes of the 13 base bodies (world lanes 1..13) and the 12 base joints.</summary>
private static ulong BaseCreationHash(Box3DSoaWorld world)
@ -31,8 +32,11 @@ public sealed class HandTests
return h;
}
/// <summary>Recorded at Lodur dedf391 (no hands); equal there and with the hands appended.</summary>
private const ulong BaseHash = 0xccf5cedb0df1b2e8ul;
/// <summary>
/// Re-recorded at the BodyPlan cut: the Limb lane now carries plan part ordinals (it carried the old Limb enum values, which differ
/// from LowerArmL on). With the Limb term left out the function gives 0x65216f91ffc63d24 on both Lodur d7a626b and this cut.
/// </summary>
private const ulong BaseHash = 0xbbcc7aff6c088398ul;
[Fact]
public void Hands_are_appended_after_the_base_bodies_and_joints_and_leave_them_as_they_were()
@ -44,23 +48,23 @@ public sealed class HandTests
Assert.Equal(18, v.JointCount);
Assert.Equal(BaseHash, BaseCreationHash(s.World));
Assert.Equal(new ulong[] { 113, 114, 115, 116, 117, 118 }, Enumerable.Range(14, 6).Select(i => v.StableId[i]).ToArray());
Assert.All(HandBodies, l => Assert.InRange(r.BodyLane(l), 14, 19));
foreach (var m in new[] { Muscle.WristL, Muscle.WristR, Muscle.ThumbL, Muscle.ThumbR, Muscle.FingersL, Muscle.FingersR }) Assert.InRange(r.JointLane(m), 12, 17);
foreach (var side in new[] { 0, 1 })
Assert.All(HandBodies(s), l => Assert.InRange(r.BodyLane(l), 14, 19));
foreach (var m in new[] { "Wrist", "Thumb", "Fingers" }.SelectMany(l => new[] { s.Plan.JointIndex(l, Side.Left), s.Plan.JointIndex(l, Side.Right) })) Assert.InRange(r.JointLane(m), 12, 17);
foreach (var side in new[] { Side.Left, Side.Right })
{
var palm = r.BodyLane(Limb.PalmL + side);
var thumb = r.BodyLane(Limb.ThumbL + side);
var fingers = r.BodyLane(Limb.FingersL + side);
Assert.Equal(r.BodyLane(Limb.LowerArmL + side), v.Parent[palm]);
var palm = r.BodyLane(s.Plan.PartIndex("Palm", side));
var thumb = r.BodyLane(s.Plan.PartIndex("Thumb", side));
var fingers = r.BodyLane(s.Plan.PartIndex("Fingers", side));
Assert.Equal(r.BodyLane(s.Plan.PartIndex("LowerArm", side)), v.Parent[palm]);
Assert.Equal(palm, v.Parent[thumb]);
Assert.Equal(palm, v.Parent[fingers]);
Assert.Equal(((uint)Box3DSoaKind.Box, (uint)Box3DSoaKind.Capsule, (uint)Box3DSoaKind.Box), (v.Kind[palm], v.Kind[thumb], v.Kind[fingers]));
Assert.Equal((0.014f, 0.045f, 0.040f), (v.Size0[palm], v.Size1[palm], v.Size2[palm]));
Assert.Equal((0.011f, 0.03f), (v.Size0[thumb], v.Size1[thumb]));
Assert.Equal((0.011f, 0.0425f, 0.038f), (v.Size0[fingers], v.Size1[fingers], v.Size2[fingers]));
Assert.Equal((r.BodyLane(Limb.LowerArmL + side), palm), (v.JointBodyA[r.JointLane(Muscle.WristL + side)], v.JointBodyB[r.JointLane(Muscle.WristL + side)]));
Assert.Equal((palm, thumb), (v.JointBodyA[r.JointLane(Muscle.ThumbL + side)], v.JointBodyB[r.JointLane(Muscle.ThumbL + side)]));
Assert.Equal((palm, fingers), (v.JointBodyA[r.JointLane(Muscle.FingersL + side)], v.JointBodyB[r.JointLane(Muscle.FingersL + side)]));
Assert.Equal((r.BodyLane(s.Plan.PartIndex("LowerArm", side)), palm), (v.JointBodyA[r.JointLane(s.Plan.JointIndex("Wrist", side))], v.JointBodyB[r.JointLane(s.Plan.JointIndex("Wrist", side))]));
Assert.Equal((palm, thumb), (v.JointBodyA[r.JointLane(s.Plan.JointIndex("Thumb", side))], v.JointBodyB[r.JointLane(s.Plan.JointIndex("Thumb", side))]));
Assert.Equal((palm, fingers), (v.JointBodyA[r.JointLane(s.Plan.JointIndex("Fingers", side))], v.JointBodyB[r.JointLane(s.Plan.JointIndex("Fingers", side))]));
}
}
@ -70,18 +74,18 @@ public sealed class HandTests
using var s = new RagdollScenario(seed: 2);
Array.Clear(s.Strength);
s.Run(1.0f); // falling: the palms are nowhere near the creation pose
var x = new float[HumanoidRagdoll.RegionCount]; var y = new float[HumanoidRagdoll.RegionCount]; var z = new float[HumanoidRagdoll.RegionCount];
s.Ragdoll.ReadRegions(x, y, z);
var x = new float[3]; var y = new float[3]; var z = new float[3];
s.Ragdoll.ReadSensePoints(x, y, z);
var v = s.World.View;
foreach (var (region, limb) in new[] { (Region.HandL, Limb.PalmL), (Region.HandR, Limb.PalmR) })
foreach (var (region, limb) in new[] { (s.Plan.SenseIndex("Hand", Side.Left), s.Plan.PartIndex("Palm", Side.Left)), (s.Plan.SenseIndex("Hand", Side.Right), s.Plan.PartIndex("Palm", Side.Right)) })
{
var i = s.Ragdoll.BodyLane(limb);
Assert.Equal((v.PositionX[i], v.PositionY[i], v.PositionZ[i]), (x[(int)region], y[(int)region], z[(int)region]));
Assert.Equal((v.PositionX[i], v.PositionY[i], v.PositionZ[i]), (x[region], y[region], z[region]));
}
}
/// <summary>Runs <paramref name="runSeconds"/>, then one more second step by step; the fastest the limbs turn and move in that second.</summary>
private static (float Angular, float Linear) LastSecond(RagdollScenario s, float runSeconds, IEnumerable<Limb> limbs)
private static (float Angular, float Linear) LastSecond(RagdollScenario s, float runSeconds, IEnumerable<int> limbs)
{
s.Run(runSeconds);
float ang = 0f, lin = 0f;
@ -106,7 +110,7 @@ public sealed class HandTests
public void Hands_rest_standing_palm_thumb_and_fingers_alike(ulong seed)
{
using var s = new RagdollScenario(seed);
var (ang, _) = LastSecond(s, 5f, HandBodies);
var (ang, _) = LastSecond(s, 5f, HandBodies(s));
Assert.True(ang < 0.05f, $"seed {seed}: a hand body (thumbs included: a free thumb twist spins) still turns at {ang} rad/s in the last second of 6");
}
@ -117,7 +121,7 @@ public sealed class HandTests
{
using var s = new RagdollScenario(seed);
Array.Clear(s.Strength);
var (ang, lin) = LastSecond(s, 7f, HandBodies);
var (ang, lin) = LastSecond(s, 7f, HandBodies(s));
Assert.True(ang < 1f && lin < 0.1f, $"seed {seed}: a limp hand still moves at {lin} m/s, {ang} rad/s in the last second of 8");
}
}
@ -179,26 +183,26 @@ public sealed class HandTests
{
var (seed, half) = cases[k];
using var s = new RagdollScenario(seed);
var all = Enumerable.Range(0, HumanoidRagdoll.MuscleCount).ToArray();
var sep = new JointSeparation(s.World, all.Select(m => s.Ragdoll.JointLane((Muscle)m)));
var all = Enumerable.Range(0, s.Plan.Joints.Count).ToArray();
var sep = new JointSeparation(s.World, all.Select(m => s.Ragdoll.JointLane(m)));
float hand = 0f, body = 0f;
for (var i = 0; i < 6 * 120; i++)
{
var strike = (i / half) % 2 == 0;
foreach (var (sh, el) in new[] { (Muscle.ShoulderL, Muscle.ElbowL), (Muscle.ShoulderR, Muscle.ElbowR) })
foreach (var (sh, el) in new[] { (s.Plan.JointIndex("Shoulder", Side.Left), s.Plan.JointIndex("Elbow", Side.Left)), (s.Plan.JointIndex("Shoulder", Side.Right), s.Plan.JointIndex("Elbow", Side.Right)) })
{
s.Target[(int)sh] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? -1.5f : -0.5f);
s.Target[(int)el] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? 0f : -2.2f);
s.Target[sh] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? -1.5f : -0.5f);
s.Target[el] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? 0f : -2.2f);
}
s.Target[(int)Muscle.FingersL] = s.Target[(int)Muscle.FingersR] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? -1.5f : 0f);
s.Target[(int)Muscle.WristL] = s.Target[(int)Muscle.WristR] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? 0.8f : -0.8f);
s.Target[s.Plan.JointIndex("Fingers", Side.Left)] = s.Target[s.Plan.JointIndex("Fingers", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, strike ? -1.5f : 0f);
s.Target[s.Plan.JointIndex("Wrist", Side.Left)] = s.Target[s.Plan.JointIndex("Wrist", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, strike ? 0.8f : -0.8f);
s.Run(RagdollScenario.Dt);
var v = s.World.View;
for (var b = 0; b < v.Count; b++)
{
Assert.True(float.IsFinite(v.PositionX[b] + v.PositionY[b] + v.PositionZ[b] + v.RotationW[b] + v.VelocityX[b] + v.AngularVelocityX[b]), $"seed {seed} half {half}: body {b} is finite at step {i}");
}
var (h, bo) = sep.MaxBy(v, (int)Muscle.WristL);
var (h, bo) = sep.MaxBy(v, s.Plan.JointIndex("Wrist", Side.Left));
hand = MathF.Max(hand, h);
body = MathF.Max(body, bo);
}
@ -220,7 +224,7 @@ public sealed class HandTests
}
/// <summary>Swing of a joint's rotation off its axis, radians (the twist about the joint z removed).</summary>
private static float Swing(RagdollScenario s, Muscle m)
private static float Swing(RagdollScenario s, int m)
{
var v = s.World.View;
var j = s.Ragdoll.JointLane(m);
@ -229,22 +233,22 @@ public sealed class HandTests
}
/// <summary>How far the fingers are curled from straight (palm-frame), radians; curl is positive for both hands.</summary>
private static float Curl(RagdollScenario s, int side)
private static float Curl(RagdollScenario s, Side side)
{
var v = s.World.View;
var palm = s.Ragdoll.BodyLane(Limb.PalmL + side);
var fingers = s.Ragdoll.BodyLane(Limb.FingersL + side);
var palm = s.Ragdoll.BodyLane(s.Plan.PartIndex("Palm", side));
var fingers = s.Ragdoll.BodyLane(s.Plan.PartIndex("Fingers", side));
var relative = new Quat(v.RotationX[palm], v.RotationY[palm], v.RotationZ[palm], v.RotationW[palm]).Conjugate()
* new Quat(v.RotationX[fingers], v.RotationY[fingers], v.RotationZ[fingers], v.RotationW[fingers]);
var sx = side == 0 ? 1f : -1f;
var sx = side == Side.Left ? 1f : -1f;
var angleAboutZ = 2f * MathF.Atan2(relative.Z, relative.W);
return -sx * angleAboutZ;
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void The_fingers_rest_relaxed_at_creation_and_stay_there_while_nothing_grips(int side)
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void The_fingers_rest_relaxed_at_creation_and_stay_there_while_nothing_grips(Side side)
{
using var s = new RagdollScenario(seed: 1);
Assert.Equal(0.35f, Curl(s, side), 0.01f); // ruling hand-rest-curl-relaxed
@ -253,14 +257,14 @@ public sealed class HandTests
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void The_knuckle_curls_to_1_6_rad_from_straight_and_extends_0_35_rad_past_it_and_no_further(int side)
[InlineData(Side.Left)]
[InlineData(Side.Right)]
public void The_knuckle_curls_to_1_6_rad_from_straight_and_extends_0_35_rad_past_it_and_no_further(Side side)
{
float Reach(float target)
{
using var s = new RagdollScenario(seed: 1);
s.Target[(int)Muscle.FingersL + side] = Quat.FromAxisAngle(0f, 0f, 1f, target);
s.Target[s.Plan.JointIndex("Fingers", side)] = Quat.FromAxisAngle(0f, 0f, 1f, target);
s.Run(2f);
return Curl(s, side);
}
@ -270,22 +274,23 @@ public sealed class HandTests
}
[Theory]
[InlineData(Muscle.WristL, 1.0f)]
[InlineData(Muscle.WristR, 1.0f)]
[InlineData(Muscle.ThumbL, 0.7f)]
[InlineData(Muscle.ThumbR, 0.7f)]
public void A_hand_joint_swings_to_its_cone_and_no_further_whichever_way_it_is_told(Muscle joint, float cone)
[InlineData("Wrist", Side.Left, 1.0f)]
[InlineData("Wrist", Side.Right, 1.0f)]
[InlineData("Thumb", Side.Left, 0.7f)]
[InlineData("Thumb", Side.Right, 0.7f)]
public void A_hand_joint_swings_to_its_cone_and_no_further_whichever_way_it_is_told(string label, Side side, float cone)
{
var reached = 0f;
foreach (var (ax, ay) in new[] { (1f, 0f), (-1f, 0f), (0f, 1f), (0f, -1f) })
{
using var s = new RagdollScenario(seed: 1);
s.Target[(int)joint] = Quat.FromAxisAngle(ax, ay, 0f, 2.5f);
var joint = s.Plan.JointIndex(label, side);
s.Target[joint] = Quat.FromAxisAngle(ax, ay, 0f, 2.5f);
s.Run(2f);
var swing = Swing(s, joint);
Assert.True(swing < cone + 0.06f, $"{joint} swung {swing} past its cone {cone} toward ({ax}, {ay})");
Assert.True(swing < cone + 0.06f, $"{label} {side} swung {swing} past its cone {cone} toward ({ax}, {ay})");
reached = MathF.Max(reached, swing);
}
Assert.True(reached > cone - 0.15f, $"{joint} only swung {reached} of its cone {cone} in any direction");
Assert.True(reached > cone - 0.15f, $"{label} {side} only swung {reached} of its cone {cone} in any direction");
}
}

View file

@ -0,0 +1,96 @@
using Lodur;
using Lodur.Body.Ymir;
using Ymir.Box3D;
namespace Lodur.Tests;
/// <summary>The builder assumes no species: a six-part quadruped builds and steps beside the humanoid in one caller world.</summary>
public sealed class QuadrupedPlanTests
{
private static BodyPlan Quadruped()
{
PartDef Part(string label, Side side, PartShape shape, (float, float, float) size, (float, float, float) at) =>
new(label, side, shape, size, at, Quat.Identity, 1000f, 0.8f, 0f);
JointDef Joint(string label, Side side, JointKind kind, int parent, int child, (float, float, float) at, (float, float, float) axis, float lower, float upper, float cone) =>
new(label, side, kind, parent, child, at, axis, lower, upper, cone, new MuscleGains(10f, 1f, 5f, 0.5f));
var parts = new[]
{
Part("Trunk", Side.Center, PartShape.Box, (0.4f, 0.15f, 0.12f), (0f, 0.6f, 0f)),
Part("Head", Side.Center, PartShape.Sphere, (0.12f, 0f, 0f), (0.55f, 0.8f, 0f)),
Part("Foreleg", Side.Left, PartShape.Capsule, (0.04f, 0.2f, 0f), (0.3f, 0.25f, 0.1f)),
Part("Foreleg", Side.Right, PartShape.Capsule, (0.04f, 0.2f, 0f), (0.3f, 0.25f, -0.1f)),
Part("Hindleg", Side.Left, PartShape.Capsule, (0.04f, 0.2f, 0f), (-0.3f, 0.25f, 0.1f)),
Part("Hindleg", Side.Right, PartShape.Capsule, (0.04f, 0.2f, 0f), (-0.3f, 0.25f, -0.1f)),
};
var joints = new[]
{
Joint("Neck", Side.Center, JointKind.Spherical, 0, 1, (0.45f, 0.7f, 0f), (0f, 1f, 0f), -0.5f, 0.5f, 0.5f),
Joint("Shoulder", Side.Left, JointKind.Revolute, 0, 2, (0.3f, 0.5f, 0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
Joint("Shoulder", Side.Right, JointKind.Revolute, 0, 3, (0.3f, 0.5f, -0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
Joint("Hip", Side.Left, JointKind.Revolute, 0, 4, (-0.3f, 0.5f, 0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
Joint("Hip", Side.Right, JointKind.Revolute, 0, 5, (-0.3f, 0.5f, -0.1f), (0f, 0f, 1f), -1f, 1f, 0f),
};
return new BodyPlan(parts, joints, new[] { new SensePointDef("Muzzle", Side.Center, 1, (0.12f, 0f, 0f)) });
}
[Fact]
public void A_quadruped_builds_after_the_humanoid_in_one_world_in_its_own_plan_order_and_steps_finite()
{
var humanoidPlan = BodyPlans.Humanoid();
var quadPlan = Quadruped();
var (hb, hj) = Ragdoll.Needs(humanoidPlan);
var (qb, qj) = Ragdoll.Needs(quadPlan);
Assert.Equal((6, 5), (qb, qj));
using var world = new Box3DSoaWorld(capacity: hb + qb + 1, jointCapacity: hj + qj);
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
var human = Ragdoll.Build(world, humanoidPlan, (0f, 0f), firstStableId: 100);
var quad = Ragdoll.Build(world, quadPlan, (2f, 0f), firstStableId: 200);
var v = world.View;
Assert.Equal(1 + hb + qb, v.Count);
Assert.Equal(hj + qj, v.JointCount);
for (var i = 0; i < qb; i++)
{
var lane = quad.BodyLane(i);
Assert.Equal(1 + hb + i, lane); // contiguous, right after the humanoid
Assert.Equal(200ul + (ulong)i, v.StableId[lane]); // stable id = first + plan ordinal
Assert.Equal(i, v.Limb[lane]); // limb lane = plan ordinal
Assert.Equal(quadPlan.ParentOf(i) < 0 ? -1 : quad.BodyLane(quadPlan.ParentOf(i)), v.Parent[lane]);
}
for (var j = 0; j < qj; j++)
{
var lane = quad.JointLane(j);
Assert.Equal(hj + j, lane);
Assert.Equal((quad.BodyLane(quadPlan.Joints[j].Parent), quad.BodyLane(quadPlan.Joints[j].Child)), (v.JointBodyA[lane], v.JointBodyB[lane]));
}
Assert.Equal((uint)Box3DSoaKind.Box, v.Kind[quad.BodyLane(quadPlan.PartIndex("Trunk"))]);
Assert.Equal((uint)Box3DSoaKind.Sphere, v.Kind[quad.BodyLane(quadPlan.PartIndex("Head"))]);
Assert.Equal((uint)Box3DSoaKind.Capsule, v.Kind[quad.BodyLane(quadPlan.PartIndex("Hindleg", Side.Right))]);
Assert.Equal(2.3f, v.PositionX[quad.BodyLane(quadPlan.PartIndex("Foreleg", Side.Left))], 4); // origin x 2 + plan x 0.3
var humanStrength = new float[humanoidPlan.Joints.Count]; var humanTarget = new Quat[humanoidPlan.Joints.Count];
var quadStrength = new float[qj]; var quadTarget = new Quat[qj];
Array.Fill(humanTarget, Quat.Identity); Array.Fill(quadTarget, Quat.Identity);
for (var tick = 0; tick < 60; tick++)
{
human.Drive(humanStrength, humanTarget);
quad.Drive(quadStrength, quadTarget);
world.Step(1f / 120f, 4);
}
for (var i = 0; i < v.Count; i++)
{
Assert.True(float.IsFinite(v.PositionX[i] + v.PositionY[i] + v.PositionZ[i] + v.RotationW[i]), $"body {i} finite");
}
var x = new float[1]; var y = new float[1]; var z = new float[1];
quad.ReadSensePoints(x, y, z);
var head = quad.BodyLane(quadPlan.PartIndex("Head"));
Assert.True(MathF.Abs(x[0] - v.PositionX[head]) < 0.2f); // the muzzle sits within its offset of the head
Assert.Throws<ArgumentException>(() => quad.ReadSensePoints(new float[3], new float[3], new float[3]));
Assert.Throws<ArgumentException>(() => quad.Drive(new float[3], quadTarget));
}
}

View file

@ -9,17 +9,20 @@ internal sealed class RagdollScenario : IDisposable
{
public const float Dt = 1f / 120f;
public readonly Box3DSoaWorld World;
public readonly HumanoidRagdoll Ragdoll;
public readonly float[] Strength = new float[HumanoidRagdoll.MuscleCount];
public readonly Quat[] Target = new Quat[HumanoidRagdoll.MuscleCount];
public readonly BodyPlan Plan = BodyPlans.Humanoid();
public readonly Ragdoll Ragdoll;
public readonly float[] Strength;
public readonly Quat[] Target;
private int _steps;
public RagdollScenario(ulong seed)
{
var (bodies, joints) = HumanoidRagdoll.Needs;
var (bodies, joints) = Ragdoll.Needs(Plan);
Strength = new float[Plan.Joints.Count];
Target = new Quat[Plan.Joints.Count];
World = new Box3DSoaWorld(capacity: bodies + 1, jointCapacity: joints);
World.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f);
Ragdoll = HumanoidRagdoll.Build(World, (0f, 0f), firstStableId: 100);
Ragdoll = Ragdoll.Build(World, Plan, (0f, 0f), firstStableId: 100);
Array.Fill(Target, Quat.Identity);
Array.Fill(Strength, 1f);
Shove(seed);
@ -30,7 +33,7 @@ internal sealed class RagdollScenario : IDisposable
{
var rng = new SplitMix64(seed);
var v = World.View;
foreach (var limb in new[] { Limb.Pelvis, Limb.Torso })
foreach (var limb in new[] { Plan.PartIndex("Pelvis"), Plan.PartIndex("Torso") })
{
var i = Ragdoll.BodyLane(limb);
v.TorqueX[i] = 30f * rng.NextSigned();
@ -50,14 +53,14 @@ internal sealed class RagdollScenario : IDisposable
}
}
public float HeadHeight => World.View.PositionY[Ragdoll.BodyLane(Limb.Head)];
public float PelvisHeight => World.View.PositionY[Ragdoll.BodyLane(Limb.Pelvis)];
public float HeadHeight => World.View.PositionY[Ragdoll.BodyLane(Plan.PartIndex("Head"))];
public float PelvisHeight => World.View.PositionY[Ragdoll.BodyLane(Plan.PartIndex("Pelvis"))];
/// <summary>Linear and angular speed of one limb's body.</summary>
public (float Linear, float Angular) Speeds(Limb limb)
public (float Linear, float Angular) Speeds(int part)
{
var v = World.View;
var i = Ragdoll.BodyLane(limb);
var i = Ragdoll.BodyLane(part);
return (MathF.Sqrt(v.VelocityX[i] * v.VelocityX[i] + v.VelocityY[i] * v.VelocityY[i] + v.VelocityZ[i] * v.VelocityZ[i]),
MathF.Sqrt(v.AngularVelocityX[i] * v.AngularVelocityX[i] + v.AngularVelocityY[i] * v.AngularVelocityY[i] + v.AngularVelocityZ[i] * v.AngularVelocityZ[i]));
}

View file

@ -25,10 +25,10 @@ public sealed class RagdollTests
/// <summary>The trunk is at rest; extremities may still rock a little (a head resting on an arm chatters at a few rad/s for seconds).</summary>
private static void AssertResting(RagdollScenario s, string label)
{
foreach (var limb in new[] { Limb.Pelvis, Limb.Torso })
foreach (var (limb, name) in new[] { (s.Plan.PartIndex("Pelvis"), "Pelvis"), (s.Plan.PartIndex("Torso"), "Torso") })
{
var (linear, angular) = s.Speeds(limb);
Assert.True(linear < 0.05f && angular < 0.2f, $"{label}: {limb} at {linear} m/s, {angular} rad/s");
Assert.True(linear < 0.05f && angular < 0.2f, $"{label}: {name} at {linear} m/s, {angular} rad/s");
}
var (maxLinear, maxAngular) = s.MaxSpeeds();
Assert.True(maxLinear < 0.6f && maxAngular < 6f, $"{label}: an extremity still moves at {maxLinear} m/s, {maxAngular} rad/s");
@ -74,12 +74,12 @@ public sealed class RagdollTests
{
using var s = new RagdollScenario(seed: 1);
// Both knees are told to flex 0.5 rad about their hinge (the joint frame's z axis).
s.Target[(int)Muscle.KneeL] = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
s.Target[(int)Muscle.KneeR] = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
s.Strength[(int)Muscle.KneeL] = leftStrength; // a caller-owned element, written in place
s.Target[s.Plan.JointIndex("Knee", Side.Left)] = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
s.Target[s.Plan.JointIndex("Knee", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
s.Strength[s.Plan.JointIndex("Knee", Side.Left)] = leftStrength; // a caller-owned element, written in place
s.Run(0.5f);
var v = s.World.View;
return (v.JointAngle[s.Ragdoll.JointLane(Muscle.KneeL)], v.JointAngle[s.Ragdoll.JointLane(Muscle.KneeR)]);
return (v.JointAngle[s.Ragdoll.JointLane(s.Plan.JointIndex("Knee", Side.Left))], v.JointAngle[s.Ragdoll.JointLane(s.Plan.JointIndex("Knee", Side.Right))]);
}
var (strongL, strongR) = Knees(1f);
@ -107,7 +107,7 @@ public sealed class RagdollTests
Assert.Equal(a, Hashes(42));
Assert.Equal(a.Count, a.Distinct().Count()); // the hash moves every checkpoint: the ragdoll is not frozen
Assert.NotEqual(a[0], Hashes(43)[0]); // the seed matters
Assert.NotEqual(a[0], Hashes(42, (int)Muscle.HipL)[0]); // and so does one strength element
Assert.NotEqual(a[0], Hashes(42, BodyPlans.Humanoid().JointIndex("Hip", Side.Left))[0]); // and so does one strength element
}
[Fact]
@ -117,10 +117,10 @@ public sealed class RagdollTests
var v = s.World.View;
v.TorqueX.Clear(); v.TorqueY.Clear(); v.TorqueZ.Clear(); // drop the shove
Array.Clear(s.Strength);
s.Strength[(int)Muscle.ElbowL] = 1f;
s.Strength[(int)Muscle.HipR] = 1f;
s.Target[(int)Muscle.ElbowL] = Quat.FromAxisAngle(0f, 0f, 1f, -0.5f);
s.Target[(int)Muscle.HipR] = Quat.FromAxisAngle(1f, 0f, 0f, 0.4f);
s.Strength[s.Plan.JointIndex("Elbow", Side.Left)] = 1f;
s.Strength[s.Plan.JointIndex("Hip", Side.Right)] = 1f;
s.Target[s.Plan.JointIndex("Elbow", Side.Left)] = Quat.FromAxisAngle(0f, 0f, 1f, -0.5f);
s.Target[s.Plan.JointIndex("Hip", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, 0.4f);
s.Ragdoll.Drive(s.Strength, s.Target);
float sx = 0f, sy = 0f, sz = 0f;
@ -131,16 +131,16 @@ public sealed class RagdollTests
var touched = Enumerable.Range(0, v.Count).Where(i => v.TorqueX[i] != 0f || v.TorqueY[i] != 0f || v.TorqueZ[i] != 0f).ToHashSet();
Assert.Equal(new HashSet<int>
{
s.Ragdoll.BodyLane(Limb.UpperArmL), s.Ragdoll.BodyLane(Limb.LowerArmL),
s.Ragdoll.BodyLane(Limb.Pelvis), s.Ragdoll.BodyLane(Limb.ThighR),
s.Ragdoll.BodyLane(s.Plan.PartIndex("UpperArm", Side.Left)), s.Ragdoll.BodyLane(s.Plan.PartIndex("LowerArm", Side.Left)),
s.Ragdoll.BodyLane(s.Plan.PartIndex("Pelvis")), s.Ragdoll.BodyLane(s.Plan.PartIndex("Thigh", Side.Right)),
}, touched);
Assert.NotEqual(0f, v.TorqueX[s.Ragdoll.BodyLane(Limb.LowerArmL)]);
Assert.NotEqual(0f, v.TorqueX[s.Ragdoll.BodyLane(s.Plan.PartIndex("LowerArm", Side.Left))]);
}
private static float TorqueNorm(RagdollScenario s, Limb limb)
private static float TorqueNorm(RagdollScenario s, int part)
{
var v = s.World.View;
var i = s.Ragdoll.BodyLane(limb);
var i = s.Ragdoll.BodyLane(part);
return MathF.Sqrt(v.TorqueX[i] * v.TorqueX[i] + v.TorqueY[i] * v.TorqueY[i] + v.TorqueZ[i] * v.TorqueZ[i]);
}
@ -155,16 +155,16 @@ public sealed class RagdollTests
{
using var s = new RagdollScenario(seed: 1);
Array.Clear(s.Strength);
s.Target[(int)Muscle.HipL] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
s.Target[s.Plan.JointIndex("Hip", Side.Left)] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f);
ClearTorques(s);
s.Strength[(int)Muscle.HipL] = 1f;
s.Strength[s.Plan.JointIndex("Hip", Side.Left)] = 1f;
s.Ragdoll.Drive(s.Strength, s.Target);
var full = TorqueNorm(s, Limb.ThighL);
var full = TorqueNorm(s, s.Plan.PartIndex("Thigh", Side.Left));
ClearTorques(s);
s.Strength[(int)Muscle.HipL] = 0.25f;
s.Strength[s.Plan.JointIndex("Hip", Side.Left)] = 0.25f;
s.Ragdoll.Drive(s.Strength, s.Target);
Assert.True(full > 1f);
Assert.Equal(full * 0.25f, TorqueNorm(s, Limb.ThighL), full * 1e-3f);
Assert.Equal(full * 0.25f, TorqueNorm(s, s.Plan.PartIndex("Thigh", Side.Left)), full * 1e-3f);
}
[Fact]
@ -173,14 +173,14 @@ public sealed class RagdollTests
using var s = new RagdollScenario(seed: 1);
Array.Clear(s.Strength);
var offAxis = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f); // about the joint frame's x: not the hinge axis (z)
s.Target[(int)Muscle.ElbowL] = offAxis;
s.Target[(int)Muscle.HipL] = offAxis;
s.Strength[(int)Muscle.ElbowL] = 1f;
s.Strength[(int)Muscle.HipL] = 1f;
s.Target[s.Plan.JointIndex("Elbow", Side.Left)] = offAxis;
s.Target[s.Plan.JointIndex("Hip", Side.Left)] = offAxis;
s.Strength[s.Plan.JointIndex("Elbow", Side.Left)] = 1f;
s.Strength[s.Plan.JointIndex("Hip", Side.Left)] = 1f;
ClearTorques(s);
s.Ragdoll.Drive(s.Strength, s.Target);
Assert.Equal(0f, TorqueNorm(s, Limb.LowerArmL)); // the hinge ignores what it cannot turn
Assert.True(TorqueNorm(s, Limb.ThighL) > 1f); // the ball joint does not
Assert.Equal(0f, TorqueNorm(s, s.Plan.PartIndex("LowerArm", Side.Left))); // the hinge ignores what it cannot turn
Assert.True(TorqueNorm(s, s.Plan.PartIndex("Thigh", Side.Left)) > 1f); // the ball joint does not
}
[Fact]
@ -199,15 +199,15 @@ public sealed class RagdollTests
using var s = new RagdollScenario(seed: 1);
var v = s.World.View;
var r = s.Ragdoll;
Assert.Equal(-1, v.Parent[r.BodyLane(Limb.Pelvis)]);
Assert.Equal(r.BodyLane(Limb.Pelvis), v.Parent[r.BodyLane(Limb.Torso)]);
Assert.Equal(r.BodyLane(Limb.ThighL), v.Parent[r.BodyLane(Limb.ShinL)]);
Assert.Equal(r.BodyLane(Limb.ShinR), v.Parent[r.BodyLane(Limb.FootR)]);
Assert.Equal((int)Limb.LowerArmR, v.Limb[r.BodyLane(Limb.LowerArmR)]);
Assert.Equal((uint)Box3DSoaKind.Capsule, v.Kind[r.BodyLane(Limb.ThighL)]);
Assert.Equal((uint)Box3DSoaKind.Box, v.Kind[r.BodyLane(Limb.Torso)]);
Assert.Equal((uint)Box3DSoaKind.Sphere, v.Kind[r.BodyLane(Limb.Head)]);
Assert.Equal(HumanoidRagdoll.MuscleCount, v.JointCount);
Assert.Equal(-1, v.Parent[r.BodyLane(s.Plan.PartIndex("Pelvis"))]);
Assert.Equal(r.BodyLane(s.Plan.PartIndex("Pelvis")), v.Parent[r.BodyLane(s.Plan.PartIndex("Torso"))]);
Assert.Equal(r.BodyLane(s.Plan.PartIndex("Thigh", Side.Left)), v.Parent[r.BodyLane(s.Plan.PartIndex("Shin", Side.Left))]);
Assert.Equal(r.BodyLane(s.Plan.PartIndex("Shin", Side.Right)), v.Parent[r.BodyLane(s.Plan.PartIndex("Foot", Side.Right))]);
Assert.Equal(s.Plan.PartIndex("LowerArm", Side.Right), v.Limb[r.BodyLane(s.Plan.PartIndex("LowerArm", Side.Right))]);
Assert.Equal((uint)Box3DSoaKind.Capsule, v.Kind[r.BodyLane(s.Plan.PartIndex("Thigh", Side.Left))]);
Assert.Equal((uint)Box3DSoaKind.Box, v.Kind[r.BodyLane(s.Plan.PartIndex("Torso"))]);
Assert.Equal((uint)Box3DSoaKind.Sphere, v.Kind[r.BodyLane(s.Plan.PartIndex("Head"))]);
Assert.Equal(s.Plan.Joints.Count, v.JointCount);
Assert.Throws<ArgumentException>(() => r.Drive(new float[3], s.Target));
Assert.Throws<ArgumentException>(() => r.Drive(s.Strength, new Quat[3]));
}