diff --git a/characters/assombracao-lanhouse/rig.json b/characters/assombracao-lanhouse/rig.json new file mode 100644 index 0000000..ef6a135 --- /dev/null +++ b/characters/assombracao-lanhouse/rig.json @@ -0,0 +1,78 @@ +{ + "id": "assombracao-lanhouse", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.06 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "gradientRamp": 0.04, + "neckBand": 0.04 + }, + "extras": [ + { + "name": "hood", + "select": { + "from": [ + "head", + "torso" + ], + "box": { + "min": [ + null, + null, + 1.43 + ], + "max": [ + null, + null, + null + ] + } + }, + "bones": ["Spine", "neck", "Head", "LeftShoulder", "RightShoulder"], + "measure": true + }, + { + "name": "hood-crown", + "select": { "from": ["hood"], "box": { "min": [null, null, 1.58], "max": [null, null, null] } }, + "rigid": "Head", + "measure": true + }, + { + "name": "pelvis", + "select": { + "from": [ + "torso", + "leg_L", + "leg_R" + ], + "box": { + "min": [ + -0.15, + null, + 0.72 + ], + "max": [ + 0.15, + null, + 0.83 + ] + } + }, + "rigid": "Hips" + } + ] +} diff --git a/characters/bebe-reborn/rig.json b/characters/bebe-reborn/rig.json new file mode 100644 index 0000000..baa39d3 --- /dev/null +++ b/characters/bebe-reborn/rig.json @@ -0,0 +1,22 @@ +{ + "id": "bebe-reborn", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] + } +} diff --git a/characters/bebezao-de-feira/rig.json b/characters/bebezao-de-feira/rig.json new file mode 100644 index 0000000..5e1b0b5 --- /dev/null +++ b/characters/bebezao-de-feira/rig.json @@ -0,0 +1,59 @@ +{ + "id": "bebezao-de-feira", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "Hips", + "Spine02", + 0.1 + ], + [ + "Spine02", + "Spine01", + 0.1 + ] + ], + "chainLocality": 0.02, + "clavicleFloor": 0.5, + "gradientRamp": 0.04, + "flankBand": 0.04, + "flankFade": 0.06 + }, + "extras": [ + { + "name": "necklace", + "select": { + "islandMaxFaces": 100, + "grow": { + "seeds": [ + [ + -0.013, + -0.314, + 0.868 + ] + ], + "crease": 180 + } + }, + "rigid": "Spine01" + } + ], + "joints": { + "hipsAboveUpLeg": 0.08 + } +} \ No newline at end of file diff --git a/characters/bicheiro-barracao/joints.json b/characters/bicheiro-barracao/joints.json new file mode 100644 index 0000000..5dbda2f --- /dev/null +++ b/characters/bicheiro-barracao/joints.json @@ -0,0 +1,6 @@ +{ + "joints": { + "LeftLeg": [0.15, 0.02, 0.42], + "RightLeg": [-0.15, 0.02, 0.42] + } +} diff --git a/characters/bicheiro-barracao/rig.json b/characters/bicheiro-barracao/rig.json new file mode 100644 index 0000000..c9e488b --- /dev/null +++ b/characters/bicheiro-barracao/rig.json @@ -0,0 +1,28 @@ +{ + "id": "bicheiro-barracao", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "headRigidAbove": 0.06, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "neck", + "Head", + 0.05 + ] + ] + } +} diff --git a/characters/bicho-do-bueiro/rig.json b/characters/bicho-do-bueiro/rig.json new file mode 100644 index 0000000..8bb9740 --- /dev/null +++ b/characters/bicho-do-bueiro/rig.json @@ -0,0 +1,72 @@ +{ + "id": "bicho-do-bueiro", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "jointSmooth": { "joints": ["LeftShoulder", "RightShoulder", "LeftArm", "RightArm"], "radius": 0.04, "iterations": 10, "alpha": 0.5 }, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "gradientRamp": 0.04 + }, + "extras": [ + { + "name": "left-arm-rags", + "select": { + "islandMaxFaces": 300, + "box": { + "min": [ + 0.15, + null, + 1.05 + ], + "max": [ + 0.65, + null, + 1.35 + ] + } + }, + "bones": [ + "LeftShoulder", + "LeftArm", + "LeftForeArm" + ] + }, + { + "name": "right-arm-rags", + "select": { + "islandMaxFaces": 300, + "box": { + "min": [ + -0.65, + null, + 1.05 + ], + "max": [ + -0.15, + null, + 1.35 + ] + } + }, + "bones": [ + "RightShoulder", + "RightArm", + "RightForeArm" + ] + } + ] +} diff --git a/characters/boneca-da-cristaleira/rig.json b/characters/boneca-da-cristaleira/rig.json new file mode 100644 index 0000000..e81405f --- /dev/null +++ b/characters/boneca-da-cristaleira/rig.json @@ -0,0 +1,25 @@ +{ + "id": "boneca-da-cristaleira", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] + }, + "joints": { + "headAboveNeck": 0.0 + } +} diff --git a/characters/boneco-falante-87/rig.json b/characters/boneco-falante-87/rig.json new file mode 100644 index 0000000..e39294b --- /dev/null +++ b/characters/boneco-falante-87/rig.json @@ -0,0 +1,25 @@ +{ + "id": "boneco-falante-87", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "rampLength": 0.12, + "smoothRadius": 0.1, + "smoothIterations": 6, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] + } +} diff --git a/characters/capitao-caveira/rig.json b/characters/capitao-caveira/rig.json index 8bee394..d0c866e 100644 --- a/characters/capitao-caveira/rig.json +++ b/characters/capitao-caveira/rig.json @@ -3,28 +3,93 @@ "forward": "-Y", "targetHeight": 1.7, "parts": { - "skinColors": ["#b58567", "#996f55"], + "skinColors": [ + "#b58567", + "#996f55" + ], "skinTolerance": 0.12, "handPartOffset": 0.04 }, "weights": { - "linearBlends": [["LeftForeArm", "LeftHand", 0.06], ["RightForeArm", "RightHand", 0.06]] + "jointSmooth": { "joints": ["LeftShoulder", "RightShoulder", "LeftArm", "RightArm", "neck", "Spine"], "radius": 0.04, "iterations": 2, "alpha": 0.5 }, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] }, "extras": [ { "name": "backpack", - "select": { "from": ["torso"], "box": { "min": [-0.2, 0.155, 0.9], "max": [0.2, null, 1.33] } }, - "bones": ["Spine01", "Spine"] + "select": { + "from": [ + "torso" + ], + "box": { + "min": [ + -0.2, + 0.155, + 0.9 + ], + "max": [ + 0.2, + null, + 1.33 + ] + } + }, + "bones": [ + "Spine01", + "Spine" + ] }, { "name": "belt-pouches", - "select": { "islandMaxFaces": 100, "box": { "min": [null, 0.05, 0.88], "max": [null, null, 1.05] } }, + "select": { + "islandMaxFaces": 100, + "box": { + "min": [ + null, + 0.05, + 0.88 + ], + "max": [ + null, + null, + 1.05 + ] + } + }, "rigid": "Hips" }, { "name": "holster", - "select": { "islandMaxFaces": 100, "box": { "min": [null, null, 0.6], "max": [-0.15, null, 0.9] } }, + "select": { + "islandMaxFaces": 100, + "box": { + "min": [ + null, + null, + 0.6 + ], + "max": [ + -0.15, + null, + 0.9 + ] + } + }, "rigid": "RightUpLeg" } - ] + ], + "joints": { + "spineDepth": 0.15 + } } diff --git a/characters/capitao-creepy/rig.json b/characters/capitao-creepy/rig.json new file mode 100644 index 0000000..df89b69 --- /dev/null +++ b/characters/capitao-creepy/rig.json @@ -0,0 +1,32 @@ +{ + "id": "capitao-creepy", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "voxelSize": 0.012, + "smoothJoints": [ + "LeftArm", + "RightArm", + "LeftLeg", + "RightLeg", + "LeftUpLeg", + "RightUpLeg" + ], + "smoothRadius": 0.12 + } +} diff --git a/characters/chupa-cabra/rig.json b/characters/chupa-cabra/rig.json new file mode 100644 index 0000000..a512650 --- /dev/null +++ b/characters/chupa-cabra/rig.json @@ -0,0 +1,96 @@ +{ + "id": "chupa-cabra", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "jointSmooth": { "joints": ["LeftShoulder", "LeftArm"], "radius": 0.04, "iterations": 10, "alpha": 0.5 }, + "headRigidAbove": 0.06, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "neck", + "Head", + 0.05 + ], + [ + "Spine", + "neck", + 0.07 + ], + [ + "LeftShoulder", + "Head", + 0.08 + ], + [ + "RightShoulder", + "Head", + 0.08 + ], + [ + "Hips", + "LeftUpLeg", + 0.1 + ], + [ + "Hips", + "RightUpLeg", + 0.1 + ], + [ + "Hips", + "Spine02", + 0.08 + ], + [ + "Spine02", + "Spine01", + 0.08 + ] + ], + "gradientRamp": 0.04 + }, + "extras": [ + { + "name": "upper-torso-head-continuity", + "select": { + "from": [ + "torso", + "head" + ], + "box": { + "min": [ + null, + null, + 1.3 + ], + "max": [ + null, + null, + null + ] + } + }, + "bones": [ + "Spine", + "neck", + "Head", + "LeftShoulder", + "RightShoulder" + ], + "measure": true + } + ] +} diff --git a/characters/clovis-fora-do-ar/rig.json b/characters/clovis-fora-do-ar/rig.json new file mode 100644 index 0000000..fb7f241 --- /dev/null +++ b/characters/clovis-fora-do-ar/rig.json @@ -0,0 +1,23 @@ +{ + "id": "clovis-fora-do-ar", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03, + "armpitX": 0.3 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] + } +} \ No newline at end of file diff --git a/characters/coelho-pascoa-shopping/joints.json b/characters/coelho-pascoa-shopping/joints.json new file mode 100644 index 0000000..76a4fb2 --- /dev/null +++ b/characters/coelho-pascoa-shopping/joints.json @@ -0,0 +1,11 @@ +{ + "units": "m", + "space": "clean: +Z up, faces -Y, character left is +X", + "joints": { + "Hips": [ + 0.0, + 0.141, + 0.572 + ] + } +} \ No newline at end of file diff --git a/characters/coelho-pascoa-shopping/rig.json b/characters/coelho-pascoa-shopping/rig.json new file mode 100644 index 0000000..d9fda40 --- /dev/null +++ b/characters/coelho-pascoa-shopping/rig.json @@ -0,0 +1,65 @@ +{ + "id": "coelho-pascoa-shopping", + "forward": "-Y", + "targetHeight": 1.3, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "jointSmooth": { "joints": ["LeftForeArm", "RightForeArm"], "radius": 0.04, "iterations": 20, "alpha": 0.5 }, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.025 + ], + [ + "RightForeArm", + "RightHand", + 0.025 + ], + [ + "neck", + "Head", + 0.04 + ], + [ + "Spine", + "neck", + 0.04 + ] + ], + "thighCeiling": 1.0, + "clavicleFloor": 0.0 + }, + "extras": [ + { + "name": "rod", + "select": { + "box": { + "min": [ + null, + 0.2, + 0.45 + ], + "max": [ + null, + null, + 0.7 + ] + }, + "grow": { + "seeds": [ + [ + 0.0, + 0.3, + 0.575 + ] + ], + "crease": 180 + } + }, + "remove": true + } + ] +} \ No newline at end of file diff --git a/characters/corisco/rig.json b/characters/corisco/rig.json new file mode 100644 index 0000000..88416ba --- /dev/null +++ b/characters/corisco/rig.json @@ -0,0 +1,56 @@ +{ + "id": "corisco", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "headRigidAbove": 0.07, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "neck", + "Head", + 0.06 + ], + [ + "Hips", + "Spine02", + 0.08 + ], + [ + "Spine02", + "Spine01", + 0.08 + ], + [ + "Spine01", + "Spine", + 0.08 + ], + [ + "Hips", + "LeftUpLeg", + 0.1 + ], + [ + "Hips", + "RightUpLeg", + 0.1 + ] + ], + "thighCeiling": 1.0, + "clavicleFloor": 0.0, + "gradientRamp": 0.04 + } +} diff --git a/characters/coronel-arrego/joints.json b/characters/coronel-arrego/joints.json new file mode 100644 index 0000000..de558ac --- /dev/null +++ b/characters/coronel-arrego/joints.json @@ -0,0 +1,9 @@ +{ + "joints": { + "RightHand": [ + -0.63, + 0.05, + 1.21 + ] + } +} diff --git a/characters/coronel-arrego/rig.json b/characters/coronel-arrego/rig.json new file mode 100644 index 0000000..5123b2e --- /dev/null +++ b/characters/coronel-arrego/rig.json @@ -0,0 +1,23 @@ +{ + "id": "coronel-arrego", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03, + "wristX": 0.63 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] + } +} diff --git a/characters/dama-creepy/rig.json b/characters/dama-creepy/rig.json new file mode 100644 index 0000000..62228b9 --- /dev/null +++ b/characters/dama-creepy/rig.json @@ -0,0 +1,23 @@ +{ + "id": "dama-creepy", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "voxelSize": 0.018 + } +} diff --git a/characters/dom-pedro-i/rig.json b/characters/dom-pedro-i/rig.json new file mode 100644 index 0000000..eb1ecd1 --- /dev/null +++ b/characters/dom-pedro-i/rig.json @@ -0,0 +1,119 @@ +{ + "id": "dom-pedro-i", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "jointSmooth": { "joints": ["LeftArm", "RightArm"], "radius": 0.06, "iterations": 10, "alpha": 0.5 }, + "gradientRamp": 0.05, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "LeftShoulder", + "LeftArm", + 0.08 + ], + [ + "Spine", + "LeftShoulder", + 0.06 + ], + [ + "RightShoulder", + "RightArm", + 0.08 + ], + [ + "Spine", + "RightShoulder", + 0.06 + ], + [ + "Hips", + "Spine02", + 0.1 + ], + [ + "Spine02", + "Spine01", + 0.1 + ], + [ + "Spine01", + "Spine", + 0.08 + ], + ["LeftArm", "LeftForeArm", 0.05], + ["RightArm", "RightForeArm", 0.05] + ] + }, + "extras": [ + { + "name": "left-shoulder-transition", + "select": { + "from": [ + "torso", + "arm_L" + ], + "box": { + "min": [ + 0.075, + null, + 1.12 + ], + "max": [ + 0.3, + null, + 1.37 + ] + } + }, + "bones": [ + "Spine", + "LeftShoulder", + "LeftArm", + "LeftForeArm" + ], + "measure": true + }, + { + "name": "right-shoulder-transition", + "select": { + "from": [ + "torso", + "arm_R" + ], + "box": { + "min": [ + -0.3, + null, + 1.12 + ], + "max": [ + -0.075, + null, + 1.37 + ] + } + }, + "bones": [ + "Spine", + "RightShoulder", + "RightArm", + "RightForeArm" + ], + "measure": true + } + ] +} diff --git a/characters/dracula/joints.json b/characters/dracula/joints.json new file mode 100644 index 0000000..1ac6a52 --- /dev/null +++ b/characters/dracula/joints.json @@ -0,0 +1,14 @@ +{ + "joints": { + "LeftLeg": [ + 0.1, + -0.01, + 0.5 + ], + "RightLeg": [ + -0.1, + -0.01, + 0.5 + ] + } +} diff --git a/characters/dracula/rig.json b/characters/dracula/rig.json new file mode 100644 index 0000000..c693c6f --- /dev/null +++ b/characters/dracula/rig.json @@ -0,0 +1,122 @@ +{ + "id": "dracula", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "neck", + "Head", + 0.05 + ], + [ + "Spine01", + "Spine", + 0.08 + ], + [ + "Spine02", + "Spine01", + 0.1 + ], + [ + "Hips", + "Spine02", + 0.1 + ] + ], + "headRigidAbove": 0.06 + }, + "extras": [ + { + "name": "cape-back", + "select": { + "box": { + "min": [ + null, + 0.09, + 0.19 + ], + "max": [ + null, + null, + 1.4 + ] + } + }, + "bones": [ + "Hips", + "Spine02", + "Spine01", + "Spine" + ] + }, + { + "name": "cape-left-edge", + "select": { + "from": [ + "leg_L", + "torso" + ], + "box": { + "min": [ + 0.16, + null, + 0.19 + ], + "max": [ + null, + null, + 1.15 + ] + } + }, + "bones": [ + "Hips", + "Spine02", + "Spine01", + "Spine" + ] + }, + { + "name": "cape-right-edge", + "select": { + "from": [ + "leg_R", + "torso" + ], + "box": { + "min": [ + null, + null, + 0.19 + ], + "max": [ + -0.16, + null, + 1.15 + ] + } + }, + "bones": [ + "Hips", + "Spine02", + "Spine01", + "Spine" + ] + } + ] +} diff --git a/characters/ministro-creepy/rig.json b/characters/ministro-creepy/rig.json new file mode 100644 index 0000000..25c26fb --- /dev/null +++ b/characters/ministro-creepy/rig.json @@ -0,0 +1,96 @@ +{ + "id": "ministro-creepy", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "voxelSize": 0.012, + "heatFailShare": 0, + "waistBand": 0.06 + }, + "extras": [ + { + "name": "coat-skirt", + "select": { + "from": [ + "leg_L", + "leg_R", + "torso" + ], + "box": { + "max": [ + null, + null, + 0.95 + ] + }, + "grow": { + "seeds": [ + [ + 0, + 0.237, + 0.5 + ], + [ + 0.15, + -0.2245, + 0.4 + ], + [ + -0.15, + -0.2245, + 0.4 + ] + ], + "crease": 40, + "thickness": 0.02 + } + }, + "kind": "cape", + "cut": [ + "leg_L", + "leg_R" + ], + "measure": true + }, + { + "name": "waist-front", + "select": { + "from": [ + "torso" + ], + "box": { + "min": [ + null, + null, + 0.78 + ], + "max": [ + null, + -0.1, + 1.0 + ] + } + }, + "bones": [ + "Hips", + "Spine02", + "Spine01" + ] + } + ] +} diff --git a/characters/muro-de-caco/rig.json b/characters/muro-de-caco/rig.json new file mode 100644 index 0000000..a1093e5 --- /dev/null +++ b/characters/muro-de-caco/rig.json @@ -0,0 +1,25 @@ +{ + "id": "muro-de-caco", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] + }, + "joints": { + "shoulderAt": "junction" + } +} diff --git a/characters/nanica/joints.json b/characters/nanica/joints.json new file mode 100644 index 0000000..b67716b --- /dev/null +++ b/characters/nanica/joints.json @@ -0,0 +1,44 @@ +{ + "joints": { + "LeftShoulder": [ + 0.06, + 0, + 0.98 + ], + "LeftArm": [ + 0.23, + 0, + 0.98 + ], + "LeftForeArm": [ + 0.4, + -0.02, + 0.98 + ], + "LeftHand": [ + 0.56, + -0.025, + 0.975 + ], + "RightShoulder": [ + -0.06, + 0, + 0.985 + ], + "RightArm": [ + -0.23, + 0, + 0.985 + ], + "RightForeArm": [ + -0.4, + -0.015, + 0.98 + ], + "RightHand": [ + -0.56, + -0.01, + 0.975 + ] + } +} diff --git a/characters/nanica/rig.json b/characters/nanica/rig.json new file mode 100644 index 0000000..e90d6e1 --- /dev/null +++ b/characters/nanica/rig.json @@ -0,0 +1,83 @@ +{ + "id": "nanica", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03, + "armShoulderInset": 0.3, + "wristX": 0.56, + "armMinLength": null + }, + "weights": { + "jointSmooth": { "joints": ["LeftShoulder", "RightShoulder", "LeftArm", "RightArm"], "radius": 0.06, "iterations": 20, "alpha": 0.5 }, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "headRigidAbove": 1.0 + }, + "extras": [ + { + "name": "sleeve-lower-L", + "select": { + "from": [ + "torso" + ], + "box": { + "min": [ + 0.22, + null, + 0.85 + ], + "max": [ + null, + null, + 1.08 + ] + } + }, + "bones": [ + "LeftShoulder", + "LeftArm", + "LeftForeArm", + "LeftHand", + "Spine" + ] + }, + { + "name": "sleeve-lower-R", + "select": { + "from": [ + "torso" + ], + "box": { + "min": [ + null, + null, + 0.85 + ], + "max": [ + -0.22, + null, + 1.08 + ] + } + }, + "bones": [ + "RightShoulder", + "RightArm", + "RightForeArm", + "RightHand", + "Spine" + ] + } + ] +} \ No newline at end of file diff --git a/characters/padre-parapsicologo/rig.json b/characters/padre-parapsicologo/rig.json new file mode 100644 index 0000000..42b13c7 --- /dev/null +++ b/characters/padre-parapsicologo/rig.json @@ -0,0 +1,53 @@ +{ + "id": "padre-parapsicologo", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "neck", + "Head", + 0.05 + ], + [ + "Hips", + "Spine02", + 0.1 + ], + [ + "Spine02", + "Spine01", + 0.1 + ], + [ + "Spine01", + "Spine", + 0.1 + ], + [ + "LeftUpLeg", + "LeftLeg", + 0.15 + ], + [ + "RightUpLeg", + "RightLeg", + 0.15 + ] + ], + "headRigidAbove": 1.0 + } +} diff --git a/characters/pm-arrego/joints.json b/characters/pm-arrego/joints.json new file mode 100644 index 0000000..449df0d --- /dev/null +++ b/characters/pm-arrego/joints.json @@ -0,0 +1,44 @@ +{ + "joints": { + "LeftShoulder": [ + 0.075, + 0.12, + 1.29 + ], + "LeftArm": [ + 0.25, + 0.12, + 1.29 + ], + "LeftForeArm": [ + 0.43, + 0.06, + 1.28 + ], + "LeftLeg": [ + 0.16, + 0.025, + 0.42 + ], + "RightShoulder": [ + -0.075, + 0.12, + 1.29 + ], + "RightArm": [ + -0.25, + 0.12, + 1.29 + ], + "RightForeArm": [ + -0.43, + 0.06, + 1.28 + ], + "RightLeg": [ + -0.16, + 0.025, + 0.42 + ] + } +} diff --git a/characters/pm-arrego/rig.json b/characters/pm-arrego/rig.json new file mode 100644 index 0000000..8355e12 --- /dev/null +++ b/characters/pm-arrego/rig.json @@ -0,0 +1,27 @@ +{ + "id": "pm-arrego", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03, + "armShoulderInset": 0.15 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "headRigidAbove": 1.0 + }, + "joints": { + "spineDepth": 0.15 + } +} diff --git a/characters/prata/rig.json b/characters/prata/rig.json new file mode 100644 index 0000000..c249d54 --- /dev/null +++ b/characters/prata/rig.json @@ -0,0 +1,43 @@ +{ + "id": "prata", + "forward": "-Y", + "targetHeight": 1.7, + "weights": { + "jointSmooth": { "joints": ["LeftShoulder", "RightShoulder", "LeftArm", "RightArm"], "radius": 0.03, "iterations": 5, "alpha": 0.5 }, + "gradientRamp": 0.05, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.035 + ], + [ + "RightForeArm", + "RightHand", + 0.035 + ], + [ + "Hips", + "LeftUpLeg", + 0.15 + ], + [ + "Hips", + "RightUpLeg", + 0.15 + ], + [ + "LeftShoulder", + "LeftArm", + 0.08 + ], + [ + "RightShoulder", + "RightArm", + 0.08 + ], + ["LeftArm", "LeftForeArm", 0.05], + ["RightArm", "RightForeArm", 0.05] + ] + } +} diff --git a/characters/profeta-auditorio/rig.json b/characters/profeta-auditorio/rig.json new file mode 100644 index 0000000..7f94c66 --- /dev/null +++ b/characters/profeta-auditorio/rig.json @@ -0,0 +1,34 @@ +{ + "id": "profeta-auditorio", + "forward": "-Y", + "targetHeight": 1.7, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.035 + ], + [ + "RightForeArm", + "RightHand", + 0.035 + ], + [ + "Hips", + "Spine02", + 0.1 + ], + [ + "Spine02", + "Spine01", + 0.1 + ], + [ + "Spine01", + "Spine", + 0.1 + ] + ] + } +} diff --git a/characters/roqueiro-mistico-70/rig.json b/characters/roqueiro-mistico-70/rig.json new file mode 100644 index 0000000..cfb078f --- /dev/null +++ b/characters/roqueiro-mistico-70/rig.json @@ -0,0 +1,15 @@ +{ + "id": "roqueiro-mistico-70", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { "handPartOffset": 0.04 }, + "weights": { + "linearBlends": [["LeftForeArm", "LeftHand", 0.06], ["RightForeArm", "RightHand", 0.06]], + "jointSmooth": { "joints": ["LeftArm", "RightArm", "LeftShoulder", "RightShoulder", "neck", "LeftForeArm", "RightForeArm", "Spine", "Head"], "radius": 0.06, "iterations": 40, "alpha": 0.5 } + }, + "extras": [ + { "name": "buckle", "select": { "box": { "min": [-0.07, -0.12, 0.92], "max": [0.07, -0.07, 0.99] } }, "rigid": "Hips" }, + { "name": "fringe-L", "select": { "box": { "min": [0.20, null, 1.10], "max": [0.48, null, 1.25] } }, "bones": ["LeftArm", "LeftForeArm", "LeftHand"] }, + { "name": "fringe-R", "select": { "box": { "min": [-0.48, null, 1.10], "max": [-0.20, null, 1.25] } }, "bones": ["RightArm", "RightForeArm", "RightHand"] } + ] +} diff --git a/characters/satanista-talkshow/rig.json b/characters/satanista-talkshow/rig.json new file mode 100644 index 0000000..bd466e5 --- /dev/null +++ b/characters/satanista-talkshow/rig.json @@ -0,0 +1,69 @@ +{ + "id": "satanista-talkshow", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + [ + "LeftShoulder", + "LeftArm", + 0.06 + ], + [ + "RightShoulder", + "RightArm", + 0.06 + ] + ], + "sideExclusive": 0.03, + "chainLocality": 0.02, + "gradientRamp": 0.04 + }, + "joints": { + "kneeBendMin": 1 + }, + "extras": [ + { + "name": "cape", + "select": { + "from": [ + "torso", + "leg_L", + "leg_R" + ], + "box": { + "max": [ + null, + null, + 1.2 + ] + }, + "grow": { + "seeds": [ + [ + 0, + 0.11, + 0.6 + ] + ], + "crease": 180.0, + "thickness": 0.03 + } + }, + "kind": "cape" + } + ] +} diff --git a/characters/sorridente-onibus/rig.json b/characters/sorridente-onibus/rig.json new file mode 100644 index 0000000..aef4a6a --- /dev/null +++ b/characters/sorridente-onibus/rig.json @@ -0,0 +1,56 @@ +{ + "id": "sorridente-onibus", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "gradientRamp": 0.05, + "voxelSize": 0.003, + "rampLength": 0.12, + "smoothRadius": 0.1, + "smoothIterations": 6, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ], + ["LeftShoulder", "LeftArm", 0.06], + ["LeftArm", "LeftForeArm", 0.05], + ["RightShoulder", "RightArm", 0.06], + ["RightArm", "RightForeArm", 0.05] + ] + }, + "extras": [ + { + "name": "pelvis", + "select": { + "from": [ + "torso", + "leg_L", + "leg_R" + ], + "box": { + "min": [ + -0.06, + null, + 0.78 + ], + "max": [ + 0.06, + null, + 0.84 + ] + } + }, + "rigid": "Hips" + } + ] +} diff --git a/characters/teletreco-antenao/rig.json b/characters/teletreco-antenao/rig.json new file mode 100644 index 0000000..2822872 --- /dev/null +++ b/characters/teletreco-antenao/rig.json @@ -0,0 +1,64 @@ +{ + "id": "teletreco-antenao", + "forward": "-Y", + "targetHeight": 1.3, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.025 + ], + [ + "RightForeArm", + "RightHand", + 0.025 + ], + [ + "Hips", + "LeftUpLeg", + 0.12 + ], + [ + "Hips", + "RightUpLeg", + 0.12 + ] + ], + "smoothRadius": 0.18, + "smoothIterations": 12, + "smoothJoints": [ + "LeftArm", + "RightArm", + "LeftLeg", + "RightLeg", + "Hips", + "LeftUpLeg", + "RightUpLeg" + ] + }, + "extras": [ + { + "name": "antenna", + "select": { + "islandMaxFaces": 100, + "box": { + "min": [ + null, + null, + 1.0 + ], + "max": [ + null, + null, + null + ] + } + }, + "rigid": "Head" + } + ] +} diff --git a/characters/teletreco-chiadinho/rig.json b/characters/teletreco-chiadinho/rig.json new file mode 100644 index 0000000..d704170 --- /dev/null +++ b/characters/teletreco-chiadinho/rig.json @@ -0,0 +1,65 @@ +{ + "id": "teletreco-chiadinho", + "forward": "-Y", + "targetHeight": 1.3, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "jointSmooth": { "joints": ["LeftShoulder", "RightShoulder"], "radius": 0.03, "iterations": 20, "alpha": 0.5 }, + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.025 + ], + [ + "RightForeArm", + "RightHand", + 0.025 + ], + [ + "Hips", + "LeftUpLeg", + 0.12 + ], + [ + "Hips", + "RightUpLeg", + 0.12 + ] + ], + "smoothRadius": 0.18, + "smoothIterations": 12, + "smoothJoints": [ + "LeftArm", + "RightArm", + "LeftLeg", + "RightLeg", + "Hips", + "LeftUpLeg", + "RightUpLeg" + ] + }, + "extras": [ + { + "name": "antenna", + "select": { + "islandMaxFaces": 100, + "box": { + "min": [ + null, + null, + 1.0 + ], + "max": [ + null, + null, + null + ] + } + }, + "rigid": "Head" + } + ] +} diff --git a/characters/teletreco-fora-do-ar/rig.json b/characters/teletreco-fora-do-ar/rig.json new file mode 100644 index 0000000..7411ee2 --- /dev/null +++ b/characters/teletreco-fora-do-ar/rig.json @@ -0,0 +1,64 @@ +{ + "id": "teletreco-fora-do-ar", + "forward": "-Y", + "targetHeight": 1.3, + "parts": { + "handPartOffset": 0.03 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.025 + ], + [ + "RightForeArm", + "RightHand", + 0.025 + ], + [ + "Hips", + "LeftUpLeg", + 0.12 + ], + [ + "Hips", + "RightUpLeg", + 0.12 + ] + ], + "smoothRadius": 0.18, + "smoothIterations": 12, + "smoothJoints": [ + "LeftArm", + "RightArm", + "LeftLeg", + "RightLeg", + "Hips", + "LeftUpLeg", + "RightUpLeg" + ] + }, + "extras": [ + { + "name": "antenna", + "select": { + "islandMaxFaces": 100, + "box": { + "min": [ + null, + null, + 1.0 + ], + "max": [ + null, + null, + null + ] + } + }, + "rigid": "Head" + } + ] +} diff --git a/characters/tiradentes/rig.json b/characters/tiradentes/rig.json new file mode 100644 index 0000000..a339c8f --- /dev/null +++ b/characters/tiradentes/rig.json @@ -0,0 +1,33 @@ +{ + "id": "tiradentes", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "smoothRadius": 0.08, + "smoothIterations": 3, + "smoothJoints": [ + "LeftArm", + "RightArm", + "LeftLeg", + "RightLeg" + ], + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ] + }, + "joints": { + "shoulderAt": "junction" + } +} diff --git a/characters/vlad/rig.json b/characters/vlad/rig.json new file mode 100644 index 0000000..4d630b5 --- /dev/null +++ b/characters/vlad/rig.json @@ -0,0 +1,116 @@ +{ + "id": "vlad", + "forward": "-Y", + "targetHeight": 1.7, + "parts": { + "handPartOffset": 0.04 + }, + "weights": { + "linearBlends": [ + [ + "LeftForeArm", + "LeftHand", + 0.06 + ], + [ + "RightForeArm", + "RightHand", + 0.06 + ] + ], + "thighCeiling": 1.0, + "waistBand": null, + "chainLocality": 0.02, + "gradientRamp": 0.05, + "groinBand": 0.08 + }, + "joints": { + "kneeBendMin": 1 + }, + "extras": [ + { + "name": "coat-upper", + "select": { + "from": [ + "torso" + ], + "box": { + "min": [ + null, + null, + 0.9 + ], + "max": [ + null, + null, + 1.2 + ] + }, + "grow": { + "seeds": [ + [ + 0, + 0.13, + 1.0 + ] + ], + "crease": 40, + "thickness": 0.06 + } + }, + "kind": "cape", + "measure": true + }, + { + "name": "coat-lower", + "select": { + "from": [ + "torso", + "leg_L", + "leg_R" + ], + "box": { + "max": [ + null, + null, + 0.9 + ] + }, + "grow": { + "seeds": [ + [ + 0, + 0.216, + 0.5 + ] + ], + "crease": 40, + "thickness": 0.06 + } + }, + "kind": "cape", + "cut": [ + "leg_L", + "leg_R" + ] + }, + { + "name": "buckle", + "select": { + "box": { + "min": [ + -0.09, + -0.24, + 0.8 + ], + "max": [ + 0.09, + -0.17, + 1.03 + ] + } + }, + "rigid": "Hips" + } + ] +} \ No newline at end of file diff --git a/docs/character-pack.md b/docs/character-pack.md index 3fa88f9..9c01da0 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -65,7 +65,7 @@ Photos of real people never enter either repository. `npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB and eleven one-channel clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, and hash or size mutations. -`npm run check` also runs `tools/checks/character-rig-check.mjs`, the deterministic half of the Blender rig pipeline that produces these models (configs, `joints.json` validation, meshy-28 assembly and the pose test on a synthetic humanoid); see [character-rig.md](character-rig.md). +`npm run check` also runs `tools/checks/character-rig-check.mjs`, the deterministic half of the Blender rig pipeline that produces these models (configs, `joints.json` validation, meshy-28 assembly, the pose test on a synthetic humanoid, and the runner's step freshness with a fake Blender); see [character-rig.md](character-rig.md). ## Concept generation diff --git a/docs/character-rig.md b/docs/character-rig.md index e0aa71a..5e3aa06 100644 --- a/docs/character-rig.md +++ b/docs/character-rig.md @@ -17,7 +17,9 @@ node tools/characters/rig-character.mjs \ --retarget=/tools/retarget-glb.mjs ``` -`--from=` resumes at `clean`, `parts`, `joints`, `armature`, `weights`, `assemble` or `pose` (for example after adding a `joints.json` override). `--blender=` or `BLENDER` selects the binary (default `/Applications/Blender.app/Contents/MacOS/Blender`). Each Blender step can also run alone: +`--from=` resumes at `clean`, `parts`, `joints`, `armature`, `weights`, `assemble` or `pose` (for example after adding a `joints.json` override); `--to=` stops early. `--blender=` or `BLENDER` selects the binary (default `/Applications/Blender.app/Contents/MacOS/Blender`). + +Every Blender step exits 1 on any Python exception (`C.run_main`; plain `blender --python` exits 0). Before a step runs, the runner deletes its outputs and those of every later step, including the orthographic renders, their `.view.json` sidecars and the review sheets (also with `--skip-review`); afterwards each output must exist and be newer than the step, whatever the exit code. `/run-manifest.json` records per step the SHA-256 of its inputs (source, config, joints override) and outputs, and `--from` refuses to resume when a skipped step's outputs or inputs changed since it ran. Each Blender step can also run alone: ```bash Blender -b --factory-startup --python tools/blender/character_rig/rig_.py -- --config characters//rig.json --work [--source ] @@ -37,9 +39,9 @@ Blender -b --factory-startup --python tools/blender/character_rig/rig_.py **clean** turns the source so the character faces −Y in Blender (+Z in glTF; `forward` names the axis the source faces), scales it to `targetHeight` with the feet on z = 0, centres the legs on the origin, applies every transform, merges coincident seam vertices by distance (`mergeDistance`, 0.1 mm), dissolves degenerate faces and recalculates outward normals. `clean.json` reports seam vertices before/after the merge, flipped faces, zero-area faces, boundary and non-manifold edges, loose parts and the measured height. -**parts** tags every face (`rig_part` face attribute) from landmarks of a 1 cm front silhouette and Y-ray cross-sections: legs below the crotch (first row where the midline is 2.5% of the height deep, so touching thighs still split), arms outside the armpit and above it, hands past the wrist, head above the narrowest neck row, torso for the rest. The wrist is the thinnest arm section just inside the widest palm section, or, with `parts.skinColors`, where skin-coloured texels start on the distal arm. The rigid hand part starts `parts.handPartOffset` × height past the wrist (default 0.03). `extras` carve out accessories by AND-combined selectors over position (`box`), texture colour (`colors` + `tolerance`), loose islands (`islandMaxFaces`) and current part (`from`), each with `rigid` (100% on one bone) or `bones` (allowed set). `parts.json` lists the face counts, the landmarks and the texture palette (k-means hex colours) to write colour selectors against. Review `parts-review.png` before going on. +**parts** tags every face (`rig_part` face attribute) from landmarks of a 1 cm front silhouette and Y-ray cross-sections: legs below the crotch (first row where the midline is 2.5% of the height deep, so touching thighs still split), arms outside the armpit and above it, hands past the wrist, head above the narrowest neck row, torso for the rest. The wrist is the thinnest arm section just inside the widest palm section, or, with `parts.skinColors`, where skin-coloured texels start on the distal arm. The rigid hand part starts `parts.handPartOffset` × height past the wrist (default 0.03). `extras` carve out accessories by AND-combined selectors over position (`box`), texture colour (`colors` + `tolerance`), loose islands (`islandMaxFaces`), current part (`from`) and connectivity (`grow`), each with `rigid` (100% on one bone) or `bones` (allowed set). `grow: { seeds: [[x, y, z], …], crease, thickness }` keeps only the faces connected to the seed points (each within 5 cm of the surface): the region spreads over shared edges while the other selectors allow the face and the fold stays under `crease` degrees (default 40), so a cape's outer sheet stops at its hem and at the seams where it is fused to a boot or a coat; `thickness` (m) then adds every face connected to it through faces within that distance (the hem fold and the inner side of a thin sheet). A box only bounds the growth, so the back half of a leg or a boot inside a cape's box is no longer cape. `cut: ["leg_L", "leg_R"]` deletes the extra's faces that share a vertex with those parts, so a hem fused to a trouser leg or a heel hangs free instead of tearing between the cloth weights and the leg weights; the cut only removes one face ring, it never moves or welds vertices (`parts.json` reports `cutFaces`). `remove: true` deletes every face of the extra and fills the opening it leaves in the rest of the mesh (`bmesh` hole fill, the cap takes its neighbours' part; `parts.json` reports `removedFaces`); it is for geometry the concept does not have, and since it changes the design, check the concept first. coelho-pascoa-shopping's Mint mesh has a 44 cm rod with a ball fused to its tail, pointing straight back at hip height; the concept (`studio-assets characters/coelho-pascoa-shopping/concept/concept.jpg`) shows no such prop (the ficha lists a bow tie and a basket on the back), so the rod is removed (243 faces). The rod had pulled the measured `Hips` 8.5 cm back (y 0.141 instead of 0.056); without it death tore at the tail (4.12×), so its `joints.json` keeps `Hips` at the old position (3.30×, as before). **Short-arm guard.** The armpit is the edge of the torso run under the arm band; a sleeve or costume that fills the space under the arm (clovis-fora-do-ar's puffed sleeves, bebezao-de-feira's and boneca-da-cristaleira's short sleeves over a wide body, the cords on coronel-arrego's right shoulder) pushes it out to the sleeve end, a few centimetres from the wrist. The arm part then starts there, the sleeve stays torso (no arm bones), the shoulder joint lands near the wrist with the elbow squeezed between, and every clip leaves the arm in T while the stretch gate passes. When armpit→wrist (the configured `wristX` if set) is shorter than `parts.armMinLength` × height (0.1; every healthy rig of the 2026-11-09 set is ≥ 0.115, the four broken ones 0.065–0.088), the armpit takes the other side's when that side is long enough (coronel-arrego's right arm: 0.512 → 0.362 m), else the arm–torso junction (bebezao-de-feira 0.456 → 0.212 m, boneca-da-cristaleira 0.379 → 0.174 m); a far-out hand is then still measured from the torso run, so a wide skirt hem does not become arm. When neither is long enough (clovis-fora-do-ar: the junction lies under the puff too), set `parts.armpitX` from the 5 cm grid (clovis: 0.30 m). `parts.json` and the joint notes record the source (`armpitSource`). `parts.json` lists the face counts, the landmarks and the texture palette (k-means hex colours) to write colour selectors against. Review `parts-review.png` before going on. -**joints** estimates all 26 distinct meshy-28 joints on the body without extras (a backpack or an antenna must not pull the spine or the head), every joint on the centroid of its limb or torso cross-section: shoulder just inside the armpit on the line fitted through the outer arm sections, elbow at `elbowRatio` of shoulder→wrist, hip at the crotch row + `hipAboveCrotch`, ankle at the thinnest leg section near the floor, knee at the strongest side-profile bend (bent mascot legs) or at `kneeRatio`, toe on the ball of the foot, `Hips`/`Spine` on the torso centroid with `Spine02`/`Spine01` on the line between them, `Head` just above the narrowest neck row. Ratios under `joints` in the config override the defaults, which were measured on the donor mesh (see Calibration). `joints-review.png` shows the front and side orthographic views with the 5 cm grid (labels in metres) and every joint; a `joints.json` next to the config (or `jointsOverride`) moves any subset of joints and wins: +**joints** estimates all 26 distinct meshy-28 joints on the body without extras (a backpack or an antenna must not pull the spine or the head), every joint on the centroid of its limb or torso cross-section: shoulder just inside the armpit on the line fitted through the outer arm sections, elbow at `elbowRatio` of shoulder→wrist, hip at the crotch row + `hipAboveCrotch`, ankle at the thinnest leg section near the floor, toe on the ball of the foot, `Head` just above the narrowest neck row. The knee is searched only in the middle of the leg (`kneeWindow`, 0.38–0.62 of ankle→hip, so folds above a boot and at the hip are ignored): the strongest forward bend of the side profile of at least `kneeBendMin` (a bent leg; a bend backwards is a calf, a fold or a boot back), else the narrowest leg section between thigh and calf (cross-section area smoothed over 5 cm, `kneeProminence` below its sides, no row-to-row step over `kneeStepMax`, which is what a boot top or a coat hem looks like), else `kneeRatio`. `Hips`, `Spine02`, `Spine01` and `Spine` sit on the torso medial axis: the centroids of horizontal sections every 1 cm, sections off their running median dropped (a pouch, a belt buckle), and a tricube-weighted local line through the sections within 3% of the height of each joint; `neck` takes the median of its own narrower sections. `joints.shoulderAt: "junction"` moves the shoulder from the armpit (the torso run under the arm band, which a wide sleeve, a dropped T-shirt shoulder or an epaulette pushes out) to the arm-torso junction, where the underarm gap of the front silhouette opens; it is opt-in because it regressed most characters with fitted sleeves (see Limits). Ratios under `joints` in the config override the defaults, which were measured on the donor mesh (see Calibration). `joints-review.png` shows the front and side orthographic views with the 5 cm grid (labels in metres) and every joint; a `joints.json` next to the config (or `jointsOverride`) moves any subset of joints and wins: ```json { "joints": { "LeftArm": [0.17, 0.10, 1.36], "RightArm": [-0.17, 0.10, 1.36] }, "tips": { "LeftHand": [0.73, 0.0, 1.33] } } @@ -54,11 +56,17 @@ Coordinates are clean-space metres: +Z up, the character faces −Y, its left is **weights**: 1. Heat (automatic) weights on the cleaned mesh; a voxel remesh of the body (`voxelSize` × height) is heat-weighted too and transfers its weights to vertices heat left bare (loose islands such as eyes or pouches), or to every vertex when heat failed on a limb bone or left more than `heatFailShare` of the main shell bare. -2. Part rules: torso, vest and backpack never carry arm bones; legs carry only their own chain plus `Hips`; arms their own chain plus `Spine` and the clavicle; hands are 100% on their `Hand`; the head is 100% on `Head` above `Head` + `headRigidAbove` × height; extras follow their `rigid`/`bones`. +2. Part rules: torso, vest and backpack never carry arm bones; legs carry only their own chain plus `Hips`; arms their own chain plus `Spine` and the clavicle; hands are 100% on their `Hand`; the head is 100% on `Head` above `Head` + `headRigidAbove` × height; extras follow their `rigid`/`bones`. Opt-in height limits: with `thighCeiling`, vertices on no leg part carry the thighs no higher than that fraction of UpLeg → Hips; with `clavicleFloor`, vertices on no arm part carry the clavicles no lower than that fraction of Spine02 → Spine01 (heat lets a thigh climb a coat front or a clavicle slide down a chest). Switched on for every character they made five passing rigs fail, so they stay off by default. Two more opt-in limits act on vertices of no limb part: `chainLocality` (× height) allows each spine-chain bone (`Hips` … `neck`) only between its parent and child joints plus the margin, where a linear blend along the chain would weight it (heat left `Hips` 0.30 on vlad's chest 25 cm above the joint); `sideExclusive` (× height) removes every `Left*` bone from vertices more than the margin right of the midline and every `Right*` bone from the other side (heat through satanista-talkshow's collar put `RightShoulder` 0.14 on the left armpit). satanista-talkshow passes with both (`0.02`, `0.03`) plus `gradientRamp` 0.04 and shoulder → arm `linearBlends` (worst clip 3.79× → 3.39×). 3. Continuity: a bone allowed on one side of a part boundary and forbidden on the other fades to zero towards the boundary over `rampLength` × height of surface distance. The fade scales existing weights, so where a vertex carries nothing on the bones allowed across the boundary, normalisation restores the old ratios and a step can remain; the pose test is the guard. 4. Smoothing inside a part only, tapering to nothing at `smoothRadius` × height from `smoothJoints` (shoulders and knees), never on part-boundary or rigid vertices, never across parts. Elbows are not smoothed by default: on capitao-caveira it raised the worst walk stretch at the back of the elbow from 2.88× to 4.28×. 5. Linear hinge blends (`linearBlends`, wrists by default): the ForeArm+Hand share is re-split by position along the forearm axis, smoothstep over ±halfWidth × height, because heat switches ForeArm→Hand within one edge ring. -6. At most 4 influences per vertex, normalised. `weights.json` reports the method, bare vertices, the largest arm weight left on no-arm parts (must be 0), the minimum `Hand` weight on hand vertices (must be 1) and the influence histogram. +6. Hanging cloth: extras with `kind: "skirt"` (coat skirts, skirts, cassocks) or `kind: "cape"` get procedural weights. Above the hips they follow the spine chain by height; below the hip joints they fade into the thighs down to the knees, split left/right by x, with 80% (skirt) or 45% (cape) of the weight on the legs at knee height and the rest on `Hips`. Vertices on the seam between two cloth extras (a coat split into `coat-upper` and `coat-lower`) take the mean of both extras' cloth weights; left on heat, vlad's seam carried `Hips` 0.61 + `RightUpLeg` 0.28 next to cloth vertices at `Hips` 0.96 and tore in death (4.05× → 3.58× with the seam rule). Opt-in `frontPanel` on a cloth extra (`true` or `{ "share": 0.25, "spread": 3 }`): in front of the hip joints (blended in over one hip half-width) the cloth below the hips follows both thighs, split over ±`spread` × the hip half-width instead of ±1, with `share` of the weight on the legs at knee height instead of the kind's share. On vlad's `coat-lower` it changed nothing measurable (3.583× with and without): the remaining tear was the groin, not the coat front. +7. Band models (opt-in, `waistBand` and `neckBand`, × height): inside a horizontal band the rule weights are replaced by a smooth function of height and of the angle around the torso axis, fading back over half the margin beyond each end. The waist band runs from `waistBand` below the hip joints up to `Spine02`: the thighs take the sides (|sin| of the angle around the vertical through `Hips`, so a belly, a coat front and the small of the back stay on the spine) and fade out by the `Hips` joint, the rest goes `Hips` → `Spine02` by height. The neck band runs from `Spine` to `neckBand` above `Head`: the clavicles take the sides and fade out by `neck`, the rest goes `Spine` → `neck` → `Head`. Arms, hands and rigid vertices are left alone; `weights.json` reports `bandVertices`. On ministro-creepy the waist band (with the coat as a measured cape) took the worst clip from 6.89× to 3.27× (PASS); it helped vlad (6.03× → 5.30×) and ursinho-fliperama's neck band 5.42× → 4.40×, but made barbudo-creepy, bebezao-de-feira, rapper-zona-sul and dino-festa (tail) worse, so neither is a default. + The flank band (`flankBand`, × height) runs from `Hips` to `Spine01` on the torso sides only (|sin| of the angle around the vertical through `Hips` from 0.5 to 0.9, so the belly front and the back keep their weights): no clavicle and no thigh there, only `Hips` → `Spine02` → `Spine01` by height; legs and head are left alone. `flankFade` (× height) sets the length of its lower fade, which ends at the `Hips` joint (default half of `flankBand`). On bebezao-de-feira, `flankBand` 0.04 removed the crouchwalk tear on the left flank (`LeftShoulder` 0.43 at 0.925 m next to `LeftUpLeg` 0.29 at 0.895 m; crouchwalk 3.59× → 3.48×), but its default lower fade, 3.4 cm under `Hips`, became the new step in death (thigh 0.55 at 0.70 m next to `Hips` 0.85 at 0.75 m; 3.25× → 3.77×). With `flankFade` 0.043 (fade from 0.65 m) death was still 4.09×; 0.06 and 0.08 brought death to 3.09× and bebezao passes at 3.48× (crouchwalk) with 0.06. +8. Groin: within `groinBand` × height (0.05) of the crotch and between the thigh joints, the thigh share moves to `Hips`, fully on the midline, so spreading the legs does not tear the crotch. Where a tunic or a buckle hangs in front of the crotch the band's edge can itself be the step: on vlad (crotch 0.74 m) the midline went from `Hips` 0.46 at 0.795 m to 0.71 at 0.775 m and tore in death (3.58×); `groinBand` 0.08 (with `gradientRamp` 0.05) moved the edge off the tunic and vlad passes at 3.30× (crouch). +9. Gradient limit: the ramps of step 3 only scale weights that already exist, so neighbouring vertices could still switch bones within millimetres (heat on layered cloth, proxy transfer across fused voxels, binary weights on small islands). Every edge whose weight change exceeds its length over `gradientRamp` × height (0.025) is relaxed towards its neighbour, rigid vertices held fixed, until no edge exceeds it (`gradientIterations`). This creates shared influence across part borders. +10. At most 4 influences per vertex, normalised. `weights.json` reports the method, bare vertices, the largest arm weight left on no-arm parts (must be 0), the minimum `Hand` weight on hand vertices (must be 1), cloth and groin vertex counts, the gradient-limit iterations and the influence histogram. +11. Joint-zone smoothing (opt-in, `jointSmooth`: `{ "joints": [...], "radius": × height, "iterations": n, "alpha": 0–1 }`): on the final weights, every vertex within `radius` of a listed joint (fading to nothing at twice that) moves `alpha` of the way to the mean of its mesh neighbours per iteration, over the bones it already carries only. No vertex gains a bone, so the part rules, rigid vertices and the 4-influence limit hold; the neighbours are the welded mesh's, so UV seams stay closed. It is for the client's selection screen (`select-inflate`: the game's mixer, support-hand IK and finger curl on the idle with the character's weapon), where raised arms fold shoulder, armpit and neck edges to under half their length. On 9 "Fora do Ar" characters over that gate's ceiling it lowered the torn-edge count (ruins/1e4) from 24.2–52.9 to 7.4–41.2 with the strict pose test still passing; the joints, radius and iterations differ per character (for example dom-pedro-i `LeftArm`/`RightArm` 0.06 × 10: 29.4 → 7.4; prata shoulders 0.03 × 5: 34.6 → 15.9). It is not used on dracula, where it lowered the count (33.3 → 24.1) but raised the 99th percentile (0.501 → 0.576), nor on bebezao-de-feira, where `neck`/`Spine`/`Head` 0.06 × 20 lowered it 39.6 → 23.3 but the baked `walk1h` then failed clip QA (3.59× > 3.5). `weights.json` reports `jointSmoothedVertices`. **assemble** drops Blender's skeleton and builds the meshy-28 skin in contract order (duplicate `Curl` pair included) under an `Armature` node scaled 0.01 (centimetre bones, metre mesh, like the donor), with fresh inverse bind matrices; it fails unless the bind pose reproduces the mesh to 0.1 mm. Rest frames: spine, legs, clavicles and head keep the donor's rest world rotations (`MESHY28_REST_WORLD` in `tools/lib/character-rig.mjs`; the client's `retarget-glb.mjs` applies world-rotation deltas there). `LeftArm`, `LeftForeArm`, `LeftHand` and their right counterparts are turned by the shortest arc that puts local +Y (the meshy-28 bone axis) on the measured bone, because `retarget-glb.mjs` copies the clip's **absolute** world rotations onto every Arm/Hand bone: only an aligned frame makes the character's arm segments point where the clip's arms point (Mint T-poses angle the arms forward, the donor's angle them ~20° back). @@ -66,7 +74,7 @@ Coordinates are clean-space metres: +Z up, the character faces −Y, its left is `node tools/characters/rig-pose-test.mjs --clips= --out= [--strict] [--bake=[@]:]` skins on the CPU exactly like three.js (`Σ w · jointWorld · IBM · v`) and measures five synthetic poses (arms up 90°, arms forward 60°, a step with each leg, head turned 60°) and 8 instants of each of the 11 state clips (pass the clips retargeted to that model). Per pose: the longest edge stretch versus the bind pose, the 99th percentile, the upper-back region (between `Hips` and `neck`, behind `Spine01`), each hand (edges touching ≥ 25% hand weight, the client's `rig-maos-check` rule), the largest gap between vertices welded in the bind pose (UV seams), and the 10 worst vertices with their bones. `--bake` writes a static posed copy for renders (`tools/blender/character_rig/render_poses.py`, front/back/three-quarter with identical framing; `rig-review.mjs sheet` makes contact sheets). -Thresholds (`POSE_THRESHOLDS`): body and upper back ≤ 3.5× (the donor reaches 3.04× on its own clips), hands ≤ 2.5× (the client hand gate), seams ≤ 5 mm, bind error ≤ 2 mm. `--strict` exits 1 on any failure. +Thresholds (`POSE_THRESHOLDS`): body and upper back ≤ 3.5× (the donor reaches 3.04× on its own clips), hands ≤ 2.5× (the client hand gate), seams ≤ 5 mm, bind error ≤ 2 mm. Two arm gates catch a rig whose stretch is fine but whose arms do not move: the bind-pose `Arm`→`ForeArm` / `ForeArm`→`Hand` length ratio must lie in [0.6, 1.7] (the donor: 0.99 left, 1.06 right; report `arms`), and with clips the **idle arm angle** must lie within ±25° of the donor's. The idle arm angle is measured on the skinned mesh at `idle` at 0.5 of its duration: the angle between world down and the line from the posed `Shoulder` (clavicle) joint to the centroid of the posed hand vertices (hand weight ≥ 0.5); 0° hangs straight down, 90° is T. The donor `mst` on its own idle gives 50.8° left and 38.0° right (a rifle idle; report `armIdle`). It follows the mesh, not the bones: the clips turn the `Arm` bone the same way wherever it sits, but when the `Arm` joint sits near the wrist the clavicle carries the whole arm and the mesh stays in T (clovis-fora-do-ar 79.7°/76.5° before the fix). `--strict` exits 1 on any failure; the runner runs the pose test strict, so both gates also stop `rig-character.mjs`. ## Configuration (`characters//rig.json`) @@ -75,11 +83,11 @@ Thresholds (`POSE_THRESHOLDS`): body and upper back ≤ 3.5× (the donor reaches | `id`, `forward`, `targetHeight` | Folder id; axis the source faces (`-Y`, `+Y`, `-X`, `+X`); height in metres after cleaning. | | `mergeDistance` | Seam merge distance in metres (default 0.0001). | | `parts.skinColors`, `parts.skinTolerance` | Hex colours of bare hands; the wrist moves to where they start. | -| `parts.handPartOffset`, `parts.armShoulderInset`, `parts.wristX` | Rigid hand start past the wrist (× height); how far the arm part reaches inside the armpit; wrist override (absolute x). | -| `extras[]` | `{ name, select: { from, box: {min, max}, colors, tolerance, islandMaxFaces }, rigid \| bones }`. | -| `joints.*` | Estimator ratios (`shoulderInset`, `shoulderRaise`, `clavicleRatio`, `elbowRatio`, `hipAboveCrotch`, `hipsAboveUpLeg`, `kneeRatio`, `kneeBendMin`, `kneeForward`, `ankleWindow`, `toeRatio`, `toeHeightRatio`, `spineBelowShoulder`, `neckRatio`, `headAboveNeck`, `headfrontForward`). | +| `parts.handPartOffset`, `parts.armShoulderInset`, `parts.wristX`, `parts.armpitX`, `parts.armMinLength` | Rigid hand start past the wrist (× height); how far the arm part reaches inside the armpit; wrist override (absolute x); armpit override for both sides (absolute x, measured on the 5 cm grid; moves the arm part start and the shoulder joint); shortest plausible armpit→wrist distance of the short-arm guard (× height, default 0.1, `null` disables; see **parts**). | +| `extras[]` | `{ name, select: { from, box: {min, max}, colors, tolerance, islandMaxFaces, grow: {seeds, crease, thickness} }, rigid \| bones \| kind \| remove, measure, cut, frontPanel }`; `kind` is `skirt` or `cape`; `remove: true` deletes the selected faces in the parts step and caps the opening they leave (see **parts**); `measure: true` keeps the extra in the joint measurement (default for skirts; accessories are measured out); `cut` lists body parts to cut the extra from (see **parts**); `frontPanel` (cloth only, opt-in) splits the front of the cloth over both thighs (see **weights** step 6). | +| `joints.*` | Estimator options and ratios (`shoulderAt`: `armpit` (default) or `junction`, `shoulderInset`, `shoulderRaise`, `clavicleRatio`, `elbowRatio`, `hipAboveCrotch`, `hipsAboveUpLeg`, `kneeRatio`, `kneeWindow`, `kneeBendMin`, `kneeProminence`, `kneeStepMax`, `kneeForward`, `ankleWindow`, `toeRatio`, `toeHeightRatio`, `spineBelowShoulder`, `spineDepth` (spine axis that fraction of the way from the torso centroid to the back, default 0), `neckRatio`, `headAboveNeck`, `headfrontForward`). | | `jointsOverride` | Override file relative to the config (default `joints.json`). | -| `weights.*` | `heatFailShare`, `voxelSize`, `headRigidAbove`, `rampLength`, `smoothRadius`, `smoothIterations`, `smoothJoints`, `linearBlends`. | +| `weights.*` | `heatFailShare`, `voxelSize`, `headRigidAbove`, `rampLength`, `smoothRadius`, `smoothIterations`, `smoothJoints`, `linearBlends`, `groinBand`, `gradientRamp`, `gradientIterations`, `thighCeiling`, `clavicleFloor` (opt-in, step 2), `waistBand`, `neckBand`, `flankBand`, `flankFade` (opt-in, step 7), `chainLocality`, `sideExclusive` (opt-in, step 2), `jointSmooth` (opt-in, step 11). | ## Calibration @@ -109,8 +117,10 @@ The plush mascot keeps human-like clip motion: idle, walk, run, crouch, crouchwa ## Limits -- The estimator assumes a T-pose (arms clearly away from the body in the front view). A-pose meshes need a `joints.json` override. +- The arm-band test accepts arms down to 1.5× the torso half-width away from the body (A-poses); closer arms need a `joints.json` override. The crotch is measured on the full mesh in the parts step, because removing extras can open the mesh. +- Where an unmeasured extra wraps the whole torso (vlad's `coat-lower` raised to 0.95 m), no torso section and no body vertex is left at that height; the spine axis then uses the full-mesh section through the extra, which sits on the coat's centroid rather than the body's. Mark such an extra `measure: true` or keep its box below the spine sections. - Joint positions are a first estimate: always look at `joints-review.png` and `parts-review.png`. +- `shoulderAt: "junction"`, `spineDepth`, `thighCeiling`/`clavicleFloor` and a larger `gradientRamp` (0.04) are per-character levers, not defaults: on the 37-character set of 2026-11-09 each fixed some rigs and broke others when applied to all (junction shoulders: 7 passing rigs failed; `spineDepth` 0.4 worsened barbudo-creepy and bebezao-de-feira). - Heat weighting can fail on non-manifold meshes; the voxel proxy covers it, but check `weights.json` (`method`, `heat.unweightedVertices`). - Hips translation and in-place motion come from `retarget-glb.mjs`; this pipeline does not author clips. - `Curl_L`/`Curl_R` carry no skin (hands are 100% `Hand`), as in the rigs from `rig-from-donor.mjs`: the client's grip curl rotates those bones but the fingers do not close around the weapon. diff --git a/tools/blender/character_rig/common.py b/tools/blender/character_rig/common.py index 12362a9..d0f83c1 100644 --- a/tools/blender/character_rig/common.py +++ b/tools/blender/character_rig/common.py @@ -311,11 +311,32 @@ def _runs(row: np.ndarray): return runs -def landmarks(obj, face_mask=None, step=0.01): +def run_main(main): + """Run a step's main() and exit non-zero on any exception. + + Blender's ``--python`` swallows script exceptions and exits 0; the runner relies on the + exit code (and on fresh outputs) to never reuse a previous step's files. + """ + import os + import traceback + try: + main() + except BaseException: # noqa: BLE001 - every failure must reach the exit code + traceback.print_exc() + sys.stdout.flush() + sys.stderr.flush() + os._exit(1) + sys.stdout.flush() + + +def landmarks(obj, face_mask=None, step=0.01, crotch_z=None, arm_min=0.1, wrist_x=None, armpit_x=None): """Body landmarks measured from a 1 cm front silhouette and Y-ray cross-sections. Only faces in ``face_mask`` are measured (the joints step passes the body without extras such as a backpack or an antenna). Everything is in clean-space metres. + ``arm_min`` (x height, ``parts.armMinLength``; None disables) is the shortest plausible + armpit -> wrist distance, ``wrist_x`` the configured wrist (``parts.wristX``) and + ``armpit_x`` the configured armpit (``parts.armpitX``); see the short-arm guard below. """ bvh = bvh_for_faces(obj, face_mask) co, _ = mesh_arrays(obj) @@ -338,13 +359,16 @@ def landmarks(obj, face_mask=None, step=0.01): # Crotch: first height above 15% H where the midline (x = -1, 0, +1 cm) is at least # 2.5% H deep front to back. A silhouette test alone fails when the thighs touch. - crotch_z = 0.47 * H - for iz in range(int(0.15 * H / step), int(0.8 * H / step)): - z = float(zs[iz]) - depth = np.mean([sum(b - a for a, b in section_y(bvh, x, z, ymin, ymax)) for x in (-0.01, 0.0, 0.01)]) - if depth >= 0.025 * H: - crotch_z = z - break + # ``crotch_z`` from the caller wins: removing extras (a cape over the back of the legs) + # opens the mesh, rays then never exit and the depth test below finds no crotch. + if crotch_z is None: + crotch_z = 0.47 * H + for iz in range(int(0.15 * H / step), int(0.8 * H / step)): + z = float(zs[iz]) + depth = np.mean([sum(b - a for a, b in section_y(bvh, x, z, ymin, ymax)) for x in (-0.01, 0.0, 0.01)]) + if depth >= 0.025 * H: + crotch_z = z + break def central_run(iz): for a, b in _runs(occ[iz]): @@ -364,10 +388,16 @@ def central_run(iz): # well past the torso (T-pose arms). Ears or a wide head above it are ignored. ext_l = np.array([xs[np.nonzero(occ[iz] & (xs > 0))[0]].max() if (occ[iz] & (xs > 0)).any() else 0.0 for iz in range(nz)]) ext_r = np.array([-xs[np.nonzero(occ[iz] & (xs < 0))[0]].min() if (occ[iz] & (xs < 0)).any() else 0.0 for iz in range(nz)]) - wide = (ext_l > 2.2 * w_ref) & (ext_r > 2.2 * w_ref) & (zs > crotch_z + 0.05 * H) - rows = np.nonzero(wide)[0] + # Arm band: the T-pose test (both sides reach 2.2x the torso half-width) first; A-pose + # arms hang closer to the body, so the factor relaxes down to 1.5x before giving up. + for factor in (2.2, 1.9, 1.7, 1.5): + wide = (ext_l > factor * w_ref) & (ext_r > factor * w_ref) & (zs > crotch_z + 0.05 * H) + rows = np.nonzero(wide)[0] + if len(rows): + break if not len(rows): - raise RuntimeError("no T-pose arm band found in the front silhouette") + raise RuntimeError("no arm band found in the front silhouette (arms closer than 1.5x the torso " + "half-width); override the arm joints in joints.json") first = rows[0] last = first while last + 1 < nz and wide[last + 1]: @@ -378,11 +408,6 @@ def central_run(iz): for side, sign in (("L", 1.0), ("R", -1.0)): ext = ext_l if sign > 0 else ext_r tip = float(ext[first:last + 1].max()) - # Armpit: half-width of the torso run just below the arm band. - below = int(max(first - 3, 0)) - run = central_run(below) or (-w_ref, w_ref) - x_ap = float(run[1] if sign > 0 else -run[0]) - # Arm centre line and thickness per column, within a band around the arm rows. zlo = max(arm_lo - 0.08 * H, crotch_z) zhi = arm_hi + 0.04 * H @@ -390,7 +415,7 @@ def central_run(iz): column = {} for ix in range(nx): x = float(xs[ix]) * sign - if x < x_ap * 0.6 or x > tip + 1e-6: + if x < 0.3 * w_ref or x > tip + 1e-6: continue filled = np.nonzero(occ[izlo:izhi, ix])[0] if len(filled): @@ -402,21 +427,38 @@ def central_run(iz): def col(x): key = min(column, key=lambda k: abs(k - x)) return column[key] - # The torso row under the arm can be a narrow waist (hunched or skinny bodies), so - # the armpit is also found where the silhouette column becomes much taller than the - # arm itself, scanning inward from mid-arm. + # Armpit (the arm part boundary): half-width of the torso run just below the arm + # band. The torso row under the arm can be a narrow waist (hunched or skinny + # bodies), so the armpit is also found where the silhouette column becomes much + # taller than the arm itself, scanning inward from mid-arm. + run = central_run(int(max(first - 3, 0))) or (-w_ref, w_ref) + x_ap = float(run[1] if sign > 0 else -run[0]) keys = np.array(sorted(column)) mid_arm = keys[(keys > x_ap + 0.3 * (tip - x_ap)) & (keys < x_ap + 0.7 * (tip - x_ap))] t_arm = float(np.median([column[k][1] for k in mid_arm])) if len(mid_arm) else 0.0 - x_body = None - for k in keys[keys <= x_ap + 0.3 * (tip - x_ap)][::-1]: + for k in keys[(keys >= 0.6 * x_ap) & (keys <= x_ap + 0.3 * (tip - x_ap))][::-1]: if t_arm and column[k][1] > 2.0 * t_arm: - x_body = float(k) + step + x_ap = max(x_ap, float(k) + step) break - if x_body is not None and x_body > x_ap: - x_ap = x_body thick = col(x_ap + 0.03)[1] armpit_z = col(x_ap + 0.02)[2] + # Arm-torso junction (where the shoulder joint goes): scanning out from the torso, + # a column whose run still reaches well below the arm band is the side of the body; + # the first column whose run ends above that has open space under it, the underarm + # gap. A wide sleeve, an epaulette or a dropped T-shirt shoulder hangs below the bare + # arm but not down the side of the body, so the junction does not land on a sleeve + # end the way the torso-run armpit can. A rounded ribcage opens that gap a little + # inside the junction, so it then moves out to the first column whose underside is + # within 2% H of the arm's own underside. + floor_z = max(arm_lo - 0.06 * H, zlo + step) + x_j = next((float(k) for k in keys if column[k][2] > floor_z + 1e-9), None) + if x_j is None: + x_j = x_ap + else: + ref = keys[(keys >= x_j + 0.025 * H) & (keys <= x_j + 0.06 * H)] + if len(ref): + underside = float(np.median([column[k][2] for k in ref])) + x_j = next((float(k) for k in keys if k >= x_j and column[k][2] >= underside - 0.02 * H), x_j) # Wrist: area profile of the distal half; the palm is the widest section of the # distal 35% and the wrist is the outermost section within 8% H inside the palm @@ -440,10 +482,45 @@ def area_at(x): else: x_wrist = tip - 0.11 * H sides[side] = { - "sign": sign, "tip": tip, "armpitX": x_ap, "armpitZ": armpit_z, "armThickness": thick, + "sign": sign, "tip": tip, "armpitX": x_ap, "armpitZ": armpit_z, "junctionX": x_j, "armThickness": thick, "wristX": x_wrist, "column": column, } + # Short-arm guard: a sleeve or a costume that fills the space under the arm (clovis' + # puffed sleeves, bebezao's and boneca's short sleeves over a wide body, the cords on + # coronel's right shoulder) makes the torso run under the arm band reach the sleeve end, + # so the armpit lands a few centimetres from the wrist; the arm part then starts there, + # the sleeve stays torso and every clip leaves the arm in T. When armpit -> wrist is + # shorter than ``arm_min`` x height, the armpit takes the other side's (mirrored) when + # that side is long enough, else the arm-torso junction when that is; otherwise it stays + # and the pose test's idle arm angle fails the rig. ``armpit_x`` (``parts.armpitX``, + # absolute x measured on the 5 cm grid) sets both armpits instead, for sleeves where + # neither works (clovis: the junction lies under the puff too). + for a in sides.values(): + a["armpitSource"] = "torso run" + moves = {} + if armpit_x is not None: + moves = {s: (abs(float(armpit_x)), "config armpitX") for s in sides} + elif arm_min: + reach = {s: (abs(float(wrist_x)) if wrist_x is not None else a["wristX"]) for s, a in sides.items()} + short = {s: reach[s] - a["armpitX"] < arm_min * H for s, a in sides.items()} + for s, a in sides.items(): + if not short[s]: + continue + o = "R" if s == "L" else "L" + if not short[o]: + moves[s] = (sides[o]["armpitX"], "mirrored from the other side (short arm)") + elif reach[s] - a["junctionX"] >= arm_min * H: + moves[s] = (a["junctionX"], "junction (short arm)") + else: + a["armpitSource"] = "torso run; arm shorter than parts.armMinLength, set parts.armpitX" + for s, (x_new, source) in moves.items(): + a = sides[s] + cols = a["column"] + near = lambda x: cols[min(cols, key=lambda k: abs(k - x))] # noqa: E731 + a.update(armpitX=float(x_new), armpitSource=source, torsoRunX=a["armpitX"], + armThickness=near(x_new + 0.03)[1], armpitZ=near(x_new + 0.02)[2]) + # Neck: narrowest central run above the arm band (lower half of what is above it). neck_z, neck_w = None, None top_iz = nz - 1 @@ -481,7 +558,7 @@ def public_landmarks(lm): """JSON-friendly subset of :func:`landmarks`.""" out = {k: (r(v) if isinstance(v, float) else v) for k, v in lm.items() if not k.startswith("_") and k not in ("arms", "legs")} - out["arms"] = {s: {k: r(v) for k, v in a.items() if k not in ("column",)} for s, a in lm["arms"].items()} + out["arms"] = {s: {k: (v if isinstance(v, str) else r(v)) for k, v in a.items() if k not in ("column",)} for s, a in lm["arms"].items()} return out diff --git a/tools/blender/character_rig/rig_armature.py b/tools/blender/character_rig/rig_armature.py index 445bdb3..1f3eee6 100644 --- a/tools/blender/character_rig/rig_armature.py +++ b/tools/blender/character_rig/rig_armature.py @@ -88,4 +88,4 @@ def main(): print(f"ARMATURE {len(arm_data.bones)} bones ({sum(b.use_deform for b in arm_data.bones)} deform)") -main() +C.run_main(main) diff --git a/tools/blender/character_rig/rig_clean.py b/tools/blender/character_rig/rig_clean.py index 34351be..10ee3ac 100644 --- a/tools/blender/character_rig/rig_clean.py +++ b/tools/blender/character_rig/rig_clean.py @@ -163,4 +163,4 @@ def main(): f"merged={merged} flipped={flipped} loose={len(parts)} boundary={boundary}") -main() +C.run_main(main) diff --git a/tools/blender/character_rig/rig_joints.py b/tools/blender/character_rig/rig_joints.py index 7e2d43c..1c0e033 100644 --- a/tools/blender/character_rig/rig_joints.py +++ b/tools/blender/character_rig/rig_joints.py @@ -6,16 +6,22 @@ Deterministic first estimate from the body without extras (a backpack or an antenna must not pull the spine or the head): -- arms: shoulder just inside the armpit line, elbow at ``elbowRatio`` of shoulder→wrist, - wrist where the parts step put it; each joint sits on the centroid of the arm - cross-section (rays along Y), and the shoulder on the line fitted through them; +- arms: shoulder just inside the armpit (``shoulderAt: "armpit"``, the torso run under the + arm band) or the arm-torso junction (``"junction"``, where the underarm gap of the front + silhouette opens, so a wide sleeve or an epaulette does not push it out), elbow at + ``elbowRatio`` of shoulder→wrist, wrist where the parts step put it; each joint sits on + the centroid of the arm cross-section (rays along Y), and the shoulder on the line fitted + through them; - legs: hip at the crotch row (``hipAboveCrotch``) on the leg section; ankle at the thinnest leg - section near the floor, knee at the strongest bend of the side profile (or - ``kneeRatio`` of ankle→hip on straight legs), toe on the ball of the foot; + section near the floor, knee in the middle of the leg (``kneeWindow``) at the strongest + forward bend of the side profile, else the narrowest smoothed section between thigh and + calf, else ``kneeRatio`` of ankle→hip; toe on the ball of the foot; - spine: ``Hips`` above the hip joints, ``Spine`` just under the shoulder line, - ``Spine02``/``Spine01`` at thirds, all on the torso section centroid; -- head: ``Head`` at the narrowest neck row, ``neck`` 60% of the way from ``Spine``, - ``head_end`` on the top of the head, ``headfront`` in front of ``Head``. + ``Spine02``/``Spine01`` at thirds, all on the torso medial axis (section centroids, + outliers dropped, locally line-fitted); ``neck`` at ``neckRatio`` towards ``Head`` on the + neck sections; +- head: ``Head`` at the narrowest neck row, ``head_end`` on the top of the head, + ``headfront`` in front of ``Head``. Ratios default to measurements of the meshy-28 donor and can be set under ``joints`` in the config. A per-character override file (``jointsOverride`` in the config, relative to @@ -40,19 +46,24 @@ # Defaults measured on the meshy-28 donor mesh (client public/models/characters/mst.glb) # with tools/blender/character_rig run on it; see docs/character-rig.md. DEFAULTS = { + "shoulderAt": "armpit", # "armpit" (torso run under the arm band) or "junction" (underarm gap) "shoulderInset": 0.05, # shoulder joint x = armpit x - shoulderInset * arm thickness "shoulderRaise": 0.1, # shoulder joint z = arm centre line + shoulderRaise * arm thickness "clavicleRatio": 0.2, # LeftShoulder x = clavicleRatio * shoulder x "elbowRatio": 0.5, # elbow at this fraction of shoulder -> wrist "hipAboveCrotch": 0.045, # UpLeg z = crotch + hipAboveCrotch * H "hipsAboveUpLeg": 0.049, # Hips z = UpLeg z + hipsAboveUpLeg * H - "kneeRatio": 0.49, # knee at this fraction of ankle -> hip on straight legs - "kneeBendMin": 0.02, # side-profile deviation (m) that counts as a bent knee + "kneeRatio": 0.49, # knee at this fraction of ankle -> hip without a profile cue + "kneeWindow": [0.38, 0.62], # knee search range, fraction of ankle -> hip + "kneeProminence": 0.03, # narrowest leg section: this much below its sides (smoothed area) + "kneeStepMax": 0.15, # ... with no row-to-row area step above this (boot tops, hems) + "kneeBendMin": 0.02, # forward side-profile deviation (m) that counts as a bent knee "kneeForward": 0.25, # knee joint moves this fraction of the leg depth to the front "ankleWindow": [0.035, 0.09], "toeRatio": 0.72, # ball of the foot from heel to toe tip "toeHeightRatio": 0.4, # toe joint height as a fraction of the ankle height "spineBelowShoulder": 0.015, + "spineDepth": 0.0, # spine axis this fraction of the way from torso centroid to back "neckRatio": 0.6, "headAboveNeck": 0.02, # Head z = narrowest neck row + headAboveNeck * H "headfrontForward": 0.069, @@ -93,9 +104,17 @@ def main(): body = C.body_object() labels, parts = C.read_face_parts(body, cfg) n_body = len(C.PART_NAMES) - body_mask = parts < n_body - lm = C.landmarks(body, face_mask=body_mask) + # Joints are measured without accessories, but extras that are the body's own surface + # (a coat skirt over the legs, weight-only regions) stay: ``measure: true``, default for + # kind skirt. Removing them would leave no thigh or torso to measure. + measured = [n_body + i for i, extra in enumerate(cfg.get("extras", [])) + if extra.get("measure", extra.get("kind") == "skirt")] + body_mask = (parts < n_body) | np.isin(parts, measured) parts_report = json.loads((args.work / "parts.json").read_text()) + # The crotch comes from the parts step (full, closed mesh); see common.landmarks. + pcfg = cfg.get("parts", {}) + lm = C.landmarks(body, face_mask=body_mask, crotch_z=float(parts_report["landmarks"]["crotchZ"]), + arm_min=pcfg.get("armMinLength", 0.1), wrist_x=pcfg.get("wristX"), armpit_x=pcfg.get("armpitX")) bvh = lm["_bvh"] ymin, ymax = lm["_y"] H = lm["height"] @@ -112,7 +131,9 @@ def main(): override_wrist = cfg.get("parts", {}).get("wristX") if override_wrist is not None: wrist = abs(float(override_wrist)) - x_sh = arm["armpitX"] - J["shoulderInset"] * arm["armThickness"] + if J["shoulderAt"] not in ("armpit", "junction"): + raise RuntimeError(f'joints.shoulderAt must be "armpit" or "junction", not {J["shoulderAt"]!r}') + x_sh = arm["junctionX" if J["shoulderAt"] == "junction" else "armpitX"] - J["shoulderInset"] * arm["armThickness"] x_el = x_sh + J["elbowRatio"] * (wrist - x_sh) # Fit the arm centre line on the outer 75% of shoulder->wrist: straps, vest edges # and the deltoid next to the torso would drag a full-length fit. @@ -132,6 +153,7 @@ def main(): joints[f"{prefix}Shoulder"] = Vector((J["clavicleRatio"] * x_sh * s, shoulder.y, shoulder.z)) joints[f"Curl_{side}"] = hand.copy() notes[f"{prefix}Hand"] = parts_report["wrists"][side]["source"] if override_wrist is None else "config wristX" + notes[f"{prefix}Arm"] = arm.get("armpitSource", "torso run") tip_x = arm["tip"] tip, _ = arm_section(bvh, lm, side, tip_x - 0.01, ymin, ymax) notes[f"{prefix}HandTip"] = C.r(tip) @@ -150,9 +172,19 @@ def leg_row(z): return line[key] def leg_section(z): - _mean, xmin_, xmax_ = leg_row(z) - xs = np.arange(xmin_, xmax_ + 1e-9, 0.005) - return section_xy(bvh, xs, z, ymin, ymax) + """Leg centroid at z; a row the silhouette or the rays miss (an extra such as a + tail removed from the body, a gap in the mesh) falls back to the nearest row + within 3 cm that has a section.""" + for dz in (0.0, -0.005, 0.005, -0.01, 0.01, -0.02, 0.02, -0.03, 0.03): + _mean, xmin_, xmax_ = leg_row(z + dz) + cen, area = section_xy(bvh, np.arange(xmin_, xmax_ + 1e-9, 0.005), z + dz, ymin, ymax) + if cen is not None: + return cen, area + return None, 0.0 + + if not len(zs_line): + raise RuntimeError(f"{prefix} leg: no leg silhouette below the crotch (z {C.r(crotch, 3)}); " + "check the leg parts in parts-review.png and the extras that select below the crotch") lo_w, hi_w = J["ankleWindow"] best = None @@ -160,8 +192,14 @@ def leg_section(z): cen, area = leg_section(z) if cen is not None and (best is None or area < best[2]): best = (z, cen, area) + if best is None: + raise RuntimeError(f"{prefix}Foot: no leg section in the ankle window " + f"{C.r(lo_w * H, 3)}..{C.r(hi_w * H, 3)} m; set joints.ankleWindow or override {prefix}Foot") ankle_z, ankle_c, _ = best thigh_c, _ = leg_section(crotch - 0.03) + if thigh_c is None: + raise RuntimeError(f"{prefix}UpLeg: no thigh section just below the crotch (z {C.r(crotch - 0.03, 3)} m); " + f"an extra probably removed the thigh faces, or override {prefix}UpLeg") pelvis_y = None cen_p, _ = section_xy(bvh, np.arange(-lm["torsoHalfWidth"] * 0.6, lm["torsoHalfWidth"] * 0.6 + 1e-9, 0.005), hip_z, ymin, ymax) @@ -169,22 +207,54 @@ def leg_section(z): pelvis_y = cen_p[1] hip = Vector((thigh_c[0], thigh_c[1] if pelvis_y is None else 0.5 * (thigh_c[1] + pelvis_y), hip_z)) ankle = Vector((ankle_c[0], ankle_c[1], ankle_z)) - # Knee: strongest bend of the side profile, else the donor ratio. + # Knee, from the leg profile between the ankle and the hip, inside kneeWindow + # (fraction of ankle -> hip) so trouser folds near the boot and the hip are ignored: + # 1. the strongest forward bend of the side profile, at least kneeBendMin (a bent + # leg; a bend backwards is a calf, a fold or a boot back, never a knee); + # 2. else the narrowest section between thigh and calf: a local minimum of the + # cross-section area smoothed over 5 cm, at least kneeProminence below the widest + # section on each side within 8 cm, with no row-to-row step over kneeStepMax + # within 4 cm (a boot top or a coat hem is a step, not a knee); + # 3. else kneeRatio. + lo_k, hi_k = J["kneeWindow"] prof = [] - for z in np.arange(ankle_z + 0.05, hip_z - 0.05, 0.01): - cen, _ = leg_section(z) + for z in np.arange(ankle_z + 0.03, hip_z - 0.03, 0.01): + cen, area = leg_section(z) if cen is not None: t = (z - ankle_z) / (hip_z - ankle_z) straight = ankle + (hip - ankle) * t - prof.append((z, cen, cen[1] - straight.y)) - bend = max(prof, key=lambda p: abs(p[2])) if prof else None - if bend and abs(bend[2]) >= J["kneeBendMin"]: - knee_z = bend[0] - notes[f"{prefix}Leg"] = f"side-profile bend {C.r(bend[2], 3)} m" - else: + prof.append((z, t, area, cen[1] - straight.y)) + bends = [p for p in prof if lo_k <= p[1] <= hi_k and -p[3] >= J["kneeBendMin"]] + knee_z, best_drop = None, J["kneeProminence"] + if bends: + bend = max(bends, key=lambda p: -p[3]) + knee_z = float(bend[0]) + notes[f"{prefix}Leg"] = f"side-profile bend {C.r(-bend[3], 3)} m forward" + elif len(prof) >= 9: + P = np.array(prof) + area = np.convolve(P[:, 2], np.ones(5) / 5, mode="same") + for i in range(4, len(P) - 4): + if not (lo_k <= P[i, 1] <= hi_k) or area[i] > area[i - 1] or area[i] > area[i + 1]: + continue + raw = P[i - 4:i + 5, 2] + if np.max(np.abs(np.diff(raw)) / np.maximum(raw[:-1], 1e-9)) > J["kneeStepMax"]: + continue + lo_i, hi_i = max(i - 8, 0), min(i + 9, len(P)) + drop = min(area[lo_i:i].max(), area[i + 1:hi_i].max()) / max(area[i], 1e-9) - 1 + if drop >= best_drop: + knee_z, best_drop = float(P[i, 0]), drop + if knee_z is not None: + notes[f"{prefix}Leg"] = f"narrowest section, {C.r(100 * best_drop, 1)}% below its sides" + if knee_z is None: knee_z = ankle_z + J["kneeRatio"] * (hip_z - ankle_z) notes[f"{prefix}Leg"] = "kneeRatio" knee_c, _ = leg_section(knee_z) + if knee_c is None: + # No section at the knee row (a skirt or tail extra took those faces): put the + # knee on the straight hip-ankle line. + t = (knee_z - ankle_z) / (hip_z - ankle_z) + knee_c = np.array([ankle.x + (hip.x - ankle.x) * t, ankle.y + (hip.y - ankle.y) * t]) + notes[f"{prefix}Leg"] += "; no knee section, on the hip-ankle line" spans = C.section_y(bvh, float(knee_c[0]), float(knee_z), ymin, ymax) knee_y = knee_c[1] if spans: @@ -212,17 +282,31 @@ def leg_section(z): # ---------------------------------------------------------------- spine and head full_bvh = C.bvh_for_faces(body) - extra_v = set() + extra_v, body_v = set(), set() for i, p in enumerate(me.polygons): - if not body_mask[i]: - extra_v.update(p.vertices) + (body_v if body_mask[i] else extra_v).update(p.vertices) extra_co = co[sorted(extra_v)] if extra_v else np.zeros((0, 3)) + body_co = co[sorted(body_v)] + + def full_section(xs, z, y_cut): + """Area centroid (x, y) of the full-mesh section at height z behind y_cut, or None.""" + total, acc = 0.0, np.zeros(2) + for x in xs: + for a, b in C.section_y(full_bvh, float(x), float(z), ymin, ymax): + ya, yb = ymin - 0.1 + a, min(ymin - 0.1 + b, y_cut) + if yb > ya: + total += yb - ya + acc += np.array([x, 0.5 * (ya + yb)]) * (yb - ya) + return acc / total if total > 0 else None def torso_section(z, half=None): """Torso centroid at height z without extras. Removing a backpack fused to the back leaves a hole, so rays that miss their exit - fall back to the full mesh clipped in front of the extras at this height. + fall back to the full mesh clipped in front of the extras at this height, then to + the mid-depth of the body vertices there. An extra that wraps the whole torso at + this height (vlad's coat-lower moved up to 0.95 m) leaves no body vertex and clips + every span away; the full-mesh section, unclipped, is the last resort. """ half = half or lm["torsoHalfWidth"] * 0.6 xs = np.arange(-half, half + 1e-9, 0.005) @@ -230,35 +314,63 @@ def torso_section(z, half=None): if cen is not None: return cen near = extra_co[(np.abs(extra_co[:, 2] - z) < 0.03) & (np.abs(extra_co[:, 0]) < half)] if len(extra_co) else extra_co - y_cut = float(near[:, 1].min()) if len(near) else ymax - total, acc = 0.0, np.zeros(2) - for x in xs: - for a, b in C.section_y(full_bvh, float(x), float(z), ymin, ymax): - ya, yb = ymin - 0.1 + a, min(ymin - 0.1 + b, y_cut) - if yb > ya: - total += yb - ya - acc += np.array([x, 0.5 * (ya + yb)]) * (yb - ya) - if total <= 0: - raise RuntimeError(f"no torso section at z={z:.3f}") - return acc / total + cen = full_section(xs, z, float(near[:, 1].min()) if len(near) else ymax) + if cen is not None: + return cen + near = body_co[np.abs(body_co[:, 2] - z) < 0.02] + if len(near): + return np.array([0.0, 0.5 * (near[:, 1].min() + near[:, 1].max())]) + cen = full_section(xs, z, ymax) + if cen is None: + raise RuntimeError(f"no torso section or body vertices at z={z:.3f}") + return cen up_z = 0.5 * (joints["LeftUpLeg"].z + joints["RightUpLeg"].z) hips_z = up_z + J["hipsAboveUpLeg"] * H shoulder_z = 0.5 * (joints["LeftArm"].z + joints["RightArm"].z) spine_z = shoulder_z - J["spineBelowShoulder"] * H - # Hips and Spine sit on the torso section centroid; the two middle joints lie on the - # straight line between them (vest plates, pouches and a removed backpack make the - # mid-torso centroid jump front to back). - hips_y = torso_section(hips_z)[1] - spine_y = torso_section(spine_z)[1] - for name, t in (("Hips", 0.0), ("Spine02", 1 / 3), ("Spine01", 2 / 3), ("Spine", 1.0)): - joints[name] = Vector((0.0, hips_y + t * (spine_y - hips_y), hips_z + t * (spine_z - hips_z))) head_z = lm["neckZ"] + J["headAboveNeck"] * H + neck_z = spine_z + J["neckRatio"] * (head_z - spine_z) + # Hips, Spine02, Spine01 and Spine sit on the torso medial axis: the centroids of + # horizontal sections every 1 cm (within 0.6 torso half-widths of the midline, so the + # arms stay out), smoothed by a local line fit. Sections more than 2.5 robust + # deviations off their 7-section running median (a pouch, a belt buckle, a removed + # backpack) are dropped; each joint then takes a tricube-weighted line through the + # sections within 3% H of it, so the axis follows a hunched back or a belly without + # one odd section moving a joint, and the end joints are not extrapolated. spineDepth + # moves the axis that fraction of the way from the centroid to the back surface (the + # donor's spine is 7-9 cm behind its torso centroid; a big belly pulls the centroid far + # forward of the back, so crouching stretches the back around a hinge inside the belly). + axis_z = np.arange(hips_z - 0.03 * H, spine_z + 0.03 * H + 1e-9, 0.01) + axis_y = np.array([torso_section(z)[1] for z in axis_z]) + if J["spineDepth"]: + half = lm["torsoHalfWidth"] * 0.6 + for i, z in enumerate(axis_z): + backs = [ymin - 0.1 + b for x in np.arange(-half, half + 1e-9, 0.005) + for _a, b in C.section_y(bvh, float(x), float(z), ymin, ymax)] + if backs: + axis_y[i] += J["spineDepth"] * (max(backs) - axis_y[i]) + running = np.array([np.median(axis_y[max(i - 3, 0):i + 4]) for i in range(len(axis_y))]) + resid = np.abs(axis_y - running) + keep = resid <= 2.5 * (1.4826 * np.median(resid) + 1e-3) + + def axis_at(z): + d = np.abs(axis_z - z) / (0.03 * H) + w = np.where(keep & (d < 1), (1 - d ** 3) ** 3, 0.0) + if (w > 0).sum() < 3: + return float(running[np.argmin(np.abs(axis_z - z))]) + A = np.vstack([np.ones_like(axis_z), axis_z - z]).T * np.sqrt(w)[:, None] + return float(np.linalg.lstsq(A, axis_y * np.sqrt(w), rcond=None)[0][0]) + + notes["spineAxis"] = {"sections": int(len(axis_z)), "dropped": int((~keep).sum())} + for name, t in (("Hips", 0.0), ("Spine02", 1 / 3), ("Spine01", 2 / 3), ("Spine", 1.0)): + z = hips_z + t * (spine_z - hips_z) + joints[name] = Vector((0.0, axis_at(z), z)) + # The neck is narrower than the torso: its own sections within 2 cm, median. + neck_y = [torso_section(z, half=lm["neckHalfWidth"] * 1.5)[1] for z in np.arange(neck_z - 0.02, neck_z + 0.02 + 1e-9, 0.01)] + joints["neck"] = Vector((0.0, float(np.median(neck_y)), neck_z)) cen = torso_section(head_z, half=lm["neckHalfWidth"]) joints["Head"] = Vector((0.0, cen[1], head_z)) - neck_z = spine_z + J["neckRatio"] * (head_z - spine_z) - cen = torso_section(neck_z, half=lm["neckHalfWidth"] * 1.5) - joints["neck"] = Vector((0.0, cen[1], neck_z)) top = lm["headTopZ"] cen = torso_section(head_z + 0.6 * (top - head_z), half=lm["neckHalfWidth"]) joints["head_end"] = Vector((0.0, cen[1], top)) @@ -305,4 +417,4 @@ def torso_section(z, half=None): print("JOINTS " + " ".join(f"{k}={v}" for k, v in final.items())) -main() +C.run_main(main) diff --git a/tools/blender/character_rig/rig_parts.py b/tools/blender/character_rig/rig_parts.py index 779d3b8..906a285 100644 --- a/tools/blender/character_rig/rig_parts.py +++ b/tools/blender/character_rig/rig_parts.py @@ -20,15 +20,83 @@ """ from __future__ import annotations +import math import sys +from collections import defaultdict, deque from pathlib import Path +import bmesh import bpy import numpy as np +from mathutils import Vector sys.path.insert(0, str(Path(__file__).resolve().parent)) import common as C # noqa: E402 +SEED_MAX_DISTANCE = 0.05 # m: a grow seed must lie this close to the surface + + +def face_neighbours(me): + """Face index -> faces sharing an edge with it.""" + by_edge = defaultdict(list) + for p in me.polygons: + for key in p.edge_keys: + by_edge[key].append(p.index) + nbrs = [[] for _ in me.polygons] + for faces in by_edge.values(): + for f in faces: + nbrs[f].extend(g for g in faces if g != f) + return nbrs + + +def flood(nbrs, start, passes): + """Faces reachable from ``start`` over edge neighbours where ``passes(f, g)``.""" + sel = np.zeros(len(nbrs), dtype=bool) + sel[list(start)] = True + queue = deque(start) + while queue: + f = queue.popleft() + for g in nbrs[f]: + if not sel[g] and passes(f, g): + sel[g] = True + queue.append(g) + return sel + + +def grow_mask(body, grow, allowed, nbrs, centers, name): + """Faces of one connected region grown from seed points. + + From the faces nearest to ``seeds`` the region spreads over shared edges while the + other selectors allow the face and the fold between the two faces stays under + ``crease`` degrees (default 40), so a cape's outer sheet stops at its hem and at the + seams where it is fused to boots or a coat. ``thickness`` (m, default 0) then adds the + rest of a thin sheet: every face connected to the region through faces lying within + ``thickness`` of it (the hem fold and the inner side), whatever the fold. + """ + me = body.data + bvh = C.bvh_for_faces(body) + seeds = [] + for point in grow["seeds"]: + loc, _normal, face, dist = bvh.find_nearest(Vector(point)) + if face is None or dist > SEED_MAX_DISTANCE: + raise RuntimeError(f"extra {name}: grow seed {point} is not within {SEED_MAX_DISTANCE} m of the surface " + f"(nearest surface point {C.r(loc, 3) if loc else None})") + if not allowed[face]: + raise RuntimeError(f"extra {name}: grow seed {point} lands on face {face}, which its other selectors exclude") + seeds.append(face) + normals = np.empty(len(me.polygons) * 3) + me.polygons.foreach_get("normal", normals) + normals = normals.reshape(-1, 3) + cos_crease = math.cos(math.radians(float(grow.get("crease", 40)))) + sel = flood(nbrs, seeds, lambda f, g: allowed[g] and normals[f] @ normals[g] >= cos_crease) + thickness = float(grow.get("thickness", 0.0)) + if thickness > 0: + sheet = C.bvh_for_faces(body, sel) + near = np.array([sheet.find_nearest(Vector(c))[3] <= thickness for c in centers]) + sel = flood(nbrs, np.nonzero(sel)[0].tolist(), lambda f, g: allowed[g] and near[g]) + return sel +import common as C # noqa: E402 + def box_mask(centers, box): mask = np.ones(len(centers), dtype=bool) @@ -55,9 +123,9 @@ def main(): islands = C.connected_face_islands(body) island_size = np.bincount(islands) - lm = C.landmarks(body) - H = lm["height"] pcfg = cfg.get("parts", {}) + lm = C.landmarks(body, arm_min=pcfg.get("armMinLength", 0.1), wrist_x=pcfg.get("wristX"), armpit_x=pcfg.get("armpitX")) + H = lm["height"] # The arm region reaches this far inside the armpit line above the armpit (the deltoid); # default is a quarter of the arm thickness, clamped to 1..5 cm. inset_cfg = pcfg.get("armShoulderInset") @@ -76,8 +144,10 @@ def main(): inset = float(inset_cfg) if inset_cfg is not None else min(max(0.25 * arm["armThickness"], 0.01), 0.05) # Arm faces are outside the armpit line and no lower than the armpit (a hip pouch or a # tail can reach past the armpit x); only far outside the torso (drooping hands) may - # they hang lower. - far_out = xs > arm["armpitX"] + 0.5 * (arm["tip"] - arm["armpitX"]) + # they hang lower. "Far outside" is measured from the torso run, also when the + # short-arm guard moved the armpit inward (a wide skirt hem is not a drooping hand). + run_x = max(arm["armpitX"], arm.get("torsoRunX", arm["armpitX"])) + far_out = xs > run_x + 0.5 * (arm["tip"] - run_x) is_arm = (z > lm["crotchZ"]) & (z < lm["neckZ"]) & ( ((xs > arm["armpitX"] + 0.01) & ((z > arm["armpitZ"] - 0.03 * H) | far_out)) | ((xs > arm["armpitX"] - inset) & (z > arm["armpitZ"] - 0.01) & (z < arm_hi + 0.06 * H))) @@ -103,6 +173,7 @@ def main(): part[is_arm & (xs > hand_start)] = index[f"hand_{side}"] extras_report = [] + nbrs = None for extra in cfg.get("extras", []): sel = extra.get("select", {}) mask = np.ones(len(centers), dtype=bool) @@ -117,12 +188,56 @@ def main(): mask &= near if "islandMaxFaces" in sel: mask &= island_size[islands] <= int(sel["islandMaxFaces"]) + if "grow" in sel: + nbrs = nbrs or face_neighbours(me) + mask = grow_mask(body, sel["grow"], mask, nbrs, centers, extra["name"]) part[mask] = index[extra["name"]] extras_report.append({"name": extra["name"], "faces": int(mask.sum())}) + # Cuts (``cut: [parts]``): the extra's faces that share a vertex with those parts are + # deleted, so a cape or coat hem fused to a boot or a trouser leg hangs free instead of + # tearing between the cloth weights and the leg weights. Geometry is only removed, + # never moved or welded: the cut opens one face ring, it does not hide a seam. + # Removals (``remove: true``): every face of the extra is deleted and the opening it + # leaves in the rest of the mesh is capped, for geometry the concept does not have + # (coelho-pascoa-shopping: a rod with a ball fused to the tail, pointing straight back). + drop = np.zeros(len(part), dtype=bool) + capped = set() + for extra, entry in zip(cfg.get("extras", []), extras_report): + own = np.nonzero(part == index[extra["name"]])[0] + if extra.get("remove"): + drop[own] = True + entry["removedFaces"] = len(own) + capped.add(extra["name"]) + continue + if not extra.get("cut"): + continue + fused = np.zeros(len(me.vertices), dtype=bool) + for i in np.nonzero(np.isin(part, [index[name] for name in extra["cut"]]))[0]: + fused[list(me.polygons[i].vertices)] = True + hit = [i for i in own if fused[list(me.polygons[i].vertices)].any()] + drop[hit] = True + entry["cutFaces"] = len(hit) + attr = C.face_part_layer(me, create=True) attr.data.foreach_set("value", part) me.update() + if drop.any(): + removed = np.isin(part, [index[name] for name in capped]) + bm = C.bm_from(body) + rim = {v for i in np.nonzero(removed)[0] for v in bm.faces[i].verts} + bmesh.ops.delete(bm, geom=[bm.faces[i] for i in np.nonzero(drop)[0]], context="FACES") + if rim: + layer = bm.faces.layers.int.get("rig_part") + edges = [e for e in bm.edges if e.is_boundary and all(v in rim for v in e.verts)] + for face in bmesh.ops.holes_fill(bm, edges=edges, sides=0)["faces"]: + around = [g[layer] for e in face.edges for g in e.link_faces if g is not face] + face[layer] = max(set(around), key=around.count) if around else index["torso"] + bm.to_mesh(me) + bm.free() + me.update() + _, part = C.read_face_parts(body, cfg) + _, centers = C.mesh_arrays(body) C.save_blend(args.work / "parts.blend") centers_k, klabels = C.kmeans_palette(colors, k=int(pcfg.get("paletteSize", 8))) @@ -155,4 +270,4 @@ def main(): print("PARTS " + " ".join(f"{k}={v}" for k, v in counts.items())) -main() +C.run_main(main) diff --git a/tools/blender/character_rig/rig_weights.py b/tools/blender/character_rig/rig_weights.py index 35b3dbf..b83ef27 100644 --- a/tools/blender/character_rig/rig_weights.py +++ b/tools/blender/character_rig/rig_weights.py @@ -25,7 +25,12 @@ around the wrist. Heat alone switches ForeArm->Hand within one edge ring; on capitao-caveira that ring stretched 1.64× in the client hand gate (rig-maos-check) versus 1.32× with the blend and ``parts.handPartOffset`` 0.04. +4c. Opt-in band models (``weights.waistBand``, ``weights.neckBand``, ``weights.flankBand``): + weights in a band around the hips, the neck or the belly flanks as a function of height + and angle around the torso axis. 5. At most 4 influences per vertex, normalised. +6. Opt-in joint-zone smoothing (``weights.jointSmooth``): near the listed joints the final + weights are smoothed across part boundaries without giving any vertex a new bone. Writes ``weights.blend``, ``weights.json`` and ``blender-rig.glb`` (Blender's own skin; run tools/characters/rig-assemble.mjs next for the meshy-28 GLB). @@ -56,6 +61,31 @@ "smoothJoints": ["LeftArm", "RightArm", "LeftLeg", "RightLeg"], # [[parent, child, halfWidth x height], ...]: wrists by default (see step 4b). "linearBlends": [["LeftForeArm", "LeftHand", 0.035], ["RightForeArm", "RightHand", 0.035]], + # Groin: within groinBand x height of the crotch and between the thighs, the thigh share + # moves to Hips (fully on the midline), so spreading the legs does not tear the crotch. + "groinBand": 0.05, + # Weight gradient limit: along any edge no bone weight changes faster than the edge + # length / (gradientRamp x height); 0 disables. + "gradientRamp": 0.025, + "gradientIterations": 200, + # Torso height limits for the thighs and the clavicles (step 2); null leaves heat alone. + "thighCeiling": None, # fraction of UpLeg -> Hips height, e.g. 1.0 = the Hips joint + "clavicleFloor": None, # fraction of Spine02 -> Spine01 height, e.g. 0.0 = Spine02 + # Band weight models (step 4c'), x height or null: the waist band reaches this far below + # the hip joints, the neck band this far above Head; each fades out over half of it. The + # flank band covers Hips -> Spine01 on the torso sides and fades out over half of it; + # flankFade (x height or null) lengthens its lower fade, which ends at the Hips joint. + "waistBand": None, + "neckBand": None, + "flankBand": None, + "flankFade": None, + # Spine-chain locality (step 2), x height or null: margin beyond the parent and child joints. + "chainLocality": None, + # Side exclusivity (step 2), x height or null: no opposite-side bones past this margin. + "sideExclusive": None, + # Joint-zone smoothing (step 6), null or { "joints": [...], "radius": x height, + # "iterations": n, "alpha": 0..1 }. + "jointSmooth": None, } ARM_BONES = {"LeftArm", "LeftForeArm", "LeftHand", "RightArm", "RightForeArm", "RightHand"} @@ -77,11 +107,134 @@ def part_rules(cfg): if extra.get("rigid"): allowed[extra["name"]] = {extra["rigid"]} rigid[extra["name"]] = extra["rigid"] + elif extra.get("kind") in CLOTH_BONES: + allowed[extra["name"]] = set(CLOTH_BONES[extra["kind"]]) + elif extra.get("remove"): + allowed[extra["name"]] = set() # deleted in the parts step; no face is left else: allowed[extra["name"]] = set(extra["bones"]) return allowed, rigid +# Bones a hanging-cloth extra may use (``kind`` in the config); weights are procedural. +CLOTH_BONES = { + "skirt": ["Hips", "Spine02", "Spine01", "Spine", "LeftUpLeg", "RightUpLeg"], + "cape": ["Hips", "Spine02", "Spine01", "Spine", "neck", "LeftUpLeg", "RightUpLeg"], +} +# Share of a hanging cloth that follows the thighs at knee height: a skirt or a coat front +# goes with the legs, a cape behind them only partly. +CLOTH_LEG_SHARE = {"skirt": 0.8, "cape": 0.45} +# Opt-in front panel of a cloth extra (``frontPanel`` on the extra, ``true`` or an object +# overriding these): below the hip joints and in front of them the cloth follows both +# thighs, split over ±spread x the hip half-width instead of ±1, with ``share`` on the legs +# at knee height, like a skirt with less gain. +FRONT_PANEL = {"share": 0.25, "spread": 3.0} + + +def smoothstep(t): + t = np.clip(t, 0.0, 1.0) + return t * t * (3 - 2 * t) + + +def cloth_weights(points, kind, joints, bidx, front_panel=None): + """Procedural weights for hanging cloth (coat skirts, skirts, capes). + + Above the hips the cloth follows the spine chain by height (piecewise linear between + Hips, Spine02, Spine01, Spine and, for capes, neck). Below the hip joints it fades into + the thighs down to the knees, split left/right by x, with ``CLOTH_LEG_SHARE`` of the + weight on the legs at knee height and the rest on Hips, so walking opens the cloth + instead of tearing it between Hips and a leg. ``front_panel`` (see ``FRONT_PANEL``) + blends the front of the cloth, from the hip joints forward over one hip half-width, + into a both-thighs split with its own leg share. + """ + chain = ["Hips", "Spine02", "Spine01", "Spine"] + (["neck"] if kind == "cape" else []) + zs = np.array([joints[b].z for b in chain]) + W = np.zeros((len(points), len(bidx))) + z, x = points[:, 2], points[:, 0] + for i in range(len(chain) - 1): + lo, hi = zs[i], zs[i + 1] + inside = (z >= lo) & (z < hi) if i < len(chain) - 2 else (z >= lo) + t = np.clip((z[inside] - lo) / max(hi - lo, 1e-6), 0, 1) + W[inside, bidx[chain[i]]] = 1 - t + W[inside, bidx[chain[i + 1]]] += t + below = z < zs[0] + hip_z = 0.5 * (joints["LeftUpLeg"].z + joints["RightUpLeg"].z) + knee_z = 0.5 * (joints["LeftLeg"].z + joints["RightLeg"].z) + leg_x = 0.5 * (abs(joints["LeftUpLeg"].x) + abs(joints["RightUpLeg"].x)) + drop = smoothstep((hip_z - z[below]) / max(hip_z - knee_z, 1e-6)) + legs = CLOTH_LEG_SHARE[kind] * drop + left = smoothstep((x[below] + leg_x) / (2 * leg_x)) + if front_panel: + fp = {**FRONT_PANEL, **(front_panel if isinstance(front_panel, dict) else {})} + hip_y = 0.5 * (joints["LeftUpLeg"].y + joints["RightUpLeg"].y) + f = smoothstep((hip_y - points[below, 1]) / leg_x) + spread = fp["spread"] * leg_x + legs = (1 - f) * legs + f * fp["share"] * drop + left = (1 - f) * left + f * smoothstep((x[below] + spread) / (2 * spread)) + W[below, bidx["LeftUpLeg"]] = legs * left + W[below, bidx["RightUpLeg"]] = legs * (1 - left) + W[below, bidx["Hips"]] = 1 - legs + return W + + +def band_model(co, joints, bidx, kind, margin, fade_below=None): + """Weights of the waist, neck or flank band model and their blend factor per vertex. + + waist: from ``margin`` below the hip joints up to Spine02. The thighs take the sides + (|sin| of the angle around the vertical axis through Hips, so a belly or a coat front + and the small of the back stay on the spine) and fade out by the Hips joint; the rest + goes from Hips to Spine02 by height. + neck: from Spine up to ``margin`` above Head. The clavicles take the sides and fade out + by the neck joint; the rest goes Spine -> neck -> Head by height. + flank: from Hips up to Spine01, on the sides of the torso only (|sin| of the angle + around the vertical through Hips from 0.5 to 0.9, so the belly front and the back keep + their weights): only the spine chain by height (Hips -> Spine02 -> Spine01), no + clavicle and no thigh, where heat put both on one flank of a big belly. + The blend factor is 1 inside the band and smoothsteps to 0 over margin / 2 beyond it + (below it over ``fade_below`` when given). + """ + x, y, z = co[:, 0], co[:, 1], co[:, 2] + W = np.zeros((len(co), len(bidx))) + side_of = 1.0 + if kind == "flank": + lo, mid, hi = joints["Hips"].z, joints["Spine02"].z, joints["Spine01"].z + side = np.abs(x) / np.maximum(np.hypot(x, y - joints["Hips"].y), 1e-6) + side_of = smoothstep((side - 0.5) / 0.4) + up = smoothstep((z - lo) / max(mid - lo, 1e-6)) + top = smoothstep((z - mid) / max(hi - mid, 1e-6)) + W[:, bidx["Hips"]] = 1 - up + W[:, bidx["Spine02"]] = up * (1 - top) + W[:, bidx["Spine01"]] = up * top + elif kind == "waist": + axis_y = joints["Hips"].y + up_z = 0.5 * (joints["LeftUpLeg"].z + joints["RightUpLeg"].z) + lo, hips_z, hi = up_z - margin, joints["Hips"].z, joints["Spine02"].z + side = np.abs(x) / np.maximum(np.hypot(x, y - axis_y), 1e-6) + limb = smoothstep((side - 0.3) / 0.5) * smoothstep((hips_z - z) / max(hips_z - lo, 1e-6)) + up = smoothstep((z - hips_z) / max(hi - hips_z, 1e-6)) + W[:, bidx["LeftUpLeg"]] = np.where(x >= 0, limb, 0.0) + W[:, bidx["RightUpLeg"]] = np.where(x < 0, limb, 0.0) + W[:, bidx["Hips"]] = (1 - limb) * (1 - up) + W[:, bidx["Spine02"]] = (1 - limb) * up + else: + axis_y = joints["neck"].y + lo, neck_z, head_z = joints["Spine"].z, joints["neck"].z, joints["Head"].z + hi = head_z + margin + side = np.abs(x) / np.maximum(np.hypot(x, y - axis_y), 1e-6) + limb = smoothstep((side - 0.3) / 0.5) * (1 - smoothstep((z - lo) / max(neck_z - lo, 1e-6))) + lower = smoothstep((z - lo) / max(neck_z - lo, 1e-6)) + upper = smoothstep((z - neck_z) / max(head_z - neck_z, 1e-6)) + W[:, bidx["LeftShoulder"]] = np.where(x >= 0, limb, 0.0) + W[:, bidx["RightShoulder"]] = np.where(x < 0, limb, 0.0) + W[:, bidx["Spine"]] = (1 - limb) * (1 - lower) + W[:, bidx["neck"]] = (1 - limb) * lower * (1 - upper) + W[:, bidx["Head"]] = (1 - limb) * lower * upper + fade = 0.5 * margin + below = fade_below or fade + alpha = smoothstep((z - (lo - below)) / below) * smoothstep(((hi + fade) - z) / fade) * side_of + return W, alpha + + def vertex_groups_matrix(obj, bones): index = {name: i for i, name in enumerate(bones)} group_bone = {g.index: index.get(g.name) for g in obj.vertex_groups} @@ -227,6 +380,48 @@ def main(): rigid[v] = rigid_bones.pop() elif vparts[v] == {"head"} and co[v, 2] > head_rigid_z: rigid[v] = "Head" + # Torso height limits (opt-in): heat lets a thigh reach up a belly or a coat front and a + # clavicle reach down a chest or a bib, where hip flexion or a shrug then drags skin far + # from the joint. With thighCeiling, vertices on no leg part carry the thighs no higher + # than that fraction of UpLeg -> Hips; with clavicleFloor, vertices on no arm or hand + # part carry the clavicles no lower than that fraction of Spine02 -> Spine01. The + # boundary fades of step 3 ramp them out. Off by default: switched on for all 37 + # characters of the 2026-11-09 set they fixed the chest of coelho-pascoa-shopping and + # corisco but made five passing rigs fail at the hips or shoulders. + if P["thighCeiling"] is not None: + up_z = 0.5 * (joints["LeftUpLeg"].z + joints["RightUpLeg"].z) + above = co[:, 2] > up_z + P["thighCeiling"] * (joints["Hips"].z - up_z) + off_legs = np.array([not any(part.startswith("leg_") for part in vparts[v]) for v in range(n)]) + for bone in ("LeftUpLeg", "RightUpLeg"): + allowed[off_legs & above, bidx[bone]] = False + if P["clavicleFloor"] is not None: + below = co[:, 2] < joints["Spine02"].z + P["clavicleFloor"] * (joints["Spine01"].z - joints["Spine02"].z) + off_arms = np.array([not any(part.startswith(("arm_", "hand_")) for part in vparts[v]) for v in range(n)]) + for bone in ("LeftShoulder", "RightShoulder"): + allowed[off_arms & below, bidx[bone]] = False + # Spine-chain locality (opt-in, chainLocality x height): on vertices of no limb part, a + # chain bone (Hips, Spine02, Spine01, Spine, neck) is allowed only between its parent + # joint and its child joint (where a linear blend along the chain would give it any + # weight), widened by the margin. Heat on a coat or a big body can leave Hips weight + # 25 cm above the Hips joint, which a crouch then folds open. + if P["chainLocality"] is not None: + chain = ["Hips", "Spine02", "Spine01", "Spine", "neck", "Head"] + zs = [joints[b].z for b in chain] + margin = P["chainLocality"] * H + off_limbs = np.array([not any(p.startswith(("arm_", "hand_", "leg_")) for p in vparts[v]) for v in range(n)]) + for i, bone in enumerate(chain[:-1]): + lo = zs[i - 1] - margin if i > 0 else -np.inf + hi = zs[i + 1] + margin + allowed[off_limbs & ((co[:, 2] < lo) | (co[:, 2] > hi)), bidx[bone]] = False + # Side exclusivity (opt-in, sideExclusive x height): a vertex more than the margin to + # one side of the midline carries no bone of the other side. Heat through a collar, + # a cape or a fused chest can put RightShoulder weight on the left armpit. + if P["sideExclusive"] is not None: + margin = P["sideExclusive"] * H + for prefix, other_side in (("Right", co[:, 0] > margin), ("Left", co[:, 0] < -margin)): + for name in deform: + if name.startswith(prefix): + allowed[other_side, bidx[name]] = False W = np.where(allowed, W, 0.0) nearest_fill = 0 bone_heads = {name: joints[name.split(".")[0]] for name in deform} @@ -297,6 +492,104 @@ def main(): W[mask, cb] = share[mask] * s W[mask, pb] = share[mask] * (1 - s) + # ---------------------------------------------------------------- 4c. hanging cloth + for v in np.nonzero([r is not None for r in rigid])[0]: + W[v] = 0.0 + W[v, bidx[rigid[v]]] = 1.0 + landmarks = json.loads((args.work / "parts.json").read_text())["landmarks"] + crotch_z = float(landmarks["crotchZ"]) + rigid_mask = np.array([r is not None for r in rigid]) + # Vertices on a seam between two cloth extras (a coat cut into an upper and a lower + # extra) take the mean of their extras' cloth weights; left on heat they tore the seam + # (vlad death 4.05x: seam Hips 0.61 + RightUpLeg 0.28 next to cloth Hips 0.96). + cloth = {e["name"]: e for e in cfg.get("extras", []) if e.get("kind") in CLOTH_BONES} + on_cloth = np.array([bool(vparts[v]) and vparts[v] <= cloth.keys() for v in range(n)]) & ~rigid_mask + cloth_vertices = {} + if on_cloth.any(): + Wc = np.zeros((n, len(bidx))) + share = np.array([len(vparts[v]) for v in range(n)], dtype=float) + for name, extra in cloth.items(): + mask = on_cloth & np.array([name in vparts[v] for v in range(n)]) + Wc[mask] += cloth_weights(co[mask], extra["kind"], joints, bidx, extra.get("frontPanel")) / share[mask, None] + cloth_vertices[name] = int((mask & (share == 1)).sum()) + W[on_cloth] = Wc[on_cloth] + cloth_vertices["seam"] = int((on_cloth & (share > 1)).sum()) + + # ---------------------------------------------------------------- 4c'. band models + # Opt-in replacements for heat where crouch and death tear a junction whose heat + # weights depend on what the surface happens to touch (a coat front over the thighs, + # a tail base, dreads over the nape). Inside the band the weights are a smooth + # function of height and of the angle around the torso axis only; they fade back to the + # rule weights over half the margin beyond each end. + band_vertices = {} + eligible = ~rigid_mask & np.array([not any(p.startswith(("arm_", "hand_")) for p in vparts[v]) for v in range(n)]) + for kind, margin in (("waist", P["waistBand"]), ("neck", P["neckBand"]), ("flank", P["flankBand"])): + if not margin: + continue + fade_below = P["flankFade"] * H if kind == "flank" and P["flankFade"] else None + Wm, alpha = band_model(co, joints, bidx, kind, margin * H, fade_below) + Wm = np.where(allowed, Wm, 0.0) + sums = Wm.sum(axis=1) + alpha = np.where(eligible & (sums > 1e-6), alpha, 0.0) + if kind in ("waist", "flank"): + alpha = np.where([("head" in vparts[v]) for v in range(n)], 0.0, alpha) + if kind in ("neck", "flank"): + alpha = np.where([any(p.startswith("leg_") for p in vparts[v]) for v in range(n)], 0.0, alpha) + Wm = np.divide(Wm, sums[:, None], out=np.zeros_like(Wm), where=sums[:, None] > 1e-6) + rows = W.sum(axis=1, keepdims=True) + W = np.divide(W, rows, out=np.zeros_like(W), where=rows > 1e-9) + W = alpha[:, None] * Wm + (1 - alpha[:, None]) * W + band_vertices[kind] = int((alpha > 0.5).sum()) + + # ---------------------------------------------------------------- 4d. groin + band = P["groinBand"] * H + groin = 0 + if band > 0: + leg_x = 0.5 * (abs(joints["LeftUpLeg"].x) + abs(joints["RightUpLeg"].x)) + m = smoothstep(1 - np.abs(co[:, 0]) / leg_x) * smoothstep(1 - np.abs(co[:, 2] - crotch_z) / band) + m = np.where(rigid_mask | ~allowed[:, bidx["Hips"]], 0.0, m) + for side in ("LeftUpLeg", "RightUpLeg"): + moved = W[:, bidx[side]] * m + W[:, bidx[side]] -= moved + W[:, bidx["Hips"]] += moved + groin = int((m > 0.05).sum()) + + # ---------------------------------------------------------------- 4e. gradient limit + # Hard weight steps between neighbouring vertices (heat on layered cloth, proxy transfer + # across fused voxels, binary weights on small islands) tear edges open whatever the + # thresholds elsewhere. Every edge whose weight change exceeds its length over + # gradientRamp x height is relaxed towards its neighbour, rigid vertices held fixed. + limit_iterations, limit_left = 0, 0 + if P["gradientRamp"] > 0: + E = np.array([e.vertices[:] for e in me.edges], dtype=np.int64) + L = np.linalg.norm(co[E[:, 0]] - co[E[:, 1]], axis=1) + g = L / (P["gradientRamp"] * H) + free = (~rigid_mask).astype(float) + sums = W.sum(axis=1, keepdims=True) + W = np.divide(W, sums, out=np.zeros_like(W), where=sums > 1e-9) + for limit_iterations in range(1, int(P["gradientIterations"]) + 1): + d = W[E[:, 0]] - W[E[:, 1]] + mag = np.abs(d).max(axis=1) + over = mag > g * 1.001 + if not over.any(): + break + a, b = E[over, 0], E[over, 1] + fa, fb = free[a], free[b] + share = fa + fb + keep = share > 0 + corr = d[over] * (1 - g[over] / mag[over])[:, None] + delta = np.zeros_like(W) + count = np.zeros(n) + np.add.at(delta, a[keep], -corr[keep] * (fa[keep] / share[keep])[:, None]) + np.add.at(delta, b[keep], corr[keep] * (fb[keep] / share[keep])[:, None]) + np.add.at(count, a[keep], 1) + np.add.at(count, b[keep], 1) + W = np.where(allowed, np.clip(W + delta / np.maximum(count, 1)[:, None], 0, None), 0.0) + sums = W.sum(axis=1, keepdims=True) + W = np.divide(W, sums, out=np.zeros_like(W), where=sums > 1e-9) + # Counted on the final weights, after the last correction of the loop. + limit_left = int((np.abs(W[E[:, 0]] - W[E[:, 1]]).max(axis=1) > g * 1.001).sum()) + # ---------------------------------------------------------------- 5. rigid, limit, normalise for v in range(n): if rigid[v] is not None: @@ -317,6 +610,33 @@ def main(): row /= total W[v] = row + # ---------------------------------------------------------------- 6. joint-zone smoothing + # Opt-in. The rules above leave the shoulders, armpits and neck with weights that change + # bone mix from one vertex to the next (part borders, ramps, the 4-influence cut); when an + # arm is raised to hold a weapon those edges fold to under half their length or open to + # twice it (client select-inflate gate). Within ``radius`` x height of the listed joints + # (fading to nothing at twice that) each vertex moves ``alpha`` of the way to the mean of + # its neighbours, per iteration, over the bones it already carries only: no vertex gains + # a bone, so the part rules, rigid vertices (one bone) and the 4-influence limit hold. + joint_smoothed = 0 + js = P["jointSmooth"] + if js: + centres = np.array([joints[name][:] for name in js["joints"]]) + dist = np.min(np.linalg.norm(co[:, None, :] - centres[None], axis=2), axis=1) + zone = np.clip(2.0 - dist / (js["radius"] * H), 0.0, 1.0) * float(js.get("alpha", 0.5)) + support = W > 0 + zone = np.where(rigid_mask | (support.sum(axis=1) < 2), 0.0, zone) + joint_smoothed = int((zone > 0).sum()) + E = np.array([e.vertices[:] for e in me.edges], dtype=np.int64) + deg = np.bincount(E.ravel(), minlength=n).astype(float) + for _ in range(int(js.get("iterations", 20))): + mean = np.zeros_like(W) + np.add.at(mean, E[:, 0], W[E[:, 1]]) + np.add.at(mean, E[:, 1], W[E[:, 0]]) + mean = np.divide(mean, deg[:, None], out=W.copy(), where=deg[:, None] > 0) + W = np.where(support, (1 - zone[:, None]) * W + zone[:, None] * mean, 0.0) + W /= W.sum(axis=1, keepdims=True) + for g in list(body.vertex_groups): body.vertex_groups.remove(g) groups = {name: body.vertex_groups.new(name=name) for name in deform} @@ -339,6 +659,9 @@ def main(): "heat": {"unweightedVertices": int(unweighted.sum()), "emptyBones": empty_bones}, "nearestBoneFill": nearest_fill, "fadedWeights": faded, "smoothedVertices": smoothed, "rigidVertices": int(sum(r is not None for r in rigid)), + "clothVertices": cloth_vertices, "bandVertices": band_vertices, "groinVertices": groin, + "gradientLimit": {"iterations": limit_iterations, "edgesStillOver": limit_left}, + "jointSmoothedVertices": joint_smoothed, "armWeightOnNoArmParts": C.r(W[only_no_arm][:, arm_cols].max() if only_no_arm.any() else 0.0, 6), "hands": hand_checks, "influences": {str(k): int((influences == k).sum()) for k in range(1, 5)}, @@ -358,4 +681,4 @@ def main(): f"armOnTorso={report['armWeightOnNoArmParts']} hands={hand_checks} maxInf={report['maxInfluences']}") -main() +C.run_main(main) diff --git a/tools/characters/rig-character.mjs b/tools/characters/rig-character.mjs index b53d3de..40ebd89 100755 --- a/tools/characters/rig-character.mjs +++ b/tools/characters/rig-character.mjs @@ -2,18 +2,24 @@ // Run the whole Blender character rig pipeline for one character (docs/character-rig.md). // // node tools/characters/rig-character.mjs --config=characters//rig.json --work= -// [--source=] [--from=clean|parts|joints|armature|weights|assemble|pose] +// [--source=] [--from=] [--to=] // --clips-from= --retarget=/tools/retarget-glb.mjs | --no-clips -// [--blender=/Applications/Blender.app/Contents/MacOS/Blender] +// [--blender=/Applications/Blender.app/Contents/MacOS/Blender] [--skip-review] // // Steps: clean -> parts -> joints (+ review sheets; joints.json validated) -> armature -> // weights -> assemble (/.blender.glb) -> pose: the shared clips are retargeted onto // the new rig with the client's tools/retarget-glb.mjs and the pose test runs --strict, so a // threshold failure fails the run. --no-clips limits the pose test to the synthetic poses. -// Every step is rerunnable; --from resumes after a manual edit (for example a joints.json -// override next to the config). +// +// Freshness: before a step runs, its outputs and every later step's outputs are deleted; +// after it runs, each output must exist and be newer than the step's start, whatever the +// step's exit code says. /run-manifest.json records, per step, the SHA-256 of its +// inputs (source, config, joints override) and outputs. --from resumes only when every +// skipped step's outputs still hash to what the manifest recorded and its inputs are +// unchanged, so a step can never run on top of stale or hand-edited upstream files. import { spawnSync } from 'node:child_process'; -import { existsSync, readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { validateJoints } from '../lib/character-rig.mjs'; @@ -21,47 +27,113 @@ import { validateJoints } from '../lib/character-rig.mjs'; const root = fileURLToPath(new URL('../../', import.meta.url)); const args = Object.fromEntries(process.argv.slice(2).map((a) => { const [k, ...v] = a.replace(/^--/, '').split('='); return [k, v.join('=') || true]; })); if (!args.config || !args.work) { - console.error('usage: rig-character.mjs --config= --work= [--source=] [--from=] (--clips-from= --retarget= | --no-clips) [--blender=]'); + console.error('usage: rig-character.mjs --config= --work= [--source=] [--from=] [--to=] (--clips-from= --retarget= | --no-clips) [--blender=] [--skip-review]'); process.exit(1); } const config = path.resolve(args.config); const work = path.resolve(args.work); -const id = JSON.parse(readFileSync(config, 'utf8')).id; +mkdirSync(work, { recursive: true }); +const cfg = JSON.parse(readFileSync(config, 'utf8')); +const id = cfg.id; +const override = path.resolve(path.dirname(config), cfg.jointsOverride || 'joints.json'); const blender = args.blender || process.env.BLENDER || '/Applications/Blender.app/Contents/MacOS/Blender'; +const model = path.join(work, `${id}.blender.glb`); const steps = ['clean', 'parts', 'joints', 'armature', 'weights', 'assemble', 'pose']; const from = steps.indexOf(args.from || 'clean'); -if (from < 0) throw new Error(`unknown step ${args.from}`); +const to = steps.indexOf(args.to || 'pose'); +if (from < 0 || to < 0 || to < from) throw new Error(`bad --from/--to: ${args.from} .. ${args.to}`); if (from === 0 && !args.source) throw new Error('--source is required when starting from clean'); -if (!args['no-clips'] && !(args.retarget && args['clips-from'])) throw new Error('pass --clips-from and --retarget together (or --no-clips for synthetic poses only)'); +if (to === steps.length - 1 && !args['no-clips'] && !(args.retarget && args['clips-from'])) throw new Error('pass --clips-from and --retarget together (or --no-clips for synthetic poses only)'); + +/* Files each step writes (relative to the work dir) and the inputs outside the work dir it reads. + Orthographic renders come with a .view.json sidecar (rig-review.mjs reads both); the + review sheets are outputs unless --skip-review, but are deleted before their step either way. */ +const renders = (prefix, views) => views.flatMap((view) => [`${prefix}-${view}.png`, `${prefix}-${view}.png.view.json`]); +const REVIEWS = { parts: 'parts-review.png', joints: 'joints-review.png' }; +const OUTPUTS = { + clean: ['clean.blend', 'clean.json', ...renders('clean', ['front', 'back', 'side'])], + parts: ['parts.blend', 'parts.json', 'parts-legend.json', ...renders('parts', ['front', 'back', 'side']), ...(args['skip-review'] ? [] : [REVIEWS.parts])], + joints: ['joints.json', 'joints-estimate.json', ...renders('joints', ['front', 'side']), ...(args['skip-review'] ? [] : [REVIEWS.joints])], + armature: ['armature.blend'], + weights: ['weights.blend', 'weights.json', 'blender-rig.glb'], + assemble: [path.basename(model)], + pose: ['pose-test.json'], +}; +const DIRS = { pose: ['clips'] }; +const inputsOf = (step) => { + const files = { config }; + if (step === 'clean') files.source = path.resolve(args.source ?? ''); + if (step === 'joints' && existsSync(override)) files.override = override; + return files; +}; +const sha = (file) => createHash('sha256').update(readFileSync(file)).digest('hex'); +const manifestPath = path.join(work, 'run-manifest.json'); +const manifest = existsSync(manifestPath) ? JSON.parse(readFileSync(manifestPath, 'utf8')) : { steps: {} }; + +// Resume guard: every skipped step must be intact and its inputs unchanged. +for (const step of steps.slice(0, from)) { + const record = manifest.steps[step]; + if (!record) throw new Error(`cannot resume at ${steps[from]}: ${step} has no record in ${manifestPath}; run --from=${step}`); + for (const [name, digest] of Object.entries(record.outputs)) { + const file = path.join(work, name); + if (!existsSync(file) || sha(file) !== digest) throw new Error(`cannot resume at ${steps[from]}: ${name} changed or vanished since ${step} ran; run --from=${step}`); + } + for (const [role, file] of Object.entries(inputsOf(step))) { + // A --source given on resume must be the one clean ran on; without --source it is not checked. + if (role === 'source' && !args.source) continue; + const digest = existsSync(file) ? sha(file) : null; + if (record.inputs[role]?.sha256 !== digest) throw new Error(`cannot resume at ${steps[from]}: ${role} ${file} changed since ${step} ran; run --from=${step}`); + } + if (step === 'joints' && !existsSync(override) && record.inputs.override) throw new Error(`cannot resume at ${steps[from]}: the joints override was removed since joints ran; run --from=joints`); +} -const run = (cmd, cmdArgs, options = {}) => { +// Invalidate this run's steps and everything downstream before anything runs. +for (const step of steps.slice(from)) { + for (const name of [...OUTPUTS[step], ...(REVIEWS[step] ? [REVIEWS[step]] : [])]) rmSync(path.join(work, name), { force: true }); + for (const name of DIRS[step] || []) rmSync(path.join(work, name), { recursive: true, force: true }); + delete manifest.steps[step]; +} +writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + +const run = (cmd, cmdArgs) => { console.log(`$ ${[cmd, ...cmdArgs].join(' ')}`); - const result = spawnSync(cmd, cmdArgs, { stdio: 'inherit', ...options }); - if (result.status !== 0) throw new Error(`${path.basename(cmd)} failed (${result.status})`); + const result = spawnSync(cmd, cmdArgs, { stdio: 'inherit' }); + if (result.status !== 0) throw new Error(`${path.basename(cmd)} ${path.basename(cmdArgs.find((a) => /\.(py|mjs)$/.test(a)) || '')} failed (exit ${result.status ?? result.signal})`); }; const blenderStep = (step, extra = []) => run(blender, ['-b', '--factory-startup', '--python', path.join(root, `tools/blender/character_rig/rig_${step}.py`), '--', '--config', config, '--work', work, ...extra]); -const model = path.join(work, `${id}.blender.glb`); +const review = (kind) => { if (!args['skip-review']) run(process.execPath, [path.join(root, 'tools/characters/rig-review.mjs'), kind, work]); }; -for (const step of steps.slice(from)) { +for (const step of steps.slice(from, to + 1)) { + const started = Date.now(); + const inputs = Object.fromEntries(Object.entries(inputsOf(step)).map(([role, file]) => [role, { path: file, sha256: sha(file) }])); if (step === 'clean') blenderStep('clean', ['--source', path.resolve(args.source)]); - else if (step === 'parts') { blenderStep('parts'); run(process.execPath, [path.join(root, 'tools/characters/rig-review.mjs'), 'parts', work]); } + else if (step === 'parts') { blenderStep('parts'); review('parts'); } else if (step === 'joints') { blenderStep('joints'); - const errors = validateJoints(JSON.parse(readFileSync(path.join(work, 'joints.json'), 'utf8'))); - if (errors.length) throw new Error(`joints.json is invalid:\n${errors.join('\n')}`); - run(process.execPath, [path.join(root, 'tools/characters/rig-review.mjs'), 'joints', work]); - } - else if (step === 'armature' || step === 'weights') blenderStep(step); + if (existsSync(path.join(work, 'joints.json'))) { + const errors = validateJoints(JSON.parse(readFileSync(path.join(work, 'joints.json'), 'utf8'))); + if (errors.length) throw new Error(`joints.json is invalid:\n${errors.join('\n')}`); + } + review('joints'); + } else if (step === 'armature' || step === 'weights') blenderStep(step); else if (step === 'assemble') run(process.execPath, [path.join(root, 'tools/characters/rig-assemble.mjs'), work, model]); else if (step === 'pose') { const clips = path.join(work, 'clips'); const poseArgs = [path.join(root, 'tools/characters/rig-pose-test.mjs'), model, `--out=${path.join(work, 'pose-test.json')}`, `--label=${id}`, '--strict']; if (!args['no-clips']) { - const retarget = path.resolve(args.retarget); - run(process.execPath, [retarget, path.resolve(args['clips-from']), model, clips]); + run(process.execPath, [path.resolve(args.retarget), path.resolve(args['clips-from']), model, clips]); if (!existsSync(path.join(clips, 'idle.glb'))) throw new Error(`retarget wrote no clips to ${clips}`); poseArgs.push(`--clips=${clips}`); } run(process.execPath, poseArgs); } + const outputs = {}; + for (const name of OUTPUTS[step]) { + const file = path.join(work, name); + if (!existsSync(file)) throw new Error(`${step} did not write ${name} (exit code was 0); not continuing on missing or stale files`); + if (statSync(file).mtimeMs < started - 1000) throw new Error(`${step} left ${name} older than the step; not continuing on stale files`); + outputs[name] = sha(file); + } + manifest.steps[step] = { finishedAt: new Date().toISOString(), inputs, outputs }; + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); } diff --git a/tools/characters/rig-pose-test.mjs b/tools/characters/rig-pose-test.mjs index de99e52..d63f11f 100755 --- a/tools/characters/rig-pose-test.mjs +++ b/tools/characters/rig-pose-test.mjs @@ -9,7 +9,9 @@ // 8 instants of each of the 11 state clips (use the clips retargeted to this model): the // longest edge stretch versus the bind pose, the 99th percentile, the upper-back and hand // regions, how far welded seam vertices drift apart, and the 10 worst vertices with their -// bones. --strict exits 1 when tools/lib/character-rig.mjs#POSE_THRESHOLDS fail. +// bones. It also records the bind-pose arm proportions and, with --clips, the visible arm +// angle at idle@0.5 against the donor's (armAngles in tools/lib/character-rig.mjs). +// --strict exits 1 when tools/lib/character-rig.mjs#POSE_THRESHOLDS fail. // --bake writes a static posed copy (no skin) for renders, e.g. --bake=walk@0.25:walk.glb or // --bake=arms-up-90:up.glb; `rest` bakes the bind pose. import { NodeIO } from '@gltf-transform/core'; @@ -17,8 +19,8 @@ import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; import { existsSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { - CLIP_SAMPLES, CLIP_STATES, SYNTHETIC_POSES, bakePosedDocument, clipOverrides, clipSampler, evaluatePoseReport, - loadRig, measurePose, measureSetup, skinPositions, summarize, syntheticOverrides, + CLIP_SAMPLES, CLIP_STATES, IDLE_ARM_SAMPLE, SYNTHETIC_POSES, armAngles, armProportions, bakePosedDocument, clipOverrides, + clipSampler, evaluatePoseReport, loadRig, measurePose, measureSetup, skinPositions, summarize, syntheticOverrides, } from '../lib/character-rig.mjs'; const args = process.argv.slice(2); @@ -34,6 +36,7 @@ const rig = loadRig(await io.read(model)); const setup = measureSetup(rig); const poses = []; const samplers = new Map(); +let armIdle = null; for (const pose of SYNTHETIC_POSES) { poses.push({ kind: 'synthetic', name: pose.name, ...measurePose(rig, setup, skinPositions(rig, syntheticOverrides(rig, pose))) }); @@ -51,6 +54,11 @@ if (clipsDir) { poses.push({ kind: 'clip', name: state, time, ...measurePose(rig, setup, skinPositions(rig, clipOverrides(rig, sampler, time))) }); } } + const idle = samplers.get('idle'); + if (idle) { + const idleOverrides = clipOverrides(rig, idle, idle.duration * IDLE_ARM_SAMPLE); + armIdle = armAngles(rig, setup, skinPositions(rig, idleOverrides), idleOverrides); + } } const triangles = rig.prims.reduce((sum, p) => sum + (p.idx ? p.idx.length : p.count) / 3, 0); @@ -60,7 +68,7 @@ const report = { model: path.resolve(model), label: flag('label') || path.basename(model, '.glb'), clips: clipsDir ? path.resolve(clipsDir) : null, triangles, vertices: rig.prims.reduce((sum, p) => sum + p.count, 0), height: +(maxY - minY).toFixed(4), bindError: +setup.bindError.toExponential(3), hasBack: setup.hasBack, hasHands: setup.hasHands, - summary: summarize(poses), poses, + summary: summarize(poses), arms: armProportions(rig), armIdle, poses, }; report.failures = evaluatePoseReport(report); if (flag('out')) writeFileSync(flag('out'), `${JSON.stringify(report, null, 2)}\n`); @@ -75,6 +83,7 @@ for (const kind of ['synthetic', 'clip']) { console.log(` worst ${kind} vertices (${worstPose.name}${worstPose.time != null ? `@${worstPose.time}s` : ''}):`); for (const v of worstPose.worstVertices) console.log(` ${String(v.ratio).padEnd(7)} v${v.vertex} rest ${v.rest.join(',')} ${v.bones.map(([b, w]) => `${b}:${w}`).join(' ')}`); } +console.log(` arms L ratio ${report.arms.L.ratio} R ratio ${report.arms.R.ratio}${report.armIdle ? ` | idle arm angle L ${report.armIdle.L}° R ${report.armIdle.R}°` : ''}`); console.log(report.failures.length ? ` FAIL ${report.failures.length} threshold(s): ${report.failures.slice(0, 5).join(' | ')}` : ' PASS pose thresholds'); for (const spec of args.filter((a) => a.startsWith('--bake=')).map((a) => a.slice(7))) { diff --git a/tools/checks/character-rig-check.mjs b/tools/checks/character-rig-check.mjs index f6052a6..dde0b9b 100755 --- a/tools/checks/character-rig-check.mjs +++ b/tools/checks/character-rig-check.mjs @@ -6,16 +6,20 @@ // R3 the meshy-28 skeleton the assembler builds has the contract's 28 joints in skin // order, the donor rest frames, and inverse bind matrices that reproduce the mesh; // R4 the pose test passes a synthetic, well-skinned humanoid (programmatic tubes, no real -// asset bytes) and fails each mutant on the clause it breaks. -import { readdirSync, readFileSync, statSync } from 'node:fs'; +// asset bytes) and fails each mutant on the clause it breaks; +// R5 every Blender step exits non-zero on exceptions, and the runner (with a fake Blender) +// records input/output hashes and never continues on missing, stale or edited files. +import { spawnSync } from 'node:child_process'; +import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { Document } from '@gltf-transform/core'; import * as THREE from 'three'; import { meshy28Joints } from '../lib/character-pack.mjs'; import { - ALIGNED_BONES, MESHY28_REST_WORLD, SYNTHETIC_POSES, assembleMeshy28Model, buildMeshy28Skeleton, deformJointNames, evaluatePoseReport, - loadRig, measurePose, measureSetup, skinPositions, summarize, syntheticOverrides, uniqueJointNames, validateJoints, + ALIGNED_BONES, MESHY28_REST_WORLD, SYNTHETIC_POSES, armAngles, armProportions, assembleMeshy28Model, buildMeshy28Skeleton, deformJointNames, + evaluatePoseReport, loadRig, measurePose, measureSetup, skinPositions, summarize, syntheticOverrides, uniqueJointNames, validateJoints, } from '../lib/character-rig.mjs'; const root = fileURLToPath(new URL('../../', import.meta.url)); @@ -44,14 +48,44 @@ clause('R1 character rig configs are well formed', () => { for (const extra of cfg.extras || []) { assert(extra.name && !partNames.has(extra.name) && !names.has(extra.name), `${file}: extra names must be unique and not body parts (${extra.name})`); names.add(extra.name); - assert(Boolean(extra.rigid) !== Boolean(extra.bones), `${file}: extra ${extra.name} needs exactly one of rigid or bones`); - for (const bone of extra.rigid ? [extra.rigid] : extra.bones) assert(deformJointNames.includes(bone), `${file}: ${extra.name} names ${bone}, which is not a deforming meshy-28 bone`); + const modes = [Boolean(extra.rigid), Boolean(extra.bones), Boolean(extra.kind), extra.remove === true].filter(Boolean).length; + assert(modes === 1, `${file}: extra ${extra.name} needs exactly one of rigid, bones, kind or remove: true`); + assert(extra.remove === undefined || (extra.remove === true && !extra.cut && extra.measure === undefined), `${file}: extra ${extra.name} remove must be true, without cut or measure`); + assert(!extra.kind || ['skirt', 'cape'].includes(extra.kind), `${file}: extra ${extra.name} has unknown kind ${extra.kind}`); + assert(extra.measure === undefined || typeof extra.measure === 'boolean', `${file}: extra ${extra.name} measure must be true or false`); + const fp = extra.frontPanel; + const fpObject = fp !== null && typeof fp === 'object' && Object.keys(fp).every((k) => ['share', 'spread'].includes(k)) + && (fp.share === undefined || (fp.share >= 0 && fp.share <= 1)) && (fp.spread === undefined || fp.spread > 0); + assert(fp === undefined || (Boolean(extra.kind) && (typeof fp === 'boolean' || fpObject)), + `${file}: extra ${extra.name} frontPanel must be a boolean or { share in [0, 1], spread > 0 } on a kind extra`); + for (const bone of extra.rigid ? [extra.rigid] : extra.bones || []) assert(deformJointNames.includes(bone), `${file}: ${extra.name} names ${bone}, which is not a deforming meshy-28 bone`); for (const from of extra.select?.from || []) assert(partNames.has(from) || names.has(from), `${file}: ${extra.name} selects from unknown part ${from}`); + const grow = extra.select?.grow; + if (grow) { + assert(Array.isArray(grow.seeds) && grow.seeds.length && grow.seeds.every((p) => Array.isArray(p) && p.length === 3 && p.every(Number.isFinite)), `${file}: ${extra.name} grow.seeds must be [x, y, z] points`); + assert(grow.crease === undefined || (grow.crease > 0 && grow.crease <= 180), `${file}: ${extra.name} grow.crease must be in (0, 180] degrees`); + assert(grow.thickness === undefined || grow.thickness >= 0, `${file}: ${extra.name} grow.thickness must be >= 0`); + } + for (const part of extra.cut || []) assert(partNames.has(part), `${file}: ${extra.name} cuts from unknown body part ${part}`); } for (const [parent, child] of cfg.weights?.linearBlends || []) { assert(deformJointNames.includes(parent) && deformJointNames.includes(child), `${file}: linearBlends names a bone that does not deform`); } + const { armpitX, armMinLength } = cfg.parts || {}; + assert(armpitX === undefined || (Number.isFinite(armpitX) && Math.abs(armpitX) > 0 && Math.abs(armpitX) < 1.5), `${file}: parts.armpitX must be an x in metres`); + assert(armMinLength === undefined || armMinLength === null || (armMinLength > 0 && armMinLength <= 0.3), `${file}: parts.armMinLength must be null or in (0, 0.3] x height`); for (const joint of cfg.weights?.smoothJoints || []) assert(uniqueJointNames.includes(joint), `${file}: smoothJoints names unknown joint ${joint}`); + for (const key of ['waistBand', 'neckBand', 'flankBand', 'flankFade']) { + const v = cfg.weights?.[key]; + assert(v === undefined || v === null || (v > 0 && v <= 0.2), `${file}: weights.${key} must be null or in (0, 0.2] x height`); + } + const js = cfg.weights?.jointSmooth; + assert(js === undefined || js === null || (typeof js === 'object' && Object.keys(js).every((k) => ['joints', 'radius', 'iterations', 'alpha'].includes(k)) + && Array.isArray(js.joints) && js.joints.length && js.joints.every((j) => uniqueJointNames.includes(j)) + && js.radius > 0 && js.radius <= 0.2 && (js.iterations === undefined || (Number.isInteger(js.iterations) && js.iterations > 0 && js.iterations <= 200)) + && (js.alpha === undefined || (js.alpha > 0 && js.alpha <= 1))), + `${file}: weights.jointSmooth must be null or { joints: [meshy-28 joints], radius in (0, 0.2] x height, iterations in 1..200, alpha in (0, 1] }`); + assert([undefined, 'armpit', 'junction'].includes(cfg.joints?.shoulderAt), `${file}: joints.shoulderAt must be "armpit" or "junction"`); } return configs.map(([dir]) => dir).join(', '); }); @@ -79,12 +113,22 @@ const J = { const TIPS = { LeftHandTip: [0.72, 1.25, 0], RightHandTip: [-0.72, 1.25, 0] }; const cleanJoints = Object.fromEntries(Object.entries(J).map(([n, [x, y, z]]) => [n, [x, -z, y]])); +/* Arm mutants move joints of the left arm (mesh and skeleton alike): `elbow-at-wrist` puts + the elbow 4 cm from the wrist (proportions), `arm-at-wrist` puts shoulder and elbow there, + so the clavicle carries the whole arm, the defect of a sleeve read as torso. */ +const mutantJoints = (mutant) => ({ + ...J, + ...(mutant === 'elbow-at-wrist' ? { LeftForeArm: [0.58, 1.25, 0] } : {}), + ...(mutant === 'arm-at-wrist' ? { LeftArm: [0.54, 1.25, 0], LeftForeArm: [0.58, 1.25, 0] } : {}), +}); + /** Tubes along joint chains; each ring is weighted by a smoothstep blend around every joint. */ function synthBody({ mutant = null } = {}) { + const JM = mutantJoints(mutant); const positions = [], joints = [], weights = [], indices = []; const slot = new Map(meshy28Joints.map(([name], i) => [name, i]).reverse()); const tube = (chain, radius, step = 0.02, sides = 8, blend = 0.05) => { - const points = chain.map((n) => new THREE.Vector3(...(Array.isArray(n) ? n : J[n]))); + const points = chain.map((n) => new THREE.Vector3(...(Array.isArray(n) ? n : JM[n]))); const names = chain.map((n) => (Array.isArray(n) ? null : n)); const total = points.slice(1).reduce((s, p, i) => s + p.distanceTo(points[i]), 0); const rings = Math.max(2, Math.round(total / step) + 1); @@ -167,7 +211,7 @@ function synthDocument(options = {}) { .setAttribute('WEIGHTS_0', doc.createAccessor().setType('VEC4').setArray(new Float32Array(body.weights)).setBuffer(buffer)) .setIndices(doc.createAccessor().setType('SCALAR').setArray(new Uint32Array(body.indices)).setBuffer(buffer)); const meshNode = doc.createNode('Body').setMesh(doc.createMesh('Body').addPrimitive(prim)); - const skeleton = buildMeshy28Skeleton(doc, { ...J, ...TIPS }); + const skeleton = buildMeshy28Skeleton(doc, { ...mutantJoints(options.mutant), ...TIPS }); if (options.mutant === 'stale-ibm') skeleton.joints[13].setTranslation(skeleton.joints[13].getTranslation().map((v, i) => v + (i === 1 ? 5 : 0))); const skin = doc.createSkin('meshy-28').setSkeleton(skeleton.joints[0]) .setInverseBindMatrices(doc.createAccessor().setType('MAT4').setArray(skeleton.inverseBindMatrices).setBuffer(buffer)); @@ -177,11 +221,17 @@ function synthDocument(options = {}) { return doc; } +/* A stand-in idle: both arms lowered 60° from T (the donor's idle arm angles are 50.8° and + 38.0° from down), measured as a clip pose so the idle arm gate applies. */ +const SYNTH_IDLE = { name: 'idle', steps: [['LeftArm', 'z', -60], ['RightArm', 'z', 60]] }; function poseReport(doc) { const rig = loadRig(doc); const setup = measureSetup(rig); const poses = SYNTHETIC_POSES.map((pose) => ({ kind: 'synthetic', name: pose.name, ...measurePose(rig, setup, skinPositions(rig, syntheticOverrides(rig, pose))) })); - return { bindError: setup.bindError, poses, summary: summarize(poses) }; + const idle = syntheticOverrides(rig, SYNTH_IDLE); + const idlePosed = skinPositions(rig, idle); + poses.push({ kind: 'clip', name: 'idle', time: 0, ...measurePose(rig, setup, idlePosed) }); + return { bindError: setup.bindError, poses, summary: summarize(poses), arms: armProportions(rig), armIdle: armAngles(rig, setup, idlePosed, idle) }; } // ------------------------------------------------------------------------------ R2 joints.json @@ -316,7 +366,7 @@ clause('R4 synthetic humanoid passes the pose thresholds', () => { const report = poseReport(synthDocument()); const failed = evaluatePoseReport(report); assert(!failed.length, failed.join('; ')); - return `worst ${report.summary.synthetic.maxEdge.value}× (${report.summary.synthetic.maxEdge.pose})`; + return `worst ${report.summary.synthetic.maxEdge.value}× (${report.summary.synthetic.maxEdge.pose}); arm ratio ${report.arms.L.ratio}, idle arm ${report.armIdle.L}°/${report.armIdle.R}°`; }); const poseMutants = [ ['arm-weight-on-torso', /back stretch/], @@ -324,6 +374,8 @@ const poseMutants = [ ['stale-ibm', /bind pose does not reproduce/], ['hard-step', /max edge stretch/], ['hand-on-spine', /hand L stretch/], + ['elbow-at-wrist', /arm L: Arm→ForeArm \/ ForeArm→Hand/], + ['arm-at-wrist', /idle arm L: /], ]; for (const [mutant, expected] of poseMutants) { clause(`R4 pose-test mutant rejected: ${mutant}`, () => { @@ -335,7 +387,86 @@ for (const [mutant, expected] of poseMutants) { clause('R4 a report without synthetic poses is rejected', () => { const failed = evaluatePoseReport({ bindError: 0, poses: [] }); assert(failed.some((f) => /no synthetic poses/.test(f)), failed.join('; ')); + assert(failed.some((f) => /no arm proportions/.test(f)), failed.join('; ')); +}); +clause('R4 a clip report without the idle arm angle is rejected', () => { + const report = poseReport(synthDocument()); + delete report.armIdle; + const failed = evaluatePoseReport(report); + assert(failed.some((f) => /no idle arm angle/.test(f)), failed.join('; ') || 'a pass'); +}); + +// ------------------------------------------------------------------------------ R5 runner +/* The runner never continues on missing or stale step outputs. Blender itself cannot run in + CI, so a fake Blender (a Node script with Blender's command line) writes each step's files; + FAKE_SKIP= makes it exit 0 without writing (what Blender did when a Python step + raised before the steps called C.run_main), FAKE_FAIL= makes it exit 1. */ +clause('R5 every Blender step exits non-zero on exceptions (C.run_main)', () => { + const dir = path.join(root, 'tools/blender/character_rig'); + const steps = readdirSync(dir).filter((f) => /^rig_.*\.py$/.test(f)); + for (const file of steps) assert(/\nC\.run_main\(main\)\s*$/.test(readFileSync(path.join(dir, file), 'utf8')), `${file} does not end with C.run_main(main)`); + assert(/os\._exit\(1\)/.test(readFileSync(path.join(dir, 'common.py'), 'utf8')), 'common.run_main does not exit 1'); + return steps.join(', '); }); +{ + const tmp = mkdtempSync(path.join(os.tmpdir(), 'rig-runner-')); + const fake = path.join(tmp, 'fake-blender.mjs'); + writeFileSync(fake, `#!/usr/bin/env node +import { writeFileSync } from 'node:fs'; +import path from 'node:path'; +const argv = process.argv.slice(2); +const step = path.basename(argv[argv.indexOf('--python') + 1]).replace(/^rig_|\\.py$/g, ''); +const work = argv[argv.indexOf('--work') + 1]; +if (process.env.FAKE_FAIL === step) process.exit(1); +if (process.env.FAKE_SKIP === step) process.exit(0); +const views = { clean: ['front', 'back', 'side'], parts: ['front', 'back', 'side'], joints: ['front', 'side'] }[step]; +const renders = views.flatMap((v) => [step + '-' + v + '.png', step + '-' + v + '.png.view.json']).filter((f) => f !== process.env.FAKE_NO_RENDER); +const files = { clean: ['clean.blend', 'clean.json'], parts: ['parts.blend', 'parts.json', 'parts-legend.json'], joints: ['joints-estimate.json'] }[step]; +for (const f of [...files, ...renders]) writeFileSync(path.join(work, f), step + Date.now()); +if (step === 'joints') writeFileSync(path.join(work, 'joints.json'), process.env.FAKE_JOINTS); +`); + chmodSync(fake, 0o755); + const config = path.join(tmp, 'rig.json'); + const source = path.join(tmp, 'source.glb'); + writeFileSync(config, JSON.stringify({ id: 'fake', targetHeight: 1.7 })); + writeFileSync(source, 'mesh'); + const work = path.join(tmp, 'work'); + const runner = (from, env = {}) => spawnSync(process.execPath, [path.join(root, 'tools/characters/rig-character.mjs'), + `--config=${config}`, `--work=${work}`, `--source=${source}`, `--from=${from}`, '--to=joints', '--no-clips', '--skip-review', `--blender=${fake}`], + { encoding: 'utf8', env: { ...process.env, FAKE_JOINTS: JSON.stringify(baseJoints), ...env } }); + const expectFail = (result, pattern) => { + assert(result.status !== 0, 'runner succeeded'); + assert(pattern.test(result.stderr), `expected ${pattern}, got ${result.stderr.split('\n').find((l) => /Error/.test(l)) || result.stderr.slice(0, 200)}`); + }; + clause('R5 runner records clean -> parts -> joints with input and output hashes', () => { + const result = runner('clean'); + assert(result.status === 0, result.stderr); + const manifest = JSON.parse(readFileSync(path.join(work, 'run-manifest.json'), 'utf8')); + assert(['clean', 'parts', 'joints'].every((s) => manifest.steps[s]?.outputs), 'manifest lacks a step'); + assert(manifest.steps.clean.inputs.source.sha256 && manifest.steps.joints.outputs['joints.json'], 'manifest lacks hashes'); + }); + clause('R5 mutant rejected: a step exits 0 without writing (stale joints.json is not reused)', () => { + expectFail(runner('joints', { FAKE_SKIP: 'joints' }), /joints did not write joints\.json/); + assert(!existsSync(path.join(work, 'joints.json')), 'the stale joints.json survived'); + }); + clause('R5 mutant rejected: a step exits 1', () => expectFail(runner('clean', { FAKE_FAIL: 'parts' }), /failed \(exit 1\)/)); + clause('R5 mutant rejected: a step leaves an old render behind', () => { + assert(runner('clean').status === 0, 'baseline run failed'); + expectFail(runner('parts', { FAKE_NO_RENDER: 'parts-side.png' }), /parts did not write parts-side\.png/); + assert(!existsSync(path.join(work, 'parts-side.png')), 'the stale parts-side.png survived'); + }); + clause('R5 mutant rejected: resuming after the config changed', () => { + assert(runner('clean').status === 0, 'baseline run failed'); + writeFileSync(config, JSON.stringify({ id: 'fake', targetHeight: 1.6 })); + expectFail(runner('joints'), /config .* changed since clean ran/); + }); + clause('R5 mutant rejected: resuming on a hand-edited upstream output', () => { + assert(runner('clean').status === 0, 'baseline run failed'); + writeFileSync(path.join(work, 'parts.json'), '{}'); + expectFail(runner('joints'), /parts\.json changed or vanished since parts ran/); + }); + rmSync(tmp, { recursive: true, force: true }); +} if (failures) { console.error(`character-rig-check: ${failures} clause(s) failed`); diff --git a/tools/lib/character-rig.mjs b/tools/lib/character-rig.mjs index 70a58f2..ff11684 100644 --- a/tools/lib/character-rig.mjs +++ b/tools/lib/character-rig.mjs @@ -316,7 +316,9 @@ export function measureSetup(rig) { const list = groups.get(key); if (list) list.push(v); else groups.set(key, [v]); } const seams = [...groups.values()].filter((g) => g.length > 1); - return { edges, regions, seams, bind: s }; + const hands = { L: [], R: [] }; + for (let v = 0; v < p.count; v += 1) for (const side of ['L', 'R']) if (handWeight(side, v) >= 0.5) hands[side].push(v); + return { edges, regions, seams, hands, bind: s }; }); return { bind, bindError, prims, @@ -378,18 +380,63 @@ export function measurePose(rig, setup, posed, { worst = 10 } = {}) { }; } +/** Bind-pose arm proportions per side: Arm→ForeArm and ForeArm→Hand lengths (m) and their ratio. */ +export function armProportions(rig) { + const world = worldMatrices(rig); + const at = (name) => new THREE.Vector3().setFromMatrixPosition(world(rig.byName.get(name)[0])); + const out = {}; + for (const [side, prefix] of [['L', 'Left'], ['R', 'Right']]) { + const upper = at(`${prefix}Arm`).distanceTo(at(`${prefix}ForeArm`)); + const lower = at(`${prefix}ForeArm`).distanceTo(at(`${prefix}Hand`)); + out[side] = { upper: +upper.toFixed(4), lower: +lower.toFixed(4), ratio: +(upper / Math.max(lower, 1e-6)).toFixed(3) }; + } + return out; +} + +/* Visible arm angle of a posed state per side, in degrees: the angle between world down and the + line from the posed `Shoulder` (clavicle) joint to the centroid of the posed hand + vertices (hand weight >= 0.5). It follows the skinned mesh, not the arm bones: the clips + turn the Arm bone the same way whatever its position, but when the Arm joint sits near the + wrist the clavicle carries the whole arm and the mesh stays in T. 0° = hanging straight + down, 90° = T. null when the side has no hand vertices. */ +export function armAngles(rig, setup, posed, overrides) { + const world = worldMatrices(rig, overrides); + const out = {}; + for (const [side, prefix] of [['L', 'Left'], ['R', 'Right']]) { + const c = new THREE.Vector3(); + let count = 0; + setup.prims.forEach((sp, pi) => { + for (const v of sp.hands[side]) { c.x += posed[pi][v * 3]; c.y += posed[pi][v * 3 + 1]; c.z += posed[pi][v * 3 + 2]; count += 1; } + }); + if (!count) { out[side] = null; continue; } + c.divideScalar(count).sub(new THREE.Vector3().setFromMatrixPosition(world(rig.byName.get(`${prefix}Shoulder`)[0]))); + out[side] = +THREE.MathUtils.radToDeg(c.angleTo(new THREE.Vector3(0, -1, 0))).toFixed(1); + } + return out; +} + export const CLIP_STATES = Object.freeze(['idle', 'walk', 'run', 'shoot', 'death', 'crouch', 'crouchwalk', 'jump', 'idle1h', 'walk1h', 'walkfire']); export const CLIP_SAMPLES = 8; /* Pass/fail limits of the pose test. Hands follow the client's hand gate (RM1 2.5x, tools/eval/rig-maos-check.mjs). Body and upper-back limits sit just above the meshy-28 donor's own result on its shared clips (mst: 3.04x max edge, 3.04x back, 2.19x synthetic; - docs/character-rig.md). Seams welded in the clean step must not open: 5 mm. */ + docs/character-rig.md). Seams welded in the clean step must not open: 5 mm. + Arms: the bind-pose Arm→ForeArm / ForeArm→Hand length ratio must lie in armRatio (the + donor is 0.99 / 1.06), and the visible arm angle at idle@0.5 (armAngles(): world down vs + clavicle joint → hand centroid of the skinned mesh) must lie within idleArmDeg of the + donor's own (mst on its idle clip at 0.5: 50.8° left, 38.0° right, rifle idle). A rig + whose Arm joint sits near the wrist keeps every clip's arms in T (60-80°). */ export const POSE_THRESHOLDS = Object.freeze({ clip: { maxEdge: 3.5, backMaxEdge: 3.5, handMaxEdge: 2.5, seamGapMax: 0.005 }, synthetic: { maxEdge: 3.5, backMaxEdge: 3.5, handMaxEdge: 2.5, seamGapMax: 0.005 }, bindError: 0.002, + armRatio: [0.6, 1.7], + idleArmDeg: 25, + donorIdleArmDeg: Object.freeze({ L: 50.8, R: 38.0 }), }); +/* Sample of the idle clip for the arm-angle gate (fraction of its duration). */ +export const IDLE_ARM_SAMPLE = 0.5; export function summarize(poses) { const pick = (kind, key, side) => { @@ -435,6 +482,22 @@ export function evaluatePoseReport(report, thresholds = POSE_THRESHOLDS) { } if (pose.seamGapMax > limit.seamGapMax) failures.push(`${at}: seam opens ${pose.seamGapMax} m > ${limit.seamGapMax}`); } + const [lo, hi] = thresholds.armRatio; + if (!report?.arms) failures.push('no arm proportions measured'); + for (const side of ['L', 'R']) { + const a = report?.arms?.[side]; + if (a && !(a.ratio >= lo && a.ratio <= hi)) failures.push(`arm ${side}: Arm→ForeArm / ForeArm→Hand ${a.ratio} outside [${lo}, ${hi}]`); + } + if (kinds.has('clip')) { + if (!report.armIdle) failures.push('no idle arm angle measured'); + for (const side of ['L', 'R']) { + if (!report.armIdle) break; + const deg = report.armIdle[side]; + const ref = thresholds.donorIdleArmDeg[side]; + if (deg == null) failures.push(`idle arm ${side}: not measurable (no hand vertices)`); + else if (Math.abs(deg - ref) > thresholds.idleArmDeg) failures.push(`idle arm ${side}: ${deg}° vs donor ${ref}° (more than ±${thresholds.idleArmDeg}°)`); + } + } return failures; }