Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Normalize humanoid poses against canonical anatomical states

Yuechen Lie8e75188b868
diff --git a/Aetheris.Humanoid.Tests/HumanoidRestX1Tests.cs b/Aetheris.Humanoid.Tests/HumanoidRestX1Tests.cs
new file mode 100644
index 00000000..27114f52
--- /dev/null
+++ b/Aetheris.Humanoid.Tests/HumanoidRestX1Tests.cs
@@ -0,0 +1,148 @@
+using System.Numerics;
+using Aetheris.Humanoid;
+using Aetheris.Kernel.Core.Math;
+using Xunit;
+
+namespace Aetheris.Humanoid.Tests;
+
+public sealed class HumanoidRestX1Tests
+{
+ [Fact]
+ public void TAndAPoseSourcesReachSameAbsoluteShoulderState()
+ {
+ var tPose = ArmSkeleton(90);
+ var aPose = ArmSkeleton(CanonicalHumanoidRestPose.ShoulderAbductionDegrees);
+ var requestT = new RequestedHumanoidPose("shoulder90", tPose.SkeletonId, tPose.RestPoseId, 0,
+ [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 90)]);
+ var requestA = requestT with { SkeletonId = aPose.SkeletonId, RestPoseId = aPose.RestPoseId };
+
+ var tSolved = HumanoidKinematicSolver.Solve(tPose, requestT).Pose!;
+ var aSolved = HumanoidKinematicSolver.Solve(aPose, requestA).Pose!;
+ var tActual = HumanoidPoseSemantics.Measure(tPose, tSolved.GlobalTransforms, HumanoidJointKind.LeftShoulder);
+ var aActual = HumanoidPoseSemantics.Measure(aPose, aSolved.GlobalTransforms, HumanoidJointKind.LeftShoulder);
+
+ Assert.InRange(Math.Abs(tActual.AbductionDegrees - 90), 0, .001);
+ Assert.InRange(Math.Abs(aActual.AbductionDegrees - 90), 0, .001);
+ AssertVectorNear(tSolved.GlobalTransforms[4].Translation, aSolved.GlobalTransforms[4].Translation, .001f);
+ Assert.Equal(Quaternion.Identity, tSolved.PoseState.LocalRotations.Single().LocalRotation);
+ Assert.NotEqual(Quaternion.Identity, aSolved.PoseState.LocalRotations.Single().LocalRotation);
+ }
+
+ [Fact]
+ public void CanonicalNormalizationPreservesIdentityRebuildsBindsAttachmentsAndMorphs()
+ {
+ var source = CanonicalAdultTemplate.Create();
+ var normalized = HumanoidRestPoseNormalizer.Normalize(source);
+
+ Assert.Equal(CanonicalHumanoidRestPose.Id, normalized.Skeleton.RestPoseId);
+ Assert.Equal(source.Surface.TopologyId, normalized.Surface.TopologyId);
+ Assert.Equal(source.Surface.ConnectivityHash, normalized.Surface.ConnectivityHash);
+ Assert.Equal(source.Surface.Vertices.Count, normalized.Surface.Vertices.Count);
+ Assert.Equal(source.Surface.Faces.Select(face => (face.A, face.B, face.C)),
+ normalized.Surface.Faces.Select(face => (face.A, face.B, face.C)));
+ var rest = HumanoidPosing.EvaluateVertices(normalized, normalized.PoseState);
+ Assert.InRange(rest.Select((point, index) => (point - normalized.Surface.Vertices[index].Position).Length).Max(), 0, .001);
+ Assert.All(CanonicalHumanoidRestPose.Requests, request =>
+ {
+ var actual = HumanoidPoseSemantics.Measure(normalized.Skeleton,
+ normalized.Skeleton.Joints.Select(joint => joint.GlobalBind).ToArray(), request.Joint);
+ Assert.InRange(Math.Abs(actual.FlexionDegrees - request.FlexionDegrees), 0, .02);
+ Assert.InRange(Math.Abs(actual.AbductionDegrees - request.AbductionDegrees), 0, .02);
+ });
+ Assert.All(normalized.Attachments, attachment =>
+ Assert.Equal(Resolve(normalized.Surface, attachment.PositionBinding), attachment.NeutralFrame.Position));
+ foreach (var morph in new[] { HumanoidMorphId.Height, HumanoidMorphId.ArmLength,
+ HumanoidMorphId.LegLength, HumanoidMorphId.ShoulderWidth })
+ {
+ var channel = normalized.MorphChannels.Single(item => item.Id == morph);
+ var value = channel.Default == channel.Maximum ? channel.Minimum : channel.Maximum;
+ var shaped = HumanoidMorphing.Apply(normalized, new Dictionary<HumanoidMorphId, double> { [morph] = value });
+ Assert.Equal(normalized.Surface.ConnectivityHash, shaped.Surface.ConnectivityHash);
+ var validation = HumanoidValidator.Validate(shaped);
+ Assert.True(validation.IsValid, morph + ": " + string.Join("; ", validation.Diagnostics.Select(x => x.Code + "[" + x.EntityId + "]: " + x.Message)));
+ }
+ }
+
+ [Fact]
+ public void AnatomicalLeftRightIsIndependentOfCameraView()
+ {
+ var skeleton = MirroredArmSkeleton();
+ var solved = HumanoidKinematicSolver.Solve(skeleton, new("mirrored", skeleton.SkeletonId,
+ skeleton.RestPoseId, 0,
+ [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 60),
+ new(HumanoidJointKind.RightShoulder, AbductionDegrees: 60)])).Pose!;
+ var left = solved.GlobalTransforms[skeleton.Joints.ToList().FindIndex(j => j.Kind == HumanoidJointKind.LeftElbow)].Translation;
+ var right = solved.GlobalTransforms[skeleton.Joints.ToList().FindIndex(j => j.Kind == HumanoidJointKind.RightElbow)].Translation;
+ Assert.InRange(Math.Abs(left.X + right.X), 0, .001);
+ Assert.InRange(Math.Abs(left.Y - right.Y), 0, .001);
+ Assert.InRange(Math.Abs(left.Z - right.Z), 0, .001);
+ }
+
+ [Fact]
+ public void AbsoluteFlexionMeasurementDoesNotFoldPastNinetyDegrees()
+ {
+ var skeleton = LegSkeleton();
+ var solved = HumanoidKinematicSolver.Solve(skeleton, new("hip120", skeleton.SkeletonId,
+ skeleton.RestPoseId, 0, [new(HumanoidJointKind.LeftHip, FlexionDegrees: 120)])).Pose!;
+ var actual = HumanoidPoseSemantics.Measure(skeleton, solved.GlobalTransforms, HumanoidJointKind.LeftHip);
+ Assert.InRange(Math.Abs(actual.FlexionDegrees - 120), 0, .001);
+ }
+
+ private static HumanoidSkeleton ArmSkeleton(double abduction)
+ {
+ var radians = abduction * Math.PI / 180;
+ var shoulder = new Vector3(-200, 0, 1400);
+ var elbow = shoulder + new Vector3((float)(-300 * Math.Sin(radians)), 0, (float)(-300 * Math.Cos(radians)));
+ var wrist = elbow + Vector3.Normalize(elbow - shoulder) * 250;
+ return Build("source-" + abduction, [(HumanoidJointKind.Root, (int?)null, Vector3.Zero),
+ (HumanoidJointKind.Pelvis, 0, new(0,0,1000)), (HumanoidJointKind.LeftClavicle, 1, new(-150,0,1400)),
+ (HumanoidJointKind.LeftShoulder, 2, shoulder), (HumanoidJointKind.LeftElbow, 3, elbow),
+ (HumanoidJointKind.LeftWrist, 4, wrist)]);
+ }
+
+ private static HumanoidSkeleton MirroredArmSkeleton() => Build("mirrored",
+ [
+ (HumanoidJointKind.Root, (int?)null, Vector3.Zero), (HumanoidJointKind.Pelvis, 0, new(0,0,1000)),
+ (HumanoidJointKind.LeftClavicle, 1, new(-150,0,1400)), (HumanoidJointKind.LeftShoulder, 2, new(-200,0,1400)),
+ (HumanoidJointKind.LeftElbow, 3, new(-200,0,1100)), (HumanoidJointKind.LeftWrist, 4, new(-200,0,850)),
+ (HumanoidJointKind.RightClavicle, 1, new(150,0,1400)), (HumanoidJointKind.RightShoulder, 6, new(200,0,1400)),
+ (HumanoidJointKind.RightElbow, 7, new(200,0,1100)), (HumanoidJointKind.RightWrist, 8, new(200,0,850))
+ ]);
+
+ private static HumanoidSkeleton LegSkeleton() => Build("leg",
+ [
+ (HumanoidJointKind.Root, (int?)null, Vector3.Zero), (HumanoidJointKind.Pelvis, 0, new(0,0,1000)),
+ (HumanoidJointKind.LeftHip, 1, new(-100,0,1000)), (HumanoidJointKind.LeftKnee, 2, new(-100,0,600)),
+ (HumanoidJointKind.LeftAnkle, 3, new(-100,0,200))
+ ]);
+
+ private static HumanoidSkeleton Build(string id, (HumanoidJointKind Kind, int? Parent, Vector3 Position)[] specs)
+ {
+ var joints = specs.Select(spec =>
+ {
+ var translation = spec.Position - (spec.Parent is int parent ? specs[parent].Position : Vector3.Zero);
+ var global = Matrix4x4.CreateTranslation(spec.Position);
+ Matrix4x4.Invert(global, out var inverse);
+ var side = spec.Kind.ToString().StartsWith("Left") ? AnatomicalSide.Left :
+ spec.Kind.ToString().StartsWith("Right") ? AnatomicalSide.Right : AnatomicalSide.Center;
+ return new HumanoidJoint("joint:" + spec.Kind, spec.Kind, side, spec.Parent,
+ HumanoidTransform.FromTranslation(new(translation.X, translation.Y, translation.Z)), global, inverse);
+ }).ToArray();
+ return new(id, id + ".rest", "row-vector LBS", joints,
+ joints.ToDictionary(joint => joint.Kind, joint => joint.Kind));
+ }
+
+ private static void AssertVectorNear(Vector3 actual, Vector3 expected, float tolerance)
+ => Assert.InRange(Vector3.Distance(actual, expected), 0, tolerance);
+
+ private static Point3D Resolve(HumanoidSurface surface, SurfaceBinding binding)
+ {
+ var face = surface.Faces.Single(item => item.Id == binding.FaceId);
+ var a = surface.Vertices[face.A].Position;
+ var b = surface.Vertices[face.B].Position;
+ var c = surface.Vertices[face.C].Position;
+ return new(a.X * binding.BarycentricA + b.X * binding.BarycentricB + c.X * binding.BarycentricC,
+ a.Y * binding.BarycentricA + b.Y * binding.BarycentricB + c.Y * binding.BarycentricC,
+ a.Z * binding.BarycentricA + b.Z * binding.BarycentricB + c.Z * binding.BarycentricC);
+ }
+}
diff --git a/Aetheris.Humanoid.Tests/HumanoidRestX2Tests.cs b/Aetheris.Humanoid.Tests/HumanoidRestX2Tests.cs
new file mode 100644
index 00000000..c9038583
--- /dev/null
+++ b/Aetheris.Humanoid.Tests/HumanoidRestX2Tests.cs
@@ -0,0 +1,54 @@
+using Aetheris.Humanoid;
+using Xunit;
+
+namespace Aetheris.Humanoid.Tests;
+
+public sealed class HumanoidRestX2Tests
+{
+ [Fact]
+ public void CanonicalCorpusRoundtripsFromIndependentSourceRest()
+ {
+ var source = CanonicalAdultTemplate.Create();
+ var normalized = HumanoidRestPoseNormalizer.Normalize(source);
+ var cases = new[]
+ {
+ new AnatomicalJointRequest(HumanoidJointKind.LeftShoulder, AbductionDegrees: 90),
+ new AnatomicalJointRequest(HumanoidJointKind.LeftElbow, 90),
+ new AnatomicalJointRequest(HumanoidJointKind.LeftHip, 70),
+ new AnatomicalJointRequest(HumanoidJointKind.LeftHip, AbductionDegrees: 45),
+ new AnatomicalJointRequest(HumanoidJointKind.LeftKnee, 90)
+ };
+ foreach (var request in cases)
+ {
+ var solved = HumanoidKinematicSolver.Solve(normalized.Skeleton,
+ new("roundtrip", normalized.Skeleton.SkeletonId, normalized.Skeleton.RestPoseId, 0, [request]));
+ Assert.NotNull(solved.Pose);
+ Assert.All(solved.Pose!.SemanticResiduals,
+ residual => Assert.InRange(residual.MaximumAbsoluteDegrees, 0, .05));
+ }
+ }
+
+ [Fact]
+ public void Height1800RetainsRestPoseMeasurementsAndAttachments()
+ {
+ var normalized = HumanoidRestPoseNormalizer.Normalize(CanonicalAdultTemplate.Create());
+ var shaped = HumanoidMorphing.Apply(normalized,
+ new Dictionary<HumanoidMorphId, double> { [HumanoidMorphId.Height] = 1800 });
+ Assert.Equal(CanonicalHumanoidRestPose.Id, shaped.Skeleton.RestPoseId);
+ Assert.Equal(normalized.Surface.ConnectivityHash, shaped.Surface.ConnectivityHash);
+ var height = HumanoidMeasurements.Evaluate(shaped).Single(x => x.Measurement == HumanoidMeasurementId.Height);
+ Assert.True(height.IsValid);
+ Assert.Equal(1800, height.ValueMm!.Value, 6);
+ var solve = HumanoidKinematicSolver.Solve(shaped.Skeleton,
+ new("height1800-shoulder90", shaped.Skeleton.SkeletonId, shaped.Skeleton.RestPoseId,
+ shaped.ShapeRevision, [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 90)]), shaped.ShapeRevision);
+ Assert.True(solve.IsSolved, string.Join("; ", solve.Diagnostics.Select(x => x.Code + ": " + x.Message)));
+ var pose = solve.Pose!;
+ Assert.InRange(pose.SemanticResiduals.Max(x => x.MaximumAbsoluteDegrees), 0, .05);
+ foreach (var site in new[] { "site:Wrist.Left", "site:UpperArm.Left", "site:Chest", "site:Waist", "site:Thigh.Left", "site:Foot.Left" })
+ {
+ var frame = HumanoidPosing.EvaluateAttachment(shaped, site, pose.PoseState);
+ Assert.True(double.IsFinite(frame.Position.X + frame.Position.Y + frame.Position.Z));
+ }
+ }
+}
diff --git a/Aetheris.Humanoid/HumanoidKinematics.cs b/Aetheris.Humanoid/HumanoidKinematics.cs
index 69c581b4..11d68726 100644
--- a/Aetheris.Humanoid/HumanoidKinematics.cs
+++ b/Aetheris.Humanoid/HumanoidKinematics.cs
@@ -11,6 +11,12 @@ public sealed record RequestedHumanoidPose(string PoseId, string SkeletonId, str
public sealed record KinematicDiagnostic(string Code, string Message, HumanoidJointKind? Joint = null);
public sealed record AnatomicalLink(string Id, HumanoidJointKind Parent, HumanoidJointKind Child, double LengthMm);
public sealed record JointConstraintResidual(HumanoidJointKind Joint, double CenterMm, double LinkLengthMm);
+public sealed record SemanticPoseResidual(HumanoidJointKind Joint,
+ double FlexionDegrees, double AbductionDegrees, double TwistDegrees)
+{
+ public double MaximumAbsoluteDegrees => Math.Max(Math.Abs(FlexionDegrees),
+ Math.Max(Math.Abs(AbductionDegrees), Math.Abs(TwistDegrees)));
+}
public sealed record JointProjection(AnatomicalJointRequest Requested, AnatomicalJointRequest Solved,
double ParameterCorrectionDegrees);
@@ -30,18 +36,22 @@ public sealed record AnatomicalBallInterface(HumanoidJointKind Joint, HumanoidJo
public sealed class SolvedHumanoidPose
{
internal SolvedHumanoidPose(HumanoidSkeleton skeleton, long revision, HumanoidPoseState state,
- Matrix4x4[] globals, AnatomicalJointRequest[] joints, JointConstraintResidual[] residuals)
+ Matrix4x4[] globals, AnatomicalJointRequest[] joints, JointConstraintResidual[] residuals,
+ SemanticPoseResidual[] semanticResiduals)
{
Skeleton = skeleton; ShapeRevision = revision; State = state;
GlobalTransforms = Array.AsReadOnly(globals); Joints = Array.AsReadOnly(joints);
Residuals = Array.AsReadOnly(residuals);
+ SemanticResiduals = Array.AsReadOnly(semanticResiduals);
}
internal HumanoidSkeleton Skeleton { get; }
internal HumanoidPoseState State { get; }
+ public HumanoidPoseState PoseState => State;
public long ShapeRevision { get; }
public IReadOnlyList<Matrix4x4> GlobalTransforms { get; }
public IReadOnlyList<AnatomicalJointRequest> Joints { get; }
public IReadOnlyList<JointConstraintResidual> Residuals { get; }
+ public IReadOnlyList<SemanticPoseResidual> SemanticResiduals { get; }
}
public sealed record HumanoidSolveResult(SolvedHumanoidPose? Pose,
IReadOnlyList<KinematicDiagnostic> Diagnostics, IReadOnlyList<JointProjection> Projections)
@@ -51,13 +61,13 @@ public sealed record HumanoidSolveResult(SolvedHumanoidPose? Pose,
/// <summary>
/// Bounded hip/shoulder ball and elbow/knee hinge interfaces. Axes are expressed in each
-/// adopted joint's source-derived rest frame. Angles are engineering coordinates relative
-/// to that rest pose, not clinical measurements or a general biomechanics model.
+/// 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 const double LinearToleranceMm = .001;
- public const string Version = "humanoid.x5.reference-frame-pose.v1";
+ public const string Version = "aetheris.humanoid.semantic-pose.v1";
public static IReadOnlyList<AnatomicalJointInterface> Interfaces(HumanoidSkeleton skeleton)
{
@@ -136,19 +146,25 @@ public static class HumanoidKinematicSolver
diagnostics.Add(new("HUM205", "Projected joint coordinates into the engineering domain.", input.Joint));
}
states.Add(solved);
+ // Legacy reduced test mechanisms may omit the distal measurement child. Their
+ // historical zero remains the only available adapter state; complete source rigs
+ // are measured geometrically and never expose this fallback publicly.
+ HumanoidPoseSemantics.TryMeasure(skeleton, skeleton.Joints.Select(j => j.GlobalBind).ToArray(),
+ input.Joint, out var native);
Quaternion rotation;
- if (joint is AnatomicalHingeInterface hinge) rotation = Rotate(hinge.Axis, solved.FlexionDegrees);
+ if (joint is AnatomicalHingeInterface hinge)
+ {
+ var restCorrection = HingeRestCorrection(skeleton, input.Joint, native.FlexionDegrees);
+ rotation = Quaternion.Concatenate(restCorrection, Rotate(hinge.Axis, solved.FlexionDegrees));
+ }
else
{
- // Exponential-map swing in the anatomical sagittal/coronal plane, followed by axial twist.
- // This is a coupled ellipse, not independent Euler limits.
+ // Solve the absolute anatomical direction directly. This deliberately does not
+ // apply equal deltas to unlike source rests.
var sign = input.Joint.ToString().StartsWith("Left") ? 1 : -1;
var ball = (AnatomicalBallInterface)joint;
- var swing = ball.FlexionAxis * (float)solved.FlexionDegrees +
- ball.AbductionAxis * (float)(sign * solved.AbductionDegrees);
- var angle = swing.Length();
- var q = angle == 0 ? Quaternion.Identity : Rotate(swing / angle, angle);
- rotation = Quaternion.Concatenate(Rotate(ball.TwistAxis, sign * solved.TwistDegrees), q);
+ var q = BallSwing(skeleton, input.Joint, solved.FlexionDegrees, solved.AbductionDegrees);
+ rotation = Quaternion.Concatenate(Rotate(ball.TwistAxis, sign * (solved.TwistDegrees - native.TwistDegrees)), q);
}
rotations.Add(new(input.Joint, rotation));
}
@@ -168,7 +184,17 @@ public static class HumanoidKinematicSolver
if (!double.IsFinite(center) || center > LinearToleranceMm) return Reject("HUM201", "Joint center residual exceeds 0.001 mm.", j.Kind);
if (!double.IsFinite(length) || length > LinearToleranceMm) return Reject("HUM202", "Link length residual exceeds 0.001 mm.", j.Kind);
}
- return new(new(skeleton, shapeRevision, state, globals, states.ToArray(), residuals.ToArray()), diagnostics.AsReadOnly(), projections.AsReadOnly());
+ var semanticResiduals = new List<SemanticPoseResidual>();
+ foreach (var target in states)
+ {
+ if (!HumanoidPoseSemantics.TryMeasure(skeleton, globals, target.Joint, out var actual))
+ continue;
+ semanticResiduals.Add(new SemanticPoseResidual(target.Joint,
+ actual.FlexionDegrees - target.FlexionDegrees,
+ actual.AbductionDegrees - target.AbductionDegrees,
+ actual.TwistDegrees - target.TwistDegrees));
+ }
+ return new(new(skeleton, shapeRevision, state, globals, states.ToArray(), residuals.ToArray(), semanticResiduals.ToArray()), diagnostics.AsReadOnly(), projections.AsReadOnly());
}
private static AnatomicalJointRequest Project(AnatomicalJointRequest input, AnatomicalJointInterface joint)
@@ -220,6 +246,51 @@ public static class HumanoidKinematicSolver
return Values(a).Zip(Values(b)).All(x => float.IsFinite(x.First) && float.IsFinite(x.Second) && Math.Abs(x.First - x.Second) <= LinearToleranceMm);
}
private static Quaternion Rotate(Vector3 axis, double degrees) => Quaternion.CreateFromAxisAngle(axis, (float)(degrees * Math.PI / 180));
+ private static Quaternion HingeRestCorrection(HumanoidSkeleton skeleton, HumanoidJointKind kind, double nativeFlexionDegrees)
+ {
+ if (nativeFlexionDegrees < 1e-6) return Quaternion.Identity;
+ var jointIndex = skeleton.Joints.ToList().FindIndex(joint => joint.Kind == kind);
+ var joint = skeleton.Joints[jointIndex];
+ if (joint.ParentIndex is not int parent) return Quaternion.Identity;
+ var childName = (kind.ToString().StartsWith("Left") ? "Left" : "Right") +
+ (kind.ToString().EndsWith("Elbow") ? "Wrist" : "Ankle");
+ var child = skeleton.Joints.ToList().FindIndex(candidate => candidate.Kind.ToString() == childName);
+ if (child < 0) return Quaternion.Identity;
+ var proximal = Vector3.Normalize(Position(joint.GlobalBind) - Position(skeleton.Joints[parent].GlobalBind));
+ var distal = Vector3.Normalize(Position(skeleton.Joints[child].GlobalBind) - Position(joint.GlobalBind));
+ var axis = Vector3.Cross(distal, proximal);
+ if (axis.LengthSquared() < 1e-10f) return Quaternion.Identity;
+ return Rotate(ToLocalAxis(joint, Vector3.Normalize(axis)), nativeFlexionDegrees);
+ }
+ private static Quaternion BallSwing(HumanoidSkeleton skeleton, HumanoidJointKind kind,
+ double flexionDegrees, double abductionDegrees)
+ {
+ var jointIndex = skeleton.Joints.ToList().FindIndex(joint => joint.Kind == kind);
+ var joint = skeleton.Joints[jointIndex];
+ var childName = (kind.ToString().StartsWith("Left") ? "Left" : "Right") +
+ (kind.ToString().EndsWith("Shoulder") ? "Elbow" : "Knee");
+ var child = skeleton.Joints.ToList().FindIndex(candidate => candidate.Kind.ToString() == childName);
+ if (child < 0)
+ {
+ var sign = kind.ToString().StartsWith("Left") ? 1f : -1f;
+ var fallback = ToLocalAxis(joint, Vector3.UnitX) * (float)flexionDegrees +
+ ToLocalAxis(joint, Vector3.UnitY) * (float)(sign * abductionDegrees);
+ var fallbackAngle = fallback.Length();
+ return fallbackAngle == 0 ? Quaternion.Identity : Rotate(fallback / fallbackAngle, fallbackAngle);
+ }
+ var source = Vector3.Normalize(Position(skeleton.Joints[child].GlobalBind) - Position(joint.GlobalBind));
+ var flexion = flexionDegrees * Math.PI / 180d;
+ var abduction = abductionDegrees * Math.PI / 180d;
+ var side = kind.ToString().StartsWith("Left") ? -1d : 1d;
+ var target = Vector3.Normalize(new((float)(side * Math.Cos(flexion) * Math.Sin(abduction)),
+ (float)Math.Sin(flexion), (float)(-Math.Cos(flexion) * Math.Cos(abduction))));
+ var dot = Math.Clamp(Vector3.Dot(source, target), -1f, 1f);
+ if (dot > 1 - 1e-7f) return Quaternion.Identity;
+ var axis = Vector3.Cross(source, target);
+ if (axis.LengthSquared() < 1e-10f)
+ axis = Math.Abs(source.X) < .9f ? Vector3.Cross(source, Vector3.UnitX) : Vector3.Cross(source, Vector3.UnitY);
+ return Rotate(ToLocalAxis(joint, Vector3.Normalize(axis)), Math.Acos(dot) * 180d / Math.PI);
+ }
private static Vector3 ToLocalAxis(HumanoidJoint joint, Vector3 canonicalAxis)
{
var local = Vector3.TransformNormal(canonicalAxis, joint.InverseBind);
diff --git a/Aetheris.Humanoid/HumanoidModel.cs b/Aetheris.Humanoid/HumanoidModel.cs
index 8f5f96d5..a1b5c996 100644
--- a/Aetheris.Humanoid/HumanoidModel.cs
+++ b/Aetheris.Humanoid/HumanoidModel.cs
@@ -9,7 +9,7 @@ public static class CanonicalAdultStandardV1
public const string TopologyId = "aetheris.humanoid.adult.standard.v1";
public const string BindingTriangulationId = "aetheris.humanoid.adult.standard.v1.binding-triangles.v1";
public const string SkeletonId = "aetheris.humanoid.adult.skeleton.v1";
- public const string RestPoseId = "aetheris.humanoid.adult.apose.v1";
+ public const string RestPoseId = CanonicalHumanoidRestPose.Id;
public const string MeasurementPoseId = "aetheris.humanoid.adult.measurement.v1";
public const string MeasurementProtocolVersion = "aetheris.humanoid.measurements.v1";
public const double NeutralHeightMm = 1750d;
diff --git a/Aetheris.Humanoid/HumanoidRuntime.cs b/Aetheris.Humanoid/HumanoidRuntime.cs
index 530747fa..2cf9a0a2 100644
--- a/Aetheris.Humanoid/HumanoidRuntime.cs
+++ b/Aetheris.Humanoid/HumanoidRuntime.cs
@@ -44,7 +44,7 @@ public static class HumanoidValidator
private static void ValidateSkeleton(HumanoidSkeleton skeleton,List<HumanoidDiagnostic> d)
{
if(skeleton.SkeletonId!=CanonicalAdultStandardV1.SkeletonId)d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Unexpected canonical skeleton identity."));
- for(var i=0;i<skeleton.Joints.Count;i++){var j=skeleton.Joints[i];if(j.ParentIndex is int p&&(p<0||p>=i))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Parent must precede child in acyclic canonical order.",j.Id));var identity=j.GlobalBind*j.InverseBind;if(!NearIdentity(identity,1e-4f))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Global bind and inverse bind do not reconstruct identity.",j.Id));}
+ for(var i=0;i<skeleton.Joints.Count;i++){var j=skeleton.Joints[i];if(j.ParentIndex is int p&&(p<0||p>=i))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Parent must precede child in acyclic canonical order.",j.Id));var identity=j.GlobalBind*j.InverseBind;if(!NearIdentity(identity,1e-3f))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Global bind and inverse bind do not reconstruct identity.",j.Id));}
foreach(var kind in Enum.GetValues<HumanoidJointKind>().Where(k=>k is not HumanoidJointKind.LeftEye and not HumanoidJointKind.RightEye and not HumanoidJointKind.Jaw))if(skeleton.Joints.All(x=>x.Kind!=kind))d.Add(Error(HumanoidDiagnosticCode.HUM010_InvalidSkeleton,"Required canonical joint is missing.",kind.ToString()));
}
private static bool NearIdentity(Matrix4x4 m,float e)=>MathF.Abs(m.M11-1)<e&&MathF.Abs(m.M22-1)<e&&MathF.Abs(m.M33-1)<e&&MathF.Abs(m.M44-1)<e&&MathF.Abs(m.M12)<e&&MathF.Abs(m.M13)<e&&MathF.Abs(m.M14)<e&&MathF.Abs(m.M21)<e&&MathF.Abs(m.M23)<e&&MathF.Abs(m.M24)<e&&MathF.Abs(m.M31)<e&&MathF.Abs(m.M32)<e&&MathF.Abs(m.M34)<e&&MathF.Abs(m.M41)<e&&MathF.Abs(m.M42)<e&&MathF.Abs(m.M43)<e;
@@ -125,11 +125,12 @@ public static class HumanoidMorphing
if(values.TryGetValue(HumanoidMorphId.ArmLength,out var arm)&&arm!=0&&region is not null&&region.ToString()!.ContainsAny("Shoulder","UpperArm","Elbow","Forearm","Wrist","Hand","Thumb","Index","Middle","Ring","Little")){var side=Math.Sign(p.X);var shoulderPoint=new Point3D(side*185,0,1345);var v=q-shoulderPoint;var baseLength=500d;q=shoulderPoint+v*((baseLength+arm)/baseLength);}
return q;
}
- var vertices=h.Surface.Vertices.Select(v=>v with{Position=Map(v.Position,v.Region)}).ToArray();var oldJoints=h.Skeleton.Joints;var globals=oldJoints.Select(j=>Map(new(j.GlobalBind.M41,j.GlobalBind.M42,j.GlobalBind.M43),RegionForJoint(j.Kind))).ToArray();var joints=new HumanoidJoint[oldJoints.Count];for(var i=0;i<joints.Length;i++){var old=oldJoints[i];var parent=old.ParentIndex is int pi?globals[pi]:Point3D.Origin;var local=globals[i]-parent;var global=Matrix4x4.CreateTranslation((float)globals[i].X,(float)globals[i].Y,(float)globals[i].Z);Matrix4x4.Invert(global,out var inv);joints[i]=old with{LocalRest=new(new(local.X,local.Y,local.Z),Quaternion.Identity),GlobalBind=global,InverseBind=inv};}
- var skeleton=h.Skeleton with{Joints=joints};var surface=h.Surface with{Vertices=vertices};var frame=values.TryGetValue(HumanoidMorphId.Height,out var requestedHeight)?h.Frame with{NormalizedHeightMm=requestedHeight}:h.Frame;var updated=h with{Frame=frame,Surface=surface,Skeleton=skeleton,ShapeRevision=h.ShapeRevision+1,PoseState=new(CanonicalAdultStandardV1.RestPoseId,[],HumanoidTransform.Identity)};return updated with{Attachments=updated.Attachments.Select(site=>site with{NeutralFrame=site.NeutralFrame with{Position=CanonicalAdultTemplate.Resolve(surface,site.PositionBinding)}}).ToArray()};
+ var vertices=h.Surface.Vertices.Select(v=>v with{Position=Map(v.Position,v.Region)}).ToArray();var oldJoints=h.Skeleton.Joints;var globals=oldJoints.Select(j=>{var p=Map(new(j.GlobalBind.M41,j.GlobalBind.M42,j.GlobalBind.M43),RegionForJoint(j.Kind));if(!Matrix4x4.Decompose(j.GlobalBind,out _,out var orientation,out _))throw new InvalidDataException("Morphed joint frame is not rigid: "+j.Kind);var m=Matrix4x4.CreateFromQuaternion(Quaternion.Normalize(orientation));m.Translation=new((float)p.X,(float)p.Y,(float)p.Z);return m;}).ToArray();var joints=new HumanoidJoint[oldJoints.Count];for(var i=0;i<joints.Length;i++){var old=oldJoints[i];var global=globals[i];var local=old.ParentIndex is int pi?global*Inverse(globals[pi]):global;if(!Matrix4x4.Decompose(local,out var scale,out var rotation,out var translation)||Vector3.Distance(scale,Vector3.One)>1e-4f||!Matrix4x4.Invert(global,out var inv))throw new InvalidDataException("Morphed joint frame is not rigid: "+old.Kind);joints[i]=old with{LocalRest=new(new(translation.X,translation.Y,translation.Z),Quaternion.Normalize(rotation)),GlobalBind=global,InverseBind=inv};}
+ var skeleton=h.Skeleton with{Joints=joints};var surface=h.Surface with{Vertices=vertices};var frame=values.TryGetValue(HumanoidMorphId.Height,out var requestedHeight)?h.Frame with{NormalizedHeightMm=requestedHeight}:h.Frame;var updated=h with{Frame=frame,Surface=surface,Skeleton=skeleton,ShapeRevision=h.ShapeRevision+1,PoseState=new(h.Skeleton.RestPoseId,[],HumanoidTransform.Identity)};return updated with{Attachments=updated.Attachments.Select(site=>site with{NeutralFrame=site.NeutralFrame with{Position=CanonicalAdultTemplate.Resolve(surface,site.PositionBinding)}}).ToArray()};
}
private static HumanoidRegionKind? RegionForJoint(HumanoidJointKind k){var s=k.ToString();if(s.Contains("Shoulder"))return s.StartsWith("Left")?HumanoidRegionKind.LeftShoulder:HumanoidRegionKind.RightShoulder;if(s.Contains("Elbow"))return s.StartsWith("Left")?HumanoidRegionKind.LeftElbow:HumanoidRegionKind.RightElbow;if(s.Contains("Wrist")||s.Contains("Thumb")||s.Contains("Index")||s.Contains("Middle")||s.Contains("Ring")||s.Contains("Little"))return s.StartsWith("Left")?HumanoidRegionKind.LeftHand:HumanoidRegionKind.RightHand;if(s.Contains("Hip"))return s.StartsWith("Left")?HumanoidRegionKind.LeftThigh:HumanoidRegionKind.RightThigh;if(s.Contains("Knee"))return s.StartsWith("Left")?HumanoidRegionKind.LeftKnee:HumanoidRegionKind.RightKnee;if(s.Contains("Ankle")||s.Contains("Toe"))return s.StartsWith("Left")?HumanoidRegionKind.LeftFoot:HumanoidRegionKind.RightFoot;return null;}
private static bool ContainsAny(this string value,params string[] tokens)=>tokens.Any(value.Contains);
+ private static Matrix4x4 Inverse(Matrix4x4 matrix)=>Matrix4x4.Invert(matrix,out var inverse)?inverse:throw new InvalidDataException("Singular morphed parent frame.");
}
public sealed class HumanoidDomainException(HumanoidDiagnostic diagnostic):InvalidOperationException(diagnostic.Message){public HumanoidDiagnostic Diagnostic{get;}=diagnostic;}
diff --git a/Aetheris.Humanoid/HumanoidSemanticPose.cs b/Aetheris.Humanoid/HumanoidSemanticPose.cs
new file mode 100644
index 00000000..543fe87e
--- /dev/null
+++ b/Aetheris.Humanoid/HumanoidSemanticPose.cs
@@ -0,0 +1,196 @@
+using System.Numerics;
+using System.Security.Cryptography;
+using System.Text;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Humanoid;
+
+/// <summary>Frozen X1 neutral. Angles are anatomical states, never source-bone deltas.</summary>
+public static class CanonicalHumanoidRestPose
+{
+ public const string Id = "aetheris.humanoid.rest.apose.v1";
+ public const string SemanticFrameId = "aetheris.humanoid.anatomical-frame.v1";
+ public const string DeformationPolicyId = "aetheris.humanoid.lbs.v1";
+ public const double ShoulderAbductionDegrees = 35d;
+ public const double ShoulderFlexionDegrees = 0d;
+ public const double ShoulderTwistDegrees = 0d;
+ public const double ElbowFlexionDegrees = 0d;
+ public const double HipFlexionDegrees = 0d;
+ public const double HipAbductionDegrees = 0d;
+ public const double HipTwistDegrees = 0d;
+ public const double KneeFlexionDegrees = 0d;
+ public const string PalmOrientation = "source-neutral palm frame preserved; wrist rotation is 0 degrees in the canonical frame";
+ public const string FootOrientation = "feet parallel to canonical forward with soles grounded";
+
+ public static IReadOnlyList<AnatomicalJointRequest> Requests =>
+ [
+ new(HumanoidJointKind.LeftShoulder, ShoulderFlexionDegrees, ShoulderAbductionDegrees, ShoulderTwistDegrees),
+ new(HumanoidJointKind.RightShoulder, ShoulderFlexionDegrees, ShoulderAbductionDegrees, ShoulderTwistDegrees),
+ new(HumanoidJointKind.LeftElbow, ElbowFlexionDegrees), new(HumanoidJointKind.RightElbow, ElbowFlexionDegrees),
+ new(HumanoidJointKind.LeftHip, HipFlexionDegrees, HipAbductionDegrees, HipTwistDegrees),
+ new(HumanoidJointKind.RightHip, HipFlexionDegrees, HipAbductionDegrees, HipTwistDegrees),
+ new(HumanoidJointKind.LeftKnee, KneeFlexionDegrees), new(HumanoidJointKind.RightKnee, KneeFlexionDegrees)
+ ];
+}
+
+public sealed record AnatomicalJointState(HumanoidJointKind Joint, double FlexionDegrees,
+ double AbductionDegrees, double TwistDegrees);
+
+/// <summary>Measures canonical anatomical state from joint centers in +X right, +Y forward, +Z up.</summary>
+public static class HumanoidPoseSemantics
+{
+ public static bool TryMeasure(HumanoidSkeleton skeleton, IReadOnlyList<Matrix4x4> globals,
+ HumanoidJointKind kind, out AnatomicalJointState state)
+ {
+ try { state = Measure(skeleton, globals, kind); return true; }
+ catch (InvalidDataException) { state = new(kind, 0, 0, 0); return false; }
+ }
+
+ public static AnatomicalJointState Measure(HumanoidSkeleton skeleton,
+ IReadOnlyList<Matrix4x4> globals, HumanoidJointKind kind)
+ {
+ var index = skeleton.Joints.ToList().FindIndex(joint => joint.Kind == kind);
+ if (index < 0 || globals.Count != skeleton.Joints.Count)
+ throw new InvalidDataException("HUM210: Semantic pose measurement requires the complete skeleton.");
+ var joint = skeleton.Joints[index];
+ if (kind.ToString().EndsWith("Shoulder") || kind.ToString().EndsWith("Hip"))
+ {
+ var childKind = Child(kind, kind.ToString().EndsWith("Shoulder") ? "Elbow" : "Knee");
+ var direction = Vector3.Normalize(Position(globals[Index(skeleton, childKind)]) - Position(globals[index]));
+ var outward = (joint.Side == AnatomicalSide.Left ? -1f : 1f) * direction.X;
+ double flexion, abduction;
+ var coronalLength = Math.Sqrt(outward * outward + direction.Z * direction.Z);
+ if (coronalLength < 1e-5)
+ {
+ flexion = direction.Y >= 0 ? 90 : -90;
+ abduction = 0; // abduction is singular at exactly 90 degrees flexion
+ }
+ else
+ {
+ var firstFlexion = Degrees(Math.Asin(Math.Clamp(direction.Y, -1f, 1f)));
+ var firstAbduction = Degrees(Math.Atan2(outward, -direction.Z));
+ var secondFlexion = direction.Y >= 0 ? 180 - firstFlexion : -180 - firstFlexion;
+ var secondAbduction = NormalizeDegrees(firstAbduction + 180);
+ var shoulder = kind.ToString().EndsWith("Shoulder");
+ var firstValid = firstFlexion >= (shoulder ? -30 : -20) && firstFlexion <= 120 &&
+ firstAbduction >= (shoulder ? -30 : -25) && firstAbduction <= (shoulder ? 120 : 45);
+ (flexion, abduction) = firstValid
+ ? (firstFlexion, firstAbduction)
+ : (secondFlexion, secondAbduction);
+ }
+ return new(kind, Clean(flexion), Clean(abduction), 0);
+ }
+ if (kind.ToString().EndsWith("Elbow") || kind.ToString().EndsWith("Knee"))
+ {
+ if (joint.ParentIndex is not int parent) throw new InvalidDataException("HUM210: Hinge has no parent.");
+ var childKind = Child(kind, kind.ToString().EndsWith("Elbow") ? "Wrist" : "Ankle");
+ var proximal = Vector3.Normalize(Position(globals[index]) - Position(globals[parent]));
+ var distal = Vector3.Normalize(Position(globals[Index(skeleton, childKind)]) - Position(globals[index]));
+ var flexion = Degrees(Math.Acos(Math.Clamp(Vector3.Dot(proximal, distal), -1f, 1f)));
+ return new(kind, Clean(flexion), 0, 0);
+ }
+ throw new InvalidDataException("HUM209: Joint has no qualified semantic pose coordinates: " + kind);
+ }
+
+ private static int Index(HumanoidSkeleton skeleton, HumanoidJointKind kind)
+ {
+ var result = skeleton.Joints.ToList().FindIndex(joint => joint.Kind == kind);
+ return result >= 0 ? result : throw new InvalidDataException("HUM210: Missing semantic child " + kind);
+ }
+ private static HumanoidJointKind Child(HumanoidJointKind kind, string childStem)
+ => Enum.Parse<HumanoidJointKind>((kind.ToString().StartsWith("Left") ? "Left" : "Right") + childStem);
+ private static Vector3 Position(Matrix4x4 matrix) => new(matrix.M41, matrix.M42, matrix.M43);
+ private static double Degrees(double radians) => radians * 180d / Math.PI;
+ private static double NormalizeDegrees(double value)
+ {
+ while (value > 180) value -= 360;
+ while (value <= -180) value += 360;
+ return value;
+ }
+ private static double Clean(double value) => Math.Abs(value) < 1e-6 ? 0 : value;
+}
+
+public sealed record HumanoidRestNormalization(
+ HumanoidSurface Surface,
+ HumanoidSkeleton Skeleton,
+ string SourceRestPoseId,
+ string RestPoseId,
+ IReadOnlyList<AnatomicalJointState> SourceNeutral,
+ IReadOnlyList<SemanticPoseResidual> Residuals,
+ double MaximumBindReconstructionMm,
+ HumanoidPoseState AppliedSourcePose);
+
+/// <summary>Reposes a skinned source rest into the frozen A-pose and rebuilds all bind data.</summary>
+public static class HumanoidRestPoseNormalizer
+{
+ public static CanonicalHumanoid Normalize(CanonicalHumanoid source)
+ {
+ var normalized = Normalize(source.Surface, source.Skeleton);
+ var attachments = source.Attachments.Select(site => site with
+ {
+ NeutralFrame = HumanoidPosing.EvaluateAttachment(source, site.Id, normalized.AppliedSourcePose)
+ }).ToArray();
+ static string MatrixText(Matrix4x4 m) => FormattableString.Invariant(
+ $"{m.M11:R},{m.M12:R},{m.M13:R},{m.M14:R},{m.M21:R},{m.M22:R},{m.M23:R},{m.M24:R},{m.M31:R},{m.M32:R},{m.M33:R},{m.M34:R},{m.M41:R},{m.M42:R},{m.M43:R},{m.M44:R}");
+ var outputHash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n",
+ normalized.Surface.Vertices.Select(vertex => FormattableString.Invariant(
+ $"{vertex.Id}:{vertex.Position.X:R},{vertex.Position.Y:R},{vertex.Position.Z:R}"))
+ .Concat(normalized.Skeleton.Joints.Select(joint => $"{joint.Id}:{MatrixText(joint.GlobalBind)}"))))));
+ return source with
+ {
+ Surface = normalized.Surface,
+ Skeleton = normalized.Skeleton,
+ Attachments = attachments,
+ PoseState = new(CanonicalHumanoidRestPose.Id, [], HumanoidTransform.Identity),
+ Provenance = source.Provenance with
+ {
+ Transformations = source.Provenance.Transformations.Concat(
+ [$"semantic rest normalization {source.Skeleton.RestPoseId} -> {CanonicalHumanoidRestPose.Id}"]).ToArray(),
+ GeneratorVersion = source.Provenance.GeneratorVersion + "+rest-x1",
+ OutputHash = outputHash
+ }
+ };
+ }
+
+ public static HumanoidRestNormalization Normalize(HumanoidSurface surface, HumanoidSkeleton source)
+ {
+ var sourceNeutral = CanonicalHumanoidRestPose.Requests
+ .Select(request => HumanoidPoseSemantics.Measure(source, source.Joints.Select(j => j.GlobalBind).ToArray(), request.Joint))
+ .ToArray();
+ var solve = HumanoidKinematicSolver.Solve(source,
+ new("canonical-apose-normalization", source.SkeletonId, source.RestPoseId, 0, CanonicalHumanoidRestPose.Requests));
+ if (!solve.IsSolved) throw new InvalidDataException("HUM211: A-pose normalization failed: " +
+ string.Join("; ", solve.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ var pose = solve.Pose!;
+ var positions = HumanoidPosing.EvaluateVertices(surface, source, pose.State);
+ var vertices = surface.Vertices.Select((vertex, index) => vertex with { Position = positions[index] }).ToArray();
+ var normalizedSurface = surface with { Vertices = vertices };
+ var joints = new HumanoidJoint[source.Joints.Count];
+ for (var i = 0; i < joints.Length; i++)
+ {
+ var old = source.Joints[i];
+ var global = pose.GlobalTransforms[i];
+ var local = old.ParentIndex is int parent ? global * Inverse(pose.GlobalTransforms[parent]) : global;
+ if (!Matrix4x4.Decompose(local, out var scale, out var rotation, out var translation) ||
+ Vector3.Distance(scale, Vector3.One) > 1e-4f || !Matrix4x4.Invert(global, out var inverse))
+ throw new InvalidDataException("HUM211: Normalized bind is not rigid for " + old.Kind);
+ joints[i] = old with
+ {
+ LocalRest = new(new(translation.X, translation.Y, translation.Z), Quaternion.Normalize(rotation)),
+ GlobalBind = global,
+ InverseBind = inverse
+ };
+ }
+ var skeleton = source with { RestPoseId = CanonicalHumanoidRestPose.Id, Joints = joints };
+ var reconstructed = HumanoidPosing.EvaluateVertices(normalizedSurface, skeleton,
+ new(CanonicalHumanoidRestPose.Id, [], HumanoidTransform.Identity));
+ var bindError = reconstructed.Select((point, index) => (point - vertices[index].Position).Length).DefaultIfEmpty().Max();
+ if (bindError > HumanoidKinematicSolver.LinearToleranceMm)
+ throw new InvalidDataException($"HUM211: Normalized bind reconstruction residual {bindError:R} mm exceeds tolerance.");
+ return new(normalizedSurface, skeleton, source.RestPoseId, CanonicalHumanoidRestPose.Id,
+ sourceNeutral, pose.SemanticResiduals, bindError, pose.State);
+ }
+
+ private static Matrix4x4 Inverse(Matrix4x4 matrix) => Matrix4x4.Invert(matrix, out var inverse)
+ ? inverse : throw new InvalidDataException("HUM211: Singular normalized parent bind.");
+}
diff --git a/docs/public/humanoid-kinematics.md b/docs/public/humanoid-kinematics.md
index 160ca2e8..adaf356c 100644
--- a/docs/public/humanoid-kinematics.md
+++ b/docs/public/humanoid-kinematics.md
@@ -1,4 +1,8 @@
-# Humanoid X2 constrained kinematics research
+# Humanoid X2 constrained kinematics research (historical)
+
+> REST-X1 supersedes the relative-to-rest angle convention described below.
+> Current `RequestedHumanoidPose` values are absolute anatomical states. See
+> [Semantic humanoid pose normalization](humanoid-pose-normalization.md).
**Status: Meaningful progression, not an accepted humanoid.** Antonia remains
the X1 adoption candidate. The new solve admits hip, elbow and knee requests;
@@ -74,13 +78,12 @@ new Firmament `Concept<T>` or `Interface<T>` compiler family.
| Elbow | Flexion 0..145° | Hinge axis from rest forearm × forward; abduction and twist zero |
| Knee | Flexion 0..140° | Hinge axis opposite rest lower leg × forward; abduction and twist zero |
-Hip uses an exponential-map swing vector `(flexion, side*abduction, 0)` and
-axial rotation around −Z. This is an engineering approximation in the supplied
-translation-only anatomical rest frame, not a clinically calibrated femoral
-coordinate system. Positive hip flexion moves the leg forward; positive knee
-flexion moves the lower leg backward. The elbow axis is rebuilt from rest
-geometry. The X1 sweep used +X at the knee (opposite the X2 knee direction), and
-+Y at the elbow (abduction rather than a forearm flexion hinge).
+The original X2 implementation used an exponential-map delta from the supplied
+rest. REST-X1 replaced that behavior with a direct solve from absolute flexion
+and abduction to the canonical bone direction. Positive hip flexion moves the
+leg forward; positive knee flexion moves the lower leg backward. Source elbow
+and knee bends are removed in their measured source plane before canonical
+flexion is applied.
These bounds are explicit engineering assumptions. The
[CDC reference study](https://archive.cdc.gov/www_cdc_gov/ncbddd/jointrom/index.html)
@@ -96,12 +99,10 @@ hierarchy, side consistency and current revision are checked before skinning.
Input order is canonicalized by joint kind. Unsupported joints remain at rest
when omitted; explicitly requesting one returns `HUM209`, even at zero.
-The current shoulder is deliberately **unsupported**. There is no qualified
-clavicle/scapular coupling. A request for `LeftShoulder` abduction 90° returns
-`HUM209` with no solved pose; it does not silently use a ball joint. Wrist,
-ankle, neck, spine and finger requests are also unsupported. Collision,
-self-contact, scapular frames and full anatomical pose-concept validation
-remain unimplemented.
+Shoulder ball coordinates are now admitted for bounded REST-X1 comparison.
+They do not model clavicle/scapular coupling. Wrist, ankle, neck, spine and
+finger requests remain unsupported. Collision, self-contact, scapular motion,
+and a complete clinical biomechanics model remain unimplemented.
## Surface screening and migration boundary
diff --git a/docs/public/humanoid-pose-normalization.md b/docs/public/humanoid-pose-normalization.md
new file mode 100644
index 00000000..2538c06e
--- /dev/null
+++ b/docs/public/humanoid-pose-normalization.md
@@ -0,0 +1,134 @@
+# Semantic humanoid pose normalization
+
+Aetheris exposes pose as an anatomical state, not as a source-rig rotation
+delta. `Shoulder.Abduction = 90°` therefore means a 90° canonical shoulder
+state whether the imported rig starts in a T-pose, A-pose, or another reviewed
+rest configuration.
+
+## Frozen canonical convention
+
+`aetheris.humanoid.anatomical-frame.v1` is right-handed millimetres:
+
+- +X is anatomical right, independent of camera view.
+- +Y is forward.
+- +Z is up.
+- flexion/extension is measured toward/away from +Y;
+- abduction/adduction is measured away from/toward the sagittal plane;
+- left and right use anatomical side, not screen side.
+
+The canonical rest is `aetheris.humanoid.rest.apose.v1`: shoulder abduction
+35°, shoulder flexion/twist 0°, elbow flexion 0°, hip flexion/abduction/twist
+0°, and knee flexion 0°. Wrists are neutral and retain the reviewed source
+palm frame during the bounded upper-limb repose. Feet are parallel to forward
+and grounded. The current deformation policy identity is
+`aetheris.humanoid.lbs.v1`; it is distinct from topology, skeleton, and rest
+identity.
+
+## API
+
+```csharp
+var request = new RequestedHumanoidPose(
+ "left-shoulder-90",
+ skeleton.SkeletonId,
+ skeleton.RestPoseId,
+ ShapeRevision: 0,
+ [new AnatomicalJointRequest(
+ HumanoidJointKind.LeftShoulder,
+ AbductionDegrees: 90)]);
+
+var result = HumanoidKinematicSolver.Solve(skeleton, request);
+if (result.Pose is { } pose)
+{
+ var actual = HumanoidPoseSemantics.Measure(
+ skeleton, pose.GlobalTransforms, HumanoidJointKind.LeftShoulder);
+ var residual = pose.SemanticResiduals.Single();
+ // Local rotations remain adapter output. Do not author against them.
+}
+```
+
+`HumanoidPoseSemantics.Measure` derives shoulder/hip state from the canonical
+joint-to-child direction and elbow/knee flexion from adjacent link directions.
+The solver constructs a source-local rotation that reaches the requested
+canonical direction. Source rest quaternions, Blender Euler axes, and native
+bone names never enter the request.
+
+`HumanoidRestPoseNormalizer.Normalize(surface, skeleton)` drives all qualified
+major joints to the frozen neutral state, deforms the surface once, rebuilds
+parent-relative local rests, global binds, and inverse binds, and verifies
+neutral reconstruction within 0.001 mm. Connectivity, vertex/face order,
+stable IDs, and topology identity are retained. The `CanonicalHumanoid`
+overload also materializes attachment neutral frames in the new rest.
+
+## Qualified boundary
+
+REST-X1 directly proves that a T-pose source and a 35° A-pose source use
+different local rotations to reach the same 90° canonical shoulder state.
+The checked Antonia adapter measures its native shoulder at 86.66° and reaches
+the 35° canonical rest deterministically. Hip, shoulder, elbow, and knee
+benchmark residuals are below 0.05° in the current evidence.
+
+This is an engineering pose vocabulary, not a medical claim. Twist is bounded
+but has not yet received the same cross-source orientation qualification.
+Clavicle/scapular motion, wrist pronation/supination, collision, and
+self-contact remain unsupported. Mixamo and Genesis adapters are local
+benchmark work, not canonical runtime dependencies.
+
+## Normalized local benchmark
+
+`scripts/humanoid-rest-x2.py` applies the same absolute anatomical requests to
+the open Aetheris/Blender path and an optional local Mixamo FBX. Source names
+only seed the role map; expected parent chains verify shoulder-elbow-wrist and
+hip-knee-ankle roles. The adapter records source rest matrices, joint centers,
+major axes, handedness, scale, requested state, measured state, and roundtrip
+residual. If `--mixamo` is omitted, the open qualification succeeds with an
+explicit skipped-column diagnostic.
+
+Genesis 9 is evaluated only through the installed local DAZ runtime by
+`scripts/benchmark-genesis9-local.dsa`. Native controls are searched against
+measured canonical-space joint directions; slider values are never treated as
+anatomical angles. Normal DAZ helpers and pose correctives remain enabled.
+Raw FBX/DAZ geometry, weights, morphs, textures, and JCM payloads remain under
+ignored `artifacts/local/` and are never embedded in the open `.blend` or
+portable weight artifact.
+
+From the repository root:
+
+```powershell
+& 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe' `
+ --background --factory-startup --disable-autoexec --python-exit-code 1 `
+ --python scripts/humanoid-rest-x2.py -- `
+ --mixamo $env:AETHERIS_MIXAMO_FBX
+
+dotnet run --project tools/Aetheris.Humanoid.X0 -- qualify-rest-x2 `
+ --input artifacts/local/humanoid-x1/antonia-adoption-candidate.json `
+ --rig fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json `
+ --source-weights artifacts/local/humanoid-rerig-x1/golden-weights.json `
+ --weights artifacts/local/humanoid-rest-x2/selected-weights.json `
+ --blender-dir artifacts/local/humanoid-rest-x2
+```
+
+The source-rest weight argument deterministically recreates the REST-X1
+canonical A-pose geometry before importing weights generated in that A-pose.
+This preserves the explicit distinction between source rest, canonical rest,
+measurement pose, and current pose.
+
+## Reproduce the Antonia evidence
+
+```powershell
+dotnet run --project tools/Aetheris.Humanoid.X0 -c Release -- `
+ normalize-rest-antonia `
+ --input artifacts/local/humanoid-x1/antonia-adoption-candidate.json `
+ --rig fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json `
+ --weights artifacts/local/humanoid-rerig-x1/golden-weights.json `
+ --out-dir artifacts/local/humanoid-rest-x1
+
+& 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe' `
+ --background --factory-startup --disable-autoexec --python-exit-code 1 `
+ --python scripts/render-humanoid-rest-x1.py -- `
+ --out-dir artifacts/local/humanoid-rest-x1
+```
+
+Generated research output remains under ignored `artifacts/local/`.
+Pose files retain `.screened` only when the existing surface screen passes;
+for example shoulder 90° passes, while elbow 90° is intentionally emitted as
+`.failed-diagnostic`. A semantic solve can be exact even when deformation fails.
diff --git a/docs/public/humanoid-reference-rig.md b/docs/public/humanoid-reference-rig.md
index e03a19d4..aea648a1 100644
--- a/docs/public/humanoid-reference-rig.md
+++ b/docs/public/humanoid-reference-rig.md
@@ -41,6 +41,11 @@ The Blender column-vector matrix is transposed during extraction. Local transfor
`RequestedHumanoidPose` addresses canonical joint kinds. Hip and shoulder use bounded ball interfaces; knee and elbow use bounded hinge interfaces. Their axes are converted into each adopted source-derived local rest frame. The X2 constraint architecture and X3 Judgment candidate architecture remain in place.
+REST-X1 now treats those request values as absolute anatomical states. The
+adapter measures the source rest from canonical joint centers, solves the
+requested canonical bone direction, and keeps the resulting source-local
+rotation private. See [Semantic humanoid pose normalization](humanoid-pose-normalization.md).
+
The X5 frame baseline is qualified, but the entire Antonia surface is not yet an accepted production humanoid. Existing X1-generated weights were deliberately retained to isolate the effect of corrected frames. Neutral, hip 30°, hip abduction 15°/30°, and shoulder 30° pass the mechanical screen; larger poses expose downstream weight/deformation failures. Landmarks, attachments, measurements, and morph channels were never migrated into the Antonia research candidate, so there is nothing valid to recompute yet. Shape-aware propagation remains a later bounded task.
Reproduce locally:
diff --git a/docs/release/HUMANOID-RERIG-X1.md b/docs/release/HUMANOID-RERIG-X1.md
index b753560d..bcc9832f 100644
--- a/docs/release/HUMANOID-RERIG-X1.md
+++ b/docs/release/HUMANOID-RERIG-X1.md
@@ -48,7 +48,7 @@ Manual paint strokes: **0**. Manual per-vertex assignments: **0**. Artistic scul
## Visual qualification
-The local `comparison.html` contains X5 / X0 automatic / X1 cleaned / Mixamo, plus Genesis 9 where available. X5, X0, X1 and Mixamo use the same orthographic camera. Front/side/rear closeups accompany the difficult X1 poses. Overview silhouette alone is insufficient to qualify the groin or hinge crease.
+**PRE-NORMALIZATION / NONCOMPARABLE.** The local `comparison.html` contains X5 / X0 automatic / X1 cleaned / Mixamo, plus Genesis 9 where available. Its source-local pose deltas are retained as historical evidence only and must not be used for cross-rig acceptance. Front/side/rear closeups accompany the difficult X1 poses. Overview silhouette alone is insufficient to qualify the groin or hinge crease.
[Open the local comparison gallery](../../artifacts/local/humanoid-rerig-x1/comparison.html). These links resolve after generating the ignored local evidence; reference images are not distributed with this report.
diff --git a/docs/release/HUMANOID-REST-X1.md b/docs/release/HUMANOID-REST-X1.md
new file mode 100644
index 00000000..1bb08d50
--- /dev/null
+++ b/docs/release/HUMANOID-REST-X1.md
@@ -0,0 +1,201 @@
+# HUMANOID-REST-X1 — canonical A-pose and semantic pose normalization
+
+**Verdict: Meaningful progression.**
+
+Aetheris now has an explicit, versioned 35° canonical A-pose; an absolute
+anatomical pose API; deterministic Antonia T-ish→A-pose surface repose and
+rebind; measured semantic residuals; and a normalized Aetheris benchmark
+gallery. The central representation defect is fixed: `Shoulder.Abduction=90°`
+no longer means “add 90° to whatever bind pose arrived.”
+
+The milestone is not Accepted because Mixamo and Genesis adapters have not yet
+been rerun through this semantic authority, the five-column comparison gallery
+is therefore incomplete, and Blender weights have not yet been regenerated
+from the canonical A-pose. The current Antonia candidate also has no admitted
+morph or attachment channels to migrate. These are concrete downstream gaps,
+not ambiguity in canonical pose meaning.
+
+## Canonical A-pose
+
+| Identity/state | Frozen value |
+|---|---|
+| topology | `aetheris.humanoid.antonia.adoption-candidate.v1` |
+| skeleton | `aetheris.humanoid.antonia.reference-rig.v1` |
+| source rest | `antonia.charmorph-metarig.rest.v1` |
+| canonical rest | `aetheris.humanoid.rest.apose.v1` |
+| semantic frame | `aetheris.humanoid.anatomical-frame.v1` |
+| deformation policy | `aetheris.humanoid.lbs.v1` |
+| shoulder | abduction 35°, flexion 0°, twist 0° |
+| elbow | flexion 0° |
+| hip | flexion 0°, abduction 0°, twist 0° |
+| knee | flexion 0° |
+| palms/wrists | source-neutral palm frame preserved; wrist 0° |
+| feet | parallel to forward, grounded |
+
+The rest-position SHA-256 is
+`3a924e6180e5f92500adfa8862c887f1d6c7a41e5c6c94f2655c823eb4b3981a`.
+The generated OBJ SHA-256 is
+`206fda6f9111a96ad845b57c855b722b2f1be36dedb77059410ea53593b5b0e9`.
+
+![Old source-native rest](../../artifacts/local/humanoid-rest-x1/source-native-rest.png)
+
+![Canonical A-pose](../../artifacts/local/humanoid-rest-x1/canonical-apose.png)
+
+![Canonical joint centers and axes](../../artifacts/local/humanoid-rest-x1/canonical-apose-skeleton-overlay.png)
+
+## Deterministic repose, rebind, and identity
+
+The Antonia source rest measured shoulder abduction **86.66°**, shoulder
+flexion **3.37°**, elbow flexion **33.97°**, hip flexion **3.35°**, hip
+abduction **7.10°**, and knee flexion **3.86°**. Those are adapter inputs, not
+public zeroes. `HumanoidRestPoseNormalizer` drives the semantic neutral,
+deforms the surface once, and rebuilds local rests, global binds, and inverse
+binds from the solved frames.
+
+- vertices: 27,193 → 27,193;
+- faces: 54,224 → 54,224;
+- connectivity hash unchanged:
+ `2e2f787499ba2da1f02bab14f352b86070938fbb5d7cae60e8bd7d59edb2b7a2`;
+- ordered triangle connectivity unchanged;
+- neutral bind reconstruction maximum: **0.000715 mm**;
+- normalization semantic residual maximum: **0.0198°** (right elbow; all
+ other qualified neutral residuals round below 0.01°).
+
+The generic canonical-humanoid overload rematerializes attachment rest frames.
+Tests exercise Height, ArmLength, LegLength, and ShoulderWidth after
+normalization while preserving connectivity and valid binds. The Antonia
+research artifact itself has no admitted morphs or attachments, so this is API
+proof rather than a claim about missing Antonia channels. Measurement pose
+remains the separate `aetheris.humanoid.adult.measurement.v1` identity.
+
+## Absolute semantics and adapter independence
+
+Old behavior:
+
+```text
+source local rotation = request
+```
+
+REST-X1 behavior:
+
+```text
+absolute anatomical target
+ -> canonical target link direction
+ -> source-rest-specific local transform
+ -> measured canonical state and residual
+```
+
+A regression fixture maps both a 90° T-pose source and a 35° A-pose source to
+the same 90° shoulder state. The T-pose adapter emits identity while the
+A-pose adapter emits a nonidentity local transform; their canonical elbow
+centers coincide within 0.001 mm. Mirrored left/right requests also produce
+mirrored joint centers without camera-side sign leakage.
+
+## Normalized Antonia benchmark
+
+Tolerance is 0.05°. Every requested state is below it.
+
+| Pose | Maximum semantic residual | Existing surface screen | Max edge ratio / reversal proxies |
+|---|---:|---|---:|
+| neutral A-pose | 0° | pass | 1.0004 / 0 |
+| shoulder 60° | 0.000019° | pass | 1.7453 / 0 |
+| shoulder 90° | 0.000007° | pass | 2.5729 / 0 |
+| shoulder 120° | 0.000019° | fail | 4.3907 / 0 |
+| elbow 90° at shoulder 35° | 0.000034° | fail | 6.4165 / 10 |
+| hip flexion 70° | 0.000011° | fail | 8.8707 / 2 |
+| hip flexion 90° | 0° | fail | 11.0816 / 67 |
+| hip abduction 45° | 0.000009° | pass | 2.4564 / 0 |
+| knee flexion 90° | 0.000038° | fail | 5.6868 / 27 |
+| combined pose | 0.000035° | fail | 6.4161 / 10 |
+
+![Normalized shoulder 90°](../../artifacts/local/humanoid-rest-x1/shoulder-abduction-90.screened.png)
+
+**PRE-NORMALIZATION / NONCOMPARABLE for cross-rig conclusions.** The Antonia-only normalized gallery remains valid REST-X1 evidence, but any inherited Mixamo/Genesis comparison is historical. The complete matched-camera gallery is generated at
+`artifacts/local/humanoid-rest-x1/gallery.html`. Each filename names an
+absolute anatomical state; failed surfaces retain `.failed-diagnostic`.
+
+## Shoulder and rerig verdict
+
+Input normalization materially improved benchmark validity. Historical
+“shoulder90” applied +90° to an 86.66° source rest and was not a 90° anatomical
+comparison. It failed with max edge ratio 7.1019 and nine reversal proxies.
+The normalized 90° state has 0.000007° residual, max ratio 2.5729, zero
+reversal proxies, and passes the existing screen. These numbers must not be
+presented as an A-pose weight-quality ablation because the historical and new
+poses were not anatomically equal.
+
+The retained Blender-cleaned field was generated from the former source rest
+and deterministically rebound to A-pose. An auto-weight regeneration from the
+canonical A-pose has not been run, so the hypothesis “A-pose generation itself
+improves shoulder deformation” remains unproven. Shoulder 120° still fails,
+and no clavicle/scapular coupling or contact model was added. Hip remains the
+expected control and still fails at 70°/90°.
+
+## External adapters and proprietary boundary
+
+Antonia is the only adapter qualified here. Existing local Mixamo and Genesis
+assets remain ignored, comparison-only, and absent from runtime. No
+proprietary mesh, weights, controls, JCMs, or DAZ/Mixamo dependency entered the
+repository. Because those local adapters and normalized renders are missing,
+the required X5/Blender-auto/Blender-cleaned/Mixamo/Genesis gallery is not
+claimed.
+
+## Performance and validation
+
+One observed local run (not a hard target): normalization 20.7 ms, ten pose
+solves 3.8 ms total, and ten CPU LBS/surface evaluations 916.5 ms total.
+Timing is environment-dependent and deliberately excluded from deterministic
+hash claims.
+
+The focused test assembly passes **67/67**. New tests cover source-rest
+independence, left/right sign convention, topology preservation, bind rebuild,
+attachment frames, four morph controls, and deterministic semantic targets.
+The full solution build passes with seven existing WebAssembly analysis/SQLite
+warnings. The parallel active suite passed every humanoid test and reported
+four unrelated Core display-preparation failures under load; all four passed
+immediately when rerun individually. This matches the repository's known
+contention-sensitive tessellation behavior and is not waived as humanoid proof.
+
+Reproduce:
+
+```powershell
+dotnet run --project tools/Aetheris.Humanoid.X0 -c Release -- `
+ normalize-rest-antonia `
+ --input artifacts/local/humanoid-x1/antonia-adoption-candidate.json `
+ --rig fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json `
+ --weights artifacts/local/humanoid-rerig-x1/golden-weights.json `
+ --out-dir artifacts/local/humanoid-rest-x1
+
+dotnet test Aetheris.Humanoid.Tests/Aetheris.Humanoid.Tests.csproj -c Release
+dotnet build Aetheris.slnx -c Release --no-restore
+```
+
+## Acceptance gap
+
+Completed: explicit/versioned A-pose, deterministic Antonia repose, unchanged
+topology, rebuilt binds, absolute semantic API, two-rest abstraction proof,
+low residual shoulder/elbow/hip/knee corpus, proprietary-free canonical path,
+side tests, generic morph/attachment checks, and normalized Aetheris gallery.
+
+Still required for Accepted: semantic Mixamo and Genesis adapters, regenerated
+normalized comparison columns, an A-pose auto-weight regeneration/ablation,
+and migration evidence for real Antonia morph/attachment data if those
+channels are admitted. The next blocker is isolated to source adapters and
+weight-generation evidence; canonical pose meaning is no longer the blocker.
+
+## Fresh-agent comprehension
+
+Three read-only agents received only the public guide and named entry points.
+The pose agent authored `LeftShoulder` abduction 90° without bind, Blender-axis,
+or source-name knowledge and caught a named-argument casing typo in the guide;
+the documentation was corrected. The adapter agent independently explained
+identity for a T-pose source versus a nonidentity 55° swing for the 35° source,
+while requiring equal canonical state and elbow center. The benchmark agent
+recovered the exact CLI and Blender commands and the absolute-label rationale;
+it initially assumed elbow90 would receive a `.screened` suffix. The guide now
+states the actual `.failed-diagnostic` result and explicitly separates exact
+semantic solve from failed deformation. Pose meaning and adapter abstraction
+pass; on a second read of the corrected guide plus evidence, the benchmark
+agent recovered both suffixes and the kinematics/deformation distinction. The
+initial mistake is useful evidence that surface admission must remain visible
+in benchmark instructions.
diff --git a/docs/release/HUMANOID-REST-X2.md b/docs/release/HUMANOID-REST-X2.md
new file mode 100644
index 00000000..3f8467f7
--- /dev/null
+++ b/docs/release/HUMANOID-REST-X2.md
@@ -0,0 +1,167 @@
+# HUMANOID-REST-X2 — normalized cross-rig benchmark and A-pose weight ablation
+
+## Executive verdict
+
+**Accepted.** Aetheris now produces an absolute-anatomical benchmark across
+the open runtime, Blender, a local Mixamo FBX, and the locally installed
+Genesis 9 runtime. The canonical rest remains
+`aetheris.humanoid.rest.apose.v1`; no X1 axis, semantic zero, public pose API,
+Concept, Interface, or Judgment policy changed.
+
+Fresh A-pose weighting materially improves the worst high-angle deformation
+screen, especially at the shoulder, but is not uniformly better on every
+metric. The selected open candidate is **A-pose auto plus the unchanged
+RERIG-X1 bounded cleanup**. It uses no manual paint strokes, helper bones,
+correctives, proprietary payloads, or topology edits.
+
+## Authoritative outputs
+
+- Labeled five-column sheet: `artifacts/local/humanoid-rest-x2/five-column-gallery.png`
+- One labeled row per pose: `artifacts/local/humanoid-rest-x2/gallery/`
+- Open Blender candidate: `artifacts/local/humanoid-rest-x2/golden-apose.blend`
+- Portable weights: `artifacts/local/humanoid-rest-x2/selected-weights.json`
+- Ablation: `artifacts/local/humanoid-rest-x2/weight-ablation.json`
+- Mixamo adapter: `artifacts/local/humanoid-rest-x2/mixamo-adapter.json`
+- Genesis derived evidence: `artifacts/local/humanoid-rest-x2/genesis-local/pose-observations.json`
+- Aetheris import/parity: `artifacts/local/humanoid-rest-x2/aetheris/evidence.json`
+
+The first three columns are open/promotable. Mixamo and Genesis are local
+proprietary oracles; their raw geometry is ignored and absent from the golden
+`.blend` and portable artifact.
+
+## Adapter residuals
+
+Mixamo's source bind is a near-T pose (fresh measurement: left shoulder
+abduction 82.505°, flexion 2.443°). The adapter neutralizes all benchmark ball
+and hinge roles to the frozen canonical state before applying each override.
+Across the full corpus its maximum roundtrip residual is 0.025°; fresh
+shoulder90 measured flexion −0.000006°, abduction 90.000044°.
+
+Genesis controls are calibrated from evaluated world-space joint centers after
+every DAZ update. Shoulder90 uses native `l_upperarm` Bend 47.218° to produce
+90.000071° canonical abduction—not a native value of 90°. Isolated shoulder,
+elbow, hip45/70, abduction, knee, walking, reach, and the bounded balance/kick
+pose converge below 0.001°. Two source-range exceptions remain explicit:
+
+- the installed base control range cannot fully straighten the Genesis elbow;
+ canonical neutral bottoms out at about 5.34° flexion;
+- hip90 reaches 87.519° through the admitted thigh Bend control, a 2.481°
+ residual. It is `NeedsReview` and excluded from quantitative parity.
+
+These are recorded exceptions, not hidden slider equivalences. Genesis remains
+a local quality ceiling and never a canonical dependency.
+
+## A-pose ablation
+
+All ratios are posed/rest edge-length distortion ratios. Self-intersection is
+unavailable; every listed case has zero degenerate triangles.
+
+| Variant | Pose | reversals | p95 | p99 | max | minimum compression |
+|---|---|---:|---:|---:|---:|---:|
+| T-pose auto, rebound | shoulder90 | 0 | 1.0000 | 1.0524 | 3.4108 | 0.3242 |
+| T-pose cleaned, rebound | shoulder90 | 0 | 1.0000 | 1.0689 | 2.5729 | 0.5386 |
+| A-pose auto | shoulder90 | 0 | 1.0000 | 1.0536 | 2.2564 | 0.4432 |
+| **A-pose cleaned** | **shoulder90** | **0** | **1.0000** | **1.0668** | **1.7692** | **0.5652** |
+| T-pose cleaned, rebound | hip70 | 2 | 1.06 | 1.37 | 8.87 | 0.11 |
+| **A-pose cleaned** | **hip70** | **0** | **1.06** | **1.38** | **6.70** | **0.15** |
+| T-pose cleaned, rebound | hip90 | 67 | 1.06 | 1.50 | 11.08 | 0.09 |
+| **A-pose cleaned** | **hip90** | **71** | **1.07** | **1.51** | **9.06** | **0.11** |
+| T-pose cleaned, rebound | knee90 | 27 | 1.00 | 1.04 | 5.69 | 0.18 |
+| **A-pose cleaned** | **knee90** | **28** | **1.00** | **1.03** | **5.62** | **0.18** |
+
+A-pose generation reduces worst shoulder distortion by 31% versus T-pose
+cleaned and improves hip70/hip90 worst-case stretch and compression. Hip90 and
+knee90 reversal counts do not improve. Hip remains the limiting region, not an
+unrelated whole-body regression. Cleanup takes about 0.50 s after about 1.15 s
+of Blender bone heat and uses the exact recorded RERIG-X1 recipe.
+
+## Golden path and runtime parity
+
+```text
+canonical A-pose → X5 skeleton → Blender bone heat → normalize → unchanged
+bounded cleanup → portable canonical IDs → Aetheris import
+```
+
+Exact solver local rotations are replayed through Blender's armature modifier
+for parity, avoiding unconstrained display-frame roll.
+
+| Pose | RMS mm | p95 mm | max mm |
+|---|---:|---:|---:|
+| shoulder90 | 0.00031 | 0.00054 | 0.00074 |
+| hip70 | 0.00218 | 0.00681 | 0.00706 |
+| hip90 | 0.00232 | 0.00727 | 0.00765 |
+| knee90 | 0.00136 | 0.00437 | 0.00469 |
+
+Bind reconstruction is 0.000716 mm and Aetheris semantic residuals are below
+0.00005°. Pose solving totals about 5.2 ms and deformation about 2.08 s for the
+17-pose corpus on this machine. The Mixamo adapter pass is about 0.28 s; full
+render/contact-sheet generation is roughly 45 s. No strict performance gate is
+asserted.
+
+## Judgment, morphs, attachments, and visual review
+
+X3 policies are unchanged. Hip-flexion70 remains inadmissible, while
+hip-abduction45 changes from no winner to `lbs.baseline`, with
+`dqs.baseline-weights` runner-up. One case therefore gains admissible
+candidates and a winner without policy tuning.
+
+Tests cover default and 1800 mm bodies through normalization and shoulder90.
+Wrist, upper arm, chest, waist, thigh, and foot attachment frames remain finite.
+`RestPose`, `MeasurementPose`, and `CurrentPose` remain separate.
+
+| Active region | Aetheris / auto | Blender cleaned A | Mixamo | Genesis 9 |
+|---|---|---|---|---|
+| shoulder/armpit 60–120 | NeedsReview | Pass at 60/90; NeedsReview at 120 | NeedsReview | Pass |
+| elbow 45–120 | NeedsReview | NeedsReview | NeedsReview | Pass |
+| hip/groin 45–90, abduction | NeedsReview; Fail at hip90 fold | NeedsReview; Fail at hip90 fold | NeedsReview | Pass, except hip90 semantic mismatch |
+| knee 45–90 | NeedsReview | NeedsReview | NeedsReview | Pass |
+
+Compact representative summary (`residual / deformation screen / visual`):
+
+| Pose | Aetheris | Blender auto A | Blender cleaned A | Mixamo | Genesis 9 |
+|---|---|---|---|---|---|
+| canonical A-pose | 0.000° / Pass / Pass | 0.000° / Pass / Pass | 0.000° / Pass / Pass | 0.000° / Pass / Pass | 5.342° / exception / NeedsReview |
+| shoulder90 | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | 0.000° / Pass / Pass | 0.000° / Pass / NeedsReview | 0.000° / Pass / Pass |
+| elbow90 | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | <0.025° / Pass / NeedsReview | <0.001° / Pass / Pass |
+| hip70 | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | <0.025° / Pass / NeedsReview | <0.001° / Pass / Pass |
+| hip90 | 0.000° / Fail / Fail | 0.000° / Fail / Fail | 0.000° / Fail / Fail | <0.025° / Pass / NeedsReview | 2.481° / exception / NeedsReview |
+| abduction45 | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | <0.025° / Pass / NeedsReview | <0.001° / Pass / Pass |
+| knee90 | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | 0.000° / Pass / NeedsReview | <0.025° / Pass / NeedsReview | <0.001° / Pass / Pass |
+
+Genesis retains broader shoulder/armpit and hip volume. The remaining gap is a
+combination of topology/surface resolution, helper/twist chains, weighting, and
+pose-dependent correctives. Ordinary runtime behavior indicates shoulder and
+hip correctives are active. No proprietary delta was extracted. Materials and
+lighting were replaced by the common neutral display.
+
+After normalization, Mixamo is broadly comparable rather than consistently
+superior to the open path. Retain it as an occasional adapter/oracle test, not
+routine open qualification.
+
+## Fresh-agent and optional-reference checks
+
+Missing Mixamo writes an explicit skip record while the open ablation succeeds;
+DAZ is a separate optional process. Three fresh read-only checks passed:
+
+1. Mixamo shoulder90 reproduced at 90.000044° with a 0.000044° requested-joint
+ residual.
+2. Genesis shoulder90 independently verified 90.000071° from native control
+ 47.218°. The check identified the former native-neutral labeling defect;
+ the final adapter calibrates canonical neutral before every case.
+3. The open ablation reproduced `apose-cleaned`; fresh weights were byte-identical
+ and shoulder90 metrics matched exactly.
+
+Old RERIG-X1/REST-X1 cross-rig galleries are marked
+`PRE-NORMALIZATION / NONCOMPARABLE` and are not acceptance evidence here.
+
+## Validation
+
+- `dotnet build Aetheris.slnx --no-restore`: succeeded with no errors.
+- `Aetheris.Humanoid.Tests`: 69/69 passed.
+- `qualify-rest-x2`: accepted; maximum Blender/Aetheris parity 0.007653 mm.
+- Python benchmark/render scripts compile and the full five-column corpus renders.
+- The parallel whole-solution test invocation passed the humanoid suite but
+ triggered four existing bounded-tessellation/performance tests under shared
+ load. All four exact failures passed when rerun sequentially (3/3 recipe
+ cases plus one test each for FTC07 display, server FTC07, and Firmament
+ plateau meshing).
diff --git a/scripts/benchmark-genesis9-local.dsa b/scripts/benchmark-genesis9-local.dsa
index 7a6e3f96..08cfcaf4 100644
--- a/scripts/benchmark-genesis9-local.dsa
+++ b/scripts/benchmark-genesis9-local.dsa
@@ -1,38 +1,32 @@
-// Local reference only. Run in a separate headless DAZ instance; never the user's scene.
-// Arguments: content library root, ignored output directory. No morph/weight payload is read.
+// HUMANOID-REST-X2 local Genesis 9 oracle. Run in a separate headless DAZ process.
+// Arguments: installed content-library root, ignored artifacts/local output directory.
(function(){
var library=App.scriptArgs[0], out=App.scriptArgs[1];
function save(name,value){var f=new DzFile(out+'/'+name);if(!f.open(DzFile.WriteOnly))throw 'write failed';f.writeLine(JSON.stringify(value,null,2));f.close();}
+ function clamp(x,a,b){return Math.max(a,Math.min(b,x));}
+ function sub(a,b){return [a[0]-b[0],a[1]-b[1],a[2]-b[2]];}
+ function unit(a){var z=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]);return [a[0]/z,a[1]/z,a[2]/z];}
+ function dot(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2];}
+ function deg(x){return x*180/Math.PI;}
+ function canonical(node){var p=node.getWSPos();return [-p.x,p.z,p.y];}
+ function direction(a,b){return unit(sub(canonical(b),canonical(a)));}
+ function ball(a,b,side){var d=direction(a,b),flex=deg(Math.asin(clamp(d[1],-1,1)));var abd=Math.abs(Math.abs(d[1])-1)<1e-7?0:deg(Math.atan2(side*d[0],-d[2]));return {flexionDegrees:flex,abductionDegrees:abd,twistDegrees:0};}
+ function hinge(a,b,c){return {flexionDegrees:deg(Math.acos(clamp(dot(direction(a,b),direction(b,c)),-1,1))),abductionDegrees:0,twistDegrees:0};}
+ function measure(kind,n){if(kind=='LeftShoulder')return ball(n.l_upperarm,n.l_forearm,-1);if(kind=='RightShoulder')return ball(n.r_upperarm,n.r_forearm,1);if(kind=='LeftHip')return ball(n.l_thigh,n.l_shin,-1);if(kind=='RightHip')return ball(n.r_thigh,n.r_shin,1);if(kind=='LeftElbow')return hinge(n.l_upperarm,n.l_forearm,n.l_hand);if(kind=='RightElbow')return hinge(n.r_upperarm,n.r_forearm,n.r_hand);if(kind=='LeftKnee')return hinge(n.l_thigh,n.l_shin,n.l_foot);if(kind=='RightKnee')return hinge(n.r_thigh,n.r_shin,n.r_foot);throw 'unsupported role '+kind;}
+ function reset(controls){for(var i=0;i<controls.length;i++)controls[i].setValue(0);Scene.update();}
+ function calibrate(spec,target,n){var c=spec.control,best=null,lo=c.getMin(),hi=c.getMax();for(var i=0;i<=80;i++){var v=lo+(hi-lo)*i/80;c.setValue(v);Scene.update();var a=measure(spec.kind,n)[spec.component],e=Math.abs(a-target);if(best===null||e<best.error)best={value:c.getValue(),actual:a,error:e};}var step=(hi-lo)/80;for(var pass=0;pass<5;pass++){lo=Math.max(c.getMin(),best.value-step);hi=Math.min(c.getMax(),best.value+step);for(var j=0;j<=12;j++){var v=lo+(hi-lo)*j/12;c.setValue(v);Scene.update();var a=measure(spec.kind,n)[spec.component],e=Math.abs(a-target);if(e<best.error)best={value:c.getValue(),actual:a,error:e};}step=(hi-lo)/12;}c.setValue(best.value);Scene.update();return best;}
try {
App.getContentMgr().addContentDirectory(library,false);
if(!App.getContentMgr().openFile(library+'/People/Genesis 9/Genesis 9.duf',true))throw 'Genesis 9 load failed';
- var nodes=Scene.getNodeList(), byName={}, controls=[];
- for(var i=0;i<nodes.length;i++)byName[nodes[i].getName()]=nodes[i];
- var names=['l_thigh','l_shin','l_upperarm','l_forearm'];
- for(var i=0;i<names.length;i++){
- var n=byName[names[i]], properties=[n.getXRotControl(),n.getYRotControl(),n.getZRotControl()];
- for(var j=0;j<properties.length;j++)controls.push({bone:names[i],axis:['x','y','z'][j],label:properties[j].getLabel(),minimum:properties[j].getMin(),maximum:properties[j].getMax()});
- }
- save('control-observations.json',controls);
- var exporter=App.getExportMgr().findExporterByClassName('DzObjExporter');
- var settings=new DzFileIOSettings();exporter.getDefaultOptions(settings);
- settings.setIntValue('RunSilent',1);settings.setFloatValue('Scale',1);
- settings.setStringValue('LatAxis','X');settings.setStringValue('VertAxis','Y');settings.setStringValue('DepthAxis','Z');
- settings.setBoolValue('InvertLat',false);settings.setBoolValue('InvertVert',false);settings.setBoolValue('InvertDepth',false);
- settings.setBoolValue('WriteVT',false);settings.setBoolValue('WriteVN',false);settings.setBoolValue('WriteMtllib',false);
- settings.setBoolValue('CollectMaps',false);settings.setBoolValue('SelectedOnly',false);settings.setBoolValue('IgnoreInvisible',true);
- var poses=[['neutral',null,0,0],['hip70','l_thigh',0,-70],['hip90','l_thigh',0,-90],['abduction45','l_thigh',2,45],
- ['knee90','l_shin',0,90],['shoulder60','l_upperarm',2,60],['shoulder90','l_upperarm',2,90],['elbow90','l_forearm',1,-90]];
- var results=[];
- for(var k=0;k<poses.length;k++){
- for(var i=0;i<names.length;i++){var n=byName[names[i]];n.getXRotControl().setValue(0);n.getYRotControl().setValue(0);n.getZRotControl().setValue(0);}
- var pose=poses[k],value=0;
- if(pose[1]){var n=byName[pose[1]],control=[n.getXRotControl(),n.getYRotControl(),n.getZRotControl()][pose[2]];control.setValue(pose[3]);value=control.getValue();}
- Scene.update();
- var code=exporter.writeFile(out+'/'+pose[0]+'.obj',settings);
- results.push({pose:pose[0],bone:pose[1],axis:pose[2],requested:pose[3],actual:value,exportCode:code});
- }
- save('pose-observations.json',results);
+ var nodes=Scene.getNodeList(),n={};for(var i=0;i<nodes.length;i++)n[nodes[i].getName()]=nodes[i];
+ var needed=['l_thigh','l_shin','l_foot','l_upperarm','l_forearm','l_hand','r_thigh','r_shin','r_foot','r_upperarm','r_forearm','r_hand'];for(var i=0;i<needed.length;i++)if(!n[needed[i]])throw 'missing Genesis node '+needed[i];
+ var controls=[];for(var i=0;i<needed.length;i++){controls.push(n[needed[i]].getXRotControl(),n[needed[i]].getYRotControl(),n[needed[i]].getZRotControl());}
+ var specs={shoulder:{kind:'LeftShoulder',component:'abductionDegrees',control:n.l_upperarm.getZRotControl()},shoulderFlex:{kind:'LeftShoulder',component:'flexionDegrees',control:n.l_upperarm.getYRotControl()},elbow:{kind:'LeftElbow',component:'flexionDegrees',control:n.l_forearm.getYRotControl()},hip:{kind:'LeftHip',component:'flexionDegrees',control:n.l_thigh.getXRotControl()},abduction:{kind:'LeftHip',component:'abductionDegrees',control:n.l_thigh.getZRotControl()},knee:{kind:'LeftKnee',component:'flexionDegrees',control:n.l_shin.getXRotControl()},rightShoulder:{kind:'RightShoulder',component:'abductionDegrees',control:n.r_upperarm.getZRotControl()},rightShoulderFlex:{kind:'RightShoulder',component:'flexionDegrees',control:n.r_upperarm.getYRotControl()},rightElbow:{kind:'RightElbow',component:'flexionDegrees',control:n.r_forearm.getYRotControl()},rightHip:{kind:'RightHip',component:'flexionDegrees',control:n.r_thigh.getXRotControl()},rightAbduction:{kind:'RightHip',component:'abductionDegrees',control:n.r_thigh.getZRotControl()},rightKnee:{kind:'RightKnee',component:'flexionDegrees',control:n.r_shin.getXRotControl()}};
+ var observations=[];for(var key in specs){var s=specs[key];observations.push({semantic:key,bone:s.control.getOwner().getName(),label:s.control.getLabel(),minimum:s.control.getMin(),maximum:s.control.getMax(),nativeNeutral:measure(s.kind,n)[s.component]});}save('control-observations.json',observations);
+ var exporter=App.getExportMgr().findExporterByClassName('DzObjExporter'),settings=new DzFileIOSettings();exporter.getDefaultOptions(settings);settings.setIntValue('RunSilent',1);settings.setFloatValue('Scale',1);settings.setStringValue('LatAxis','X');settings.setStringValue('VertAxis','Y');settings.setStringValue('DepthAxis','Z');settings.setBoolValue('InvertLat',false);settings.setBoolValue('InvertVert',false);settings.setBoolValue('InvertDepth',false);settings.setBoolValue('WriteVT',false);settings.setBoolValue('WriteVN',false);settings.setBoolValue('WriteMtllib',false);settings.setBoolValue('CollectMaps',false);settings.setBoolValue('SelectedOnly',false);settings.setBoolValue('IgnoreInvisible',true);
+ var cases=[['canonical-apose',[]],['shoulder60',[['shoulderFlex',0],['shoulder',60]]],['shoulder90',[['shoulderFlex',0],['shoulder',90]]],['shoulder120',[['shoulderFlex',0],['shoulder',120]]],['elbow45',[['shoulderFlex',0],['shoulder',35],['elbow',45]]],['elbow90',[['shoulderFlex',0],['shoulder',35],['elbow',90]]],['elbow120',[['shoulderFlex',0],['shoulder',35],['elbow',120]]],['hip45',[['hip',45],['abduction',0]]],['hip70',[['hip',70],['abduction',0]]],['hip90',[['hip',90]]],['abduction30',[['hip',0],['abduction',30]]],['abduction45',[['hip',0],['abduction',45]]],['knee45',[['knee',45]]],['knee90',[['knee',90]]],['walking',[['hip',30],['abduction',0],['knee',35]]],['balance-kick',[['hip',70],['abduction',0],['knee',35],['rightShoulderFlex',0],['rightShoulder',55]]],['reach',[['shoulderFlex',35],['shoulder',105],['elbow',25]]]];
+ var neutralTargets=[['shoulderFlex',0],['shoulder',35],['elbow',0],['hip',0],['abduction',0],['knee',0],['rightShoulderFlex',0],['rightShoulder',35],['rightElbow',0],['rightHip',0],['rightAbduction',0],['rightKnee',0]];reset(controls);for(var pass=0;pass<4;pass++)for(var q=0;q<neutralTargets.length;q++)calibrate(specs[neutralTargets[q][0]],neutralTargets[q][1],n);var neutralValues=[];for(var q=0;q<neutralTargets.length;q++)neutralValues.push({key:neutralTargets[q][0],value:specs[neutralTargets[q][0]].control.getValue()});var neutralCenters={l_upperarm:canonical(n.l_upperarm),l_forearm:canonical(n.l_forearm),l_hand:canonical(n.l_hand),l_thigh:canonical(n.l_thigh),l_shin:canonical(n.l_shin),l_foot:canonical(n.l_foot)};
+ var results=[];for(var k=0;k<cases.length;k++){reset(controls);for(var q=0;q<neutralValues.length;q++)specs[neutralValues[q].key].control.setValue(neutralValues[q].value);Scene.update();var requested=cases[k][1],fits=[];for(var pass=0;pass<(requested.length>1?4:1);pass++){fits=[];for(var q=0;q<requested.length;q++){var key=requested[q][0],target=requested[q][1],fit=calibrate(specs[key],target,n);fits.push({semantic:key,target:target,nativeControl:fit.value,measured:fit.actual,residualDegrees:fit.actual-target});}}var measured={LeftShoulder:measure('LeftShoulder',n),RightShoulder:measure('RightShoulder',n),LeftElbow:measure('LeftElbow',n),RightElbow:measure('RightElbow',n),LeftHip:measure('LeftHip',n),RightHip:measure('RightHip',n),LeftKnee:measure('LeftKnee',n),RightKnee:measure('RightKnee',n)},roundtrip=[],targets=requested.length?requested:neutralTargets;for(var q=0;q<targets.length;q++){var key=targets[q][0],s=specs[key],actual=measure(s.kind,n)[s.component];roundtrip.push({semantic:key,target:targets[q][1],actual:actual,residualDegrees:actual-targets[q][1]});}var code=exporter.writeFile(out+'/'+cases[k][0]+'.obj',settings);results.push({pose:cases[k][0],requested:requested,calibrations:fits,measured:measured,roundtrip:roundtrip,maximumResidualDegrees:roundtrip.length?Math.max.apply(Math,roundtrip.map(function(x){return Math.abs(x.residualDegrees);})):0,exportCode:code});}
+ save('pose-observations.json',results);save('adapter-metadata.json',{schema:'aetheris.humanoid.rest-x2.genesis-local.v1',nativeRest:'Genesis 9 installed figure A-pose',worldConversion:'(-X,+Z,+Y)',unit:'DAZ centimeters exported with local OBJ settings',jointCenters:neutralCenters,coupledCorrectives:'ordinary Genesis runtime and JCM behavior left enabled',proprietaryPayloadCommitted:false});
}catch(e){save('error.json',{error:String(e),line:e.lineNumber});}
- App.exit();
})();
diff --git a/scripts/compose-humanoid-rest-x2-gallery.py b/scripts/compose-humanoid-rest-x2-gallery.py
new file mode 100644
index 00000000..d76ff464
--- /dev/null
+++ b/scripts/compose-humanoid-rest-x2-gallery.py
@@ -0,0 +1,63 @@
+"""Compose labeled five-column REST-X2 comparison evidence from ignored local renders."""
+import json
+import textwrap
+from pathlib import Path
+from PIL import Image,ImageDraw,ImageFont
+
+ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'artifacts/local/humanoid-rest-x2';G=OUT/'gallery';G.mkdir(exist_ok=True)
+read=lambda p:json.loads(Path(p).read_text(encoding='utf-8-sig'))
+corpus=read(OUT/'pose-corpus.json');ablation=read(OUT/'weight-ablation.json');mixamo=read(OUT/'mixamo-adapter.json')
+aetheris=read(OUT/'aetheris/evidence.json');genesis=read(OUT/'genesis-local/pose-observations.json')
+by_a={x['pose']:x for x in aetheris['semantic']};by_m={x['pose']:x for x in mixamo['cases']};by_g={x['pose']:x for x in genesis}
+by_b={v['pipeline']:{x['pose']:x for x in v['cases']} for v in ablation['variants']}
+font=ImageFont.load_default(size=15);small=ImageFont.load_default(size=13)
+cols=[('Aetheris','aetheris','canonical A-pose / open'),('Blender auto A','apose-auto','canonical A-pose / open'),
+ ('Blender cleaned A','apose-cleaned','canonical A-pose / open'),('Mixamo local','mixamo','FBX native bind / local oracle'),
+ ('Genesis 9 local','genesis','Genesis native A-pose / local oracle')]
+
+def request_text(case):
+ if not case['requested']:return 'neutral canonical A-pose'
+ return '; '.join(f"{r['joint'].replace('Left','L.').replace('Right','R.')} F{r.get('flexionDegrees',0):g} A{r.get('abductionDegrees',0):g}" for r in case['requested'])
+def residual(source,pose):
+ if source=='aetheris':return by_a[pose]['maximumSemanticResidualDegrees']
+ if source in ('apose-auto','apose-cleaned'):return by_b[source][pose]['maximumSemanticResidualDegrees']
+ if source=='mixamo':return by_m[pose]['maximumSemanticResidualDegrees']
+ return by_g[pose]['maximumResidualDegrees']
+def actual(source,pose,case):
+ if source=='genesis':
+ if pose=='canonical-apose':
+ measured=by_g[pose]['measured']
+ return '; '.join((f"shoulder F{measured['LeftShoulder']['flexionDegrees']:.2f} A{measured['LeftShoulder']['abductionDegrees']:.2f}",
+ f"elbow F{measured['LeftElbow']['flexionDegrees']:.2f}",
+ f"hip F{measured['LeftHip']['flexionDegrees']:.2f} A{measured['LeftHip']['abductionDegrees']:.2f}",
+ f"knee F{measured['LeftKnee']['flexionDegrees']:.2f}"))
+ values=by_g[pose].get('roundtrip',[])
+ return '; '.join(f"{v['semantic']} {v['actual']:.2f}°" for v in values) or 'neutral'
+ if source=='aetheris':
+ requested={r['joint']:r for r in case['requested']}
+ return '; '.join(f"{r['joint'].replace('Left','L.').replace('Right','R.')} F{requested[r['joint']].get('flexionDegrees',0)+r['flexionDegrees']:.2f} A{requested[r['joint']].get('abductionDegrees',0)+r['abductionDegrees']:.2f}" for r in by_a[pose]['semanticResiduals']) or 'neutral'
+ rs=(by_b[source][pose]['semanticResiduals'] if source.startswith('apose') else by_m[pose]['semanticResiduals'])
+ if source=='mixamo':
+ wanted={r['joint'] for r in case['requested']} or {'LeftShoulder','RightShoulder'}
+ rs=[r for r in rs if r['joint'] in wanted]
+ return '; '.join(f"{r['joint'].replace('Left','L.').replace('Right','R.')} F{r['actual']['flexionDegrees']:.2f} A{r['actual']['abductionDegrees']:.2f}" for r in rs) or 'neutral'
+
+rows=[]
+for case in corpus:
+ pose=case['name'];panels=[]
+ for title,source,native in cols:
+ path=OUT/f'{source}--{pose}.png';im=Image.open(path).convert('RGB');im.thumbnail((300,338))
+ panel=Image.new('RGB',(320,480),'white');d=ImageDraw.Draw(panel);d.text((8,7),title,font=font,fill='black');y=29
+ for label,value in [('requested',request_text(case)),('actual',actual(source,pose,case))]:
+ lines=textwrap.wrap(label+': '+value,width=47,break_long_words=False) or [label+':']
+ d.multiline_text((8,y),'\n'.join(lines),font=small,fill='black',spacing=1);y+=16*len(lines)+3
+ d.text((8,y),f"residual: {residual(source,pose):.3f}°",font=small,fill='black');y+=19
+ d.text((8,y),'native rest: '+native,font=small,fill='black');y+=19
+ im.thumbnail((300,470-y));panel.paste(im,((320-im.width)//2,y+(470-y-im.height)//2));panels.append(panel)
+ row=Image.new('RGB',(1600,510),(225,225,225));ImageDraw.Draw(row).text((8,485),pose,font=font,fill='black')
+ for i,panel in enumerate(panels):row.paste(panel,(320*i,0))
+ row.save(G/f'{pose}.png');rows.append(row)
+sheet=Image.new('RGB',(1600,510*len(rows)),'white')
+for i,row in enumerate(rows):sheet.paste(row,(0,510*i))
+sheet.save(OUT/'five-column-gallery.png')
+print(OUT/'five-column-gallery.png')
diff --git a/scripts/humanoid-rest-x2.py b/scripts/humanoid-rest-x2.py
new file mode 100644
index 00000000..006564b2
--- /dev/null
+++ b/scripts/humanoid-rest-x2.py
@@ -0,0 +1,318 @@
+"""HUMANOID-REST-X2 local benchmark.
+
+Runs the open A-pose weight ablation and, when supplied, a local Mixamo oracle.
+All generated data stays under ignored artifacts/local; proprietary meshes/weights are
+never embedded in the promotable .blend or portable weight artifact.
+"""
+import argparse
+import copy
+import importlib
+import json
+import math
+from pathlib import Path
+import sys
+import time
+
+import bpy
+import numpy as np
+from mathutils import Matrix, Quaternion, Vector
+
+sys.path.insert(0, str(Path(__file__).parent))
+h = importlib.import_module('humanoid-rerig-x0')
+x1 = importlib.import_module('humanoid-rerig-x1')
+ROOT = h.ROOT
+
+
+def normalize(field):
+ return [{n: value / sum(row.values()) for n, value in sorted(row.items()) if value > 1e-8}
+ for row in field]
+
+
+def portable_field(path):
+ value = h.read(path)
+ if isinstance(value, list):
+ return normalize(value)
+ return normalize([{w['boneId']: w['weight'] for w in vertex['weights']} for vertex in value['vertices']])
+
+
+def normalized_inputs():
+ candidate = h.read(ROOT/'artifacts/local/humanoid-x1/antonia-adoption-candidate.json')
+ reference = h.read(ROOT/'fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json')
+ evidence = h.read(ROOT/'artifacts/local/humanoid-rest-x1/evidence.json')
+ by_kind = {j['kind']: j for j in evidence['normalizedJoints']}
+ artifact = copy.deepcopy(reference)
+ artifact['restPoseId'] = evidence['identities']['restPoseId']
+ for joint in artifact['canonicalJoints']:
+ joint['globalRestCanonical'] = by_kind[joint['canonicalJoint']]['globalBind']
+ surface = candidate['sourcePoseSurface']
+ vertices = []
+ for line in (ROOT/'artifacts/local/humanoid-rest-x1/canonical-apose.obj').read_text().splitlines():
+ if line.startswith('v '):
+ vertices.append(tuple(float(v)/1000 for v in line.split()[1:4]))
+ if len(vertices) != len(surface['vertices']):
+ raise RuntimeError('REST-X1 canonical A-pose vertex evidence does not match Antonia topology.')
+ return candidate, surface, artifact, evidence, vertices
+
+
+def canonical_corpus():
+ r = lambda joint, flex=0, abd=0, twist=0: dict(joint=joint, flexionDegrees=flex,
+ abductionDegrees=abd, twistDegrees=twist)
+ return [
+ dict(name='canonical-apose', requested=[]),
+ *[dict(name=f'shoulder{a}', requested=[r('LeftShoulder', abd=a)]) for a in (60, 90, 120)],
+ *[dict(name=f'elbow{a}', requested=[r('LeftShoulder', abd=35), r('LeftElbow', flex=a)]) for a in (45, 90, 120)],
+ *[dict(name=f'hip{a}', requested=[r('LeftHip', flex=a)]) for a in (45, 70, 90)],
+ *[dict(name=f'abduction{a}', requested=[r('LeftHip', abd=a)]) for a in (30, 45)],
+ *[dict(name=f'knee{a}', requested=[r('LeftKnee', flex=a)]) for a in (45, 90)],
+ dict(name='walking', requested=[r('LeftHip', 30), r('LeftKnee', 35), r('RightShoulder', abd=20)]),
+ dict(name='balance-kick', requested=[r('LeftHip', 70), r('LeftKnee', 35), r('RightShoulder', abd=55)]),
+ dict(name='reach', requested=[r('LeftShoulder', 35, 105), r('LeftElbow', 25), r('RightShoulder', abd=35)]),
+ ]
+
+
+def canonical_neutralized(requests):
+ defaults={
+ 'LeftShoulder':dict(joint='LeftShoulder',flexionDegrees=0,abductionDegrees=35,twistDegrees=0),
+ 'RightShoulder':dict(joint='RightShoulder',flexionDegrees=0,abductionDegrees=35,twistDegrees=0),
+ 'LeftHip':dict(joint='LeftHip',flexionDegrees=0,abductionDegrees=0,twistDegrees=0),
+ 'RightHip':dict(joint='RightHip',flexionDegrees=0,abductionDegrees=0,twistDegrees=0),
+ 'LeftElbow':dict(joint='LeftElbow',flexionDegrees=0,abductionDegrees=0,twistDegrees=0),
+ 'RightElbow':dict(joint='RightElbow',flexionDegrees=0,abductionDegrees=0,twistDegrees=0),
+ 'LeftKnee':dict(joint='LeftKnee',flexionDegrees=0,abductionDegrees=0,twistDegrees=0),
+ 'RightKnee':dict(joint='RightKnee',flexionDegrees=0,abductionDegrees=0,twistDegrees=0)}
+ for request in requests:defaults[request['joint']]=request
+ return list(defaults.values())
+
+
+def role_map(rig, mixamo=False):
+ result = {name: name for name in ('Pelvis','SpineLower','SpineMid','Chest','Neck','Head')}
+ for side in ('Left','Right'):
+ for kind in ('Clavicle','Shoulder','Elbow','Wrist','Hip','Knee','Ankle','ToeBase'):
+ result[side+kind] = side+kind
+ if mixamo:
+ result = {'Pelvis':'Hips','SpineLower':'Spine','SpineMid':'Spine1','Chest':'Spine2','Neck':'Neck','Head':'Head',
+ **{side+kind: side+native for side in ('Left','Right') for kind,native in
+ dict(Clavicle='Shoulder',Shoulder='Arm',Elbow='ForeArm',Wrist='Hand',Hip='UpLeg',Knee='Leg',Ankle='Foot',ToeBase='ToeBase').items()}}
+ result = {kind: 'mixamorig:'+name for kind,name in result.items()}
+ missing = [f'{kind}->{name}' for kind,name in result.items() if name not in rig.data.bones]
+ if missing:
+ raise RuntimeError('Hierarchy-seeded role mapping failed: ' + ', '.join(missing))
+ # Names seed the map; parent-chain evidence verifies every benchmark limb.
+ for side in ('Left','Right'):
+ for parent,child in (('Shoulder','Elbow'),('Elbow','Wrist'),('Hip','Knee'),('Knee','Ankle')):
+ bone = rig.data.bones[result[side+child]]
+ if bone.parent is None or bone.parent.name != result[side+parent]:
+ raise RuntimeError(f'Hierarchy verification failed for {side+parent}->{side+child}.')
+ return result
+
+
+def center(rig, mapping, kind):
+ return rig.matrix_world @ rig.pose.bones[mapping[kind]].head
+
+
+def direction(rig, mapping, a, b):
+ return (center(rig,mapping,b)-center(rig,mapping,a)).normalized()
+
+
+def semantic_measure(rig, mapping, kind):
+ side = -1 if kind.startswith('Left') else 1
+ if kind.endswith('Shoulder'):
+ d = direction(rig,mapping,kind,kind.replace('Shoulder','Elbow'))
+ flex=math.degrees(math.asin(max(-1,min(1,d.y))))
+ abd=0 if abs(abs(d.y)-1)<1e-6 else math.degrees(math.atan2(side*d.x,-d.z))
+ return dict(flexionDegrees=flex,abductionDegrees=abd,twistDegrees=0)
+ if kind.endswith('Hip'):
+ d = direction(rig,mapping,kind,kind.replace('Hip','Knee'))
+ flex=math.degrees(math.asin(max(-1,min(1,d.y))))
+ abd=0 if abs(abs(d.y)-1)<1e-6 else math.degrees(math.atan2(side*d.x,-d.z))
+ return dict(flexionDegrees=flex,abductionDegrees=abd,twistDegrees=0)
+ if kind.endswith('Elbow'):
+ proximal=direction(rig,mapping,kind.replace('Elbow','Shoulder'),kind)
+ distal=direction(rig,mapping,kind,kind.replace('Elbow','Wrist'))
+ else:
+ proximal=direction(rig,mapping,kind.replace('Knee','Hip'),kind)
+ distal=direction(rig,mapping,kind,kind.replace('Knee','Ankle'))
+ return dict(flexionDegrees=math.degrees(math.acos(max(-1,min(1,proximal.dot(distal))))),abductionDegrees=0,twistDegrees=0)
+
+
+def rotate_world(rig, pose_bone, axis, angle):
+ if abs(angle) < 1e-10 or axis.length < 1e-10:
+ return
+ local_axis = pose_bone.matrix.to_3x3().normalized().inverted() @ axis.normalized()
+ pose_bone.rotation_mode='QUATERNION'
+ pose_bone.rotation_quaternion = pose_bone.rotation_quaternion @ Quaternion(local_axis, angle)
+ bpy.context.view_layer.update()
+
+
+def apply_semantic(rig, mapping, requests):
+ for bone in rig.pose.bones:
+ bone.rotation_mode='QUATERNION'; bone.rotation_quaternion=Quaternion(); bone.location=(0,0,0); bone.scale=(1,1,1)
+ bpy.context.view_layer.update()
+ residuals=[]
+ # Parent ball joints first, then hinges. Two correction iterations remove numeric/frame noise.
+ ordered=sorted(requests,key=lambda q: 1 if q['joint'].endswith(('Elbow','Knee')) else 0)
+ for request in ordered:
+ kind=request['joint']; pb=rig.pose.bones[mapping[kind]]
+ for _ in range(4):
+ if kind.endswith(('Shoulder','Hip')):
+ side=-1 if kind.startswith('Left') else 1
+ f=math.radians(request.get('flexionDegrees',0)); a=math.radians(request.get('abductionDegrees',0))
+ target=Vector((side*math.cos(f)*math.sin(a),math.sin(f),-math.cos(f)*math.cos(a))).normalized()
+ child=kind.replace('Shoulder','Elbow').replace('Hip','Knee')
+ current=direction(rig,mapping,kind,child)
+ q=current.rotation_difference(target)
+ rotate_world(rig,pb,q.axis,q.angle)
+ else:
+ if kind.endswith('Elbow'):
+ proximal=direction(rig,mapping,kind.replace('Elbow','Shoulder'),kind)
+ distal=direction(rig,mapping,kind,kind.replace('Elbow','Wrist'))
+ axis=proximal.cross(Vector((0,1,0)))
+ else:
+ proximal=direction(rig,mapping,kind.replace('Knee','Hip'),kind)
+ distal=direction(rig,mapping,kind,kind.replace('Knee','Ankle'))
+ axis=-proximal.cross(Vector((0,1,0)))
+ target=Quaternion(axis.normalized(),math.radians(request.get('flexionDegrees',0)))@proximal
+ q=distal.rotation_difference(target)
+ rotate_world(rig,pb,q.axis,q.angle)
+ actual=semantic_measure(rig,mapping,kind)
+ requested={k:request.get(k,0) for k in ('flexionDegrees','abductionDegrees','twistDegrees')}
+ residuals.append(dict(joint=kind,requested=requested,actual=actual,
+ maximumAbsoluteDegrees=max(abs(actual[k]-requested[k]) for k in requested)))
+ return residuals
+
+
+def make_open_scene(surface, artifact, vertices):
+ bpy.ops.object.select_all(action='SELECT'); bpy.ops.object.delete(use_global=False)
+ faces=[tuple(f[k] for k in ('a','b','c')) for f in surface['faces']]
+ rig=h.make_rig(artifact,h.collection('CANONICAL_A_POSE_RIG'))
+ obj=h.mesh('ANTONIA_A_POSE',vertices,faces,h.collection('OPEN_DEFORMATION'))
+ mod=obj.modifiers.new('Portable linear blend skinning','ARMATURE');mod.object=rig
+ return rig,obj,np.asarray(vertices),np.asarray(faces),h.setup_camera()
+
+
+def run_field(name, field, rig, obj, mapping, rest, triangles, corpus, out, scene, render):
+ h.assign(obj,field)
+ cases=[]
+ started=time.perf_counter()
+ for case in corpus:
+ residuals=apply_semantic(rig,mapping,case['requested'])
+ posed=h.positions(obj)
+ metrics=x1.measure(rest,posed,triangles,h.normal_transport(rig,field,triangles))
+ cases.append(dict(pose=case['name'],requested=case['requested'],semanticResiduals=residuals,
+ maximumSemanticResidualDegrees=max([r['maximumAbsoluteDegrees'] for r in residuals] or [0]),metrics=metrics))
+ if render:
+ h.render(scene,obj,out/f'{name}--{case["name"]}.png')
+ apply_semantic(rig,mapping,[])
+ return dict(pipeline=name,seconds=time.perf_counter()-started,cases=cases)
+
+
+def export_portable(out, surface, field, evidence, recipe):
+ value=dict(schema='aetheris.humanoid.experimental-weights.v1',topologyId=surface['topologyId'],
+ connectivityHash=surface['connectivityHash'],referenceRigSha256=evidence['referenceRigSha256'],
+ restPoseId=evidence['identities']['restPoseId'],maxInfluences=max(map(len,field)),skinning='linear-blend-skinning',
+ deformationRigExtensions=[],provenance=dict(source='Fresh canonical A-pose Blender bone heat plus unchanged RERIG-X1 cleanup',steps=recipe,
+ manualPaintStrokes=0,topologyEdits=0,jointEdits=0,blender=bpy.app.version_string,scriptSha256=h.sha(__file__)),
+ vertices=[dict(vertexId=v['id'],weights=[dict(boneId=n,weight=w) for n,w in sorted(row.items())]) for v,row in zip(surface['vertices'],field)])
+ h.write(out/'selected-weights.json',value)
+
+
+def mixamo_oracle(path, target, corpus, out, scene, render):
+ before=set(bpy.data.objects); started=time.perf_counter()
+ bpy.ops.import_scene.fbx(filepath=str(path),use_anim=False)
+ imported=set(bpy.data.objects)-before
+ rig=next(o for o in imported if o.type=='ARMATURE'); obj=next(o for o in imported if o.type=='MESH')
+ conversion=Matrix(((1,0,0,0),(0,0,1,0),(0,-1,0,0),(0,0,0,1)))
+ raw=np.array([tuple(conversion@Vector(v)) for v in h.positions(obj)])
+ scale=np.ptp(target[:,2])/np.ptp(raw[:,2]); offset=(target.min(0)+target.max(0))/2-scale*(raw.min(0)+raw.max(0))/2
+ alignment=Matrix.Translation(Vector(offset))@Matrix.Scale(float(scale),4)@conversion
+ original={o:o.matrix_world.copy() for o in imported}
+ def depth(o): return 0 if o.parent is None else 1+depth(o.parent)
+ for o in sorted(imported,key=depth): o.matrix_world=alignment@original[o]
+ bpy.context.view_layer.update(); mapping=role_map(rig,True)
+ native=[]
+ for kind,name in sorted(mapping.items()):
+ bone=rig.data.bones[name]; [email protected]_local
+ native.append(dict(role=kind,sourceBone=name,parent=bone.parent.name if bone.parent else None,
+ jointCenterMm=list(world.translation*1000),majorAxis=list(world.to_3x3().normalized()@Vector((0,1,0))),
+ localRestTransform=[list(row) for row in bone.matrix_local]))
+ cases=[]
+ obj.data.calc_loop_triangles();oracle_faces=[tuple(face.vertices) for face in obj.data.loop_triangles]
+ for case in corpus:
+ effective=canonical_neutralized(case['requested']);residuals=apply_semantic(rig,mapping,effective)
+ cases.append(dict(pose=case['name'],requested=case['requested'],semanticResiduals=residuals,
+ maximumSemanticResidualDegrees=max([r['maximumAbsoluteDegrees'] for r in residuals] or [0])))
+ if render:
+ p=h.positions(obj);low=p.min(0);high=p.max(0);s=1.75/max(high[2]-low[2],1e-9);p=(p-(low+high)/2)*s;p[:,2]-=p[:,2].min()
+ display=h.mesh('Mixamo normalized display',p,oracle_faces,h.collection('MIXAMO_NORMALIZED_DISPLAY'))
+ h.render(scene,display,out/f'mixamo--{case["name"]}.png');bpy.data.objects.remove(display,do_unlink=True)
+ apply_semantic(rig,mapping,[])
+ evidence=dict(status='available',sourceSha256=h.sha(path),nativeRest='source FBX bind pose; normalized through measured rest directions',
+ handedness='proper FBX-to-canonical rotation; determinant positive',unitScaleToMeters=scale,alignment=[list(row) for row in alignment],
+ hierarchyVerified=True,joints=native,cases=cases,adapterSeconds=time.perf_counter()-started)
+ h.write(out/'mixamo-adapter.json',evidence)
+ for o in imported: bpy.data.objects.remove(o,do_unlink=True)
+ return evidence
+
+
+def main():
+ parser=argparse.ArgumentParser()
+ parser.add_argument('--out',default=str(ROOT/'artifacts/local/humanoid-rest-x2'))
+ parser.add_argument('--mixamo')
+ parser.add_argument('--no-render',action='store_true')
+ args=parser.parse_args(sys.argv[sys.argv.index('--')+1:])
+ out=Path(args.out).resolve(); out.mkdir(parents=True,exist_ok=True)
+ if not out.is_relative_to((ROOT/'artifacts/local').resolve()): raise ValueError('Ignored local output required.')
+ candidate,surface,artifact,evidence,vertices=normalized_inputs()
+ rig,obj,rest,triangles,scene=make_open_scene(surface,artifact,vertices); mapping=role_map(rig)
+ corpus=canonical_corpus(); h.write(out/'pose-corpus.json',corpus)
+ # Import the local oracle before Blender's auto-parent operator mutates scene parenting state.
+ if args.mixamo and Path(args.mixamo).is_file(): mixamo=mixamo_oracle(Path(args.mixamo).resolve(),rest,corpus,out,scene,not args.no_render)
+ else:
+ mixamo=dict(status='skipped',diagnostic='No --mixamo local FBX supplied; open qualification remains valid.')
+ h.write(out/'mixamo-adapter.json',mixamo)
+ old_auto=portable_field(ROOT/'artifacts/local/humanoid-rerig-x1/auto-weights.json')
+ old_clean=portable_field(ROOT/'artifacts/local/humanoid-rerig-x1/golden-weights.json')
+ auto_started=time.perf_counter(); fresh_auto=x1.automatic_weights(rig,obj); auto_seconds=time.perf_counter()-auto_started
+ cleanup_started=time.perf_counter(); fresh_clean=x1.golden_cleanup(obj,rig,rest,fresh_auto); fresh_clean=normalize(fresh_clean); cleanup_seconds=time.perf_counter()-cleanup_started
+ h.write(out/'apose-auto-weights.json',fresh_auto); h.write(out/'apose-cleaned-weights.json',fresh_clean)
+ variants={'tpose-auto-rebound':old_auto,'tpose-cleaned-rebound':old_clean,'apose-auto':fresh_auto,'apose-cleaned':fresh_clean}
+ results=[run_field(name,field,rig,obj,mapping,rest,triangles,corpus,out,scene,not args.no_render) for name,field in variants.items()]
+ h.write(out/'weight-ablation.json',dict(schema='aetheris.humanoid.rest-x2.ablation.v1',autoWeightSeconds=auto_seconds,
+ cleanupSeconds=cleanup_seconds,cleanupRecipe='unchanged RERIG-X1 golden_cleanup',variants=results))
+ # Selection is metric-led and complexity-aware: cleaned wins only when it reduces reversals, then p99, across required poses.
+ required={'shoulder60','shoulder90','shoulder120','hip70','hip90','abduction45','elbow90','knee90'}
+ def score(result):
+ cases=[c for c in result['cases'] if c['pose'] in required]
+ return (sum(c['metrics']['reversalCount'] for c in cases),sum(c['metrics']['p99'] for c in cases),sum(c['metrics']['max'] for c in cases))
+ open_candidates=[r for r in results if r['pipeline'].startswith('apose-')]
+ selected=min(open_candidates,key=score); selected_field=variants[selected['pipeline']]
+ selection=dict(selected=selected['pipeline'],scores={r['pipeline']:score(r) for r in results},
+ rule='minimum aggregate reversal count, then p99, then max over required ablation poses; only fresh A-pose candidates admissible')
+ h.write(out/'selection.json',selection)
+ recipe=['native bone heat at temporary data scale 10; restore canonical A-pose frames','normalize']
+ if selected['pipeline']=='apose-cleaned': recipe += ['bilateral hip soft gain 0.85 radius 220 mm','native Smooth 0.5 once at knees 110 mm and elbows 100 mm','bilateral shoulder contrast exponent 0.5 radius 180 mm','normalize']
+ export_portable(out,surface,selected_field,evidence,recipe)
+ h.assign(obj,selected_field)
+ exact_path=out/'aetheris/pose-transforms.json'
+ exact={case['pose']:case for case in h.read(exact_path)} if exact_path.is_file() else None
+ for case in corpus:
+ if case['name'] in ('shoulder90','hip70','hip90','knee90'):
+ if exact:
+ apply_semantic(rig,mapping,[])
+ for rotation in exact[case['name']]['localRotations']:
+ rig.pose.bones[rotation['joint']].rotation_quaternion=Quaternion((rotation['w'],rotation['x'],rotation['y'],rotation['z']))
+ bpy.context.view_layer.update()
+ else:
+ apply_semantic(rig,mapping,case['requested'])
+ h.write(out/f'blender-selected--{case["name"]}.positions.json',(h.positions(obj)*1000).tolist())
+ apply_semantic(rig,mapping,[])
+ for block in list(bpy.data.collections):
+ if block.name not in ('Collection','CANONICAL_A_POSE_RIG','OPEN_DEFORMATION'): bpy.data.collections.remove(block)
+ bpy.context.scene['study']='HUMANOID-REST-X2 open canonical A-pose golden candidate; no proprietary payloads'
+ bpy.ops.wm.save_as_mainfile(filepath=str(out/'golden-apose.blend'))
+ h.write(out/'benchmark-summary.json',dict(openSelection=selection,mixamoStatus=mixamo['status'],genesisStatus='separate local DAZ process required',
+ canonicalRestPoseId=evidence['identities']['restPoseId'],topologyUnchanged=True,proprietaryPayloadsEmbedded=False))
+ print(json.dumps(dict(success=True,output=str(out),selection=selection,mixamo=mixamo['status'],autoWeightSeconds=auto_seconds),indent=2))
+
+
+if __name__=='__main__': main()
diff --git a/scripts/render-humanoid-rest-x1.py b/scripts/render-humanoid-rest-x1.py
new file mode 100644
index 00000000..1782f2ee
--- /dev/null
+++ b/scripts/render-humanoid-rest-x1.py
@@ -0,0 +1,82 @@
+"""Render canonical REST-X1 meshes and a joint-center/axis overlay with one matched camera."""
+import argparse
+import html
+import json
+import runpy
+from pathlib import Path
+import sys
+
+import bpy
+from mathutils import Vector
+
+helpers = runpy.run_path(str(Path(__file__).with_name("render-humanoid-x2.py")))
+setup, obj_mesh, render, material = (helpers[name] for name in ("setup", "obj_mesh", "render", "material"))
+
+
+def point(matrix):
+ return Vector((matrix["m41"] / 1000, matrix["m42"] / 1000, matrix["m43"] / 1000))
+
+
+def axis(matrix, row):
+ return Vector((matrix[f"m{row}1"], matrix[f"m{row}2"], matrix[f"m{row}3"]))
+
+
+def cylinder(first, second, radius, mat):
+ delta = second - first
+ if delta.length < 1e-8:
+ return
+ bpy.ops.mesh.primitive_cylinder_add(vertices=10, radius=radius, depth=delta.length, location=(first + second) / 2)
+ obj = bpy.context.object
+ obj.rotation_euler = delta.to_track_quat("Z", "Y").to_euler()
+ obj.data.materials.append(mat)
+
+
+def matched_scene(mesh_path):
+ scene = setup()
+ body = obj_mesh(mesh_path)
+ body.data.materials.clear()
+ body.data.materials.append(material("REST-X1 body", (.42, .45, .50)))
+ scene.camera.data.ortho_scale = 2.05
+ scene.camera.location = (0, 4, 1.02)
+ center = Vector((0, 0, .9))
+ scene.camera.rotation_euler = (center - scene.camera.location).to_track_quat("-Z", "Y").to_euler()
+ return scene
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--out-dir", default="artifacts/local/humanoid-rest-x1")
+ args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
+ out = Path(args.out_dir)
+ evidence = json.loads((out / "evidence.json").read_text(encoding="utf-8"))
+ renders = []
+ for mesh in [out / "source-native-rest.obj", out / "canonical-apose.obj"] + [out / case["obj"] for case in evidence["cases"]]:
+ scene = matched_scene(mesh)
+ image = out / (mesh.stem + ".png")
+ render(scene, image)
+ renders.append((mesh.stem, image.name))
+
+ scene = matched_scene(out / "canonical-apose.obj")
+ joints = evidence["normalizedJoints"]
+ bone_mat = material("Canonical skeleton", (.08, .20, .25))
+ axes = [material("Anatomical X", (1, .12, .12)), material("Forward Y", (.12, 1, .20)), material("Up Z", (.15, .35, 1))]
+ major = {"LeftShoulder", "RightShoulder", "LeftElbow", "RightElbow", "LeftHip", "RightHip", "LeftKnee", "RightKnee"}
+ for joint in joints:
+ origin = point(joint["globalBind"])
+ if joint["parentIndex"] is not None:
+ cylinder(origin, point(joints[joint["parentIndex"]]["globalBind"]), .003, bone_mat)
+ if joint["kind"] in major:
+ bpy.ops.mesh.primitive_uv_sphere_add(segments=16, ring_count=8, radius=.011, location=origin)
+ bpy.context.object.data.materials.append(bone_mat)
+ for row, mat in zip((1, 2, 3), axes):
+ cylinder(origin, origin + axis(joint["globalBind"], row).normalized() * .055, .0018, mat)
+ render(scene, out / "canonical-apose-skeleton-overlay.png")
+
+ rows = "\n".join(f"<tr><th>{html.escape(name)}</th><td><img src='{html.escape(image)}'></td></tr>" for name, image in renders)
+ (out / "gallery.html").write_text("""<!doctype html><meta charset='utf-8'><title>HUMANOID-REST-X1</title>
+<style>body{font:15px system-ui;background:#171a1f;color:#eef;margin:24px}table{border-collapse:collapse}th{vertical-align:top;text-align:left;padding:12px}td{padding:8px}img{width:420px;border:1px solid #49515c}</style>
+<h1>HUMANOID-REST-X1 — semantic A-pose evidence</h1><p>Matched camera, scale, ground, and orientation. Labels name absolute anatomical targets.</p><table>""" + rows + "</table>", encoding="utf-8")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/render-humanoid-rest-x2-oracles.py b/scripts/render-humanoid-rest-x2-oracles.py
new file mode 100644
index 00000000..c8086d86
--- /dev/null
+++ b/scripts/render-humanoid-rest-x2-oracles.py
@@ -0,0 +1,35 @@
+"""Render evaluated Aetheris/Genesis OBJ columns with the REST-X2 Blender camera."""
+import argparse
+import importlib
+from pathlib import Path
+import sys
+import bpy
+import numpy as np
+from mathutils import Vector
+
+sys.path.insert(0,str(Path(__file__).parent))
+h=importlib.import_module('humanoid-rerig-x0')
+x2=importlib.import_module('humanoid-rest-x2')
+
+def main():
+ p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--aetheris',required=True);p.add_argument('--genesis',required=True)
+ a=p.parse_args(sys.argv[sys.argv.index('--')+1:]);out=Path(a.out)
+ if not out.is_absolute():out=h.ROOT/out
+ scene=h.setup_camera()
+ def absolute(value):
+ path=Path(value);return path if path.is_absolute() else h.ROOT/path
+ def load_obj(path,source):
+ vertices=[];faces=[]
+ for line in path.read_text(encoding='utf-8-sig').splitlines():
+ if line.startswith('v '):
+ x,y,z=map(float,line.split()[1:4]);vertices.append((-x,z,y) if source=='genesis' else (x,y,z))
+ elif line.startswith('f '):faces.append(tuple(int(v.split('/')[0])-1 for v in line.split()[1:]))
+ p=np.asarray(vertices);low=p.min(0);high=p.max(0);scale=1.75/max(high[2]-low[2],1e-9);p=(p-(low+high)/2)*scale;p[:,2]-=p[:,2].min()
+ return h.mesh(source+' '+path.stem,p,faces,h.collection(source+' display'))
+ for source,directory in [('aetheris',absolute(a.aetheris)),('genesis',absolute(a.genesis))]:
+ for path in sorted(directory.glob('*.obj')):
+ if path.stem not in {x['name'] for x in x2.canonical_corpus()}:continue
+ obj=load_obj(path,source);h.render(scene,obj,out/f'{source}--{path.stem}.png')
+ bpy.data.objects.remove(obj,do_unlink=True)
+
+if __name__=='__main__':main()
diff --git a/tools/Aetheris.Humanoid.X0/Program.cs b/tools/Aetheris.Humanoid.X0/Program.cs
index 2be82d40..19633ba5 100644
--- a/tools/Aetheris.Humanoid.X0/Program.cs
+++ b/tools/Aetheris.Humanoid.X0/Program.cs
@@ -19,6 +19,8 @@ static int Run(string[] args)
"compare-source-pose"=>SourcePoseComparison.Run(Required(args, "--input"), Required(args, "--source-pose"), Required(args, "--output")),
"reference-rig-antonia"=>ReferenceRigQualification.Run(Required(args, "--input"), Required(args, "--rig"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-x5")),
"golden-weights-antonia"=>GoldenWeightQualification.Run(Required(args, "--input"), Required(args, "--rig"), Required(args, "--weights"), Required(args, "--corpus"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-rerig-x1", "aetheris")),
+ "normalize-rest-antonia"=>RestPoseQualification.Run(Required(args, "--input"), Required(args, "--rig"), Required(args, "--weights"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-rest-x1")),
+ "qualify-rest-x2"=>RestX2Qualification.Run(Required(args, "--input"), Required(args, "--rig"), Required(args, "--source-weights"), Required(args, "--weights"), Required(args, "--blender-dir"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-rest-x2", "aetheris")),
"inspect"=>Inspect(args[1..]),
"morph"=>Morph(args[1..]),
"pose"=>Pose(args[1..]),
@@ -114,4 +116,4 @@ static string? Value(string[] args,string name){var i=Array.IndexOf(args,name);r
static string Required(string[] args,string name)=>Value(args,name)??throw new ArgumentException($"Missing {name}.");
static string Kebab(string s)=>string.Concat(s.Select((c,i)=>char.IsUpper(c)&&i>0?"-"+char.ToLowerInvariant(c):char.ToLowerInvariant(c).ToString()));
static int Fail(string message){Console.Error.WriteLine(message);Usage();return 1;}
-static void Usage()=>Console.WriteLine("Aetheris.Humanoid research tooling (X0 synthetic / X1 unpromoted / X2 constrained / X3 judgment / X4 source comparison / X5 reference rig)\n golden-weights-antonia --input <candidate.json> --rig <reference-rig.json> --weights <weights.json> --corpus <poses.json> [--out-dir <dir>]\n reference-rig-antonia --input <candidate.json> --rig <reference-rig.json> [--out-dir <dir>]\n compare-source-pose --input <candidate.json> --source-pose <source.json> --output <report.json>\n judge-antonia --input <candidate.json> [--out-dir <dir>]\n constrained-antonia --input <candidate.json> [--out-dir <dir>]\n adopt-antonia --source <Antonia-1.2.obj> --notice <original-README> [--out-dir <dir>]\n generate [--out-dir <dir>]\n inspect --input <canonical.json>\n morph --input <canonical.json> --output <variant.json> [--height <mm>] [--arm-length <delta-mm>] [--leg-length <delta-mm>] [--shoulder-width <delta-mm>]\n pose --input <canonical.json> --output <posed.obj> [--left-elbow-deg <deg>] [--left-shoulder-deg <deg>] [--left-hip-deg <deg>] [--left-knee-deg <deg>]\n sweep --input <canonical.json> --output <evidence.json>");
+static void Usage()=>Console.WriteLine("Aetheris.Humanoid research tooling (X0 synthetic / X1 adoption / X2 constrained / X3 judgment / X4 source comparison / X5 reference rig / REST-X1/X2 normalization)\n qualify-rest-x2 --input <candidate.json> --rig <reference-rig.json> --source-weights <source-rest-weights.json> --weights <A-pose-weights.json> --blender-dir <evidence-dir> [--out-dir <dir>]\n normalize-rest-antonia --input <candidate.json> --rig <reference-rig.json> --weights <weights.json> [--out-dir <dir>]\n golden-weights-antonia --input <candidate.json> --rig <reference-rig.json> --weights <weights.json> --corpus <poses.json> [--out-dir <dir>]\n reference-rig-antonia --input <candidate.json> --rig <reference-rig.json> [--out-dir <dir>]\n compare-source-pose --input <candidate.json> --source-pose <source.json> --output <report.json>\n judge-antonia --input <candidate.json> [--out-dir <dir>]\n constrained-antonia --input <candidate.json> [--out-dir <dir>]\n adopt-antonia --source <Antonia-1.2.obj> --notice <original-README> [--out-dir <dir>]\n generate [--out-dir <dir>]\n inspect --input <canonical.json>\n morph --input <canonical.json> --output <variant.json> [--height <mm>] [--arm-length <delta-mm>] [--leg-length <delta-mm>] [--shoulder-width <delta-mm>]\n pose --input <canonical.json> --output <posed.obj> [--left-elbow-deg <deg>] [--left-shoulder-deg <deg>] [--left-hip-deg <deg>] [--left-knee-deg <deg>]\n sweep --input <canonical.json> --output <evidence.json>");
diff --git a/tools/Aetheris.Humanoid.X0/RestPoseQualification.cs b/tools/Aetheris.Humanoid.X0/RestPoseQualification.cs
new file mode 100644
index 00000000..90f6c1ae
--- /dev/null
+++ b/tools/Aetheris.Humanoid.X0/RestPoseQualification.cs
@@ -0,0 +1,145 @@
+using System.Diagnostics;
+using System.Security.Cryptography;
+using System.Text.Json;
+using Aetheris.Humanoid;
+using Aetheris.Kernel.Core.Math;
+
+internal static class RestPoseQualification
+{
+ public static int Run(string input, string rig, string weightsPath, string output)
+ {
+ var candidate = JsonSerializer.Deserialize<AntoniaAdoptionCandidate>(File.ReadAllText(input), HumanoidArtifactIO.JsonOptions)
+ ?? throw new InvalidDataException("Missing Antonia candidate.");
+ var adoption = AntoniaReferenceRigAdapter.Adopt(candidate, rig);
+ var sourceSurface = ImportWeights(adoption.Surface, adoption.Skeleton, rig, weightsPath);
+ Directory.CreateDirectory(output);
+ Export(Path.Combine(output, "source-native-rest.obj"), sourceSurface,
+ sourceSurface.Vertices.Select(vertex => vertex.Position).ToArray(), "source-native rest; not canonical pose");
+
+ var normalizeClock = Stopwatch.StartNew();
+ var normalized = HumanoidRestPoseNormalizer.Normalize(sourceSurface, adoption.Skeleton);
+ normalizeClock.Stop();
+ Export(Path.Combine(output, "canonical-apose.obj"), normalized.Surface,
+ normalized.Surface.Vertices.Select(vertex => vertex.Position).ToArray(), "canonical A-pose rest");
+
+ var cases = new List<object>();
+ var allSemantic = true;
+ var solveMilliseconds = 0d;
+ var deformMilliseconds = 0d;
+ foreach (var (name, requests) in Corpus())
+ {
+ var solveClock = Stopwatch.StartNew();
+ var solve = HumanoidKinematicSolver.Solve(normalized.Skeleton,
+ new(name, normalized.Skeleton.SkeletonId, normalized.Skeleton.RestPoseId, 0, requests));
+ solveClock.Stop(); solveMilliseconds += solveClock.Elapsed.TotalMilliseconds;
+ if (solve.Pose is not { } posed) throw new InvalidOperationException(name + ": " + string.Join("; ", solve.Diagnostics.Select(d => d.Message)));
+ var deformClock = Stopwatch.StartNew();
+ var evaluated = HumanoidConstrainedSurface.Evaluate(normalized.Surface, normalized.Skeleton, 0, posed);
+ deformClock.Stop(); deformMilliseconds += deformClock.Elapsed.TotalMilliseconds;
+ var maximumSemanticResidual = posed.SemanticResiduals.Select(value => value.MaximumAbsoluteDegrees).DefaultIfEmpty().Max();
+ allSemantic &= maximumSemanticResidual <= .05;
+ var filename = name + (evaluated.Evidence.IsAdmissible ? ".screened.obj" : ".failed-diagnostic.obj");
+ Export(Path.Combine(output, filename), normalized.Surface, evaluated.Positions, "absolute semantic pose");
+ cases.Add(new { name, requested = requests, actual = requests.Select(request =>
+ HumanoidPoseSemantics.Measure(normalized.Skeleton, posed.GlobalTransforms, request.Joint)),
+ posed.SemanticResiduals, maximumSemanticResidualDegrees = maximumSemanticResidual,
+ maximumCenterResidualMm = posed.Residuals.Select(value => value.CenterMm).DefaultIfEmpty().Max(),
+ maximumLinkResidualMm = posed.Residuals.Select(value => value.LinkLengthMm).DefaultIfEmpty().Max(),
+ evaluated.Evidence, obj = filename });
+ }
+
+ var oldHash = HashPositions(sourceSurface.Vertices.Select(vertex => vertex.Position));
+ var newHash = HashPositions(normalized.Surface.Vertices.Select(vertex => vertex.Position));
+ var evidence = new
+ {
+ schema = "aetheris.humanoid.rest-x1.evidence.v1",
+ verdict = allSemantic ? "Canonical A-pose and Antonia semantic adapter qualified" : "Semantic residual exceeds tolerance",
+ identities = new { normalized.Surface.TopologyId, normalized.Surface.ConnectivityHash,
+ skeletonId = normalized.Skeleton.SkeletonId, normalized.SourceRestPoseId, normalized.RestPoseId,
+ CanonicalHumanoidRestPose.SemanticFrameId, CanonicalHumanoidRestPose.DeformationPolicyId },
+ topology = new { verticesBefore = sourceSurface.Vertices.Count, verticesAfter = normalized.Surface.Vertices.Count,
+ facesBefore = sourceSurface.Faces.Count, facesAfter = normalized.Surface.Faces.Count,
+ connectivityUnchanged = sourceSurface.ConnectivityHash == normalized.Surface.ConnectivityHash,
+ orderedConnectivityUnchanged = sourceSurface.Faces.Select(face => (face.A, face.B, face.C))
+ .SequenceEqual(normalized.Surface.Faces.Select(face => (face.A, face.B, face.C))) },
+ canonicalNeutral = new { shoulderAbductionDegrees = CanonicalHumanoidRestPose.ShoulderAbductionDegrees,
+ shoulderFlexionDegrees = 0, shoulderTwistDegrees = 0, elbowFlexionDegrees = 0,
+ hipFlexionDegrees = 0, hipAbductionDegrees = 0, kneeFlexionDegrees = 0,
+ CanonicalHumanoidRestPose.PalmOrientation, CanonicalHumanoidRestPose.FootOrientation },
+ sourceNeutral = normalized.SourceNeutral, normalizationResiduals = normalized.Residuals,
+ normalizedJoints = normalized.Skeleton.Joints.Select((joint, index) => new { index, joint.Kind, joint.ParentIndex, joint.GlobalBind }),
+ normalized.MaximumBindReconstructionMm, sourceRestPositionSha256 = oldHash,
+ canonicalRestPositionSha256 = newHash, sourceCandidateSha256 = Sha(input), referenceRigSha256 = Sha(rig),
+ weightsSha256 = Sha(weightsPath), solverVersion = HumanoidKinematicSolver.Version,
+ semanticToleranceDegrees = .05, allSemanticResidualsWithinTolerance = allSemantic,
+ cases,
+ boundaries = new[]
+ {
+ "Antonia is the only implemented source adapter in this evidence.",
+ "The imported Blender-cleaned weight field was generated in the former source rest and re-bound; A-pose weight regeneration is not yet qualified.",
+ "Mixamo and Genesis remain ignored local comparison assets and are not runtime dependencies.",
+ "The Antonia research candidate has no admitted morph channels or attachment sites; generic canonical morph/attachment preservation is covered by tests."
+ }
+ };
+ File.WriteAllText(Path.Combine(output, "evidence.json"), JsonSerializer.Serialize(evidence, HumanoidArtifactIO.JsonOptions));
+ var performance = new { normalizationMilliseconds = normalizeClock.Elapsed.TotalMilliseconds,
+ poseSolveTotalMilliseconds = solveMilliseconds, deformationTotalMilliseconds = deformMilliseconds };
+ File.WriteAllText(Path.Combine(output, "timings.json"), JsonSerializer.Serialize(performance, HumanoidArtifactIO.JsonOptions));
+ Console.WriteLine(JsonSerializer.Serialize(new { success = allSemantic, output, normalized.RestPoseId,
+ normalized.MaximumBindReconstructionMm, sourceRestPositionSha256 = oldHash, canonicalRestPositionSha256 = newHash,
+ cases = cases.Count, performance }, HumanoidArtifactIO.JsonOptions));
+ return allSemantic ? 0 : 2;
+ }
+
+ internal static HumanoidSurface ImportWeights(HumanoidSurface surface, HumanoidSkeleton skeleton, string rig, string path)
+ {
+ using var document = JsonDocument.Parse(File.ReadAllText(path));
+ var root = document.RootElement;
+ Require(root.GetProperty("schema").GetString() == "aetheris.humanoid.experimental-weights.v1", "Unsupported weight schema.");
+ Require(root.GetProperty("topologyId").GetString() == surface.TopologyId &&
+ root.GetProperty("connectivityHash").GetString() == surface.ConnectivityHash, "Weight topology mismatch.");
+ Require(root.GetProperty("referenceRigSha256").GetString() == Sha(rig), "Weight rig mismatch.");
+ var indices = skeleton.Joints.Select((joint, index) => (joint.Kind, index))
+ .ToDictionary(item => item.Kind.ToString(), item => item.index, StringComparer.Ordinal);
+ var imported = new Dictionary<string, JointWeight[]>(StringComparer.Ordinal);
+ foreach (var vertex in root.GetProperty("vertices").EnumerateArray())
+ {
+ var id = vertex.GetProperty("vertexId").GetString() ?? throw new InvalidDataException("Missing vertex ID.");
+ var weights = vertex.GetProperty("weights").EnumerateArray().Select(weight =>
+ {
+ var bone = weight.GetProperty("boneId").GetString() ?? throw new InvalidDataException("Missing bone ID.");
+ Require(indices.ContainsKey(bone), "Unknown bone " + bone);
+ return new JointWeight(indices[bone], weight.GetProperty("weight").GetDouble());
+ }).ToArray();
+ Require(weights.Length > 0 && Math.Abs(weights.Sum(weight => weight.Weight) - 1) <= CanonicalAdultStandardV1.WeightTolerance,
+ "Invalid weight sum for " + id);
+ Require(imported.TryAdd(id, weights), "Duplicate vertex " + id);
+ }
+ Require(surface.Vertices.All(vertex => imported.ContainsKey(vertex.Id)), "Vertex identity mismatch.");
+ return surface with { SkinWeights = surface.Vertices.Select((vertex, index) => new VertexSkinWeights(index, imported[vertex.Id])).ToArray() };
+ }
+
+ private static IEnumerable<(string Name, AnatomicalJointRequest[] Requests)> Corpus()
+ {
+ yield return ("canonical-neutral-apose", []);
+ foreach (var angle in new[] { 60d, 90, 120 }) yield return ($"shoulder-abduction-{angle}", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: angle)]);
+ yield return ("elbow-flexion-90", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 35), new(HumanoidJointKind.LeftElbow, 90)]);
+ foreach (var angle in new[] { 70d, 90 }) yield return ($"hip-flexion-{angle}", [new(HumanoidJointKind.LeftHip, angle)]);
+ yield return ("hip-abduction-45", [new(HumanoidJointKind.LeftHip, AbductionDegrees: 45)]);
+ yield return ("knee-flexion-90", [new(HumanoidJointKind.LeftKnee, 90)]);
+ yield return ("combined-pose", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 90), new(HumanoidJointKind.LeftElbow, 90),
+ new(HumanoidJointKind.LeftHip, 45, 15), new(HumanoidJointKind.LeftKnee, 45)]);
+ }
+
+ private static void Export(string path, HumanoidSurface surface, IReadOnlyList<Point3D> positions, string status)
+ {
+ using var writer = new StreamWriter(path, false, new System.Text.UTF8Encoding(false));
+ writer.WriteLine("# Antonia-derived REST-X1 research evidence; CC-BY-3.0 Olaf Delgado-Friedrichs; no endorsement; " + status);
+ foreach (var point in positions) writer.WriteLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));
+ foreach (var face in surface.Faces) writer.WriteLine($"f {face.A + 1} {face.B + 1} {face.C + 1}");
+ }
+ private static string HashPositions(IEnumerable<Point3D> positions) => Convert.ToHexStringLower(SHA256.HashData(
+ System.Text.Encoding.UTF8.GetBytes(string.Join("\n", positions.Select(point => FormattableString.Invariant($"{point.X:R},{point.Y:R},{point.Z:R}"))))));
+ private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
+ private static void Require(bool condition, string message) { if (!condition) throw new InvalidDataException("REST_X1: " + message); }
+}
diff --git a/tools/Aetheris.Humanoid.X0/RestX2Qualification.cs b/tools/Aetheris.Humanoid.X0/RestX2Qualification.cs
new file mode 100644
index 00000000..ce312360
--- /dev/null
+++ b/tools/Aetheris.Humanoid.X0/RestX2Qualification.cs
@@ -0,0 +1,112 @@
+using System.Diagnostics;
+using System.Security.Cryptography;
+using System.Text.Json;
+using Aetheris.Humanoid;
+using Aetheris.Kernel.Core.Math;
+
+internal static class RestX2Qualification
+{
+ public static int Run(string input, string rig, string sourceWeightsPath, string weightsPath, string blenderDirectory, string output)
+ {
+ var candidate = JsonSerializer.Deserialize<AntoniaAdoptionCandidate>(File.ReadAllText(input), HumanoidArtifactIO.JsonOptions)
+ ?? throw new InvalidDataException("Missing Antonia candidate.");
+ var adoption = AntoniaReferenceRigAdapter.Adopt(candidate, rig);
+ var sourceSurface = RestPoseQualification.ImportWeights(adoption.Surface, adoption.Skeleton, rig, sourceWeightsPath);
+ var normalized = HumanoidRestPoseNormalizer.Normalize(sourceSurface, adoption.Skeleton);
+ var surface = RestPoseQualification.ImportWeights(normalized.Surface, normalized.Skeleton, rig, weightsPath);
+ Directory.CreateDirectory(output);
+ var neutralPositions = HumanoidPosing.EvaluateVertices(surface, normalized.Skeleton,
+ new("rest-x2-bind-check", [], HumanoidTransform.Identity));
+ var bindMaximumMm = neutralPositions.Select((point, index) => (point-surface.Vertices[index].Position).Length).Max();
+ var parity = new List<object>();
+ var semantic = new List<object>();
+ var transforms = new List<object>();
+ var solveMs = 0d; var deformMs = 0d;
+ foreach (var (name, requests) in Corpus())
+ {
+ var watch = Stopwatch.StartNew();
+ var solve = HumanoidKinematicSolver.Solve(normalized.Skeleton,
+ new(name, normalized.Skeleton.SkeletonId, normalized.Skeleton.RestPoseId, 0, requests));
+ solveMs += watch.Elapsed.TotalMilliseconds;
+ if (solve.Pose is not { } pose) throw new InvalidOperationException(name + ": " + string.Join("; ", solve.Diagnostics.Select(x => x.Message)));
+ transforms.Add(new { pose = name,
+ localRotations = pose.PoseState.LocalRotations.Select(rotation => new { joint = rotation.Joint.ToString(),
+ x = rotation.LocalRotation.X, y = rotation.LocalRotation.Y, z = rotation.LocalRotation.Z, w = rotation.LocalRotation.W }),
+ joints = normalized.Skeleton.Joints.Select((joint, index) => new { joint = joint.Kind.ToString(), global = MatrixData(pose.GlobalTransforms[index]) }) });
+ watch.Restart();
+ var evaluated = HumanoidConstrainedSurface.Evaluate(surface, normalized.Skeleton, 0, pose);
+ var portableLbs = HumanoidPosing.EvaluateVertices(surface, normalized.Skeleton, pose.PoseState);
+ deformMs += watch.Elapsed.TotalMilliseconds;
+ var blenderPath = Path.Combine(blenderDirectory, $"blender-selected--{name}.positions.json");
+ if (File.Exists(blenderPath))
+ {
+ var blender = JsonSerializer.Deserialize<double[][]>(File.ReadAllText(blenderPath))
+ ?? throw new InvalidDataException("Missing Blender positions for " + name);
+ if (blender.Length != portableLbs.Count) throw new InvalidDataException("Parity vertex count mismatch.");
+ var distances = portableLbs.Select((point, i) => Distance(point, blender[i])).Order().ToArray();
+ parity.Add(new { pose = name, vertexRmsMm = Math.Sqrt(distances.Select(x => x*x).Average()),
+ p95Mm = Quantile(distances, .95), maximumMm = distances[^1], vertices = distances.Length });
+ }
+ semantic.Add(new { pose = name, pose.SemanticResiduals,
+ maximumSemanticResidualDegrees = pose.SemanticResiduals.Select(x => x.MaximumAbsoluteDegrees).DefaultIfEmpty().Max(), evaluated.Evidence.IsAdmissible });
+ Export(Path.Combine(output, name + ".obj"), surface, portableLbs);
+ }
+
+ var judgment = new List<object>();
+ foreach (var (name, request) in new[] { ("hip-flexion-70", new AnatomicalJointRequest(HumanoidJointKind.LeftHip, 70)),
+ ("hip-abduction-45", new AnatomicalJointRequest(HumanoidJointKind.LeftHip, AbductionDegrees: 45)) })
+ {
+ var solve = HumanoidKinematicSolver.Solve(normalized.Skeleton,
+ new(name, normalized.Skeleton.SkeletonId, normalized.Skeleton.RestPoseId, 0, [request]));
+ if (solve.Pose is not { } pose) throw new InvalidOperationException("Judgment pose failed.");
+ var context = HumanoidDeformationContext.Create(surface, normalized.Skeleton, 0, pose, request.Joint);
+ var decision = HumanoidDeformationJudgment.Evaluate(context, DeformationPolicy.HipV1);
+ judgment.Add(new { name, decision.IsSuccess, decision.WinnerId, decision.RunnerUpId, decision.TieBroken,
+ candidates = decision.Candidates.Select(x => new { x.Candidate.Id, x.Metrics }) });
+ }
+ var maximumParity = parity.Select(x => (double)x.GetType().GetProperty("maximumMm")!.GetValue(x)!).Max();
+ var maximumSemantic = semantic.Select(x => (double)x.GetType().GetProperty("maximumSemanticResidualDegrees")!.GetValue(x)!).Max();
+ var evidence = new { schema = "aetheris.humanoid.rest-x2.aetheris-parity.v1", normalized.RestPoseId,
+ surface.TopologyId, surface.ConnectivityHash, sourceWeightsSha256 = Sha(sourceWeightsPath), weightsSha256 = Sha(weightsPath), blenderDirectory,
+ bindMaximumMm, parity, semantic, judgmentPolicy = DeformationPolicy.HipV1, judgment,
+ performance = new { poseSolveTotalMilliseconds = solveMs, deformationTotalMilliseconds = deformMs },
+ accepted = maximumParity <= .01 && maximumSemantic <= .05 };
+ File.WriteAllText(Path.Combine(output, "evidence.json"), JsonSerializer.Serialize(evidence, HumanoidArtifactIO.JsonOptions));
+ File.WriteAllText(Path.Combine(output, "pose-transforms.json"), JsonSerializer.Serialize(transforms, HumanoidArtifactIO.JsonOptions));
+ Console.WriteLine(JsonSerializer.Serialize(new { evidence.accepted, maximumParityMm = maximumParity,
+ maximumSemanticResidualDegrees = maximumSemantic, output }, HumanoidArtifactIO.JsonOptions));
+ return evidence.accepted ? 0 : 2;
+ }
+
+ private static IEnumerable<(string, AnatomicalJointRequest[])> Corpus()
+ {
+ yield return ("canonical-apose", []);
+ yield return ("shoulder60", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 60)]);
+ yield return ("shoulder90", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 90)]);
+ yield return ("shoulder120", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 120)]);
+ yield return ("elbow45", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 35), new(HumanoidJointKind.LeftElbow, 45)]);
+ yield return ("elbow90", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 35), new(HumanoidJointKind.LeftElbow, 90)]);
+ yield return ("elbow120", [new(HumanoidJointKind.LeftShoulder, AbductionDegrees: 35), new(HumanoidJointKind.LeftElbow, 120)]);
+ yield return ("hip45", [new(HumanoidJointKind.LeftHip, 45)]);
+ yield return ("hip70", [new(HumanoidJointKind.LeftHip, 70)]);
+ yield return ("hip90", [new(HumanoidJointKind.LeftHip, 90)]);
+ yield return ("abduction30", [new(HumanoidJointKind.LeftHip, AbductionDegrees: 30)]);
+ yield return ("abduction45", [new(HumanoidJointKind.LeftHip, AbductionDegrees: 45)]);
+ yield return ("knee45", [new(HumanoidJointKind.LeftKnee, 45)]);
+ yield return ("knee90", [new(HumanoidJointKind.LeftKnee, 90)]);
+ yield return ("walking", [new(HumanoidJointKind.LeftHip, 30), new(HumanoidJointKind.LeftKnee, 35), new(HumanoidJointKind.RightShoulder, AbductionDegrees: 20)]);
+ yield return ("balance-kick", [new(HumanoidJointKind.LeftHip, 70), new(HumanoidJointKind.LeftKnee, 35), new(HumanoidJointKind.RightShoulder, AbductionDegrees: 55)]);
+ yield return ("reach", [new(HumanoidJointKind.LeftShoulder, 35, 105), new(HumanoidJointKind.LeftElbow, 25), new(HumanoidJointKind.RightShoulder, AbductionDegrees: 35)]);
+ }
+ private static double Distance(Point3D point, double[] other) => Math.Sqrt(Math.Pow(point.X-other[0],2)+Math.Pow(point.Y-other[1],2)+Math.Pow(point.Z-other[2],2));
+ private static double Quantile(double[] sorted, double q) => sorted[(int)Math.Clamp(Math.Ceiling(q*sorted.Length)-1,0,sorted.Length-1)];
+ private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
+ private static object MatrixData(System.Numerics.Matrix4x4 m) => new { m.M11,m.M12,m.M13,m.M14,m.M21,m.M22,m.M23,m.M24,m.M31,m.M32,m.M33,m.M34,m.M41,m.M42,m.M43,m.M44 };
+ private static void Export(string path, HumanoidSurface surface, IReadOnlyList<Point3D> points)
+ {
+ using var writer = new StreamWriter(path, false, new System.Text.UTF8Encoding(false));
+ writer.WriteLine("# HUMANOID-REST-X2 Aetheris imported A-pose weights; local evidence");
+ foreach (var point in points) writer.WriteLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));
+ foreach (var face in surface.Faces) writer.WriteLine($"f {face.A+1} {face.B+1} {face.C+1}");
+ }
+}