@babylonjs-toolkit/agent 1.2.15 → 1.2.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/lib/diskinfo/cli.js +40 -6
- package/lib/diskinfo/report.js +28 -15
- package/package.json +1 -1
- package/skills/bt-blender/SKILL.md +386 -0
- package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
- package/skills/bt-blender/references/art-style-and-genre.md +173 -0
- package/skills/bt-blender/references/characters-and-creatures.md +644 -0
- package/skills/bt-blender/references/environments.md +478 -0
- package/skills/bt-blender/references/game-engine-export.md +284 -0
- package/skills/bt-blender/references/geometry-nodes.md +447 -0
- package/skills/bt-blender/references/hard-surface.md +720 -0
- package/skills/bt-blender/references/procedural-generation.md +358 -0
- package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
- package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
- package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
- package/skills/bt-blender/references/vehicles.md +632 -0
- package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
- package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
- package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
- package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
- package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
- package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
- package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
- package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
- package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
- package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
- package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
- package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
- package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
- package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
- package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
- package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
- package/skills/bt-blender/scripts/blender/review_render.py +358 -0
- package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
- package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
- package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
- package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
- package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
- package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
- package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
- package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
- package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
- package/skills/bt-gauntlet/SKILL.md +6 -6
- package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
- package/skills/bt-gauntlet/references/spec-composition.md +13 -0
- package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
- package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
|
@@ -0,0 +1,1080 @@
|
|
|
1
|
+
# Rigging and animation: skeletons, weights, clips, IK, retargeting, shape keys, mechanical rigs and export
|
|
2
|
+
|
|
3
|
+
**Load this when** something has to move: a character or creature skeleton, skin weights, walk and idle cycles,
|
|
4
|
+
constraints that must become keys, a clip moved from one skeleton to another, shape keys, or a mechanical rig
|
|
5
|
+
(wheels, steering, doors, turrets) driven by an object hierarchy. Load it for the export to Unity (FBX,
|
|
6
|
+
Humanoid) and to glTF for BabylonJS, and for proving the exported animation matches the source.
|
|
7
|
+
|
|
8
|
+
**What it assumes.** The Agent Reference's Blender guide (`references/unity-blender-cli.md`) covers the basics:
|
|
9
|
+
§4 for the four ways to (re)build weights, the verified re-weight script, direct weight edits, the clean ->
|
|
10
|
+
limit -> normalize order (§4.4), weight transfer (§4.5) and the weight report (§4.6); §5 for listing actions;
|
|
11
|
+
§8.2a for Unity's axes and scale and `bake_space_transform` (False for anything rigged). This file goes deeper on
|
|
12
|
+
building rigs and clips headless and on what survives export. `characters-and-creatures.md` builds the meshes
|
|
13
|
+
and the joint chart the skeleton is made from; `vehicles.md` §6 covers vehicle pivots and parts.
|
|
14
|
+
|
|
15
|
+
**Helpers.** `scripts/blender/rigging_tools.py` provides:
|
|
16
|
+
- skeletons: `build_armature`, `mirror_report`, `humanoid_report`, `game_skeleton`, `UNITY_HUMANOID_MAP`;
|
|
17
|
+
- weights: `bind_auto`, `heat_weights`, `make_engine_legal`, `fill_unweighted`, `rigid_bind`, `attach`,
|
|
18
|
+
`weight_report`;
|
|
19
|
+
- clips: `new_action`, `use_action`, `fcurves`, `key_pose`, `key_object`, `set_interpolation`, `make_cyclic`,
|
|
20
|
+
`stash_action`, `clear_active_action`, `split_action`, `bake_to_keys`, `fit_pole_angle`;
|
|
21
|
+
- retargeting: `retarget_action`, `bone_direction_error`; shape keys: `add_shape_key`, `key_shape`;
|
|
22
|
+
- mechanical rigs: `set_origin`, `pivot_empty`, `parent_to`, `wheel_degrees_per_frame`;
|
|
23
|
+
- export and proof: `GLTF_RIG_SETTINGS`, `UNITY_FBX_RIG_SETTINGS`, `UNITY_FBX_SCENE_TAKE`, `export_rig`,
|
|
24
|
+
`gltf_animation_summary`, `import_rig`, `find_clip`, `play`, `play_clip`, `gltf_rest`, `nearest_vertex`,
|
|
25
|
+
`evaluated_positions`, `reset_pose`.
|
|
26
|
+
|
|
27
|
+
Every recipe below is a complete script. Run it with
|
|
28
|
+
`node <skill>/scripts/bt-blender.mjs run recipe.py <out folder>`.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## 1. The professional workflow
|
|
33
|
+
|
|
34
|
+
1. **Two skeletons, one job each.** The *deform skeleton* is what ships: only bones that move vertices, in one
|
|
35
|
+
clean hierarchy. The *control rig* (IK, constraints, widgets) drives it and never ships (Valve; every
|
|
36
|
+
studio rig). Small rigs can be one skeleton with no controls; then the clips are keyed on the deform bones.
|
|
37
|
+
2. **Build the deform skeleton from the same chart as the mesh** (section 2), check names, mirror and rolls.
|
|
38
|
+
3. **Bind** with automatic weights made engine-legal (section 4); check every vertex is weighted.
|
|
39
|
+
4. **Deformation test**: pose every joint to its range (elbow 140 degrees, knee 140, shoulder up and forward,
|
|
40
|
+
hip forward and to the side, spine twist, neck turn) and look at a review render of each. Bad weights are a
|
|
41
|
+
hand-off for weight painting by eye when a hero character must look right in close-up.
|
|
42
|
+
5. **Author clips** on the control rig or directly on the deform bones (section 5); bake constraints to keys
|
|
43
|
+
(section 6).
|
|
44
|
+
6. **Export** by target (section 10), then **re-import and compare** (section 11). An export that has not been
|
|
45
|
+
re-imported has not been checked.
|
|
46
|
+
|
|
47
|
+
**What needs a person.** Weight painting judged by eye, facial expressions with acting, and polished motion
|
|
48
|
+
(timing, spacing, overlap: the animator's craft) need a person or motion capture. Headless covers skeletons,
|
|
49
|
+
binding, procedural and keyed clips, mechanical motion, baking, retargeting and every check.
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 2. A deform skeleton from scratch
|
|
54
|
+
|
|
55
|
+
`build_armature(name, chart)` creates one bone per chart entry, connected where the chart says so, with the
|
|
56
|
+
rolls recalculated in one pass. Rules that matter:
|
|
57
|
+
|
|
58
|
+
- **Chains, not islands**: every bone has a parent except the root; a clavicle's head may sit off its parent's
|
|
59
|
+
tail (unconnected) but it still has a parent.
|
|
60
|
+
- **Roll** decides which local axis a bend uses. `GLOBAL_NEG_Y` (local Z towards the character's front, -Y)
|
|
61
|
+
gives every hinge (elbow, knee, finger) a fold about local X, and mirrors left and right exactly
|
|
62
|
+
(`mirror_report`: 8 pairs, 0 errors). `GLOBAL_POS_Z` gave the legs an 88-degree roll: rotations still work,
|
|
63
|
+
but X no longer means "bend" on every bone, which makes keyed clips and IK pole angles inconsistent.
|
|
64
|
+
- **A rest bend** of a few degrees at elbows and knees sets the IK bend direction (`humanoid_chart` puts 8 and 4
|
|
65
|
+
in).
|
|
66
|
+
- **Scale 1, rotation 0** on the armature object, applied before binding and exporting.
|
|
67
|
+
|
|
68
|
+
### Names: Mixamo, Unity Humanoid and other conventions
|
|
69
|
+
|
|
70
|
+
| Mixamo (`mixamorig:` prefix optional) | Unity HumanBodyBones | Common game-engine name | Required by Humanoid |
|
|
71
|
+
|---|---|---|---|
|
|
72
|
+
| Hips | Hips (must be the root of the bone hierarchy) | pelvis | Yes |
|
|
73
|
+
| Spine | Spine | spine_01 | Yes |
|
|
74
|
+
| Spine1 | Chest | spine_02 | Optional |
|
|
75
|
+
| Spine2 | UpperChest | spine_03 | Optional |
|
|
76
|
+
| Neck | Neck | neck | Optional |
|
|
77
|
+
| Head | Head | head | Yes |
|
|
78
|
+
| LeftShoulder | LeftShoulder | clavicle_l | Optional |
|
|
79
|
+
| LeftArm | LeftUpperArm | upperarm_l | Yes |
|
|
80
|
+
| LeftForeArm | LeftLowerArm | lowerarm_l | Yes |
|
|
81
|
+
| LeftHand | LeftHand | hand_l | Yes |
|
|
82
|
+
| LeftUpLeg | LeftUpperLeg | thigh_l | Yes |
|
|
83
|
+
| LeftLeg | LeftLowerLeg | calf_l | Yes |
|
|
84
|
+
| LeftFoot | LeftFoot | foot_l | Yes |
|
|
85
|
+
| LeftToeBase | LeftToes | ball_l | Optional |
|
|
86
|
+
| LeftHandThumb1-3, Index1-3, ... | Left Thumb/Index/... Proximal, Intermediate, Distal | thumb_01_l ... | Optional (0-3 per finger) |
|
|
87
|
+
|
|
88
|
+
Right mirrors left. Unity needs at least these 15 bones (Hips, Spine, Head and per side upper arm, lower arm,
|
|
89
|
+
hand, upper leg, lower leg, foot); its auto-mapping recognises the Mixamo names with or without the prefix.
|
|
90
|
+
`humanoid_report` checks the map, the hierarchy, the arm angle and the scale. Humanoid has **no twist-bone
|
|
91
|
+
slots** (it spreads twist itself, 50 % by default): twist bones in a Humanoid rig are not driven by Humanoid
|
|
92
|
+
clips. Mixamo's full rig is about 65 bones with fingers and end bones and has no twist bones.
|
|
93
|
+
|
|
94
|
+
**Pose for Unity.** Humanoid's reference is a T-pose: an A-pose rig imports with "Character not in T-Pose", and
|
|
95
|
+
**Pose > Enforce T-Pose** in the avatar configuration fixes it without touching the file. Translation is
|
|
96
|
+
animated on the Hips only by default (Translate DoF off).
|
|
97
|
+
|
|
98
|
+
**Root bone.** Unity Humanoid wants Hips as the root. A Generic rig or a glTF character that uses root motion
|
|
99
|
+
wants a dedicated root bone at the floor under the hips that represents no body part: in-place clips leave it
|
|
100
|
+
still, root-motion clips move it (Unreal's convention, which Unity's Generic Root node setting also follows).
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 3. Rigify headless, or a plain deform rig
|
|
105
|
+
|
|
106
|
+
| | Plain deform rig (`build_armature`) | Rigify control rig + `game_skeleton` |
|
|
107
|
+
|---|---|---|
|
|
108
|
+
| Bones | Exactly the chart (22 for the test biped) | 222 generated, 35 deform for the basic human |
|
|
109
|
+
| Authoring | Keys on deform bones; constraints added by script | FK/IK switches, foot roll, pole controls: the animator's rig |
|
|
110
|
+
| Export | Directly | Bake to the game skeleton, export that alone |
|
|
111
|
+
| Unity Humanoid | Names map directly | Rename (`DEF-upper_arm.L` style) or map the avatar by hand |
|
|
112
|
+
| Use | Procedural, keyed and retargeted clips; mechanical props | Hand animation in the GUI, then headless bake and export |
|
|
113
|
+
|
|
114
|
+
**Rigify runs headless** (Blender 5.3.0, 0.07 s for the basic human) with one trap: `pose.rigify_generate`
|
|
115
|
+
asserts that the metarig is the context's active object. Select it and make it active in the view layer, and
|
|
116
|
+
call the operator **without** `temp_override`; an override fails the assertion.
|
|
117
|
+
|
|
118
|
+
**The game-skeleton problem.** Rigify parents 11 of its 35 deform bones under ORG / MCH helper bones, so a
|
|
119
|
+
deform-only export is not one connected chain and Unity's auto-mapping struggles. `game_skeleton` copies the
|
|
120
|
+
deform bones at their rest matrices into a new armature, parents each to its nearest deform ancestor (one
|
|
121
|
+
root, `spine`), drives them from the control rig with Copy Transforms and moves the skinned meshes over;
|
|
122
|
+
`bake_to_keys` then turns each clip into plain keys.
|
|
123
|
+
|
|
124
|
+
### Recipe: Rigify headless, a clean game skeleton, a baked clip
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
"""Rigify headless, then a game skeleton. Rigify generates a full control rig from its human metarig; the
|
|
128
|
+
deform (DEF-) bones hang under ORG / MCH helpers, which engines should not get. game_skeleton copies the
|
|
129
|
+
deform bones into a clean single-root hierarchy driven by the control rig; one clip animated on the controls
|
|
130
|
+
is baked onto it. Saves rigify.blend and exports game_skeleton.glb."""
|
|
131
|
+
import json
|
|
132
|
+
import os
|
|
133
|
+
import sys
|
|
134
|
+
import time
|
|
135
|
+
|
|
136
|
+
import addon_utils
|
|
137
|
+
import bpy
|
|
138
|
+
|
|
139
|
+
import construction_kit as kit
|
|
140
|
+
import rigging_tools as rig
|
|
141
|
+
|
|
142
|
+
out_folder = sys.argv[sys.argv.index("--") + 1]
|
|
143
|
+
WAVE_DEGREES = 60.0
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def strip_deform_prefix(name):
|
|
147
|
+
"""DEF-upper_arm.L -> upper_arm.L (the engine-side name)."""
|
|
148
|
+
return name[len(rig.DEFORM_PREFIX):] if name.startswith(rig.DEFORM_PREFIX) else name
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
kit.clear_default_scene()
|
|
152
|
+
bpy.context.scene.render.fps = 30
|
|
153
|
+
addon_utils.enable("rigify", default_set=True, persistent=False)
|
|
154
|
+
bpy.ops.object.armature_basic_human_metarig_add()
|
|
155
|
+
metarig = bpy.context.view_layer.objects.active
|
|
156
|
+
# rigify_generate asserts that the metarig is the context's active object: select it in the view layer and
|
|
157
|
+
# call it WITHOUT temp_override (an override fails that assertion in Blender 5.3).
|
|
158
|
+
bpy.context.view_layer.update()
|
|
159
|
+
for obj in bpy.context.view_layer.objects:
|
|
160
|
+
obj.select_set(obj == metarig)
|
|
161
|
+
bpy.context.view_layer.objects.active = metarig
|
|
162
|
+
started = time.time()
|
|
163
|
+
outcome = bpy.ops.pose.rigify_generate()
|
|
164
|
+
seconds = time.time() - started
|
|
165
|
+
if "FINISHED" not in outcome:
|
|
166
|
+
raise RuntimeError(f"rigify_generate returned {outcome}")
|
|
167
|
+
control = metarig.data.rigify_target_rig
|
|
168
|
+
bones = control.data.bones
|
|
169
|
+
report = {"rigify": {"seconds": round(seconds, 2), "bones": len(bones), "deform": sum(bone.use_deform for bone in bones),
|
|
170
|
+
"deform_under_helpers": sum(1 for bone in bones
|
|
171
|
+
if bone.use_deform and bone.parent and not bone.parent.use_deform)}}
|
|
172
|
+
|
|
173
|
+
game = rig.game_skeleton(control, "GameRig", rename=strip_deform_prefix)
|
|
174
|
+
report["game"] = {"bones": len(game.data.bones), "roots": [bone.name for bone in game.data.bones if not bone.parent]}
|
|
175
|
+
|
|
176
|
+
wave = rig.new_action(control, "WaveControls")
|
|
177
|
+
for frame, angle in ((1, 0.0), (10, WAVE_DEGREES), (20, 0.0)):
|
|
178
|
+
rig.key_pose(control, wave, frame, {"upper_arm_fk.L": (0.0, 0.0, angle)})
|
|
179
|
+
bpy.context.scene.frame_set(10)
|
|
180
|
+
wanted = (control.matrix_world @ control.pose.bones["DEF-forearm.L"].head).copy()
|
|
181
|
+
baked = rig.bake_to_keys(game, "Wave", 1, 20)
|
|
182
|
+
rig.play(game, baked, 10)
|
|
183
|
+
report["game"]["bake_error_m"] = ((game.matrix_world @ game.pose.bones["forearm.L"].head) - wanted).length
|
|
184
|
+
rig.stash_action(game, baked)
|
|
185
|
+
rig.clear_active_action(game)
|
|
186
|
+
rig.reset_pose(game)
|
|
187
|
+
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "rigify.blend"))
|
|
188
|
+
glb_path = os.path.join(out_folder, "game_skeleton.glb")
|
|
189
|
+
rig.export_rig(glb_path, [game])
|
|
190
|
+
report["glb"] = rig.gltf_animation_summary(glb_path)
|
|
191
|
+
print(json.dumps(report))
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Measured: 222 bones, 35 deform, 11 of them under helpers; game skeleton 35 bones, one root; baked forearm
|
|
195
|
+
position error 1.3e-7 m; the GLB holds exactly one animation, `Wave`.
|
|
196
|
+
|
|
197
|
+
---
|
|
198
|
+
|
|
199
|
+
## 4. Automatic weights: failure modes and fixes
|
|
200
|
+
|
|
201
|
+
Bone heat (`parent_set` with ARMATURE_AUTO) is the right start for organic meshes, and fails in known ways:
|
|
202
|
+
|
|
203
|
+
| Situation | Plain bone heat (measured) | Cause | `bind_auto` fix (measured) |
|
|
204
|
+
|---|---|---|---|
|
|
205
|
+
| Character modelled at the wrong scale (1.75 cm) | **All 1,870 vertices unweighted**, no error | The heat solve depends on absolute size; it works from about 0.175 m up | Binds at 1.8 m and scales back: 0 unweighted |
|
|
206
|
+
| Floating parts (an eye, a loose card, a box) | 24 vertices unweighted | Heat does not cross between disconnected islands no bone sits in | Proxy: voxel-remesh a copy into one shell, heat-weight it, transfer the weights; leftovers filled from the nearest weighted vertex: 0 unweighted |
|
|
207
|
+
| Open holes | Fine (0 unweighted) | | |
|
|
208
|
+
| Any mesh | 5 influences on some vertices; sums 0.92-1.0 (median 0.988), 88 % of vertices not normalised | Heat keeps every bone it reaches | Clean -> limit 4 -> normalize (guide §4.4): max 4, all normalised |
|
|
209
|
+
| Intersecting or zero-area faces | "Bone Heat Weighting: failed to find solution" | Bad geometry | The proxy route, or clean the mesh |
|
|
210
|
+
|
|
211
|
+
Hard-surface parts (a helmet, a weapon, armour plates) want **rigid** weights: `rigid_bind(mesh, armature,
|
|
212
|
+
bone)` puts every vertex at 1.0 on one bone. Mixed meshes: bind organically, then overwrite the rigid parts'
|
|
213
|
+
groups by direct edits (guide §4.3).
|
|
214
|
+
|
|
215
|
+
### Recipe: where bone heat fails, and bind_auto on the same inputs
|
|
216
|
+
|
|
217
|
+
```python
|
|
218
|
+
"""Automatic weights: where bone heat fails and what fixes it. The same character is bound raw (bone heat,
|
|
219
|
+
ARMATURE_AUTO) and with bind_auto in three broken situations: built at 1/100 scale, with floating parts
|
|
220
|
+
that no bone's heat reaches (an eye, a loose card, a detached box), and with open holes. Prints the
|
|
221
|
+
unweighted vertex counts and influence limits for each. Saves weights.blend."""
|
|
222
|
+
import json
|
|
223
|
+
import os
|
|
224
|
+
import sys
|
|
225
|
+
|
|
226
|
+
import bmesh
|
|
227
|
+
import bpy
|
|
228
|
+
from mathutils import Matrix
|
|
229
|
+
|
|
230
|
+
import character_blockout as blockout
|
|
231
|
+
import construction_kit as kit
|
|
232
|
+
import retopology_tools as retopo
|
|
233
|
+
import rigging_tools as rig
|
|
234
|
+
|
|
235
|
+
out_folder = sys.argv[sys.argv.index("--") + 1]
|
|
236
|
+
HEIGHT = 1.75
|
|
237
|
+
TINY_HEIGHT = 0.0175 # a character modelled in the wrong units (1.75 cm)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def character(name, height):
|
|
241
|
+
"""Mesh and matching armature at a height."""
|
|
242
|
+
chart = blockout.humanoid_chart(height=height)
|
|
243
|
+
body = blockout.skin_blockout(name, chart)
|
|
244
|
+
retopo.voxel_remesh(body, voxel_size=height / 175.0)
|
|
245
|
+
retopo.quadriflow(body, target_triangles=5000, symmetry_axes=("X",))
|
|
246
|
+
chart = blockout.scale_chart(chart, blockout.fit_height(body, height))
|
|
247
|
+
return body, rig.build_armature(name + "_Rig", chart)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def add_floating_parts(body):
|
|
251
|
+
"""An eye sphere off the face, a loose card behind the head and a box behind the hips: separate islands."""
|
|
252
|
+
edit_mesh = bmesh.new()
|
|
253
|
+
edit_mesh.from_mesh(body.data)
|
|
254
|
+
bmesh.ops.create_uvsphere(edit_mesh, u_segments=12, v_segments=8, radius=0.025,
|
|
255
|
+
matrix=Matrix.Translation((0.035, -0.08, 1.62)))
|
|
256
|
+
bmesh.ops.create_grid(edit_mesh, x_segments=3, y_segments=3, size=0.06, matrix=Matrix.Translation((0.0, 0.25, 1.3)))
|
|
257
|
+
bmesh.ops.create_cube(edit_mesh, size=0.05, matrix=Matrix.Translation((0.0, 0.6, 0.9)))
|
|
258
|
+
edit_mesh.to_mesh(body.data)
|
|
259
|
+
edit_mesh.free()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def open_holes(body):
|
|
263
|
+
"""Deletes the faces of the back of the head: an open mesh, as scans and kitbashed parts often are."""
|
|
264
|
+
edit_mesh = bmesh.new()
|
|
265
|
+
edit_mesh.from_mesh(body.data)
|
|
266
|
+
back_of_head = [face for face in edit_mesh.faces
|
|
267
|
+
if face.calc_center_median().z > 1.6 and face.calc_center_median().y > 0.0]
|
|
268
|
+
bmesh.ops.delete(edit_mesh, geom=back_of_head, context="FACES")
|
|
269
|
+
edit_mesh.to_mesh(body.data)
|
|
270
|
+
edit_mesh.free()
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def bind_both_ways(name, height, damage=None):
|
|
274
|
+
"""Plain bone heat, then bind_auto, on fresh copies of the same damaged character."""
|
|
275
|
+
raw_body, raw_armature = character(f"{name}_heat", height)
|
|
276
|
+
auto_body, auto_armature = character(f"{name}_auto", height)
|
|
277
|
+
if damage:
|
|
278
|
+
damage(raw_body)
|
|
279
|
+
damage(auto_body)
|
|
280
|
+
rig.heat_weights(raw_body, raw_armature)
|
|
281
|
+
raw = rig.weight_report(raw_body, raw_armature)
|
|
282
|
+
bound = rig.bind_auto(auto_body, auto_armature)
|
|
283
|
+
return {"heat": {"vertices": raw["vertices"], "unweighted": raw["unweighted"],
|
|
284
|
+
"max_influences": raw["max_influences"], "not_normalised": raw["not_normalised"]},
|
|
285
|
+
"bind_auto": {key: bound[key] for key in ("method", "unweighted", "max_influences", "not_normalised",
|
|
286
|
+
"filled_from_nearest", "scaled_for_heat")}}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
kit.clear_default_scene()
|
|
290
|
+
report = {"tiny_scale": bind_both_ways("Tiny", TINY_HEIGHT),
|
|
291
|
+
"floating_parts": bind_both_ways("Floating", HEIGHT, add_floating_parts),
|
|
292
|
+
"open_holes": bind_both_ways("Holes", HEIGHT, open_holes)}
|
|
293
|
+
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "weights.blend"))
|
|
294
|
+
print(json.dumps(report))
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
---
|
|
298
|
+
|
|
299
|
+
## 5. Clips in bpy (Blender 5.x)
|
|
300
|
+
|
|
301
|
+
**Actions are slotted in Blender 5.x.** `Action.fcurves` is gone: an action holds layers, strips and slots, and
|
|
302
|
+
the F-curves live in a channelbag per slot (`bpy_extras.anim_utils.action_get_channelbag_for_slot`, wrapped by
|
|
303
|
+
`fcurves(action, owner)`). The owner picks an action **and** a slot (`animation_data.action_slot`).
|
|
304
|
+
|
|
305
|
+
**The slot trap (measured).** Every object slot "suits" every object. When several objects share one action (a
|
|
306
|
+
mechanical rig's Drive clip), giving each object the first suitable slot keys all of them into the first
|
|
307
|
+
object's curves: the exported Drive animation had one channel instead of six, with no error anywhere.
|
|
308
|
+
`use_action` gives each owner the slot named after it (or the one it used last) and creates one otherwise.
|
|
309
|
+
|
|
310
|
+
| Task | How | Note |
|
|
311
|
+
|---|---|---|
|
|
312
|
+
| Key a pose | `key_pose(armature, action, frame, {bone: (x, y, z) degrees}, {bone: location})` | Euler for authoring; the exporters sample quaternions |
|
|
313
|
+
| Key an object | `key_object(obj, action, frame, location=..., rotation_degrees=..., scale=...)` | Mechanical rigs |
|
|
314
|
+
| Interpolation | `set_interpolation(action, "LINEAR")` (wheels, conveyors), `"BEZIER"` (bodies), `"CONSTANT"` (snaps) | glTF stores STEP, LINEAR or CUBICSPLINE: Bezier and easing are sampled per frame on export |
|
|
315
|
+
| Loop | `make_cyclic(action)`: copies the first key to the last frame, adds a Cycles modifier, sets the frame range | It reports `max_seam_jump`; 0 means the loop is seamless. The last frame repeats the first: in an engine, play to the last frame minus one or let the loop wrap |
|
|
316
|
+
| One clip per engine animation | `stash_action(owner, action)`: an NLA track named after the clip, muted | glTF writes one animation per track name; FBX one take per action |
|
|
317
|
+
| Split a long take | `split_action(take, "Nod", 20, 40, start_at=1)` | Copies the keys in the range, moves them to start at frame 1, sets the manual frame range |
|
|
318
|
+
| Trim | `split_action` with the kept range | |
|
|
319
|
+
| Bake constraints / drivers | `bake_to_keys(armature, name, start, end)` | Visual keying, constraints removed (section 6) |
|
|
320
|
+
|
|
321
|
+
**Timing.** glTF stores seconds. BabylonJS's glTF loader converts at 60 frames per second (`targetFps`) and
|
|
322
|
+
starts the first animation group looped (`animationStartMode` FIRST); every glTF animation becomes one
|
|
323
|
+
`AnimationGroup`, named after the clip. A clip keyed from frame 1 at 30 fps starts at 0.0333 s in the file
|
|
324
|
+
(`export_anim_slide_to_zero` False keeps clips aligned to the scene; set it True if every clip must start at 0).
|
|
325
|
+
Unity clips get **Loop Time** and **Loop Pose**; for a walk, match rotation and Y in the loop-match indicators,
|
|
326
|
+
not XZ.
|
|
327
|
+
|
|
328
|
+
**Root motion.** Author loops in place unless the game reads motion from the clip. For root motion, move the
|
|
329
|
+
root bone (or Hips, for Humanoid) forward through the clip; in Unity choose per clip whether to **Bake Into
|
|
330
|
+
Pose** the root's rotation, Y and XZ (Based Upon: Body Orientation, Feet, Center of Mass). glTF has no root
|
|
331
|
+
motion concept: the engine code reads the root's translation from the animation group.
|
|
332
|
+
|
|
333
|
+
### Recipe: the rig test asset, two looping clips, GLB and FBX export, and the round trip
|
|
334
|
+
|
|
335
|
+
```python
|
|
336
|
+
"""Rig test asset and round trip. The 5k biped gets a 22-bone deform skeleton with Mixamo / Unity-Humanoid
|
|
337
|
+
names (built from the same chart as the mesh), automatic weights made engine-legal, and two looping clips
|
|
338
|
+
(Walk, 32 frames; Idle, 60 frames). It is exported to GLB (BabylonJS) and FBX (Unity), then each file is
|
|
339
|
+
re-imported into an empty scene and a hand vertex is compared at two frames of each clip."""
|
|
340
|
+
import json
|
|
341
|
+
import math
|
|
342
|
+
import os
|
|
343
|
+
import sys
|
|
344
|
+
|
|
345
|
+
import bpy
|
|
346
|
+
import numpy as np
|
|
347
|
+
|
|
348
|
+
import character_blockout as blockout
|
|
349
|
+
import construction_kit as kit
|
|
350
|
+
import retopology_tools as retopo
|
|
351
|
+
import rigging_tools as rig
|
|
352
|
+
|
|
353
|
+
out_folder = sys.argv[sys.argv.index("--") + 1]
|
|
354
|
+
HEIGHT = 1.75
|
|
355
|
+
FPS = 30
|
|
356
|
+
WALK_FRAMES = 32 # one full stride (two steps) in about 1.07 s: a typical walking cadence
|
|
357
|
+
IDLE_FRAMES = 60
|
|
358
|
+
WALK_KEYS = 4 # keys per cycle: contact, passing, contact, passing
|
|
359
|
+
CHECK_FRAMES = {"Walk": (5, 13), "Idle": (16, 31)}
|
|
360
|
+
ROUND_TRIP_TOLERANCE = 0.001 # metres
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def walk_pose(phase):
|
|
364
|
+
"""Bone rotations (degrees) and the hips' bob (metres) at a phase of the stride, 0..1."""
|
|
365
|
+
swing = math.sin(2.0 * math.pi * phase)
|
|
366
|
+
knee = 40.0 * max(0.0, math.sin(2.0 * math.pi * phase + 1.2))
|
|
367
|
+
other_knee = 40.0 * max(0.0, -math.sin(2.0 * math.pi * phase + 1.2))
|
|
368
|
+
rotations = {"LeftUpLeg": (-25.0 * swing, 0.0, 0.0), "RightUpLeg": (25.0 * swing, 0.0, 0.0),
|
|
369
|
+
"LeftLeg": (knee, 0.0, 0.0), "RightLeg": (other_knee, 0.0, 0.0),
|
|
370
|
+
"LeftArm": (20.0 * swing, 0.0, 0.0), "RightArm": (-20.0 * swing, 0.0, 0.0),
|
|
371
|
+
"Spine": (0.0, 4.0 * swing, 0.0)}
|
|
372
|
+
bob = {"Hips": (0.0, 0.02 * abs(math.cos(2.0 * math.pi * phase)), 0.0)}
|
|
373
|
+
return rotations, bob
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def build_character():
|
|
377
|
+
"""The character test asset: chart, Skin blockout, voxel remesh, QuadriFlow, UVs, one material."""
|
|
378
|
+
chart = blockout.humanoid_chart(height=HEIGHT, arm_angle_degrees=45.0)
|
|
379
|
+
body = blockout.skin_blockout("Body", chart)
|
|
380
|
+
retopo.voxel_remesh(body, voxel_size=HEIGHT / 175.0)
|
|
381
|
+
retopo.quadriflow(body, target_triangles=5000, symmetry_axes=("X",))
|
|
382
|
+
chart = blockout.scale_chart(chart, blockout.fit_height(body, HEIGHT))
|
|
383
|
+
kit.smart_unwrap(body)
|
|
384
|
+
body.data.materials.append(bpy.data.materials.new("Body_Skin"))
|
|
385
|
+
return body, chart
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def author_clips(armature):
|
|
389
|
+
"""Walk and Idle, cyclic, each stashed on its own NLA track: one glTF animation / FBX take each."""
|
|
390
|
+
walk = rig.new_action(armature, "Walk")
|
|
391
|
+
for key in range(WALK_KEYS + 1):
|
|
392
|
+
frame = 1 + key * WALK_FRAMES / WALK_KEYS
|
|
393
|
+
rotations, locations = walk_pose(key / WALK_KEYS)
|
|
394
|
+
rig.key_pose(armature, walk, frame, rotations, locations)
|
|
395
|
+
walk_loop = rig.make_cyclic(walk)
|
|
396
|
+
idle = rig.new_action(armature, "Idle")
|
|
397
|
+
for frame, breath in ((1, 0.0), (1 + IDLE_FRAMES // 2, 3.0), (1 + IDLE_FRAMES, 0.0)):
|
|
398
|
+
rig.key_pose(armature, idle, frame, {"Spine1": (breath, 0.0, 0.0), "Neck": (-breath, 0.0, 0.0),
|
|
399
|
+
"LeftArm": (0.0, 0.0, breath), "RightArm": (0.0, 0.0, -breath)})
|
|
400
|
+
idle_loop = rig.make_cyclic(idle)
|
|
401
|
+
for clip in (walk, idle):
|
|
402
|
+
rig.stash_action(armature, clip)
|
|
403
|
+
rig.clear_active_action(armature)
|
|
404
|
+
return {"Walk": walk_loop, "Idle": idle_loop}
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def sample_clips(armature, mesh, vertex):
|
|
408
|
+
"""World position of one vertex at the check frames of each clip, as the exporters play them."""
|
|
409
|
+
samples = {}
|
|
410
|
+
for clip, frames in CHECK_FRAMES.items():
|
|
411
|
+
for frame in frames:
|
|
412
|
+
rig.play(armature, rig.find_clip(clip), frame)
|
|
413
|
+
samples[f"{clip}@{frame}"] = rig.evaluated_positions(mesh)[vertex].tolist()
|
|
414
|
+
rig.clear_active_action(armature)
|
|
415
|
+
rig.reset_pose(armature)
|
|
416
|
+
return samples
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def round_trip(path, rest_point, samples):
|
|
420
|
+
"""Re-imports an exported file and measures bones, clips and the sampled vertex against the source."""
|
|
421
|
+
armature, mesh = rig.import_rig(path, FPS)
|
|
422
|
+
vertex = rig.nearest_vertex(mesh, armature, rest_point)
|
|
423
|
+
errors = {}
|
|
424
|
+
for key, expected in samples.items():
|
|
425
|
+
clip, frame = key.split("@")
|
|
426
|
+
rig.play(armature, rig.find_clip(clip), int(frame))
|
|
427
|
+
errors[key] = float(np.linalg.norm(rig.evaluated_positions(mesh)[vertex] - expected))
|
|
428
|
+
clips = sorted({name for name in CHECK_FRAMES if rig.find_clip(name) is not None})
|
|
429
|
+
return {"bones": len(armature.data.bones), "clips": clips, "worst_error_m": max(errors.values()),
|
|
430
|
+
"pass": max(errors.values()) <= ROUND_TRIP_TOLERANCE}
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
kit.clear_default_scene()
|
|
434
|
+
bpy.context.scene.render.fps = FPS
|
|
435
|
+
body, chart = build_character()
|
|
436
|
+
armature = rig.build_armature("Rig", chart)
|
|
437
|
+
report = {"humanoid": rig.humanoid_report(armature), "mirror": rig.mirror_report(armature),
|
|
438
|
+
"bind": rig.bind_auto(body, armature)}
|
|
439
|
+
# Pick the probe vertex in the rest pose, before any clip has posed the bones: the left fingertip, the
|
|
440
|
+
# longest lever in the skeleton, so any bone or weight error shows there first.
|
|
441
|
+
rest_positions = rig.evaluated_positions(body)
|
|
442
|
+
hand_vertex = int(np.argmax(rest_positions[:, 0]))
|
|
443
|
+
rest_point = rest_positions[hand_vertex].tolist()
|
|
444
|
+
report["loops"] = author_clips(armature)
|
|
445
|
+
samples = sample_clips(armature, body, hand_vertex)
|
|
446
|
+
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "character_rig.blend"))
|
|
447
|
+
glb_path = os.path.join(out_folder, "character.glb")
|
|
448
|
+
fbx_path = os.path.join(out_folder, "character.fbx")
|
|
449
|
+
rig.export_rig(glb_path, [armature, body])
|
|
450
|
+
rig.export_rig(fbx_path, [armature, body])
|
|
451
|
+
report["gltf"] = rig.gltf_animation_summary(glb_path)
|
|
452
|
+
report["source_bones"] = len(armature.data.bones)
|
|
453
|
+
report["round_trip_glb"] = round_trip(glb_path, rest_point, samples)
|
|
454
|
+
report["round_trip_fbx"] = round_trip(fbx_path, rest_point, samples)
|
|
455
|
+
print(json.dumps(report))
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
Measured: 22 bones, Humanoid map passes (arm angle 44.5 degrees), 0 unweighted, 4 influences, normalised;
|
|
459
|
+
Walk and Idle loop with a seam jump of 0. The GLB holds two animations (66 channels each: rotation, scale and
|
|
460
|
+
translation for every bone, because force sampling and reset-pose write them all) and one 22-joint skin.
|
|
461
|
+
Re-imported, both files give 22 bones, both clips, and the fingertip within 4e-7 m at all four frames.
|
|
462
|
+
|
|
463
|
+
---
|
|
464
|
+
|
|
465
|
+
## 6. IK and constraints baked to keys
|
|
466
|
+
|
|
467
|
+
Engines play keys, not Blender constraints. Author with constraints, then bake:
|
|
468
|
+
|
|
469
|
+
- **IK chain**: an IK constraint on the shin (chain length 2) with a foot target and a knee pole in front of the
|
|
470
|
+
knee. **Fit the pole angle, do not guess it**: it depends on the bone rolls. `fit_pole_angle` searches for
|
|
471
|
+
the angle that leaves the rest pose unchanged (90 degrees for this rig; the rest knee then moved 0.01 mm).
|
|
472
|
+
- **Bake**: `bake_to_keys` runs `nla.bake` with visual keying (constraint results become keys) and removes the
|
|
473
|
+
constraints. Without visual keying the constraint's effect is not keyed. Keep an authoring copy with the
|
|
474
|
+
constraints if the clip will be edited again.
|
|
475
|
+
- **Check**: play the baked clip and compare a bone's world position with the constrained version.
|
|
476
|
+
|
|
477
|
+
Other constraints bake the same way: Damped Track and Locked Track for eyes and turrets, Copy Rotation for
|
|
478
|
+
gears, Child Of for picking up props, drivers for anything procedural. BabylonJS has a 2-bone IK
|
|
479
|
+
(`BoneIKController`) and a look-at controller (`BoneLookController`) for runtime IK; anything else must be
|
|
480
|
+
keys.
|
|
481
|
+
|
|
482
|
+
---
|
|
483
|
+
|
|
484
|
+
## 7. Retargeting
|
|
485
|
+
|
|
486
|
+
`retarget_action(source, target, bone_map, frames, name, root_source, root_target)` copies a clip between
|
|
487
|
+
skeletons with different names, proportions and bone rolls: for every mapped bone and frame it takes the
|
|
488
|
+
source bone's world rotation change from its rest, applies the same change to the target bone's rest, and keys
|
|
489
|
+
it; the root's translation is scaled by the ratio of hip heights.
|
|
490
|
+
|
|
491
|
+
- **Rolls do not matter**: the change is measured in world space (the test retargets onto a rig with
|
|
492
|
+
`GLOBAL_POS_Z` rolls and other names: 0.0 degrees bone-direction error with matching rest poses).
|
|
493
|
+
- **Rest poses do**: the target keeps its rest-pose difference. A 45-degree A-pose clip on a 30-degree A-pose rig
|
|
494
|
+
stays 15 degrees off (measured exactly 15.0). Pose the target's rest to match the source first, or retarget
|
|
495
|
+
in Unity's Humanoid, which maps through muscle space.
|
|
496
|
+
- **Lossless Humanoid retargeting** (Unity) needs the same local bone positions, no animation on in-between
|
|
497
|
+
bones, and translation on the Hips only.
|
|
498
|
+
- **Proportions**: foot sliding comes from different leg lengths; scale the root translation (done) and add a
|
|
499
|
+
foot IK pass baked to keys (section 6) when contact matters.
|
|
500
|
+
|
|
501
|
+
### Recipe: IK baked to keys, a clip split from a take, and retargeting
|
|
502
|
+
|
|
503
|
+
```python
|
|
504
|
+
"""Constraints baked to keys, a clip split out of a long take, and retargeting. A two-bone IK leg (pole angle
|
|
505
|
+
fitted, not guessed) follows an animated foot target and is baked to plain rotation keys; a long take is
|
|
506
|
+
split into two clips; a clip is retargeted onto a smaller rig with other bone names and rolls, once with a
|
|
507
|
+
matching rest pose and once with a different one. Saves constraints.blend."""
|
|
508
|
+
import json
|
|
509
|
+
import os
|
|
510
|
+
import sys
|
|
511
|
+
|
|
512
|
+
import bpy
|
|
513
|
+
from mathutils import Vector
|
|
514
|
+
|
|
515
|
+
import character_blockout as blockout
|
|
516
|
+
import construction_kit as kit
|
|
517
|
+
import rigging_tools as rig
|
|
518
|
+
|
|
519
|
+
out_folder = sys.argv[sys.argv.index("--") + 1]
|
|
520
|
+
FOOT_LIFT = 0.25 # metres
|
|
521
|
+
STEP_FORWARD = 0.1
|
|
522
|
+
POLE_DISTANCE = 0.5 # the knee pole sits this far in front of the knee
|
|
523
|
+
GAME_RIG_NAMES = {"Hips": "pelvis", "Spine": "spine_01", "Spine1": "spine_02", "Spine2": "spine_03",
|
|
524
|
+
"Neck": "neck", "Head": "head"}
|
|
525
|
+
for side, suffix in (("Left", "l"), ("Right", "r")):
|
|
526
|
+
for source, target in (("Shoulder", "clavicle"), ("Arm", "upperarm"), ("ForeArm", "lowerarm"),
|
|
527
|
+
("Hand", "hand"), ("UpLeg", "thigh"), ("Leg", "calf"), ("Foot", "foot"),
|
|
528
|
+
("ToeBase", "ball")):
|
|
529
|
+
GAME_RIG_NAMES[side + source] = f"{target}_{suffix}"
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def world_head(armature, bone):
|
|
533
|
+
"""World position of a pose bone's head."""
|
|
534
|
+
return armature.matrix_world @ armature.pose.bones[bone].head
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def ik_leg(armature):
|
|
538
|
+
"""A two-bone IK on the left shin, with a foot target and a knee pole, pole angle fitted."""
|
|
539
|
+
rest_foot = armature.data.bones["LeftFoot"].head_local.copy()
|
|
540
|
+
target = rig.pivot_empty("FootTarget", rest_foot)
|
|
541
|
+
pole = rig.pivot_empty("KneePole", armature.data.bones["LeftLeg"].head_local + Vector((0, -POLE_DISTANCE, 0)))
|
|
542
|
+
constraint = armature.pose.bones["LeftLeg"].constraints.new("IK")
|
|
543
|
+
constraint.target, constraint.pole_target, constraint.chain_count = target, pole, 2
|
|
544
|
+
pole_angle = rig.fit_pole_angle(armature, "LeftLeg")
|
|
545
|
+
knee_drift = (world_head(armature, "LeftLeg") - armature.data.bones["LeftLeg"].head_local).length
|
|
546
|
+
return target, rest_foot, {"pole_angle_degrees": pole_angle, "rest_knee_drift_m": knee_drift}
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def renamed_chart(height, heads, arm_angle):
|
|
550
|
+
"""A humanoid chart with game-engine (UE-style) bone names instead of Mixamo names."""
|
|
551
|
+
chart = blockout.humanoid_chart(height=height, heads=heads, arm_angle_degrees=arm_angle)
|
|
552
|
+
for bone in chart:
|
|
553
|
+
bone.name = GAME_RIG_NAMES[bone.name]
|
|
554
|
+
bone.parent = GAME_RIG_NAMES.get(bone.parent) if bone.parent else None
|
|
555
|
+
return chart
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
kit.clear_default_scene()
|
|
559
|
+
scene = bpy.context.scene
|
|
560
|
+
armature = rig.build_armature("Rig", blockout.humanoid_chart(height=1.75, arm_angle_degrees=45.0))
|
|
561
|
+
report = {}
|
|
562
|
+
|
|
563
|
+
# 1. IK to keys.
|
|
564
|
+
target, rest_foot, report["ik"] = ik_leg(armature)
|
|
565
|
+
lift = bpy.data.actions.new("FootLiftTarget")
|
|
566
|
+
for frame, height in ((1, 0.0), (11, FOOT_LIFT), (21, 0.0)):
|
|
567
|
+
forward = Vector((0.0, -STEP_FORWARD if height else 0.0, height))
|
|
568
|
+
rig.key_object(target, lift, frame, location=tuple(rest_foot + forward))
|
|
569
|
+
wanted = {}
|
|
570
|
+
for frame in (6, 11):
|
|
571
|
+
scene.frame_set(frame)
|
|
572
|
+
wanted[frame] = target.matrix_world.translation.copy()
|
|
573
|
+
baked = rig.bake_to_keys(armature, "FootLift", 1, 21)
|
|
574
|
+
rig.clear_active_action(target)
|
|
575
|
+
report["ik"]["constraints_left"] = len(armature.pose.bones["LeftLeg"].constraints)
|
|
576
|
+
report["ik"]["foot_error_m"] = {}
|
|
577
|
+
for frame, position in wanted.items():
|
|
578
|
+
rig.play(armature, baked, frame)
|
|
579
|
+
report["ik"]["foot_error_m"][frame] = (world_head(armature, "LeftFoot") - position).length
|
|
580
|
+
|
|
581
|
+
# 2. Split a long take into clips.
|
|
582
|
+
take = rig.new_action(armature, "Take")
|
|
583
|
+
for frame, wave, nod in ((1, 0, 0), (10, 70, 0), (20, 0, 0), (30, 0, 25), (40, 0, 0)):
|
|
584
|
+
rig.key_pose(armature, take, frame, {"RightArm": (0, 0, -wave), "Head": (nod, 0, 0)})
|
|
585
|
+
wave_clip = rig.split_action(take, "Wave", 1, 20, start_at=1)
|
|
586
|
+
nod_clip = rig.split_action(take, "Nod", 20, 40, start_at=1)
|
|
587
|
+
rig.play(armature, take, 30)
|
|
588
|
+
nod_in_take = armature.pose.bones["Head"].rotation_euler.x
|
|
589
|
+
rig.play(armature, nod_clip, 11)
|
|
590
|
+
report["split"] = {"wave_range": list(wave_clip.frame_range), "nod_range": list(nod_clip.frame_range),
|
|
591
|
+
"nod_value_error": abs(armature.pose.bones["Head"].rotation_euler.x - nod_in_take)}
|
|
592
|
+
|
|
593
|
+
# 3. Retarget the take onto a smaller, differently named and rolled rig: matching rest, then a 30-degree A-pose.
|
|
594
|
+
report["retarget"] = {}
|
|
595
|
+
for label, arm_angle in (("same_rest", 45.0), ("other_rest", 30.0)):
|
|
596
|
+
small = rig.build_armature(f"Small_{label}", renamed_chart(1.1, 4.0, arm_angle), roll_type="GLOBAL_POS_Z")
|
|
597
|
+
small.location.x = 1.5
|
|
598
|
+
rig.play(armature, take, 1)
|
|
599
|
+
retargeted = rig.retarget_action(armature, small, GAME_RIG_NAMES, list(range(1, 41)), f"Take_{label}",
|
|
600
|
+
"Hips", "pelvis")
|
|
601
|
+
worst = 0.0
|
|
602
|
+
for frame in (10, 30):
|
|
603
|
+
rig.play(armature, take, frame)
|
|
604
|
+
rig.play(small, retargeted, frame)
|
|
605
|
+
worst = max(worst, rig.bone_direction_error(armature, small, GAME_RIG_NAMES))
|
|
606
|
+
report["retarget"][label] = {"worst_direction_error_degrees": round(worst, 3)}
|
|
607
|
+
rig.clear_active_action(armature)
|
|
608
|
+
rig.reset_pose(armature)
|
|
609
|
+
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "constraints.blend"))
|
|
610
|
+
print(json.dumps(report))
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
Measured: pole angle 90 degrees, rest knee drift 1e-5 m; baked foot within 18-47 µm of the IK target, no
|
|
614
|
+
constraints left; the split clip reads the take's values exactly; retarget error 0.0 degrees with matching rest
|
|
615
|
+
poses, 15.0 degrees with a 30-degree A-pose target.
|
|
616
|
+
|
|
617
|
+
---
|
|
618
|
+
|
|
619
|
+
## 8. Shape keys (morph targets, blendshapes)
|
|
620
|
+
|
|
621
|
+
- Every key stores a full copy of the positions (and normals) in the file: 50 face keys on a 10k-vertex head is
|
|
622
|
+
50 extra position and normal arrays. Keep keys on the head mesh, not the whole body.
|
|
623
|
+
- Build keys from offsets (`add_shape_key(mesh, name, offsets)`): a region, a falloff and a direction (the
|
|
624
|
+
vertex normal for puffs and breathing, a bone's axis for jaw corrections).
|
|
625
|
+
- Animate with `key_shape(mesh, action, frame, {name: value})` on an action owned by the shape-key block
|
|
626
|
+
(`mesh.data.shape_keys`), stashed like any clip. glTF writes it as a `weights` channel; FBX as a blendshape
|
|
627
|
+
channel.
|
|
628
|
+
- **BabylonJS**: WebGL2 stores targets in textures (memory is the limit); the WebGL1 attribute fallback allows
|
|
629
|
+
8 active targets. Every target must have the mesh's vertex count. CPU skinning cannot be combined with morph
|
|
630
|
+
targets.
|
|
631
|
+
- **Corrective shapes** (an elbow that keeps its volume) are keys driven by a bone angle; drivers do not export,
|
|
632
|
+
so bake the key's value per clip (`key_shape` per frame) or drive it in engine code.
|
|
633
|
+
|
|
634
|
+
### Recipe: shape keys on a skinned character, exported to GLB and FBX
|
|
635
|
+
|
|
636
|
+
```python
|
|
637
|
+
"""Shape keys (morph targets / blendshapes) on a skinned mesh. Two keys built from offsets along the vertex
|
|
638
|
+
normals inside a region - a cheek puff on the head and a breath on the chest - and a Breathe clip that
|
|
639
|
+
animates them. Exported to GLB (morph targets, a "weights" animation channel) and FBX (blendshapes), and
|
|
640
|
+
both files re-imported to check the keys survived. Saves shapes.blend."""
|
|
641
|
+
import json
|
|
642
|
+
import os
|
|
643
|
+
import sys
|
|
644
|
+
|
|
645
|
+
import bpy
|
|
646
|
+
import numpy as np
|
|
647
|
+
|
|
648
|
+
import character_blockout as blockout
|
|
649
|
+
import construction_kit as kit
|
|
650
|
+
import retopology_tools as retopo
|
|
651
|
+
import rigging_tools as rig
|
|
652
|
+
|
|
653
|
+
out_folder = sys.argv[sys.argv.index("--") + 1]
|
|
654
|
+
HEIGHT = 1.75
|
|
655
|
+
PUFF = 0.012 # metres along the normal at the centre of the region
|
|
656
|
+
BREATH = 0.015
|
|
657
|
+
FALLOFF_POWER = 2.0 # smooth falloff: (1 - distance / radius) ** power
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def region_offsets(mesh, centre, radius, depth):
|
|
661
|
+
"""Per-vertex offsets along the vertex normal, fading out smoothly to zero at `radius` from `centre`."""
|
|
662
|
+
positions = np.array([vertex.co[:] for vertex in mesh.data.vertices])
|
|
663
|
+
normals = np.array([vertex.normal[:] for vertex in mesh.data.vertices])
|
|
664
|
+
distance = np.linalg.norm(positions - np.asarray(centre), axis=1)
|
|
665
|
+
weight = np.clip(1.0 - distance / radius, 0.0, 1.0) ** FALLOFF_POWER
|
|
666
|
+
return normals * (weight * depth)[:, None]
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
kit.clear_default_scene()
|
|
670
|
+
bpy.context.scene.render.fps = 30
|
|
671
|
+
chart = blockout.humanoid_chart(height=HEIGHT)
|
|
672
|
+
body = blockout.skin_blockout("Body", chart)
|
|
673
|
+
retopo.voxel_remesh(body, voxel_size=HEIGHT / 175.0)
|
|
674
|
+
retopo.quadriflow(body, target_triangles=5000, symmetry_axes=("X",))
|
|
675
|
+
chart = blockout.scale_chart(chart, blockout.fit_height(body, HEIGHT))
|
|
676
|
+
kit.smart_unwrap(body)
|
|
677
|
+
body.data.materials.append(bpy.data.materials.new("Body_Skin"))
|
|
678
|
+
bones = {bone.name: bone for bone in chart}
|
|
679
|
+
armature = rig.build_armature("Rig", chart)
|
|
680
|
+
rig.bind_auto(body, armature)
|
|
681
|
+
|
|
682
|
+
head = bones["Head"]
|
|
683
|
+
cheek = (0.06, head.head[1] - 0.08, head.head[2] + 0.06)
|
|
684
|
+
chest = (0.0, bones["Spine1"].head[1] - 0.12, bones["Spine1"].tail[2])
|
|
685
|
+
rig.add_shape_key(body, "CheekPuff", region_offsets(body, cheek, 0.07, PUFF))
|
|
686
|
+
rig.add_shape_key(body, "ChestBreath", region_offsets(body, chest, 0.2, BREATH))
|
|
687
|
+
keys = body.data.shape_keys
|
|
688
|
+
breathe = rig.new_action(keys, "Breathe")
|
|
689
|
+
for frame, puff, breath in ((1, 0.0, 0.0), (20, 1.0, 1.0), (40, 0.0, 0.0)):
|
|
690
|
+
rig.key_shape(body, breathe, frame, {"CheekPuff": puff, "ChestBreath": breath})
|
|
691
|
+
rig.stash_action(keys, breathe)
|
|
692
|
+
rig.clear_active_action(keys)
|
|
693
|
+
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "shapes.blend"))
|
|
694
|
+
|
|
695
|
+
glb_path = os.path.join(out_folder, "shapes.glb")
|
|
696
|
+
fbx_path = os.path.join(out_folder, "shapes.fbx")
|
|
697
|
+
rig.export_rig(glb_path, [armature, body])
|
|
698
|
+
rig.export_rig(fbx_path, [armature, body])
|
|
699
|
+
report = {"gltf": rig.gltf_animation_summary(glb_path)}
|
|
700
|
+
for label, path in (("glb_keys", glb_path), ("fbx_keys", fbx_path)):
|
|
701
|
+
imported_armature, imported_mesh = rig.import_rig(path)
|
|
702
|
+
report[label] = [block.name for block in imported_mesh.data.shape_keys.key_blocks]
|
|
703
|
+
print(json.dumps(report))
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
Measured: the GLB carries both morph targets (`CheekPuff`, `ChestBreath`), a `Breathe` animation with one
|
|
707
|
+
`weights` channel, and the 22-joint skin; both files re-import with the three key blocks.
|
|
708
|
+
|
|
709
|
+
---
|
|
710
|
+
|
|
711
|
+
## 9. Mechanical rigs: wheels, steering, hinges, turrets
|
|
712
|
+
|
|
713
|
+
No bones: an object hierarchy where every moving part rotates about its own origin. Pivots and part setup are
|
|
714
|
+
in `vehicles.md` §6; what matters for animation:
|
|
715
|
+
|
|
716
|
+
| Part | Hierarchy | Animate | Rule |
|
|
717
|
+
|---|---|---|---|
|
|
718
|
+
| Wheel | Body > (steering pivot) > wheel, origin on the axle | Rotation X: `wheel_degrees_per_frame(speed, radius, fps)` per frame, LINEAR | Spin must match ground speed: speed / radius radians per second |
|
|
719
|
+
| Steering | Body > pivot empty at the hub > wheel | Rotation Z of the pivot | The wheel's spin and the steer are on different objects, so they never fight |
|
|
720
|
+
| Hinged door, hatch, lid | Body > door, origin on the hinge line (`set_origin`) | One rotation axis | Rotate the origin, not the geometry |
|
|
721
|
+
| Turret | Body > yaw empty > pitch empty > barrel | Yaw Z, pitch X | One axis per object: no gimbal surprises, engine code can drive each |
|
|
722
|
+
| Piston, suspension | Parent > slider | One translation axis | Keep travel in the object's local axis |
|
|
723
|
+
|
|
724
|
+
- **`parent_to` and `set_origin` update the view layer first.** In a script, `matrix_world` is stale after
|
|
725
|
+
setting `.location`; parenting with the stale (identity) matrix silently moves the child to the origin. The
|
|
726
|
+
first version of the recipe below exported every wheel at the origin with no error.
|
|
727
|
+
- **One action, a slot per object** for a clip that moves several objects (Drive moves four wheels and two
|
|
728
|
+
pivots): glTF writes one animation with six channels. See the slot trap in section 5.
|
|
729
|
+
- **Reset to rest before export.** Objects keep the last keyed transform when an action is unassigned: a door
|
|
730
|
+
left open by the last sample exports open as its rest.
|
|
731
|
+
- **Engines**: BabylonJS plays each animation group on its nodes only, and nodes it does not animate keep their
|
|
732
|
+
current state. Unity imports each FBX take as a clip on the hierarchy.
|
|
733
|
+
|
|
734
|
+
### Recipe: a wheeled, hinged mechanical rig through GLB and FBX
|
|
735
|
+
|
|
736
|
+
```python
|
|
737
|
+
"""Mechanical rig: no bones, an object hierarchy. A body with four wheels (front ones under steering pivots)
|
|
738
|
+
and a door hinged on its front edge. Clips: Drive (wheel spin matched to ground speed, a steering sweep)
|
|
739
|
+
and DoorOpen. Exported to GLB (one animation per clip) and to FBX (one file per clip, one scene take each),
|
|
740
|
+
re-imported, and the world positions of points on the moving parts compared. Saves vehicle_rig.blend."""
|
|
741
|
+
import json
|
|
742
|
+
import os
|
|
743
|
+
import sys
|
|
744
|
+
|
|
745
|
+
import bpy
|
|
746
|
+
from mathutils import Vector
|
|
747
|
+
|
|
748
|
+
import construction_kit as kit
|
|
749
|
+
import rigging_tools as rig
|
|
750
|
+
|
|
751
|
+
out_folder = sys.argv[sys.argv.index("--") + 1]
|
|
752
|
+
FPS = 30
|
|
753
|
+
SPEED = 5.0 # metres per second
|
|
754
|
+
WHEEL_RADIUS = 0.3
|
|
755
|
+
STEER_DEGREES = 25.0
|
|
756
|
+
DOOR_OPEN_DEGREES = 70.0
|
|
757
|
+
CLIP_FRAMES = {"Drive": (0, 30), "DoorOpen": (0, 20)}
|
|
758
|
+
CHECK_FRAMES = {"Drive": (7, 15), "DoorOpen": (10, 20)}
|
|
759
|
+
PROBE_POINTS = ((0.0, 0.0, 0.3), (0.0, 0.3, 0.0)) # local points off each origin: catch spin, not just travel
|
|
760
|
+
WHEEL_PROFILE = [(0.0, -0.08), (0.28, -0.08), (0.3, -0.05), (0.3, 0.05), (0.28, 0.08), (0.0, 0.08)]
|
|
761
|
+
WHEELS = {"WheelFL": (0.5, -0.6), "WheelFR": (-0.5, -0.6), "WheelRL": (0.5, 0.6), "WheelRR": (-0.5, 0.6)}
|
|
762
|
+
WATCHED = ("WheelFL", "WheelRR", "Door")
|
|
763
|
+
TOLERANCE = 0.001
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def build_vehicle():
|
|
767
|
+
"""Body, wheels with their origins on the axle, steering pivots, a door with its origin on the hinge."""
|
|
768
|
+
body_section = kit.translate_section(kit.rounded_section(0.9, 0.35, 0.08, 0.03), z=0.25)
|
|
769
|
+
body = kit.loft("Body", [(-0.9, body_section), (0.9, body_section)])
|
|
770
|
+
parts = {"Body": body}
|
|
771
|
+
for name, (x, y) in WHEELS.items():
|
|
772
|
+
wheel = kit.profile_spin(name, WHEEL_PROFILE, steps=24, axis="X")
|
|
773
|
+
wheel.location = (x, y, WHEEL_RADIUS)
|
|
774
|
+
parts[name] = wheel
|
|
775
|
+
door_section = kit.translate_section(kit.rounded_section(0.04, 0.3, 0.01, 0.01, segments=2), x=0.47, z=0.28)
|
|
776
|
+
door = kit.loft("Door", [(-0.3, door_section), (0.3, door_section)])
|
|
777
|
+
rig.set_origin(door, (0.47, -0.3, 0.43)) # the hinge line, at the door's front edge
|
|
778
|
+
parts["Door"] = door
|
|
779
|
+
for corner in ("FL", "FR"):
|
|
780
|
+
knuckle = rig.pivot_empty(f"Steer{corner}", parts[f"Wheel{corner}"].location, parent=body)
|
|
781
|
+
rig.parent_to(parts[f"Wheel{corner}"], knuckle)
|
|
782
|
+
parts[knuckle.name] = knuckle
|
|
783
|
+
for corner in ("RL", "RR"):
|
|
784
|
+
rig.parent_to(parts[f"Wheel{corner}"], body)
|
|
785
|
+
rig.parent_to(door, body)
|
|
786
|
+
return parts
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def author_clips(parts):
|
|
790
|
+
"""Drive: one action, a slot per moving object. DoorOpen: the door alone. Linear keys (constant spin)."""
|
|
791
|
+
drive = bpy.data.actions.new("Drive")
|
|
792
|
+
drive.use_fake_user = True
|
|
793
|
+
spin_per_frame = rig.wheel_degrees_per_frame(SPEED, WHEEL_RADIUS, FPS)
|
|
794
|
+
last = CLIP_FRAMES["Drive"][1]
|
|
795
|
+
for name in WHEELS:
|
|
796
|
+
for frame in CLIP_FRAMES["Drive"]:
|
|
797
|
+
rig.key_object(parts[name], drive, frame, rotation_degrees=(-spin_per_frame * frame, 0.0, 0.0))
|
|
798
|
+
for corner in ("FL", "FR"):
|
|
799
|
+
for frame, angle in ((0, 0.0), (last // 2, STEER_DEGREES), (last, 0.0)):
|
|
800
|
+
rig.key_object(parts[f"Steer{corner}"], drive, frame, rotation_degrees=(0.0, 0.0, angle))
|
|
801
|
+
rig.set_interpolation(drive, "LINEAR")
|
|
802
|
+
door_open = bpy.data.actions.new("DoorOpen")
|
|
803
|
+
door_open.use_fake_user = True
|
|
804
|
+
for frame, angle in zip(CLIP_FRAMES["DoorOpen"], (0.0, DOOR_OPEN_DEGREES)):
|
|
805
|
+
rig.key_object(parts["Door"], door_open, frame, rotation_degrees=(0.0, 0.0, angle))
|
|
806
|
+
return {"Drive": drive, "DoorOpen": door_open}
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def owners_of(action):
|
|
810
|
+
"""The scene objects an action has a slot for."""
|
|
811
|
+
return [bpy.data.objects[slot.name_display] for slot in action.slots if slot.name_display in bpy.data.objects]
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def world_points(names):
|
|
815
|
+
"""World positions of the probe points of each watched object."""
|
|
816
|
+
return {name: [list(bpy.data.objects[name].matrix_world @ Vector(point)) for point in PROBE_POINTS]
|
|
817
|
+
for name in names}
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def rest_all(parts):
|
|
821
|
+
"""Unassigns every clip and returns each object to its rest transform (objects keep their last keyed values)."""
|
|
822
|
+
for obj in parts.values():
|
|
823
|
+
rig.clear_active_action(obj)
|
|
824
|
+
for name in WHEELS:
|
|
825
|
+
parts[name].rotation_euler = (0.0, 0.0, 0.0)
|
|
826
|
+
for name in ("SteerFL", "SteerFR", "Door"):
|
|
827
|
+
parts[name].rotation_euler = (0.0, 0.0, 0.0)
|
|
828
|
+
bpy.context.view_layer.update()
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def sample(clips, parts):
|
|
832
|
+
"""World probe points at the check frames of each clip, as the exporters play them."""
|
|
833
|
+
samples = {}
|
|
834
|
+
for name, action in clips.items():
|
|
835
|
+
for frame in CHECK_FRAMES[name]:
|
|
836
|
+
rest_all(parts)
|
|
837
|
+
for owner in owners_of(action):
|
|
838
|
+
rig.play(owner, action, frame)
|
|
839
|
+
samples[f"{name}@{frame}"] = world_points(WATCHED)
|
|
840
|
+
rest_all(parts)
|
|
841
|
+
return samples
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
def compare(samples, single_take=None, rest=None):
|
|
845
|
+
"""
|
|
846
|
+
Worst distance between the re-imported probe points and the source, per clip key. A GLB holds every
|
|
847
|
+
clip (each is played by name); a single-take FBX holds one, already active, whose time 0 the importer
|
|
848
|
+
puts on frame 1.
|
|
849
|
+
"""
|
|
850
|
+
errors = {}
|
|
851
|
+
for key, expected in samples.items():
|
|
852
|
+
clip, frame = key.split("@")
|
|
853
|
+
if single_take is None:
|
|
854
|
+
rig.play_clip(clip, int(frame), rest)
|
|
855
|
+
elif clip == single_take:
|
|
856
|
+
bpy.context.scene.frame_set(int(frame) + 1)
|
|
857
|
+
else:
|
|
858
|
+
continue
|
|
859
|
+
actual = world_points(WATCHED)
|
|
860
|
+
errors[key] = max((Vector(actual[name][index]) - Vector(point)).length
|
|
861
|
+
for name, points in expected.items() for index, point in enumerate(points))
|
|
862
|
+
return errors
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
kit.clear_default_scene()
|
|
866
|
+
bpy.context.scene.render.fps = FPS
|
|
867
|
+
parts = build_vehicle()
|
|
868
|
+
clips = author_clips(parts)
|
|
869
|
+
samples = sample(clips, parts)
|
|
870
|
+
for name, action in clips.items():
|
|
871
|
+
for owner in owners_of(action):
|
|
872
|
+
rig.stash_action(owner, action)
|
|
873
|
+
rest_all(parts)
|
|
874
|
+
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "vehicle_rig.blend"))
|
|
875
|
+
objects = list(parts.values())
|
|
876
|
+
glb_path = os.path.join(out_folder, "vehicle.glb")
|
|
877
|
+
rig.export_rig(glb_path, objects)
|
|
878
|
+
report = {"gltf": rig.gltf_animation_summary(glb_path)}
|
|
879
|
+
|
|
880
|
+
# FBX: one scene take per file. The clip is made active on its owners and the scene range set to the clip;
|
|
881
|
+
# with NLA strips and all-actions off, the exporter writes exactly one take of the whole hierarchy.
|
|
882
|
+
fbx_paths = {}
|
|
883
|
+
for name, action in clips.items():
|
|
884
|
+
for owner in owners_of(action):
|
|
885
|
+
rig.use_action(owner, action)
|
|
886
|
+
bpy.context.scene.frame_start, bpy.context.scene.frame_end = CLIP_FRAMES[name]
|
|
887
|
+
fbx_paths[name] = os.path.join(out_folder, f"vehicle_{name}.fbx")
|
|
888
|
+
rig.export_rig(fbx_paths[name], objects, rig.UNITY_FBX_SCENE_TAKE)
|
|
889
|
+
rest_all(parts)
|
|
890
|
+
|
|
891
|
+
bpy.ops.wm.read_factory_settings(use_empty=True)
|
|
892
|
+
bpy.context.scene.render.fps = FPS
|
|
893
|
+
bpy.ops.import_scene.gltf(filepath=glb_path)
|
|
894
|
+
report["glb_errors_m"] = compare(samples, rest=rig.gltf_rest(glb_path))
|
|
895
|
+
report["fbx_errors_m"] = {}
|
|
896
|
+
for name, path in fbx_paths.items():
|
|
897
|
+
bpy.ops.wm.read_factory_settings(use_empty=True)
|
|
898
|
+
bpy.context.scene.render.fps = FPS
|
|
899
|
+
bpy.ops.import_scene.fbx(filepath=path)
|
|
900
|
+
report["fbx_errors_m"].update(compare(samples, single_take=name))
|
|
901
|
+
worst = max(list(report["glb_errors_m"].values()) + list(report["fbx_errors_m"].values()))
|
|
902
|
+
report["pass"] = worst <= TOLERANCE
|
|
903
|
+
print(json.dumps(report))
|
|
904
|
+
```
|
|
905
|
+
|
|
906
|
+
Measured: the GLB holds `Drive` (6 rotation channels) and `DoorOpen` (1); re-imported, probe points on two
|
|
907
|
+
wheels and the door are within 1e-7 m in both clips; the FBX scene takes within 2e-7 m (one frame later: FBX
|
|
908
|
+
takes start at time 0, which Blender's importer puts on frame 1).
|
|
909
|
+
|
|
910
|
+
---
|
|
911
|
+
|
|
912
|
+
## 10. Export
|
|
913
|
+
|
|
914
|
+
### glTF for BabylonJS (`GLTF_RIG_SETTINGS`)
|
|
915
|
+
|
|
916
|
+
| Setting | Value | Why |
|
|
917
|
+
|---|---|---|
|
|
918
|
+
| `export_animation_mode` | `NLA_TRACKS` | One animation per stashed track name, merged across objects. The default ACTIONS mode plus "Export all Armature Actions" gave a single-armature file every armature action in the .blend (a control rig's authoring clip shipped on the game skeleton) |
|
|
919
|
+
| `export_apply` | False | The Armature modifier is the skin: applying modifiers would bake a pose |
|
|
920
|
+
| `export_def_bones` | True | Deform bones only; control bones stay home |
|
|
921
|
+
| `export_leaf_bone` | False | No `_end` bones |
|
|
922
|
+
| `export_influence_nb` | 4 | `JOINTS_0` / `WEIGHTS_0`, BabylonJS's default; 8 adds `JOINTS_1` |
|
|
923
|
+
| `export_force_sampling`, `export_frame_step` 1 | On | Bezier, easing and constraints become per-frame keys |
|
|
924
|
+
| `export_reset_pose_bones` | True | Bones a clip does not key go back to rest between clips |
|
|
925
|
+
| `export_anim_slide_to_zero` | False | Clips keep their scene timing |
|
|
926
|
+
| `export_morph`, `export_morph_animation` | True | Shape keys and their clips |
|
|
927
|
+
| `export_tangents` | Pass True when the mesh has a normal map | BabylonJS otherwise builds a screen-space frame (`sculpting-and-retopology.md` section 6) |
|
|
928
|
+
|
|
929
|
+
glTF weights must sum to 1 (unorm: exactly; float: within about 2e-7 per weight): run `make_engine_legal` last.
|
|
930
|
+
|
|
931
|
+
### FBX for Unity (`UNITY_FBX_RIG_SETTINGS`)
|
|
932
|
+
|
|
933
|
+
Guide §8.2a's preset with `bake_space_transform=False` (rigs), plus: deform bones only, no leaf bones, normals
|
|
934
|
+
only, `bake_anim_use_all_actions` True (one take per action), Key All Bones, start and end keyed, no
|
|
935
|
+
simplification. Unity reads a take named `Rig|Walk`; Blender re-imports it as `Rig|Rig|Walk`
|
|
936
|
+
(`find_clip` compares the part after the last `|`).
|
|
937
|
+
|
|
938
|
+
For a **mechanical rig**, all-actions mode writes a take per object and action (14 for a 7-object rig with 2
|
|
939
|
+
clips) and NLA-strip mode a take per strip (6 identical `Drive` takes). Export one file per clip instead: make
|
|
940
|
+
the clip active on its objects, set the scene range to the clip and use `UNITY_FBX_SCENE_TAKE`, which writes
|
|
941
|
+
exactly one take.
|
|
942
|
+
|
|
943
|
+
The skill's `export` tool is for static assets: its FBX preset bakes the space transform even for armatures
|
|
944
|
+
(guide §8.2a says False for rigs) and its importer check drops leaf bones. Export rigs with `export_rig`.
|
|
945
|
+
|
|
946
|
+
**Unity import settings** for a Humanoid: Rig tab Animation Type Humanoid, Avatar Create From This Model,
|
|
947
|
+
Skin Weights Standard (4 bones); Animation tab per clip Loop Time / Loop Pose, root transform Bake Into Pose as
|
|
948
|
+
needed. Optimize Game Object strips the transform hierarchy (expose bones you attach props to).
|
|
949
|
+
|
|
950
|
+
---
|
|
951
|
+
|
|
952
|
+
## 11. The round trip
|
|
953
|
+
|
|
954
|
+
Re-import every export into an empty scene and compare: bone count, clip names, and an evaluated vertex (the
|
|
955
|
+
fingertip: the longest lever) at two frames of each clip. Traps the check itself must avoid (each one gave a
|
|
956
|
+
false failure while this file was written):
|
|
957
|
+
|
|
958
|
+
- **Pick the probe vertex in the rest pose**, before any clip has posed the bones: `clear_active_action` leaves
|
|
959
|
+
every bone at the last evaluated pose (a 2.8 cm false error from a hip bob the idle clip never keys).
|
|
960
|
+
- **Reset the pose between clips** (`play` does): bones a clip does not key keep the previous clip's values,
|
|
961
|
+
but the exporters reset them (glTF `export_reset_pose_bones`, FBX Key All Bones).
|
|
962
|
+
- **Vertex order and count change** (glTF splits vertices at UV seams): find the vertex by its rest position
|
|
963
|
+
(`nearest_vertex`).
|
|
964
|
+
- **Blender's glTF importer evaluates the first animation at the current frame** right after import, overwriting
|
|
965
|
+
object transforms; for object rigs, return every node to its file rest (`gltf_rest`) before playing a clip
|
|
966
|
+
(`play_clip(name, frame, rest)`).
|
|
967
|
+
- **FBX takes start at time 0**; the importer puts that on frame 1.
|
|
968
|
+
|
|
969
|
+
---
|
|
970
|
+
|
|
971
|
+
## 12. Budgets (web and BabylonJS first)
|
|
972
|
+
|
|
973
|
+
| Item | Web / mobile | Desktop / console | Notes |
|
|
974
|
+
|---|---|---|---|
|
|
975
|
+
| Deform bones, character | 20-35 (no fingers); under 30 (Unity, mobile) | 50-75 with fingers; 15-60 (Unity, desktop); 100-200+ AAA hero | One industry guide: 30-50 background / mobile, 60-100 standard, 100-200+ hero |
|
|
976
|
+
| Twist bones | 0 (Humanoid ignores them) | 1-2 forearm, 1 upper arm, 1 thigh per side | UE5's Manny: 16 of its 89 |
|
|
977
|
+
| Influences per vertex | 4 | 4; 8 maximum in BabylonJS | Unity Standard: 4; Custom 1-32 |
|
|
978
|
+
| Clip sample rate | 30 fps keys, sampled per frame on export | 30-60 | BabylonJS plays at 60: 30 fps keys interpolate |
|
|
979
|
+
| Clips per character | As needed; each is an AnimationGroup | | File size grows with bones x frames x 3 channels (66 channels for 22 bones) |
|
|
980
|
+
| Morph targets | A few per mesh | 50+ for a face | WebGL1: 8 active |
|
|
981
|
+
| Mechanical rig | One object per moving axis | | Each moving object is a node and, with its own material, a draw |
|
|
982
|
+
|
|
983
|
+
---
|
|
984
|
+
|
|
985
|
+
## 13. Pitfalls
|
|
986
|
+
|
|
987
|
+
| Pitfall | What happens | Fix |
|
|
988
|
+
|---|---|---|
|
|
989
|
+
| Shared multi-object action, first suitable slot | All objects keyed into one slot; one channel exported | `use_action` (owner's own slot) |
|
|
990
|
+
| Parenting right after setting `.location` | The child jumps to the origin | `parent_to` updates the view layer first |
|
|
991
|
+
| Selection-based export right after linking objects | An empty file (a 4 KB FBX), "export finished" | Update the view layer before selecting (`export_rig` does) |
|
|
992
|
+
| glTF ACTIONS mode with one armature | Every armature action in the .blend ships | `NLA_TRACKS` (the preset) |
|
|
993
|
+
| Bone heat at the wrong scale | Every vertex unweighted, no error | `bind_auto` (scales to 1.8 m) |
|
|
994
|
+
| Floating parts | Unweighted vertices | `bind_auto` proxy + fill, or `rigid_bind` |
|
|
995
|
+
| Raw heat weights | 5 influences, sums 0.92-1.0 | `make_engine_legal` |
|
|
996
|
+
| Rigify generate under `temp_override` | Assertion error | Active object in the view layer, no override |
|
|
997
|
+
| Rigify deform bones exported directly | 11 roots, broken chains | `game_skeleton` |
|
|
998
|
+
| Rolls by `GLOBAL_POS_Z` | 88-degree leg roll; X no longer "bend" | `GLOBAL_NEG_Y` |
|
|
999
|
+
| IK pole angle guessed | The knee twists at rest | `fit_pole_angle` |
|
|
1000
|
+
| Constraints not baked | Engine plays no motion | `bake_to_keys` (visual keying) |
|
|
1001
|
+
| Retarget between different rest poses | Constant offset (15 degrees for 45 vs 30) | Match rest poses first |
|
|
1002
|
+
| FBX all-actions on a mechanical rig | A take per object and action | One file per clip, `UNITY_FBX_SCENE_TAKE` |
|
|
1003
|
+
| FBX `bake_space_transform=True` on a rig | Root rotations disagree in Unity (guide §8.2a) | False (`UNITY_FBX_RIG_SETTINGS`) |
|
|
1004
|
+
| Re-importing FBX with `ignore_leaf_bones=True` | Real end bones dropped | Leave it False for checks |
|
|
1005
|
+
| Probe vertex picked after authoring | False round-trip errors | Pick in the rest pose |
|
|
1006
|
+
| Objects left at the last keyed transform | Wrong rest in the export | Reset before export |
|
|
1007
|
+
|
|
1008
|
+
---
|
|
1009
|
+
|
|
1010
|
+
## 14. Verification checklist
|
|
1011
|
+
|
|
1012
|
+
```bash
|
|
1013
|
+
node <skill>/scripts/bt-blender.mjs qa-check --model character_rig.blend --profile web # weights: none unweighted, <= 4 influences
|
|
1014
|
+
node <skill>/scripts/bt-blender.mjs assembly-check --model character_rig.blend
|
|
1015
|
+
node <skill>/scripts/bt-blender.mjs review-render --model character_rig.blend --out review --pixel-height 180
|
|
1016
|
+
node <skill>/scripts/bt-blender.mjs measure-stations --spec refs/spec.json --model character_rig.blend
|
|
1017
|
+
node <skill>/scripts/bt-blender.mjs validate-gltf build/character.glb
|
|
1018
|
+
```
|
|
1019
|
+
|
|
1020
|
+
- [ ] `humanoid_report` passes (for Unity Humanoid) and `mirror_report` shows no errors.
|
|
1021
|
+
- [ ] `weight_report`: 0 unweighted, max 4 influences, 0 not normalised.
|
|
1022
|
+
- [ ] Every joint posed to its range looks right in a review render.
|
|
1023
|
+
- [ ] Every clip loops with `max_seam_jump` 0 (or is a one-shot by design) and is stashed on its own track.
|
|
1024
|
+
- [ ] No constraints or drivers left on what ships; IK baked and checked against its target.
|
|
1025
|
+
- [ ] `gltf_animation_summary` lists exactly the intended clips, the skin's joint count and the morph targets.
|
|
1026
|
+
- [ ] The GLB and the FBX re-import with the same bone count and clips, and a probe vertex matches within 1 mm
|
|
1027
|
+
at two frames of every clip.
|
|
1028
|
+
- [ ] Mechanical rigs: origins on pivots, every object reset to rest, probe points match after re-import.
|
|
1029
|
+
|
|
1030
|
+
---
|
|
1031
|
+
|
|
1032
|
+
## Sources
|
|
1033
|
+
|
|
1034
|
+
- Unity Manual: Using humanoid characters; Configuring the Avatar; Rig tab; Animation tab; Muscle definitions;
|
|
1035
|
+
HumanDescription; HumanBodyBones; Preparing a character from scratch (5.3); Looping animation clips —
|
|
1036
|
+
https://docs.unity.com/en-us/engine/current/manual/assets-and-media/asset-types/models/creating-dccassets/using-humanoid-chars ,
|
|
1037
|
+
https://docs.unity.com/en-us/engine/current/manual/assets-and-media/asset-types/models/importing/configuringthe-avatar ,
|
|
1038
|
+
https://docs.unity.com/en-us/engine/current/manual/assets-and-media/asset-types/models/importing/fbximporter-rig ,
|
|
1039
|
+
https://docs.unity.com/en-us/engine/current/manual/assets-and-media/asset-types/models/importing/class-animation-clip ,
|
|
1040
|
+
https://docs.unity.com/en-us/engine/current/manual/animation-section/animation-mecanim/avatar-creationand-setup/muscle-definitions ,
|
|
1041
|
+
https://docs.unity.com/en-us/engine/current/script-reference/unityengine/humandescription ,
|
|
1042
|
+
https://docs.unity.com/en-us/engine/current/script-reference/unityengine/humanbodybones ,
|
|
1043
|
+
https://docs.unity3d.com/530/Documentation/Manual/Preparingacharacterfromscratch.html ,
|
|
1044
|
+
https://docs.unity3d.com/2019.4/Documentation/Manual/LoopingAnimationClips.html
|
|
1045
|
+
- Unity blog, Mecanim humanoids — https://unity.com/blog/engine-platform/mecanim-humanoids
|
|
1046
|
+
- Mixamo bone names — https://gist.github.com/frnsys/e1eaea896bd01e6388b54e1ebf9782c7 ,
|
|
1047
|
+
https://cosindra.ai/guides/mixamo-bone-names
|
|
1048
|
+
- Khronos, glTF 2.0 specification (skins, animations, weights) — https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html
|
|
1049
|
+
- Blender glTF importer/exporter documentation and add-on options —
|
|
1050
|
+
https://docs.blender.org/manual/en/latest/addons/import_export/scene_gltf2.html ,
|
|
1051
|
+
https://github.com/KhronosGroup/glTF-Blender-IO/blob/main/addons/io_scene_gltf2/__init__.py
|
|
1052
|
+
- Blender FBX exporter options — https://github.com/blender/blender/blob/main/scripts/addons_core/io_scene_fbx/__init__.py
|
|
1053
|
+
- Blender Manual: Bone roll; Parenting with automatic weights; Armature modifier; IK solver; Actions; F-curve
|
|
1054
|
+
modifiers and properties; Rigify basics and rig features —
|
|
1055
|
+
https://docs.blender.org/manual/en/latest/animation/armatures/bones/editing/bone_roll.html ,
|
|
1056
|
+
https://docs.blender.org/manual/en/latest/animation/armatures/skinning/parenting.html ,
|
|
1057
|
+
https://docs.blender.org/manual/en/latest/modeling/modifiers/deform/armature.html ,
|
|
1058
|
+
https://docs.blender.org/manual/en/latest/animation/constraints/tracking/ik_solver.html ,
|
|
1059
|
+
https://docs.blender.org/manual/en/latest/animation/actions.html ,
|
|
1060
|
+
https://docs.blender.org/manual/en/latest/editors/graph_editor/fcurves/modifiers.html ,
|
|
1061
|
+
https://docs.blender.org/manual/en/latest/addons/rigify/basics.html ,
|
|
1062
|
+
https://docs.blender.org/manual/en/latest/addons/rigify/rig_features.html
|
|
1063
|
+
- Blender source, Bake Action (`nla.bake`) — https://github.com/blender/blender/blob/main/scripts/startup/bl_operators/anim.py
|
|
1064
|
+
- Rigify deform-bone parenting — https://devtalk.blender.org/t/rigify-parent-bones-of-some-def-bones/14745 ,
|
|
1065
|
+
https://projects.blender.org/blender/blender-addons/pulls/104644
|
|
1066
|
+
- Bone heat weighting failures — https://www.blendernation.com/2023/05/19/solutions-to-bone-heat-weighting-error/
|
|
1067
|
+
- BabylonJS: Bones and skeletons; glTF loader; Animation groups; Morph targets —
|
|
1068
|
+
https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons ,
|
|
1069
|
+
https://github.com/BabylonJS/Babylon.js/blob/master/packages/dev/loaders/src/glTF/2.0/glTFLoader.pure.ts ,
|
|
1070
|
+
https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations ,
|
|
1071
|
+
https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets
|
|
1072
|
+
- Epic Games, Root motion — https://dev.epicgames.com/documentation/en-us/unreal-engine/root-motion-in-unreal-engine
|
|
1073
|
+
- Valve Developer Community, Skeletons and rigging — https://developer.valvesoftware.com/wiki/Skeletons_and_Rigging
|
|
1074
|
+
- Mocap Online, skeleton hierarchy guide (bone budgets) — https://mocaponline.com/blogs/mocap-news/skeleton-hierarchy-animation-guide
|
|
1075
|
+
- GDC Vault: T. Wang, Joint-Based Skin Deformation in God of War Ragnarok; B. Hanke, Rigging a Resident Evil —
|
|
1076
|
+
https://gdcvault.com/play/1029203/Joint-Based-Skin-Deformation-in ,
|
|
1077
|
+
https://gdcvault.com/play/1015533/Rigging-a-Resident-Evil-Inside
|
|
1078
|
+
- Technique credits: the heat-weights-then-voxel-proxy fallback and the deform-only game skeleton follow
|
|
1079
|
+
EL4CTEO/blender-skills (bind_mesh.py, rigify_build.py; MIT; ideas only, no code copied) —
|
|
1080
|
+
https://github.com/EL4CTEO/blender-skills
|