Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Study localized Blender humanoid cleanup and portable weight import

Yuechen Licb10f0bbd13e
diff --git a/docs/release/HUMANOID-RERIG-X1.md b/docs/release/HUMANOID-RERIG-X1.md
new file mode 100644
index 00000000..b753560d
--- /dev/null
+++ b/docs/release/HUMANOID-RERIG-X1.md
@@ -0,0 +1,165 @@
+# HUMANOID-RERIG-X1
+
+**EXPERIMENTAL GOLDEN-PATH STUDY — Useful but still insufficient**
+
+Branch: `experiment/humanoid-blender-rerig`. Starting checkpoint: `34fc13a6`.
+
+Ordinary Blender tooling produces a much better, portable development candidate than X5, but this cleanup does **not** establish the requested fully qualified golden path. Hip70's one reversal proxy is removed, and shoulder90 maximum distortion improves from 10.48 to 7.10. Hip70's maximum distortion actually worsens from 4.23 to 4.47. High-angle folds remain, including 39 reversal proxies at hip90. The unchanged Aetheris evaluator accepts 10 of 19 surfaces, although all 19 kinematic requests solve. This is meaningful progression: portable import and independent replay work; high-angle skin compatibility is now the isolated blocker. Neither canonical acceptance nor a production-quality body is claimed.
+
+## Scope and authority
+
+The experiment retains all 55 X5 semantic joints, hierarchy, reference frames and corrected centers. No intentional joint edits, topology changes, helper bones, corrective shapes, Rigify, or core runtime changes. X2 constraints and X3 screens remain intact. Only the research executable gains an explicit weight-import command. The surface remains `aetheris.humanoid.antonia.adoption-candidate.v1`; calling this experiment `adult.standard.v1` would misstate its present identity.
+
+The golden-named file is the best retained **candidate**, not a declaration of acceptance. It contains only canonical Antonia source, the X5-derived rig and cleaned mesh. Mixamo and Genesis 9 are absent from it.
+
+## First reversal and cleanup
+
+The X0 hip70 reversal is triangle index **15278**, stable face `antonia:f:008767:t0`, region Pelvis, vertex indices **7879 / 24612 / 12124**, stable IDs `antonia:v:010549`, `antonia:v:032231`, `antonia:v:016323`. Its transported-normal cosine is -0.0054042. It lies at the front hip crease, not at the separate worst-compressed crotch edge.
+
+| Influence | Vertex 7879 | Vertex 24612 | Vertex 12124 |
+|---|---:|---:|---:|
+| LeftHip | .414285 | .510949 | .547186 |
+| Pelvis | .209749 | .223748 | .157378 |
+| SpineLower | .346542 | .256388 | .271734 |
+| SpineMid | .029424 | .008915 | .023702 |
+
+The triangle straddles a thigh/torso weight transition. A bilateral soft reduction of existing hip influence removes this reversal, without naming the triangle in the cleanup code or changing geometry. Full adjacency, positions and weight neighborhoods are recorded in local `hip70-reversal-diagnosis.json`. This is a local weight-field fix with a measured tradeoff, not a solution to every hip fold.
+
+The retained recipe in `scripts/humanoid-rerig-x1.py` is:
+
+1. Generate Blender automatic weights from the X5 skeleton. Temporarily scale mesh and armature data by 10 for the heat solve, then restore stored coordinates and frames. Meter-scale heat failed in X0; this workaround is reproduced, not hidden.
+2. Normalize. Within 220 mm of each hip center, multiply that hip's existing weight by `1 - 0.15*s`, with `s=max(0,1-(distance/radius)^2)^2`; normalize again.
+3. Native Smooth, factor 0.5, **one** iteration, all groups restricted to vertices within 110 mm of either knee; normalize.
+4. Native Smooth, factor 0.5, **one** iteration, within 100 mm of either elbow; normalize.
+5. Soften existing weight contrast within 180 mm of either shoulder: exponent `1 - 0.5*s`; apply to each existing positive influence, then normalize. This is a scripted local Levels-like operation, not an autorigger or weight solver.
+6. Export normalized weights ordered by stable vertex and bone IDs, retaining at most the naturally generated six influences. Evaluate ordinary linear blend skinning.
+
+The masks and brush operations are bilateral. They do not force exact mirror identity onto the slightly asymmetric automatic field. All existing influences are inspected through region summaries, edge weight gradients and opposite-side influence statistics in `weight-inspection.json`; no broad reassignment to unrelated bones was introduced. Mean influence count is 2.467, maximum six, zero unweighted vertices; p95 adjacent-edge weight L1 difference is 0.315, maximum 1.268. This is not a claim that all gradients are smooth.
+
+## Bounded alternatives and effort
+
+The recorded search comprises 28 native smoothing/gain variants, five hip-local brush variants, 16 local contrast variants, and influence limits 2/4/8. Broader hip smoothing and strong inner-thigh reassignment did not consistently improve high-angle behavior. Limiting to two influences makes hip70 maximum distortion 66.6 with 49 reversals; four gives 4.74 with 12 reversals. Eight leaves the natural six-influence field unchanged. Six is retained instead of imposing a four-weight runtime shortcut.
+
+One knee smoothing pass improves knee45 maximum distortion (4.60 to 3.75), but barely changes knee90 and adds one proxy reversal. One elbow pass removes one elbow90 proxy while slightly worsening its maximum distortion. Shoulder contrast softening supplies the largest new benefit. These limitations are explicitly retained in the comparison rather than selecting only favorable statistics.
+
+X0 already tested native preserve-volume skinning and Corrective Smooth: their improvements in some regions came with worse knee or other folds. X1 adds no helper or pose corrective: there is no ablation evidence that a twist helper fixes these flexion folds, and adding runtime corrective machinery would exceed this bounded weight-cleanup result. This is not proof that every possible DCC edit has failed. A focused artist or one bounded corrective remains a plausible next experiment.
+
+Manual paint strokes: **0**. Manual per-vertex assignments: **0**. Artistic sculpting: **0**. Cleanup consists of the five scripted local operations above. Approximate agent effort is under an hour for diagnosis, bounded trials, reference inspection, import and qualification; it is not a measured human painting time. Final build including the 19 overview renders took approximately **17.6 seconds** on this machine. Reproduction cost is distinct from investigation cost.
+
+## 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.
+
+[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.
+
+![Hip70 comparison](../../artifacts/local/humanoid-rerig-x1/comparison--hip-flexion-70.jpg)
+![Hip90 comparison](../../artifacts/local/humanoid-rerig-x1/comparison--hip-flexion-90.jpg)
+![Abduction45 comparison](../../artifacts/local/humanoid-rerig-x1/comparison--hip-abduction-45.jpg)
+![Knee90 comparison](../../artifacts/local/humanoid-rerig-x1/comparison--knee-flexion-90.jpg)
+![Shoulder90 comparison](../../artifacts/local/humanoid-rerig-x1/comparison--shoulder-abduction-90.jpg)
+![Elbow90 comparison](../../artifacts/local/humanoid-rerig-x1/comparison--elbow-flexion-90.jpg)
+
+| Pose/region | X1 review | Observation |
+|---|---|---|
+| Neutral | Pass | Rest reconstruction retained |
+| Hip30 | Pass | Continuous pelvis/thigh |
+| Hip45 | NeedsReview | Crease remains visible |
+| Hip70 | NeedsReview | Sane connected silhouette, much less X5 webbing; compressed crease remains despite zero proxy reversals |
+| Hip90 | Fail | Pronounced inner-thigh/crotch folded bulge in closeup; not qualified as a usable high-angle baseline |
+| Abduction15 / 30 / 45 | Pass | Leg separation and pelvis continuity retained; no reversal proxies |
+| Knee45 | NeedsReview | Improved transition, still shaped by a simple hinge |
+| Knee90 | NeedsReview | Limb connected; pointed back-of-knee compression and 27 proxies remain |
+| Elbow45 | NeedsReview | Continuous, limited volume qualification |
+| Elbow90 / 120 | NeedsReview | Sharp angular crease/mound; no limb separation, but local stress persists |
+| Shoulder30 | Pass | No gross collapse |
+| Shoulder60 | NeedsReview | Better broad transition; not commercial deltoid/clavicle behavior |
+| Shoulder90 | NeedsReview | Material improvement; still pinched axilla, nine proxies, no scapular coupling |
+| Combined stride | NeedsReview | Coherent whole-body stance; local folds retained |
+| Combined raised-arm reach | NeedsReview | Coherent reach; inherits elbow stress |
+| Combined balance/kick | NeedsReview | Coherent silhouette; inherits knee stress |
+| Wrists / ankles | NeedsReview | Carried continuously through this corpus; independent wrist/ankle extremes were not qualified |
+
+These are assistant visual reviews, not artist signoff. Hip90 is admitted by the kinematic solver, so its failure cannot be hidden by claiming an out-of-range request. The evidence isolates a skin-weight/high-angle fold limitation, with collision/contact and lack of pose-dependent volume correction possible contributors. It does **not** prove a canonical topology defect; topology remains untouched.
+
+## Metrics
+
+Distortion is `max(edge length ratio, reciprocal ratio)` on canonical edges. Compression is the minimum posed/rest edge ratio. Reversal means a negative dot product against the dominant-influence transported rest normal; it is a proxy, not certified triangle inversion or self-intersection. Hip90 cosines reach -0.734, knee90 -0.978, shoulder90 -0.982 and elbow90 -0.848: the residual counts cannot all be dismissed as floating-point sign noise. No degenerate triangles were found. Certified self-intersection/contact testing was not performed. Local JSON also includes stretch percentiles, area ratios, reversed face IDs and worst edges.
+
+| Pose | X0 max / reversals | X1 p50 | p95 | p99 | max | min compression | reversals |
+|---|---:|---:|---:|---:|---:|---:|---:|
+| neutral | 1.001 / 0 | 1.000 | 1.000 | 1.000 | 1.001 | 0.999 | 0 |
+| hip-flexion-30 | 1.599 / 0 | 1.000 | 1.027 | 1.140 | 1.595 | 0.627 | 0 |
+| hip-flexion-45 | 2.291 / 0 | 1.000 | 1.039 | 1.219 | 2.269 | 0.441 | 0 |
+| hip-flexion-70 | 4.228 / 1 | 1.000 | 1.055 | 1.373 | 4.468 | 0.224 | 0 |
+| hip-flexion-90 | 9.443 / 40 | 1.000 | 1.061 | 1.497 | 9.352 | 0.107 | 39 |
+| hip-abduction-15 | 1.440 / 0 | 1.000 | 1.009 | 1.079 | 1.426 | 0.818 | 0 |
+| hip-abduction-30 | 1.861 / 0 | 1.000 | 1.019 | 1.166 | 1.834 | 0.640 | 0 |
+| hip-abduction-45 | 2.253 / 0 | 1.000 | 1.028 | 1.259 | 2.213 | 0.483 | 0 |
+| knee-flexion-45 | 4.695 / 0 | 1.000 | 1.000 | 1.020 | 3.749 | 0.267 | 0 |
+| knee-flexion-90 | 5.457 / 26 | 1.000 | 1.000 | 1.036 | 5.417 | 0.185 | 27 |
+| shoulder-abduction-30 | 2.168 / 0 | 1.000 | 1.000 | 1.037 | 1.530 | 0.654 | 0 |
+| shoulder-abduction-60 | 9.631 / 6 | 1.000 | 1.000 | 1.083 | 3.807 | 0.263 | 0 |
+| shoulder-abduction-90 | 10.478 / 21 | 1.000 | 1.000 | 1.136 | 7.102 | 0.141 | 9 |
+| elbow-flexion-45 | 5.082 / 0 | 1.000 | 1.000 | 1.003 | 3.486 | 0.287 | 0 |
+| elbow-flexion-90 | 4.074 / 15 | 1.000 | 1.000 | 1.007 | 4.124 | 0.243 | 14 |
+| elbow-flexion-120 | 4.866 / 23 | 1.000 | 1.000 | 1.009 | 5.072 | 0.197 | 22 |
+| combined-stride | 5.154 / 0 | 1.000 | 1.055 | 1.216 | 4.181 | 0.239 | 0 |
+| combined-raised-arm | 9.631 / 27 | 1.000 | 1.018 | 1.187 | 4.124 | 0.243 | 14 |
+| combined-balance | 5.456 / 27 | 1.000 | 1.090 | 1.420 | 5.417 | 0.185 | 27 |
+
+## Reference benchmarks
+
+Mixamo remains the same local FBX oracle as X0: `Female Standing Pose (2).fbx`, SHA-256 `53038e7c78816b25df1bb2412d33b8d2d1530de5f02a785352c529dd2de376d9`. X0's mapping and weight observations remain applicable; X1 reuses its matched-pose renders. It shows that ordinary auto-rigging improves X5, but does not establish a uniformly superior high-angle solution. X1 does not import its weights, helpers or mesh into the candidate.
+
+Genesis 9 was locally available. A **separate headless DAZ instance** loaded the installed base figure and evaluated neutral, hip70, hip90, abduction45, knee90, shoulder60, shoulder90 and elbow90. The user's interactive scene was left alone. `benchmark-genesis9-local.dsa` records actual native control values and exports evaluated local reference meshes for matched-camera rendering. Native controls used thigh X Bend -70/-90, thigh Z Side-Side +45, shin X Bend +90, upper-arm Z Bend +60/+90, forearm Y Bend -90. Different rest poses and axes make this an approximate quality comparison; particularly, shoulder90 does not have identical world-space arm orientation. No topology or vertex-difference comparison is claimed.
+
+Genesis shows broader, rounder transitions and illustrates a mature rig's separate twist chains (two segments in each thigh, upper arm and forearm). That observation does not prove those helpers cause superior bending: no helper/corrective ablation was performed, and proprietary JCM payloads were not inspected or copied. The remaining gap is substantial: high-angle fold shape, volume, coordinated shoulder motion and contact handling. Genesis quality is not the acceptance threshold, and no DAZ runtime dependency is introduced.
+
+All raw reference exports, inventories and images stay in ignored local output. No Mixamo/DAZ raw data is embedded in this report, source, or final Blender file. No ML training or service probing occurred. Any later proposal to promote reference-derived data requires a separate license review.
+
+## Portable artifacts and validation
+
+Local output root: `artifacts/local/humanoid-rerig-x1/`.
+
+- `golden.blend`: `ANTONIA_CANONICAL`, `X5_DEFORM_RIG`, `GOLDEN_DEFORMATION`; embedded compressed canonical surface, reference skeleton, corpus and edit history. No external oracle objects.
+- `golden-weights.json`: `aetheris.humanoid.experimental-weights.v1`, stable vertex IDs, canonical bone IDs, sorted normalized weights, input rig hash and generation provenance. SHA-256 `f117189857e6c54be6f58b08b4d2847322ebca8fb4230ecf8328b43c5004ae29`.
+- `golden-skeleton.json`: complete X5 reference plus empty `deformationRigExtensions`.
+- `pose-corpus.json`: 19 explicit semantic requests including three combined poses; angles are translated through the existing frame convention, not eyeballed.
+- `metrics.json`, `integrity.json`, `weight-inspection.json`, per-pose positions, overview and closeup renders, and `comparison.html`.
+- `aetheris/evidence.json`, `aetheris/parity.json`, per-pose diagnostic/screened OBJ files and ordered positions.
+
+Before/after: **27,193 vertices, 54,224 triangles**, exact ordered triangle indices and stable vertex IDs unchanged. Connectivity hash `2e2f787499ba2da1f02bab14f352b86070938fbb5d7cae60e8bd7d59edb2b7a2`. Candidate SHA-256 `af45c535ab21d93ae2c23f7a63f71925f3c6cfc6a68e5af9c04e1ab0033834dd`; X5 reference SHA-256 `0647f681f67043610e8829fff20ca29901648b3c3245b589f2942ba453e13148`.
+
+Blender neutral maximum residual **0.000365 mm**; normalized field error at floating-point precision; finite transforms. Maximum frame-element round-trip difference is **3.4124e-6**, reflecting Blender storage precision, not an intentional skeleton adjustment. Aetheris inverse-bind/neutral reconstruction maximum **0.000679 mm**; maximum joint-center residual **0**, link residual **0.000126 mm**.
+
+An independently assigned import agent consumed only the portable weights and corpus through existing `AntoniaReferenceRigAdapter`, `HumanoidKinematicSolver` and `HumanoidConstrainedSurface`. **19/19 solves**, **10/19 surface-screen passes**, zero collapsed triangles. Nine failures remain diagnostic exports: hip70, hip90, knee90, shoulder90, elbow90, elbow120, and all three combined poses. Maximum Blender/.NET vertex-position difference **0.0011472 mm**, RMS per pose **0.000202–0.000325 mm**. This proves runtime portability, not deformation acceptance.
+
+Import rejects mismatched topology/rig hash/IDs, duplicate IDs/bones, unknown bones, nonfinite/negative/unnormalized weights, unsupported extensions and excessive influences. Eleven malformed-artifact probes were rejected. It supports LBS, canonical joints and up to eight influences; it does not silently normalize or waive existing screens. Research-tool build: **zero warnings/errors**. Humanoid tests: **63 passed**, none failed/skipped. No production library changes required.
+
+A separate fresh replay agent rebuilt from the embedded scene, cleanup scripts and corpus without Aetheris implementation internals, then inspected hip70, knee90 and shoulder90 renders. All 19 renders reproduced. Replay is **approximately deterministic, not bit-exact**: maximum stable-ID weight delta 5.8181e-6; maximum positional difference 0.00089782 mm; maximum scalar metric difference 0.00028744. Reversal/degeneracy counts, stable IDs, ordered topology and corpus are unchanged. Replay neutral residual is 0.00033154 mm. Local `fresh-replay/replay-evidence.json` records the comparison. Sub-millimetre study reproducibility is established; byte-identical heat-solver output is not.
+
+## Reproduce
+
+Use Blender **5.2.2 LTS**, Python with Pillow for the gallery, and the repository's .NET SDK. From the repository root (PowerShell):
+
+```powershell
+$blenderExe = 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe'
+& $blenderExe --background --factory-startup --disable-autoexec --python-exit-code 1 --python scripts/humanoid-rerig-x1.py -- --phase build
+& $blenderExe --background --factory-startup --disable-autoexec --python-exit-code 1 --python scripts/review-humanoid-rerig-x1.py
+python scripts/summarize-humanoid-rerig-x1.py
+dotnet run --project tools/Aetheris.Humanoid.X0 -- golden-weights-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 --corpus artifacts/local/humanoid-rerig-x1/pose-corpus.json --out-dir artifacts/local/humanoid-rerig-x1/aetheris
+```
+
+Initial build uses the existing X0 corpus and canonical candidate. A fresh replay needs only the saved scene and the X1 script plus its X0 helper, not Aetheris internals:
+
+```powershell
+& $blenderExe --background --factory-startup --disable-autoexec --python-exit-code 1 --python scripts/humanoid-rerig-x1.py -- --phase build --scene artifacts/local/humanoid-rerig-x1/golden.blend --out artifacts/local/humanoid-rerig-x1/fresh-replay
+```
+
+The optional Genesis script uses documented [DAZ command-line options](https://docs.daz3d.com/public/software/dazstudio/4/referenceguide/tech_articles/command_line_options/start) and the [native OBJ exporter API](https://docs.daz3d.com/public/software/dazstudio/4/referenceguide/scripting/api_reference/samples/file_io/export_obj_silent/start). Pass the installed library root and an ignored output directory as two `-scriptArg` values in a separate headless instance. Oracle availability is not required for either rebuild or runtime import. Blender operations follow its [weight-paint tooling](https://docs.blender.org/manual/en/5.2/sculpt_paint/weight_paint/index.html).
+
+## Cheapest retained path and next boundary
+
+**X5 skeleton → Blender heat weights → normalization → small local cleanup → deterministic portable field → existing Aetheris LBS.** Keep this development candidate and the stronger shoulder result. Do not promote it as a fully accepted humanoid or weaken Judgment screens to make it pass.
+
+The smallest next step is a bounded hip90 fold experiment, with artist review or one local corrective and explicit contact inspection, judged against these same closeups. It should not start by moving joints or replacing topology. Only after that quality gap closes should generated weights be admitted as canonical data. Weight generation and cleanup may eventually move inside Aetheris, but the demonstrated portable import removes any immediate need to internalize Blender's tools. The remaining 20% is now a concrete high-angle fold problem, not a reason to invent another skinning system.
diff --git a/scripts/benchmark-genesis9-local.dsa b/scripts/benchmark-genesis9-local.dsa
new file mode 100644
index 00000000..7a6e3f96
--- /dev/null
+++ b/scripts/benchmark-genesis9-local.dsa
@@ -0,0 +1,38 @@
+// 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.
+(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();}
+ 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);
+ }catch(e){save('error.json',{error:String(e),line:e.lineNumber});}
+ App.exit();
+})();
diff --git a/scripts/humanoid-rerig-x1.py b/scripts/humanoid-rerig-x1.py
new file mode 100644
index 00000000..ab4b595e
--- /dev/null
+++ b/scripts/humanoid-rerig-x1.py
@@ -0,0 +1,307 @@
+"""Bounded X1 weight cleanup study, using Blender native deformation and operators."""
+import argparse
+import base64
+import importlib
+import math
+from pathlib import Path
+import sys
+import time
+import zlib
+
+import bpy
+import numpy as np
+from mathutils import Matrix, Vector
+
+sys.path.insert(0, str(Path(__file__).parent))
+h = importlib.import_module('humanoid-rerig-x0')
+ROOT = h.ROOT
+
+
+def normalize(field):
+ return [{n: w/sum(row.values()) for n,w in sorted(row.items()) if w>0} for row in field]
+
+
+def setup():
+ candidate = h.read(ROOT/'artifacts/local/humanoid-x1/antonia-adoption-candidate.json')
+ surface = candidate['sourcePoseSurface']
+ artifact = h.read(ROOT/'fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json')
+ bpy.ops.object.select_all(action='SELECT')
+ bpy.ops.object.delete(use_global=False)
+ 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']]
+ original = h.mesh('ANTONIA_CANONICAL',verts,faces,h.collection('ANTONIA_CANONICAL'))
+ original.hide_set(True);original.hide_render=True
+ rig = h.make_rig(artifact,h.collection('X5_DEFORM_RIG'))
+ obj = h.mesh('ANTONIA_GOLDEN',verts,faces,h.collection('GOLDEN_DEFORMATION'))
+ mod = obj.modifiers.new('Portable linear blend skinning','ARMATURE');mod.object=rig
+ scene=h.setup_camera()
+ return surface,rig,obj,np.array(verts),np.array(faces),scene
+
+
+def automatic_weights(rig,obj):
+ saved=[(b.name,b.matrix_local.copy(),b.length) for b in rig.data.bones]
+ coords=[v.co.copy() for v in obj.data.vertices]
+ h.pose(rig,[])
+ obj.vertex_groups.clear()
+ for v in obj.data.vertices:v.co*=10
+ h.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')
+ h.active(obj);rig.select_set(True);bpy.context.view_layer.objects.active=rig
+ bpy.ops.object.parent_set(type='ARMATURE_AUTO')
+ raw=h.weights(obj)
+ for v,co in zip(obj.data.vertices,coords):v.co=co
+ h.active(rig);bpy.ops.object.mode_set(mode='EDIT')
+ for name,matrix,length in saved:
+ rig.data.edit_bones[name].matrix=matrix;rig.data.edit_bones[name].length=length
+ bpy.ops.object.mode_set(mode='OBJECT')
+ if any(not row for row in raw):raise RuntimeError('Incomplete native heat weights')
+ return normalize(raw)
+
+
+def golden_cleanup(obj,rig,rest,field):
+ result=brush_gain(field,rest,rig,'Hip',.22,.85)
+ for kind,radius in [('Knee',.11),('Elbow',.10)]:
+ centers=[np.array(rig.data.bones[side+kind].head_local) for side in ('Left','Right')]
+ mask=np.minimum(*[np.linalg.norm(rest-c,axis=1) for c in centers])<radius
+ result=local_smooth(obj,result,mask,1)
+ return local_contrast(result,rest,rig,'Shoulder',.18,.5)
+
+
+def build(out,surface,rig,obj,rest,tris,scene,corpus,no_render=False):
+ started=time.monotonic()
+ automatic=automatic_weights(rig,obj)
+ field=golden_cleanup(obj,rig,rest,automatic)
+ h.assign(obj,field)
+ # Read back the actual float field Blender evaluates, then normalize portable doubles.
+ field=normalize(h.weights(obj));h.assign(obj,field)
+ h.write(out/'auto-weights.json',automatic)
+ h.write(out/'cleaned-weights.json',field)
+ rigpath=ROOT/'fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json'
+ import json
+ artifact=json.loads(bpy.data.texts['x5-reference.json'].as_string()) if bpy.data.texts.get('x5-reference.json') else h.read(rigpath)
+ reference_hash=rig.get('referenceRigSha256') or h.sha(rigpath)
+ rig['referenceRigSha256']=reference_hash
+ h.write(out/'golden-skeleton.json',dict(canonicalReference=artifact,deformationRigExtensions=[]))
+ portable=dict(schema='aetheris.humanoid.experimental-weights.v1',topologyId=surface['topologyId'],
+ connectivityHash=surface['connectivityHash'],referenceRigSha256=reference_hash,
+ maxInfluences=max(len(w) for w in field),skinning='linear-blend-skinning',deformationRigExtensions=[],
+ provenance=dict(blender=bpy.app.version_string,scriptSha256=h.sha(__file__),source='Blender native automatic weights plus recorded local cleanup; no oracle transfer',
+ steps=['native bone heat at temporary data scale 10; restore X5 frames',
+ 'normalize','bilateral hip soft gain 0.85, radius 220 mm, quartic radial falloff',
+ 'native Smooth factor 0.5 once within knee 110 mm and elbow 100 mm spheres',
+ 'bilateral shoulder contrast exponent 0.5, radius 180 mm, quartic radial falloff','normalize'],
+ manualPaintStrokes=0,topologyEdits=0,jointEdits=0),
+ 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/'golden-weights.json',portable)
+ h.write(out/'pose-corpus.json',corpus)
+ results=[]
+ for case in corpus:
+ h.pose(rig,case['requested'])
+ posed=h.positions(obj)
+ transport=h.normal_transport(rig,field,tris)
+ m=measure(rest,posed,tris,transport,True)
+ m['regions']={region:measure(rest,posed,tris[mask],transport[mask]) for region in sorted({f['region'] for f in surface['faces']})
+ for mask in [np.array([f['region']==region for f in surface['faces']])]}
+ results.append(dict(pose=case['name'],metrics=m))
+ h.write(out/(case['name']+'.positions.json'),(posed*1000).tolist())
+ if not no_render:
+ h.render(scene,obj,out/('cleaned--'+case['name']+'.png'))
+ print('GOLDEN',case['name'],round(m['max'],3),m['reversalCount'],flush=True)
+ h.write(out/'metrics.json',results)
+ h.pose(rig,[])
+ bind_error=float(np.linalg.norm(h.positions(obj)-rest,axis=1).max()*1000)
+ topology=[tuple(p.vertices) for p in obj.data.polygons]
+ if topology!=[tuple(t) for t in tris] or bind_error>.001:raise RuntimeError('Topology/bind invariant failed')
+ h.write(out/'integrity.json',dict(vertexCount=len(rest),faceCount=len(tris),connectivityHash=surface['connectivityHash'],
+ exactOrderedTriangleIndices=True,stableVertexIds=[v['id'] for v in surface['vertices']],neutralReconstructionMaximumMm=bind_error,
+ maxNormalizationError=max(abs(sum(row.values())-1) for row in field),finiteTransforms=all(math.isfinite(x) for b in rig.pose.bones for row in b.matrix for x in row),
+ x5FrameMaximumElementDelta=max(abs(rig.data.bones[j['canonicalJoint']].matrix_local[r][c]-h.matrix(j['globalRestCanonical'])[r][c]) for j in artifact['canonicalJoints'] for r in range(4) for c in range(4))))
+ h.write(out/'weight-inspection.json',h.weight_stats(obj,field,[v['region'] for v in surface['vertices']]))
+ # These embedded inputs make a fresh replay independent of the repo's implementation/data.
+ import json
+ for name,value in [('canonical-surface.json.zlib',{k:surface[k] for k in ('vertices','faces','topologyId','connectivityHash')}),('x5-reference.json',artifact),('pose-corpus.json',corpus),('cleanup-history.json',portable['provenance'])]:
+ text=bpy.data.texts.get(name) or bpy.data.texts.new(name);text.clear()
+ encoded=json.dumps(value,sort_keys=True,indent=2)
+ if name.endswith('.zlib'):
+ encoded=base64.b64encode(zlib.compress(encoded.encode(),9)).decode()
+ encoded='\n'.join(encoded[i:i+76] for i in range(0,len(encoded),76))
+ text.write(encoded)
+ scene['study']='HUMANOID-RERIG-X1; experimental, no proprietary references; portable LBS'
+ h.active(obj)
+ bpy.ops.wm.save_as_mainfile(filepath=str(out/'golden.blend'))
+ h.write(out/'effort.json',dict(buildSeconds=time.monotonic()-started,manualPaintStrokes=0))
+
+
+def measure(rest, posed, tris, transported, details=False):
+ edges=np.unique(np.sort(np.concatenate([tris[:,[0,1]],tris[:,[1,2]],tris[:,[2,0]]]),axis=1),axis=0)
+ ratio=np.linalg.norm(posed[edges[:,0]]-posed[edges[:,1]],axis=1)/np.maximum(np.linalg.norm(rest[edges[:,0]]-rest[edges[:,1]],axis=1),1e-12)
+ distortion=np.maximum(ratio,1/np.maximum(ratio,1e-12))
+ n0=np.cross(rest[tris[:,1]]-rest[tris[:,0]],rest[tris[:,2]]-rest[tris[:,0]])
+ n1=np.cross(posed[tris[:,1]]-posed[tris[:,0]],posed[tris[:,2]]-posed[tris[:,0]])
+ expected=np.einsum('nij,nj->ni',transported,n0)
+ cos=np.sum(n1*expected,axis=1)/np.maximum(np.linalg.norm(n1,axis=1)*np.linalg.norm(expected,axis=1),1e-20)
+ area=np.linalg.norm(n1,axis=1)/np.maximum(np.linalg.norm(n0,axis=1),1e-20)
+ result=dict(p50=float(np.quantile(distortion,.5)),p95=float(np.quantile(distortion,.95)),p99=float(np.quantile(distortion,.99)),
+ max=float(distortion.max()),minCompression=float(ratio.min()),maxStretch=float(ratio.max()),
+ p95Stretch=float(np.quantile(ratio,.95)),p99Stretch=float(np.quantile(ratio,.99)),
+ reversalCount=int((cos<0).sum()),degenerateTriangles=int((area<1e-6).sum()),minArea=float(area.min()),maxArea=float(area.max()))
+ if details:
+ result.update(reversedFaces=np.where(cos<0)[0].tolist(),reversedCosines=cos[cos<0].tolist(),
+ worstEdges=[dict(vertices=edges[i].tolist(),ratio=float(ratio[i])) for i in np.argsort(distortion)[-10:][::-1]])
+ return result
+
+
+def evaluate(rig,obj,field,rest,tris,corpus):
+ h.assign(obj,field)
+ results=[]
+ for case in corpus:
+ h.pose(rig,case['requested'])
+ m=measure(rest,h.positions(obj),tris,h.normal_transport(rig,field,tris),True)
+ results.append(dict(pose=case['name'],metrics=m))
+ h.pose(rig,[])
+ return results
+
+
+def local_smooth(obj,field,mask,repeat,factor=.5):
+ h.assign(obj,field);h.active(obj)
+ for v,selected in zip(obj.data.vertices,mask):v.select=bool(selected)
+ obj.data.use_paint_mask_vertex=True
+ bpy.ops.object.mode_set(mode='WEIGHT_PAINT')
+ bpy.ops.object.vertex_group_smooth(group_select_mode='ALL',factor=factor,repeat=repeat)
+ bpy.ops.object.vertex_group_normalize_all(lock_active=False)
+ bpy.ops.object.mode_set(mode='OBJECT')
+ obj.data.use_paint_mask_vertex=False
+ return normalize(h.weights(obj))
+
+
+def brush_gain(field,rest,rig,kind,radius,gain):
+ edited=[dict(row) for row in field]
+ for side in ('Left','Right'):
+ name=side+kind
+ center=np.array(rig.data.bones[name].head_local)
+ distance=np.linalg.norm(rest-center,axis=1)/radius
+ strength=np.maximum(0,1-distance**2)**2
+ for i,row in enumerate(edited):
+ if name in row:row[name]*=1+(gain-1)*strength[i]
+ return normalize(edited)
+
+
+def hip_brush(field,rest,rig,inner_gain):
+ """Two mirrored soft Levels strokes, defined relative to the hip frames in metres."""
+ edited=[dict(row) for row in field]
+ for side in ('Left','Right'):
+ name=side+'Hip';hip=np.array(rig.data.bones[name].head_local)
+ for center,radii,gain in [(hip+np.array([0,.09,.05]),np.array([.08,.07,.10]),.80),
+ (hip*np.array([.55,1,1])+np.array([0,.075,-.07]),np.array([.075,.09,.14]),inner_gain)]:
+ q=np.sum(((rest-center)/radii)**2,axis=1)
+ strength=np.maximum(0,1-q)**2
+ for i,row in enumerate(edited):
+ if name in row:row[name]*=1+(gain-1)*strength[i]
+ return normalize(edited)
+
+
+def local_contrast(field,rest,rig,kind,radius,power):
+ centers=[np.array(rig.data.bones[side+kind].head_local) for side in ('Left','Right')]
+ distance=np.minimum(*[np.linalg.norm(rest-c,axis=1) for c in centers])/radius
+ strength=np.maximum(0,1-distance**2)**2
+ result=[]
+ for row,s in zip(field,strength):
+ exponent=1+(power-1)*s
+ result.append({n:w**exponent for n,w in sorted(row.items())})
+ return normalize(result)
+
+
+def cleanup_trials(out,surface,rig,obj,rest,tris,field,corpus):
+ records={}
+ for kind,radius,needle in [('Hip',.22,'hip-'),('Knee',.11,'knee-'),('Elbow',.10,'elbow-'),('Shoulder',.15,'shoulder-')]:
+ subset=[c for c in corpus if needle in c['name']]
+ centers=[np.array(rig.data.bones[side+kind].head_local) for side in ('Left','Right')]
+ mask=np.minimum(*[np.linalg.norm(rest-c,axis=1) for c in centers])<radius
+ for repeat in (1,3,6):
+ name=f'{kind.lower()}-smooth-{repeat}'
+ edited=local_smooth(obj,field,mask,repeat)
+ records[name]=evaluate(rig,obj,edited,rest,tris,subset)
+ h.write(out/(name+'-weights.json'),edited)
+ print(name,[(x['pose'],round(x['metrics']['max'],3),x['metrics']['reversalCount']) for x in records[name]],flush=True)
+ for gain in (.65,.85,1.2,1.5):
+ name=f'{kind.lower()}-gain-{gain}'
+ edited=brush_gain(field,rest,rig,kind,radius,gain)
+ records[name]=evaluate(rig,obj,edited,rest,tris,subset)
+ h.write(out/(name+'-weights.json'),edited)
+ print(name,[(x['pose'],round(x['metrics']['max'],3),x['metrics']['reversalCount']) for x in records[name]],flush=True)
+ h.write(out/'cleanup-trials.json',records)
+
+
+def main():
+ p=argparse.ArgumentParser()
+ p.add_argument('--out',default=str(ROOT/'artifacts/local/humanoid-rerig-x1'))
+ p.add_argument('--phase',choices=['diagnose','cleanup','hip','contrast','build'],default='diagnose')
+ p.add_argument('--scene')
+ p.add_argument('--no-render',action='store_true')
+ args=p.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'):raise ValueError('Local ignored output required')
+ if args.scene:
+ import json
+ bpy.ops.wm.open_mainfile(filepath=str(Path(args.scene).resolve()),use_scripts=False)
+ surface=json.loads(zlib.decompress(base64.b64decode(bpy.data.texts['canonical-surface.json.zlib'].as_string())))
+ corpus=json.loads(bpy.data.texts['pose-corpus.json'].as_string())
+ rig=bpy.data.objects['X5_DEFORM'];obj=bpy.data.objects['ANTONIA_GOLDEN'];scene=bpy.context.scene
+ rest=np.array([tuple(v['position'][k]/1000 for k in 'xyz') for v in surface['vertices']])
+ tris=np.array([tuple(f[k] for k in ('a','b','c')) for f in surface['faces']])
+ else:
+ surface,rig,obj,rest,tris,scene=setup()
+ corpus=h.read(ROOT/'artifacts/local/humanoid-rerig-x0/pose-corpus.json')
+ if args.phase=='build':
+ build(out,surface,rig,obj,rest,tris,scene,corpus,args.no_render)
+ return
+ field=normalize(h.read(ROOT/'artifacts/local/humanoid-rerig-x0/pass-a-weights.json'))
+ if args.phase=='cleanup':
+ cleanup_trials(out,surface,rig,obj,rest,tris,field,corpus)
+ return
+ if args.phase=='hip':
+ sweep={}
+ for gain in (.5,1,1.5,2,3):
+ name=f'hip-local-{gain}'
+ edited=hip_brush(field,rest,rig,gain)
+ sweep[name]=evaluate(rig,obj,edited,rest,tris,[c for c in corpus if 'hip-' in c['name']])
+ h.write(out/(name+'-weights.json'),edited)
+ print(name,[(x['pose'],round(x['metrics']['max'],3),x['metrics']['reversalCount']) for x in sweep[name]],flush=True)
+ h.write(out/'hip-local-trials.json',sweep)
+ return
+ if args.phase=='contrast':
+ sweep={}
+ for kind,radius,needle in [('Hip',.28,'hip-'),('Knee',.14,'knee-'),('Elbow',.12,'elbow-'),('Shoulder',.18,'shoulder-')]:
+ for power in (.5,.75,1.5,2):
+ name=f'{kind.lower()}-contrast-{power}'
+ edited=local_contrast(field,rest,rig,kind,radius,power)
+ sweep[name]=evaluate(rig,obj,edited,rest,tris,[c for c in corpus if needle in c['name']])
+ h.write(out/(name+'-weights.json'),edited)
+ print(name,[(x['pose'],round(x['metrics']['max'],3),x['metrics']['reversalCount']) for x in sweep[name]],flush=True)
+ h.write(out/'contrast-trials.json',sweep)
+ return
+ baseline=evaluate(rig,obj,field,rest,tris,corpus)
+ h.write(out/'baseline-metrics.json',baseline)
+ hip70=next(c for c in baseline if c['pose']=='hip-flexion-70')['metrics']
+ findings=[]
+ for fi,cosine in zip(hip70['reversedFaces'],hip70['reversedCosines']):
+ indices=tris[fi].tolist()
+ adjacent=sorted(set(tris[np.any(np.isin(tris,indices),axis=1)].ravel().tolist()))
+ findings.append(dict(faceIndex=fi,face=surface['faces'][fi],cosine=cosine,
+ vertices=[dict(index=i,record=surface['vertices'][i],weights=field[i]) for i in indices],
+ adjacentVertices=[dict(index=i,position=rest[i].tolist(),weights=field[i]) for i in adjacent]))
+ h.write(out/'hip70-reversal-diagnosis.json',findings)
+ sweep={'normalized-auto':baseline}
+ for limit in (2,4,8):
+ h.assign(obj,field);h.active(obj)
+ bpy.ops.object.vertex_group_limit_total(group_select_mode='ALL',limit=limit)
+ bpy.ops.object.vertex_group_normalize_all(lock_active=False)
+ limited=normalize(h.weights(obj))
+ h.write(out/f'limit-{limit}-weights.json',limited)
+ sweep[f'limit-{limit}']=evaluate(rig,obj,limited,rest,tris,corpus)
+ print('LIMIT',limit,[(x['pose'],round(x['metrics']['max'],3),x['metrics']['reversalCount']) for x in sweep[f'limit-{limit}']],flush=True)
+ h.write(out/'influence-sweep.json',sweep)
+
+
+if __name__=='__main__':main()
diff --git a/scripts/review-humanoid-rerig-x1.py b/scripts/review-humanoid-rerig-x1.py
new file mode 100644
index 00000000..2d9eb770
--- /dev/null
+++ b/scripts/review-humanoid-rerig-x1.py
@@ -0,0 +1,57 @@
+"""Local matched-camera overview and close-up review; no reference data enters golden.blend."""
+import argparse
+import base64
+import importlib
+import json
+from pathlib import Path
+import sys
+import zlib
+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')
+p=argparse.ArgumentParser()
+p.add_argument('--out',default=str(h.ROOT/'artifacts/local/humanoid-rerig-x1'))
+p.add_argument('--genesis',action='store_true')
+a=p.parse_args(sys.argv[sys.argv.index('--')+1:]);out=Path(a.out).resolve()
+
+def read_obj(path):
+ v=[];f=[]
+ for line in path.read_text().splitlines():
+ parts=line.split()
+ if parts and parts[0]=='v':v.append([float(c) for c in parts[1:4]])
+ if parts and parts[0]=='f':f.append([int(c.split('/')[0])-1 for c in parts[1:]])
+ return np.array(v),f
+
+if a.genesis:
+ bpy.ops.object.select_all(action='SELECT');bpy.ops.object.delete(use_global=False)
+ scene=h.setup_camera()
+ root=out/'daz-reference';neutral,_=read_obj(root/'neutral.obj')
+ converted=neutral[:,[0,2,1]]*np.array([-1,1,1])
+ scale=1.75/np.ptp(converted[:,2]);offset=-np.array([0,0,converted[:,2].min()])*scale
+ records=[]
+ for name in ['neutral','hip70','hip90','abduction45','knee90','shoulder60','shoulder90','elbow90']:
+ v,f=read_obj(root/(name+'.obj'));v=v[:,[0,2,1]]*np.array([-1,1,1])*scale+offset
+ obj=h.mesh('Genesis 9 local rendered reference',v,f,bpy.context.scene.collection)
+ h.render(scene,obj,root/(name+'.png'));bpy.data.objects.remove(obj,do_unlink=True)
+ records.append(dict(pose=name,vertices=len(v),faces=len(f)))
+ h.write(root/'render-notes.json',dict(scale=scale,axis='(-X,+Z,+Y), height matched in neutral only',nativeDeformation='DAZ evaluated OBJ; no weight/morph transfer',cases=records))
+else:
+ bpy.ops.wm.open_mainfile(filepath=str(out/'golden.blend'),use_scripts=False)
+ rig=bpy.data.objects['X5_DEFORM'];obj=bpy.data.objects['ANTONIA_GOLDEN'];scene=bpy.context.scene
+ corpus={c['name']:c for c in json.loads(bpy.data.texts['pose-corpus.json'].as_string())}
+ metrics={c['pose']:c['metrics'] for c in h.read(out/'metrics.json')}
+ surface=json.loads(zlib.decompress(base64.b64decode(bpy.data.texts['canonical-surface.json.zlib'].as_string())))
+ cases=[('hip-flexion-70','LeftHip',.60),('hip-flexion-90','LeftHip',.60),('hip-abduction-45','LeftHip',.70),
+ ('knee-flexion-90','LeftKnee',.40),('elbow-flexion-90','LeftElbow',.36),('elbow-flexion-120','LeftElbow',.36),
+ ('shoulder-abduction-60','LeftShoulder',.48),('shoulder-abduction-90','LeftShoulder',.48)]
+ for name,joint,size in cases:
+ h.pose(rig,corpus[name]['requested']);target=rig.pose.bones[joint].matrix.translation
+ scene.camera.data.ortho_scale=size
+ for view,direction in [('front',(0,5,0)),('side',(-5,0,0)),('rear',(0,-5,0))]:
+ scene.camera.location=target+Vector(direction)
+ scene.camera.rotation_euler=(target-scene.camera.location).to_track_quat('-Z','Y').to_euler()
+ h.render(scene,obj,out/('detail--'+name+'--'+view+'.png'))
+ h.pose(rig,[])
diff --git a/scripts/summarize-humanoid-rerig-x1.py b/scripts/summarize-humanoid-rerig-x1.py
new file mode 100644
index 00000000..2ec47896
--- /dev/null
+++ b/scripts/summarize-humanoid-rerig-x1.py
@@ -0,0 +1,42 @@
+"""Local-only comparison gallery; references remain outside distributable artifacts."""
+import html
+import json
+from pathlib import Path
+from PIL import Image, ImageDraw
+
+root = Path(__file__).resolve().parents[1]
+out = root / 'artifacts/local/humanoid-rerig-x1'
+x0 = out.parent / 'humanoid-rerig-x0'
+metrics = json.loads((out / 'metrics.json').read_text())
+oracle = {'neutral':'neutral','hip-flexion-70':'hip70','hip-flexion-90':'hip90',
+ 'hip-abduction-45':'abduction45','knee-flexion-90':'knee90',
+ 'shoulder-abduction-60':'shoulder60','shoulder-abduction-90':'shoulder90','elbow-flexion-90':'elbow90'}
+body = ['<!doctype html><meta charset="utf-8"><title>X1 local comparison</title>',
+ '<style>body{font:16px system-ui;background:#202328;color:white;padding:20px}img{width:240px}td{vertical-align:top}a{color:#ace}</style>',
+ '<h1>EXPERIMENTAL GOLDEN-PATH STUDY — local evidence</h1>',
+ '<p>X5, X0, X1 and Mixamo share the camera. Genesis 9 uses matched projection and normalized height, approximate native control angles, unrelated topology. Oracle images remain local. Reversals are transported-normal proxies, not certified intersections.</p>']
+for item in metrics:
+ pose = item['pose']
+ files = [('X5', x0 / f'x5--{pose}.png'), ('X0 auto', x0 / f'pass-a--{pose}.png'),
+ ('X1 cleaned', out / f'cleaned--{pose}.png'), ('Mixamo local', x0 / f'mixamo--{pose}.png')]
+ if pose in oracle:
+ files.append(('Genesis 9 local', out / 'daz-reference' / (oracle[pose]+'.png')))
+ body.append('<h2>'+html.escape(pose)+'</h2><table><tr>')
+ for label, file in files:
+ href = '../'+file.relative_to(out.parent).as_posix()
+ body.append(f'<td>{label}<br><a href="{href}"><img src="{href}"></a></td>' if file.exists() else f'<td>{label}: unavailable</td>')
+ body.append('</tr></table><p>X1: '+html.escape(json.dumps({k:v for k,v in item['metrics'].items() if k in ['p50','p95','p99','max','minCompression','reversalCount','degenerateTriangles']}))+'</p>')
+ for view in ('front','side','rear'):
+ file = out / f'detail--{pose}--{view}.png'
+ if file.exists(): body.append(f'<a href="{file.name}"><img src="{file.name}" alt="{view}"></a>')
+ if pose in oracle:
+ sheet = Image.new('RGB', (320*len(files),390), 'white')
+ draw = ImageDraw.Draw(sheet)
+ for i,(label,file) in enumerate(files):
+ draw.text((320*i+5,5),label+' / '+pose,fill='black')
+ if file.exists():
+ image=Image.open(file).convert('RGB');image.thumbnail((320,360))
+ sheet.paste(image,(320*i,25))
+ sheet.save(out / f'comparison--{pose}.jpg')
+(out / 'comparison.html').write_text('\n'.join(body),encoding='utf-8')
+print(out / 'comparison.html')
diff --git a/tools/Aetheris.Humanoid.X0/GoldenWeightQualification.cs b/tools/Aetheris.Humanoid.X0/GoldenWeightQualification.cs
new file mode 100644
index 00000000..e9761c3e
--- /dev/null
+++ b/tools/Aetheris.Humanoid.X0/GoldenWeightQualification.cs
@@ -0,0 +1,126 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+using Aetheris.Humanoid;
+using Aetheris.Kernel.Core.Math;
+
+/// <summary>Bounded research import of portable canonical-joint weights; no rig synthesis.</summary>
+internal static class GoldenWeightQualification
+{
+ public static int Run(string input, string rig, string weightsPath, string corpusPath, 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 skeleton = adoption.Skeleton;
+ using var document = JsonDocument.Parse(File.ReadAllText(weightsPath));
+ var root = document.RootElement;
+ Require(root.GetProperty("schema").GetString() == "aetheris.humanoid.experimental-weights.v1", "Unsupported weight schema.");
+ Require(root.GetProperty("topologyId").GetString() == adoption.Surface.TopologyId, "Weight topology mismatch.");
+ Require(root.GetProperty("connectivityHash").GetString() == adoption.Surface.ConnectivityHash, "Weight connectivity hash mismatch.");
+ Require(root.GetProperty("referenceRigSha256").GetString() == Sha(rig), "Weight reference rig hash mismatch.");
+ Require(root.GetProperty("skinning").GetString() == "linear-blend-skinning", "Unsupported skinning convention.");
+ var extensions = root.GetProperty("deformationRigExtensions");
+ Require(extensions.ValueKind == JsonValueKind.Array && extensions.GetArrayLength() == 0, "Deformation rig extensions are unsupported.");
+ var maximum = root.GetProperty("maxInfluences").GetInt32();
+ Require(maximum is >= 1 and <= 8, "This experiment supports one to eight influences.");
+ var vertices = root.GetProperty("vertices");
+ Require(vertices.GetArrayLength() == adoption.Surface.Vertices.Count, "Weight vertex count mismatch.");
+ var jointIndices = skeleton.Joints.Select((joint, index) => (joint.Kind, index)).ToDictionary(x => x.Kind.ToString(), x => x.index, StringComparer.Ordinal);
+ var imported = new Dictionary<string, JointWeight[]>(StringComparer.Ordinal);
+ foreach (var vertex in vertices.EnumerateArray())
+ {
+ var id = vertex.GetProperty("vertexId").GetString() ?? throw new InvalidDataException("Missing vertex ID.");
+ var entries = vertex.GetProperty("weights");
+ Require(entries.GetArrayLength() is > 0 && entries.GetArrayLength() <= maximum, "Influence count outside declared bound: " + id);
+ var weights = new List<JointWeight>();
+ foreach (var entry in entries.EnumerateArray())
+ {
+ var bone = entry.GetProperty("boneId").GetString();
+ Require(bone is not null && jointIndices.ContainsKey(bone), "Unknown canonical bone: " + bone);
+ var value = entry.GetProperty("weight").GetDouble();
+ Require(double.IsFinite(value) && value >= 0, "Invalid weight: " + id);
+ weights.Add(new(jointIndices[bone!], value));
+ }
+ Require(weights.Select(w => w.JointIndex).Distinct().Count() == weights.Count, "Duplicate bone influence: " + id);
+ Require(Math.Abs(weights.Sum(w => w.Weight) - 1) <= CanonicalAdultStandardV1.WeightTolerance, "Unnormalized weight sum: " + id);
+ Require(imported.TryAdd(id, weights.ToArray()), "Duplicate vertex ID: " + id);
+ }
+ Require(adoption.Surface.Vertices.All(v => imported.ContainsKey(v.Id)), "Stable vertex ID set mismatch.");
+ var surface = adoption.Surface with { SkinWeights = adoption.Surface.Vertices.Select((v, i) => new VertexSkinWeights(i, imported[v.Id])).ToArray() };
+ using var corpus = JsonDocument.Parse(File.ReadAllText(corpusPath));
+ var requests = corpus.RootElement.EnumerateArray().Select(item =>
+ {
+ var name = item.GetProperty("name").GetString() ?? throw new InvalidDataException("Missing pose name.");
+ Require(name.Length > 0 && name.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_'), "Unsafe pose filename: " + name);
+ var joints = item.GetProperty("requested").EnumerateArray().Select(joint =>
+ {
+ var kind = joint.GetProperty("joint").GetString();
+ Require(kind is not null && jointIndices.ContainsKey(kind), "Unknown pose joint: " + kind);
+ return new AnatomicalJointRequest(Enum.Parse<HumanoidJointKind>(kind!), Angle("flexionDegrees"), Angle("abductionDegrees"), Angle("twistDegrees"));
+ double Angle(string key)
+ {
+ var value = joint.TryGetProperty(key, out var angle) ? angle.GetDouble() : 0;
+ Require(double.IsFinite(value), "Nonfinite pose angle: " + name);
+ return value;
+ }
+ }).ToArray();
+ return (name, joints);
+ }).ToArray();
+ Require(requests.Length > 0 && requests.Select(r => r.name).Distinct(StringComparer.OrdinalIgnoreCase).Count() == requests.Length, "Empty corpus or duplicate pose names.");
+ Directory.CreateDirectory(output);
+ Write("vertex-order.json", surface.Vertices.Select(v => v.Id));
+ var neutral = HumanoidKinematicSolver.Solve(skeleton, new("import-bind-check", skeleton.SkeletonId, skeleton.RestPoseId, 0, []));
+ Require(neutral.Pose is not null, "Reference neutral solve failed.");
+ var bind = HumanoidConstrainedSurface.Evaluate(surface, skeleton, 0, neutral.Pose!);
+ var bindMaximumMm = bind.Positions.Select((p, i) => (p - surface.Vertices[i].Position).Length).Max();
+ var heightMm = surface.Vertices.Max(v => v.Position.Z) - surface.Vertices.Min(v => v.Position.Z);
+ var cases = new List<object>();
+ foreach (var (name, joints) in requests)
+ {
+ var solve = HumanoidKinematicSolver.Solve(skeleton, new(name, skeleton.SkeletonId, skeleton.RestPoseId, 0, joints));
+ if (solve.Pose is not { } posed)
+ {
+ cases.Add(new { name, requested = joints, solve.IsSolved, solve.Diagnostics, solve.Projections });
+ continue;
+ }
+ var evaluated = HumanoidConstrainedSurface.Evaluate(surface, skeleton, 0, posed);
+ var obj = name + (evaluated.Evidence.IsAdmissible ? ".screened.obj" : ".failed-diagnostic.obj");
+ Export(Path.Combine(output, obj), surface, evaluated.Positions);
+ var positions = name + ".positions.json";
+ Write(positions, evaluated.Positions.Select(p => new[] { p.X, p.Y, p.Z }));
+ cases.Add(new { name, requested = joints, solve.IsSolved, solve.Diagnostics, solve.Projections,
+ maximumCenterResidualMm = posed.Residuals.Select(r => r.CenterMm).DefaultIfEmpty().Max(),
+ maximumLinkResidualMm = posed.Residuals.Select(r => r.LinkLengthMm).DefaultIfEmpty().Max(),
+ surfaceEvidence = evaluated.Evidence, obj, positions });
+ }
+ Write("evidence.json", new
+ {
+ schema = "aetheris.humanoid.rerig-x1.golden-weight-import.v1", solverVersion = HumanoidKinematicSolver.Version,
+ sourceCandidateSha256 = Sha(input), referenceRigSha256 = Sha(rig), weightsSha256 = Sha(weightsPath), corpusSha256 = Sha(corpusPath),
+ surface.TopologyId, surface.ConnectivityHash, vertexCount = surface.Vertices.Count,
+ declaredMaximumInfluences = maximum, observedMaximumInfluences = surface.SkinWeights.Max(w => w.Weights.Count),
+ maximumWeightSumError = surface.SkinWeights.Max(w => Math.Abs(w.Weights.Sum(x => x.Weight) - 1)),
+ bindMaximumMm, bindMaximumNormalizedByHeight = bindMaximumMm / heightMm, heightMm,
+ bindWithinExistingTolerance = bindMaximumMm <= HumanoidKinematicSolver.LinearToleranceMm,
+ stableVertexOrder = "vertex-order.json", adoption.Evidence, cases,
+ limitations = new[] { "Research diagnostic export only; no canonical promotion or visual acceptance.", "Orientation screen is a proxy; self-intersection count unavailable.", "Only surface skin weights replaced; source topology, reference skeleton and solver unchanged." }
+ });
+ Console.WriteLine($"Golden-weight import evidence: {Path.Combine(output, "evidence.json")}; {cases.Count} pose results.");
+ return 0;
+
+ void Write(string file, object value) => File.WriteAllText(Path.Combine(output, file), JsonSerializer.Serialize(value, HumanoidArtifactIO.JsonOptions));
+ }
+
+ private static void Require(bool condition, string message)
+ {
+ if (!condition) throw new InvalidDataException("GOLDEN_IMPORT: " + message);
+ }
+ private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
+ private static void Export(string path, HumanoidSurface surface, IReadOnlyList<Point3D> positions)
+ {
+ using var writer = new StreamWriter(path, false, new System.Text.UTF8Encoding(false));
+ writer.WriteLine("# NONCANONICAL diagnostic; Antonia Polygon CC-BY-3.0 Olaf Delgado-Friedrichs; no endorsement");
+ foreach (var p in positions) writer.WriteLine(FormattableString.Invariant($"v {p.X:R} {p.Y:R} {p.Z:R}"));
+ foreach (var f in surface.Faces) writer.WriteLine($"f {f.A + 1} {f.B + 1} {f.C + 1}");
+ }
+}
diff --git a/tools/Aetheris.Humanoid.X0/Program.cs b/tools/Aetheris.Humanoid.X0/Program.cs
index 9b107be8..2be82d40 100644
--- a/tools/Aetheris.Humanoid.X0/Program.cs
+++ b/tools/Aetheris.Humanoid.X0/Program.cs
@@ -18,6 +18,7 @@ static int Run(string[] args)
"judge-antonia"=>JudgmentQualification.Run(Required(args, "--input"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-x3")),
"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")),
"inspect"=>Inspect(args[1..]),
"morph"=>Morph(args[1..]),
"pose"=>Pose(args[1..]),
@@ -113,4 +114,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 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 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>");