Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Experiment with Blender-native Antonia re-rig against X5 and local Mixamo oracle
Yuechen Li34fc13a60b0c
diff --git a/docs/release/HUMANOID-RERIG-X0.md b/docs/release/HUMANOID-RERIG-X0.mdnew file mode 100644index 00000000..b11cb1bf--- /dev/null+++ b/docs/release/HUMANOID-RERIG-X0.md@@ -0,0 +1,190 @@+# HUMANOID-RERIG-X0 — Blender re-rig experiment++**EXPERIMENTAL / BRANCH STUDY**++**Verdict: Useful but inconclusive. Moonshot success bar not met.**++Branch: `experiment/humanoid-blender-rerig`. This is not an Accepted release.++Conventional Blender tooling produces a visibly better Antonia baseline cheaply, especially at the hip and shoulder. It does **not** yet establish a mechanically clean whole-body rig across the requested corpus. Automatic weights remove much of X5's obvious groin stretching and shoulder collapse, but high-angle compression and transported-normal screening failures remain. Smoothing, Preserve Volume, and bounded local cleanup produce tradeoffs rather than a universal improvement. No new skin solver, runtime API, Judgment policy, helper skeleton, or topology change was needed or introduced.++The experiment ends in **Meaningful progression**: the native heat-weight failure is resolved, a usable reproducible rig exists, and the remaining blocker is isolated to the high-angle transition field. The evidence does not justify either promoting this field or declaring ordinary DCC tooling fundamentally insufficient. More artist-directed regional work may help; this bounded study does not estimate that effort.++## Cheapest working path++Use the X5 frames and canonical triangle mesh, temporarily scale their **data** tenfold for Blender's native bone-heat solve, restore the original coordinates/frames, and use an ordinary Armature modifier. This takes seconds rather than requiring another Aetheris deformation theory. Keep plain automatic LBS as the general comparison baseline; Preserve Volume is a useful hip-specific experiment, not the default winner across limbs.++The cheapest path to a **better** baseline is demonstrated. The cheapest path to a fully **good** rig is not yet demonstrated. The smallest next step is a bounded artist review of the remaining hip90, shoulder60/90, and hinge creases in this saved scene. If that yields a consistently good field, qualify a Blender-authored weight import against frozen X5 frames and topology. Do not redesign the runtime or adopt Mixamo weights on this evidence.++## Inputs, ownership, and reproducibility++All generated scenes, weights, skeleton dumps, metrics, images, and the HTML gallery live under ignored `artifacts/local/humanoid-rerig-x0/`. The raw FBX remains in the user's Downloads directory. Only the scripts and this compact report belong in Git. Existing X5 source, release records, reference fixture, runtime code, and generated baseline artifacts are unchanged.++| Input | Identity |+|---|---|+| Canonical Antonia candidate | SHA-256 `af45c535ab21d93ae2c23f7a63f71925f3c6cfc6a68e5af9c04e1ab0033834dd` |+| X5 reference skeleton | SHA-256 `0647f681f67043610e8829fff20ca29901648b3c3245b589f2942ba453e13148` |+| Mixamo oracle | `Female Standing Pose (2).fbx`, 1,400,944 bytes; SHA-256 `53038e7c78816b25df1bb2412d33b8d2d1530de5f02a785352c529dd2de376d9` |+| Blender | 5.2.2 LTS, build `d13f752e3b9c` |+| Canonical surface | 27,193 vertices, 54,224 triangles; connectivity `2e2f787499ba2da1f02bab14f352b86070938fbb5d7cae60e8bd7d59edb2b7a2` |++The X5 artifact supplies all 55 semantic frames and hierarchy, including its corrected hips. Its pinned CharMorph provenance remains authoritative: `char.blend` hash `4bc468c44c8ca7c6971cac3692c5d670b09f6723687e89cd49f258c2a8251c69`, metarig hash `eee2e7185331595fb0912e03aace583d7e02c5a467a04f1af0b786e2ecf687e2`. Original source files are not reinterpreted or executed. Antonia attribution remains Olaf Delgado-Friedrichs / Antonia Polygon, CC-BY-3.0; the existing research provenance boundary still applies.++The scene separates `ANTONIA_CANONICAL`, `X5_REFERENCE_RIG`, `EXPERIMENTAL_RIG`, `X5_CURRENT_DEFORMATION`, and `MIXAMO_REFERENCE_LOCAL`. There are 55 experimental bones: 54 deform bones and the non-deforming synthetic Root. No Rigify controls, twist helpers, constraints, or manual joint moves were added. The reference rig is a separate hidden object, available for inspection.++Run from the repository root, after generating the existing X1 candidate and X5 evidence:++```powershell+$blender = 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe'+$mixamo = Join-Path $env:USERPROFILE 'Downloads/Female Standing Pose (2).fbx'+& $blender --background --factory-startup --disable-autoexec --python-exit-code 1 `+ --python scripts/humanoid-rerig-x0.py -- `+ --mixamo $mixamo++# Independent rebuild without rendering, for weight/metric comparison:+& $blender --background --factory-startup --disable-autoexec --python-exit-code 1 `+ --python scripts/humanoid-rerig-x0.py -- `+ --mixamo $mixamo `+ --out artifacts/local/humanoid-rerig-x0/replay --no-render++# Optional local gallery; Python requires Pillow:+python scripts/summarize-humanoid-rerig-x0.py+```++The script verifies that the existing X5 evidence hashes match the candidate and skeleton. Embedded Blender scripts are disabled; FBX animation is not imported. Output paths are restricted to ignored `artifacts/local/`. Reproduction depends on the admitted local candidate and the supplied local FBX; this is intentionally not a self-contained distributable asset package.++## Bounded passes and effort++| Pass | Exact operation | Result |+|---|---|---|+| A, initial | `ARMATURE_AUTO`, native meter-scale data | Bone heat warning; all 27,193 vertices unweighted, despite `FINISHED` return |+| A, diagnostic | Disable eye deformation for native solve | 418 vertices remain unweighted; rejected |+| A, retained | All mapped deform bones; temporarily scale mesh and bone data ×10; native heat; restore original positions/frames | Every vertex weighted; solve approximately 0.9 seconds in the isolated probe |+| B | A + Normalize All + native Smooth, factor 0.5, three iterations + Normalize All | Reduces abrupt weight changes, but worsens several extreme-pose metrics |+| C, volume | Normalize A; Armature Preserve Volume | Hip70 clears this study's screen; knee/elbow extrema worsen |+| C, corrective | C volume + native length-weighted Corrective Smooth, factor 0.5, five iterations, limited to mixed-weight body transitions | Mixed improvements; extra reversals and compression elsewhere; not retained |+| C, local | Normalize A; average exact semantic mirror partners; one native smoothing iteration at factor 0.25 within 80 mm of knees/elbows; normalize | Better symmetry and some extrema, but no consistent whole-body advantage |++Manual weight-paint strokes: **0**. Manual per-vertex assignments: **0**. Joint edits: **0**. The scale workaround, mirror averaging, masks, and smoothing are scripted. No source pose reproduction, face polish, topology surgery, or Rigify pass was attempted: control generation would not resolve the observed weight-field tradeoffs.++The operations are standard Blender facilities: [automatic Armature Deform weights](https://docs.blender.org/manual/en/5.0/animation/armatures/skinning/parenting.html) and [Armature Preserve Volume](https://docs.blender.org/manual/en/latest/modeling/modifiers/deform/armature.html). The scale workaround is an observation from this experiment, not a claimed Blender guarantee.++The saved `experimental.blend` opens in neutral with Pass A visible. Alternate fields are local JSON and can be replayed with `--pipeline pass-b`, `pass-c-volume`, `pass-c-corrective`, or `pass-c-local`. A separate FBX/glTF export was unnecessary for the question being tested; the Blender scene and dumps preserve the experiment without an additional exporter changing indices or triangulation.++## Mixamo oracle observations++The supplied binary FBX imports as one 65-bone armature and one weighted mesh. Blender's interpreted hierarchy, rest matrices, inverse rest-world bind matrices, object matrices, and vertex groups are dumped to local-only inventory files. These are inspection results from Blender's importer, not a custom FBX parser or a reconstruction of Mixamo's service.++The imported coordinate frame is −Y-up/+Z-forward. A proper axis rotation and uniform approximately 0.1 scale align it to canonical +Z-up/+Y-forward. After alignment, nearest-surface error is below 0.001 mm, with 27,193 unique nearest matches; indexwise error is also below 0.001 mm. This establishes strong positional correspondence, **not** a claim of identical FBX triangulation. Mixamo metrics use its own Blender loop triangles and nearest-canonical region labels. No direct posed-vertex delta is used to judge differently placed skeletons.++Major-joint correspondence uses `Hips`, `Spine/Spine1/Spine2`, `Neck/Head`, `Left/RightShoulder`, `Arm`, `ForeArm`, `Hand`, `UpLeg`, `Leg`, and `Foot`. Numeric differences below are after alignment. Frame angles are shortest quaternion angles; different bone roll conventions can produce large frame angles without an anatomical axis error.++| X5 joint → Mixamo counterpart | Center difference mm | Frame difference degrees |+|---|---:|---:|+| Pelvis → Hips | 148.62 | 11.29 |+| SpineLower → Spine | 104.69 | 7.68 |+| SpineMid → Spine1 | 90.45 | 1.39 |+| Chest → Spine2 | 90.37 | 4.75 |+| Neck → Neck | 45.36 | 14.32 |+| Head → Head | 45.76 | 0.29 |+| LeftClavicle → LeftShoulder | 47.09 | 179.32 |+| LeftShoulder → LeftArm | 25.76 | 101.41 |+| LeftElbow → LeftForeArm | 12.73 | 83.09 |+| LeftWrist → LeftHand | 9.84 | 80.86 |+| LeftHip → LeftUpLeg | 39.09 | 179.76 |+| LeftKnee → LeftLeg | 33.51 | 175.77 |+| LeftAnkle → LeftFoot | 5.78 | 175.13 |++The local mapping file contains both sides and signed displacement vectors. Right-side distances are comparable. Large trunk differences partly reflect different semantic subdivisions and pelvis origins; they are not evidence that either rig should simply replace the other. Mixamo has end/finger bones but no identified limb twist-helper chain. It is not uniformly better: shoulder60 is stronger, whereas the hip70/90 edge extrema are worse than Blender A. No Mixamo weights, helpers, or joint centers were transferred to the experimental rig.++## Weight inspection++Influence counts use a `1e-4` weight threshold. Adjacency gradient is the L1 change in the full weight vector along an edge, not a physical-distance derivative. Detailed per-region means, influence neighborhoods, gradients, normalization, symmetry, and opposite-side influence diagnostics are in `weight-inspection.json`.++| Field | Maximum influences | Mean influences | p95 edge weight L1 | Maximum normalization error |+|---|---:|---:|---:|---:|+| X1 weights used by X5 | 5 | 1.900 | 0.378 | 3.4e−16 |+| Blender A | 6 | 2.461 | 0.313 | 0.1074 |+| Blender B | 7 | 2.823 | 0.293 | 1.8e−7 |+| Mixamo | 8 | 2.343 | 0.304 | 1.5e−7 |++All retained fields weight every vertex. Blender's Armature modifier normalizes the raw A group weights during evaluation; raw A group sums are not themselves export-ready normalized attachment data. C volume explicitly normalizes them. A's p95 mirror-partner L1 difference is 0.0273, with an outlier maximum 1.0074; global smoothing lowers the maximum but raises p95 asymmetry to 0.0772. The local mirror pass addresses that outlier, but does not establish better deformation. More influences alone do not explain quality.++The region distributions expose a concrete difference. In the canonical pelvis region, X5 averages 91.5% Pelvis and only 2.6% each hip; Blender A averages 38.2% Pelvis and approximately 27.2% each hip. Mixamo averages 27.6% Hips and approximately 36% each upper leg. In the left shoulder region, X5 averages 92.8% clavicle; Blender spreads influence across clavicle (30.5%), upper arm (26.8%), chest (26.2%), and mid-spine (11.3%). Mixamo likewise distributes substantial weight across upper arm and trunk. These are raw-group regional averages, not an instruction to copy another rig's weights. Pelvis adjacency p95 L1 falls from 0.378 in X5 to 0.229 in Blender and 0.233 in Mixamo, indicating less abrupt local field transitions.++Cross-body diagnostics deserve review rather than automatic deletion: Blender A has 81 left-shoulder-region vertices above 1% opposite-side weight, with a maximum 9.57%, chiefly involving the opposite clavicle. Mixamo has 75 left-thigh-region vertices above 1%, maximum 17.46%. Neither field is a universal ideal. Region borders are semantic labels, not proof that every cross-border contribution is anatomically wrong.++## Pose equivalence, metrics, and limits++All 16 X5 requests are read from its evidence: neutral; hip flexion 30/45/70/90; hip abduction 15/30/45; knee flexion 45/90; shoulder abduction 30/60/90; elbow flexion 45/90/120. Three explicit combinations add stride, raised arms, and one-leg balance. Angles are **deltas from the authored rest posture**, so shoulder90 raises an already extended arm overhead. They are not clinical angles from arms-down.++Ball swings use the X5 global anatomical X/Y axes transformed into each bone's rest frame, with side sign; hinges use `cross(child direction, forward)` and the existing knee sign. Mixamo uses the same rule against its own aligned rest frames, not identical Euler channels or eyeballed rotations. No clipping or pose fitting is applied. The original 16 X5 comparison images use the actual existing X5 exported meshes. The three added X5 combinations use Blender LBS replay of X5 weights and frames, explicitly labeled in metrics; they are not claimed as new .NET solver qualification. Native replay matches the real single-pose X5 meshes within approximately 0.0011 mm.++All pipelines share one orthographic camera, projection, material, studio lighting, and image size. Separate side views resolve the folded-knee occlusion. There are 19 × 7 main images, plus side views and fresh-agent evidence.++Metric definitions are identical across pipelines: edge ratio is posed/rest; bidirectional distortion is `max(r,1/r)`; area ratio is posed/rest triangle area. The orientation count compares the posed normal to the rest normal transported by the face's dominant summed influence. It is a **reversal proxy**, not a certified inverted-volume or self-intersection count. A flagged triangle has a >4× bidirectional edge ratio, <1e−6 area ratio, or a reversal proxy. Self-intersection is not qualified. Whole-body p95 is often near 1 because most of the body does not move; region statistics and extrema are retained rather than hiding local failures in that aggregate.++| Pose | X5 max distortion / reversal proxy | Blender A | Mixamo |+|---|---:|---:|---:|+| Hip70 | 6.88 / 118 | **4.23 / 1** | 12.20 / 23 |+| Hip90 | 17.92 / 155 | **9.44 / 40** | 20.94 / 94 |+| Abduction45 | 4.23 / 18 | **2.25 / 0** | 4.80 / 0 |+| Knee90 | 9.10 / 51 | **5.46 / 26** | 9.12 / 40 |+| Shoulder60 | 5.81 / 27 | 9.63 / 6 | **2.89 / 0** |+| Shoulder90 | 8.93 / 75 | 10.48 / 21 | 12.90 / 4 |+| Elbow90 | 5.19 / 17 | 4.07 / 15 | 5.78 / 2 |++These counts are recomputed with one common transported-normal proxy; do not substitute X5's differently defined source-comparison normal counts. Hip70 flagged triangles fall from 169 to 3 with A, and to 0 with C volume. Hip90 remains 92 flagged triangles with A; C volume reduces that to 8. C volume reaches hip70 distortion 3.70 with zero reversal proxies but raises knee90 distortion to 9.09. C corrective lowers shoulder90 distortion to 4.49 but leaves 20 reversal proxies and worsens knee90 to 12.31. B raises hip90 to 12.40 and elbow90 to 9.08. No tested option dominates.++## Visual rubric++Assistant review, not user/artist signoff. `NeedsReview` means continuity is retained but crease, volume, or compression remains unresolved. A metric failure is reported independently of visible plausibility; proxy failures are not automatically proof of a visible fold-through.++| Pose/region | X5 visual | Blender A visual | Mixamo visual | Evidence interpretation |+|---|---|---|---|---|+| Neutral | Pass | Pass | Pass | Surface correspondence retained |+| Hip30 | NeedsReview | Pass | Pass | Low-angle continuity retained |+| Hip45 | Fail | NeedsReview | NeedsReview | X5 groin pull; improved but creased transition in both DCC fields |+| Hip70 groin/crease | Fail | NeedsReview | NeedsReview | A substantially reduces webbing; residual local crease |+| Hip90 glute/hip | Fail | NeedsReview | NeedsReview | Continuous thigh, but compressed crease; no certified collision result |+| Abduction15 / 30 | NeedsReview | Pass | Pass | No gross webbing observed at these lower angles |+| Abduction45 | Fail | Pass | NeedsReview | A clears local screen and visibly separates the leg |+| Knee45 | NeedsReview | NeedsReview | NeedsReview | No separation; hinge shape still warrants regional inspection |+| Knee90 | Fail | NeedsReview | NeedsReview | A retains limb continuity; pointed/strong hinge crease remains |+| Shoulder30 | NeedsReview | Pass | Pass | No gross collapse observed |+| Shoulder60 | Fail | NeedsReview | Pass | Mixamo has the strongest screen here |+| Shoulder90 axilla/deltoid | Fail | NeedsReview | NeedsReview | Large X5 collapse visibly reduced; no scapular/clavicle coupling |+| Elbow45 | NeedsReview | NeedsReview | NeedsReview | Continuous silhouette; no volume qualification |+| Elbow90 / 120 | NeedsReview | NeedsReview | NeedsReview | Continuous limb; sharp crease/volume transition still visible |+| Combined stride | NeedsReview | NeedsReview | NeedsReview | Continuous whole-body stance; local hinge quality remains unqualified |+| Combined raised arms / balance | Fail | NeedsReview | NeedsReview | A remains connected; high-angle local defects persist |+| Wrists / ankles | NeedsReview | NeedsReview | NeedsReview | Carried through corpus; independent wrist/ankle bending was not requested or qualified |++Lower-angle cases and all combinations are included in the local gallery; no claim of facial quality is made. No gross candy-wrapper twist was visible in the reviewed corpus, but the corpus does not include a dedicated axial-twist sweep.++Local visual evidence: [full gallery](../../artifacts/local/humanoid-rerig-x0/comparison.html), [gate comparisons](../../artifacts/local/humanoid-rerig-x0/comparison-gates.png), [extreme comparisons](../../artifacts/local/humanoid-rerig-x0/comparison-extremes.png), [remaining required views](../../artifacts/local/humanoid-rerig-x0/comparison-remaining.png). Each sheet shows X5, Blender A, and Mixamo with matched projection. Images remain ignored local evidence, not redistributed Mixamo assets.++## Integrity and independent replay++Canonical vertex ordering and all 54,224 triangle index tuples are preserved exactly. No import/export remapping is used for the experimental mesh. Neutral evaluated reconstruction error is approximately 0.000365 mm. Maximum X5-vs-Blender rest-matrix element difference is 3.42e−6, reflecting Blender float bone reconstruction; no intentional center or frame changes occurred. `integrity.json`, the skeleton dump, and the pinned input hashes retain this boundary. Blender may recompute shading normals; index/topology identity does not claim unchanged shading-normal serialization.++Independent full rebuilds reproduce A, B, and local-cleanup weight JSON, the pose corpus, all metric JSON, and integrity JSON byte-for-byte. The `.blend` container itself is not claimed byte-stable. Explicit sorted group assignment avoids Python set-order effects in the local cleanup. Saved-scene replay of all 19 poses measures maximum parent-socket center residual 0.000374 mm and link-length residual 0.000158 mm. Thus the residual failure is surface deformation, not a return to guessed pivots or detached joint centers.++A fresh agent received only the scene, corpus, and local scripts, with no Aetheris implementation internals. It successfully rendered hip70, knee90, and shoulder90 with exit code 0, and visually inspected all three. It correctly noted that shoulder90 is a rest-relative delta and that the initial view partially occludes the folded knee; side views were then added. Replay requires no original source mesh or FBX for the default saved Pass A.++```powershell+& $blender --background --disable-autoexec --python-exit-code 1 `+ --python scripts/replay-humanoid-rerig-x0.py -- `+ --scene artifacts/local/humanoid-rerig-x0/experimental.blend `+ --corpus artifacts/local/humanoid-rerig-x0/pose-corpus.json `+ --out artifacts/local/humanoid-rerig-x0/fresh-agent `+ --poses hip-flexion-70 knee-flexion-90 shoulder-abduction-90 --pipeline pass-a+```++Validation: full solution build passed (seven warnings); full active .NET suite ran, with 3,215 passed and one server display-budget test failure under concurrent load. `Ftc07ViewMaterialization_FailsWithDiagnosticInsteadOfHang` passed on isolated rerun. All 63 humanoid tests passed. Aetheris.CLI help was checked; it has no humanoid re-rig command, so the existing X5 research artifacts provide the domain baseline rather than an invented CLI capability.++## Promotion boundary++Do not promote this scene or its weight field yet. It includes the local Mixamo reference collection and remains research-only. No Mixamo raw asset or dense generated skeleton/weight data is embedded in this report or tracked as SDK content. No model training, service probing, proprietary algorithm reconstruction, or runtime dependency was introduced. Any later proposal to promote Mixamo-derived skeleton/weights requires a separate license review first.++The useful conclusion is concrete: **Blender heat weights are a cheap, reproducible improvement over the old field, but small generic cleanup has not yet produced one consistently good full-corpus rig.** Keep this DCC baseline and its evidence; do not return to inventing a new solver merely because a few extreme creases remain.diff --git a/scripts/humanoid-rerig-x0.py b/scripts/humanoid-rerig-x0.pynew file mode 100644index 00000000..43ca9633--- /dev/null+++ b/scripts/humanoid-rerig-x0.py@@ -0,0 +1,478 @@+"""Local, experimental Blender study. No canonical files or Mixamo assets are written to Git.++Run with Blender --background --factory-startup --disable-autoexec --python-exit-code 1+--python scripts/humanoid-rerig-x0.py -- --mixamo <local.fbx> [--no-render].+"""+import argparse+import hashlib+import json+import math+from pathlib import Path+import sys+import time++import bpy+import numpy as np+from mathutils import Matrix, Quaternion, Vector++ROOT = Path(__file__).resolve().parents[1]+++def read(path):+ return json.loads(Path(path).read_text(encoding='utf-8-sig'))+++def write(path, value):+ Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + '\n', encoding='utf-8')+++def sha(path):+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()+++def matrix(value):+ m = Matrix([[value[f'm{c+1}{r+1}'] for c in range(4)] for r in range(4)])+ m.translation /= 1000+ return m+++def collection(name):+ c = bpy.data.collections.new(name)+ bpy.context.scene.collection.children.link(c)+ return c+++def mesh(name, positions, faces, coll):+ data = bpy.data.meshes.new(name)+ data.from_pydata(positions, [], faces)+ data.update()+ obj = bpy.data.objects.new(name, data)+ coll.objects.link(obj)+ for p in data.polygons:+ p.use_smooth = True+ return obj+++def active(obj):+ bpy.ops.object.select_all(action='DESELECT')+ obj.hide_set(False)+ obj.select_set(True)+ bpy.context.view_layer.objects.active = obj+++def make_rig(artifact, coll):+ data = bpy.data.armatures.new('X5 exact rest frames')+ obj = bpy.data.objects.new('X5_DEFORM', data)+ coll.objects.link(obj)+ active(obj)+ bpy.ops.object.mode_set(mode='EDIT')+ sources = {s['sourceJointId']: s for s in artifact['sourceJoints']}+ for j in artifact['canonicalJoints']:+ b = data.edit_bones.new(j['canonicalJoint'])+ b.head = (0, 0, 0)+ b.tail = (0, .05, 0)+ b.matrix = matrix(j['globalRestCanonical'])+ if j['sourceJointId']:+ s = sources[j['sourceJointId']]+ b.length = (Vector(tuple(s['tailCanonicalMm'][k] for k in 'xyz')) -+ Vector(tuple(s['headCanonicalMm'][k] for k in 'xyz'))).length / 1000+ b.use_deform = j['canonicalJoint'] != 'Root'+ for j in artifact['canonicalJoints']:+ if j['canonicalParent']:+ data.edit_bones[j['canonicalJoint']].parent = data.edit_bones[j['canonicalParent']]+ bpy.ops.object.mode_set(mode='OBJECT')+ obj.show_in_front = True+ return obj+++def weights(obj):+ names = [g.name for g in obj.vertex_groups]+ return [{names[g.group]: float(g.weight) for g in v.groups if g.weight > 1e-8}+ for v in obj.data.vertices]+++def assign(obj, field):+ obj.vertex_groups.clear()+ groups = {name: obj.vertex_groups.new(name=name) for name in sorted({n for w in field for n in w})}+ for i, w in enumerate(field):+ for n, value in sorted(w.items()):+ groups[n].add([i], value, 'REPLACE')+++def positions(obj):+ evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())+ return np.array([tuple(evaluated.matrix_world @ v.co) for v in evaluated.data.vertices])+++def pose(rig, requests, mapping=None):+ for b in rig.pose.bones:+ b.matrix_basis = Matrix.Identity(4)+ mapping = mapping or {b.name: b.name for b in rig.data.bones}+ for r in requests:+ kind = r['joint']+ b = rig.pose.bones[mapping[kind]]+ rest = (rig.matrix_world @ b.bone.matrix_local).to_3x3().normalized()+ sign = 1 if kind.startswith('Left') else -1+ if kind.endswith(('Knee', 'Elbow')):+ end = kind.replace('Knee', 'Ankle').replace('Elbow', 'Wrist')+ direction = (rig.matrix_world @ rig.data.bones[mapping[end]].head_local -+ rig.matrix_world @ b.bone.head_local)+ axis = direction.cross(Vector((0, 1, 0))).normalized()+ if kind.endswith('Knee'):+ axis.negate()+ q = Quaternion(rest.inverted() @ axis, math.radians(r['flexionDegrees']))+ else:+ swing = Vector((r['flexionDegrees'], sign*r['abductionDegrees'], 0))+ q = Quaternion(rest.inverted() @ swing.normalized(), math.radians(swing.length)) if swing.length else Quaternion()+ q = q @ Quaternion(rest.inverted() @ Vector((0, 0, -1)), math.radians(sign*r.get('twistDegrees', 0)))+ b.rotation_mode = 'QUATERNION'+ b.rotation_quaternion = q+ bpy.context.view_layer.update()+++def metric(rest, posed, triangles, region_ids=None, transported=None):+ t = np.asarray(triangles, dtype=int)+ edges = np.unique(np.sort(np.concatenate((t[:, [0, 1]], t[:, [1, 2]], t[:, [2, 0]])), axis=1), axis=0)+ before = np.linalg.norm(rest[edges[:, 0]]-rest[edges[:, 1]], axis=1)+ after = np.linalg.norm(posed[edges[:, 0]]-posed[edges[:, 1]], axis=1)+ ratio = after / np.maximum(before, 1e-12)+ distortion = np.maximum(ratio, 1 / np.maximum(ratio, 1e-12))+ n0 = np.cross(rest[t[:, 1]]-rest[t[:, 0]], rest[t[:, 2]]-rest[t[:, 0]])+ n1 = np.cross(posed[t[:, 1]]-posed[t[:, 0]], posed[t[:, 2]]-posed[t[:, 0]])+ area = np.linalg.norm(n1, axis=1)/np.maximum(np.linalg.norm(n0, axis=1), 1e-12)+ expected = n0 if transported is None else np.einsum('nij,nj->ni',transported,n0)+ reversal = np.sum(expected*n1, axis=1) < 0+ face_ratios = []+ for a, b in ((0, 1), (1, 2), (2, 0)):+ q = np.linalg.norm(posed[t[:, a]]-posed[t[:, b]], axis=1)/np.maximum(np.linalg.norm(rest[t[:, a]]-rest[t[:, b]], axis=1), 1e-12)+ face_ratios.append(np.maximum(q, 1/np.maximum(q, 1e-12)))+ flagged = (np.max(face_ratios, axis=0)>4) | (area<1e-6) | reversal+ result = dict(minEdgeRatio=float(ratio.min()), maxEdgeRatio=float(ratio.max()),+ p95EdgeDistortion=float(np.quantile(distortion, .95)), maxEdgeDistortion=float(distortion.max()),+ minAreaRatio=float(area.min()), maxAreaRatio=float(area.max()),+ normalReversalProxy=int(reversal.sum()), flaggedTriangles=int(flagged.sum()),+ collapsedTriangles=int((area<1e-6).sum()))+ if region_ids is not None:+ result['regions'] = {name: metric(rest, posed, t[np.asarray(region_ids)==name], transported=None if transported is None else transported[np.asarray(region_ids)==name])+ for name in sorted(set(region_ids))}+ return result+++def normal_transport(rig, field, triangles):+ rotations = {b.name: np.array((rig.matrix_world @ b.matrix @ b.bone.matrix_local.inverted() @ rig.matrix_world.inverted()).to_3x3()) for b in rig.pose.bones}+ result=[]+ for tri in triangles:+ sums={}+ for i in tri:+ for name,value in field[i].items():+ sums[name]=sums.get(name,0)+value+ dominant=max(sorted(sums),key=sums.get)+ result.append(rotations[dominant])+ return np.array(result)+++def weight_stats(obj, field, regions=None):+ names = sorted({n for w in field for n in w})+ dense = np.array([[w.get(n, 0) for n in names] for w in field])+ edges = np.array([tuple(e.vertices) for e in obj.data.edges])+ gradient = np.sum(np.abs(dense[edges[:, 0]]-dense[edges[:, 1]]), axis=1)+ counts = (dense>1e-4).sum(axis=1)+ result = dict(vertices=len(field), maxInfluences=int(counts.max()), meanInfluences=float(counts.mean()),+ unweighted=int((dense.sum(axis=1)<1e-6).sum()),+ maxNormalizationError=float(np.max(np.abs(dense.sum(axis=1)-1))),+ p95EdgeWeightL1=float(np.quantile(gradient,.95)), maxEdgeWeightL1=float(gradient.max()))+ if regions:+ result['regions'] = {}+ for region in sorted(set(regions)):+ mask = np.array(regions)==region+ emask = mask[edges[:,0]] | mask[edges[:,1]]+ mean = dense[mask].mean(axis=0)+ result['regions'][region] = dict(meanInfluences=float(counts[mask].mean()),+ p95EdgeWeightL1=float(np.quantile(gradient[emask], .95)),+ meanWeights={n:float(v) for n,v in zip(names,mean) if v>.001})+ opposite='Right' if region.startswith('Left') else 'Left' if region.startswith('Right') else None+ if opposite:+ cross=dense[mask][:,[i for i,n in enumerate(names) if opposite in n]].sum(axis=1)+ result['regions'][region]['oppositeSideWeightMax']=float(cross.max())+ result['regions'][region]['verticesAboveOnePercentOppositeWeight']=int((cross>.01).sum())+ return result+++def setup_camera():+ scene = bpy.context.scene+ scene.render.engine = 'BLENDER_WORKBENCH'+ scene.display.shading.light = 'STUDIO'+ scene.display.shading.color_type = 'SINGLE'+ scene.display.shading.single_color = (.58,.63,.68)+ scene.display.shading.show_cavity = True+ scene.display.shading.cavity_type = 'BOTH'+ scene.render.resolution_x = 800+ scene.render.resolution_y = 900+ scene.render.resolution_percentage = 100+ data = bpy.data.cameras.new('Comparison orthographic')+ camera = bpy.data.objects.new('Comparison orthographic', data)+ scene.collection.objects.link(camera)+ scene.camera = camera+ data.type = 'ORTHO'+ data.ortho_scale = 2.65+ camera.location = (2.8, 5, 1.8)+ camera.rotation_euler = (Vector((0,0,1.12))-camera.location).to_track_quat('-Z','Y').to_euler()+ return scene+++def render(scene, obj, path):+ for o in scene.objects:+ if o.type == 'MESH':+ o.hide_render = o != obj+ scene.render.filepath = str(path)+ bpy.ops.render.render(write_still=True)+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument('--mixamo', required=True)+ parser.add_argument('--out', default=str(ROOT/'artifacts/local/humanoid-rerig-x0'))+ parser.add_argument('--no-render', action='store_true')+ args = parser.parse_args(sys.argv[sys.argv.index('--')+1:])+ out = Path(args.out).resolve()+ if not out.is_relative_to((ROOT/'artifacts/local').resolve()):+ raise ValueError('This local-only study must write beneath ignored artifacts/local/.')+ out.mkdir(parents=True, exist_ok=True)+ bpy.ops.object.select_all(action='SELECT')+ bpy.ops.object.delete(use_global=False)+ candidate_path = ROOT/'artifacts/local/humanoid-x1/antonia-adoption-candidate.json'+ rig_path = ROOT/'fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json'+ candidate, artifact = read(candidate_path), read(rig_path)+ baseline_evidence=read(ROOT/'artifacts/local/humanoid-x5/evidence.json')+ if baseline_evidence['sourceCandidateSha256']!=sha(candidate_path) or baseline_evidence['referenceRigSha256']!=sha(rig_path):+ raise RuntimeError('X5 evidence does not match the candidate/reference rig; regenerate X5 before comparison.')+ surface = candidate['sourcePoseSurface']+ verts = [tuple(v['position'][k]/1000 for k in 'xyz') for v in surface['vertices']]+ faces = [tuple(f[k] for k in ('a','b','c')) for f in surface['faces']]+ regions = [v['region'] for v in surface['vertices']]+ face_regions = [f['region'] for f in surface['faces']]+ canonical = mesh('ANTONIA_CANONICAL', verts, faces, collection('ANTONIA_CANONICAL'))+ rig = make_rig(artifact, collection('EXPERIMENTAL_RIG'))+ reference = rig.copy()+ reference.data = rig.data.copy()+ reference.name = 'X5_REFERENCE_RIG'+ collection('X5_REFERENCE_RIG').objects.link(reference)+ reference.hide_set(True)+ experiment = mesh('Blender experiment', verts, faces, rig.users_collection[0])+ active(experiment)+ rig.select_set(True)+ bpy.context.view_layer.objects.active = rig+ started = time.time()+ result = bpy.ops.object.parent_set(type='ARMATURE_AUTO')+ elapsed = time.time()-started+ automatic = weights(experiment)+ write(out/'initial.json', dict(blender=bpy.app.version_string, automaticSeconds=elapsed,+ operatorResult=list(result), stats=weight_stats(experiment, automatic, regions)))+ if any(not w for w in automatic):+ # Native heat is scale-sensitive for this mesh's tiny eye/finger structures.+ # Scale temporary data tenfold, solve, then restore the EXACT input frames/vertices.+ for v in experiment.data.vertices: v.co *= 10+ active(rig)+ bpy.ops.object.mode_set(mode='EDIT')+ for b in rig.data.edit_bones: b.head *= 10; b.tail *= 10+ bpy.ops.object.mode_set(mode='OBJECT')+ experiment.vertex_groups.clear()+ active(experiment); rig.select_set(True); bpy.context.view_layer.objects.active=rig+ bpy.ops.object.parent_set(type='ARMATURE_AUTO')+ automatic=weights(experiment)+ for v,co in zip(experiment.data.vertices,verts): v.co=co+ active(rig); bpy.ops.object.mode_set(mode='EDIT')+ for b in rig.data.edit_bones:+ original=reference.data.bones[b.name]+ b.matrix=original.matrix_local; b.length=original.length+ bpy.ops.object.mode_set(mode='OBJECT')+ write(out/'scale-retry.json', dict(scale=10,stats=weight_stats(experiment,automatic,regions)))+ if any(not w for w in automatic):+ raise RuntimeError('Native automatic weights remain incomplete; no usable rig claimed.')+ write(out/'pass-a-weights.json', automatic)+ # Inspect the local oracle without animation and retain the imported bind pose.+ before = set(bpy.data.objects)+ bpy.ops.import_scene.fbx(filepath=str(Path(args.mixamo).resolve()), use_anim=False)+ imported = set(bpy.data.objects)-before+ coll = collection('MIXAMO_REFERENCE_LOCAL')+ for obj in imported:+ for c in list(obj.users_collection):+ c.objects.unlink(obj)+ coll.objects.link(obj)+ inventory = []+ for o in sorted(imported, key=lambda o:o.name):+ item = dict(name=o.name, type=o.type, matrix=[list(row) for row in o.matrix_world])+ if o.type=='ARMATURE':+ item['bones'] = [dict(name=b.name,parent=b.parent.name if b.parent else None,+ head=list([email protected]_local),tail=list([email protected]_local),+ restMatrix=[list(row) for row in b.matrix_local],inverseBind=[list(row) for row in ([email protected]_local).inverted()]) for b in o.data.bones]+ if o.type=='MESH':+ item.update(vertices=len(o.data.vertices), polygons=len(o.data.polygons),stats=weight_stats(o,weights(o)))+ write(out/(o.name.replace(':','_')+'-mixamo-local-weights.json'),weights(o))+ inventory.append(item)+ write(out/'mixamo-local-inventory.json', dict(sha256=sha(args.mixamo),objects=inventory))+ write(out/'inputs.json',dict(candidateSha256=sha(candidate_path),rigSha256=sha(rig_path),mixamoSha256=sha(args.mixamo),blender=bpy.app.version_string))+ oracle_rig=next(o for o in imported if o.type=='ARMATURE')+ oracle=next(o for o in imported if o.type=='MESH')+ pose(oracle_rig, [])+ # FBX imported -Y-up, +Z-front. Proper rotation maps it to X5 +Z-up,+Y-front.+ 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 positions(oracle)])+ target=np.array(verts)+ scale=np.ptp(target[:,2])/np.ptp(raw[:,2])+ offset=(target.min(axis=0)+target.max(axis=0))/2-scale*(raw.min(axis=0)+raw.max(axis=0))/2+ alignment=Matrix.Translation(Vector(offset)) @ Matrix.Scale(float(scale),4) @ conversion+ original_world={o:o.matrix_world.copy() for o in imported}+ # Assign parent first, then each object's desired global matrix.+ 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_world[o]+ bpy.context.view_layer.update()+ mapping={'Pelvis':'Hips','SpineLower':'Spine','SpineMid':'Spine1','Chest':'Spine2','Neck':'Neck','Head':'Head'}+ for side in ('Left','Right'):+ mapping.update({side+k:side+v for k,v in dict(Clavicle='Shoulder',Shoulder='Arm',Elbow='ForeArm',Wrist='Hand',Hip='UpLeg',Knee='Leg',Ankle='Foot',ToeBase='ToeBase').items()})+ mapping={k:'mixamorig:'+v for k,v in mapping.items()}+ differences=[]+ for kind,name in mapping.items():+ x5=rig.matrix_world @ rig.data.bones[kind].matrix_local+ mx=oracle_rig.matrix_world @ oracle_rig.data.bones[name].matrix_local+ angle=math.degrees(x5.to_quaternion().rotation_difference(mx.to_quaternion()).angle)+ differences.append(dict(joint=kind,mixamo=name,positionDifferenceMm=list((mx.translation-x5.translation)*1000),+ centerDistanceMm=(mx.translation-x5.translation).length*1000,+ frameAngleDegrees=min(angle,360-angle)))+ oracle_rest=positions(oracle)+ from mathutils.kdtree import KDTree+ tree=KDTree(len(target))+ for i,v in enumerate(target):tree.insert(Vector(v),i)+ tree.balance()+ matches=[tree.find(Vector(v)) for v in oracle_rest]+ nearest=[m[1] for m in matches]+ oracle_regions=[regions[i] for i in nearest]+ write(out/'mixamo-local-mapping.json',dict(alignment=[list(row) for row in alignment],+ nearestSurfaceMaxMm=max(m[2] for m in matches)*1000,nearestUnique=len(set(nearest)),+ indexwiseMaxMm=float(np.linalg.norm(oracle_rest-target,axis=1).max()*1000) if len(oracle_rest)==len(target) else None,+ majorJoints=differences))+ oracle.data.calc_loop_triangles()+ oracle_faces=[tuple(t.vertices) for t in oracle.data.loop_triangles]+ oracle_face_regions=[oracle_regions[t[0]] for t in oracle_faces]+ oracle_field=weights(oracle)+ old_names=[j['kind'] for j in candidate['sourcePoseSkeleton']['joints']]+ old_field=[{old_names[w['jointIndex']]:w['weight'] for w in v['weights']} for v in surface['skinWeights']]+ baseline=mesh('X5 LBS comparison',verts,faces,collection('X5_CURRENT_DEFORMATION'))+ assign(baseline,old_field)+ mod=baseline.modifiers.new('X5 LBS','ARMATURE');mod.object=rig+ active(experiment)+ bpy.ops.object.vertex_group_normalize_all(lock_active=False)+ bpy.ops.object.mode_set(mode='WEIGHT_PAINT')+ bpy.ops.object.vertex_group_smooth(group_select_mode='ALL',factor=.5,repeat=3)+ bpy.ops.object.vertex_group_normalize_all(lock_active=False)+ bpy.ops.object.mode_set(mode='OBJECT')+ smoothed=weights(experiment)+ write(out/'pass-b-weights.json',smoothed)+ normalized=[{n:w/sum(v.values()) for n,w in v.items()} for v in automatic]+ # Final bounded cleanup: exact semantic mirror averaging, then native smoothing+ # only within 80 mm of elbow/knee centers. No vertex positions or pivots change.+ symmetric=[]+ for i,v in enumerate(surface['vertices']):+ partner=v['symmetryPartnerIndex']+ other=normalized[partner] if partner is not None else normalized[i]+ mirrored={n.replace('Left','TEMP').replace('Right','Left').replace('TEMP','Right'):w for n,w in other.items()}+ symmetric.append({n:(normalized[i].get(n,0)+mirrored.get(n,0))/2 for n in sorted(set(normalized[i])|set(mirrored))})+ assign(experiment,symmetric)+ centers=[rig.data.bones[s+j].head_local for s in ('Left','Right') for j in ('Knee','Elbow')]+ for v in experiment.data.vertices:v.select=min((v.co-c).length for c in centers)<.08+ experiment.data.use_paint_mask_vertex=True+ active(experiment);bpy.ops.object.mode_set(mode='WEIGHT_PAINT')+ bpy.ops.object.vertex_group_smooth(group_select_mode='ALL',factor=.25,repeat=1)+ bpy.ops.object.vertex_group_normalize_all(lock_active=False)+ bpy.ops.object.mode_set(mode='OBJECT')+ experiment.data.use_paint_mask_vertex=False+ cleanup=weights(experiment)+ write(out/'pass-c-local-weights.json',cleanup)+ fields={'pass-a':automatic,'pass-b':smoothed,'pass-c-volume':normalized,'pass-c-corrective':normalized,+ 'pass-c-local':cleanup}+ stats={'x5':weight_stats(baseline,old_field,regions),'mixamo':weight_stats(oracle,oracle_field,oracle_regions)}+ for name,field in fields.items():+ stats[name]=weight_stats(experiment,field,regions)+ # Canonical identity provides exact symmetry partners; no nearest-neighbor paint transfer.+ errors=[]+ for i,v in enumerate(surface['vertices']):+ other=field[v['symmetryPartnerIndex']] if v['symmetryPartnerIndex'] is not None else field[i]+ mirrored={n.replace('Left','TEMP').replace('Right','Left').replace('TEMP','Right'):w for n,w in other.items()}+ errors.append(sum(abs(field[i].get(n,0)-mirrored.get(n,0)) for n in set(field[i])|set(mirrored)))+ stats[name]['symmetryWeightL1Max']=max(errors)+ stats[name]['symmetryWeightL1P95']=float(np.quantile(errors,.95))+ write(out/'weight-inspection.json',stats)+ evidence=baseline_evidence+ corpus=[dict(name=c['name'],requested=c['requested']) for c in evidence['cases']]+ def request(j,f=0,a=0):return dict(joint=j,flexionDegrees=f,abductionDegrees=a,twistDegrees=0)+ corpus += [dict(name='combined-stride',requested=[request('LeftHip',30),request('RightHip',-15),request('LeftKnee',45),request('RightElbow',45)]),+ dict(name='combined-raised-arm',requested=[request('LeftShoulder',a=60),request('RightShoulder',a=60),request('LeftElbow',90)]),+ dict(name='combined-balance',requested=[request('LeftHip',70),request('LeftKnee',90),request('RightShoulder',a=30)])]+ write(out/'pose-corpus.json',corpus)+ scene=setup_camera()+ armature=next(m for m in experiment.modifiers if m.type=='ARMATURE')+ correction=experiment.modifiers.new('Native local Corrective Smooth','CORRECTIVE_SMOOTH')+ correction.factor=.5+ correction.iterations=5+ correction.smooth_type='LENGTH_WEIGHTED'+ correction.show_viewport=False;correction.show_render=False+ records=[]+ for variant,field in fields.items():+ assign(experiment,field)+ armature.use_deform_preserve_volume=variant in ('pass-c-volume','pass-c-corrective')+ correction.show_viewport=correction.show_render=variant=='pass-c-corrective'+ if variant=='pass-c-corrective':+ group=experiment.vertex_groups.new(name='LOCAL_TRANSITIONS')+ for i,w in enumerate(field):+ if regions[i] not in ('Head','LeftEye','RightEye','Neck') and max(w.values())<.98:+ group.add([i],1,'REPLACE')+ correction.vertex_group=group.name+ write(out/'corrective-mask.json',[v.index for v in experiment.data.vertices if any(g.group==group.index for g in v.groups)])+ for case in corpus:+ pose(rig,case['requested'])+ p=positions(experiment)+ record=dict(pipeline=variant,pose=case['name'],metrics=metric(target,p,faces,face_regions,normal_transport(rig,field,faces)))+ records.append(record)+ print(variant,case['name'],record['metrics']['maxEdgeDistortion'],flush=True)+ if not args.no_render:render(scene,experiment,out/(variant+'--'+case['name']+'.png'))+ write(out/'metrics-progress.json',records)+ for case in corpus:+ pose(rig,case['requested']);pose(oracle_rig,case['requested'],mapping)+ x5=next((c for c in evidence['cases'] if c['name']==case['name']),None)+ if x5:+ lines=(ROOT/'artifacts/local/humanoid-x5'/x5['obj']).read_text().splitlines()+ p=np.array([[float(x)/1000 for x in line.split()[1:]] for line in lines if line.startswith('v ')])+ # Compare native LBS emulation to the real X5 output; hip JDM winners may differ.+ residual=float(np.linalg.norm(p-positions(baseline),axis=1).max()*1000)+ display=mesh('X5 actual '+case['name'],p,faces,baseline.users_collection[0])+ else:+ p=positions(baseline);residual=None;display=baseline+ records.append(dict(pipeline='x5',pose=case['name'],nativeLbsResidualMm=residual,+ origin='X5 real exported mesh' if x5 else 'Blender LBS replay of X5 weights/frames',+ metrics=metric(target,p,faces,face_regions,normal_transport(rig,old_field,faces))))+ if not args.no_render:render(scene,display,out/('x5--'+case['name']+'.png'))+ if display!=baseline:bpy.data.objects.remove(display,do_unlink=True)+ p=positions(oracle)+ records.append(dict(pipeline='mixamo',pose=case['name'],metrics=metric(oracle_rest,p,oracle_faces,oracle_face_regions,normal_transport(oracle_rig,oracle_field,oracle_faces))))+ if not args.no_render:render(scene,oracle,out/('mixamo--'+case['name']+'.png'))+ write(out/'metrics.json',records)+ pose(rig,[]);pose(oracle_rig,[],mapping)+ assign(experiment,automatic)+ armature.use_deform_preserve_volume=False+ correction.show_viewport=correction.show_render=False+ for o in scene.objects:+ if o.type=='MESH':o.hide_render=o!=experiment;o.hide_set(o!=experiment)+ reference.hide_set(True);oracle_rig.hide_set(True)+ topology=[tuple(p.vertices) for p in experiment.data.polygons]+ frame_error=max(max(abs(rig.data.bones[j['canonicalJoint']].matrix_local[r][c]-matrix(j['globalRestCanonical'])[r][c]) for r in range(4) for c in range(4)) for j in artifact['canonicalJoints'])+ write(out/'integrity.json',dict(vertices=len(verts),faces=len(faces),topologyExact=topology==faces,+ restPositionMaxMm=float(np.linalg.norm(positions(experiment)-target,axis=1).max()*1000),maxRestMatrixElementError=frame_error,+ connectivityHash=surface['connectivityHash'],manualPaintEdits=0))+ write(out/'x5-skeleton.json',artifact)+ bpy.ops.wm.save_as_mainfile(filepath=str(out/'experimental.blend'))+++if __name__ == '__main__':+ main()diff --git a/scripts/replay-humanoid-rerig-x0.py b/scripts/replay-humanoid-rerig-x0.pynew file mode 100644index 00000000..3075de9a--- /dev/null+++ b/scripts/replay-humanoid-rerig-x0.py@@ -0,0 +1,76 @@+"""Pose a saved X0 scene without Aetheris runtime or source assets.++blender --background --disable-autoexec --python-exit-code 1+ --python scripts/replay-humanoid-rerig-x0.py -- --scene <experimental.blend>+ --corpus <pose-corpus.json> --out <directory> --poses hip-flexion-70 knee-flexion-90 shoulder-abduction-90+"""+import argparse+import importlib+import sys+from pathlib import Path+import bpy++sys.path.insert(0,str(Path(__file__).parent))+h=importlib.import_module('humanoid-rerig-x0')+p=argparse.ArgumentParser()+p.add_argument('--scene',required=True)+p.add_argument('--corpus',required=True)+p.add_argument('--out',required=True)+p.add_argument('--poses',nargs='+',default=['hip-flexion-70','knee-flexion-90','shoulder-abduction-90'])+p.add_argument('--pipeline',choices=['pass-a','pass-b','pass-c-local','pass-c-volume','pass-c-corrective','mixamo','x5'],default='pass-a')+p.add_argument('--view',choices=['iso','front','side','rear'],default='iso')+args=p.parse_args(sys.argv[sys.argv.index('--')+1:])+bpy.ops.wm.open_mainfile(filepath=str(Path(args.scene).resolve()),use_scripts=False)+out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)+root=Path(args.scene).resolve().parent+corpus={c['name']:c for c in h.read(args.corpus)}+rig=bpy.data.objects['X5_DEFORM']+obj=bpy.data.objects['Blender experiment']+mapping=None+if args.pipeline=='mixamo':+ coll=bpy.data.collections['MIXAMO_REFERENCE_LOCAL']+ rig=next(o for o in coll.objects if o.type=='ARMATURE')+ obj=next(o for o in coll.objects if o.type=='MESH')+ mapping={j['joint']:j['mixamo'] for j in h.read(root/'mixamo-local-mapping.json')['majorJoints']}+elif args.pipeline=='x5':+ obj=bpy.data.objects['X5 LBS comparison']+elif args.pipeline=='pass-b':+ h.assign(obj,h.read(root/'pass-b-weights.json'))+elif args.pipeline=='pass-c-local':+ h.assign(obj,h.read(root/'pass-c-local-weights.json'))+elif args.pipeline.startswith('pass-c'):+ field=h.read(root/'pass-a-weights.json')+ field=[{n:w/sum(v.values()) for n,w in v.items()} for v in field]+ h.assign(obj,field)+ next(m for m in obj.modifiers if m.type=='ARMATURE').use_deform_preserve_volume=True+ correction=obj.modifiers.get('Native local Corrective Smooth')+ if args.pipeline=='pass-c-corrective':+ group=obj.vertex_groups.new(name='LOCAL_TRANSITIONS')+ group.add(h.read(root/'corrective-mask.json'),1,'REPLACE')+ correction.vertex_group=group.name+ correction.show_viewport=correction.show_render=True+obj.hide_set(False);rig.hide_set(False)+scene=bpy.context.scene+if args.view!='iso':+ from mathutils import Vector+ scene.camera.location={'front':(0,5,1.12),'side':(-5,0,1.12),'rear':(0,-5,1.12)}[args.view]+ scene.camera.rotation_euler=(Vector((0,0,1.12))-scene.camera.location).to_track_quat('-Z','Y').to_euler()+records=[]+for name in args.poses:+ h.pose(rig,corpus[name]['requested'],mapping)+ h.render(scene,obj,out/(args.pipeline+'--'+name+'.png'))+ values=h.positions(obj)+ import hashlib+ centers=[];lengths=[]+ for bone in rig.pose.bones:+ if not bone.parent:continue+ local=bone.parent.bone.matrix_local.inverted() @ bone.bone.matrix_local+ expected=rig.matrix_world @ bone.parent.matrix @ local.translation+ actual=rig.matrix_world @ bone.matrix.translation+ centers.append((actual-expected).length*1000)+ current=(actual-rig.matrix_world @ bone.parent.matrix.translation).length+ rest=(rig.matrix_world @ bone.bone.head_local-rig.matrix_world @ bone.parent.bone.head_local).length+ lengths.append(abs(current-rest)*1000)+ records.append(dict(pose=name,positionSha256=hashlib.sha256(values.tobytes()).hexdigest(),+ maximumCenterResidualMm=max(centers),maximumLinkResidualMm=max(lengths)))+h.write(out/'replay.json',dict(blender=bpy.app.version_string,pipeline=args.pipeline,poses=records))diff --git a/scripts/summarize-humanoid-rerig-x0.py b/scripts/summarize-humanoid-rerig-x0.pynew file mode 100644index 00000000..fe620cd2--- /dev/null+++ b/scripts/summarize-humanoid-rerig-x0.py@@ -0,0 +1,43 @@+"""Build a local HTML gallery and contact sheets; requires Pillow, no source assets."""+import argparse+import html+import json+from pathlib import Path+from PIL import Image, ImageDraw++p=argparse.ArgumentParser()+p.add_argument('--out',default=str(Path(__file__).resolve().parents[1]/'artifacts/local/humanoid-rerig-x0'))+args=p.parse_args()+out=Path(args.out)+metrics=json.loads((out/'metrics.json').read_text())+names=['x5','pass-a','pass-b','pass-c-volume','pass-c-corrective','pass-c-local','mixamo']+poses=list(dict.fromkeys(x['pose'] for x in metrics))+lookup={(x['pipeline'],x['pose']):x['metrics'] for x in metrics}+body=['<!doctype html><meta charset="utf-8"><title>HUMANOID-RERIG-X0 local comparison</title>',+ '<style>body{font:15px system-ui;background:#181a1d;color:#eee;margin:24px}table{border-collapse:collapse}td,th{padding:8px;border:1px solid #555}img{width:240px}a{color:#ade}h2{margin-top:40px}</style>',+ '<h1>EXPERIMENTAL / BRANCH STUDY — local-only comparison</h1>',+ '<p>Same orthographic camera. Angles are deltas from the authored rest pose. Mixamo data and renders are local evidence only.</p>',+ '<p>Values: maximum bidirectional edge distortion / transported-normal reversal proxy / flagged triangles. These are screening proxies, not certified self-intersections.</p>']+for pose in poses:+ body.append('<h2>'+html.escape(pose)+'</h2><table><tr>')+ for name in names:body.append('<th>'+name+'</th>')+ body.append('</tr><tr>')+ for name in names:+ file=name+'--'+pose+'.png'+ m=lookup[name,pose]+ body.append(f'<td><a href="{file}"><img src="{file}"></a><br>{m["maxEdgeDistortion"]:.2f} / {m["normalReversalProxy"]} / {m["flaggedTriangles"]}</td>')+ body.append('</tr></table>')+(out/'comparison.html').write_text('\n'.join(body),encoding='utf-8')+for label,subset in [('gates',['hip-flexion-70','knee-flexion-90','shoulder-abduction-90']),+ ('extremes',['hip-flexion-90','elbow-flexion-90','combined-raised-arm']),+ ('remaining',['neutral','hip-abduction-45','shoulder-abduction-60','combined-balance'])]:+ columns=['x5','pass-a','mixamo']+ sheet=Image.new('RGB',(450*len(columns),532*len(subset)),'white')+ draw=ImageDraw.Draw(sheet)+ for y,pose in enumerate(subset):+ for x,name in enumerate(columns):+ image=Image.open(out/(name+'--'+pose+'.png')).convert('RGB').resize((450,506))+ sheet.paste(image,(x*450,y*532+26))+ draw.text((x*450+8,y*532+6),name+' / '+pose,fill='black')+ sheet.save(out/('comparison-'+label+'.png'))+print(out/'comparison.html')