Only a touch outside a joint's subtree supports it: each body's weight is carried from the common ancestor of it and what it touches

Ragdoll.Drive deposits each body's weight at the lowest common ancestor of it and every
body it touches in this ragdoll (a touch outside the ragdoll deposits nowhere), reading
Facts.Touching, and throws when the world dropped touching pairs. The ContactCount gate
is deleted (ruling gravity-support-subtree-external). Hold pose -0.68, -0.25, box half
0.155, bounds re-derived by the margin rule, replay golden re-recorded.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-26 17:43:32 +01:00
commit 23591429e2
5 changed files with 108 additions and 43 deletions

View file

@ -10,7 +10,10 @@ namespace Lodur.Body.Ymir
/// <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. Each muscle's torque is a PD term toward its target plus the gravity load of the
/// muscle's unsupported subtree times its strength, projected on the axes it has gains for (ruling gravity-feedforward-all-muscles), so
/// sag comes only from weakness; the load reads Ymir's Mass, ContactCount, JointOrigin and Gravity, and a body in contact carries none. The binding holds no body numbers; the plan owns them.
/// sag comes only from weakness. Each body's weight is carried from the lowest common ancestor of it and every body it touches, and by
/// no joint when it touches anything outside this ragdoll: only a touch outside a joint's subtree supports that joint's load (ruling
/// gravity-support-subtree-external, superseding gravity-feedforward-count-gate). The load reads Ymir's Mass, Facts.Touching, JointOrigin and
/// Gravity. The binding holds no body numbers; the plan owns them.
/// In a world with a particle system Build also places one liquid sensor per plan airway opening, and <see cref="ReadAirway"/> reads them.
/// </summary>
public sealed class Ragdoll
@ -22,6 +25,9 @@ namespace Lodur.Body.Ymir
private readonly MuscleGains[] _gains;
// Subtree mass and mass-weighted position per part: scratch rebuilt every Drive, never read across ticks.
private readonly float[] _mass, _momentX, _momentY, _momentZ;
// Depth in the plan's tree, fixed at construction, and the part each part's weight is deposited at (-1: carried from outside): the deposit is scratch rebuilt every Drive.
private readonly int[] _depth, _deposit;
private ulong _firstStableId;
private Ragdoll(Box3DSoaWorld world, BodyPlan plan)
{
@ -36,6 +42,9 @@ namespace Lodur.Body.Ymir
_momentX = new float[plan.Parts.Count];
_momentY = new float[plan.Parts.Count];
_momentZ = new float[plan.Parts.Count];
_depth = new int[plan.Parts.Count];
_deposit = new int[plan.Parts.Count];
for (var i = 1; i < _depth.Length; i++) _depth[i] = plan.ParentOf(i) < 0 ? 0 : _depth[plan.ParentOf(i)] + 1; // parent before child
}
/// <summary>The plan this ragdoll was built from.</summary>
@ -57,6 +66,7 @@ namespace Lodur.Body.Ymir
public static Ragdoll Build(Box3DSoaWorld world, BodyPlan plan, (float X, float Z) origin, ulong firstStableId)
{
var r = new Ragdoll(world, plan);
r._firstStableId = firstStableId;
var ox = origin.X;
var oz = origin.Z;
for (var i = 0; i < plan.Parts.Count; i++)
@ -113,9 +123,10 @@ namespace Lodur.Body.Ymir
/// 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, plus the gravity feedforward: the torque about the joint origin that holds up the weight of the child's
/// subtree, except every body in contact with anything (a supported body, one lying or leaning, carries no load: ruling gravity-feedforward-count-gate),
/// times the strength and kept to the joint frame axes the muscle has gains for. A world with no gravity skips it. 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
/// subtree, except each body in it that touches something outside the subtree (the floor, an object, another body: ruling
/// gravity-support-subtree-external), times the strength and kept to the joint frame axes the muscle has gains for. A world with no gravity skips it.
/// Both arrays are the caller's, one entry per plan joint; nothing is copied or retained. Allocates nothing. Throws when the world dropped
/// touching pairs for want of fact capacity: a load from a partial list is wrong without a trace. 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)
@ -143,14 +154,40 @@ namespace Lodur.Body.Ymir
var (gx, gy, gz) = _world.Gravity;
if (gx == 0f && gy == 0f && gz == 0f) return;
var n = _mass.Length;
var facts = _world.Facts;
if (facts.Dropped.Touching > 0)
{
throw new InvalidOperationException("The world dropped touching pairs past its fact capacity; the gravity load needs every pair. Raise the world's fact capacity.");
}
for (var p = 0; p < n; p++) _deposit[p] = p;
foreach (var t in facts.Touching)
{
var a = PartOf(t.LaneA, t.StableIdA);
var b = PartOf(t.LaneB, t.StableIdB);
if (a >= 0 && b >= 0)
{
if (_deposit[a] >= 0) _deposit[a] = CommonAncestor(_deposit[a], b);
if (_deposit[b] >= 0) _deposit[b] = CommonAncestor(_deposit[b], a);
}
else if (a >= 0) _deposit[a] = -1;
else if (b >= 0) _deposit[b] = -1;
}
Array.Clear(_mass);
Array.Clear(_momentX);
Array.Clear(_momentY);
Array.Clear(_momentZ);
for (var p = 0; p < n; p++)
{
var d = _deposit[p];
if (d < 0) continue;
var b = _bodyLane[p];
var load = v.ContactCount[b] > 0 ? 0f : v.Mass[b];
_mass[p] = load;
_momentX[p] = load * v.PositionX[b];
_momentY[p] = load * v.PositionY[b];
_momentZ[p] = load * v.PositionZ[b];
var load = v.Mass[b];
_mass[d] += load;
_momentX[d] += load * v.PositionX[b];
_momentY[d] += load * v.PositionY[b];
_momentZ[d] += load * v.PositionZ[b];
}
for (var p = n - 1; p > 0; p--) // BodyPlan puts every parent before its child
@ -187,6 +224,21 @@ namespace Lodur.Body.Ymir
}
}
/// <summary>The plan part a touch end is, or -1 when the body is not this ragdoll's (its stable id is outside the range, or its lane is not the part's).</summary>
private int PartOf(int lane, ulong stableId)
{
var part = stableId - _firstStableId;
return stableId >= _firstStableId && part < (ulong)_bodyLane.Length && _bodyLane[(int)part] == lane ? (int)part : -1;
}
private int CommonAncestor(int a, int b)
{
while (_depth[a] > _depth[b]) a = Plan.ParentOf(a);
while (_depth[b] > _depth[a]) b = Plan.ParentOf(b);
while (a != b) { a = Plan.ParentOf(a); b = Plan.ParentOf(b); }
return a;
}
/// <summary>
/// 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.

