@project-ava-supernova/core 0.2.196 → 0.2.198

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 (124) hide show
  1. package/dist/agent/agent.js +24 -24
  2. package/dist/agent/fresh-eyes.js +10 -10
  3. package/dist/agent/system-prompt.js +1223 -1223
  4. package/dist/agent/text-tool-parser.js +14 -14
  5. package/dist/auto/intent-gate.js +44 -44
  6. package/dist/auto/task-executor.js +45 -45
  7. package/dist/brand/kit-py.js +41 -41
  8. package/dist/desktop/personas.js +116 -116
  9. package/dist/docs/content/concepts.js +1 -1
  10. package/dist/docs/content/concepts.js.map +1 -1
  11. package/dist/docs/data/tools.js +3 -3
  12. package/dist/docs/data/tools.js.map +1 -1
  13. package/dist/docs/i18n/translations.d.ts.map +1 -1
  14. package/dist/docs/i18n/translations.js +1 -1
  15. package/dist/docs/i18n/translations.js.map +1 -1
  16. package/dist/i18n/locales/ar.js +2 -2
  17. package/dist/i18n/locales/ar.js.map +1 -1
  18. package/dist/i18n/locales/de.js +2 -2
  19. package/dist/i18n/locales/de.js.map +1 -1
  20. package/dist/i18n/locales/en.js +2 -2
  21. package/dist/i18n/locales/en.js.map +1 -1
  22. package/dist/i18n/locales/es.js +2 -2
  23. package/dist/i18n/locales/es.js.map +1 -1
  24. package/dist/i18n/locales/fr.js +2 -2
  25. package/dist/i18n/locales/fr.js.map +1 -1
  26. package/dist/i18n/locales/hi.js +2 -2
  27. package/dist/i18n/locales/hi.js.map +1 -1
  28. package/dist/i18n/locales/id.js +2 -2
  29. package/dist/i18n/locales/id.js.map +1 -1
  30. package/dist/i18n/locales/it.js +2 -2
  31. package/dist/i18n/locales/it.js.map +1 -1
  32. package/dist/i18n/locales/ja.js +2 -2
  33. package/dist/i18n/locales/ja.js.map +1 -1
  34. package/dist/i18n/locales/ko.js +2 -2
  35. package/dist/i18n/locales/ko.js.map +1 -1
  36. package/dist/i18n/locales/nl.js +2 -2
  37. package/dist/i18n/locales/nl.js.map +1 -1
  38. package/dist/i18n/locales/pl.js +2 -2
  39. package/dist/i18n/locales/pl.js.map +1 -1
  40. package/dist/i18n/locales/pt.js +2 -2
  41. package/dist/i18n/locales/pt.js.map +1 -1
  42. package/dist/i18n/locales/ru.js +2 -2
  43. package/dist/i18n/locales/ru.js.map +1 -1
  44. package/dist/i18n/locales/th.js +2 -2
  45. package/dist/i18n/locales/th.js.map +1 -1
  46. package/dist/i18n/locales/tr.js +2 -2
  47. package/dist/i18n/locales/tr.js.map +1 -1
  48. package/dist/i18n/locales/uk.js +2 -2
  49. package/dist/i18n/locales/uk.js.map +1 -1
  50. package/dist/i18n/locales/vi.js +2 -2
  51. package/dist/i18n/locales/vi.js.map +1 -1
  52. package/dist/i18n/locales/zh-CN.js +2 -2
  53. package/dist/i18n/locales/zh-CN.js.map +1 -1
  54. package/dist/i18n/locales/zh-TW.js +2 -2
  55. package/dist/i18n/locales/zh-TW.js.map +1 -1
  56. package/dist/memory/auto-extract.js +36 -36
  57. package/dist/memory/insights.js +24 -24
  58. package/dist/memory/memory-agent.js +55 -55
  59. package/dist/personas/conductor.js +12 -12
  60. package/dist/tools/apply-plan.js +2 -2
  61. package/dist/tools/apply-plan.js.map +1 -1
  62. package/dist/tools/benchmark.d.ts.map +1 -1
  63. package/dist/tools/benchmark.js +4 -1
  64. package/dist/tools/benchmark.js.map +1 -1
  65. package/dist/tools/blender/runner-py.js +443 -443
  66. package/dist/tools/debug-logs.d.ts.map +1 -1
  67. package/dist/tools/debug-logs.js +4 -1
  68. package/dist/tools/debug-logs.js.map +1 -1
  69. package/dist/tools/design-docs.js +186 -186
  70. package/dist/tools/doc-generate.js +2 -2
  71. package/dist/tools/doc-generate.js.map +1 -1
  72. package/dist/tools/document-author.js +3 -3
  73. package/dist/tools/document-author.js.map +1 -1
  74. package/dist/tools/document-manage.js +4 -4
  75. package/dist/tools/document-manage.js.map +1 -1
  76. package/dist/tools/env-write.d.ts.map +1 -1
  77. package/dist/tools/env-write.js +2 -1
  78. package/dist/tools/env-write.js.map +1 -1
  79. package/dist/tools/file-edit.js +2 -2
  80. package/dist/tools/file-edit.js.map +1 -1
  81. package/dist/tools/file-write.js +2 -2
  82. package/dist/tools/file-write.js.map +1 -1
  83. package/dist/tools/generate-image.d.ts.map +1 -1
  84. package/dist/tools/generate-image.js +3 -2
  85. package/dist/tools/generate-image.js.map +1 -1
  86. package/dist/tools/generate-video.d.ts.map +1 -1
  87. package/dist/tools/generate-video.js +3 -2
  88. package/dist/tools/generate-video.js.map +1 -1
  89. package/dist/tools/generate-voice.d.ts.map +1 -1
  90. package/dist/tools/generate-voice.js +3 -2
  91. package/dist/tools/generate-voice.js.map +1 -1
  92. package/dist/tools/gimp/runner-py.js +740 -740
  93. package/dist/tools/git.d.ts.map +1 -1
  94. package/dist/tools/git.js +43 -1
  95. package/dist/tools/git.js.map +1 -1
  96. package/dist/tools/remove-background.d.ts.map +1 -1
  97. package/dist/tools/remove-background.js +4 -3
  98. package/dist/tools/remove-background.js.map +1 -1
  99. package/dist/tools/security.d.ts +5 -0
  100. package/dist/tools/security.d.ts.map +1 -1
  101. package/dist/tools/security.js +73 -8
  102. package/dist/tools/security.js.map +1 -1
  103. package/dist/tools/test-generate.js +2 -2
  104. package/dist/tools/test-generate.js.map +1 -1
  105. package/dist/tools/test-run.d.ts.map +1 -1
  106. package/dist/tools/test-run.js +4 -1
  107. package/dist/tools/test-run.js.map +1 -1
  108. package/package.json +6 -1
  109. package/dist/tools/memory-delete.d.ts +0 -11
  110. package/dist/tools/memory-delete.d.ts.map +0 -1
  111. package/dist/tools/memory-delete.js +0 -54
  112. package/dist/tools/memory-delete.js.map +0 -1
  113. package/dist/tools/memory-recall.d.ts +0 -11
  114. package/dist/tools/memory-recall.d.ts.map +0 -1
  115. package/dist/tools/memory-recall.js +0 -101
  116. package/dist/tools/memory-recall.js.map +0 -1
  117. package/dist/tools/memory-save.d.ts +0 -11
  118. package/dist/tools/memory-save.d.ts.map +0 -1
  119. package/dist/tools/memory-save.js +0 -112
  120. package/dist/tools/memory-save.js.map +0 -1
  121. package/dist/tools/memory-update.d.ts +0 -11
  122. package/dist/tools/memory-update.d.ts.map +0 -1
  123. package/dist/tools/memory-update.js +0 -88
  124. package/dist/tools/memory-update.js.map +0 -1
