@babylonjs-toolkit/agent 1.2.15 → 1.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +8 -2
  2. package/lib/diskinfo/cli.js +40 -6
  3. package/lib/diskinfo/report.js +28 -15
  4. package/package.json +1 -1
  5. package/skills/bt-blender/SKILL.md +386 -0
  6. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  7. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  8. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  9. package/skills/bt-blender/references/environments.md +478 -0
  10. package/skills/bt-blender/references/game-engine-export.md +284 -0
  11. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  12. package/skills/bt-blender/references/hard-surface.md +720 -0
  13. package/skills/bt-blender/references/procedural-generation.md +358 -0
  14. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  15. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  16. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  17. package/skills/bt-blender/references/vehicles.md +632 -0
  18. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  19. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  20. package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
  21. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  22. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  23. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  24. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  25. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  26. package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
  27. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  28. package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
  29. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  30. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  31. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  32. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  33. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  34. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  35. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  36. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  37. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  38. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  39. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  40. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  41. package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
  42. package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
  43. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  44. package/skills/bt-gauntlet/SKILL.md +6 -6
  45. package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
  46. package/skills/bt-gauntlet/references/spec-composition.md +13 -0
  47. package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
  48. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  49. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  50. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  51. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  52. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  53. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  54. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  55. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  56. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  57. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  58. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,439 @@
