Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Refactor humanoid pose issuance into a helper

Yuechen Li47aa28c05e80
diff --git a/Aetheris.Humanoid.Tests/HumanoidLocomotionTests.cs b/Aetheris.Humanoid.Tests/HumanoidLocomotionTests.cs
new file mode 100644
index 00000000..4802f137
--- /dev/null
+++ b/Aetheris.Humanoid.Tests/HumanoidLocomotionTests.cs
@@ -0,0 +1,64 @@
+using System.Numerics;
+using Xunit;
+
+namespace Aetheris.Humanoid.Tests;
+
+public sealed class HumanoidLocomotionTests
+{
+ [Fact]
+ public void AuthoredAdmissionPreservesLinksAndRejectsInvalidFrames()
+ {
+ var normalized = HumanoidRestPoseNormalizer.Normalize(CanonicalAdultTemplate.Create());
+ var skeleton = normalized.Skeleton;
+ var request = new AuthoredHumanoidPose("idle", skeleton.SkeletonId, skeleton.RestPoseId, [], new(0, 0, -25));
+ var solved = HumanoidKinematicSolver.SolveAuthored(skeleton, request);
+ Assert.True(solved.IsSolved);
+ Assert.All(solved.Pose!.Residuals, residual => Assert.InRange(residual.CenterMm, 0, .001));
+ Assert.False(HumanoidKinematicSolver.SolveAuthored(skeleton, request with { RootOffsetMm = new(0, 0, 251) }).IsSolved);
+ Assert.False(HumanoidKinematicSolver.SolveAuthored(skeleton, request with
+ {
+ Rotations = [new(HumanoidJointKind.Neck, Quaternion.CreateFromAxisAngle(Vector3.UnitX, 2))],
+ }).IsSolved);
+ Assert.False(HumanoidKinematicSolver.SolveAuthored(skeleton, request with
+ {
+ Rotations = [new(HumanoidJointKind.LeftHip, new(0, 0, 0, 2))],
+ }).IsSolved);
+ }
+
+ [Theory]
+ [InlineData(AnatomicalSide.Left)]
+ [InlineData(AnatomicalSide.Right)]
+ public void TwoBoneSolveReachesAnkleAndPreservesTheRigidSkeleton(AnatomicalSide side)
+ {
+ var normalized = HumanoidRestPoseNormalizer.Normalize(CanonicalAdultTemplate.Create());
+ var skeleton = normalized.Skeleton;
+ var source = HumanoidKinematicSolver.SolveAuthored(skeleton,
+ new("rest", skeleton.SkeletonId, skeleton.RestPoseId, [], Vector3.Zero)).Pose!;
+ int index = skeleton.Joints.ToList().FindIndex(joint => joint.Kind.ToString() == side + "Ankle");
+ Vector3 target = source.GlobalTransforms[index].Translation + new Vector3(0, 40, 80);
+ var result = HumanoidKinematicSolver.SolveLeg(skeleton, source, new(side, target, Vector3.UnitZ));
+ Assert.InRange(result.ResidualMm, 0, .01f);
+ Assert.False(result.ReachClamped);
+ Assert.All(result.Pose.Residuals, residual =>
+ {
+ Assert.InRange(residual.CenterMm, 0, .001);
+ Assert.InRange(residual.LinkLengthMm, 0, .001);
+ });
+ var binding = new HumanoidSkinningBinding(normalized.Surface, skeleton);
+ Assert.Equal(skeleton.Joints.Count, binding.CreatePalette(result.Pose).Count);
+ }
+
+ [Fact]
+ public void UnreachableTargetIsReportedWithoutStretchingTheLeg()
+ {
+ var normalized = HumanoidRestPoseNormalizer.Normalize(CanonicalAdultTemplate.Create());
+ var skeleton = normalized.Skeleton;
+ var source = HumanoidKinematicSolver.SolveAuthored(skeleton,
+ new("rest", skeleton.SkeletonId, skeleton.RestPoseId, [], Vector3.Zero)).Pose!;
+ var result = HumanoidKinematicSolver.SolveLeg(skeleton, source,
+ new(AnatomicalSide.Left, new(-100, 0, -2000), Vector3.UnitZ));
+ Assert.True(result.ReachClamped);
+ Assert.True(result.ResidualMm > 500);
+ Assert.All(result.Pose.Residuals, residual => Assert.InRange(residual.LinkLengthMm, 0, .001));
+ }
+}
diff --git a/Aetheris.Humanoid/HumanoidKinematics.cs b/Aetheris.Humanoid/HumanoidKinematics.cs
index 11d68726..71c5618a 100644
--- a/Aetheris.Humanoid/HumanoidKinematics.cs
+++ b/Aetheris.Humanoid/HumanoidKinematics.cs
@@ -64,7 +64,7 @@ public sealed record HumanoidSolveResult(SolvedHumanoidPose? Pose,
/// adopted joint's source-derived rest frame. Public angles are absolute canonical anatomical
/// states; source-rest offsets are measured and removed inside the adapter.
/// </summary>
-public static class HumanoidKinematicSolver
+public static partial class HumanoidKinematicSolver
{
public const double LinearToleranceMm = .001;
public const string Version = "aetheris.humanoid.semantic-pose.v1";
@@ -169,6 +169,18 @@ public static class HumanoidKinematicSolver
rotations.Add(new(input.Joint, rotation));
}
var state = new HumanoidPoseState(request.PoseId, rotations.AsReadOnly(), HumanoidTransform.Identity);
+ return IssuePose(skeleton, state, states, shapeRevision, diagnostics, projections);
+ }
+
+ private static HumanoidSolveResult IssuePose(HumanoidSkeleton skeleton, HumanoidPoseState state,
+ IReadOnlyList<AnatomicalJointRequest> states, long shapeRevision,
+ List<KinematicDiagnostic> diagnostics, List<JointProjection> projections)
+ {
+ HumanoidSolveResult Reject(string code, string message, HumanoidJointKind joint)
+ {
+ diagnostics.Add(new(code, message, joint));
+ return new(null, diagnostics.AsReadOnly(), projections.AsReadOnly());
+ }
var globals = HumanoidPosing.GlobalPose(skeleton, state).ToArray();
var residuals = new List<JointConstraintResidual>();
for (var i = 0; i < skeleton.Joints.Count; i++)
diff --git a/Aetheris.Humanoid/HumanoidLocomotion.cs b/Aetheris.Humanoid/HumanoidLocomotion.cs
new file mode 100644
index 00000000..4b123549
--- /dev/null
+++ b/Aetheris.Humanoid/HumanoidLocomotion.cs
@@ -0,0 +1,193 @@
+using System.Numerics;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Humanoid;
+
+/// <summary>Rest-relative authored rotations and bounded visual root offset, in canonical millimetres.</summary>
+public sealed record AuthoredHumanoidPose(string PoseId, string SkeletonId, string RestPoseId,
+ IReadOnlyList<JointPose> Rotations, Vector3 RootOffsetMm);
+
+public sealed record HumanoidLegTarget(AnatomicalSide Side, Vector3 AnkleMm, Vector3 SoleNormal);
+public sealed record HumanoidLegSolve(SolvedHumanoidPose Pose, float ResidualMm, bool ReachClamped);
+
+public static partial class HumanoidKinematicSolver
+{
+ /// <summary>
+ /// Gameplay animation admission. Preserves rigid rest links, validates every explicit
+ /// rotation against a named engineering envelope, and issues the existing skinning token.
+ /// These rest-relative coordinates are distinct from absolute anatomical requests.
+ /// </summary>
+ public static HumanoidSolveResult SolveAuthored(HumanoidSkeleton skeleton, AuthoredHumanoidPose request)
+ {
+ HumanoidSolveResult Reject(string message) => new(null, [new("HUM320", message)], []);
+ var error = ValidateRest(skeleton);
+ if (error is not null || request.SkeletonId != skeleton.SkeletonId || request.RestPoseId != skeleton.RestPoseId)
+ {
+ return Reject(error ?? "Authored pose belongs to a different rest skeleton.");
+ }
+ if (!Finite(request.RootOffsetMm) || request.RootOffsetMm.Length() > 250 || request.Rotations is null ||
+ request.Rotations.Select(item => item.Joint).Distinct().Count() != request.Rotations.Count)
+ {
+ return Reject("Authored root offset must be finite and at most 250 mm; rotations must be unique.");
+ }
+ var known = skeleton.Joints.Select(joint => joint.Kind).ToHashSet();
+ foreach (var rotation in request.Rotations)
+ {
+ var q = rotation.LocalRotation;
+ if (!known.Contains(rotation.Joint) || !Finite(q) || MathF.Abs(q.LengthSquared() - 1) > .0001f)
+ {
+ return Reject("Authored rotations must name existing joints and be finite unit quaternions.");
+ }
+ float angle = 2 * MathF.Acos(Math.Clamp(MathF.Abs(q.W), 0, 1)) * 180 / MathF.PI;
+ if (angle > AuthoredEnvelopeDegrees(rotation.Joint) + .001f)
+ {
+ return Reject($"Authored joint '{rotation.Joint}' exceeds its rest-relative engineering envelope ({angle:F3} degrees).");
+ }
+ }
+ skeleton = skeleton with
+ {
+ Joints = Array.AsReadOnly(skeleton.Joints.ToArray()),
+ Symmetry = new System.Collections.ObjectModel.ReadOnlyDictionary<HumanoidJointKind, HumanoidJointKind>(skeleton.Symmetry.ToDictionary()),
+ };
+ var offset = request.RootOffsetMm;
+ var state = new HumanoidPoseState(request.PoseId, Array.AsReadOnly(request.Rotations.ToArray()),
+ HumanoidTransform.FromTranslation(new Point3D(offset.X, offset.Y, offset.Z)));
+ var globals = HumanoidPosing.GlobalPose(skeleton, state);
+ var measured = new List<AnatomicalJointRequest>();
+ foreach (var joint in Interfaces(skeleton))
+ {
+ if (HumanoidPoseSemantics.TryMeasure(skeleton, globals, joint.Joint, out var value))
+ {
+ // Corrective activation uses measured absolute flexion, not imported bone Euler angles.
+ measured.Add(new(value.Joint, value.FlexionDegrees, value.AbductionDegrees, value.TwistDegrees));
+ if (joint is AnatomicalHingeInterface && value.FlexionDegrees > joint.MaximumFlexion + .01)
+ {
+ return Reject($"Authored hinge '{joint.Joint}' exceeds its flexion limit.");
+ }
+ }
+ }
+ return IssuePose(skeleton, state, measured, 0, [], []);
+ }
+
+ private static float AuthoredEnvelopeDegrees(HumanoidJointKind joint)
+ {
+ string name = joint.ToString();
+ if (name.EndsWith("Shoulder")) return 165;
+ if (name.EndsWith("Hip")) return 135;
+ if (name.EndsWith("Knee") || name.EndsWith("Elbow")) return 150;
+ if (name.EndsWith("Ankle")) return 95;
+ // This gameplay hand frame includes pronation from collapsed forearm helpers.
+ if (name.EndsWith("Wrist")) return 120;
+ if (name.EndsWith("ToeBase")) return 70;
+ if (joint is HumanoidJointKind.Pelvis) return 35;
+ if (joint is HumanoidJointKind.SpineLower or HumanoidJointKind.SpineMid or HumanoidJointKind.Chest) return 35;
+ if (joint is HumanoidJointKind.Neck or HumanoidJointKind.Head) return 55;
+ if (name.EndsWith("Clavicle")) return 35;
+ // Fingers and root rotation are deliberately outside this locomotion profile.
+ return 0;
+ }
+
+ /// <summary>Analytic hip-knee-ankle solve; keeps link lengths and the animated knee pole.</summary>
+ public static HumanoidLegSolve SolveLeg(HumanoidSkeleton skeleton, SolvedHumanoidPose source, HumanoidLegTarget target)
+ {
+ if (target.Side is not (AnatomicalSide.Left or AnatomicalSide.Right) ||
+ !Finite(target.AnkleMm) || !Finite(target.SoleNormal) || target.SoleNormal.LengthSquared() < .5f ||
+ !skeleton.Joints.SequenceEqual(source.Skeleton.Joints))
+ {
+ throw new ArgumentException("Leg IK needs a matching pose, finite ankle and a ground normal.");
+ }
+ string side = target.Side.ToString();
+ int hip = Index(side + "Hip");
+ int knee = Index(side + "Knee");
+ int ankle = Index(side + "Ankle");
+ Vector3 origin = source.GlobalTransforms[hip].Translation;
+ Vector3 middle = source.GlobalTransforms[knee].Translation;
+ Vector3 end = source.GlobalTransforms[ankle].Translation;
+ float upper = Vector3.Distance(origin, middle);
+ float lower = Vector3.Distance(middle, end);
+ Vector3 direction = target.AnkleMm - origin;
+ float requestedDistance = direction.Length();
+ if (requestedDistance < .001f) direction = end - origin;
+ direction = Vector3.Normalize(direction);
+ float distance = Math.Clamp(requestedDistance, MathF.Abs(upper - lower) + .1f, upper + lower - .1f);
+ Vector3 pole = middle - origin;
+ pole -= direction * Vector3.Dot(pole, direction);
+ if (pole.LengthSquared() < .01f)
+ {
+ pole = Vector3.UnitY - direction * Vector3.Dot(Vector3.UnitY, direction);
+ }
+ if (pole.LengthSquared() < .01f) pole = Vector3.UnitX;
+ pole = Vector3.Normalize(pole);
+ float along = (upper * upper - lower * lower + distance * distance) / (2 * distance);
+ float height = MathF.Sqrt(MathF.Max(0, upper * upper - along * along));
+ Vector3 solvedMiddle = origin + direction * along + pole * height;
+ Vector3 solvedEnd = origin + direction * distance;
+ var rotations = source.PoseState.LocalRotations.ToDictionary(item => item.Joint, item => item.LocalRotation);
+ var globals = source.GlobalTransforms.ToArray();
+ RotateJoint(hip, middle - origin, solvedMiddle - origin);
+ Recompute();
+ RotateJoint(knee, globals[ankle].Translation - globals[knee].Translation, solvedEnd - globals[knee].Translation);
+ Recompute();
+ // Preserve animated foot heading while aligning its transported rest sole to the contact normal.
+ Vector3 restUpLocal = Vector3.TransformNormal(Vector3.UnitZ, skeleton.Joints[ankle].InverseBind);
+ Vector3 footUp = Vector3.TransformNormal(restUpLocal, globals[ankle]);
+ RotateJoint(ankle, footUp, Vector3.Normalize(target.SoleNormal));
+ var authored = new AuthoredHumanoidPose(source.PoseState.PoseId + ".ik", skeleton.SkeletonId, skeleton.RestPoseId,
+ rotations.OrderBy(pair => pair.Key).Select(pair => new JointPose(pair.Key, pair.Value)).ToArray(),
+ source.PoseState.RootTransform.Matrix.Translation);
+ var result = SolveAuthored(skeleton, authored);
+ if (!result.IsSolved)
+ {
+ throw new InvalidDataException(string.Join("; ", result.Diagnostics.Select(item => item.Message)));
+ }
+ return new(result.Pose!, Vector3.Distance(result.Pose!.GlobalTransforms[ankle].Translation, target.AnkleMm),
+ MathF.Abs(distance - requestedDistance) > .01f);
+
+ int Index(string name)
+ {
+ int index = skeleton.Joints.ToList().FindIndex(joint => joint.Kind.ToString() == name);
+ if (index < 0) throw new InvalidDataException("Leg IK is missing " + name);
+ return index;
+ }
+ void Recompute()
+ {
+ var state = source.PoseState with
+ {
+ LocalRotations = rotations.Select(pair => new JointPose(pair.Key, pair.Value)).ToArray(),
+ };
+ globals = HumanoidPosing.GlobalPose(skeleton, state).ToArray();
+ }
+ void RotateJoint(int index, Vector3 from, Vector3 to)
+ {
+ Matrix4x4 parent = skeleton.Joints[index].ParentIndex is int p ? globals[p] : source.PoseState.RootTransform.Matrix;
+ if (!Matrix4x4.Invert(parent, out var inverseParent) ||
+ !Matrix4x4.Invert(skeleton.Joints[index].LocalRest.Matrix, out var inverseRest))
+ {
+ throw new InvalidDataException("Leg IK encountered a singular rest frame.");
+ }
+ Matrix4x4 desired = globals[index] * Matrix4x4.CreateFromQuaternion(Arc(from, to));
+ desired.Translation = globals[index].Translation;
+ Matrix4x4 delta = desired * inverseParent * inverseRest;
+ rotations[skeleton.Joints[index].Kind] = Quaternion.Normalize(Quaternion.CreateFromRotationMatrix(delta));
+ }
+ }
+
+ private static Quaternion Arc(Vector3 from, Vector3 to)
+ {
+ from = Vector3.Normalize(from);
+ to = Vector3.Normalize(to);
+ float dot = Math.Clamp(Vector3.Dot(from, to), -1, 1);
+ if (dot > .999999f) return Quaternion.Identity;
+ if (dot < -.999999f)
+ {
+ Vector3 axis = Vector3.Cross(from, Vector3.UnitX);
+ if (axis.LengthSquared() < .001f) axis = Vector3.Cross(from, Vector3.UnitY);
+ return Quaternion.CreateFromAxisAngle(Vector3.Normalize(axis), MathF.PI);
+ }
+ var cross = Vector3.Cross(from, to);
+ return Quaternion.Normalize(new Quaternion(cross, 1 + dot));
+ }
+
+ private static bool Finite(Vector3 value) => float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z);
+ private static bool Finite(Quaternion value) => float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z) && float.IsFinite(value.W);
+}
diff --git a/docs/public/humanoid-locomotion.md b/docs/public/humanoid-locomotion.md
new file mode 100644
index 00000000..918ce0b8
--- /dev/null
+++ b/docs/public/humanoid-locomotion.md
@@ -0,0 +1,47 @@
+# Authored humanoid poses and leg IK
+
+`HumanoidKinematicSolver.SolveAuthored` admits explicit rest-relative quaternion
+channels and a canonical millimetre visual root offset. The caller names the
+skeleton and rest revision. The API checks finite unit quaternions, known unique
+joints, a root offset of at most 250 mm, named engineering rotation envelopes,
+measured hinge flexion and the existing rigid-link residual checks. It issues
+the same `SolvedHumanoidPose` consumed by skinning; there is no bypass token or
+alternate skeleton authority.
+
+These coordinates differ from `AnatomicalJointRequest`, whose flexion/abduction/
+twist coordinates are absolute anatomical requests. Imported local quaternions
+must be converted against the actual rest skeleton. Engineering envelopes are
+not medical limits and do not certify an arbitrary mesh deformation. Call
+`HumanoidGameplayBody.Evaluate` and inspect its surface evidence independently.
+
+`SolveLeg` accepts a matching solved pose, anatomical side, canonical ankle
+target and ground normal. It solves hip-knee-ankle analytically using the source
+knee pole, keeps both rigid link lengths, and transports the sole normal onto
+the ground while preserving animated heading. Unreachable targets clamp to the
+rigid chain and report `ReachClamped` plus ankle residual in millimetres. The
+result is re-admitted through `SolveAuthored`; admission failure is explicit.
+
+The application owns collision queries, stance detection, world-space locks,
+pelvis adjustment, fading and release policy. Aetheris owns pose admission and
+the solve. The small joint calculation does not deform the surface; Aurelian's
+existing GPU skinning consumes the resulting palette.
+
+Tests cover authored admission failures, both reachable legs, rigid-link
+residuals, palette compatibility and an unreachable target without stretching.
+The Copeland Mixamo bank exercises this API with a separately prepared Antonia
+body. Its 1,737-pose qualification now passes the existing surface screen on CPU
+and Vulkan ground queries. Kinematic test success alone does not confer animation
+or production-mesh qualification.
+
+`scripts/repair-antonia-locomotion-weights.py` writes an explicit body variant,
+leaving its source intact. It changes only normalized skin support: a continuous
+neck-to-skull transition from 60 mm below the neck pivot over 100 mm, and a knee
+transition half-width of 200 mm with the existing radial fade. Geometry, topology,
+rest skeleton and authored hip correctives are retained and checked. Source hash
+and recipe are recorded in provenance; the result remains a development candidate
+pending its own pose qualification. The original body is not promoted or replaced.
+
+Run `scripts/test-antonia-locomotion-weights.py` with Python for regressions on
+region-boundary continuity, bilateral support, retained geometry and distant
+support. New clips still require independent surface qualification; the successful
+bank does not certify arbitrary poses, fingers, facial animation or intersections.
diff --git a/scripts/repair-antonia-locomotion-weights.py b/scripts/repair-antonia-locomotion-weights.py
new file mode 100644
index 00000000..2f7b3025
--- /dev/null
+++ b/scripts/repair-antonia-locomotion-weights.py
@@ -0,0 +1,125 @@
+"""Prepare an explicit Antonia development body for authored locomotion.
+
+Preserves geometry, topology, rest transforms and correctives. The recipe changes
+anatomical weight support only; every resulting pose still needs qualification.
+"""
+import argparse
+import hashlib
+import json
+import math
+from pathlib import Path
+
+
+def smoothstep(value):
+ value = min(1.0, max(0.0, value))
+ return value * value * (3.0 - 2.0 * value)
+
+
+def point(value):
+ return [value[axis] for axis in ("x", "y", "z")]
+
+
+def subtract(a, b):
+ return [left - right for left, right in zip(a, b)]
+
+
+def length(value):
+ return math.sqrt(sum(component * component for component in value))
+
+
+def prepare(body, knee_width_mm):
+ joints = body["skeleton"]["joints"]
+ indices = {joint["kind"]: index for index, joint in enumerate(joints)}
+ centers = {joint["kind"]: [joint["globalBind"][key] for key in ("m41", "m42", "m43")]
+ for joint in joints}
+ neck = centers["Neck"][2]
+ changes = {"head": 0, "knee": 0}
+ for vertex, skin in zip(body["surface"]["vertices"], body["surface"]["skinWeights"]):
+ position = point(vertex["position"])
+ weights = {entry["jointIndex"]: entry["weight"] for entry in skin["weights"]}
+ # Facial tissue above the jaw follows the skull, not the cervical chain.
+ if weights.get(indices["Neck"], 0) > 0:
+ amount = weights.get(indices["Neck"], 0) * smoothstep(
+ (position[2] - (neck - 60)) / 100)
+ if amount > 0:
+ weights[indices["Neck"]] -= amount
+ weights[indices["Head"]] = weights.get(indices["Head"], 0) + amount
+ changes["head"] += 1
+ for side in ("Left", "Right"):
+ hip = indices[side + "Hip"]
+ knee = indices[side + "Knee"]
+ total = weights.get(hip, 0) + weights.get(knee, 0)
+ center = centers[side + "Knee"]
+ relative = subtract(position, center)
+ distance = length(relative)
+ if total < .5 or distance > 250:
+ continue
+ direction = subtract(centers[side + "Ankle"], center)
+ direction = [component / length(direction) for component in direction]
+ along = sum(a * b for a, b in zip(relative, direction))
+ desired = smoothstep((along + knee_width_mm) / (2 * knee_width_mm))
+ fade = 1 - smoothstep((distance - 150) / 100)
+ current = weights.get(knee, 0) / total
+ fraction = current + fade * (desired - current)
+ weights[knee] = total * fraction
+ weights[hip] = total * (1 - fraction)
+ changes["knee"] += 1
+ weights = {index: value for index, value in weights.items() if value > 1e-12}
+ total = sum(weights.values())
+ skin["weights"] = [{"jointIndex": index, "weight": value / total}
+ for index, value in sorted(weights.items())]
+ return changes
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--body", required=True)
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--knee-width-mm", type=float, default=200)
+ args = parser.parse_args()
+ source = Path(args.body)
+ output = Path(args.out)
+ if source.resolve() == output.resolve():
+ raise ValueError("Write a new candidate; do not overwrite the source body.")
+ if not 40 <= args.knee_width_mm <= 240:
+ raise ValueError("Knee transition half-width must be 40..240 mm.")
+ raw = source.read_bytes()
+ body = json.loads(raw)
+ if body.get("schema") != "aetheris.humanoid.gameplay-body.v1" or \
+ body["surface"]["topologyId"] != "aetheris.humanoid.antonia.adoption-candidate.v1" or \
+ body["skeleton"]["restPoseId"] != "aetheris.humanoid.rest.apose.v1":
+ raise ValueError("This recipe requires the explicit Antonia A-pose gameplay body.")
+ vertices = body["surface"]["vertices"]
+ skins = body["surface"]["skinWeights"]
+ if len(vertices) != len(skins) or any(skin["vertexIndex"] != index for index, skin in enumerate(skins)):
+ raise ValueError("Skin rows must correspond to every retained vertex in order.")
+ retained = json.dumps([body["surface"][key] for key in ("vertices", "faces", "bindingTriangles")]
+ + [body["skeleton"], body["correctives"]], sort_keys=True)
+ changes = prepare(body, args.knee_width_mm)
+ after = json.dumps([body["surface"][key] for key in ("vertices", "faces", "bindingTriangles")]
+ + [body["skeleton"], body["correctives"]], sort_keys=True)
+ if retained != after:
+ raise ValueError("Weight repair changed retained geometry, topology, skeleton or correctives.")
+ for skin in body["surface"]["skinWeights"]:
+ values = [weight["weight"] for weight in skin["weights"]]
+ if len(values) > 6 or not all(math.isfinite(value) and value > 0 for value in values):
+ raise ValueError("Invalid or excessive skin influences.")
+ if abs(sum(values) - 1) > 1e-9:
+ raise ValueError("Skin weights must stay normalized.")
+ source_hash = hashlib.sha256(raw).hexdigest().upper()
+ recipe = dict(sourceSha256=source_hash, kneeTransitionHalfWidthMm=args.knee_width_mm,
+ faceSupport="neck-to-head transfer above jaw with smooth transition")
+ body["id"] += ".locomotion-weights.v1"
+ body["provenance"]["transformations"].append(
+ "Locomotion support repair: " + json.dumps(recipe, sort_keys=True))
+ body["provenance"]["generatorVersion"] = "antonia.locomotion-weights.v1"
+ body["provenance"]["configHash"] = hashlib.sha256(json.dumps(recipe, sort_keys=True).encode()).hexdigest()
+ body["provenance"]["admissionStatus"] = "Unqualified locomotion weight candidate; evaluate every pose separately"
+ body["provenance"]["outputHash"] = hashlib.sha256(json.dumps(body["surface"]["skinWeights"]).encode()).hexdigest()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(body, separators=(",", ":")))
+ print("LOCOMOTION_WEIGHTS_PREPARED", json.dumps(dict(recipe=recipe, changedVertices=changes)))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-antonia-locomotion-weights.py b/scripts/test-antonia-locomotion-weights.py
new file mode 100644
index 00000000..43a0e2bd
--- /dev/null
+++ b/scripts/test-antonia-locomotion-weights.py
@@ -0,0 +1,64 @@
+"""Regression checks for continuous anatomical support across region boundaries."""
+import copy
+import importlib.util
+from pathlib import Path
+import unittest
+
+spec = importlib.util.spec_from_file_location("locomotion_weights",
+ Path(__file__).with_name("repair-antonia-locomotion-weights.py"))
+repair = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(repair)
+
+
+def body_with(vertices):
+ positions = {"Neck": (0, 0, 1510), "Head": (0, 0, 1570)}
+ for side, x in (("Left", -90), ("Right", 90)):
+ positions[side + "Hip"] = (x, 0, 960)
+ positions[side + "Knee"] = (x, 0, 524)
+ positions[side + "Ankle"] = (x, 0, 80)
+ joints = [{"kind": name, "globalBind": dict(zip(("m41", "m42", "m43"), position))}
+ for name, position in positions.items()]
+ indices = {joint["kind"]: index for index, joint in enumerate(joints)}
+ return dict(skeleton=dict(joints=joints), surface=dict(
+ vertices=[dict(region=region, position=dict(zip(("x", "y", "z"), position)))
+ for region, position, weights in vertices],
+ skinWeights=[dict(weights=[dict(jointIndex=indices[name], weight=value)
+ for name, value in weights.items()])
+ for region, position, weights in vertices]))
+
+
+class WeightSupportTests(unittest.TestCase):
+ def test_neck_jaw_region_boundary_has_no_weight_seam(self):
+ weights = dict(Neck=.4, Head=.6)
+ body = body_with([("Head", (20, 80, 1564), weights),
+ ("Neck", (20, 80, 1564), weights),
+ ("Neck", (20, 0, 1490), weights)])
+ repair.prepare(body, 200)
+ rows = body["surface"]["skinWeights"]
+ self.assertEqual(rows[0], rows[1])
+ self.assertEqual(rows[0]["weights"], [dict(jointIndex=1, weight=1)])
+ self.assertGreater(rows[2]["weights"][0]["weight"], 0)
+
+ def test_bilateral_knee_support_preserves_other_channels_and_geometry(self):
+ body = body_with([("LeftShin", (-90, -70, 510), dict(LeftHip=.45, LeftKnee=.45, Head=.1)),
+ ("RightShin", (90, -70, 510), dict(RightHip=.45, RightKnee=.45, Head=.1))])
+ original = copy.deepcopy(body)
+ repair.prepare(body, 200)
+ self.assertEqual(body["surface"]["vertices"], original["surface"]["vertices"])
+ self.assertEqual(body["skeleton"], original["skeleton"])
+ left, right = body["surface"]["skinWeights"]
+ self.assertEqual([item["weight"] for item in left["weights"]],
+ [item["weight"] for item in right["weights"]])
+ for row in (left, right):
+ self.assertAlmostEqual(sum(item["weight"] for item in row["weights"]), 1)
+ self.assertAlmostEqual(row["weights"][0]["weight"], .1)
+
+ def test_support_outside_knee_neighborhood_is_unchanged(self):
+ body = body_with([("LeftFoot", (-90, 90, 50), dict(LeftKnee=.3, LeftAnkle=.7))])
+ original = copy.deepcopy(body)
+ repair.prepare(body, 200)
+ self.assertEqual(body, original)
+
+
+if __name__ == "__main__":
+ unittest.main()