View file

@ -14,10 +14,11 @@ internal sealed class ConnectedPainBox : IDisposable
public const double Dt = 1.0 / 120.0;
/// <summary>
/// The stimulus box's half extent, the smallest in 0.005 m steps that holds the shipped run's hand (seed 1) in the box from 2 s until the break. At e47e3d3 that was 0.125
/// (0.120 let the palm out 4 ticks early). With the gravity feedforward the will's failing sag, which the break no longer outruns, leaves the box earlier:
/// 0.125 lets it out 18 ticks early, 0.140 eight, 0.145 none. Limit 0.150: past it the hold no longer holds by intent.
/// (0.120 let the palm out 4 ticks early). With the gravity feedforward the will's failing sag, which the break no longer outruns, leaves the box earlier. Ticks out,
/// under the subtree-external gate (ruling gravity-support-subtree-external): 0.140 six, 0.145 three, 0.150 two, 0.155 none. At 63444f0 (the count gate) it was 0.145
/// (0.125 eighteen ticks out, 0.140 eight). Limit 0.160: past it the hold no longer holds by intent.
/// </summary>
public const float BoxHalf = 0.145f;
public const float BoxHalf = 0.155f;
/// <summary>The hold point: where the hold pose is solved to put the strength-1 right palm (the shoulder-right and elbow-right angles below; settled seed 1, 3-4 s, no leak), no longer where the controller sags it to.</summary>
public static readonly (float X, float Y, float Z) Box = (-0.210f, 1.116f, 0.441f);
@ -50,10 +51,11 @@ internal sealed class ConnectedPainBox : IDisposable
Array.Fill(holdPose, Quat.Identity);
Array.Fill(withdrawPose, Quat.Identity);
// The hold pose is solved by intent: the shoulder and elbow angles that put the settled strength-1 palm on Box (grid then refine over both, seed 1, 3-4 s,
// box silent): -0.70 and -0.36, 0.34 cm off. At e47e3d3 the same fit was -1.0 and -0.6, a pose that gravity sagged onto Box; with the feedforward the
// controller no longer sags, and -1.0, -0.6 would hold the palm well above it.
holdPose[Plan.JointIndex("Shoulder", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, -0.70f);
holdPose[Plan.JointIndex("Elbow", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, -0.36f);
// box silent): -0.68 and -0.25, 0.15 cm off. At 63444f0 (the count gate) the fit was -0.70 and -0.36, 0.34 cm off; under the subtree-external gate that pose settles
// the palm 4.74 cm out, because the right thumb and fingers now load the arm (the grid at 0.04 gives -0.68, -0.24 at 0.19 cm, the refine at 0.01 -0.68, -0.25: the fit is a ridge).
// At e47e3d3 the same fit was -1.0 and -0.6, a pose that gravity sagged onto Box; with the feedforward the controller no longer sags, and -1.0, -0.6 would hold the palm well above it.
holdPose[Plan.JointIndex("Shoulder", Side.Right)] = Quat.FromAxisAngle(1f, 0f, 0f, -0.68f);
holdPose[Plan.JointIndex("Elbow", Side.Right)] = Quat.FromAxisAngle(0f, 0f, 1f, -0.25f);
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);
@ -222,13 +224,15 @@ public sealed class ConnectedPainBoxTests
[Fact]
public void The_hold_pose_puts_the_settled_palm_on_the_box_centre_at_full_strength()
{
// The pose is solved for this (0.34 cm at the fit): with a flat will and no leak the palm's mean from 3 to 4 s is within 0.5 cm of the hold point (0.24 cm measured).
// The pose is solved for this (0.15 cm at the fit): with a flat will and no leak the palm's mean from 3 to 4 s is within 0.5 cm of the hold point (0.15 cm measured; 0.24 at 63444f0).
var t = Run(seed: 1, new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 }, maxSeconds: 5.0, new DriveParameters { WillCurve = 0.001 });
var settled = t.Hand.Skip(3 * Hz).Take(Hz).ToList();
var mean = (X: settled.Average(h => h.Hand.X), Y: settled.Average(h => h.Hand.Y), Z: settled.Average(h => h.Hand.Z));
Assert.True(Dist(mean, Centre) <= 0.005f, $"settled palm {Dist(mean, Centre) * 100f:F2} cm from the hold point");
}
private const float ShakeLine = 0.0202f;
private static float VerticalPeakToPeak(Timeline t, int fromSecond)
{
var seg = t.Hand.Skip(fromSecond * Hz).Take(Hz).Select(h => h.Hand.Y).ToList();
@ -239,15 +243,16 @@ public sealed class ConnectedPainBoxTests
public void Strain_shows_as_a_visible_shake_of_the_hand_which_the_shipped_amplitude_makes_and_zero_does_not()
{
// Seconds 8 to 13 of seed 1: strain is about 3, the will has not broken (it breaks at 14.75 s). Measured at the
// palm with the shipped StrainShake 0.08 / ShakeHz 3.5: 3.3-4.6 cm peak to peak in hand height per second; at 0, 0.2-1.4 cm (3.2-5.5 and 0.6-1.2 cm at e47e3d3).
// palm with the shipped StrainShake 0.08 / ShakeHz 3.5: 2.68-4.84 cm peak to peak in hand height per second; at 0, 0.15-1.52 cm (3.3-4.6 and 0.2-1.4 cm at 63444f0; 3.2-5.5 and 0.6-1.2 cm at e47e3d3).
// The floor and the still cap are one line, ShakeLine, the geometric midpoint (deterministic-bound-margin) of the shipped least (2.68) and the zero-shake worst (1.52): 2.02 cm, separation 1.76.
// (The shake was 0.03 on the forearm-tip hand, 3.9-4.7 cm there; the hands' mass damps the arm and the default rose to keep the rule.)
var shaking = Run(seed: 1, new HoldParameters(), maxSeconds: 16.0);
var still = Run(seed: 1, new HoldParameters { StrainShake = 0.0 }, maxSeconds: 16.0);
for (var s = 8; s <= 13; s++)
{
Assert.True(VerticalPeakToPeak(shaking, s) > 0.03f, $"shipped shake only {VerticalPeakToPeak(shaking, s)} m peak to peak in second {s}");
Assert.True(VerticalPeakToPeak(shaking, s) > ShakeLine, $"shipped shake only {VerticalPeakToPeak(shaking, s)} m peak to peak in second {s}");
Assert.True(VerticalPeakToPeak(shaking, s) < 0.07f, $"shipped shake is {VerticalPeakToPeak(shaking, s)} m peak to peak in second {s}, more than a strain tremor");
Assert.True(VerticalPeakToPeak(still, s) < 0.015f, $"no shake still moved {VerticalPeakToPeak(still, s)} m in second {s}");
Assert.True(VerticalPeakToPeak(still, s) < ShakeLine, $"no shake still moved {VerticalPeakToPeak(still, s)} m in second {s}");
}
}
@ -282,11 +287,13 @@ public sealed class ConnectedPainBoxTests
[Fact]
public void Seed_1_to_16_seconds_replays_the_world_the_break_and_the_deliberate_switch_recorded_at_the_will_mix()
{
// Recorded with the gravity feedforward and the re-solved hold (pose -0.70, -0.36, box half 0.145); the line before was recorded at e47e3d3, the ragdoll hands
// (palm region, hand-mass damping, StrainShake 0.08, box half 0.125, pose -1.0, -0.6): broke=1772 withdrew=1784 flinches=16 hand=17416bc7c2d12853 world=9f710f8186aff900.
// The break moved one tick, the flinch count did not; the hand and the world moved because the muscles now carry the arm's weight.
// Recorded with the subtree-external gravity support (ruling gravity-support-subtree-external) and the hold re-solved under it (pose -0.68, -0.25, box half 0.155).
// The line before was recorded at 63444f0, the count gate (pose -0.70, -0.36, box half 0.145): broke=1773 withdrew=1785 flinches=16 hand=6db1f8d175e3e635 world=348765d9a09a27cf.
// The line before that was recorded at e47e3d3, the ragdoll hands (palm region, hand-mass damping, StrainShake 0.08, box half 0.125, pose -1.0, -0.6):
// broke=1772 withdrew=1784 flinches=16 hand=17416bc7c2d12853 world=9f710f8186aff900. The break moved one tick each time, the flinch count never; the hand and the world moved
// because the muscles carry the arm's weight, and again because the thumb and fingers resting on each other now load the arm.
var t = Run(seed: 1, maxSeconds: 16.0);
Assert.Equal("broke=1773 withdrew=1785 flinches=16 hand=6db1f8d175e3e635 world=348765d9a09a27cf",
Assert.Equal("broke=1774 withdrew=1786 flinches=16 hand=27e153fde720075e world=8998d8f0fca463ec",
$"broke={t.Broke} withdrew={t.Withdrew} flinches={t.Flinches.Count} hand={HandTrackHash(t):x16} world={t.Hash:x16}");
}
}

View file

@ -275,10 +275,12 @@ public sealed class HandTests
/// <summary>
/// How far past its cone a hand joint may swing, at the geometric midpoint (deterministic-bound-margin) of the shipped worst and the least claimed mutant:
/// 0.0621 rad (wrist, seeds 1-3, four directions, both sides; 0.0557 thumb) against 0.6048 (the wrist added without its cone limit; the thumb reads 0.894), margin 3.1 each side.
/// The gravity feedforward lets the muscle press its full torque on Box3D's soft limit, which gives 0.0621 where the controller at e47e3d3 sagged off it (0.0587), and the old 0.06 bound.
/// 0.0684 rad (wrist, both sides, four directions; 0.0528 thumb) against 0.0970 (the wrist cone 0.03 rad wider than its plan; 0.0874 at 0.02, 0.1065 at 0.04, the cone limit off
/// 1.47), separation 1.42, margin 1.19 each side. The gravity feedforward lets the muscle press its full torque on Box3D's soft limit, which gives 0.0684 where the controller at
/// e47e3d3 sagged off it (0.0587; 0.0621 under the count gate at 63444f0, whose bound was 0.194 against the cone-less mutant 0.6048: three times looser than the old 0.06, a limit
/// 0.1 rad wider would have passed). Claiming a limit 1.7 degrees wide keeps the bound under 0.082 rad.
/// </summary>
private const float ConeOvershoot = 0.194f;
private const float ConeOvershoot = 0.0815f;
[Theory]
[InlineData("Wrist", Side.Left, 1.0f)]

View file

@ -106,12 +106,14 @@ public sealed class IkReachTests
}
/// <summary>
/// Gravity reach bound at the geometric midpoint (deterministic-bound-margin) of the shipped worst, 3.97 cm over the three targets with the pelvis welded (3.01, 3.16, 3.97),
/// and the least claimed mutant, 24.01 cm (the feedforward off: 13.69, 10.16, 24.01): margin 2.46 each side. The controller no longer sags: zero gravity reads 0.89 cm here.
/// With the count gate off the shipped worst reads 0.89 cm: the right hand's thumb and fingers touch each other, so their weight leaves the arm's load (ruling
/// gravity-feedforward-count-gate, given up: self-contact counts as support; follow-up gravity-support-subtree-external).
/// Gravity reach bound at the geometric midpoint (deterministic-bound-margin) of the shipped worst, 0.77 cm over the three targets with the pelvis welded (0.77, 0.16, 0.72),
/// and the least claimed mutant, 3.97 cm (the count gate, any touch carries the body's weight at no joint: 3.01, 3.16, 3.97): 1.75 cm, margin 2.27 each side, separation 5.2.
/// Also killed: a deposit at the touched body instead of the common ancestor, 5.84 cm; the feedforward off, 24.01 cm (13.69, 10.16, 24.01). Not claimed here: no gate at all reads
/// 0.89 cm and a touch outside the ragdoll ignored 0.77 cm, 1.16 and 1.00 times the shipped worst; the hand-rest tests in HandTests kill both. The controller no longer sags: zero
/// gravity reads 0.89 cm. Only a touch outside a joint's subtree supports it (ruling gravity-support-subtree-external), so the right hand's thumb on its fingers no longer lifts the arm's load.
/// At 63444f0 this bound was 9.76 cm, pinned to the count gate's own self-contact cost.
/// </summary>
private const float GravityBound = 0.0976f;
private const float GravityBound = 0.0175f;
[Fact]
public void Gravity_reach_lands_the_wrist_at_full_strength()
@ -129,11 +131,11 @@ public sealed class IkReachTests
}
/// <summary>
/// The least a half-strength arm sags at any target, at the geometric midpoint of the shipped least (13.38 cm; 20.31, 13.38, 25.01) and the least claimed mutant (1.47 cm:
/// the feedforward without its strength factor, which holds the weight up at half strength; 18.95, 5.47, 1.47): margin 3.0 each side. A weak will sags (strength 0.5 is
/// weakness, not the controller), and the feedforward off reads 22.45, 17.18, 38.77 there.
/// The least a half-strength arm sags at any target, at the geometric midpoint of the shipped least (13.85 cm; 19.00, 13.85, 22.79) and the least claimed mutant (0.88 cm:
/// the feedforward without its strength factor, which holds the weight up at half strength; 0.88, 0.89, 12.78): 3.49 cm, margin 3.97 each side. A weak will sags (strength 0.5 is
/// weakness, not the controller), and the feedforward off reads 22.45, 17.18, 38.77 there. At 63444f0 the bound was 4.43 cm (shipped least 13.38, mutant 1.47).
/// </summary>
private const float WeakSag = 0.0443f;
private const float WeakSag = 0.0349f;
[Fact]
public void A_half_strength_arm_still_sags_under_gravity_at_every_target()