@@ -16,450 +16,450 @@ import { KIT_PY } from '../../brand/kit-py.js';
16
16
  * Needs: bpy, os, ASSET_DIR in scope.
17
17
  */
18
18
  // prettier-ignore
19
- export const BLENDER_HELPERS_PY = String.raw `# ── Helpers Ava calls from her script ────────────────────────────────────────
20
- # Texturing is where she lost twenty minutes on the first real model (3 Nov
21
- # 2026): a beautiful live shader that exports as nothing, a dozen runs on UV
22
- # layout, and Blender reporting only EEVEE when asked which engines exist —
23
- # so she concluded Cycles (which baking needs) was missing. It is not. These
24
- # do the known-good versions of both steps in one line each.
25
-
26
- import math as _math
27
-
28
- def _meshes(objects):
29
- if objects is None:
30
- return [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.visible_get()]
31
- return [bpy.data.objects[o] if isinstance(o, str) else o for o in objects]
32
-
33
- def _select_only(obs):
34
- if bpy.context.object and bpy.context.object.mode != 'OBJECT':
35
- bpy.ops.object.mode_set(mode='OBJECT')
36
- for o in bpy.context.scene.objects:
37
- o.select_set(False)
38
- for o in obs:
39
- o.select_set(True)
40
- bpy.context.view_layer.objects.active = obs[0]
41
-
42
- def _keep_live_uvs(obs):
43
- """Before a new layout goes in, keep the one the live shader was written
44
- against. A shader can READ its UVs (her barrel told wood from iron by
45
- position on the layout), so replacing them silently scrambles the look —
46
- found the first time this ran on a real model, 3 Nov 2026. The old layout
47
- is copied to 'LiveUV' and every material pointed at it explicitly; the new
48
- packed layout then takes the FIRST slot, the one game engines read."""
49
- mats = set()
50
- for o in obs:
51
- uvs = o.data.uv_layers
52
- if not uvs:
53
- uvs.new(name='UVMap')
54
- continue
55
- if 'LiveUV' not in uvs:
56
- uvs.active = uvs[0]
57
- uvs.new(name='LiveUV', do_init=True) # copies the current layout
58
- uvs.active = uvs[0]
59
- for sl in o.material_slots:
60
- if sl.material and sl.material.use_nodes and not sl.material.get('ava_baked'):
61
- mats.add(sl.material)
62
- for m in mats:
63
- nt = m.node_tree
64
- for n in list(nt.nodes):
65
- if n.bl_idname == 'ShaderNodeTexCoord' and n.outputs['UV'].links:
66
- uvn = nt.nodes.new('ShaderNodeUVMap'); uvn.uv_map = 'LiveUV'
67
- uvn.location = (n.location.x, n.location.y - 180)
68
- for l in list(n.outputs['UV'].links):
69
- nt.links.new(uvn.outputs['UV'], l.to_socket)
70
- elif n.bl_idname == 'ShaderNodeUVMap' and n.uv_map in ('', 'UVMap'):
71
- n.uv_map = 'LiveUV'
72
- elif n.bl_idname == 'ShaderNodeTexImage' and not n.inputs['Vector'].links:
73
- uvn = nt.nodes.new('ShaderNodeUVMap'); uvn.uv_map = 'LiveUV'
74
- nt.links.new(uvn.outputs['UV'], n.inputs['Vector'])
75
- return mats
76
-
77
- def ava_unwrap(objects=None, margin=0.004, angle=66):
78
- """Unwrap every mesh (or the ones named) and pack ALL their UV islands into
79
- one shared 0-1 square with no overlaps — what one texture set for the
80
- whole asset needs. Safe for a shader that reads its UVs: the old layout is
81
- kept as 'LiveUV' and the materials keep reading it, so the look does not
82
- change. Returns the number of objects unwrapped."""
83
- obs = _meshes(objects)
84
- if not obs:
85
- raise ValueError('ava_unwrap: no mesh objects to unwrap')
86
- _keep_live_uvs(obs)
87
- _select_only(obs)
88
- bpy.ops.object.mode_set(mode='EDIT')
89
- bpy.ops.mesh.select_all(action='SELECT')
90
- bpy.ops.uv.smart_project(angle_limit=_math.radians(angle), island_margin=margin)
91
- bpy.ops.uv.select_all(action='SELECT')
92
- bpy.ops.uv.pack_islands(margin=margin, rotate=True)
93
- bpy.ops.object.mode_set(mode='OBJECT')
94
- print(f'AVA_UNWRAP: {len(obs)} objects packed into one UV square (old layout kept as LiveUV)')
95
- return len(obs)
96
-
97
- def _principled(mat):
98
- out = next((n for n in mat.node_tree.nodes if n.type == 'OUTPUT_MATERIAL' and n.is_active_output), None) \
99
- or next((n for n in mat.node_tree.nodes if n.type == 'OUTPUT_MATERIAL'), None)
100
- if not out or not out.inputs['Surface'].links:
101
- return None, None
102
- node = out.inputs['Surface'].links[0].from_node
103
- return (node if node.type == 'BSDF_PRINCIPLED' else None), out
104
-
105
- def ava_bake(objects=None, size=2048, maps=('base_color', 'roughness', 'metallic', 'normal'), samples=16):
106
- """Bake the live materials into image textures in ASSET_DIR/textures and
107
- put a clean, export-ready material on the objects — the step procedural
108
- shaders need before FBX/glTF, because live nodes do not export.
109
-
110
- Works per channel the proven way: colour, roughness and metal are baked
111
- through an emission pass (a plain diffuse bake turns metal black); the
112
- normal pass keeps bumps and carved detail. The live materials stay in the
113
- file, so changing the look and calling ava_bake() again re-bakes from them.
114
- Needs non-overlapping UVs across the objects — ava_unwrap() gives that."""
115
- import os as _os
116
- obs = _meshes(objects)
117
- if not obs:
118
- raise ValueError('ava_bake: no mesh objects to bake')
119
- for o in obs:
120
- if not o.data.uv_layers:
121
- raise ValueError(f'ava_bake: "{o.name}" has no UVs — call ava_unwrap() first')
122
- o.data.uv_layers.active = o.data.uv_layers[0] # the bake lands on the first map
123
- # Re-baking: put the live materials back on first.
124
- src = o.get('ava_live_materials')
125
- if src:
126
- for i, nm in enumerate(src):
127
- if nm in bpy.data.materials and i < len(o.material_slots):
128
- o.material_slots[i].material = bpy.data.materials[nm]
129
-
130
- mats = []
131
- for o in obs:
132
- for slot in o.material_slots:
133
- if slot.material and slot.material not in mats:
134
- mats.append(slot.material)
135
- if not mats:
136
- raise ValueError('ava_bake: the objects have no materials to bake')
137
- for m in mats:
138
- m.use_nodes = True
139
- if _principled(m)[0] is None:
140
- raise ValueError(f'ava_bake: material "{m.name}" does not end in a Principled BSDF')
141
-
142
- sc = bpy.context.scene
143
- prev_engine = sc.render.engine
144
- sc.render.engine = 'CYCLES' # baking is Cycles-only; it IS available
145
- sc.cycles.device = 'CPU'
146
- sc.cycles.samples = samples
147
- sc.render.bake.margin = 8
148
- _select_only(obs)
149
-
150
- asset = _os.path.basename(ASSET_DIR.rstrip('\\/'))
151
- tex_dir = _os.path.join(ASSET_DIR, 'textures')
152
- _os.makedirs(tex_dir, exist_ok=True)
153
- SPEC = {
154
- 'base_color': ('Base Color', 'BaseColor', False),
155
- 'roughness': ('Roughness', 'Roughness', True),
156
- 'metallic': ('Metallic', 'Metallic', True),
157
- 'normal': (None, 'Normal', True),
158
- }
159
- images = {}
160
- for key in maps:
161
- if key not in SPEC:
162
- raise ValueError(f'ava_bake: unknown map "{key}" — use base_color, roughness, metallic, normal')
163
- socket_name, label, data = SPEC[key]
164
- img = bpy.data.images.new(f'{asset}_{label}', size, size, alpha=False)
165
- if data:
166
- img.colorspace_settings.name = 'Non-Color'
167
- temp = [] # (material, nodes added, links to restore)
168
- for m in mats:
169
- nt = m.node_tree
170
- bsdf, out = _principled(m)
171
- tn = nt.nodes.new('ShaderNodeTexImage'); tn.image = img
172
- nt.nodes.active = tn
173
- added = [tn]; restore = None
174
- if socket_name:
175
- # Route this channel into an emission shader and bake EMIT:
176
- # exact values, metal included.
177
- sock = bsdf.inputs[socket_name]
178
- em = nt.nodes.new('ShaderNodeEmission'); added.append(em)
179
- if sock.links:
180
- nt.links.new(sock.links[0].from_socket, em.inputs['Color'])
181
- else:
182
- v = sock.default_value
183
- em.inputs['Color'].default_value = tuple(v) if hasattr(v, '__len__') else (v, v, v, 1.0)
184
- restore = out.inputs['Surface'].links[0].from_socket
185
- nt.links.new(em.outputs['Emission'], out.inputs['Surface'])
186
- temp.append((m, added, restore, out))
187
- if socket_name:
188
- bpy.ops.object.bake(type='EMIT')
189
- else:
190
- bpy.ops.object.bake(type='NORMAL', normal_space='TANGENT')
191
- for m, added, restore, out in temp:
192
- if restore is not None:
193
- m.node_tree.links.new(restore, out.inputs['Surface'])
194
- for n in added:
195
- m.node_tree.nodes.remove(n)
196
- img.filepath_raw = _os.path.join(tex_dir, f'{asset}_{label}.png')
197
- img.file_format = 'PNG'
198
- img.save()
199
- images[key] = img
200
-
201
- # The export-ready material: the baked images, nothing live.
202
- baked = bpy.data.materials.get(f'M_{asset}_Baked') or bpy.data.materials.new(f'M_{asset}_Baked')
203
- baked.use_nodes = True
204
- nt = baked.node_tree; nt.nodes.clear()
205
- bsdf = nt.nodes.new('ShaderNodeBsdfPrincipled'); bsdf.location = (300, 0)
206
- out = nt.nodes.new('ShaderNodeOutputMaterial'); out.location = (600, 0)
207
- nt.links.new(bsdf.outputs['BSDF'], out.inputs['Surface'])
208
- y = 300
209
- for key, img in images.items():
210
- tn = nt.nodes.new('ShaderNodeTexImage'); tn.image = img; tn.location = (-300, y); y -= 280
211
- if key == 'normal':
212
- nm = nt.nodes.new('ShaderNodeNormalMap'); nm.location = (0, -500)
213
- nt.links.new(tn.outputs['Color'], nm.inputs['Color'])
214
- nt.links.new(nm.outputs['Normal'], bsdf.inputs['Normal'])
215
- else:
216
- nt.links.new(tn.outputs['Color'], bsdf.inputs[SPEC[key][0]])
217
- baked['ava_baked'] = True
218
-
219
- for o in obs:
220
- live = [s.material.name if s.material else '' for s in o.material_slots]
221
- for nm in live:
222
- if nm in bpy.data.materials:
223
- bpy.data.materials[nm].use_fake_user = True # kept for re-baking
224
- o['ava_live_materials'] = live
225
- for slot in o.material_slots:
226
- slot.material = baked
227
-
228
- sc.render.engine = prev_engine
229
- files = [f'textures/{_os.path.basename(i.filepath_raw)}' for i in images.values()]
230
- print(f'AVA_BAKE: {len(obs)} objects, {len(mats)} live material(s) -> {", ".join(files)} on {baked.name}')
231
- return files
19
+ export const BLENDER_HELPERS_PY = String.raw `# ── Helpers Ava calls from her script ────────────────────────────────────────
20
+ # Texturing is where she lost twenty minutes on the first real model (3 Nov
21
+ # 2026): a beautiful live shader that exports as nothing, a dozen runs on UV
22
+ # layout, and Blender reporting only EEVEE when asked which engines exist —
23
+ # so she concluded Cycles (which baking needs) was missing. It is not. These
24
+ # do the known-good versions of both steps in one line each.
25
+
26
+ import math as _math
27
+
28
+ def _meshes(objects):
29
+ if objects is None:
30
+ return [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.visible_get()]
31
+ return [bpy.data.objects[o] if isinstance(o, str) else o for o in objects]
32
+
33
+ def _select_only(obs):
34
+ if bpy.context.object and bpy.context.object.mode != 'OBJECT':
35
+ bpy.ops.object.mode_set(mode='OBJECT')
36
+ for o in bpy.context.scene.objects:
37
+ o.select_set(False)
38
+ for o in obs:
39
+ o.select_set(True)
40
+ bpy.context.view_layer.objects.active = obs[0]
41
+
42
+ def _keep_live_uvs(obs):
43
+ """Before a new layout goes in, keep the one the live shader was written
44
+ against. A shader can READ its UVs (her barrel told wood from iron by
45
+ position on the layout), so replacing them silently scrambles the look —
46
+ found the first time this ran on a real model, 3 Nov 2026. The old layout
47
+ is copied to 'LiveUV' and every material pointed at it explicitly; the new
48
+ packed layout then takes the FIRST slot, the one game engines read."""
49
+ mats = set()
50
+ for o in obs:
51
+ uvs = o.data.uv_layers
52
+ if not uvs:
53
+ uvs.new(name='UVMap')
54
+ continue
55
+ if 'LiveUV' not in uvs:
56
+ uvs.active = uvs[0]
57
+ uvs.new(name='LiveUV', do_init=True) # copies the current layout
58
+ uvs.active = uvs[0]
59
+ for sl in o.material_slots:
60
+ if sl.material and sl.material.use_nodes and not sl.material.get('ava_baked'):
61
+ mats.add(sl.material)
62
+ for m in mats:
63
+ nt = m.node_tree
64
+ for n in list(nt.nodes):
65
+ if n.bl_idname == 'ShaderNodeTexCoord' and n.outputs['UV'].links:
66
+ uvn = nt.nodes.new('ShaderNodeUVMap'); uvn.uv_map = 'LiveUV'
67
+ uvn.location = (n.location.x, n.location.y - 180)
68
+ for l in list(n.outputs['UV'].links):
69
+ nt.links.new(uvn.outputs['UV'], l.to_socket)
70
+ elif n.bl_idname == 'ShaderNodeUVMap' and n.uv_map in ('', 'UVMap'):
71
+ n.uv_map = 'LiveUV'
72
+ elif n.bl_idname == 'ShaderNodeTexImage' and not n.inputs['Vector'].links:
73
+ uvn = nt.nodes.new('ShaderNodeUVMap'); uvn.uv_map = 'LiveUV'
74
+ nt.links.new(uvn.outputs['UV'], n.inputs['Vector'])
75
+ return mats
76
+
77
+ def ava_unwrap(objects=None, margin=0.004, angle=66):
78
+ """Unwrap every mesh (or the ones named) and pack ALL their UV islands into
79
+ one shared 0-1 square with no overlaps — what one texture set for the
80
+ whole asset needs. Safe for a shader that reads its UVs: the old layout is
81
+ kept as 'LiveUV' and the materials keep reading it, so the look does not
82
+ change. Returns the number of objects unwrapped."""
83
+ obs = _meshes(objects)
84
+ if not obs:
85
+ raise ValueError('ava_unwrap: no mesh objects to unwrap')
86
+ _keep_live_uvs(obs)
87
+ _select_only(obs)
88
+ bpy.ops.object.mode_set(mode='EDIT')
89
+ bpy.ops.mesh.select_all(action='SELECT')
90
+ bpy.ops.uv.smart_project(angle_limit=_math.radians(angle), island_margin=margin)
91
+ bpy.ops.uv.select_all(action='SELECT')
92
+ bpy.ops.uv.pack_islands(margin=margin, rotate=True)
93
+ bpy.ops.object.mode_set(mode='OBJECT')
94
+ print(f'AVA_UNWRAP: {len(obs)} objects packed into one UV square (old layout kept as LiveUV)')
95
+ return len(obs)
96
+
97
+ def _principled(mat):
98
+ out = next((n for n in mat.node_tree.nodes if n.type == 'OUTPUT_MATERIAL' and n.is_active_output), None) \
99
+ or next((n for n in mat.node_tree.nodes if n.type == 'OUTPUT_MATERIAL'), None)
100
+ if not out or not out.inputs['Surface'].links:
101
+ return None, None
102
+ node = out.inputs['Surface'].links[0].from_node
103
+ return (node if node.type == 'BSDF_PRINCIPLED' else None), out
104
+
105
+ def ava_bake(objects=None, size=2048, maps=('base_color', 'roughness', 'metallic', 'normal'), samples=16):
106
+ """Bake the live materials into image textures in ASSET_DIR/textures and
107
+ put a clean, export-ready material on the objects — the step procedural
108
+ shaders need before FBX/glTF, because live nodes do not export.
109
+
110
+ Works per channel the proven way: colour, roughness and metal are baked
111
+ through an emission pass (a plain diffuse bake turns metal black); the
112
+ normal pass keeps bumps and carved detail. The live materials stay in the
113
+ file, so changing the look and calling ava_bake() again re-bakes from them.
114
+ Needs non-overlapping UVs across the objects — ava_unwrap() gives that."""
115
+ import os as _os
116
+ obs = _meshes(objects)
117
+ if not obs:
118
+ raise ValueError('ava_bake: no mesh objects to bake')
119
+ for o in obs:
120
+ if not o.data.uv_layers:
121
+ raise ValueError(f'ava_bake: "{o.name}" has no UVs — call ava_unwrap() first')
122
+ o.data.uv_layers.active = o.data.uv_layers[0] # the bake lands on the first map
123
+ # Re-baking: put the live materials back on first.
124
+ src = o.get('ava_live_materials')
125
+ if src:
126
+ for i, nm in enumerate(src):
127
+ if nm in bpy.data.materials and i < len(o.material_slots):
128
+ o.material_slots[i].material = bpy.data.materials[nm]
129
+
130
+ mats = []
131
+ for o in obs:
132
+ for slot in o.material_slots:
133
+ if slot.material and slot.material not in mats:
134
+ mats.append(slot.material)
135
+ if not mats:
136
+ raise ValueError('ava_bake: the objects have no materials to bake')
137
+ for m in mats:
138
+ m.use_nodes = True
139
+ if _principled(m)[0] is None:
140
+ raise ValueError(f'ava_bake: material "{m.name}" does not end in a Principled BSDF')
141
+
142
+ sc = bpy.context.scene
143
+ prev_engine = sc.render.engine
144
+ sc.render.engine = 'CYCLES' # baking is Cycles-only; it IS available
145
+ sc.cycles.device = 'CPU'
146
+ sc.cycles.samples = samples
147
+ sc.render.bake.margin = 8
148
+ _select_only(obs)
149
+
150
+ asset = _os.path.basename(ASSET_DIR.rstrip('\\/'))
151
+ tex_dir = _os.path.join(ASSET_DIR, 'textures')
152
+ _os.makedirs(tex_dir, exist_ok=True)
153
+ SPEC = {
154
+ 'base_color': ('Base Color', 'BaseColor', False),
155
+ 'roughness': ('Roughness', 'Roughness', True),
156
+ 'metallic': ('Metallic', 'Metallic', True),
157
+ 'normal': (None, 'Normal', True),
158
+ }
159
+ images = {}
160
+ for key in maps:
161
+ if key not in SPEC:
162
+ raise ValueError(f'ava_bake: unknown map "{key}" — use base_color, roughness, metallic, normal')
163
+ socket_name, label, data = SPEC[key]
164
+ img = bpy.data.images.new(f'{asset}_{label}', size, size, alpha=False)
165
+ if data:
166
+ img.colorspace_settings.name = 'Non-Color'
167
+ temp = [] # (material, nodes added, links to restore)
168
+ for m in mats:
169
+ nt = m.node_tree
170
+ bsdf, out = _principled(m)
171
+ tn = nt.nodes.new('ShaderNodeTexImage'); tn.image = img
172
+ nt.nodes.active = tn
173
+ added = [tn]; restore = None
174
+ if socket_name:
175
+ # Route this channel into an emission shader and bake EMIT:
176
+ # exact values, metal included.
177
+ sock = bsdf.inputs[socket_name]
178
+ em = nt.nodes.new('ShaderNodeEmission'); added.append(em)
179
+ if sock.links:
180
+ nt.links.new(sock.links[0].from_socket, em.inputs['Color'])
181
+ else:
182
+ v = sock.default_value
183
+ em.inputs['Color'].default_value = tuple(v) if hasattr(v, '__len__') else (v, v, v, 1.0)
184
+ restore = out.inputs['Surface'].links[0].from_socket
185
+ nt.links.new(em.outputs['Emission'], out.inputs['Surface'])
186
+ temp.append((m, added, restore, out))
187
+ if socket_name:
188
+ bpy.ops.object.bake(type='EMIT')
189
+ else:
190
+ bpy.ops.object.bake(type='NORMAL', normal_space='TANGENT')
191
+ for m, added, restore, out in temp:
192
+ if restore is not None:
193
+ m.node_tree.links.new(restore, out.inputs['Surface'])
194
+ for n in added:
195
+ m.node_tree.nodes.remove(n)
196
+ img.filepath_raw = _os.path.join(tex_dir, f'{asset}_{label}.png')
197
+ img.file_format = 'PNG'
198
+ img.save()
199
+ images[key] = img
200
+
201
+ # The export-ready material: the baked images, nothing live.
202
+ baked = bpy.data.materials.get(f'M_{asset}_Baked') or bpy.data.materials.new(f'M_{asset}_Baked')
203
+ baked.use_nodes = True
204
+ nt = baked.node_tree; nt.nodes.clear()
205
+ bsdf = nt.nodes.new('ShaderNodeBsdfPrincipled'); bsdf.location = (300, 0)
206
+ out = nt.nodes.new('ShaderNodeOutputMaterial'); out.location = (600, 0)
207
+ nt.links.new(bsdf.outputs['BSDF'], out.inputs['Surface'])
208
+ y = 300
209
+ for key, img in images.items():
210
+ tn = nt.nodes.new('ShaderNodeTexImage'); tn.image = img; tn.location = (-300, y); y -= 280
211
+ if key == 'normal':
212
+ nm = nt.nodes.new('ShaderNodeNormalMap'); nm.location = (0, -500)
213
+ nt.links.new(tn.outputs['Color'], nm.inputs['Color'])
214
+ nt.links.new(nm.outputs['Normal'], bsdf.inputs['Normal'])
215
+ else:
216
+ nt.links.new(tn.outputs['Color'], bsdf.inputs[SPEC[key][0]])
217
+ baked['ava_baked'] = True
218
+
219
+ for o in obs:
220
+ live = [s.material.name if s.material else '' for s in o.material_slots]
221
+ for nm in live:
222
+ if nm in bpy.data.materials:
223
+ bpy.data.materials[nm].use_fake_user = True # kept for re-baking
224
+ o['ava_live_materials'] = live
225
+ for slot in o.material_slots:
226
+ slot.material = baked
227
+
228
+ sc.render.engine = prev_engine
229
+ files = [f'textures/{_os.path.basename(i.filepath_raw)}' for i in images.values()]
230
+ print(f'AVA_BAKE: {len(obs)} objects, {len(mats)} live material(s) -> {", ".join(files)} on {baked.name}')
231
+ return files
232
232
  `;
233
233
  // prettier-ignore
234
- export const BLENDER_RUNNER_PY = String.raw `# Ava's Blender runner. Started by design_build_model as:
235
- # blender -b [model.blend] --factory-startup --disable-autoexec --python runner.py -- job.json
236
- # It prepares the scene, installs the guard, runs Ava's script, then saves,
237
- # exports and renders a preview. The last line it prints is the result.
238
- import sys, os, json, time, traceback, tempfile, shutil, math
239
-
240
- JOB = json.load(open(sys.argv[sys.argv.index('--') + 1], encoding='utf-8'))
241
- ASSET_DIR = os.path.realpath(JOB['assetDir'])
242
- NAME = JOB['name']
243
- BLEND = os.path.join(ASSET_DIR, NAME + '.blend')
244
- STARTED = time.time()
245
- result = {'ok': False, 'files': [], 'warnings': []}
246
- ${KIT_PY}
247
-
248
- def emit():
249
- sys.stdout.write('\n@@AVA_RESULT@@' + json.dumps(result) + '\n')
250
- sys.stdout.flush()
251
-
252
- import bpy
253
- sys.dont_write_bytecode = True
254
- bpy.context.preferences.filepaths.save_version = 0 # no .blend1 clutter beside the model
255
-
256
- if not JOB['continue']:
257
- bpy.ops.wm.read_factory_settings(use_empty=True) # a new canvas: nothing in it
258
- for sc in bpy.data.scenes:
259
- sc.render.filepath = os.path.join(ASSET_DIR, 'render_')
260
-
261
- # ── The guard ────────────────────────────────────────────────────────────────
262
- # Python audit hooks see every file write, process start and network call made
263
- # from Python, and cannot be removed once installed. A guard, not a sandbox:
264
- # Blender's own C code (saving a .blend, writing a render) is not seen here,
265
- # which is why the tool also refuses absolute paths in the script itself.
266
- # Writes are allowed in the model folder and in Blender's OWN per-run temp
267
- # folder (blender_xxxx), not the whole system temp. Python's tempfile is
268
- # pointed there too, so any library that needs scratch space stays inside it.
269
- _BTMP = bpy.app.tempdir or os.path.join(ASSET_DIR, '.tmp')
270
- os.makedirs(_BTMP, exist_ok=True)
271
- tempfile.tempdir = _BTMP
272
- _ALLOWED = [os.path.normcase(os.path.realpath(p)) for p in {ASSET_DIR, _BTMP}]
273
-
274
- def _inside(p):
275
- try:
276
- rp = os.path.normcase(os.path.realpath(os.fsdecode(p)))
277
- except Exception:
278
- return False
279
- return any(rp == a or rp.startswith(a.rstrip(os.sep) + os.sep) for a in _ALLOWED)
280
-
281
- _BLOCKED = {
282
- 'subprocess.Popen': 'starting other programs', 'os.system': 'starting other programs',
283
- 'os.exec': 'starting other programs', 'os.posix_spawn': 'starting other programs',
284
- 'os.spawn': 'starting other programs', 'os.startfile': 'opening files in other programs',
285
- 'os.kill': 'stopping other programs', 'webbrowser.open': 'opening a browser',
286
- 'socket.connect': 'network access', 'socket.bind': 'network access',
287
- 'socket.getaddrinfo': 'network access', 'socket.gethostbyname': 'network access',
288
- 'urllib.Request': 'network access', 'ctypes.dlopen': 'loading native code',
289
- 'ctypes.dlsym': 'calling native code', 'ctypes.call_function': 'calling native code',
290
- 'winreg.CreateKey': 'changing the registry', 'winreg.SetValue': 'changing the registry',
291
- 'winreg.DeleteKey': 'changing the registry', 'winreg.DeleteValue': 'changing the registry',
292
- }
293
- _WRITE_ARGS = { # event -> indexes of the paths it writes or removes
294
- 'os.remove': (0,), 'os.rmdir': (0,), 'os.mkdir': (0,), 'os.chmod': (0,),
295
- 'os.truncate': (0,), 'os.utime': (0,), 'shutil.rmtree': (0,),
296
- 'os.rename': (0, 1), 'shutil.move': (0, 1), 'shutil.copyfile': (1,),
297
- 'shutil.copytree': (1,), 'os.symlink': (1,), 'os.link': (1,),
298
- }
299
- _WRITE_FLAGS = os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_TRUNC
300
-
301
- def _refuse(why):
302
- raise PermissionError(f'Blocked by the Design Studio guard: {why}. '
303
- f'Scripts here may only build the model and write inside its own folder (ASSET_DIR).')
304
-
305
- def _hook(event, args):
306
- if event in _BLOCKED:
307
- _refuse(_BLOCKED[event])
308
- if event == 'open':
309
- path, mode, flags = (list(args) + [None, None, 0])[:3]
310
- if path is None or isinstance(path, int):
311
- return
312
- writing = (isinstance(mode, str) and any(c in mode for c in 'wax+')) or \
313
- (mode is None and isinstance(flags, int) and flags & _WRITE_FLAGS)
314
- if writing and not _inside(path):
315
- _refuse(f'writing outside the model folder ({os.fsdecode(path)})')
316
- elif event in _WRITE_ARGS:
317
- for i in _WRITE_ARGS[event]:
318
- if i < len(args) and args[i] is not None and not isinstance(args[i], int) and not _inside(args[i]):
319
- _refuse(f'changing files outside the model folder ({os.fsdecode(args[i])})')
320
-
321
- # Blender's own exporters load native code when first imported (the glTF one
322
- # pulls in ctypes for Draco). Import them BEFORE the guard goes up, so the guard
323
- # only ever sees what Ava's script does.
324
- import ctypes # noqa: F401
325
- for _mod in ('io_scene_gltf2.blender.exp.export', 'io_scene_fbx.export_fbx_bin'):
326
- try:
327
- __import__(_mod)
328
- except Exception as e:
329
- result['warnings'].append(f'Could not preload {_mod}: {e}')
330
-
331
- sys.addaudithook(_hook)
332
-
333
- ${BLENDER_HELPERS_PY}
334
- # ── Ava's script ─────────────────────────────────────────────────────────────
335
- script_path = os.path.join(ASSET_DIR, 'script.py')
336
- ns = {'__name__': '__main__', '__file__': script_path, 'ASSET_DIR': ASSET_DIR, 'bpy': bpy, 'KIT': KIT,
337
- 'ava_unwrap': ava_unwrap, 'ava_bake': ava_bake}
338
- try:
339
- with open(script_path, encoding='utf-8') as f:
340
- code = compile(f.read(), 'script.py', 'exec')
341
- exec(code, ns)
342
- except BaseException as e: # SystemExit included: the saved model must stay as it was
343
- result['error'] = ''.join(traceback.format_exception(type(e), e, e.__traceback__)[-12:])
344
- emit()
345
- sys.exit(0)
346
-
347
- # ── Save, export, measure ────────────────────────────────────────────────────
348
- try:
349
- if os.path.exists(BLEND): # keep the last 5 versions so a bad run can be undone
350
- vdir = os.path.join(ASSET_DIR, 'versions')
351
- os.makedirs(vdir, exist_ok=True)
352
- shutil.copy2(BLEND, os.path.join(vdir, time.strftime('%Y%m%d-%H%M%S') + '.blend'))
353
- for old in sorted(os.listdir(vdir))[:-5]:
354
- os.remove(os.path.join(vdir, old))
355
- bpy.ops.wm.save_as_mainfile(filepath=BLEND)
356
- result['files'].append(NAME + '.blend')
357
-
358
- meshes = [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.visible_get()]
359
- deps = bpy.context.evaluated_depsgraph_get()
360
- tris = 0
361
- lo = [math.inf] * 3; hi = [-math.inf] * 3
362
- for o in meshes:
363
- ev = o.evaluated_get(deps)
364
- m = ev.to_mesh()
365
- m.calc_loop_triangles()
366
- tris += len(m.loop_triangles)
367
- for v in m.vertices:
368
- w = ev.matrix_world @ v.co
369
- for i in range(3):
370
- lo[i] = min(lo[i], w[i]); hi[i] = max(hi[i], w[i])
371
- ev.to_mesh_clear()
372
- result['objects'] = len(meshes)
373
- result['triangles'] = tris
374
- if meshes:
375
- result['size_m'] = [round(hi[i] - lo[i], 3) for i in range(3)]
376
- result['center'] = [(hi[i] + lo[i]) / 2 for i in range(3)]
377
-
378
- glb = os.path.join(ASSET_DIR, NAME + '.glb')
379
- bpy.ops.export_scene.gltf(filepath=glb, export_format='GLB', use_selection=False, export_apply=True)
380
- result['files'].append(NAME + '.glb')
381
- if JOB.get('fbx'):
382
- fbx = os.path.join(ASSET_DIR, NAME + '.fbx')
383
- # mesh_smooth_type='FACE': without smoothing groups Unreal warns on every
384
- # part (seen importing the wooden crate into 5.9, 19 Nov).
385
- bpy.ops.export_scene.fbx(filepath=fbx, use_selection=False, apply_scale_options='FBX_SCALE_ALL', path_mode='COPY', embed_textures=True, mesh_smooth_type='FACE')
386
- result['files'].append(NAME + '.fbx')
387
- # Live shaders do not export. Say so whenever the export will reach an
388
- # engine bare — the gap she lost twenty minutes in on the first model.
389
- _PROC = ('ShaderNodeTexNoise', 'ShaderNodeTexVoronoi', 'ShaderNodeTexWave', 'ShaderNodeTexMusgrave',
390
- 'ShaderNodeTexGradient', 'ShaderNodeTexMagic', 'ShaderNodeTexChecker', 'ShaderNodeTexBrick',
391
- 'ShaderNodeMath', 'ShaderNodeVectorMath', 'ShaderNodeValToRGB', 'ShaderNodeBump', 'ShaderNodeMix')
392
- _live = sorted({sl.material.name for o in meshes for sl in o.material_slots
393
- if sl.material and sl.material.use_nodes and not sl.material.get('ava_baked')
394
- and any(n.bl_idname in _PROC for n in sl.material.node_tree.nodes)})
395
- if _live:
396
- result['warnings'].append(
397
- 'The exported model carries NONE of the live shader detail in ' + ', '.join(_live) +
398
- ' — game engines and the Library viewer will show it flat. Bake it: ava_unwrap() if the UVs overlap, then ava_bake().')
399
- _tex = os.path.join(ASSET_DIR, 'textures')
400
- if os.path.isdir(_tex):
401
- result['files'] += ['textures/' + f for f in sorted(os.listdir(_tex))]
402
- # For the making record: fonts and pictures in the SAVED model, whoever put
403
- # them there (her script or the person by hand), and kit logos she used.
404
- try:
405
- result['fonts'] = sorted({(f.name if f.filepath in ('', '<builtin>') else
406
- os.path.basename(bpy.path.abspath(f.filepath)))
407
- + ('|builtin' if f.filepath in ('', '<builtin>') else '')
408
- for f in bpy.data.fonts if f.users})
409
- result['images_used'] = sorted({os.path.basename(bpy.path.abspath(i.filepath)) for i in bpy.data.images
410
- if i.users and i.filepath and i.source == 'FILE'
411
- and os.path.dirname(os.path.normcase(os.path.abspath(bpy.path.abspath(i.filepath)))) != os.path.normcase(os.path.abspath(_tex))})
412
- except Exception as e:
413
- result['warnings'].append(f'Could not list fonts and pictures for the making record: {e}')
414
- result['kit_logos'] = list(KIT_LOGOS_USED)
415
- except BaseException as e:
416
- result['error'] = 'The script ran, but saving or exporting failed:\n' + \
417
- ''.join(traceback.format_exception(type(e), e, e.__traceback__)[-8:])
418
- emit()
419
- sys.exit(0)
420
-
421
- # ── Preview ──────────────────────────────────────────────────────────────────
422
- # Her own render wins. Otherwise use her camera, or frame the model from a
423
- # three-quarter view. Temporary camera/lights are added AFTER saving, so they
424
- # never end up in the model.
425
- preview = os.path.join(ASSET_DIR, 'preview.png')
426
- try:
427
- if os.path.exists(preview) and os.path.getmtime(preview) >= STARTED:
428
- result['preview'] = 'hers'
429
- elif meshes:
430
- scene = bpy.context.scene
431
- if scene.camera is None:
432
- from mathutils import Vector
433
- c = Vector(result['center']); size = max(result['size_m']) or 1.0
434
- cam_data = bpy.data.cameras.new('AvaPreviewCam'); cam_data.lens = 50
435
- cam = bpy.data.objects.new('AvaPreviewCam', cam_data)
436
- scene.collection.objects.link(cam)
437
- cam.location = c + Vector((1.0, -1.25, 0.8)).normalized() * size * 2.6
438
- cam.rotation_euler = (c - cam.location).to_track_quat('-Z', 'Y').to_euler()
439
- cam_data.clip_end = size * 100
440
- scene.camera = cam
441
- result['preview_camera'] = 'auto'
442
- if not any(o.type == 'LIGHT' for o in scene.objects):
443
- for nm, rot, energy in (('AvaKey', (0.9, 0.2, 0.8), 4.0), ('AvaFill', (1.1, -0.3, -2.4), 1.5)):
444
- ld = bpy.data.lights.new(nm, 'SUN'); ld.energy = energy
445
- lo_ = bpy.data.objects.new(nm, ld); lo_.rotation_euler = rot
446
- scene.collection.objects.link(lo_)
447
- if scene.world is None:
448
- scene.world = bpy.data.worlds.new('AvaPreviewWorld')
449
- r = scene.render
450
- r.resolution_x = r.resolution_y = 1024; r.resolution_percentage = 100
451
- r.film_transparent = True
452
- r.image_settings.file_format = 'PNG'; r.image_settings.color_mode = 'RGBA'
453
- r.filepath = preview
454
- bpy.ops.render.render(write_still=True)
455
- result['preview'] = 'auto'
456
- if os.path.exists(preview):
457
- result['files'].append('preview.png')
458
- except BaseException as e:
459
- result['warnings'].append('Preview render failed: ' + str(e))
460
-
461
- result['ok'] = True
462
- result['seconds'] = round(time.time() - STARTED, 1)
463
- emit()
234
+ export const BLENDER_RUNNER_PY = String.raw `# Ava's Blender runner. Started by design_build_model as:
235
+ # blender -b [model.blend] --factory-startup --disable-autoexec --python runner.py -- job.json
236
+ # It prepares the scene, installs the guard, runs Ava's script, then saves,
237
+ # exports and renders a preview. The last line it prints is the result.
238
+ import sys, os, json, time, traceback, tempfile, shutil, math
239
+
240
+ JOB = json.load(open(sys.argv[sys.argv.index('--') + 1], encoding='utf-8'))
241
+ ASSET_DIR = os.path.realpath(JOB['assetDir'])
242
+ NAME = JOB['name']
243
+ BLEND = os.path.join(ASSET_DIR, NAME + '.blend')
244
+ STARTED = time.time()
245
+ result = {'ok': False, 'files': [], 'warnings': []}
246
+ ${KIT_PY}
247
+
248
+ def emit():
249
+ sys.stdout.write('\n@@AVA_RESULT@@' + json.dumps(result) + '\n')
250
+ sys.stdout.flush()
251
+
252
+ import bpy
253
+ sys.dont_write_bytecode = True
254
+ bpy.context.preferences.filepaths.save_version = 0 # no .blend1 clutter beside the model
255
+
256
+ if not JOB['continue']:
257
+ bpy.ops.wm.read_factory_settings(use_empty=True) # a new canvas: nothing in it
258
+ for sc in bpy.data.scenes:
259
+ sc.render.filepath = os.path.join(ASSET_DIR, 'render_')
260
+
261
+ # ── The guard ────────────────────────────────────────────────────────────────
262
+ # Python audit hooks see every file write, process start and network call made
263
+ # from Python, and cannot be removed once installed. A guard, not a sandbox:
264
+ # Blender's own C code (saving a .blend, writing a render) is not seen here,
265
+ # which is why the tool also refuses absolute paths in the script itself.
266
+ # Writes are allowed in the model folder and in Blender's OWN per-run temp
267
+ # folder (blender_xxxx), not the whole system temp. Python's tempfile is
268
+ # pointed there too, so any library that needs scratch space stays inside it.
269
+ _BTMP = bpy.app.tempdir or os.path.join(ASSET_DIR, '.tmp')
270
+ os.makedirs(_BTMP, exist_ok=True)
271
+ tempfile.tempdir = _BTMP
272
+ _ALLOWED = [os.path.normcase(os.path.realpath(p)) for p in {ASSET_DIR, _BTMP}]
273
+
274
+ def _inside(p):
275
+ try:
276
+ rp = os.path.normcase(os.path.realpath(os.fsdecode(p)))
277
+ except Exception:
278
+ return False
279
+ return any(rp == a or rp.startswith(a.rstrip(os.sep) + os.sep) for a in _ALLOWED)
280
+
281
+ _BLOCKED = {
282
+ 'subprocess.Popen': 'starting other programs', 'os.system': 'starting other programs',
283
+ 'os.exec': 'starting other programs', 'os.posix_spawn': 'starting other programs',
284
+ 'os.spawn': 'starting other programs', 'os.startfile': 'opening files in other programs',
285
+ 'os.kill': 'stopping other programs', 'webbrowser.open': 'opening a browser',
286
+ 'socket.connect': 'network access', 'socket.bind': 'network access',
287
+ 'socket.getaddrinfo': 'network access', 'socket.gethostbyname': 'network access',
288
+ 'urllib.Request': 'network access', 'ctypes.dlopen': 'loading native code',
289
+ 'ctypes.dlsym': 'calling native code', 'ctypes.call_function': 'calling native code',
290
+ 'winreg.CreateKey': 'changing the registry', 'winreg.SetValue': 'changing the registry',
291
+ 'winreg.DeleteKey': 'changing the registry', 'winreg.DeleteValue': 'changing the registry',
292
+ }
293
+ _WRITE_ARGS = { # event -> indexes of the paths it writes or removes
294
+ 'os.remove': (0,), 'os.rmdir': (0,), 'os.mkdir': (0,), 'os.chmod': (0,),
295
+ 'os.truncate': (0,), 'os.utime': (0,), 'shutil.rmtree': (0,),
296
+ 'os.rename': (0, 1), 'shutil.move': (0, 1), 'shutil.copyfile': (1,),
297
+ 'shutil.copytree': (1,), 'os.symlink': (1,), 'os.link': (1,),
298
+ }
299
+ _WRITE_FLAGS = os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_TRUNC
300
+
301
+ def _refuse(why):
302
+ raise PermissionError(f'Blocked by the Design Studio guard: {why}. '
303
+ f'Scripts here may only build the model and write inside its own folder (ASSET_DIR).')
304
+
305
+ def _hook(event, args):
306
+ if event in _BLOCKED:
307
+ _refuse(_BLOCKED[event])
308
+ if event == 'open':
309
+ path, mode, flags = (list(args) + [None, None, 0])[:3]
310
+ if path is None or isinstance(path, int):
311
+ return
312
+ writing = (isinstance(mode, str) and any(c in mode for c in 'wax+')) or \
313
+ (mode is None and isinstance(flags, int) and flags & _WRITE_FLAGS)
314
+ if writing and not _inside(path):
315
+ _refuse(f'writing outside the model folder ({os.fsdecode(path)})')
316
+ elif event in _WRITE_ARGS:
317
+ for i in _WRITE_ARGS[event]:
318
+ if i < len(args) and args[i] is not None and not isinstance(args[i], int) and not _inside(args[i]):
319
+ _refuse(f'changing files outside the model folder ({os.fsdecode(args[i])})')
320
+
321
+ # Blender's own exporters load native code when first imported (the glTF one
322
+ # pulls in ctypes for Draco). Import them BEFORE the guard goes up, so the guard
323
+ # only ever sees what Ava's script does.
324
+ import ctypes # noqa: F401
325
+ for _mod in ('io_scene_gltf2.blender.exp.export', 'io_scene_fbx.export_fbx_bin'):
326
+ try:
327
+ __import__(_mod)
328
+ except Exception as e:
329
+ result['warnings'].append(f'Could not preload {_mod}: {e}')
330
+
331
+ sys.addaudithook(_hook)
332
+
333
+ ${BLENDER_HELPERS_PY}
334
+ # ── Ava's script ─────────────────────────────────────────────────────────────
335
+ script_path = os.path.join(ASSET_DIR, 'script.py')
336
+ ns = {'__name__': '__main__', '__file__': script_path, 'ASSET_DIR': ASSET_DIR, 'bpy': bpy, 'KIT': KIT,
337
+ 'ava_unwrap': ava_unwrap, 'ava_bake': ava_bake}
338
+ try:
339
+ with open(script_path, encoding='utf-8') as f:
340
+ code = compile(f.read(), 'script.py', 'exec')
341
+ exec(code, ns)
342
+ except BaseException as e: # SystemExit included: the saved model must stay as it was
343
+ result['error'] = ''.join(traceback.format_exception(type(e), e, e.__traceback__)[-12:])
344
+ emit()
345
+ sys.exit(0)
346
+
347
+ # ── Save, export, measure ────────────────────────────────────────────────────
348
+ try:
349
+ if os.path.exists(BLEND): # keep the last 5 versions so a bad run can be undone
350
+ vdir = os.path.join(ASSET_DIR, 'versions')
351
+ os.makedirs(vdir, exist_ok=True)
352
+ shutil.copy2(BLEND, os.path.join(vdir, time.strftime('%Y%m%d-%H%M%S') + '.blend'))
353
+ for old in sorted(os.listdir(vdir))[:-5]:
354
+ os.remove(os.path.join(vdir, old))
355
+ bpy.ops.wm.save_as_mainfile(filepath=BLEND)
356
+ result['files'].append(NAME + '.blend')
357
+
358
+ meshes = [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.visible_get()]
359
+ deps = bpy.context.evaluated_depsgraph_get()
360
+ tris = 0
361
+ lo = [math.inf] * 3; hi = [-math.inf] * 3
362
+ for o in meshes:
363
+ ev = o.evaluated_get(deps)
364
+ m = ev.to_mesh()
365
+ m.calc_loop_triangles()
366
+ tris += len(m.loop_triangles)
367
+ for v in m.vertices:
368
+ w = ev.matrix_world @ v.co
369
+ for i in range(3):
370
+ lo[i] = min(lo[i], w[i]); hi[i] = max(hi[i], w[i])
371
+ ev.to_mesh_clear()
372
+ result['objects'] = len(meshes)
373
+ result['triangles'] = tris
374
+ if meshes:
375
+ result['size_m'] = [round(hi[i] - lo[i], 3) for i in range(3)]
376
+ result['center'] = [(hi[i] + lo[i]) / 2 for i in range(3)]
377
+
378
+ glb = os.path.join(ASSET_DIR, NAME + '.glb')
379
+ bpy.ops.export_scene.gltf(filepath=glb, export_format='GLB', use_selection=False, export_apply=True)
380
+ result['files'].append(NAME + '.glb')
381
+ if JOB.get('fbx'):
382
+ fbx = os.path.join(ASSET_DIR, NAME + '.fbx')
383
+ # mesh_smooth_type='FACE': without smoothing groups Unreal warns on every
384
+ # part (seen importing the wooden crate into 5.9, 19 Nov).
385
+ bpy.ops.export_scene.fbx(filepath=fbx, use_selection=False, apply_scale_options='FBX_SCALE_ALL', path_mode='COPY', embed_textures=True, mesh_smooth_type='FACE')
386
+ result['files'].append(NAME + '.fbx')
387
+ # Live shaders do not export. Say so whenever the export will reach an
388
+ # engine bare — the gap she lost twenty minutes in on the first model.
389
+ _PROC = ('ShaderNodeTexNoise', 'ShaderNodeTexVoronoi', 'ShaderNodeTexWave', 'ShaderNodeTexMusgrave',
390
+ 'ShaderNodeTexGradient', 'ShaderNodeTexMagic', 'ShaderNodeTexChecker', 'ShaderNodeTexBrick',
391
+ 'ShaderNodeMath', 'ShaderNodeVectorMath', 'ShaderNodeValToRGB', 'ShaderNodeBump', 'ShaderNodeMix')
392
+ _live = sorted({sl.material.name for o in meshes for sl in o.material_slots
393
+ if sl.material and sl.material.use_nodes and not sl.material.get('ava_baked')
394
+ and any(n.bl_idname in _PROC for n in sl.material.node_tree.nodes)})
395
+ if _live:
396
+ result['warnings'].append(
397
+ 'The exported model carries NONE of the live shader detail in ' + ', '.join(_live) +
398
+ ' — game engines and the Library viewer will show it flat. Bake it: ava_unwrap() if the UVs overlap, then ava_bake().')
399
+ _tex = os.path.join(ASSET_DIR, 'textures')
400
+ if os.path.isdir(_tex):
401
+ result['files'] += ['textures/' + f for f in sorted(os.listdir(_tex))]
402
+ # For the making record: fonts and pictures in the SAVED model, whoever put
403
+ # them there (her script or the person by hand), and kit logos she used.
404
+ try:
405
+ result['fonts'] = sorted({(f.name if f.filepath in ('', '<builtin>') else
406
+ os.path.basename(bpy.path.abspath(f.filepath)))
407
+ + ('|builtin' if f.filepath in ('', '<builtin>') else '')
408
+ for f in bpy.data.fonts if f.users})
409
+ result['images_used'] = sorted({os.path.basename(bpy.path.abspath(i.filepath)) for i in bpy.data.images
410
+ if i.users and i.filepath and i.source == 'FILE'
411
+ and os.path.dirname(os.path.normcase(os.path.abspath(bpy.path.abspath(i.filepath)))) != os.path.normcase(os.path.abspath(_tex))})
412
+ except Exception as e:
413
+ result['warnings'].append(f'Could not list fonts and pictures for the making record: {e}')
414
+ result['kit_logos'] = list(KIT_LOGOS_USED)
415
+ except BaseException as e:
416
+ result['error'] = 'The script ran, but saving or exporting failed:\n' + \
417
+ ''.join(traceback.format_exception(type(e), e, e.__traceback__)[-8:])
418
+ emit()
419
+ sys.exit(0)
420
+
421
+ # ── Preview ──────────────────────────────────────────────────────────────────
422
+ # Her own render wins. Otherwise use her camera, or frame the model from a
423
+ # three-quarter view. Temporary camera/lights are added AFTER saving, so they
424
+ # never end up in the model.
425
+ preview = os.path.join(ASSET_DIR, 'preview.png')
426
+ try:
427
+ if os.path.exists(preview) and os.path.getmtime(preview) >= STARTED:
428
+ result['preview'] = 'hers'
429
+ elif meshes:
430
+ scene = bpy.context.scene
431
+ if scene.camera is None:
432
+ from mathutils import Vector
433
+ c = Vector(result['center']); size = max(result['size_m']) or 1.0
434
+ cam_data = bpy.data.cameras.new('AvaPreviewCam'); cam_data.lens = 50
435
+ cam = bpy.data.objects.new('AvaPreviewCam', cam_data)
436
+ scene.collection.objects.link(cam)
437
+ cam.location = c + Vector((1.0, -1.25, 0.8)).normalized() * size * 2.6
438
+ cam.rotation_euler = (c - cam.location).to_track_quat('-Z', 'Y').to_euler()
439
+ cam_data.clip_end = size * 100
440
+ scene.camera = cam
441
+ result['preview_camera'] = 'auto'
442
+ if not any(o.type == 'LIGHT' for o in scene.objects):
443
+ for nm, rot, energy in (('AvaKey', (0.9, 0.2, 0.8), 4.0), ('AvaFill', (1.1, -0.3, -2.4), 1.5)):
444
+ ld = bpy.data.lights.new(nm, 'SUN'); ld.energy = energy
445
+ lo_ = bpy.data.objects.new(nm, ld); lo_.rotation_euler = rot
446
+ scene.collection.objects.link(lo_)
447
+ if scene.world is None:
448
+ scene.world = bpy.data.worlds.new('AvaPreviewWorld')
449
+ r = scene.render
450
+ r.resolution_x = r.resolution_y = 1024; r.resolution_percentage = 100
451
+ r.film_transparent = True
452
+ r.image_settings.file_format = 'PNG'; r.image_settings.color_mode = 'RGBA'
453
+ r.filepath = preview
454
+ bpy.ops.render.render(write_still=True)
455
+ result['preview'] = 'auto'
456
+ if os.path.exists(preview):
457
+ result['files'].append('preview.png')
458
+ except BaseException as e:
459
+ result['warnings'].append('Preview render failed: ' + str(e))
460
+
461
+ result['ok'] = True
462
+ result['seconds'] = round(time.time() - STARTED, 1)
463
+ emit()
464
464
  `;
465
465
  //# sourceMappingURL=runner-py.js.map