@babylonjs-toolkit/agent 1.2.16 → 1.2.21

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.
Files changed (70) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +448 -0
  4. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  5. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  6. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  7. package/skills/bt-blender/references/environments.md +478 -0
  8. package/skills/bt-blender/references/game-engine-export.md +284 -0
  9. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  10. package/skills/bt-blender/references/hard-surface.md +724 -0
  11. package/skills/bt-blender/references/procedural-generation.md +358 -0
  12. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  13. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  14. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  15. package/skills/bt-blender/references/vehicles.md +637 -0
  16. package/skills/bt-blender/scripts/blender/__pycache__/construction_kit.cpython-313.pyc +0 -0
  17. package/skills/bt-blender/scripts/blender/__pycache__/geometry_nodes_builders.cpython-313.pyc +0 -0
  18. package/skills/bt-blender/scripts/blender/__pycache__/image_measure.cpython-313.pyc +0 -0
  19. package/skills/bt-blender/scripts/blender/__pycache__/reference_traces.cpython-313.pyc +0 -0
  20. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  21. package/skills/bt-blender/scripts/blender/blueprint.py +293 -0
  22. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  23. package/skills/bt-blender/scripts/blender/construction_kit.py +1770 -0
  24. package/skills/bt-blender/scripts/blender/coverage_check.py +221 -0
  25. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  26. package/skills/bt-blender/scripts/blender/evidence_sheet.py +243 -0
  27. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  28. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  29. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  30. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  31. package/skills/bt-blender/scripts/blender/image_measure.py +917 -0
  32. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  33. package/skills/bt-blender/scripts/blender/measure_stations.py +496 -0
  34. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  35. package/skills/bt-blender/scripts/blender/overlay_sheet.py +238 -0
  36. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  37. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  38. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  39. package/skills/bt-blender/scripts/blender/reference_traces.py +344 -0
  40. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  41. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  42. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  43. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  44. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  45. package/skills/bt-blender/scripts/blender/trace.py +283 -0
  46. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  47. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  48. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  49. package/skills/bt-blender/scripts/blender/world_gate.py +231 -0
  50. package/skills/bt-blender/scripts/bt-blender.mjs +333 -0
  51. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  52. package/skills/bt-execute/SKILL.md +2 -1
  53. package/skills/bt-gauntlet/SKILL.md +30 -20
  54. package/skills/bt-gauntlet/references/critic-rubrics.md +106 -7
  55. package/skills/bt-gauntlet/references/loop-templates.md +23 -3
  56. package/skills/bt-gauntlet/references/spec-composition.md +20 -1
  57. package/skills/bt-gauntlet/references/target-images.md +27 -0
  58. package/skills/bt-gauntlet/references/unity-pipeline.md +41 -4
  59. package/skills/bt-gauntlet/references/workspace.md +90 -6
  60. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  61. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  62. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  63. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  64. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  65. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  66. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  67. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  68. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  69. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  70. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,462 @@