View file

@ -57,14 +57,16 @@ public sealed class SeatedOrientTests
private const float NearWardBound = 0.0576f;
/// <summary>
/// Under gravity, the head-height bound on each wrist: the geometric midpoint of the shipped worst, 6.00 cm, and the least claimed mutant, 15.52 cm (the via point
/// at the trunk front, clearance 0): margin 1.61 each side. Also killed: the gravity feedforward off, 18.68 cm (the controller's own sag, which was the shipped
/// worst before it, 18.68); the wrists sent sideways of the head, 33.87 cm; the via point's x at the midpoint, 29.77 cm; no spread, 28.38 cm; the arms at half weight, 54.60 cm.
/// Not killed: every reach solved directly, 7.20 cm. The bound at e47e3d3, before the feedforward, was 21.78 cm (shipped worst 18.68, least claimed mutant 25.41, the via
/// point's x at the midpoint). With the count gate off the shipped worst reads 7.59 cm: bodies in self-contact leave the arm's load
/// (ruling gravity-feedforward-count-gate, given up: self-contact counts as support). Not re-measured: spread halved and offset, and the clamped zero-twist swivel.
/// Under gravity, the head-height bound on each wrist: the geometric midpoint of the shipped worst, 7.03 cm, and the least claimed mutant, 9.81 cm (the arm's path never
/// blocked by the trunk: 9.81 and 3.76 cm): 8.30 cm, margin 1.18 each side, separation 1.40. Also killed, re-measured under the subtree-external gate (ruling
/// gravity-support-subtree-external): the gravity feedforward off, 18.68 cm; no spread, 21.21 cm; the via point's x at the midpoint, 26.77 cm; the wrists sent sideways of
/// the head, 34.25 cm; the via point at the trunk front with clearance 0, 34.30 cm (15.52 at 63444f0, where the count gate left the arm lighter); the arms at half weight, 52.17 cm.
/// Not killed: every reach solved directly, 7.20 cm at 63444f0, not re-measured. The ward is not limited by gravity or by the gate: zero gravity reads 8.11 cm, the count gate
/// 6.00, no gate 7.59, the subtree-external gate 7.03, so the reading rests on the planner's own residual. At 63444f0 the bound was 9.65 cm (shipped worst 6.00, least claimed
/// mutant 15.52); the shipped reading rose to 7.03 and the path-never-blocked mutant, 9.81, is separated from it by 1.40, so it is claimed and the bound fell. The bound at e47e3d3, before the feedforward, was 21.78 cm (shipped worst 18.68, least claimed mutant
/// 25.41). Not re-measured: spread halved and offset, and the clamped zero-twist swivel.
/// </summary>
private const float GravityWardBound = 0.0965f;
private const float GravityWardBound = 0.0830f;
private readonly ITestOutputHelper _out;