@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,555 @@
1
+ """
2
+ bt-blender UV layout: seams, unwraps, packing in pixels, texel density, lightmap UVs, and the measurements
3
+ that prove a layout is shippable, all headless on Blender 5.3.
4
+
5
+ import uv_layout
6
+
7
+ uv_layout.mark_seams_from_sharp(obj) # every hard edge is a seam
8
+ uv_layout.unwrap(obj, texture_size=2048, margin_pixels=16) # angle-based, from the marked seams
9
+ uv_layout.set_texel_density(obj, 512, 2048) # 512 px per metre on every island
10
+ uv_layout.pack(obj, 2048, margin_pixels=16, scale=False) # arrange without rescaling
11
+ uv_layout.add_lightmap_uv(obj, lightmap_size=512, margin_pixels=4)
12
+ print(uv_layout.texel_density(obj, 2048), uv_layout.overlap(obj, "UVLightmap", 1024))
13
+
14
+ What is in it:
15
+ - seams and unwraps: mark_seams_from_sharp, unwrap (ANGLE_BASED / CONFORMAL / MINIMUM_STRETCH from seams),
16
+ box_project (world-scale planar UVs for tiling and trim materials);
17
+ - packing: pack (margins given in pixels at the texture size), add_lightmap_uv (a second, non-overlapping
18
+ map for baked lighting; Unity reads it as Mesh.uv2, glTF as TEXCOORD_1; the one lightmap helper of the
19
+ skill: environment_kit.lightmap_uv calls it);
20
+ - measuring: islands, texel_density (px per metre per island), set_texel_density, overlap (texels claimed by
21
+ two islands), self_overlap (texels claimed by two triangles, folds inside an island included),
22
+ island_gap_pixels, bounds.
23
+
24
+ The UV operators act on the active UV map in Edit Mode; every function here sets that up itself (full context
25
+ override) and restores the active map. Measurements read mesh data only.
26
+ """
27
+ import math
28
+
29
+ import bmesh
30
+ import bpy
31
+ import numpy as np
32
+
33
+ # Default unwrap angle for seams from hard edges: edges sharper than this between faces become seams.
34
+ DEFAULT_SEAM_ANGLE_DEGREES = 60.0
35
+
36
+ # Two corners share a UV island when their UVs differ by less than this (UV units).
37
+ UV_WELD_TOLERANCE = 1e-6
38
+
39
+ # Faces with less world area than this (square metres) are left out of density statistics.
40
+ MINIMUM_WORLD_AREA = 1e-12
41
+
42
+ # Largest search, in pixels, for the closest gap between two islands.
43
+ MAXIMUM_GAP_SEARCH_PIXELS = 64
44
+
45
+ # How add_lightmap_uv makes its islands: "copy" the first map's islands, "smart" project them from the faces,
46
+ # or "auto" (copy, and fall back to smart when the copied layout overlaps itself, as a tiling UV0 does).
47
+ LIGHTMAP_METHODS = ("auto", "copy", "smart")
48
+
49
+ # Smart UV Project angle for lightmap islands (degrees): splits a box at its corners, keeps a flat run whole.
50
+ LIGHTMAP_SMART_ANGLE_DEGREES = 66.0
51
+
52
+ # Packing shape of the quick probe pack "auto" gives the copied layout before it measures the folds, so a
53
+ # layout it then throws away never gets the slow pack: on an 8-face L piece (Blender 5.3.0) CONCAVE took
54
+ # 17.9 s on the folded copy and 6.3 s on the smart islands; AABB took under 0.01 s on either.
55
+ LIGHTMAP_PROBE_SHAPE = "AABB"
56
+
57
+
58
+ # --- context helpers ------------------------------------------------------------------------------------------
59
+
60
+ class _EditUV:
61
+ """Context manager: the object alone in Edit Mode, all faces selected, with `uv_name` the active UV map."""
62
+
63
+ def __init__(self, obj: bpy.types.Object, uv_name=None):
64
+ """:param obj: Mesh object. :param uv_name: UV map to act on (created if missing), or None for the active one."""
65
+ self.obj = obj
66
+ self.uv_name = uv_name
67
+ self.previous_active = None
68
+ self.override = None
69
+
70
+ def __enter__(self):
71
+ """Selects the object, activates the UV map and enters Edit Mode with every face selected."""
72
+ layers = self.obj.data.uv_layers
73
+ self.previous_active = layers.active.name if layers.active else None
74
+ if self.uv_name:
75
+ layer = layers.get(self.uv_name) or layers.new(name=self.uv_name)
76
+ layers.active = layer
77
+ elif not layers:
78
+ layers.new(name="UVMap")
79
+ view_layer = bpy.context.view_layer
80
+ for candidate in view_layer.objects:
81
+ candidate.select_set(candidate == self.obj)
82
+ view_layer.objects.active = self.obj
83
+ self.override = bpy.context.temp_override(object=self.obj, active_object=self.obj,
84
+ selected_objects=[self.obj], selected_editable_objects=[self.obj])
85
+ self.override.__enter__()
86
+ _check(bpy.ops.object.mode_set(mode="EDIT"), "mode_set EDIT")
87
+ _check(bpy.ops.mesh.select_all(action="SELECT"), "select_all")
88
+ _check(bpy.ops.uv.select_all(action="SELECT"), "uv select_all")
89
+ return self
90
+
91
+ def __exit__(self, *exception):
92
+ """Returns to Object Mode and restores the previously active UV map."""
93
+ bpy.ops.object.mode_set(mode="OBJECT")
94
+ self.override.__exit__(*exception)
95
+ if self.previous_active and self.previous_active in self.obj.data.uv_layers:
96
+ self.obj.data.uv_layers.active = self.obj.data.uv_layers[self.previous_active]
97
+ return False
98
+
99
+
100
+ def _check(outcome: set, what: str) -> None:
101
+ """Raises when an operator did not finish (operators return CANCELLED instead of raising)."""
102
+ if "FINISHED" not in outcome:
103
+ raise RuntimeError(f"{what} returned {outcome}")
104
+
105
+
106
+ # --- seams and unwraps ----------------------------------------------------------------------------------------
107
+
108
+ def mark_seams_from_sharp(obj: bpy.types.Object, angle_degrees=DEFAULT_SEAM_ANGLE_DEGREES) -> int:
109
+ """
110
+ Marks a UV seam on every edge that is shaded hard: edges already marked sharp, edges whose faces meet at
111
+ more than `angle_degrees` (None: marked sharp edges only), and open boundaries. A tangent-space normal map
112
+ needs a UV split wherever the vertex normals split, or the bake shows seams and gradients.
113
+
114
+ :param obj: Mesh object.
115
+ :param angle_degrees: Dihedral limit, or None.
116
+ :returns: Number of seam edges.
117
+ """
118
+ edit_mesh = bmesh.new()
119
+ edit_mesh.from_mesh(obj.data)
120
+ limit = None if angle_degrees is None else math.radians(angle_degrees)
121
+ count = 0
122
+ for edge in edit_mesh.edges:
123
+ is_seam = not edge.smooth or len(edge.link_faces) != 2
124
+ if limit is not None and len(edge.link_faces) == 2:
125
+ is_seam = is_seam or edge.calc_face_angle(0.0) > limit
126
+ edge.seam = is_seam
127
+ count += is_seam
128
+ edit_mesh.to_mesh(obj.data)
129
+ edit_mesh.free()
130
+ return count
131
+
132
+
133
+ def unwrap(obj: bpy.types.Object, texture_size: int = 2048, margin_pixels: float = 16.0, method: str = "ANGLE_BASED",
134
+ uv_name=None) -> None:
135
+ """
136
+ Unwraps from the marked seams, then packs. ANGLE_BASED suits hard surface, CONFORMAL keeps straight
137
+ edges straighter, MINIMUM_STRETCH (SLIM) gives the least area distortion on organic shapes.
138
+
139
+ :param obj: Mesh object with seams marked.
140
+ :param texture_size: Texture width in pixels the margin is measured at.
141
+ :param margin_pixels: Margin around each island in pixels (islands end about twice this apart).
142
+ :param method: Unwrap method.
143
+ :param uv_name: UV map (default the active one).
144
+ """
145
+ with _EditUV(obj, uv_name):
146
+ _check(bpy.ops.uv.unwrap(method=method, fill_holes=True, correct_aspect=True, margin_method="FRACTION",
147
+ margin=margin_pixels / texture_size), "uv.unwrap")
148
+ pack(obj, texture_size, margin_pixels, uv_name=uv_name)
149
+
150
+
151
+ def box_project(obj: bpy.types.Object, metres_per_tile: float, uv_name: str = "UVMap") -> None:
152
+ """
153
+ World-scale planar UVs: each face is projected along its dominant normal axis, one UV unit per
154
+ `metres_per_tile` metres. Walls get V up (world Z). Every object projected this way has the same texel
155
+ density, which is what tiling and trim-sheet materials need; UVs run past 0..1 by design.
156
+
157
+ :param obj: Mesh object (its world transform is applied to the projection).
158
+ :param metres_per_tile: Metres per UV unit.
159
+ :param uv_name: UV map to write (created if missing).
160
+ """
161
+ mesh = obj.data
162
+ layer = mesh.uv_layers.get(uv_name) or mesh.uv_layers.new(name=uv_name)
163
+ matrix = obj.matrix_world
164
+ normal_matrix = matrix.to_3x3().inverted_safe().transposed()
165
+ for polygon in mesh.polygons:
166
+ normal = (normal_matrix @ polygon.normal).normalized()
167
+ axis = max(range(3), key=lambda index: abs(normal[index]))
168
+ for loop_index in polygon.loop_indices:
169
+ world = matrix @ mesh.vertices[mesh.loops[loop_index].vertex_index].co
170
+ layer.data[loop_index].uv = _planar_uv(world, normal, axis, metres_per_tile)
171
+
172
+
173
+ def _planar_uv(world, normal, axis: int, metres_per_tile: float) -> tuple:
174
+ """UV of a world point on a face whose dominant normal axis is `axis` (0 X, 1 Y, 2 Z)."""
175
+ if axis == 2:
176
+ return (world.x / metres_per_tile, world.y * math.copysign(1.0, normal.z) / metres_per_tile)
177
+ if axis == 0:
178
+ return (world.y * math.copysign(1.0, normal.x) / metres_per_tile, world.z / metres_per_tile)
179
+ return (-world.x * math.copysign(1.0, normal.y) / metres_per_tile, world.z / metres_per_tile)
180
+
181
+
182
+ # --- packing --------------------------------------------------------------------------------------------------
183
+
184
+ def pack(obj: bpy.types.Object, texture_size: int, margin_pixels: float, uv_name=None, scale: bool = True,
185
+ rotate: bool = True, shape: str = "CONCAVE") -> None:
186
+ """
187
+ Packs the islands into 0..1 with a margin given in pixels at the texture size (FRACTION margin: a fixed
188
+ share of the UV square, whatever the island scale). The margin is per island side, so neighbouring
189
+ islands end up about twice `margin_pixels` apart and the outer islands `margin_pixels` from the border:
190
+ pass the bake padding, and the gutter between islands comes out at twice it.
191
+
192
+ :param obj: Mesh object.
193
+ :param texture_size: Texture width in pixels.
194
+ :param margin_pixels: Margin around each island in pixels.
195
+ :param uv_name: UV map (default the active one).
196
+ :param scale: Scale the islands to fill the square (False keeps a texel density set beforehand).
197
+ :param rotate: Allow quarter turns (texel rows stay aligned with the island's straight edges); turn off
198
+ for trim sheets and lettering.
199
+ :param shape: CONCAVE (default: tightest, about 10 % more coverage on organic islands, seconds per call),
200
+ AABB (a tenth of a second; as tight on boxy islands; use it while iterating) or CONVEX (measured no
201
+ tighter than AABB and as slow as CONCAVE).
202
+ :raises ValueError: with scale=False, when the islands do not fit in 0..1 at their current density.
203
+ """
204
+ with _EditUV(obj, uv_name):
205
+ _check(bpy.ops.uv.pack_islands(rotate=rotate, rotate_method="CARDINAL", scale=scale, margin_method="FRACTION",
206
+ margin=margin_pixels / texture_size, shape_method=shape), "uv.pack_islands")
207
+ if not scale:
208
+ highest = max(bounds(obj, uv_name)["max"])
209
+ if highest > 1.0 + UV_WELD_TOLERANCE:
210
+ raise ValueError(f"{obj.name}: the islands need {highest:.2f} UV squares at this texel density; lower "
211
+ f"the density by {1.0 / highest:.2f}x or raise the texture size")
212
+
213
+
214
+ def add_lightmap_uv(obj: bpy.types.Object, name: str = "UVLightmap", lightmap_size: int = 512,
215
+ margin_pixels: float = 4.0, shape: str = "CONCAVE", method: str = "auto") -> str:
216
+ """
217
+ Adds a second UV map for baked lighting: islands at one texel density, packed without overlap with a pixel
218
+ margin at the lightmap's resolution. The first map stays the active and render map, so it remains
219
+ TEXCOORD_0 / UV0.
220
+
221
+ The islands come from the first map ("copy": its seams already sit on hard edges, where a lightmap needs
222
+ them too) or from the faces ("smart": Smart UV Project at 66 degrees, which needs no first map). A tiling
223
+ or box-projected first map can fold over itself inside one island; copied, it overlapped by 349-448
224
+ texels on modular kit pieces (Blender 5.3.0). "auto" copies, packs the copy quickly (AABB), measures the
225
+ overlap and re-projects with "smart" when there is any; a mesh with no first map always gets "smart".
226
+
227
+ :param obj: Mesh object (with a first UV map for "copy").
228
+ :param name: Name of the lightmap UV map.
229
+ :param lightmap_size: Lightmap resolution the object will get (pixels across its atlas region).
230
+ :param margin_pixels: Margin around each island in lightmap pixels. It is applied per island side, so
231
+ neighbouring islands end about twice this apart (texels of neighbouring charts must never touch, or
232
+ light bleeds between them).
233
+ :param shape: Packing shape, as in pack().
234
+ :param method: "auto" (default), "copy" or "smart".
235
+ :returns: The UV map name.
236
+ :raises ValueError: for an unknown method, or "copy" on a mesh without a first UV map.
237
+ """
238
+ if method not in LIGHTMAP_METHODS:
239
+ raise ValueError(f"unknown lightmap method '{method}'; use one of {LIGHTMAP_METHODS}")
240
+ layers = obj.data.uv_layers
241
+ has_first_map = bool(layers)
242
+ if not has_first_map:
243
+ if method == "copy":
244
+ raise ValueError(f"{obj.name} has no UV map to derive a lightmap layout from")
245
+ layers.new(name="UVMap")
246
+ texture_name = layers[0].name
247
+ if method == "copy":
248
+ _copy_first_map(obj, name)
249
+ _average_and_pack(obj, name, lightmap_size, margin_pixels, shape, smart_project=False)
250
+ elif method == "smart" or not has_first_map or _copy_folds(obj, name, lightmap_size, margin_pixels):
251
+ _average_and_pack(obj, name, lightmap_size, margin_pixels, shape, smart_project=True)
252
+ elif shape != LIGHTMAP_PROBE_SHAPE:
253
+ pack(obj, lightmap_size, margin_pixels, uv_name=name, shape=shape)
254
+ # Layer references go stale when layers are added or Edit Mode is left: look them up again by name.
255
+ texture_layer = obj.data.uv_layers[texture_name]
256
+ obj.data.uv_layers.active = texture_layer
257
+ texture_layer.active_render = True
258
+ return name
259
+
260
+
261
+ def _copy_first_map(obj: bpy.types.Object, name: str) -> None:
262
+ """Copies the first UV map's coordinates into the map `name` (created if missing)."""
263
+ layers = obj.data.uv_layers
264
+ values = np.empty(len(obj.data.loops) * 2, dtype=np.float32)
265
+ layers[0].data.foreach_get("uv", values)
266
+ lightmap = layers.get(name) or layers.new(name=name, do_init=False)
267
+ lightmap.data.foreach_set("uv", values)
268
+
269
+
270
+ def _copy_folds(obj: bpy.types.Object, name: str, lightmap_size: int, margin_pixels: float) -> bool:
271
+ """
272
+ Copies the first map into `name`, evens and packs it with the quick LIGHTMAP_PROBE_SHAPE, and tells whether
273
+ the copy still overlaps itself (packing moves whole islands, so only folds inside an island remain).
274
+ """
275
+ _copy_first_map(obj, name)
276
+ _average_and_pack(obj, name, lightmap_size, margin_pixels, LIGHTMAP_PROBE_SHAPE, smart_project=False)
277
+ return self_overlap(obj, name, lightmap_size) > 0
278
+
279
+
280
+ def _average_and_pack(obj: bpy.types.Object, name: str, lightmap_size: int, margin_pixels: float, shape: str,
281
+ smart_project: bool) -> None:
282
+ """Optionally re-projects the map `name` (Smart UV Project), evens its texel density and packs it."""
283
+ with _EditUV(obj, name):
284
+ if smart_project:
285
+ _check(bpy.ops.uv.smart_project(angle_limit=math.radians(LIGHTMAP_SMART_ANGLE_DEGREES), island_margin=0.0),
286
+ "uv.smart_project")
287
+ _check(bpy.ops.uv.average_islands_scale(), "uv.average_islands_scale")
288
+ _check(bpy.ops.uv.pack_islands(rotate=True, rotate_method="CARDINAL", scale=True, margin_method="FRACTION",
289
+ margin=margin_pixels / lightmap_size, shape_method=shape),
290
+ "uv.pack_islands")
291
+
292
+
293
+ # --- measuring ------------------------------------------------------------------------------------------------
294
+
295
+ def _uv_array(obj: bpy.types.Object, uv_name=None) -> np.ndarray:
296
+ """(corner count, 2) UVs of a map."""
297
+ layer = obj.data.uv_layers[uv_name] if uv_name else obj.data.uv_layers.active
298
+ if layer is None:
299
+ raise ValueError(f"{obj.name} has no UV map {uv_name or ''}".strip())
300
+ values = np.empty(len(obj.data.loops) * 2, dtype=np.float64)
301
+ layer.data.foreach_get("uv", values)
302
+ return values.reshape(-1, 2)
303
+
304
+
305
+ def islands(obj: bpy.types.Object, uv_name=None) -> list:
306
+ """
307
+ UV islands as lists of face indices: faces are joined across an edge only when both its corners carry
308
+ the same UVs on the two faces (a seam or a cut splits them).
309
+
310
+ :returns: [[face index, ...], ...], largest first.
311
+ """
312
+ mesh = obj.data
313
+ uvs = _uv_array(obj, uv_name)
314
+ parent = list(range(len(mesh.polygons)))
315
+
316
+ def root(index: int) -> int:
317
+ while parent[index] != index:
318
+ parent[index] = parent[parent[index]]
319
+ index = parent[index]
320
+ return index
321
+
322
+ edge_sides = {}
323
+ for polygon in mesh.polygons:
324
+ corners = list(polygon.loop_indices)
325
+ for position, loop_index in enumerate(corners):
326
+ next_loop = corners[(position + 1) % len(corners)]
327
+ first, second = mesh.loops[loop_index].vertex_index, mesh.loops[next_loop].vertex_index
328
+ key = (min(first, second), max(first, second))
329
+ uv_by_vertex = {first: uvs[loop_index], second: uvs[next_loop]}
330
+ edge_sides.setdefault(key, []).append((polygon.index, uv_by_vertex))
331
+ for (first, second), sides in edge_sides.items():
332
+ for (face_a, uv_a), (face_b, uv_b) in zip(sides, sides[1:]):
333
+ same_first = np.abs(uv_a[first] - uv_b[first]).max() < UV_WELD_TOLERANCE
334
+ same_second = np.abs(uv_a[second] - uv_b[second]).max() < UV_WELD_TOLERANCE
335
+ if same_first and same_second:
336
+ parent[root(face_a)] = root(face_b)
337
+ groups = {}
338
+ for polygon in mesh.polygons:
339
+ groups.setdefault(root(polygon.index), []).append(polygon.index)
340
+ return sorted(groups.values(), key=len, reverse=True)
341
+
342
+
343
+ def _face_areas(obj: bpy.types.Object, uv_name=None) -> tuple:
344
+ """(world area per face in m^2, UV area per face) from the triangulated mesh."""
345
+ mesh = obj.data
346
+ mesh.calc_loop_triangles()
347
+ uvs = _uv_array(obj, uv_name)
348
+ matrix = np.array(obj.matrix_world)
349
+ coordinates = np.empty(len(mesh.vertices) * 3)
350
+ mesh.vertices.foreach_get("co", coordinates)
351
+ world = coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
352
+ world_area = np.zeros(len(mesh.polygons))
353
+ uv_area = np.zeros(len(mesh.polygons))
354
+ for triangle in mesh.loop_triangles:
355
+ first, second, third = (world[index] for index in triangle.vertices)
356
+ world_area[triangle.polygon_index] += 0.5 * np.linalg.norm(np.cross(second - first, third - first))
357
+ uv_first, uv_second, uv_third = (uvs[index] for index in triangle.loops)
358
+ edge_one, edge_two = uv_second - uv_first, uv_third - uv_first
359
+ uv_area[triangle.polygon_index] += 0.5 * abs(edge_one[0] * edge_two[1] - edge_two[0] * edge_one[1])
360
+ return world_area, uv_area
361
+
362
+
363
+ def texel_density(obj: bpy.types.Object, texture_size: int, uv_name=None) -> dict:
364
+ """
365
+ Texel density in pixels per metre: sqrt(UV area / world area) x texture size, per island and overall
366
+ (area-weighted). The spread (largest / smallest island) is what a consistent asset keeps near 1.
367
+
368
+ :param obj: Mesh object (its world scale counts).
369
+ :param texture_size: Texture width in pixels.
370
+ :param uv_name: UV map (default the active one).
371
+ :returns: {"mean", "min", "max", "spread", "islands": [px/m per island]}.
372
+ """
373
+ world_area, uv_area = _face_areas(obj, uv_name)
374
+ densities = []
375
+ for island in islands(obj, uv_name):
376
+ island_world = world_area[island].sum()
377
+ if island_world > MINIMUM_WORLD_AREA:
378
+ densities.append(math.sqrt(uv_area[island].sum() / island_world) * texture_size)
379
+ total_world = world_area.sum()
380
+ mean = math.sqrt(uv_area.sum() / total_world) * texture_size if total_world > MINIMUM_WORLD_AREA else 0.0
381
+ smallest = min(densities) if densities else 0.0
382
+ return {"mean": round(mean, 2), "min": round(smallest, 2), "max": round(max(densities, default=0.0), 2),
383
+ "spread": round(max(densities, default=0.0) / smallest, 3) if smallest else None,
384
+ "islands": [round(value, 2) for value in densities]}
385
+
386
+
387
+ def set_texel_density(obj: bpy.types.Object, target_pixels_per_metre: float, texture_size: int, uv_name=None) -> int:
388
+ """
389
+ Scales every island about its own UV centre to the target density (pack afterwards with scale=False).
390
+
391
+ :param obj: Mesh object.
392
+ :param target_pixels_per_metre: Wanted density.
393
+ :param texture_size: Texture width in pixels.
394
+ :param uv_name: UV map (default the active one).
395
+ :returns: Number of islands scaled.
396
+ """
397
+ layer = obj.data.uv_layers[uv_name] if uv_name else obj.data.uv_layers.active
398
+ world_area, uv_area = _face_areas(obj, uv_name)
399
+ uvs = _uv_array(obj, uv_name)
400
+ polygons = obj.data.polygons
401
+ scaled = 0
402
+ for island in islands(obj, uv_name):
403
+ island_world, island_uv = world_area[island].sum(), uv_area[island].sum()
404
+ if island_world <= MINIMUM_WORLD_AREA or island_uv <= 0.0:
405
+ continue
406
+ factor = target_pixels_per_metre / (math.sqrt(island_uv / island_world) * texture_size)
407
+ corners = [loop for face in island for loop in polygons[face].loop_indices]
408
+ center = uvs[corners].mean(axis=0)
409
+ uvs[corners] = center + (uvs[corners] - center) * factor
410
+ scaled += 1
411
+ layer.data.foreach_set("uv", uvs.astype(np.float32).ravel())
412
+ return scaled
413
+
414
+
415
+ def _island_masks(obj: bpy.types.Object, uv_name, resolution: int) -> list:
416
+ """One boolean raster per island: texel centres inside any of its UV triangles."""
417
+ mesh = obj.data
418
+ mesh.calc_loop_triangles()
419
+ uvs = _uv_array(obj, uv_name) * resolution
420
+ face_island = {}
421
+ for island_index, island in enumerate(islands(obj, uv_name)):
422
+ for face in island:
423
+ face_island[face] = island_index
424
+ masks = [np.zeros((resolution, resolution), dtype=bool) for _ in range(len(set(face_island.values())))]
425
+ for triangle in mesh.loop_triangles:
426
+ _fill_triangle(masks[face_island[triangle.polygon_index]], uvs[list(triangle.loops)])
427
+ return masks
428
+
429
+
430
+ def _triangle_cells(corners: np.ndarray, size: int, strict: bool = False):
431
+ """
432
+ The texels whose centres lie inside a triangle given in pixel coordinates, as (window, inside): the
433
+ raster window (row slice, column slice) and a boolean array over it. With strict, centres exactly on an
434
+ edge are left out, so two triangles that only share an edge never claim the same texel. None for a
435
+ degenerate triangle.
436
+ """
437
+ low = np.clip(np.floor(corners.min(axis=0) - 0.5).astype(int), 0, size - 1)
438
+ high = np.clip(np.ceil(corners.max(axis=0) + 0.5).astype(int), 0, size - 1)
439
+ xs, ys = np.meshgrid(np.arange(low[0], high[0] + 1) + 0.5, np.arange(low[1], high[1] + 1) + 0.5)
440
+ (ax, ay), (bx, by), (cx, cy) = corners
441
+ area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay)
442
+ if abs(area) < 1e-12:
443
+ return None
444
+ first = ((bx - xs) * (cy - ys) - (cx - xs) * (by - ys)) / area
445
+ second = ((cx - xs) * (ay - ys) - (ax - xs) * (cy - ys)) / area
446
+ third = 1.0 - first - second
447
+ if strict:
448
+ inside = (first > 0) & (second > 0) & (third > 0)
449
+ else:
450
+ inside = (first >= 0) & (second >= 0) & (third >= 0)
451
+ return (slice(low[1], high[1] + 1), slice(low[0], high[0] + 1)), inside
452
+
453
+
454
+ def _fill_triangle(mask: np.ndarray, corners: np.ndarray) -> None:
455
+ """Sets the texels whose centres lie inside (or on) a triangle given in pixel coordinates."""
456
+ cells = _triangle_cells(corners, mask.shape[0])
457
+ if cells is not None:
458
+ window, inside = cells
459
+ mask[window] |= inside
460
+
461
+
462
+ def self_overlap(obj: bpy.types.Object, uv_name=None, resolution: int = 1024) -> int:
463
+ """
464
+ Texels covered by two or more triangles of a UV map: overlap between islands AND inside one island that
465
+ folds over itself (what a box-projected or tiling map does where two faces land on the same UVs).
466
+ overlap() compares islands only. Texel centres exactly on a shared edge belong to neither triangle, so a
467
+ clean layout reads 0.
468
+
469
+ :returns: The number of texels claimed more than once.
470
+ """
471
+ mesh = obj.data
472
+ mesh.calc_loop_triangles()
473
+ uvs = _uv_array(obj, uv_name) * resolution
474
+ claims = np.zeros((resolution, resolution), dtype=np.int32)
475
+ for triangle in mesh.loop_triangles:
476
+ cells = _triangle_cells(uvs[list(triangle.loops)], resolution, strict=True)
477
+ if cells is not None:
478
+ window, inside = cells
479
+ claims[window] += inside
480
+ return int((claims > 1).sum())
481
+
482
+
483
+ def overlap(obj: bpy.types.Object, uv_name=None, resolution: int = 1024) -> dict:
484
+ """
485
+ Texels claimed by more than one island (a lightmap or a unique bake needs none) and texels outside 0..1.
486
+
487
+ :returns: {"overlap_texels", "covered_texels", "overlap_ratio", "outside_unit_square"}.
488
+ """
489
+ masks = _island_masks(obj, uv_name, resolution)
490
+ claims = np.sum(masks, axis=0) if masks else np.zeros((resolution, resolution))
491
+ uvs = _uv_array(obj, uv_name)
492
+ outside = bool((uvs < -1e-6).any() or (uvs > 1.0 + 1e-6).any())
493
+ covered = int((claims > 0).sum())
494
+ overlapping = int((claims > 1).sum())
495
+ return {"overlap_texels": overlapping, "covered_texels": covered,
496
+ "overlap_ratio": round(overlapping / covered, 6) if covered else 0.0, "outside_unit_square": outside}
497
+
498
+
499
+ def island_gap_pixels(obj: bpy.types.Object, uv_name=None, resolution: int = 1024) -> int:
500
+ """
501
+ The closest any two islands come, in texels at `resolution` (Chebyshev distance, found by growing every
502
+ island one texel at a time until two meet). Exact for odd gaps and one texel low for even ones, so it never
503
+ reports more room than there is. Compare it with the bake margin: islands closer than twice the padding
504
+ bleed into each other as the texture is mip-mapped.
505
+
506
+ :returns: The gap in pixels (0 = touching or overlapping), or MAXIMUM_GAP_SEARCH_PIXELS when none met.
507
+ """
508
+ masks = _island_masks(obj, uv_name, resolution)
509
+ if len(masks) < 2:
510
+ return MAXIMUM_GAP_SEARCH_PIXELS
511
+ labels = np.full((resolution, resolution), -1, dtype=np.int32)
512
+ for index, mask in enumerate(masks):
513
+ if (labels[mask] >= 0).any():
514
+ return 0
515
+ labels[mask] = index
516
+ for grown in range(MAXIMUM_GAP_SEARCH_PIXELS + 1):
517
+ if _labels_touch(labels):
518
+ return max(0, 2 * grown - 1)
519
+ labels = _grow_labels(labels)
520
+ return MAXIMUM_GAP_SEARCH_PIXELS
521
+
522
+
523
+ def _neighbour_shifts(labels: np.ndarray):
524
+ """Yields the label image shifted by each of the 8 neighbour offsets (-1 where shifted in from outside)."""
525
+ height, width = labels.shape
526
+ for shift_y in (-1, 0, 1):
527
+ for shift_x in (-1, 0, 1):
528
+ if shift_x == 0 and shift_y == 0:
529
+ continue
530
+ shifted = np.full_like(labels, -1)
531
+ shifted[max(0, shift_y):height - max(0, -shift_y), max(0, shift_x):width - max(0, -shift_x)] = \
532
+ labels[max(0, -shift_y):height - max(0, shift_y), max(0, -shift_x):width - max(0, shift_x)]
533
+ yield shifted
534
+
535
+
536
+ def _labels_touch(labels: np.ndarray) -> bool:
537
+ """True when two different labels are 8-neighbours somewhere."""
538
+ return any(bool(((shifted >= 0) & (labels >= 0) & (shifted != labels)).any())
539
+ for shifted in _neighbour_shifts(labels))
540
+
541
+
542
+ def _grow_labels(labels: np.ndarray) -> np.ndarray:
543
+ """Grows every label one texel into its empty 8-neighbours."""
544
+ grown = labels.copy()
545
+ for shifted in _neighbour_shifts(labels):
546
+ empty = (grown < 0) & (shifted >= 0)
547
+ grown[empty] = shifted[empty]
548
+ return grown
549
+
550
+
551
+ def bounds(obj: bpy.types.Object, uv_name=None) -> dict:
552
+ """{"min": [u, v], "max": [u, v]} of a UV map."""
553
+ uvs = _uv_array(obj, uv_name)
554
+ return {"min": [round(float(value), 6) for value in uvs.min(axis=0)],
555
+ "max": [round(float(value), 6) for value in uvs.max(axis=0)]}