diff --git a/docs/goal-ai-map.md b/docs/goal-ai-map.md
index 6e4aad8..369b721 100644
--- a/docs/goal-ai-map.md
+++ b/docs/goal-ai-map.md
@@ -323,7 +323,7 @@ one joint contest by will. Nothing in the cuts below may write a body-wide outpu
| 2b | `lodur-goal-planner` | Lodur | percept facts, verbs with needs and gives, depth-limited regressive planner (core, no caller) | 2 | M, specced |
| 2c | `lodur-planner-select` | Lodur | wants, Select admission, direct tries at a discount and frustration (`bds-unplannable-tries-direct`), plan on the Actor | 2b, Actor.cs cuts in flight | M |
| 3 | `lodur-ik-goals` | Lodur | Look, ArmL, ArmR as a Core producer of joint targets (legs later) | none (parallel to 2) | M |
-| 3b | `lodur-reach-path` | Lodur | hand path through a clearance via point when blocked; arm hand-off slewed both ways | 3, 4 | M, specced |
+| 3b | `lodur-reach-path` | Lodur | hand path through a clearance via point when blocked; arm hand-off slewed both ways | 3, 4 | M, landed |
| 3c | `ymir-world-gravity`, then `lodur-gravity-feedforward` | Ymir, Lodur (+ BDS content) | the world reports its gravity; muscles carry their subtree's weight times strength | Q `gravity-feedforward-scope` | S, M |
| 4 | `lodur-orient-goals` | Lodur + BDS | look, reach, ward off and recoil as layers; fetal (a key-pose goal) and stare-at-hands (Look and Reach on a phantom) are data; seated Fella demo | 2, 3 | M |
| 5 | `lodur-phantom-percepts` + `bds-thought-bubble` | Lodur, BDS | phantom things by hallucination type; the bubble reads their kinds | 1, 4 | M, S |
@@ -359,18 +359,21 @@ gives up: IK is no longer a pure function of the goal. Near a half-turn swing th
singular, so the clamped solution can still jump; ruling `ik-output-slew-limit` covers it at the output: the returned
shoulder and elbow targets move toward the solution no faster than `MaxAngularRate` (a placeholder near human peak
arm speed), everywhere, and the singular-band special case is deleted. What that gives up: a leaping goal is followed
-at the rate, not at once. The slew holds only while the Arms layer drives; the hand-off into and out of the layer is
-cut `lodur-reach-path` (facts 19-23). Reach under gravity lands short by PD sag (facts 9, 19); that is follow-up
-`lodur-gravity-feedforward`.
+at the rate, not at once. The slew holds across the hand-off too (cut `lodur-reach-path`, fact 27): an arm that engages
+slews from the base pose, one the layer stops driving slews back to it, and `OrientRig.Compose` runs on every tick of an
+Actor with a rig, so the written arm targets move at most `MaxAngularRate` times the tick throughout. Reach under gravity
+lands short by PD sag (facts 9, 23); that is follow-up `lodur-gravity-feedforward`.
**Reach rationale (pass `reach-tracking-map`, ruling `reach-clears-body-by-via-point`).** One owner of an arm's motion
across ticks: `ArmChain` holds the held swivel, the slewed output and now the hand path and the hand-off state, so a
teleport's `Reset` forgets all of it at once. The path is minimum-jerk (Flash and Hogan 1985) in the arm parent's creation
frame, where the chain already solves; it starts at the measured wrist when the arm engages or the Actor commits a (goal,
-target) pair, and it is taken only when the straight wrist segment is blocked by the trunk (fact 21; whether unblocked
-reaches also take a path is question `reach-path-unblocked`, fact 22). The via point sits ahead of the wrist's own side,
-not of the midpoint: the arm comes forward first, then across, as a person reaching across their body does. Gravity is a
-muscle-layer term, not a reach-layer correction (fact 19): computed-torque practice (PD plus gravity compensation,
+target) pair, and it is taken only when the straight wrist segment is blocked by the trunk (fact 25). An unblocked reach
+solves the goal directly each tick, slewed (ruling `reach-path-blocked-only`; a path there ends further off, fact 26;
+it gives up the bell-shaped hand speed of an unobstructed human reach). The via point sits ahead of the wrist's own side,
+not of the midpoint (`ArmChain.ViaClearance` 0.2 m and `PathSegmentSeconds` 0.3 s are placeholders; blocked is decided once per
+path start, against the trunk bounds the chain derives from the arm's parent part and its ancestors): the arm comes forward first, then across, as a person reaching across their body does. Gravity is a
+muscle-layer term, not a reach-layer correction (fact 23): computed-torque practice (PD plus gravity compensation,
Takegaki and Arimoto 1981; Coros et al. 2010 for simulated characters) puts it in the torque, scaled here by strength so a
failing will still sags; a task-space loop on the target was unstable (fact 9) and fights a weak will. PuppetMaster's
alternative, pin forces pulling bodies to the target pose, is an external force and breaks `body-one-interface`.
diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs
index a077bfb..80240dd 100644
--- a/src/Lodur.Core/Actor.cs
+++ b/src/Lodur.Core/Actor.cs
@@ -339,6 +339,7 @@ namespace Lodur
_goal = _pending;
_target = _pendingTarget;
_pending = -1;
+ _rig?.Commit();
if (_layered && _brain.Goals[_goal].Behaviour.Arms is { Side: ArmSide.Nearer } && _target != 0UL)
{
var committed = Target;
@@ -382,9 +383,9 @@ namespace Lodur
var secondsInGoal = (_tick - _goalSince) * _dt;
var weight = _tick - _goalSince >= _onset[_goal] ? Math.Pow(_drive.Will, _driveP.WillCurve) : 1.0;
var behaviour = _brain.Goals[_goal].Behaviour;
- if (behaviour.HasLayers)
+ if (_rig != null)
{
- behaviour.Write(weight, leak, _drive.Strain, _tick * _dt, secondsInGoal, strengths, targets, new OrientInput(_rig!, parts, Target, _arm));
+ behaviour.Write(weight, leak, _drive.Strain, _tick * _dt, secondsInGoal, strengths, targets, new OrientInput(_rig, parts, Target, _arm));
}
else
{
diff --git a/src/Lodur.Core/Ik.cs b/src/Lodur.Core/Ik.cs
index f708fd5..420dd55 100644
--- a/src/Lodur.Core/Ik.cs
+++ b/src/Lodur.Core/Ik.cs
@@ -118,7 +118,19 @@ namespace Lodur
// The targets the previous solve returned, which the next one slews from, share the flag.
private Quat _previous, _shoulderOut;
private float _flexOut;
- private bool _hasPrevious;
+ private bool _hasPrevious, _hasOutput;
+
+ private enum Hand : byte { Idle, Driving, Releasing }
+
+ // The hand-off and the hand path. The path is in the arm parent's creation frame; its time counts the ticks driven since it started.
+ private Hand _hand;
+ private double _weight;
+ private bool _newPath, _pathBlocked, _hasSegGoal;
+ private IkVec _pathStart, _pathVia, _segGoal, _aim;
+ private int _pathTicks;
+ private readonly float _dt;
+ private readonly IkVec[] _trunkCentre, _trunkHalf;
+ private readonly float _trunkFront, _forearmRadius;
///
/// Radians of limit violation, or of twist when both swivels are feasible, by which the stateless choice must beat the held swivel's
@@ -140,6 +152,15 @@ namespace Lodur
///
public const float MaxAngularRate = 10f;
+ ///
+ /// Metres the via point sits ahead of the trunk's front. Placeholder: the probe (goal-ai-map fact 25) measured 0.15 to 0.3 m clearing the
+ /// seated far arm; no pose cost sets it.
+ ///
+ public const float ViaClearance = 0.2f;
+
+ /// Seconds of each of the path's two segments, wrist to via point and via point to goal. Placeholder: a deliberate reach, not measured (fact 25).
+ public const float PathSegmentSeconds = 0.3f;
+
// Swivel search: steps of Pi / SwivelSteps outward from the zero-twist swivel, then bisection to the feasible boundary. When none is
// feasible, the least-violating of LeastSteps steps round the circle, refined by golden section.
private const int SwivelSteps = 90;
@@ -158,6 +179,7 @@ namespace Lodur
throw new ArgumentException($"the tick length {tickSeconds} s is not finite and positive.");
}
+ _dt = (float)tickSeconds;
_maxSwivelStep = (float)(SwivelRate * tickSeconds);
_maxStep = (float)(MaxAngularRate * tickSeconds);
_cosHalfMaxStep = MathF.Cos(0.5f * _maxStep);
@@ -212,14 +234,70 @@ namespace Lodur
ShoulderAnchor = s.Anchor;
ElbowAnchor = e.Anchor;
WristAnchor = w.Anchor;
+ ForearmPart = e.Child;
+
+ // The trunk: the shoulder's parent part and its ancestors, each as its creation-pose axis-aligned bound.
+ var trunk = 0;
+ for (var part = s.Parent; part >= 0; part = plan.ParentOf(part)) trunk++;
+ _trunkCentre = new IkVec[trunk];
+ _trunkHalf = new IkVec[trunk];
+ _trunkFront = float.NegativeInfinity;
+ trunk = 0;
+ for (var part = s.Parent; part >= 0; part = plan.ParentOf(part))
+ {
+ var def = plan.Parts[part];
+ _trunkCentre[trunk] = new IkVec(def.Position);
+ _trunkHalf[trunk] = Half(def);
+ _trunkFront = MathF.Max(_trunkFront, def.Position.Z + _trunkHalf[trunk].Z);
+ trunk++;
+ }
+
+ var fore = plan.Parts[e.Child];
+ _forearmRadius = fore.Shape == PartShape.Box ? MathF.Min(fore.Size.X, MathF.Min(fore.Size.Y, fore.Size.Z)) : fore.Size.X;
+ _newPath = true;
+ }
+
+ // The half extents of a part's creation-pose axis-aligned bound.
+ private static IkVec Half(in PartDef part)
+ {
+ var q = part.Rotation;
+ var (sx, sy, sz) = part.Size;
+ q.Rotate(1f, 0f, 0f, out var xx, out var xy, out var xz);
+ q.Rotate(0f, 1f, 0f, out var yx, out var yy, out var yz);
+ q.Rotate(0f, 0f, 1f, out var zx, out var zy, out var zz);
+ switch (part.Shape)
+ {
+ case PartShape.Box:
+ return new IkVec(MathF.Abs(xx) * sx + MathF.Abs(yx) * sy + MathF.Abs(zx) * sz,
+ MathF.Abs(xy) * sx + MathF.Abs(yy) * sy + MathF.Abs(zy) * sz,
+ MathF.Abs(xz) * sx + MathF.Abs(yz) * sy + MathF.Abs(zz) * sz);
+ case PartShape.Capsule:
+ // Radius sx, half length sy along the part's y.
+ return new IkVec(MathF.Abs(yx) * sy + sx, MathF.Abs(yy) * sy + sx, MathF.Abs(yz) * sy + sx);
+ default:
+ return new IkVec(sx, sx, sx);
+ }
}
/// Finds the shoulder, elbow and wrist of by label; if the plan has no such arm.
/// One chain is one arm's solver across ticks of , which sets how far the swivel turns per solve.
public static ArmChain Of(BodyPlan plan, Side side, double tickSeconds) => new ArmChain(plan, side, tickSeconds);
- /// Forgets the previous swivel and returned targets: the next solve uses the stateless rule and returns its solution unslewed.
- public void Reset() => _hasPrevious = false;
+ ///
+ /// Forgets the previous swivel, the returned targets, the hand path and the hand-off: the next uses the stateless rule
+ /// and returns its solution unslewed, and the arm is idle, so passes the base through and engages
+ /// from it.
+ ///
+ public void Reset()
+ {
+ _hasPrevious = false;
+ _hasOutput = false;
+ _hand = Hand.Idle;
+ _newPath = true;
+ }
+
+ /// The next starts a new hand path from the measured wrist, keeping the swivel and the returned targets.
+ public void Restart() => _newPath = true;
/// The last solve's shoulder target before clamping, whose swivel the next solve holds (identity before any solve); tests read it.
internal Quat Held => _hasPrevious ? _previous : Quat.Identity;
@@ -231,6 +309,9 @@ namespace Lodur
/// The part the shoulder hangs from; Solve takes its world rotation and position.
public int ParentPart { get; }
+ /// The forearm part, which carries the wrist anchor; Drive takes the measured wrist from its pose.
+ public int ForearmPart { get; }
+
/// Creation-pose anchors. The effector is .
public (float X, float Y, float Z) ShoulderAnchor { get; }
public (float X, float Y, float Z) ElbowAnchor { get; }
@@ -247,10 +328,14 @@ namespace Lodur
/// basins, the clamped pose of the swivel on its way. The returned targets are slewed toward that solution at
/// ; the return value describes the solution. One call is one tick of the arm's history.
///
- public bool Solve(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, out Quat shoulder, out Quat elbow)
+ public bool Solve(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, out Quat shoulder, out Quat elbow) =>
+ SolveCreation(Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz), out shoulder, out elbow);
+
+ // Solve for a wrist point already in the parent's creation frame.
+ private bool SolveCreation(IkVec target, out Quat shoulder, out Quat elbow)
{
var reached = true;
- var v = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz) - _shoulderAnchor;
+ var v = target - _shoulderAnchor;
var d = v.Length;
var dMin = MathF.Abs(L1 - L2) + 1e-3f;
var dMax = L1 + L2 - 1e-3f;
@@ -285,9 +370,10 @@ namespace Lodur
}
var local = Local(a, b, phi);
- var slew = _hasPrevious;
+ var slew = _hasOutput;
_previous = local;
_hasPrevious = true;
+ _hasOutput = true;
if (clamp)
{
// Infeasible: swing and twist clamped to the limits.
@@ -310,6 +396,164 @@ namespace Lodur
return reached;
}
+ ///
+ /// One tick the arm's layer drives: the targets to write for the wrist goal (tx, ty, tz) given the arm parent's world pose, the wrist
+ /// measured now (mx, my, mz) and the base shoulder and elbow targets, blended toward the solution by in [0, 1].
+ /// An arm that was idle starts slewing from the base targets; one that was releasing, from where its output was. The tick that engages the
+ /// arm, and every tick after , starts a hand path from the measured wrist. Returns whether the goal was reached,
+ /// as does for the point it was given.
+ ///
+ public bool Drive(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, float mx, float my, float mz,
+ in Quat baseShoulder, in Quat baseElbow, double weight, out Quat shoulder, out Quat elbow)
+ {
+ if (_hand != Hand.Driving)
+ {
+ if (_hand == Hand.Idle)
+ {
+ _shoulderOut = baseShoulder;
+ _flexOut = Flex(baseElbow);
+ _hasOutput = true;
+ }
+
+ _hand = Hand.Driving;
+ _newPath = true;
+ }
+
+ _weight = weight;
+ var goal = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz);
+ if (_newPath)
+ {
+ _newPath = false;
+ var wrist = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, mx, my, mz);
+ _pathStart = wrist;
+ _pathBlocked = Blocked(wrist, goal);
+ _pathVia = new IkVec(wrist.X, 0.5f * (wrist.Y + goal.Y), _trunkFront + ViaClearance);
+ _pathTicks = 0;
+ _hasSegGoal = false;
+ }
+
+ var aim = goal;
+ if (_pathBlocked && _pathTicks * _dt < 2f * PathSegmentSeconds)
+ {
+ var t = _pathTicks * _dt;
+ if (!_hasSegGoal && t >= PathSegmentSeconds)
+ {
+ _segGoal = goal;
+ _hasSegGoal = true;
+ }
+
+ aim = PathPoint(_pathStart, _pathVia, _segGoal, goal, t);
+ _pathTicks++;
+ }
+
+ _aim = aim;
+ var reached = SolveCreation(aim, out var s, out var e);
+ shoulder = Blend(baseShoulder, s, weight);
+ elbow = Blend(baseElbow, e, weight);
+ return reached;
+ }
+
+ ///
+ /// One tick the arm's layer does not drive: while the arm still holds a driven output, it slews to the base targets at
+ /// , written blended toward the base by the weight it was last driven at; when it has arrived, and for an arm
+ /// that never was driven, the written targets are the base ones, untouched.
+ ///
+ public void Release(in Quat baseShoulder, in Quat baseElbow, out Quat shoulder, out Quat elbow)
+ {
+ if (_hand == Hand.Idle)
+ {
+ shoulder = baseShoulder;
+ elbow = baseElbow;
+ return;
+ }
+
+ _hand = Hand.Releasing;
+ _shoulderOut = Toward(_shoulderOut, baseShoulder);
+ var flex = Flex(baseElbow);
+ var gap = flex - _flexOut;
+ _flexOut = MathF.Abs(gap) <= _maxStep ? flex : _flexOut + (gap > 0f ? _maxStep : -_maxStep);
+ if (_flexOut == flex && _shoulderOut.X == baseShoulder.X && _shoulderOut.Y == baseShoulder.Y && _shoulderOut.Z == baseShoulder.Z
+ && _shoulderOut.W == baseShoulder.W)
+ {
+ _hand = Hand.Idle;
+ shoulder = baseShoulder;
+ elbow = baseElbow;
+ return;
+ }
+
+ shoulder = Blend(baseShoulder, _shoulderOut, _weight);
+ elbow = Blend(baseElbow, Quat.FromAxisAngle(0f, 0f, 1f, _flexOut), _weight);
+ }
+
+ // The solution itself at weight 1, a blend toward it from the base below that.
+ private static Quat Blend(in Quat baseTarget, in Quat solution, double weight) =>
+ weight >= 1.0 ? solution : Quat.Nlerp(baseTarget, solution, (float)weight);
+
+ // The flex of an elbow target, a rotation about the hinge's frame z, on the shortest turn.
+ private static float Flex(in Quat elbow) => 2f * MathF.Atan2(elbow.W < 0f ? -elbow.Z : elbow.Z, MathF.Abs(elbow.W));
+
+ // Minimum jerk (Flash and Hogan 1985): 0 to 1 with zero velocity and acceleration at both ends.
+ internal static float MinimumJerk(float t)
+ {
+ t = Ik.Clamp(t, 0f, 1f);
+ return t * t * t * (10f - 15f * t + 6f * t * t);
+ }
+
+ ///
+ /// The hand path in the arm parent's creation frame at seconds: the start to the via point over
+ /// , then the goal plus the via point's offset from the goal as it was when the segment began, shrinking
+ /// to nothing, so a goal that moves is met at the end. is the goal at that moment.
+ ///
+ internal static (float X, float Y, float Z) PathPoint((float X, float Y, float Z) start, (float X, float Y, float Z) via,
+ (float X, float Y, float Z) segmentGoal, (float X, float Y, float Z) goal, float t)
+ {
+ var p = PathPoint(new IkVec(start), new IkVec(via), new IkVec(segmentGoal), new IkVec(goal), t);
+ return (p.X, p.Y, p.Z);
+ }
+
+ private static IkVec PathPoint(IkVec start, IkVec via, IkVec segmentGoal, IkVec goal, float t)
+ {
+ if (t < PathSegmentSeconds) return start + (via - start) * MinimumJerk(t / PathSegmentSeconds);
+ return goal + (via - segmentGoal) * (1f - MinimumJerk((t - PathSegmentSeconds) / PathSegmentSeconds));
+ }
+
+ /// Whether the last path start found the trunk in the way (tests read it).
+ internal bool PathBlocked => _pathBlocked;
+
+ /// The creation-frame point the last solved for: the path point, or the goal (tests read it).
+ internal (float X, float Y, float Z) Aim => (_aim.X, _aim.Y, _aim.Z);
+
+ // Whether the straight segment from the wrist to the goal passes within the forearm radius of a trunk bound.
+ private bool Blocked(IkVec wrist, IkVec goal)
+ {
+ for (var b = 0; b < _trunkCentre.Length; b++)
+ {
+ // The distance to a box is convex along a line, so a ternary search finds its least over the segment.
+ float lo = 0f, hi = 1f;
+ for (var i = 0; i < 40; i++)
+ {
+ var m1 = lo + (hi - lo) / 3f;
+ var m2 = hi - (hi - lo) / 3f;
+ if (BoxDistance(wrist + (goal - wrist) * m1, b) < BoxDistance(wrist + (goal - wrist) * m2, b)) hi = m2;
+ else lo = m1;
+ }
+
+ if (BoxDistance(wrist + (goal - wrist) * (0.5f * (lo + hi)), b) < _forearmRadius) return true;
+ }
+
+ return false;
+ }
+
+ private float BoxDistance(IkVec p, int box)
+ {
+ var d = p - _trunkCentre[box];
+ var h = _trunkHalf[box];
+ var x = MathF.Max(0f, MathF.Abs(d.X) - h.X);
+ var y = MathF.Max(0f, MathF.Abs(d.Y) - h.Y);
+ var z = MathF.Max(0f, MathF.Abs(d.Z) - h.Z);
+ return MathF.Sqrt(x * x + y * y + z * z);
+ }
+
// The rotation from current toward target, turned by at most the per-solve step: the target itself when it is within the step.
private Quat Toward(in Quat current, in Quat target)
{
diff --git a/src/Lodur.Core/Orient.cs b/src/Lodur.Core/Orient.cs
index 1e4dd4f..e48d7f4 100644
--- a/src/Lodur.Core/Orient.cs
+++ b/src/Lodur.Core/Orient.cs
@@ -187,8 +187,9 @@ namespace Lodur
///
/// The solvers an Actor's brain needs, resolved once from the body plan: the look chain when any goal looks, wards off or recoils (they read
/// the head), an arm chain for each side an Arms layer can use. A chain the plan cannot give refuses at construction, naming the goal, so a
- /// plan the closed form cannot solve fails at spawn and never mid-tick. The arm chains are the Actor's arms across ticks and hold each
- /// arm's swivel and returned targets from tick to tick (an arm not driven on a tick keeps its last ones, and slews from them when next driven, until ); the rig holds nothing else, and solving allocates nothing.
+ /// plan the closed form cannot solve fails at spawn and never mid-tick. The arm chains are the Actor's arms across ticks: each holds its
+ /// arm's swivel, hand path and written targets from tick to tick, and the rig holds nothing else. The arms are composed on every tick of an
+ /// Actor with a rig, so an arm its layer does not drive eases back to the base pose (); solving allocates nothing.
///
internal sealed class OrientRig
{
@@ -247,13 +248,20 @@ namespace Lodur
}
}
- /// Forgets both arms' held swivels and returned targets: each arm's next solve is the stateless rule, unslewed.
+ /// Forgets both arms' held swivels, paths and written targets: each arm is idle, and engages from the base pose.
public void ResetArms()
{
_left?.Reset();
_right?.Reset();
}
+ /// The Actor committed a (goal, target) pair: each arm starts a new hand path when next driven.
+ public void Commit()
+ {
+ _left?.Restart();
+ _right?.Restart();
+ }
+
/// The arm whose shoulder is nearer the target; ties go to the right.
public Side NearerArm(ReadOnlySpan parts, in Percept target)
{
@@ -282,7 +290,11 @@ namespace Lodur
return new IkVec(pose.X, pose.Y, pose.Z) + (creationPoint - new IkVec(def.Position)).Rotated(rel);
}
- /// Composes the layers onto the base pose already in : recoil, then look, then the arms.
+ ///
+ /// Composes the layers onto the base pose already in : recoil, then look, then the arms. An arm the behaviour
+ /// does not drive this tick is released, which passes the base pose through once it has eased back. The part poses are read only for what is
+ /// driven.
+ ///
public void Compose(PoseBehaviour b, in OrientInput input, Span targets)
{
var parts = input.Parts;
@@ -294,7 +306,7 @@ namespace Lodur
var left = default(IkVec);
var toward = default(IkVec);
var distance = 0f;
- if (hasTarget && _look != null)
+ if (hasTarget && _look != null && b.HasLayers)
{
var h = parts[_look.ChildPart];
head = new IkVec(h.X, h.Y, h.Z);
@@ -326,20 +338,39 @@ namespace Lodur
targets[_look.Joint] = Toward(targets[_look.Joint], neck, look.Weight);
}
+ var driveLeft = false;
+ var driveRight = false;
if (b.Arms is { } arms && (hasTarget || arms.Mode == ArmMode.Present))
{
- var leftArm = arms.Side == ArmSide.Left || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm == Side.Left);
- var rightArm = arms.Side == ArmSide.Right || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm != Side.Left);
- if (leftArm && _left != null)
+ driveLeft = _left != null && (arms.Side == ArmSide.Left || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm == Side.Left));
+ driveRight = _right != null && (arms.Side == ArmSide.Right || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm != Side.Left));
+ if (driveLeft)
{
- Drive(_left, 1f, arms, parts, goal, head, toward, left, targets);
+ Drive(_left!, 1f, arms, parts, goal, head, toward, left, targets);
}
- if (rightArm && _right != null)
+ if (driveRight)
{
- Drive(_right, -1f, arms, parts, goal, head, toward, left, targets);
+ Drive(_right!, -1f, arms, parts, goal, head, toward, left, targets);
}
}
+
+ if (!driveLeft && _left != null)
+ {
+ Release(_left, targets);
+ }
+
+ if (!driveRight && _right != null)
+ {
+ Release(_right, targets);
+ }
+ }
+
+ private static void Release(ArmChain arm, Span targets)
+ {
+ arm.Release(targets[arm.ShoulderJoint], targets[arm.ElbowJoint], out var shoulder, out var elbow);
+ targets[arm.ShoulderJoint] = shoulder;
+ targets[arm.ElbowJoint] = elbow;
}
// The solution itself at weight 1, a blend toward it below that.
@@ -364,9 +395,11 @@ namespace Lodur
}
var p = parts[arm.ParentPart];
- arm.Solve(p.Rotation, p.X, p.Y, p.Z, wrist.X, wrist.Y, wrist.Z, out var shoulder, out var elbow);
- targets[arm.ShoulderJoint] = Toward(targets[arm.ShoulderJoint], shoulder, arms.Weight);
- targets[arm.ElbowJoint] = Toward(targets[arm.ElbowJoint], elbow, arms.Weight);
+ var hand = World(arm.ForearmPart, parts, new IkVec(arm.WristAnchor));
+ arm.Drive(p.Rotation, p.X, p.Y, p.Z, wrist.X, wrist.Y, wrist.Z, hand.X, hand.Y, hand.Z, targets[arm.ShoulderJoint], targets[arm.ElbowJoint], arms.Weight,
+ out var shoulder, out var elbow);
+ targets[arm.ShoulderJoint] = shoulder;
+ targets[arm.ElbowJoint] = elbow;
}
}
}
diff --git a/src/Lodur.Core/PoseBehaviour.cs b/src/Lodur.Core/PoseBehaviour.cs
index 633263b..76c6671 100644
--- a/src/Lodur.Core/PoseBehaviour.cs
+++ b/src/Lodur.Core/PoseBehaviour.cs
@@ -144,7 +144,8 @@ namespace Lodur
///
/// The same, with the orient layers composed between the keys and the flinch: the base key pose, then recoil, look and the arms (each a
- /// blend toward its solution), then the flinch blend over every muscle. Layers write joint targets only; the strength line is the pose rule's.
+ /// blend toward its solution), then the flinch blend over every muscle. With a rig, the arms are composed on every call, driven or
+ /// released, so an arm the goal stopped driving eases back to the base pose. Layers write joint targets only; the strength line is the pose rule's.
/// With no layers, the arithmetic is the key loop's, operation for operation.
///
internal void Write(double weight, double leak, double strain, double seconds, double secondsInGoal, Span strengths, Span targets, in OrientInput orient)
@@ -193,9 +194,9 @@ namespace Lodur
targets[m] = a;
}
- if (layered)
+ if (orient.Rig != null)
{
- orient.Rig!.Compose(this, orient, targets);
+ orient.Rig.Compose(this, orient, targets);
}
for (var m = 0; m < count; m++)
diff --git a/tests/Lodur.Core.Tests/ArmPathTests.cs b/tests/Lodur.Core.Tests/ArmPathTests.cs
new file mode 100644
index 0000000..795e27f
--- /dev/null
+++ b/tests/Lodur.Core.Tests/ArmPathTests.cs
@@ -0,0 +1,387 @@
+using System;
+using Lodur;
+using Xunit.Abstractions;
+
+namespace Lodur.Core.Tests;
+
+///
+/// An arm's motion across ticks, owned by : the minimum-jerk hand path through a via point ahead of the trunk, taken only
+/// when the trunk is in the way (rulings reach-clears-body-by-via-point, reach-path-blocked-only), and the hand-off into and out of the arm layer,
+/// slewed at the output rate both ways (ruling ik-output-slew-limit, follow-up orient-s4-lows).
+///
+public sealed class ArmPathTests
+{
+ private const double Dt = 0.01;
+ private const uint Thing = 7;
+ private const float Step = (float)(ArmChain.MaxAngularRate * Dt);
+ private static readonly BodyPlan Plan = BodyPlans.Humanoid();
+ private static readonly int Joints = Plan.Joints.Count;
+ private static readonly BoxStimulus[] NoBoxes = Array.Empty();
+ private static readonly float[] Origin = { 0f };
+ private readonly ITestOutputHelper _output;
+
+ public ArmPathTests(ITestOutputHelper output) => _output = output;
+
+ private static (float X, float Y, float Z) Mirror((float X, float Y, float Z) p, Side side) => side == Side.Right ? p : (-p.X, p.Y, p.Z);
+
+ private static float Gap((float X, float Y, float Z) a, (float X, float Y, float Z) b) =>
+ 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));
+
+ private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
+
+ /// Drives the arm with the body at its creation pose and the wrist where it hangs, or at .
+ private static bool Drive(ArmChain arm, (float X, float Y, float Z) goal, Quat baseShoulder, Quat baseElbow, double weight, out Quat shoulder, out Quat elbow,
+ (float X, float Y, float Z)? wrist = null)
+ {
+ var parent = Plan.Parts[arm.ParentPart];
+ var w = wrist ?? arm.WristAnchor;
+ return arm.Drive(parent.Rotation, parent.Position.X, parent.Position.Y, parent.Position.Z, goal.X, goal.Y, goal.Z, w.X, w.Y, w.Z,
+ baseShoulder, baseElbow, weight, out shoulder, out elbow);
+ }
+
+ [Theory]
+ [InlineData(Side.Right)]
+ [InlineData(Side.Left)]
+ public void Blocked_is_decided_by_the_trunk_once_per_path_start(Side side)
+ {
+ // The hanging wrist to a goal across the chest and level with the torso: the straight segment touches the trunk. To a goal out to the
+ // arm's own side it stays clear of the trunk by more than the forearm radius.
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var across = Mirror((-0.04f, 1.60f, 0.24f), side);
+ var aside = Mirror((-0.30f, 1.74f, 0.26f), side);
+
+ Drive(arm, across, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.True(arm.PathBlocked);
+ Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"the path starts at the wrist, not {arm.Aim}");
+
+ // Decided once: the goal moving clear of the trunk does not unblock the path.
+ Drive(arm, aside, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.True(arm.PathBlocked);
+
+ arm.Restart();
+ Drive(arm, aside, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.False(arm.PathBlocked);
+ Assert.True(Gap(arm.Aim, aside) < 1e-4f, $"an unblocked reach solves the goal itself, not {arm.Aim}");
+ }
+
+ [Fact]
+ public void The_hand_path_is_minimum_jerk_through_the_via_point_and_meets_a_moving_goal()
+ {
+ var start = (0f, 1f, 0f);
+ var via = (0.1f, 1.2f, 0.3f);
+ var seg = ArmChain.PathSegmentSeconds;
+ var g0 = (0.5f, 1.5f, 0.4f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0f), start) < 1e-4f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, seg), via) < 1e-4f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 2f * seg), g0) < 1e-4f);
+ var mid = ((start.Item1 + via.Item1) / 2f, (start.Item2 + via.Item2) / 2f, (start.Item3 + via.Item3) / 2f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0.5f * seg), mid) < 1e-4f, "midway in the first segment is the midpoint");
+ // Zero velocity at both ends of a segment: a tick in is far less than a linear tick in.
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0.01f * seg), start) < 1e-3f * Gap(start, via));
+
+ // A goal that has moved on during the second segment is met at its end, and the via point's offset shrinks to nothing on the way.
+ var g1 = (0.7f, 1.4f, 0.5f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g1, 2f * seg), g1) < 1e-4f);
+ var half = ArmChain.PathPoint(start, via, g0, g1, 1.5f * seg);
+ var want = (g1.Item1 + 0.5f * (via.Item1 - g0.Item1), g1.Item2 + 0.5f * (via.Item2 - g0.Item2), g1.Item3 + 0.5f * (via.Item3 - g0.Item3));
+ Assert.True(Gap(half, want) < 1e-4f);
+
+ // The chain follows it from the measured wrist: the via point is (wrist x, mid y, trunk front + clearance), the trunk front 0.09 m on the humanoid.
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var wrist = arm.WristAnchor;
+ (float X, float Y, float Z) goal = (-0.04f, 1.60f, 0.24f);
+ (float X, float Y, float Z) viaWant = (wrist.X, 0.5f * (wrist.Y + goal.Y), 0.09f + ArmChain.ViaClearance);
+ var ticks = (int)Math.Round(2.0 * ArmChain.PathSegmentSeconds / Dt);
+ for (var i = 0; i <= ticks + 5; i++)
+ {
+ // The goal drifts 0.1 m forward over the path.
+ (float X, float Y, float Z) g = (goal.X, goal.Y, goal.Z + 0.1f * Math.Min(1f, i / (float)ticks));
+ Drive(arm, g, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ var t = i * (float)Dt;
+ if (i == 0) Assert.True(Gap(arm.Aim, wrist) < 1e-4f);
+ if (i == (int)Math.Round(0.5 * ArmChain.PathSegmentSeconds / Dt))
+ {
+ var half1 = ((wrist.X + viaWant.X) / 2f, (wrist.Y + viaWant.Y) / 2f, (wrist.Z + viaWant.Z) / 2f);
+ Assert.True(Gap(arm.Aim, half1) < 2e-3f, $"midway to the via point at {t} s: {arm.Aim}");
+ }
+
+ if (i == (int)Math.Round(ArmChain.PathSegmentSeconds / Dt))
+ {
+ Assert.True(Gap(arm.Aim, viaWant) < 2e-3f, $"at the via point at {t} s: {arm.Aim}");
+ }
+
+ if (i >= ticks)
+ {
+ Assert.True(Gap(arm.Aim, g) < 1e-4f, $"after the path the goal itself is solved for, not {arm.Aim}");
+ }
+ }
+ }
+
+ [Fact]
+ public void Slewed_by_the_actor_the_hand_off_moves_the_written_arm_targets_at_most_the_rate_both_ways_and_ends_in_the_base()
+ {
+ // A pose goal and a ward-off goal alternate as a sound comes and goes. Every tick, the shoulder and elbow targets of both arms move at most
+ // the rate times the tick, across engaging and disengaging; and once the arms have eased back they write exactly what the pose goal does.
+ var key = new Quat[Joints];
+ for (var m = 0; m < Joints; m++) key[m] = Quat.FromAxisAngle(0f, 0f, 1f, 0.02f * (m + 1));
+ var idle = Pose(key, null);
+ var ward = Pose(key, new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = 0.3f, Spread = 0.15f });
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = idle },
+ new GoalSpec
+ {
+ Id = "ward", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
+ Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
+ Behaviour = ward,
+ },
+ },
+ };
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = 4, MemorySeconds = 0.2 }, body: Plan);
+ var parts = Rest();
+ var targets = new Quat[Joints];
+ var previous = new Quat[Joints];
+ var strengths = new float[Joints];
+ var armJoints = new[] { Plan.JointIndex("Shoulder", Side.Left), Plan.JointIndex("Elbow", Side.Left), Plan.JointIndex("Shoulder", Side.Right), Plan.JointIndex("Elbow", Side.Right) };
+ var sound = new[] { new Emitter { Channel = Channel.Audio, X = 0.3f, Y = 1.5f, Z = 0.7f, Radius = 40f, Intensity = 1.0, Id = 1, Kind = Thing } };
+ var reference = new Quat[Joints];
+ idle.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], reference);
+
+ var (worst, engaged, released, restored) = (0f, 0, 0, 0);
+ var wasWard = false;
+ for (var i = 0; i < 1800; i++)
+ {
+ var on = (i / 150) % 2 == 0;
+ actor.Tick(Origin, Origin, Origin, NoBoxes, strengths, targets, on ? sound : Array.Empty(), parts: parts);
+ var ward1 = actor.GoalIndex == 1;
+ if (ward1 && !wasWard) engaged++;
+ if (!ward1 && wasWard) released++;
+ wasWard = ward1;
+ if (i > 0)
+ {
+ foreach (var m in armJoints) worst = MathF.Max(worst, Turn(previous[m], targets[m]));
+ }
+
+ if (!ward1 && i % 150 == 149 && !on)
+ {
+ // The arms have had the rest of the off-phase to ease back.
+ var same = true;
+ for (var m = 0; m < Joints; m++) same &= targets[m].Equals(reference[m]);
+ if (same) restored++;
+ }
+
+ Array.Copy(targets, previous, Joints);
+ }
+
+ _output.WriteLine($"worst per-tick change {worst:F5} rad against {Step}; engaged {engaged}, released {released}, written the base bit for bit at {restored} phase ends");
+ Assert.True(engaged >= 5 && released >= 5, $"the goals alternated too little to test the hand-off: {engaged}, {released}");
+ Assert.True(worst <= Step + 1e-5f, $"an arm target moved {worst} rad in one tick, the bound is {Step}");
+ Assert.True(worst > 0.5f * Step, $"the arms moved at most {worst} rad a tick, so the hand-off was not slewed at the rate");
+ Assert.True(restored >= 5, $"the arms wrote the base pose bit for bit at only {restored} of the off-phases");
+
+ static PoseBehaviour Pose(Quat[] key, ArmLayer? arms) => new()
+ {
+ Keys = new[] { key }, FlinchPose = Array.ConvertAll(key, _ => Quat.Identity), Arms = arms,
+ };
+ }
+
+ [Fact]
+ public void A_released_arm_stays_the_base_and_reset_and_restart_forget_the_path_and_the_hand_off()
+ {
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var baseShoulder = Quat.FromAxisAngle(0f, 0f, 1f, 0.2f);
+ var baseElbow = Quat.FromAxisAngle(0f, 0f, 1f, -0.3f);
+ var goal = (-0.04f, 1.60f, 0.24f);
+
+ // An arm never driven writes the base untouched.
+ arm.Release(baseShoulder, baseElbow, out var s0, out var e0);
+ Assert.Equal(baseShoulder, s0);
+ Assert.Equal(baseElbow, e0);
+
+ for (var i = 0; i < 100; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ var held = Quat.Identity;
+ var converged = -1;
+ for (var i = 0; i < 100; i++)
+ {
+ arm.Release(baseShoulder, baseElbow, out var s, out var e);
+ if (i > 0) Assert.True(Turn(held, s) <= Step + 1e-5f, "the release moved the shoulder faster than the rate");
+ held = s;
+ if (converged < 0 && s.Equals(baseShoulder) && e.Equals(baseElbow)) converged = i;
+ if (converged >= 0) Assert.True(s.Equals(baseShoulder) && e.Equals(baseElbow), "a released arm left the base after arriving");
+ }
+
+ Assert.True(converged > 3, $"the arm was back on the base after {converged} ticks: it was not slewed");
+
+ // Reset forgets the hand-off: the arm is idle, so the base passes through at once.
+ for (var i = 0; i < 20; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ arm.Reset();
+ arm.Release(baseShoulder, baseElbow, out var s1, out var e1);
+ Assert.Equal(baseShoulder, s1);
+ Assert.Equal(baseElbow, e1);
+
+ // At half weight the written targets are the base blended toward the output, and the hand-off is continuous in them, not in the output.
+ var half = ArmChain.Of(Plan, Side.Right, Dt);
+ var writtenHalf = Quat.Identity;
+ for (var i = 0; i < 100; i++) Drive(half, goal, baseShoulder, baseElbow, 0.5, out writtenHalf, out _);
+ var released = 0f;
+ for (var i = 0; i < 20; i++)
+ {
+ half.Release(baseShoulder, baseElbow, out var sh, out _);
+ released = MathF.Max(released, Turn(writtenHalf, sh));
+ writtenHalf = sh;
+ }
+
+ Assert.True(released <= Step + 1e-5f, $"releasing at half weight moved the written shoulder {released} rad in a tick");
+
+ // Restart starts the path again at the measured wrist, keeping the output: the aim goes back to the wrist.
+ for (var i = 0; i < 100; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ Assert.True(Gap(arm.Aim, goal) < 1e-4f);
+ arm.Restart();
+ Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"a restarted path begins at the measured wrist, not {arm.Aim}");
+ }
+
+ [Fact]
+ public void A_commit_restarts_both_arms_paths_from_the_measured_wrist()
+ {
+ // Reach across the body with the right arm, settled; the parts do not follow, so the measured wrist stays hanging. A tick after
+ // the rig is told of a commit, the arm is on a new path from that wrist and its output turns back toward it by a step; without
+ // the commit the settled output does not move.
+ var key = new Quat[Joints];
+ Array.Fill(key, Quat.Identity);
+ var b = new PoseBehaviour { Keys = new[] { key }, FlinchPose = key, Arms = new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right } };
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Behaviour = b } } };
+ var parts = Rest();
+ var target = new Percept(1, Thing, 0.3f, 1.45f, 0.5f, 1.0, 0.0);
+ var shoulder = Plan.JointIndex("Shoulder", Side.Right);
+ foreach (var commit in new[] { false, true })
+ {
+ var rig = new OrientRig(Plan, brain, Dt);
+ var targets = new Quat[Joints];
+ for (var i = 0; i < 100; i++) b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], targets, new OrientInput(rig, parts, target, Side.Right));
+ var settled = targets[shoulder];
+ if (commit) rig.Commit();
+ b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], targets, new OrientInput(rig, parts, target, Side.Right));
+ var moved = Turn(settled, targets[shoulder]);
+ if (commit) Assert.True(moved > 0.5f * Step, $"after a commit the arm moved only {moved} rad");
+ else Assert.True(moved < 1e-4f, $"a settled arm moved {moved} rad without a commit");
+ }
+ }
+
+ [Fact]
+ public void The_actor_restarts_the_hand_path_when_it_commits_another_target()
+ {
+ // The right arm reaches across the body to a sound, settled. The parts do not follow, so the measured wrist stays hanging. A second,
+ // sound, a millimetre nearer, is committed a latency later and the arm starts a new path from that wrist, turning back by steps; with no second sound the
+ // settled arm does not move.
+ var key = new Quat[Joints];
+ Array.Fill(key, Quat.Identity);
+ PoseBehaviour Pose(ArmLayer? arms) => new() { Keys = new[] { key }, FlinchPose = key, Arms = arms };
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = Pose(null) },
+ new GoalSpec
+ {
+ Id = "reach", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
+ Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
+ Behaviour = Pose(new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right }),
+ },
+ },
+ };
+ Emitter Sound(ulong id, float x, float y, float z) => new() { Channel = Channel.Audio, X = x, Y = y, Z = z, Radius = 40f, Intensity = 1.0, Id = id, Kind = Thing };
+ var shoulder = Plan.JointIndex("Shoulder", Side.Right);
+ foreach (var retarget in new[] { false, true })
+ {
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, body: Plan);
+ var parts = Rest();
+ var targets = new Quat[Joints];
+ var first = new[] { Sound(1, 0.3f, 1.45f, 0.5f) };
+ var both = new[] { Sound(1, 0.3f, 1.45f, 0.5f), Sound(2, 0.3f, 1.45f, 0.499f) };
+ for (var i = 0; i < 150; i++) actor.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, first, parts: parts);
+ Assert.Equal(1UL, actor.TargetId);
+ var last = targets[shoulder];
+ var worst = 0f;
+ for (var i = 0; i < 100; i++)
+ {
+ actor.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, retarget ? both : first, parts: parts);
+ worst = MathF.Max(worst, Turn(last, targets[shoulder]));
+ last = targets[shoulder];
+ }
+
+ if (retarget)
+ {
+ Assert.Equal(2UL, actor.TargetId);
+ Assert.True(worst > 0.5f * Step, $"a committed retarget moved the arm at most {worst} rad in a tick");
+ }
+ else
+ {
+ Assert.True(worst < 1e-3f, $"a settled arm moved {worst} rad in a tick with nothing new");
+ }
+ }
+ }
+
+ [Fact]
+ public void An_engaging_arm_takes_the_short_way_from_a_base_given_with_the_opposite_sign()
+ {
+ // The same rotation as q and as -q: engaging from -q must not turn the long way round to the solution q.
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var fresh = ArmChain.Of(Plan, Side.Right, Dt);
+ var goal = (-0.2f, 1.4f, 0.35f);
+ var parent = Plan.Parts[arm.ParentPart];
+ fresh.Solve(parent.Rotation, parent.Position.X, parent.Position.Y, parent.Position.Z, goal.Item1, goal.Item2, goal.Item3, out var solution, out _);
+ // A base a few steps short of the solution, negated: engaging turns the step toward it, not away.
+ var toward = Quat.Nlerp(solution, Quat.Identity, 0.05f);
+ var negated = new Quat(-toward.X, -toward.Y, -toward.Z, -toward.W);
+ Drive(arm, goal, negated, Quat.Identity, 1.0, out var written, out _);
+ Assert.True(Turn(negated, written) <= Step + 1e-5f, $"engaging turned {Turn(negated, written)} rad from the base in one tick");
+ Assert.True(Turn(written, solution) < Turn(negated, solution) + 1e-4f, "engaging turned away from the solution");
+ Assert.True(Turn(negated, solution) > 0f);
+ }
+
+ [Theory]
+ [InlineData(Side.Right)]
+ [InlineData(Side.Left)]
+ public void A_goal_outrunning_the_rate_keeps_the_shoulder_target_a_unit_rotation(Side side)
+ {
+ // The goal circles the shoulder so fast that the target is always behind it: ten thousand slewed steps compose without drift.
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var s = arm.ShoulderAnchor;
+ var worst = 0f;
+ var chasing = 0;
+ var last = Quat.Identity;
+ for (var i = 0; i < 10000; i++)
+ {
+ var th = 0.9f * i;
+ arm.Solve(Plan.Parts[arm.ParentPart].Rotation, Plan.Parts[arm.ParentPart].Position.X, Plan.Parts[arm.ParentPart].Position.Y, Plan.Parts[arm.ParentPart].Position.Z,
+ s.X + 0.4f * MathF.Sin(th), s.Y - 0.1f, s.Z + 0.4f * MathF.Cos(th), out var q, out _);
+ worst = MathF.Max(worst, MathF.Abs(MathF.Sqrt(q.X * q.X + q.Y * q.Y + q.Z * q.Z + q.W * q.W) - 1f));
+ if (i > 0 && Turn(last, q) > 0.99f * Step) chasing++;
+ last = q;
+ }
+
+ _output.WriteLine($"{side}: norm error {worst:E2}, {chasing} of 10000 ticks at the rate");
+ Assert.True(chasing > 5000, $"the target was at the rate on only {chasing} ticks, so it was not outrun");
+ Assert.True(worst < 1e-5f, $"the shoulder target left the unit sphere by {worst}");
+ }
+
+ // A pose with the arms at rest, to look at the written targets of.
+ private static PartPose[] Rest()
+ {
+ var poses = new PartPose[Plan.Parts.Count];
+ for (var p = 0; p < poses.Length; p++)
+ {
+ var d = Plan.Parts[p];
+ poses[p] = new PartPose(d.Rotation, d.Position.X, d.Position.Y, d.Position.Z);
+ }
+
+ return poses;
+ }
+}
diff --git a/tests/Lodur.Core.Tests/OrientTests.cs b/tests/Lodur.Core.Tests/OrientTests.cs
index 63f6598..127e151 100644
--- a/tests/Lodur.Core.Tests/OrientTests.cs
+++ b/tests/Lodur.Core.Tests/OrientTests.cs
@@ -73,11 +73,18 @@ public sealed class OrientTests
private static Percept At((float X, float Y, float Z) p, ulong id = 1) => new(id, Thing, p.X, p.Y, p.Z, 1.0, 0.0);
- private static Quat[] Run(PoseBehaviour b, PartPose[] parts, Percept target, Side arm = Side.Right, double weight = 1.0, double leak = 0.0, float[]? strengths = null)
+ /// Ticks enough for the arms to engage from the base pose, follow any hand path and settle on their solution (1 s at the test tick).
+ private const int Settle = 100;
+
+ private static Quat[] Run(PoseBehaviour b, PartPose[] parts, Percept target, Side arm = Side.Right, double weight = 1.0, double leak = 0.0, float[]? strengths = null, int ticks = 1)
{
var targets = new Quat[Joints];
var rig = RigOf(b);
- b.Write(weight, leak, 0.0, 0.0, 0.0, strengths ?? new float[Joints], targets, new OrientInput(rig, parts, target, arm));
+ for (var i = 0; i < ticks; i++)
+ {
+ b.Write(weight, leak, 0.0, 0.0, 0.0, strengths ?? new float[Joints], targets, new OrientInput(rig, parts, target, arm));
+ }
+
return targets;
}
@@ -92,6 +99,9 @@ public sealed class OrientTests
private static void SameBits(Quat a, Quat b) => Assert.Equal(a, b);
+ /// The angle of the shortest rotation from a to b.
+ private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
+
private static Quat Flinched(Quat q, Quat flinch, float w) => Quat.Nlerp(q, flinch, w);
private static (float X, float Y, float Z) Wrist(ArmChain arm, PartPose parent, Quat shoulder, Quat elbow)
@@ -163,7 +173,7 @@ public sealed class OrientTests
var parts = Turned();
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = side });
var baseline = Base(b);
- var got = Run(b, parts, At(Ahead));
+ var got = Run(b, parts, At(Ahead), ticks: Settle);
var t = parts[Torso];
foreach (var s in new[] { Side.Left, Side.Right })
{
@@ -172,8 +182,8 @@ public sealed class OrientTests
if (used)
{
arm.Solve(t.Rotation, t.X, t.Y, t.Z, Ahead.X, Ahead.Y, Ahead.Z, out var sh, out var el);
- SameBits(Flinched(sh, Quat.Identity, 0f), got[arm.ShoulderJoint]);
- SameBits(Flinched(el, Quat.Identity, 0f), got[arm.ElbowJoint]);
+ Same(Flinched(sh, Quat.Identity, 0f), got[arm.ShoulderJoint]);
+ Same(Flinched(el, Quat.Identity, 0f), got[arm.ElbowJoint]);
}
else
{
@@ -212,7 +222,7 @@ public sealed class OrientTests
var spread = 0.15f;
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = distance, Spread = spread });
var target = (0.0f, 1.1f, 1.2f);
- var got = Run(b, parts, At(target));
+ var got = Run(b, parts, At(target), ticks: Settle);
var h = parts[Head];
var head = (h.X, h.Y, h.Z);
var u = Sub(target, head);
@@ -244,8 +254,8 @@ public sealed class OrientTests
{
var parts = Rest();
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both, Point = (-0.2f, 1.3f, 0.3f) });
- var without = Run(b, parts, default);
- var with = Run(b, parts, At((3f, 1f, -2f)));
+ var without = Run(b, parts, default, ticks: Settle);
+ var with = Run(b, parts, At((3f, 1f, -2f)), ticks: Settle);
for (var m = 0; m < Joints; m++) SameBits(without[m], with[m]);
var t = parts[Torso];
var wl = Wrist(ArmChain.Of(Plan, Side.Left, Dt), t, Unflinch(with, Side.Left, out var el), el);
@@ -314,7 +324,7 @@ public sealed class OrientTests
var b = Behaviour(new LookLayer { Weight = 0.5 }, new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right, Weight = 0.5 }, recoil);
var parts = Rest();
var target = Bearing(0.5f, 0.5f);
- var got = Run(b, parts, At(target));
+ var got = Run(b, parts, At(target), ticks: Settle);
var depth = (float)recoil.Proximity.Response(0.5);
var key = Key();
@@ -494,11 +504,11 @@ public sealed class OrientTests
[Theory]
[InlineData(Side.Right)]
[InlineData(Side.Left)]
- public void ResetArms_makes_both_arms_solve_the_stateless_rule_again(Side side)
+ public void ResetArms_makes_both_arms_engage_from_the_base_and_settle_on_the_stateless_rule(Side side)
{
// Reach with both arms along the feasible tie of one arm's shoulder (goal (dx, -0.25, -0.25) from it, mirrored for the left), from
- // dx -10 mm to 2 mm past the tie: that arm holds its basin, away from the stateless target. After ResetArms the next tick writes the
- // stateless solve for both arms, bit for bit.
+ // dx -10 mm to 2 mm past the tie: that arm holds its basin, away from the stateless target. After ResetArms both arms are idle: the
+ // next tick writes within one slew step of the base pose, and with the goal held they settle on the stateless solve.
var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both });
var a = Watcher(Watching(b), Plan);
var parts = Rest();
@@ -514,15 +524,22 @@ public sealed class OrientTests
var held = (Quat[])targets.Clone();
a.ResetArms();
Step(a, parts, targets, Emit(1, Goal(0.002f)));
+ var baseline = Base(b);
+ foreach (var arm in arms)
+ {
+ Assert.True(Turn(baseline[arm.ShoulderJoint], targets[arm.ShoulderJoint]) <= ArmChain.MaxAngularRate * Dt + 1e-5f, "the shoulder jumped from the base on engaging");
+ Assert.True(Turn(baseline[arm.ElbowJoint], targets[arm.ElbowJoint]) <= ArmChain.MaxAngularRate * Dt + 1e-5f, "the elbow jumped from the base on engaging");
+ }
+ for (var i = 0; i < Settle; i++) Step(a, parts, targets, Emit(1, Goal(0.002f)));
var t = a.Target;
Assert.Equal(Goal(0.002f), (t.X, t.Y, t.Z));
foreach (var arm in arms)
{
var p = parts[arm.ParentPart];
arm.Solve(p.Rotation, p.X, p.Y, p.Z, t.X, t.Y, t.Z, out var shoulder, out var elbow);
- SameBits(Flinched(shoulder, Quat.Identity, 0f), targets[arm.ShoulderJoint]);
- SameBits(Flinched(elbow, Quat.Identity, 0f), targets[arm.ElbowJoint]);
+ Same(Flinched(shoulder, Quat.Identity, 0f), targets[arm.ShoulderJoint]);
+ Same(Flinched(elbow, Quat.Identity, 0f), targets[arm.ElbowJoint]);
}
var held2 = held[tie.ShoulderJoint];
diff --git a/tests/Lodur.Tests/SeatedOrientTests.cs b/tests/Lodur.Tests/SeatedOrientTests.cs
index a1fe539..9914141 100644
--- a/tests/Lodur.Tests/SeatedOrientTests.cs
+++ b/tests/Lodur.Tests/SeatedOrientTests.cs
@@ -21,46 +21,48 @@ public sealed class SeatedOrientTests
private static readonly (float X, float Y, float Z)[] Sounds = { (0.4f, 1.74f, 0.7f), (-0.4f, 1.74f, 0.7f) };
///
- /// A lower sound to the left, whose ward goals the near (left) arm reaches with zero shoulder twist. The far arm's goal crosses the midline, and
- /// its swing toward it drives the forearm into the side of the trunk, where it wedges (44.6 cm off, gravity or not): the far arm is not claimed here.
- /// Owner: ruling lodur:ruling:reach-clears-body-by-via-point gives the fix (a hand path through a clearance via point) to the follow-up cut
- /// lodur-reach-tracking, which claims the far arm with a bound and retires .
+ /// A lower sound to the left, whose ward goals the near (left) arm reaches with zero shoulder twist. The far arm's goal crosses the midline and the
+ /// straight wrist path to it touches the trunk, so the far arm follows the hand path through the clearance via point (ruling
+ /// lodur:ruling:reach-clears-body-by-via-point): forward first, then across.
///
private static readonly (float X, float Y, float Z) LowSound = (0.4f, 1.2f, 0.9f);
///
- /// Tripwire on the unclaimed far arm at the low sound, metres: the geometric midpoint of the wedged reading, 44.6 cm, and the near-arm bound, 7.04 cm.
- /// Below it the far arm has started to reach, so whoever made it reach claims it with a bound here and deletes this floor.
+ /// Without gravity, bound on the far (right) wrist's distance to its ward goal at the low sound after 2 s, metres: the geometric midpoint of the shipped
+ /// 6.97 cm and the least claimed mutant, 34.92 cm (the via point at the trunk front, clearance 0). Also killed: the via point's x at the midpoint of wrist
+ /// and goal, 39.31 cm; every reach solved directly (blocked forced false), 44.90 cm; the wedge before the path, 44.6 cm.
///
- private const float FarArmWedgedFloor = 0.177f;
+ private const float FarArmBound = 0.1560f;
///
- /// Head forward error bound after 2 s, degrees, at the geometric midpoint (deterministic-bound-margin) of the shipped worst, 1.030 deg over the two
- /// sounds with and without gravity, and the least claimed mutant, 15.233 deg (the look blended at half weight): separation 14.8. Layers off reads 29.7 deg.
+ /// Head forward error bound after 2 s, degrees, set at the geometric midpoint (deterministic-bound-margin) of the shipped worst then, 1.030 deg, and the
+ /// least claimed mutant, 15.233 deg (the look blended at half weight), and not loosened since: the shipped worst is now 1.080 deg over the two sounds with and
+ /// without gravity, the half-weight mutant 15.729 deg. Layers off reads 29.7 deg.
///
private const float LookBoundDegrees = 3.961f;
///
/// Without gravity, bound on each wrist's distance to its own ward goal after 2 s at the head-height sounds, metres: the geometric midpoint of the shipped
- /// worst, 7.00 cm, and the least claimed mutant, 16.23 cm (no spread: both wrists on the line). Also killed: the wrists sent sideways of the head by the
- /// ward distance, 27.72 cm; spread halved and offset 0.1 m, 19.36 cm; the arms blended at half weight, 27.51 cm; the zero-twist swivel clamped to the
- /// shoulder cone (the solver before the feasible-swivel search), 64.94 cm. Layers off reads the start, 81.3 and 83.5 cm.
+ /// worst, 8.11 cm (the arm that the other sound's side blocks, on its via path), and the least claimed mutant, 13.25 cm (no spread: both wrists on the line).
+ /// Also killed: the wrists sent sideways of the head by the ward distance, 35.02 cm; the arms blended at half weight, 46.09 cm. Layers off reads the start,
+ /// 81.3 and 83.5 cm. Not re-measured: spread halved and offset, and the clamped zero-twist swivel (64.94 cm before the hand path), each far above the bound.
///
- private const float WardBound = 0.1066f;
+ private const float WardBound = 0.1037f;
///
- /// Without gravity, bound on the near (left) wrist's distance to its ward goal at the low sound: the geometric midpoint of the shipped 4.34 cm and the
- /// least claimed mutant, 11.41 cm (the arms at half weight). Also killed: sideways, 16.64 cm; no spread, 20.10 cm.
+ /// Without gravity, bound on the near (left) wrist's distance to its ward goal at the low sound, kept from the cut that set it, not loosened: shipped
+ /// 4.13 cm, then 4.34. Killed: the arms at half weight, 36.48 cm; sideways, 25.90 cm; the via point's x at the midpoint, 7.65 cm. Not killed: no spread reads
+ /// 2.95 cm, the look at half weight 5.01 cm, every reach solved directly 5.19 cm.
///
private const float NearWardBound = 0.0704f;
///
- /// Under gravity, the head-height bound on each wrist: the geometric midpoint of the shipped worst, 17.79 cm, and the least claimed mutant, 36.84 cm (no
- /// spread). Also killed: spread halved and offset, 53.28 cm; the arms at half weight, 44.24 cm; the clamped zero-twist swivel, 68.58 cm. The 11 to 13 cm
- /// over the zero-gravity case is the shoulder sagging under the arm's weight (swing 1.11 against a target of 1.50): follow-up lodur-reach-tracking.
- /// Unclaimed: the sideways mutant reads 23.92 cm, separation 1.34.
+ /// Under gravity, the head-height bound on each wrist: the geometric midpoint of the shipped worst, 18.68 cm, and the least claimed mutant, 31.21 cm
+ /// (the wrists sent sideways of the head). Also killed: no spread, 34.79 cm; the arms at half weight, 62.17 cm; the via point's x at the midpoint, 25.41 cm. Not killed: the via point at the trunk front, 23.56 cm. The 11 to 13 cm over the zero-gravity case is
+ /// the shoulder sagging under the arm's weight (swing 1.11 against a target of 1.50): follow-up lodur-gravity-feedforward. Not re-measured: spread halved
+ /// and offset, and the clamped zero-twist swivel, each far above the bound before this cut.
///
- private const float GravityWardBound = 0.2560f;
+ private const float GravityWardBound = 0.2414f;
private readonly ITestOutputHelper _out;
@@ -199,8 +201,7 @@ public sealed class SeatedOrientTests
var low = Run(LowSound, gravity: 0f);
_out.WriteLine($"low sound: wrists to their goals {low.Left * 100f:F2} and {low.Right * 100f:F2} cm");
Assert.True(low.Left < NearWardBound, $"the near wrist is {low.Left * 100f:F1} cm from its goal, bound {NearWardBound * 100f:F1} cm");
- Assert.True(low.Right > FarArmWedgedFloor,
- $"the far wrist now reaches its goal ({low.Right * 100f:F1} cm): claim it with a bound (lodur-reach-tracking) and delete FarArmWedgedFloor");
+ Assert.True(low.Right < FarArmBound, $"the far wrist is {low.Right * 100f:F1} cm from its goal, bound {FarArmBound * 100f:F1} cm");
}
[Fact]