1
+ """
2
+ bt-blender character blockout: a proportioned joint chart for a biped (or any joint graph you write for a
3
+ creature), turned into a fused base mesh with the Skin modifier. The same chart later places the rig's
4
+ bones (rigging_tools.build_armature), so the mesh and the skeleton agree by construction - the
5
+ headless equivalent of building a ZSphere / Skin-modifier armature first and the body around it.
6
+
7
+ import character_blockout as blockout
8
+ chart = blockout.humanoid_chart(height=1.75, heads=7.5, arm_angle_degrees=45.0)
9
+ body = blockout.skin_blockout("Body", chart) # fused, closed, mostly quads
10
+ blockout.fit_height(body, 1.75) # measured world height = brief height
11
+
12
+ Proportions follow the figure-drawing canon (realistic 7.5 heads tall, half height at the greater
13
+ trochanter, knee about two heads above the floor). Below the chin everything is measured in body units
14
+ (the floor-to-chin length / 6.5), so a stylised 3-head character gets a big head on a human-proportioned
15
+ body instead of a body inflated to the head size.
16
+
17
+ Lengths are metres; Blender is Z up and the character faces -Y (glTF / BabylonJS forward). Bone names are
18
+ the Mixamo set without its `mixamorig:` prefix, which Unity's Humanoid auto-mapping recognises.
19
+ """
20
+ import math
21
+ from dataclasses import dataclass
22
+
23
+ import bmesh
24
+ import bpy
25
+ import mathutils
26
+ import numpy as np
27
+
28
+ import construction_kit as kit
29
+
30
+ # The realistic canon: a figure 7.5 heads tall, so the floor-to-chin length is 6.5 head units.
31
+ REALISTIC_HEADS = 7.5
32
+ BODY_UNITS_BELOW_CHIN = REALISTIC_HEADS - 1.0
33
+
34
+ # Heights above the floor, in body units (the realistic canon, where a body unit equals a head unit).
35
+ SHOULDER_LINE_HEIGHT = 6.15 # top of the clavicles, about a third of a head under the chin
36
+ CHEST_HEIGHT = 5.5 # nipple line, two heads from the top
37
+ WAIST_HEIGHT = 4.5 # navel, three heads from the top
38
+ PELVIS_HEIGHT = 3.95 # pelvis centre, the Hips bone head
39
+ HIP_JOINT_HEIGHT = 3.7 # femoral head, just above the greater trochanter at half height
40
+ KNEE_HEIGHT = 1.95 # knee pivot, about two heads above the floor
41
+ ANKLE_HEIGHT = 0.3 # ankle pivot
42
+ BALL_HEIGHT = 0.08 # ball of the foot (toe joint)
43
+
44
+ # Horizontal offsets in body units.
45
+ CLAVICLE_START_X = 0.12 # sternal end of the clavicle
46
+ SHOULDER_JOINT_X = 0.85 # glenohumeral pivot
47
+ SHOULDER_DROP = 0.12 # the shoulder pivot sits a little under the clavicle line
48
+ HIP_JOINT_X = 0.48
49
+ ANKLE_X = 0.5
50
+ BALL_FORWARD = 0.72 # ankle to ball of the foot, along -Y
51
+ TOE_TIP_FORWARD = 1.02 # ankle to toe tip
52
+
53
+ # Limb segment lengths in body units.
54
+ UPPER_ARM_LENGTH = 1.45
55
+ FOREARM_LENGTH = 1.25
56
+ HAND_LENGTH = 0.78 # about the face's height
57
+
58
+ # Natural joint bends in the rest pose (degrees), so IK and auto weights know which way each hinge folds.
59
+ ELBOW_REST_BEND = 8.0
60
+ KNEE_REST_BEND = 4.0
61
+
62
+ # Skin radii (half-widths, metres per body unit) along the local X / Y of each joint.
63
+ TORSO_RADII = {"Hips": (0.78, 0.55), "Spine": (0.66, 0.48), "Spine1": (0.74, 0.52), "Spine2": (0.82, 0.55)}
64
+ LIMB_RADII = {"Neck": 0.3, "Shoulder": 0.36, "Arm": 0.33, "ForeArm": 0.26, "Hand": 0.2, "HandEnd": 0.16,
65
+ "UpLeg": 0.47, "Leg": 0.34, "Foot": 0.24, "ToeBase": 0.2, "ToeEnd": 0.16}
66
+
67
+ # Head volume, in head units: the skull's half-width and half-depth.
68
+ HEAD_RADII = (0.36, 0.42)
69
+ NECK_TOP_BELOW_CHIN = 0.05 # the neck joint sits just above the jaw line, in head units
70
+
71
+ # Branch smoothing relaxes joints with three or more edges; 0.5 rounds the crotch and armpits without the
72
+ # shrink a full 1.0 gives.
73
+ DEFAULT_BRANCH_SMOOTHING = 0.5
74
+
75
+ # Subdivision levels on top of the skin; 2 gives a smooth, fused sculpt-ready base.
76
+ DEFAULT_SKIN_SUBDIVISIONS = 2
77
+ FOLD_DEGENERATE_DISTANCE = 1e-6 # metres; dissolves the zero-length edges left by collapsing a fold
78
+
79
+
80
+ @dataclass
81
+ class ChartBone:
82
+ """One bone of a joint chart: a named segment from head to tail, with its skin radius at each end."""
83
+ name: str
84
+ head: tuple
85
+ tail: tuple
86
+ parent: str = None
87
+ connected: bool = False
88
+ head_radius: tuple = (0.05, 0.05)
89
+ tail_radius: tuple = (0.05, 0.05)
90
+ deform: bool = True
91
+
92
+
93
+ def _point(x: float, y: float, z: float) -> tuple:
94
+ """A rounded (x, y, z) tuple, so mirrored joints compare equal."""
95
+ return (round(x, 6), round(y, 6), round(z, 6))
96
+
97
+
98
+ def _along(start: tuple, direction: tuple, length: float) -> tuple:
99
+ """The point `length` metres from `start` along a (not necessarily unit) direction."""
100
+ vector = np.array(direction, dtype=np.float64)
101
+ vector /= np.linalg.norm(vector)
102
+ return _point(*(np.array(start) + vector * length))
103
+
104
+
105
+ def _bent_chain(start: tuple, direction: tuple, lengths: list, bend_degrees: float, bend_axis: tuple) -> list:
106
+ """
107
+ Points of a two-segment limb with a small rest bend at the middle joint: the middle joint is pushed
108
+ off the straight line along `bend_axis` so the hinge has a defined folding direction.
109
+
110
+ :returns: [start, middle, end] points.
111
+ """
112
+ straight_middle = np.array(_along(start, direction, lengths[0]))
113
+ offset = math.sin(math.radians(bend_degrees)) * lengths[0]
114
+ middle = straight_middle + np.array(bend_axis, dtype=np.float64) * offset
115
+ end = np.array(_along(tuple(middle), direction, lengths[1]))
116
+ return [start, _point(*middle), _point(*end)]
117
+
118
+
119
+ def humanoid_chart(height: float = 1.75, heads: float = REALISTIC_HEADS, arm_angle_degrees: float = 45.0,
120
+ spine_bones: int = 3, radius_scale: float = 1.0) -> list:
121
+ """
122
+ The joint chart of a biped standing on Z = 0, facing -Y: bone segments with Mixamo / Unity-Humanoid
123
+ compatible names and skin radii. Use it for the blockout (skin_blockout) and for the rig
124
+ (rigging_tools.build_armature).
125
+
126
+ :param height: Total height in metres, floor to the top of the skull.
127
+ :param heads: How many heads tall: 7.5 realistic, 8 idealised, 8.5 heroic, 5-6 stylised, 2-4 chibi.
128
+ :param arm_angle_degrees: Arms below horizontal in the rest pose: 0 is a T-pose, 30-45 an A-pose (deforms
129
+ the shoulders better).
130
+ :param spine_bones: 2 (Spine, Spine1) or 3 (adds Spine2, Unity's UpperChest).
131
+ :param radius_scale: Multiplies every skin radius (0.8 slim, 1.2 heavy).
132
+ :returns: List of ChartBone, parents before children.
133
+ :raises ValueError: for a non-positive height, fewer than 2 heads or an unsupported spine count.
134
+ """
135
+ if height <= 0 or heads < 2 or spine_bones not in (2, 3):
136
+ raise ValueError("humanoid_chart needs height > 0, heads >= 2 and spine_bones of 2 or 3")
137
+ head_unit = height / heads
138
+ chin = height - head_unit
139
+ body_unit = chin / BODY_UNITS_BELOW_CHIN
140
+ bones = []
141
+
142
+ def radius(value: float) -> tuple:
143
+ return (value * body_unit * radius_scale, value * body_unit * radius_scale)
144
+
145
+ def torso(name: str) -> tuple:
146
+ x_radius, y_radius = TORSO_RADII[name]
147
+ return (x_radius * body_unit * radius_scale, y_radius * body_unit * radius_scale)
148
+
149
+ neck_base = _point(0.0, 0.0, SHOULDER_LINE_HEIGHT * body_unit)
150
+ neck_top = _point(0.0, 0.0, chin + NECK_TOP_BELOW_CHIN * head_unit)
151
+ # The spine is Hips (pelvis) -> Spine (waist) -> Spine1 (chest) [-> Spine2 (upper chest)] -> neck base.
152
+ spine_names = ["Hips", "Spine", "Spine1", "Spine2"][:spine_bones + 1]
153
+ joint_heights = [PELVIS_HEIGHT, WAIST_HEIGHT, CHEST_HEIGHT][:spine_bones] + [SHOULDER_LINE_HEIGHT]
154
+ if spine_bones == 2:
155
+ joint_heights = [PELVIS_HEIGHT, WAIST_HEIGHT, (CHEST_HEIGHT + SHOULDER_LINE_HEIGHT) / 2.0]
156
+ joints = [_point(0.0, 0.0, value * body_unit) for value in joint_heights] + [neck_base]
157
+ for index, name in enumerate(spine_names):
158
+ next_name = spine_names[index + 1] if index + 1 < len(spine_names) else name
159
+ bones.append(ChartBone(name, joints[index], joints[index + 1], spine_names[index - 1] if index else None,
160
+ index > 0, torso(name), torso(next_name)))
161
+ chest_name = spine_names[-1]
162
+ head_radius = (HEAD_RADII[0] * head_unit * radius_scale, HEAD_RADII[1] * head_unit * radius_scale)
163
+ bones.append(ChartBone("Neck", neck_base, neck_top, chest_name, True, radius(LIMB_RADII["Neck"]),
164
+ radius(LIMB_RADII["Neck"])))
165
+ bones.append(ChartBone("Head", neck_top, _point(0.0, 0.0, height), "Neck", True, head_radius, head_radius))
166
+
167
+ angle = math.radians(arm_angle_degrees)
168
+ for side, sign in (("Left", 1.0), ("Right", -1.0)):
169
+ clavicle_start = _point(sign * CLAVICLE_START_X * body_unit, 0.0, SHOULDER_LINE_HEIGHT * body_unit)
170
+ shoulder_joint = _point(sign * SHOULDER_JOINT_X * body_unit, 0.0,
171
+ (SHOULDER_LINE_HEIGHT - SHOULDER_DROP) * body_unit)
172
+ arm_direction = (sign * math.cos(angle), 0.0, -math.sin(angle))
173
+ # The elbow bends backward (+Y) at rest: the forearm folds forward from there.
174
+ arm = _bent_chain(shoulder_joint, arm_direction, [UPPER_ARM_LENGTH * body_unit, FOREARM_LENGTH * body_unit],
175
+ ELBOW_REST_BEND, (0.0, 1.0, 0.0))
176
+ hand_tip = _along(arm[2], arm_direction, HAND_LENGTH * body_unit)
177
+ bones.append(ChartBone(f"{side}Shoulder", clavicle_start, shoulder_joint, chest_name, False,
178
+ radius(LIMB_RADII["Shoulder"]), radius(LIMB_RADII["Arm"])))
179
+ bones.append(ChartBone(f"{side}Arm", arm[0], arm[1], f"{side}Shoulder", True,
180
+ radius(LIMB_RADII["Arm"]), radius(LIMB_RADII["ForeArm"])))
181
+ bones.append(ChartBone(f"{side}ForeArm", arm[1], arm[2], f"{side}Arm", True,
182
+ radius(LIMB_RADII["ForeArm"]), radius(LIMB_RADII["Hand"])))
183
+ bones.append(ChartBone(f"{side}Hand", arm[2], hand_tip, f"{side}ForeArm", True,
184
+ radius(LIMB_RADII["Hand"]), radius(LIMB_RADII["HandEnd"])))
185
+
186
+ hip_joint = _point(sign * HIP_JOINT_X * body_unit, 0.0, HIP_JOINT_HEIGHT * body_unit)
187
+ ankle = _point(sign * ANKLE_X * body_unit, 0.0, ANKLE_HEIGHT * body_unit)
188
+ thigh_length = HIP_JOINT_HEIGHT * body_unit - KNEE_HEIGHT * body_unit
189
+ shin_length = KNEE_HEIGHT * body_unit - ANKLE_HEIGHT * body_unit
190
+ leg_direction = np.array(ankle) - np.array(hip_joint)
191
+ # The knee bends forward (-Y) at rest: the shin folds backward from there.
192
+ leg = _bent_chain(hip_joint, tuple(leg_direction), [thigh_length, shin_length], KNEE_REST_BEND, (0.0, -1.0, 0.0))
193
+ ball = _point(sign * ANKLE_X * body_unit, -BALL_FORWARD * body_unit, BALL_HEIGHT * body_unit)
194
+ toe_tip = _point(sign * ANKLE_X * body_unit, -TOE_TIP_FORWARD * body_unit, BALL_HEIGHT * body_unit)
195
+ bones.append(ChartBone(f"{side}UpLeg", leg[0], leg[1], "Hips", False,
196
+ radius(LIMB_RADII["UpLeg"]), radius(LIMB_RADII["Leg"])))
197
+ bones.append(ChartBone(f"{side}Leg", leg[1], leg[2], f"{side}UpLeg", True,
198
+ radius(LIMB_RADII["Leg"]), radius(LIMB_RADII["Foot"])))
199
+ bones.append(ChartBone(f"{side}Foot", leg[2], ball, f"{side}Leg", True,
200
+ radius(LIMB_RADII["Foot"]), radius(LIMB_RADII["ToeBase"])))
201
+ bones.append(ChartBone(f"{side}ToeBase", ball, toe_tip, f"{side}Foot", True,
202
+ radius(LIMB_RADII["ToeBase"]), radius(LIMB_RADII["ToeEnd"])))
203
+ return bones
204
+
205
+
206
+ def chart_graph(chart: list) -> tuple:
207
+ """
208
+ Turns a joint chart into a skin graph: unique joint points, the edges between them, and a radius per
209
+ point. A bone whose head is not its parent's tail (a clavicle on the chest, a thigh on the pelvis) is
210
+ joined to the nearest point of its parent, so the graph stays one connected piece.
211
+
212
+ :param chart: List of ChartBone.
213
+ :returns: (points [(x, y, z)], edges [(i, j)], radii [(rx, ry)]).
214
+ """
215
+ points, radii, index_of = [], [], {}
216
+
217
+ def add(point: tuple, radius: tuple) -> int:
218
+ if point not in index_of:
219
+ index_of[point] = len(points)
220
+ points.append(point)
221
+ radii.append(radius)
222
+ return index_of[point]
223
+
224
+ by_name = {bone.name: bone for bone in chart}
225
+ edges = set()
226
+ for bone in chart:
227
+ head_index = add(bone.head, bone.head_radius)
228
+ tail_index = add(bone.tail, bone.tail_radius)
229
+ edges.add((head_index, tail_index))
230
+ parent = by_name.get(bone.parent)
231
+ if parent is None or bone.head in (parent.head, parent.tail):
232
+ continue
233
+ anchors = [parent.head, parent.tail]
234
+ nearest = min(anchors, key=lambda anchor: np.linalg.norm(np.subtract(anchor, bone.head)))
235
+ edges.add((index_of[nearest], head_index))
236
+ return points, sorted(edges), radii
237
+
238
+
239
+ def skin_blockout(name: str, chart: list, subdivisions: int = DEFAULT_SKIN_SUBDIVISIONS,
240
+ branch_smoothing: float = DEFAULT_BRANCH_SMOOTHING, apply: bool = True,
241
+ root_bone: str = None) -> bpy.types.Object:
242
+ """
243
+ Builds a fused base mesh around a joint chart with the Skin modifier (one closed, mostly-quad surface
244
+ with no intersections), smoothed by Subdivision. This is the headless replacement for a ZSphere or
245
+ blob blockout: sizes come from the chart, not from brush strokes.
246
+
247
+ :param name: Object and mesh name.
248
+ :param chart: List of ChartBone (humanoid_chart, or your own creature chart).
249
+ :param subdivisions: Subdivision levels over the skin (0 keeps the raw skin cage).
250
+ :param branch_smoothing: Skin branch smoothing, 0..1.
251
+ :param apply: Bake the modifiers into the mesh (needed before remeshing or sculpt-style detail).
252
+ :param root_bone: Bone whose head is the skin root (default: the first bone, the pelvis on a biped).
253
+ :returns: The new object.
254
+ """
255
+ points, edges, radii = chart_graph(chart)
256
+ mesh = bpy.data.meshes.new(name)
257
+ mesh.from_pydata(points, edges, [])
258
+ obj = bpy.data.objects.new(name, mesh)
259
+ bpy.context.scene.collection.objects.link(obj)
260
+ skin = obj.modifiers.new("Skin", "SKIN")
261
+ skin.branch_smoothing = branch_smoothing
262
+ skin.use_smooth_shade = True
263
+ root_point = next((bone.head for bone in chart if bone.name == root_bone), chart[0].head)
264
+ skin_data = mesh.skin_vertices[0].data
265
+ for point, radius, vertex in zip(points, radii, skin_data):
266
+ vertex.radius = radius
267
+ vertex.use_root = point == root_point
268
+ if not apply:
269
+ if subdivisions:
270
+ _add_subdivision(obj, subdivisions)
271
+ return obj
272
+ _apply_stack(obj)
273
+ _clean_skin(obj)
274
+ if subdivisions:
275
+ _add_subdivision(obj, subdivisions)
276
+ _apply_stack(obj)
277
+ return obj
278
+
279
+
280
+ def _add_subdivision(obj: bpy.types.Object, levels: int) -> None:
281
+ """Adds a Catmull-Clark Subdivision modifier with the same viewport and render levels."""
282
+ smoothing = obj.modifiers.new("Subdivision", "SUBSURF")
283
+ smoothing.levels = levels
284
+ smoothing.render_levels = levels
285
+
286
+
287
+ def _fold_clusters(edit_mesh: bmesh.types.BMesh) -> list:
288
+ """Groups the vertices of edges whose two faces are wound against each other into connected clusters."""
289
+ folded = {edge for edge in edit_mesh.edges if len(edge.link_faces) == 2 and not edge.is_contiguous}
290
+ unvisited = {vertex for edge in folded for vertex in edge.verts}
291
+ clusters = []
292
+ while unvisited:
293
+ stack, cluster = [unvisited.pop()], []
294
+ while stack:
295
+ vertex = stack.pop()
296
+ cluster.append(vertex)
297
+ for edge in vertex.link_edges:
298
+ if edge in folded:
299
+ for neighbour in edge.verts:
300
+ if neighbour in unvisited:
301
+ unvisited.remove(neighbour)
302
+ stack.append(neighbour)
303
+ clusters.append(cluster)
304
+ return clusters
305
+
306
+
307
+ def _clean_skin(obj: bpy.types.Object) -> dict:
308
+ """
309
+ Repairs the raw Skin cage before it is subdivided. The Skin modifier (Blender 5.3.0) leaves loose
310
+ vertices where several branches meet and folds a few tiny faces (4-170 mm2 on a 1.75 m biped) against
311
+ their neighbours at a 4-way junction such as a neck base with both clavicles. Each fold is collapsed to
312
+ its centre, degenerate geometry is dissolved and the winding made consistent. Measured over six
313
+ proportion sets this leaves 0-1 non-manifold edges on the cage (0-4 after two subdivisions), and the
314
+ Skin hull itself is up to 4 cm asymmetric on a 1.75 m body: treat the result as a blockout and
315
+ voxel-remesh it (retopology_tools.voxel_remesh) before anything needs a closed, symmetric shell.
316
+ Cleaning after subdividing does not work: the fold spreads over 16-32 faces and welding opens holes.
317
+ """
318
+ edit_mesh = bmesh.new()
319
+ edit_mesh.from_mesh(obj.data)
320
+ loose = [vertex for vertex in edit_mesh.verts if not vertex.link_edges]
321
+ bmesh.ops.delete(edit_mesh, geom=loose, context="VERTS")
322
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
323
+ clusters = _fold_clusters(edit_mesh)
324
+ for cluster in clusters:
325
+ centre = sum((vertex.co for vertex in cluster), mathutils.Vector()) / len(cluster)
326
+ bmesh.ops.pointmerge(edit_mesh, verts=cluster, merge_co=centre)
327
+ bmesh.ops.dissolve_degenerate(edit_mesh, edges=edit_mesh.edges[:], dist=FOLD_DEGENERATE_DISTANCE)
328
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
329
+ edit_mesh.to_mesh(obj.data)
330
+ edit_mesh.free()
331
+ return {"loose_removed": len(loose), "folds_collapsed": len(clusters)}
332
+
333
+
334
+ def metaball_blockout(name: str, chart: list, resolution: float = 0.02, threshold: float = 0.6,
335
+ samples_per_bone: int = 4) -> bpy.types.Object:
336
+ """
337
+ Builds a soft, blobby base from a chart with metaball ellipsoids along every bone, converted to a mesh.
338
+ Masses melt into each other (good for creatures, bellies, cartoon forms); the Skin modifier keeps
339
+ limbs crisper. Convert, then voxel-remesh before any other work: the converted surface is triangles.
340
+
341
+ :param name: Object name of the resulting mesh.
342
+ :param chart: List of ChartBone.
343
+ :param resolution: Polygonisation size in metres (smaller is denser).
344
+ :param threshold: Field level of the surface; lower grows every blob and merges more.
345
+ :param samples_per_bone: Ball elements placed along each bone.
346
+ :returns: The converted mesh object.
347
+ """
348
+ meta = bpy.data.metaballs.new(name + "Meta")
349
+ meta.resolution = resolution
350
+ meta.render_resolution = resolution
351
+ meta.threshold = threshold
352
+ for bone in chart:
353
+ for step in range(samples_per_bone + 1):
354
+ blend = step / samples_per_bone
355
+ element = meta.elements.new(type="BALL")
356
+ element.co = tuple(np.array(bone.head) * (1.0 - blend) + np.array(bone.tail) * blend)
357
+ radius = (1.0 - blend) * bone.head_radius[0] + blend * bone.tail_radius[0]
358
+ # A metaball's visible radius is smaller than its element radius at the default threshold.
359
+ element.radius = radius * 1.6
360
+ element.stiffness = 2.0
361
+ meta_object = bpy.data.objects.new(name + "Meta", meta)
362
+ bpy.context.scene.collection.objects.link(meta_object)
363
+ depsgraph = bpy.context.evaluated_depsgraph_get()
364
+ mesh = bpy.data.meshes.new_from_object(meta_object.evaluated_get(depsgraph), depsgraph=depsgraph)
365
+ bpy.data.objects.remove(meta_object)
366
+ bpy.data.metaballs.remove(meta)
367
+ mesh.name = name
368
+ obj = bpy.data.objects.new(name, mesh)
369
+ bpy.context.scene.collection.objects.link(obj)
370
+ return obj
371
+
372
+
373
+ def _apply_stack(obj: bpy.types.Object) -> None:
374
+ """Bakes the modifier stack into the mesh, keeping the mesh name (the kit's apply, which also realises any
375
+ Geometry Nodes instances instead of dropping them)."""
376
+ kit.apply_modifiers(obj)
377
+
378
+
379
+ def world_extent(obj: bpy.types.Object) -> np.ndarray:
380
+ """(min (3,), max (3,)) of the evaluated world-space vertices, as a (2, 3) array."""
381
+ depsgraph = bpy.context.evaluated_depsgraph_get()
382
+ evaluated = obj.evaluated_get(depsgraph)
383
+ mesh = evaluated.to_mesh()
384
+ try:
385
+ coordinates = np.empty(len(mesh.vertices) * 3)
386
+ mesh.vertices.foreach_get("co", coordinates)
387
+ matrix = np.array(evaluated.matrix_world)
388
+ finally:
389
+ evaluated.to_mesh_clear()
390
+ world = coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
391
+ return np.array([world.min(axis=0), world.max(axis=0)])
392
+
393
+
394
+ def fit_height(obj: bpy.types.Object, height: float, ground: bool = True) -> float:
395
+ """
396
+ Scales a mesh about its floor centre so its measured world height is exactly `height` (skin radii
397
+ and subdivision shrink make the raw blockout a few percent off), applies the scale into the mesh,
398
+ and optionally rests it on Z = 0.
399
+
400
+ :param obj: Mesh object (no parent).
401
+ :param height: Target height in metres.
402
+ :param ground: Move the lowest vertex to Z = 0.
403
+ :returns: The scale factor applied.
404
+ """
405
+ low, high = world_extent(obj)
406
+ factor = height / float(high[2] - low[2])
407
+ pivot = np.array([(low[0] + high[0]) / 2.0, (low[1] + high[1]) / 2.0, low[2]])
408
+ coordinates = np.empty(len(obj.data.vertices) * 3)
409
+ obj.data.vertices.foreach_get("co", coordinates)
410
+ local = coordinates.reshape(-1, 3)
411
+ world = local @ np.array(obj.matrix_world)[:3, :3].T + np.array(obj.matrix_world)[:3, 3]
412
+ world = pivot + (world - pivot) * factor
413
+ if ground:
414
+ world[:, 2] -= pivot[2]
415
+ obj.matrix_world = obj.matrix_world.Identity(4)
416
+ obj.data.vertices.foreach_set("co", world.ravel())
417
+ obj.data.update()
418
+ return factor
419
+
420
+
421
+ def scale_chart(chart: list, factor: float, ground_offset: float = 0.0) -> list:
422
+ """
423
+ Scales a chart about the floor origin (to follow fit_height), keeping radii in proportion.
424
+
425
+ :param chart: List of ChartBone.
426
+ :param factor: Uniform scale.
427
+ :param ground_offset: Metres added to every Z after scaling.
428
+ :returns: A new list of ChartBone.
429
+ """
430
+ def scaled(point):
431
+ return _point(point[0] * factor, point[1] * factor, point[2] * factor + ground_offset)
432
+
433
+ return [ChartBone(bone.name, scaled(bone.head), scaled(bone.tail), bone.parent, bone.connected,
434
+ tuple(value * factor for value in bone.head_radius),
435
+ tuple(value * factor for value in bone.tail_radius), bone.deform)
436
+ for bone in chart]
437
+
438
+
439
+ def symmetry_error(obj: bpy.types.Object, axis: int = 0) -> float:
440
+ """
441
+ Largest distance (metres) from any vertex's mirror image to the nearest vertex: 0 on a perfectly
442
+ symmetric mesh. Check it before relying on mirror tools (weights, shape keys, Symmetrize).
443
+
444
+ :param obj: Mesh object.
445
+ :param axis: 0 = X, 1 = Y, 2 = Z.
446
+ :returns: The worst mirror mismatch in metres.
447
+ """
448
+ from mathutils.kdtree import KDTree
449
+
450
+ edit_mesh = bmesh.new()
451
+ edit_mesh.from_mesh(obj.data)
452
+ tree = KDTree(len(edit_mesh.verts))
453
+ for vertex in edit_mesh.verts:
454
+ tree.insert(vertex.co, vertex.index)
455
+ tree.balance()
456
+ worst = 0.0
457
+ for vertex in edit_mesh.verts:
458
+ mirrored = vertex.co.copy()
459
+ mirrored[axis] = -mirrored[axis]
460
+ worst = max(worst, tree.find(mirrored)[2])
461
+ edit_mesh.free()
462
+ return worst