1
+ """
2
+ bt-blender PBR materials: Principled BSDF materials wired the way the glTF exporter, BabylonJS and Unity read
3
+ them, a Cycles bake of any node material to base colour / ORM / normal textures with the right encodings, and
4
+ channel packing for each engine. Headless on Blender 5.3.
5
+
6
+ import materials_pbr as pbr
7
+
8
+ maps = pbr.bake_maps(obj, "build/textures", "Crate", size=1024, margin_pixels=8)
9
+ material = pbr.textured_material("Crate", maps["base_color"], maps["orm"], maps["normal"])
10
+ pbr.replace_materials(obj, material)
11
+ pbr.save_png(pbr.unity_metallic_smoothness(maps["orm_pixels"]), "build/textures/Crate_MetallicSmoothness.png")
12
+
13
+ What is in it:
14
+ - colour: srgb_to_linear, linear_to_srgb (exact IEC 61966-2-1 curves, numpy);
15
+ - materials: principled_material (constant values, colours given in sRGB), textured_material (base colour sRGB,
16
+ ORM Non-Color through Separate Color, occlusion through the glTF Material Output group, tangent-space normal
17
+ map), gltf_material_output, replace_materials;
18
+ - baking: bake_maps (every channel through an Emission override and EMIT, normals through NORMAL, AO through
19
+ AO; float targets, then 8-bit PNGs encoded here, so no colour management guesses), bake_channel;
20
+ - packing: pack_orm, unity_metallic_smoothness (URP / Built-in Metallic map), hdrp_mask_map, save_png,
21
+ load_pixels.
22
+
23
+ Pixel arrays are (height, width, 4) float32, rows bottom-up as Blender stores them, values linear 0..1 unless a
24
+ name says sRGB.
25
+ """
26
+ import os
27
+
28
+ import bpy
29
+ import numpy as np
30
+
31
+ # Image colour spaces on 5.3 (OpenColorIO names).
32
+ COLOR_SPACE_SRGB = "sRGB"
33
+ COLOR_SPACE_DATA = "Non-Color"
34
+
35
+ # The node group name and sockets the glTF exporter reads for occlusion (Blender manual, glTF 2.0 add-on).
36
+ GLTF_OUTPUT_GROUP = "glTF Material Output"
37
+ GLTF_OCCLUSION_SOCKET = "Occlusion"
38
+
39
+ # sRGB transfer function constants (IEC 61966-2-1).
40
+ SRGB_LINEAR_LIMIT = 0.0031308
41
+ SRGB_ENCODED_LIMIT = 0.04045
42
+ SRGB_SLOPE = 12.92
43
+ SRGB_GAMMA = 2.4
44
+ SRGB_OFFSET = 0.055
45
+
46
+ # Cycles samples per bake kind: emission and normals are exact at one sample per texel; AO is a Monte Carlo
47
+ # estimate and needs many.
48
+ EMIT_SAMPLES = 1
49
+ NORMAL_SAMPLES = 1
50
+ AO_SAMPLES = 128
51
+
52
+ # Flat tangent-space normal (+Z) and full occlusion, used when a channel is not baked.
53
+ FLAT_NORMAL = (0.5, 0.5, 1.0, 1.0)
54
+ NO_OCCLUSION = 1.0
55
+
56
+ # Node spacing for generated materials (cosmetic: the node editor layout).
57
+ NODE_COLUMN = 300
58
+ NODE_ROW = 280
59
+
60
+
61
+ # --- colour -----------------------------------------------------------------------------------------------------
62
+
63
+ def srgb_to_linear(values):
64
+ """sRGB-encoded 0..1 values (a colour picker, a hex code / 255, a PNG byte / 255) to linear."""
65
+ encoded = np.clip(np.asarray(values, dtype=np.float64), 0.0, 1.0)
66
+ return np.where(encoded <= SRGB_ENCODED_LIMIT, encoded / SRGB_SLOPE,
67
+ ((encoded + SRGB_OFFSET) / (1.0 + SRGB_OFFSET)) ** SRGB_GAMMA)
68
+
69
+
70
+ def linear_to_srgb(values):
71
+ """Linear 0..1 values to sRGB encoding (what a base colour or emissive PNG stores)."""
72
+ linear = np.clip(np.asarray(values, dtype=np.float64), 0.0, 1.0)
73
+ return np.where(linear <= SRGB_LINEAR_LIMIT, linear * SRGB_SLOPE,
74
+ (1.0 + SRGB_OFFSET) * linear ** (1.0 / SRGB_GAMMA) - SRGB_OFFSET)
75
+
76
+
77
+ # --- materials ----------------------------------------------------------------------------------------------------
78
+
79
+ def _principled(material: bpy.types.Material) -> bpy.types.Node:
80
+ """The material's Principled BSDF (new materials on 5.3 already have one and a Material Output)."""
81
+ node = next((node for node in material.node_tree.nodes if node.type == "BSDF_PRINCIPLED"), None)
82
+ if node is None:
83
+ raise ValueError(f"material {material.name} has no Principled BSDF")
84
+ return node
85
+
86
+
87
+ def _output(material: bpy.types.Material) -> bpy.types.Node:
88
+ """The active Material Output node."""
89
+ outputs = [node for node in material.node_tree.nodes if node.type == "OUTPUT_MATERIAL"]
90
+ active = next((node for node in outputs if node.is_active_output), None)
91
+ if active is None and not outputs:
92
+ raise ValueError(f"material {material.name} has no Material Output")
93
+ return active or outputs[0]
94
+
95
+
96
+ def principled_material(name: str, base_color_srgb=(0.8, 0.8, 0.8), metallic: float = 0.0, roughness: float = 0.5,
97
+ emission_srgb=None, emission_strength: float = 1.0, alpha: float = 1.0,
98
+ double_sided: bool = False) -> bpy.types.Material:
99
+ """
100
+ A constant-valued Principled BSDF material (replaces one of the same name). Colours are given as picked
101
+ (sRGB, e.g. hex / 255) and converted to the linear values the sockets take; the glTF exporter writes the
102
+ socket values as baseColorFactor / emissiveFactor, which glTF defines as linear.
103
+
104
+ :param name: Material name.
105
+ :param base_color_srgb: (r, g, b) sRGB 0..1.
106
+ :param metallic: 0 for dielectrics, 1 for raw metal; avoid values between except on blends.
107
+ :param roughness: 0 mirror .. 1 matte.
108
+ :param emission_srgb: (r, g, b) sRGB 0..1, or None for no emission.
109
+ :param emission_strength: Emission multiplier (exported through KHR_materials_emissive_strength above 1).
110
+ :param alpha: Opacity; below 1 the material is set to blended rendering.
111
+ :param double_sided: Render back faces (glTF doubleSided). Off by default: closed game meshes never show
112
+ their insides, and a new Blender material is double-sided, which costs fill rate in the engine.
113
+ :returns: The material.
114
+ """
115
+ old = bpy.data.materials.get(name)
116
+ if old is not None:
117
+ bpy.data.materials.remove(old)
118
+ material = bpy.data.materials.new(name)
119
+ material.use_backface_culling = not double_sided
120
+ shader = _principled(material)
121
+ shader.inputs["Base Color"].default_value = (*srgb_to_linear(base_color_srgb), 1.0)
122
+ shader.inputs["Metallic"].default_value = metallic
123
+ shader.inputs["Roughness"].default_value = roughness
124
+ shader.inputs["Alpha"].default_value = alpha
125
+ if emission_srgb is not None:
126
+ shader.inputs["Emission Color"].default_value = (*srgb_to_linear(emission_srgb), 1.0)
127
+ shader.inputs["Emission Strength"].default_value = emission_strength
128
+ if alpha < 1.0:
129
+ material.surface_render_method = "BLENDED"
130
+ return material
131
+
132
+
133
+ def gltf_material_output(material: bpy.types.Material) -> bpy.types.Node:
134
+ """
135
+ Adds (once) the custom node group the glTF exporter reads occlusion from: a group named
136
+ "glTF Material Output" with a float input "Occlusion". Blender never renders it; it only carries the AO
137
+ texture into the file's occlusionTexture.
138
+
139
+ :returns: The group node in the material.
140
+ """
141
+ group = bpy.data.node_groups.get(GLTF_OUTPUT_GROUP)
142
+ if group is None:
143
+ group = bpy.data.node_groups.new(GLTF_OUTPUT_GROUP, "ShaderNodeTree")
144
+ group.interface.new_socket(GLTF_OCCLUSION_SOCKET, in_out="INPUT", socket_type="NodeSocketFloat")
145
+ tree = material.node_tree
146
+ existing = next((node for node in tree.nodes if node.type == "GROUP" and node.node_tree == group), None)
147
+ if existing is not None:
148
+ return existing
149
+ node = tree.nodes.new("ShaderNodeGroup")
150
+ node.node_tree = group
151
+ node.location = (_output(material).location.x, _output(material).location.y - NODE_ROW)
152
+ return node
153
+
154
+
155
+ def _image_node(tree, image_path: str, color_space: str, column: int, row: int) -> bpy.types.Node:
156
+ """An Image Texture node loading `image_path` (reused if already loaded) in the given colour space."""
157
+ image = bpy.data.images.load(os.path.abspath(image_path), check_existing=True)
158
+ image.colorspace_settings.name = color_space
159
+ node = tree.nodes.new("ShaderNodeTexImage")
160
+ node.image = image
161
+ node.location = (column * NODE_COLUMN, row * NODE_ROW)
162
+ return node
163
+
164
+
165
+ def textured_material(name: str, base_color_path: str, orm_path: str = None, normal_path: str = None,
166
+ emission_path: str = None, normal_strength: float = 1.0, uv_name: str = None,
167
+ double_sided: bool = False):
168
+ """
169
+ A Principled material on baked textures, wired so the glTF exporter writes a standard texture set:
170
+ base colour sRGB -> baseColorTexture; ORM Non-Color -> Separate Color, G -> Roughness, B -> Metallic,
171
+ R -> glTF Material Output "Occlusion" (exported as metallicRoughnessTexture and occlusionTexture on the
172
+ SAME image: one texture, three channels); normal Non-Color -> Normal Map (tangent space) -> normalTexture.
173
+
174
+ :param name: Material name (replaced if it exists).
175
+ :param base_color_path: Base colour PNG (sRGB-encoded).
176
+ :param orm_path: ORM PNG (R occlusion, G roughness, B metallic, linear), or None for constants.
177
+ :param normal_path: Tangent-space normal PNG (+Y up, OpenGL), or None.
178
+ :param emission_path: Emissive PNG (sRGB), or None.
179
+ :param normal_strength: Normal Map strength (exported as normalTexture.scale).
180
+ :param uv_name: UV map for the normal map's tangents (default: the render UV map).
181
+ :param double_sided: Render back faces (glTF doubleSided); off for closed meshes.
182
+ :returns: The material.
183
+ """
184
+ old = bpy.data.materials.get(name)
185
+ if old is not None:
186
+ bpy.data.materials.remove(old)
187
+ material = bpy.data.materials.new(name)
188
+ material.use_backface_culling = not double_sided
189
+ tree = material.node_tree
190
+ shader = _principled(material)
191
+ links = tree.links
192
+ base = _image_node(tree, base_color_path, COLOR_SPACE_SRGB, -3, 1)
193
+ links.new(base.outputs["Color"], shader.inputs["Base Color"])
194
+ if orm_path:
195
+ orm = _image_node(tree, orm_path, COLOR_SPACE_DATA, -3, 0)
196
+ split = tree.nodes.new("ShaderNodeSeparateColor")
197
+ split.location = (-2 * NODE_COLUMN, 0)
198
+ links.new(orm.outputs["Color"], split.inputs["Color"])
199
+ links.new(split.outputs["Green"], shader.inputs["Roughness"])
200
+ links.new(split.outputs["Blue"], shader.inputs["Metallic"])
201
+ links.new(split.outputs["Red"], gltf_material_output(material).inputs[GLTF_OCCLUSION_SOCKET])
202
+ if normal_path:
203
+ normal = _image_node(tree, normal_path, COLOR_SPACE_DATA, -3, -1)
204
+ normal_map = tree.nodes.new("ShaderNodeNormalMap")
205
+ normal_map.location = (-NODE_COLUMN, -NODE_ROW)
206
+ normal_map.space = "TANGENT"
207
+ normal_map.uv_map = uv_name or ""
208
+ normal_map.inputs["Strength"].default_value = normal_strength
209
+ links.new(normal.outputs["Color"], normal_map.inputs["Color"])
210
+ links.new(normal_map.outputs["Normal"], shader.inputs["Normal"])
211
+ if emission_path:
212
+ emission = _image_node(tree, emission_path, COLOR_SPACE_SRGB, -3, -2)
213
+ links.new(emission.outputs["Color"], shader.inputs["Emission Color"])
214
+ shader.inputs["Emission Strength"].default_value = 1.0
215
+ return material
216
+
217
+
218
+ def replace_materials(obj: bpy.types.Object, material: bpy.types.Material) -> None:
219
+ """Puts one material in every face's place: one slot, so one draw call per mesh."""
220
+ mesh = obj.data
221
+ mesh.polygons.foreach_set("material_index", np.zeros(len(mesh.polygons), dtype=np.int32))
222
+ mesh.materials.clear()
223
+ mesh.materials.append(material)
224
+
225
+
226
+ # --- baking -----------------------------------------------------------------------------------------------------
227
+
228
+ def _scene_for_baking(samples: int) -> None:
229
+ """Cycles on the CPU (headless-safe), with the sample count for this bake kind."""
230
+ scene = bpy.context.scene
231
+ scene.render.engine = "CYCLES"
232
+ scene.cycles.device = "CPU"
233
+ scene.cycles.samples = samples
234
+ scene.cycles.use_denoising = False
235
+
236
+
237
+ def _float_image(name: str, size: int) -> bpy.types.Image:
238
+ """A float bake target. Non-Color, so Cycles writes the raw (linear) values and nothing is converted."""
239
+ old = bpy.data.images.get(name)
240
+ if old is not None:
241
+ bpy.data.images.remove(old)
242
+ image = bpy.data.images.new(name, size, size, alpha=True, float_buffer=True)
243
+ image.colorspace_settings.name = COLOR_SPACE_DATA
244
+ return image
245
+
246
+
247
+ def _with_target(obj: bpy.types.Object, image: bpy.types.Image) -> list:
248
+ """Adds the target image node to every material slot and makes it the active node; returns the nodes."""
249
+ targets = []
250
+ for slot in obj.material_slots:
251
+ if slot.material is None:
252
+ continue
253
+ tree = slot.material.node_tree
254
+ node = tree.nodes.new("ShaderNodeTexImage")
255
+ node.image = image
256
+ node.select = True
257
+ tree.nodes.active = node
258
+ targets.append((tree, node))
259
+ return targets
260
+
261
+
262
+ def _emission_override(material: bpy.types.Material, channel: str):
263
+ """
264
+ Routes one Principled input (whatever feeds it, or its constant) through an Emission shader into the
265
+ output, so an EMIT bake records it exactly, unlit. Returns an undo record for _restore().
266
+ """
267
+ tree = material.node_tree
268
+ shader = _principled(material)
269
+ output = _output(material)
270
+ socket = shader.inputs[channel]
271
+ emission = tree.nodes.new("ShaderNodeEmission")
272
+ emission.inputs["Strength"].default_value = 1.0
273
+ if socket.is_linked:
274
+ tree.links.new(socket.links[0].from_socket, emission.inputs["Color"])
275
+ else:
276
+ value = socket.default_value
277
+ emission.inputs["Color"].default_value = tuple(value) if hasattr(value, "__len__") else (value, value, value, 1.0)
278
+ previous = output.inputs["Surface"].links[0].from_socket if output.inputs["Surface"].is_linked else None
279
+ tree.links.new(emission.outputs["Emission"], output.inputs["Surface"])
280
+ return tree, output, emission, previous
281
+
282
+
283
+ def _restore(record) -> None:
284
+ """Undoes _emission_override."""
285
+ tree, output, emission, previous = record
286
+ tree.nodes.remove(emission)
287
+ if previous is not None:
288
+ tree.links.new(previous, output.inputs["Surface"])
289
+
290
+
291
+ def bake_channel(obj: bpy.types.Object, kind: str, size: int, margin_pixels: int, uv_name: str = None,
292
+ channel: str = None) -> np.ndarray:
293
+ """
294
+ Bakes one channel of the object's own materials into a float image and returns its pixels.
295
+
296
+ :param obj: Mesh object with a non-overlapping UV map.
297
+ :param kind: "EMIT_CHANNEL" (a Principled input through the Emission override; give `channel`), "NORMAL"
298
+ (tangent space, +Y up) or "AO".
299
+ :param size: Texture size in pixels (square).
300
+ :param margin_pixels: Bake margin (edge padding) in pixels, extended from the island borders.
301
+ :param uv_name: UV map to bake into (made active for the bake; default the active one).
302
+ :param channel: Principled input name for EMIT_CHANNEL, e.g. "Base Color", "Roughness", "Metallic".
303
+ :returns: (size, size, 4) float32 linear pixels.
304
+ """
305
+ layers = obj.data.uv_layers
306
+ previous_uv = layers.active.name if layers.active else None
307
+ if uv_name:
308
+ layers.active = layers[uv_name]
309
+ image = _float_image(f"_bake_{obj.name}_{kind}_{channel or ''}", size)
310
+ targets = _with_target(obj, image)
311
+ overrides = []
312
+ try:
313
+ if kind == "EMIT_CHANNEL":
314
+ overrides = [_emission_override(slot.material, channel) for slot in obj.material_slots if slot.material]
315
+ _scene_for_baking(EMIT_SAMPLES)
316
+ bake_type = "EMIT"
317
+ elif kind == "NORMAL":
318
+ _scene_for_baking(NORMAL_SAMPLES)
319
+ bake_type = "NORMAL"
320
+ elif kind == "AO":
321
+ _scene_for_baking(AO_SAMPLES)
322
+ bake_type = "AO"
323
+ else:
324
+ raise ValueError(f"unknown bake kind {kind}")
325
+ with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj],
326
+ selected_editable_objects=[obj]):
327
+ outcome = bpy.ops.object.bake(type=bake_type, normal_space="TANGENT", normal_r="POS_X",
328
+ normal_g="POS_Y", normal_b="POS_Z", margin=margin_pixels,
329
+ margin_type="EXTEND", use_clear=True, target="IMAGE_TEXTURES")
330
+ if "FINISHED" not in outcome:
331
+ raise RuntimeError(f"bake {bake_type} returned {outcome}")
332
+ pixels = np.empty(size * size * 4, dtype=np.float32)
333
+ image.pixels.foreach_get(pixels)
334
+ return pixels.reshape(size, size, 4)
335
+ finally:
336
+ for record in overrides:
337
+ _restore(record)
338
+ for tree, node in targets:
339
+ tree.nodes.remove(node)
340
+ bpy.data.images.remove(image)
341
+ if previous_uv:
342
+ obj.data.uv_layers.active = obj.data.uv_layers[previous_uv]
343
+
344
+
345
+ def bake_maps(obj: bpy.types.Object, folder: str, prefix: str, size: int = 1024, margin_pixels: int = 16,
346
+ uv_name: str = None, bake_ao: bool = False) -> dict:
347
+ """
348
+ Bakes the object's node materials into a glTF texture set and writes it as 8-bit PNGs:
349
+ `<prefix>_BaseColor.png` (sRGB-encoded here), `<prefix>_ORM.png` (R occlusion, G roughness, B metallic,
350
+ linear) and `<prefix>_Normal.png` (tangent space, +Y up, linear). Every channel is baked into a float image
351
+ and encoded by this function, so the bytes on disk do not depend on colour management settings.
352
+
353
+ :param obj: Mesh object, unwrapped without overlaps, with its materials assigned.
354
+ :param folder: Output folder (created).
355
+ :param prefix: File name prefix.
356
+ :param size: Texture size.
357
+ :param margin_pixels: Edge padding in pixels (16 at 2048, 8 at 1024, 4 at 512).
358
+ :param uv_name: UV map to bake into.
359
+ :param bake_ao: Bake ambient occlusion into R (slow: AO_SAMPLES per texel); otherwise R = 1 (none).
360
+ :returns: {"base_color", "orm", "normal": paths, "orm_pixels", "base_color_linear": arrays}.
361
+ """
362
+ os.makedirs(folder, exist_ok=True)
363
+ base_linear = bake_channel(obj, "EMIT_CHANNEL", size, margin_pixels, uv_name, "Base Color")
364
+ roughness = bake_channel(obj, "EMIT_CHANNEL", size, margin_pixels, uv_name, "Roughness")[..., 0]
365
+ metallic = bake_channel(obj, "EMIT_CHANNEL", size, margin_pixels, uv_name, "Metallic")[..., 0]
366
+ occlusion = bake_channel(obj, "AO", size, margin_pixels, uv_name)[..., 0] if bake_ao else None
367
+ normal = bake_channel(obj, "NORMAL", size, margin_pixels, uv_name)
368
+ orm = pack_orm(occlusion, roughness, metallic)
369
+ base_srgb = np.concatenate([linear_to_srgb(base_linear[..., :3]), np.ones(base_linear.shape[:2] + (1,))], axis=2)
370
+ normal[..., 3] = 1.0
371
+ paths = {"base_color": os.path.join(folder, f"{prefix}_BaseColor.png"),
372
+ "orm": os.path.join(folder, f"{prefix}_ORM.png"),
373
+ "normal": os.path.join(folder, f"{prefix}_Normal.png")}
374
+ save_png(base_srgb, paths["base_color"])
375
+ save_png(orm, paths["orm"])
376
+ save_png(normal, paths["normal"])
377
+ return {**paths, "orm_pixels": orm, "base_color_linear": base_linear}
378
+
379
+
380
+ # --- packing ----------------------------------------------------------------------------------------------------
381
+
382
+ def pack_orm(occlusion, roughness, metallic) -> np.ndarray:
383
+ """
384
+ glTF / BabylonJS ORM: R occlusion, G roughness, B metallic, A 1. Each input is a (height, width) array,
385
+ or None (occlusion: 1, no darkening).
386
+ """
387
+ shape = np.shape(roughness)
388
+ occlusion = np.full(shape, NO_OCCLUSION) if occlusion is None else occlusion
389
+ return np.stack([occlusion, roughness, metallic, np.ones(shape)], axis=2).astype(np.float32)
390
+
391
+
392
+ def unity_metallic_smoothness(orm: np.ndarray) -> np.ndarray:
393
+ """
394
+ Unity URP / Built-in Lit "Metallic Map" from an ORM array: R metallic, G and B 0, A smoothness
395
+ (1 - roughness; the material's Smoothness Source must be Metallic Alpha). Occlusion goes in its own map.
396
+ """
397
+ result = np.zeros_like(orm)
398
+ result[..., 0] = orm[..., 2]
399
+ result[..., 3] = 1.0 - orm[..., 1]
400
+ return result
401
+
402
+
403
+ def hdrp_mask_map(orm: np.ndarray, detail_mask=None) -> np.ndarray:
404
+ """Unity HDRP Lit "Mask Map": R metallic, G occlusion, B detail mask (default 1), A smoothness."""
405
+ result = np.empty_like(orm)
406
+ result[..., 0] = orm[..., 2]
407
+ result[..., 1] = orm[..., 0]
408
+ result[..., 2] = 1.0 if detail_mask is None else detail_mask
409
+ result[..., 3] = 1.0 - orm[..., 1]
410
+ return result
411
+
412
+
413
+ def save_png(pixels: np.ndarray, path: str) -> str:
414
+ """
415
+ Writes an (height, width, 4) array of 0..1 values as an 8-bit RGBA PNG, byte = round(value x 255), with no
416
+ colour conversion: encode colour maps first (linear_to_srgb), leave data maps as they are.
417
+
418
+ :returns: The path.
419
+ """
420
+ height, width = pixels.shape[:2]
421
+ image = bpy.data.images.new(f"_save_{os.path.basename(path)}", width, height, alpha=True, float_buffer=False)
422
+ image.colorspace_settings.name = COLOR_SPACE_DATA
423
+ image.pixels.foreach_set(np.clip(pixels, 0.0, 1.0).astype(np.float32).ravel())
424
+ image.filepath_raw = os.path.abspath(path)
425
+ image.file_format = "PNG"
426
+ image.save()
427
+ bpy.data.images.remove(image)
428
+ return path
429
+
430
+
431
+ def load_pixels(path: str) -> np.ndarray:
432
+ """Reads a PNG's stored values (bytes / 255, no colour conversion) as an (height, width, 4) array."""
433
+ image = bpy.data.images.load(os.path.abspath(path), check_existing=False)
434
+ image.colorspace_settings.name = COLOR_SPACE_DATA
435
+ width, height = image.size
436
+ pixels = np.empty(width * height * 4, dtype=np.float32)
437
+ image.pixels.foreach_get(pixels)
438
+ bpy.data.images.remove(image)
439
+ return pixels.reshape(height, width, 4)