@babylonjs-toolkit/agent 1.2.16 → 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.
Files changed (56) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +386 -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 +720 -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 +632 -0
  16. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  17. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  18. package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
  19. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  20. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  21. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  22. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  23. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  24. package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
  25. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  26. package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
  27. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  28. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  29. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  30. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  31. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  32. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  33. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  34. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  35. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  36. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  37. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  38. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  39. package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
  40. package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
  41. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  42. package/skills/bt-gauntlet/SKILL.md +6 -6
  43. package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
  44. package/skills/bt-gauntlet/references/spec-composition.md +13 -0
  45. package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
  46. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  47. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  48. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  49. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  50. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  51. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  52. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  53. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  54. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  55. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  56. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,525 @@
1
+ """
2
+ bt-blender environment kit: modular pieces on a grid, the UVs a kit needs (world-scaled tiling UV0 and a
3
+ non-overlapping lightmap UV1), collision proxies, and the kit gate, headless.
4
+
5
+ import environment_kit as env
6
+
7
+ wall = env.prism_piece("Wall_2m", [((0, 0), (2, 0), (2, 0.2), (0, 0.2))], height=3.0)
8
+ env.drop_hidden_faces(wall, below=0.0)
9
+ env.box_uv(wall, metres_per_tile=2.0)
10
+ env.lightmap_uv(wall, resolution=256, margin_pixels=4)
11
+ print(env.kit_report([wall], grid=1.0))
12
+
13
+ Conventions: metres, Z up. A piece's pivot (object origin) sits on the walking surface (Z = 0 where a
14
+ character stands: walls stand on it, floor slabs hang below it) and on the grid, in one of two places the
15
+ kit chooses once and keeps:
16
+
17
+ - "corner": the footprint's minimum X and Y. The piece extends along +X and +Y; positions are plain grid
18
+ multiples, but a piece turned 90 degrees must move by its own width to stay in its cell.
19
+ - "centre": the middle of the footprint (Bethesda's floor-level, centred pivot). A piece turns in place,
20
+ and the snap step is half the footprint.
21
+
22
+ Lengths along the tiling axes are whole multiples of the grid; a thickness (a wall's depth) is less than
23
+ one cell. Unity snaps these pivots on the same grid and composes the level; Blender only makes the pieces.
24
+
25
+ Two helpers here are thin wrappers kept for existing scripts: lightmap_uv calls uv_layout.add_lightmap_uv
26
+ (the skill's one lightmap UV helper) and convex_proxy calls procedural_game_ready.convex_hull_collider (the
27
+ one collider builder, UCX_ naming). New code should call those directly.
28
+ """
29
+ import math
30
+
31
+ import bmesh
32
+ import bpy
33
+ import numpy as np
34
+ from mathutils import Vector, noise
35
+
36
+ import procedural_game_ready as game_ready
37
+ import uv_layout
38
+
39
+ # Footprint corners are welded when they agree to this many decimal places (micrometres).
40
+ WELD_DIGITS = 6
41
+
42
+ # Lengths and positions closer than this to a grid line count as on it, metres.
43
+ GRID_TOLERANCE = 0.001
44
+
45
+ # Texel density spread allowed across a kit, as a share of the kit median (Beyond Extent / common practice).
46
+ TEXEL_DENSITY_SPREAD = 0.25
47
+
48
+ # Lightmap UVs: Smart UV Project angle (degrees) that splits a box at its corners but keeps a flat run whole
49
+ # (uv_layout's value; lightmap_uv projects with it).
50
+ LIGHTMAP_ANGLE_DEGREES = uv_layout.LIGHTMAP_SMART_ANGLE_DEGREES
51
+
52
+ # UV coordinates match (same island across an edge) within this distance.
53
+ UV_MATCH = 1e-6
54
+
55
+ # A UV triangle with less twice-area than this is degenerate and covers no texel.
56
+ DEGENERATE_AREA = 1e-12
57
+
58
+ # Axis names, for reports.
59
+ AXIS_NAMES = ("X", "Y", "Z")
60
+
61
+ # Unity's MeshCollider accepts at most this many triangles on a convex collider, which a hull of this many
62
+ # vertices reaches (2V - 4 triangles).
63
+ UNITY_CONVEX_TRIANGLES = 255
64
+ UNITY_CONVEX_VERTICES = (UNITY_CONVEX_TRIANGLES + 4) // 2
65
+
66
+ # Pivot conventions kit_report accepts.
67
+ PIVOT_CONVENTIONS = ("corner", "centre")
68
+
69
+ # The smallest lightmap region worth packing for, texels across.
70
+ MINIMUM_LIGHTMAP_TEXELS = 16
71
+
72
+ # Terrain seams: shared border vertices agree within these (metres, degrees).
73
+ SEAM_HEIGHT_TOLERANCE = 1e-5
74
+ SEAM_ANGLE_TOLERANCE_DEGREES = 0.5
75
+
76
+ # A face pointing down has a normal Z below this.
77
+ DOWN_FACING_Z = -0.99
78
+
79
+
80
+ # --- building pieces ------------------------------------------------------------------------------------------
81
+
82
+ def prism_piece(name: str, quads: list, height: float, base: float = 0.0) -> bpy.types.Object:
83
+ """
84
+ A kit piece extruded from a footprint made of quads (a wall run, an L corner, a pillar, a floor slab
85
+ when `height` is negative): the quads are welded where they share corners, extruded by `height`, and
86
+ the object origin stays at (0, 0, 0), the footprint corner. Quads keep the caps free of n-gons.
87
+
88
+ :param name: Piece name (Kit_Type_Size: "Wall_2m", "Floor_2x2", "Corner_Out").
89
+ :param quads: [((x, y) * 4)] counter-clockwise footprint quads, metres.
90
+ :param height: Extrusion along Z, metres (negative hangs below `base`, for floor slabs).
91
+ :param base: Z of the footprint, metres.
92
+ :returns: The new object, closed, normals outward.
93
+ """
94
+ edit_mesh = bmesh.new()
95
+ corners = {}
96
+ faces = []
97
+ for quad in quads:
98
+ verts = []
99
+ for x, y in quad:
100
+ key = (round(x, WELD_DIGITS), round(y, WELD_DIGITS))
101
+ if key not in corners:
102
+ corners[key] = edit_mesh.verts.new((x, y, base))
103
+ verts.append(corners[key])
104
+ faces.append(edit_mesh.faces.new(verts))
105
+ extruded = bmesh.ops.extrude_face_region(edit_mesh, geom=faces)
106
+ moved = [element for element in extruded["geom"] if isinstance(element, bmesh.types.BMVert)]
107
+ bmesh.ops.translate(edit_mesh, verts=moved, vec=(0.0, 0.0, height))
108
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
109
+ mesh = bpy.data.meshes.new(name)
110
+ edit_mesh.to_mesh(mesh)
111
+ edit_mesh.free()
112
+ obj = bpy.data.objects.new(name, mesh)
113
+ bpy.context.scene.collection.objects.link(obj)
114
+ return obj
115
+
116
+
117
+ def drop_hidden_faces(obj: bpy.types.Object, below=None, facing_down: bool = True) -> int:
118
+ """
119
+ Deletes faces no camera can see once the piece is placed: a wall's underside standing on the floor, a
120
+ floor slab's underside. They cost triangles and lightmap space, and a wall's bottom lying on a floor's
121
+ top is a back-to-back pair QA flags.
122
+
123
+ :param obj: Mesh object.
124
+ :param below: Only faces whose centre Z is at or below this (object space); None for any height.
125
+ :param facing_down: Only faces whose normal points down.
126
+ :returns: Faces removed.
127
+ """
128
+ edit_mesh = bmesh.new()
129
+ edit_mesh.from_mesh(obj.data)
130
+ hidden = [face for face in edit_mesh.faces
131
+ if (not facing_down or face.normal.z < DOWN_FACING_Z)
132
+ and (below is None or face.calc_center_median().z <= below + GRID_TOLERANCE)]
133
+ bmesh.ops.delete(edit_mesh, geom=hidden, context="FACES")
134
+ edit_mesh.to_mesh(obj.data)
135
+ edit_mesh.free()
136
+ obj.data.update()
137
+ return len(hidden)
138
+
139
+
140
+ # --- UVs ------------------------------------------------------------------------------------------------------
141
+
142
+ def box_uv(obj: bpy.types.Object, metres_per_tile: float, uv_name: str = "UVMap") -> None:
143
+ """
144
+ World-scaled tiling UVs (UV0): every face is projected along its dominant axis in object space, one
145
+ texture repeat per `metres_per_tile`. Because every piece's pivot sits on the grid and the tile size
146
+ divides the grid, the texture continues across the seam between two snapped pieces (no visible
147
+ joint), and texel density is identical on every piece of the kit.
148
+
149
+ :param obj: Mesh object (pivot on the kit grid).
150
+ :param metres_per_tile: World size of one texture repeat (a 1024 px texture at 512 px/m = 2 m).
151
+ :param uv_name: UV map name; created as the first map if missing.
152
+ """
153
+ mesh = obj.data
154
+ layer = mesh.uv_layers.get(uv_name) or mesh.uv_layers.new(name=uv_name)
155
+ coordinates = np.empty(len(mesh.vertices) * 3)
156
+ mesh.vertices.foreach_get("co", coordinates)
157
+ positions = coordinates.reshape(-1, 3)
158
+ for polygon in mesh.polygons:
159
+ axis = int(np.argmax(np.abs(np.array(polygon.normal))))
160
+ sign = 1.0 if polygon.normal[axis] >= 0 else -1.0
161
+ for loop_index in polygon.loop_indices:
162
+ x, y, z = positions[mesh.loops[loop_index].vertex_index]
163
+ # U runs to the viewer's right on every side face, so text and grain read the right way round.
164
+ u, v = ((sign * y, z), (-sign * x, z), (x, y))[axis]
165
+ layer.data[loop_index].uv = (u / metres_per_tile, v / metres_per_tile)
166
+
167
+
168
+ def lightmap_resolution(obj: bpy.types.Object, texels_per_metre: float) -> int:
169
+ """
170
+ The texels a piece gets across its lightmap region, the way a lightmapper sizes it: the square root of
171
+ its world surface area times the scene's lightmap resolution (Unity's Lightmap Resolution, texels per
172
+ unit). Pack the lightmap UVs for THIS size, so the margin in texels is right where it is baked.
173
+
174
+ :param obj: Mesh object.
175
+ :param texels_per_metre: The scene's lightmap resolution (x the object's Scale In Lightmap).
176
+ :returns: Texels across, at least 16.
177
+ """
178
+ mesh = obj.data
179
+ mesh.calc_loop_triangles()
180
+ matrix = obj.matrix_world
181
+ area = 0.0
182
+ for triangle in mesh.loop_triangles:
183
+ corners = [matrix @ mesh.vertices[index].co for index in triangle.vertices]
184
+ area += (corners[1] - corners[0]).cross(corners[2] - corners[0]).length / 2.0
185
+ return max(int(math.ceil(math.sqrt(area) * texels_per_metre)), MINIMUM_LIGHTMAP_TEXELS)
186
+
187
+
188
+ def lightmap_uv(obj: bpy.types.Object, resolution: int, margin_pixels: float = 4.0,
189
+ uv_name: str = "Lightmap") -> dict:
190
+ """
191
+ A non-overlapping lightmap UV set as the SECOND UV map (Unity reads it as UV2, glTF as TEXCOORD_1), and
192
+ its report. A thin wrapper: uv_layout.add_lightmap_uv(method="smart") makes the map (Smart UV Project
193
+ splits at hard corners and keeps flat runs whole, which a tiling UV0 cannot give), then lightmap_report
194
+ checks it at the piece's lightmap resolution. UV0 stays the active and render map.
195
+
196
+ :param obj: Mesh object.
197
+ :param resolution: Texels across the piece's lightmap region (the lightmap's size x the piece's share).
198
+ :param margin_pixels: Margin per chart side in texels, so charts end about twice this apart (2 at least;
199
+ 4 survives block compression). The report checks the gap against this same number.
200
+ :param uv_name: Name of the lightmap map.
201
+ :returns: lightmap_report of the result.
202
+ """
203
+ uv_layout.add_lightmap_uv(obj, name=uv_name, lightmap_size=resolution, margin_pixels=margin_pixels,
204
+ method="smart")
205
+ return lightmap_report(obj, resolution, margin_pixels, uv_name)
206
+
207
+
208
+ def _uv_islands(edit_mesh: bmesh.types.BMesh, layer) -> list:
209
+ """Island id per face: faces joined by an edge whose two corners have the same UVs on both sides."""
210
+ parent = list(range(len(edit_mesh.faces)))
211
+
212
+ def root(index: int) -> int:
213
+ """Union-find root with path halving."""
214
+ while parent[index] != index:
215
+ parent[index] = parent[parent[index]]
216
+ index = parent[index]
217
+ return index
218
+
219
+ for edge in edit_mesh.edges:
220
+ if len(edge.link_faces) != 2:
221
+ continue
222
+ first, second = edge.link_faces
223
+ if all((_corner_uv(first, vertex, layer) - _corner_uv(second, vertex, layer)).length < UV_MATCH for vertex in edge.verts):
224
+ parent[root(first.index)] = root(second.index)
225
+ return [root(face.index) for face in edit_mesh.faces]
226
+
227
+
228
+ def _corner_uv(face: bmesh.types.BMFace, vertex: bmesh.types.BMVert, layer):
229
+ """The UV of a face's corner at a vertex."""
230
+ return next(loop[layer].uv for loop in face.loops if loop.vert is vertex)
231
+
232
+
233
+ def _rasterise_triangle(points: np.ndarray, resolution: int) -> tuple:
234
+ """Texel cells whose centres lie inside a UV triangle: (rows, columns) arrays."""
235
+ scaled = points * resolution
236
+ low = np.clip(np.floor(scaled.min(axis=0)).astype(int), 0, resolution - 1)
237
+ high = np.clip(np.ceil(scaled.max(axis=0)).astype(int), 0, resolution)
238
+ columns, rows = np.meshgrid(np.arange(low[0], high[0]) + 0.5, np.arange(low[1], high[1]) + 0.5)
239
+ a, b, c = scaled
240
+ denominator = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1])
241
+ if abs(denominator) < DEGENERATE_AREA:
242
+ return np.array([], int), np.array([], int)
243
+ weight_a = ((b[1] - c[1]) * (columns - c[0]) + (c[0] - b[0]) * (rows - c[1])) / denominator
244
+ weight_b = ((c[1] - a[1]) * (columns - c[0]) + (a[0] - c[0]) * (rows - c[1])) / denominator
245
+ inside = (weight_a >= 0) & (weight_b >= 0) & (weight_a + weight_b <= 1)
246
+ return (rows[inside] - 0.5).astype(int), (columns[inside] - 0.5).astype(int)
247
+
248
+
249
+ def _dilate(mask: np.ndarray, pixels: int) -> np.ndarray:
250
+ """Square dilation of a boolean mask by `pixels` texels."""
251
+ grown = mask.copy()
252
+ for _ in range(pixels):
253
+ shifted = grown.copy()
254
+ shifted[1:, :] |= grown[:-1, :]
255
+ shifted[:-1, :] |= grown[1:, :]
256
+ shifted[:, 1:] |= grown[:, :-1]
257
+ shifted[:, :-1] |= grown[:, 1:]
258
+ grown = shifted
259
+ return grown
260
+
261
+
262
+ def lightmap_report(obj: bpy.types.Object, resolution: int, margin_pixels: float = 2.0, uv_name: str = "Lightmap") -> dict:
263
+ """
264
+ Checks a lightmap UV set at the resolution it will be baked at: charts in 0..1, no texel covered by two
265
+ triangles, and every chart at least `margin_pixels` texels from every other chart.
266
+
267
+ :param obj: Mesh object.
268
+ :param resolution: Texels across the piece's lightmap region.
269
+ :param margin_pixels: Minimum gap between charts in texels. Texel-centre sampling can read a chart one
270
+ texel smaller than it is, so the check allows one texel: charts must be at least margin - 1 empty
271
+ texels apart on the raster.
272
+ :param uv_name: The lightmap UV map.
273
+ :returns: {"pass", "charts", "out_of_range", "overlap_texels", "too_close_texels", "coverage_percent"}.
274
+ """
275
+ edit_mesh = bmesh.new()
276
+ edit_mesh.from_mesh(obj.data)
277
+ edit_mesh.faces.index_update()
278
+ layer = edit_mesh.loops.layers.uv[uv_name]
279
+ islands = _uv_islands(edit_mesh, layer)
280
+ coverage = np.zeros((resolution, resolution), dtype=np.int32)
281
+ owner = np.full((resolution, resolution), -1, dtype=np.int64)
282
+ out_of_range = 0
283
+ for face in edit_mesh.faces:
284
+ uvs = np.array([tuple(loop[layer].uv) for loop in face.loops])
285
+ out_of_range += int(np.any((uvs < -UV_MATCH) | (uvs > 1.0 + UV_MATCH)))
286
+ for corner in range(1, len(uvs) - 1):
287
+ rows, columns = _rasterise_triangle(uvs[[0, corner, corner + 1]], resolution)
288
+ coverage[rows, columns] += 1
289
+ owner[rows, columns] = islands[face.index]
290
+ edit_mesh.free()
291
+ too_close = 0
292
+ for island in set(islands):
293
+ grown = _dilate(owner == island, max(int(math.ceil(margin_pixels)) - 1, 0))
294
+ too_close += int(np.count_nonzero(grown & (owner >= 0) & (owner != island)))
295
+ overlap = int(np.count_nonzero(coverage > 1))
296
+ return {"pass": out_of_range == 0 and overlap == 0 and too_close == 0, "charts": len(set(islands)),
297
+ "out_of_range": out_of_range, "overlap_texels": overlap, "too_close_texels": too_close,
298
+ "coverage_percent": round(100.0 * np.count_nonzero(coverage) / coverage.size, 1)}
299
+
300
+
301
+ def texel_density(obj: bpy.types.Object, texture_pixels: int, uv_name=None) -> float:
302
+ """
303
+ Texel density of a UV map in pixels per metre: sqrt(UV area / world area) x texture size.
304
+
305
+ :param obj: Mesh object.
306
+ :param texture_pixels: Texture width the map is used with.
307
+ :param uv_name: UV map (default the first).
308
+ :returns: Pixels per metre, or 0.0 without UVs or area.
309
+ """
310
+ mesh = obj.data
311
+ if not mesh.uv_layers:
312
+ return 0.0
313
+ layer = mesh.uv_layers[uv_name] if uv_name else mesh.uv_layers[0]
314
+ mesh.calc_loop_triangles()
315
+ matrix = obj.matrix_world
316
+ world_area = uv_area = 0.0
317
+ for triangle in mesh.loop_triangles:
318
+ corners = [matrix @ mesh.vertices[index].co for index in triangle.vertices]
319
+ uvs = [layer.data[index].uv for index in triangle.loops]
320
+ world_area += (corners[1] - corners[0]).cross(corners[2] - corners[0]).length / 2.0
321
+ uv_area += abs((uvs[1] - uvs[0]).cross(uvs[2] - uvs[0])) / 2.0
322
+ return math.sqrt(uv_area / world_area) * texture_pixels if world_area > 0 and uv_area > 0 else 0.0
323
+
324
+
325
+ # --- collision ----------------------------------------------------------------------------------------------
326
+
327
+ def convex_proxy(obj: bpy.types.Object, name=None) -> dict:
328
+ """
329
+ A convex collision proxy around a piece (one hull around all of it), for the rare piece a primitive
330
+ collider in Unity cannot fit. A thin wrapper over procedural_game_ready.convex_hull_collider (one hull,
331
+ at most UNITY_CONVEX_VERTICES vertices, so it always fits Unity's 255-triangle convex limit), shown as a
332
+ wire and hidden from renders. Prefer Box / Capsule colliders on the prefab, and a set of convex pieces
333
+ (convex_hull_collider with per_part=True) for concave shapes.
334
+
335
+ :param obj: Mesh object.
336
+ :param name: Proxy name (default UCX_<name>_00, the convention collision importers recognise).
337
+ :returns: {"object", "triangles", "fits_unity_convex"}.
338
+ :raises ValueError: when the piece is too small for a hull.
339
+ """
340
+ hulls = game_ready.convex_hull_collider(obj, max_vertices=UNITY_CONVEX_VERTICES, per_part=False)
341
+ if not hulls:
342
+ raise ValueError(f"{obj.name} is smaller than {game_ready.MINIMUM_HULL_PART} m: no hull made")
343
+ proxy = hulls[0]
344
+ if name:
345
+ proxy.name = name
346
+ proxy.data.name = name
347
+ proxy.display_type = "WIRE"
348
+ proxy.hide_render = True
349
+ triangles = len(proxy.data.polygons)
350
+ return {"object": proxy.name, "triangles": triangles, "fits_unity_convex": triangles <= UNITY_CONVEX_TRIANGLES}
351
+
352
+
353
+ # --- terrain tiles -------------------------------------------------------------------------------------------
354
+
355
+ def rolling_hills(amplitude: float, wavelength: float, octaves: int = 3, offset=(0.0, 0.0)):
356
+ """
357
+ A height field in WORLD coordinates (fractal Perlin noise): sampled by every tile at its own world
358
+ positions, so neighbouring tiles agree exactly along their shared border.
359
+
360
+ :param amplitude: Peak height, metres.
361
+ :param wavelength: Size of the largest hills, metres.
362
+ :param octaves: Noise octaves (more = rougher).
363
+ :param offset: World offset into the noise, metres (a different landscape per value).
364
+ :returns: height(x, y) -> metres.
365
+ """
366
+ def height(x: float, y: float) -> float:
367
+ """Terrain height at a world position."""
368
+ position = Vector(((x + offset[0]) / wavelength, (y + offset[1]) / wavelength, 0.0))
369
+ return amplitude * noise.fractal(position, 1.0, 2.0, octaves, noise_basis="PERLIN_ORIGINAL")
370
+ return height
371
+
372
+
373
+ def _field_normal(height, x: float, y: float, step: float) -> Vector:
374
+ """The height field's normal at a world position, by central differences one grid step wide."""
375
+ slope_x = (height(x + step, y) - height(x - step, y)) / (2.0 * step)
376
+ slope_y = (height(x, y + step) - height(x, y - step)) / (2.0 * step)
377
+ return Vector((-slope_x, -slope_y, 1.0)).normalized()
378
+
379
+
380
+ def terrain_tile(name: str, origin: tuple, size: float, cells: int, height) -> bpy.types.Object:
381
+ """
382
+ One square terrain tile of a tiled landscape: a quad grid whose heights AND normals come from a world
383
+ height field, so a row of tiles meets with no step and no shading crease. (Normals computed per tile
384
+ from its own faces would differ along every border: the faces beyond the edge are missing.) The tile's
385
+ pivot is its corner on the grid, at Z = 0.
386
+
387
+ :param name: Object name ("Terrain_0_0").
388
+ :param origin: World (x, y) of the tile's corner, on the kit grid.
389
+ :param size: Tile size, metres.
390
+ :param cells: Quads per side.
391
+ :param height: height(x, y) in world metres (rolling_hills or your own).
392
+ :returns: The tile, smooth-shaded with custom normals.
393
+ """
394
+ step = size / cells
395
+ columns = cells + 1
396
+ vertices = [(column * step, row * step, height(origin[0] + column * step, origin[1] + row * step))
397
+ for row in range(columns) for column in range(columns)]
398
+ faces = [(row * columns + column, row * columns + column + 1, (row + 1) * columns + column + 1, (row + 1) * columns + column)
399
+ for row in range(cells) for column in range(cells)]
400
+ mesh = bpy.data.meshes.new(name)
401
+ mesh.from_pydata(vertices, [], faces)
402
+ mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons))
403
+ mesh.normals_split_custom_set_from_vertices(
404
+ [tuple(_field_normal(height, origin[0] + x, origin[1] + y, step)) for x, y, _ in vertices])
405
+ mesh.update()
406
+ tile = bpy.data.objects.new(name, mesh)
407
+ tile.location = (origin[0], origin[1], 0.0)
408
+ bpy.context.scene.collection.objects.link(tile)
409
+ return tile
410
+
411
+
412
+ def _border_samples(obj: bpy.types.Object) -> dict:
413
+ """World (x, y) of every vertex, rounded, to (z, corner normal) for one object."""
414
+ matrix = obj.matrix_world
415
+ normals = {}
416
+ for loop, normal in zip(obj.data.loops, obj.data.corner_normals):
417
+ normals.setdefault(loop.vertex_index, normal.vector.copy())
418
+ samples = {}
419
+ for vertex in obj.data.vertices:
420
+ world = matrix @ vertex.co
421
+ key = (round(world.x / GRID_TOLERANCE), round(world.y / GRID_TOLERANCE))
422
+ samples[key] = (world.z, (matrix.to_3x3() @ normals[vertex.index]).normalized())
423
+ return samples
424
+
425
+
426
+ def seam_report(first: bpy.types.Object, second: bpy.types.Object) -> dict:
427
+ """
428
+ Checks that two neighbouring terrain tiles (or road and terrain pieces) meet cleanly: every vertex they
429
+ share in plan has the same height (no crack) and the same shading normal (no crease line).
430
+
431
+ :param first: One tile.
432
+ :param second: Its neighbour.
433
+ :returns: {"pass", "shared_vertices", "max_height_gap_m", "max_normal_angle_degrees"}.
434
+ """
435
+ first_samples, second_samples = _border_samples(first), _border_samples(second)
436
+ shared = set(first_samples) & set(second_samples)
437
+ gaps = [abs(first_samples[key][0] - second_samples[key][0]) for key in shared]
438
+ angles = [math.degrees(first_samples[key][1].angle(second_samples[key][1], 0.0)) for key in shared]
439
+ largest_gap, largest_angle = max(gaps, default=0.0), max(angles, default=0.0)
440
+ return {"pass": bool(shared) and largest_gap <= SEAM_HEIGHT_TOLERANCE and largest_angle <= SEAM_ANGLE_TOLERANCE_DEGREES,
441
+ "shared_vertices": len(shared), "max_height_gap_m": round(largest_gap, 6),
442
+ "max_normal_angle_degrees": round(largest_angle, 3)}
443
+
444
+
445
+ # --- the kit gate -------------------------------------------------------------------------------------------
446
+
447
+ def _on_grid(value: float, grid: float) -> bool:
448
+ """True when a length or position is a whole multiple of the grid."""
449
+ return abs(value / grid - round(value / grid)) * grid <= GRID_TOLERANCE
450
+
451
+
452
+ def _pivot_errors(low, high, grid: float, pivot: str) -> list:
453
+ """
454
+ Where the piece lies against its pivot, per plan axis. Along a tiling axis (one grid cell or longer)
455
+ the footprint starts at the pivot ("corner") or is centred on it ("centre"). Along a thin axis (a wall's
456
+ depth) the piece sits flush with a cell edge ("corner") or inside the centred footprint, whose half size
457
+ is half the longest plan extent ("centre": a wall set in from the footprint edge, Ian London's 0.125 m).
458
+ """
459
+ errors = []
460
+ footprint_half = max(float(high[0] - low[0]), float(high[1] - low[1]), grid) / 2.0
461
+ for axis in range(2):
462
+ name, start, end = AXIS_NAMES[axis], float(low[axis]), float(high[axis])
463
+ tiling = end - start >= grid - GRID_TOLERANCE
464
+ if pivot == "corner" and tiling and abs(start) > GRID_TOLERANCE:
465
+ errors.append(f"pivot is not at the footprint corner: {name} starts at {start:.4f}")
466
+ elif pivot == "corner" and not tiling and not (_on_grid(start, grid) or _on_grid(end, grid)):
467
+ errors.append(f"thin side is not flush with a cell edge: {name} {start:.4f}..{end:.4f}")
468
+ elif pivot == "centre" and tiling and abs(start + end) > 2.0 * GRID_TOLERANCE:
469
+ errors.append(f"pivot is not at the footprint centre: {name} runs {start:.4f}..{end:.4f}")
470
+ elif pivot == "centre" and not tiling and max(abs(start), abs(end)) > footprint_half + GRID_TOLERANCE:
471
+ errors.append(f"thin side leaves the centred footprint: {name} {start:.4f}..{end:.4f}")
472
+ if abs(low[2]) > GRID_TOLERANCE and abs(high[2]) > GRID_TOLERANCE:
473
+ errors.append(f"Z = 0 is neither the piece's base nor its top (z {low[2]:.4f}..{high[2]:.4f})")
474
+ return errors
475
+
476
+
477
+ def _piece_errors(obj: bpy.types.Object, grid: float, pivot: str) -> tuple:
478
+ """Errors and local extents of one piece: transforms applied, pivot placed, sizes and placement on the grid."""
479
+ errors = []
480
+ location, rotation, scale = obj.matrix_world.decompose()
481
+ if any(abs(component - 1.0) > 1e-4 for component in scale) or rotation.angle > 1e-4:
482
+ errors.append("rotation / scale not applied")
483
+ coordinates = np.empty(len(obj.data.vertices) * 3)
484
+ obj.data.vertices.foreach_get("co", coordinates)
485
+ local = coordinates.reshape(-1, 3)
486
+ low, high = local.min(axis=0), local.max(axis=0)
487
+ errors += _pivot_errors(low, high, grid, pivot)
488
+ for axis, extent in zip(AXIS_NAMES, high - low):
489
+ if extent >= grid - GRID_TOLERANCE and not _on_grid(float(extent), grid):
490
+ errors.append(f"{axis} length {extent:.4f} m is not a multiple of the {grid} m grid")
491
+ if not all(_on_grid(float(component), grid) for component in location):
492
+ errors.append(f"placed off the grid at {tuple(round(component, 4) for component in location)}")
493
+ return errors, (high - low)
494
+
495
+
496
+ def kit_report(objects: list, grid: float, texture_pixels: int = 1024, pivot: str = "corner") -> dict:
497
+ """
498
+ The modular kit gate: every piece snaps on the grid. Per piece: transforms applied, pivot on the walking
499
+ surface at the kit's convention (footprint corner or centre), every tiling length a multiple of the grid
500
+ (thicknesses under one cell are allowed), placement on the grid, triangles, and UV0 texel density within
501
+ 25 % of the kit median (a piece off the kit density shows as a seam in resolution beside another).
502
+
503
+ :param objects: The kit's pieces.
504
+ :param grid: Grid size in metres (1 m, 0.5 m, or the footprint / 2).
505
+ :param texture_pixels: Texture size UV0 is used with, for the texel density.
506
+ :param pivot: "corner" or "centre" (see the module notes).
507
+ :returns: {"pass", "grid_m", "pivot", "median_px_per_m", "pieces": {name: {...}}}.
508
+ :raises ValueError: for an unknown pivot convention.
509
+ """
510
+ if pivot not in PIVOT_CONVENTIONS:
511
+ raise ValueError(f"pivot must be one of {PIVOT_CONVENTIONS}")
512
+ pieces = {}
513
+ for obj in objects:
514
+ errors, extents = _piece_errors(obj, grid, pivot)
515
+ obj.data.calc_loop_triangles()
516
+ pieces[obj.name] = {"extents_m": [round(float(value), 4) for value in extents], "errors": errors,
517
+ "triangles": len(obj.data.loop_triangles),
518
+ "texel_px_per_m": round(texel_density(obj, texture_pixels), 1)}
519
+ densities = [piece["texel_px_per_m"] for piece in pieces.values() if piece["texel_px_per_m"] > 0]
520
+ median = float(np.median(densities)) if densities else 0.0
521
+ for piece in pieces.values():
522
+ if median and abs(piece["texel_px_per_m"] - median) > TEXEL_DENSITY_SPREAD * median:
523
+ piece["errors"].append(f"texel density {piece['texel_px_per_m']} px/m is over 25 % off the kit's {median:.1f}")
524
+ return {"pass": not any(piece["errors"] for piece in pieces.values()), "grid_m": grid, "pivot": pivot,
525
+ "median_px_per_m": round(median, 1), "pieces": pieces}