oda-engine 0.0.0-stage → 0.1.0

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 (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +90 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
@@ -0,0 +1,360 @@
1
+ # Cleans up a model that came from outside (a generator's or a library's)
2
+ # before asset_import optimises, checks and records it: a generated mesh
3
+ # comes with stray vertices, flecks floating off it, doubled points, faces
4
+ # wound the wrong way, an arbitrary scale and origin, often ten times the
5
+ # triangles a game on an inexpensive computer can draw, and 4K textures. run.mjs
6
+ # starts it like convert.py, with args
7
+ # { in_glb, out_glb, result, budget, max_texture, size, pivot, generated }
8
+ # (size: one of height, width, depth or longest in metres, or null; pivot:
9
+ # base, center or keep; generated: a generator made it, so its doubled
10
+ # points are welded, its flecks removed and its faces wound outward; a
11
+ # library's model keeps its own points, parts and normals, and loses only
12
+ # what draws nothing) and the answer in args.result:
13
+ # { ok, before, after, steps: [{ op, detail }], materials, problems,
14
+ # warnings, error? }
15
+ # before and after: { triangles, meshes, size: { width, height, depth } } in
16
+ # the game's terms (Y up: height is Blender's Z). A rigged, animated or
17
+ # shape-keyed model keeps its geometry as it is (only its textures are
18
+ # held to the budget), since welding or decimating it would break what moves.
19
+ # The export is runner.py's own (nw_export.py). Written for Blender 4.2 to 5.1.
20
+
21
+ import json
22
+ import math
23
+ import os
24
+ import sys
25
+ import time
26
+ import traceback
27
+
28
+ import bmesh
29
+ import bpy
30
+ import numpy as np
31
+ from mathutils import Matrix, Vector
32
+
33
+ sys.dont_write_bytecode = True
34
+ HERE = os.path.dirname(os.path.realpath(__file__))
35
+ if HERE not in sys.path:
36
+ sys.path.append(HERE)
37
+
38
+ from nw_export import dropped_nodes, export # noqa: E402
39
+
40
+ ARGS = json.load(open(sys.argv[sys.argv.index('--') + 1], encoding='utf-8'))
41
+ STARTED = time.time()
42
+ WARNINGS = []
43
+ STEPS = []
44
+
45
+ # A part this much smaller than the whole model (its box's diagonal), with
46
+ # this small a share of its faces, is a fleck floating off it, not a part;
47
+ # when there are more than a few of them and they would take more than this
48
+ # share of the parts or of the faces, they are the model's own small parts
49
+ # (leaves, bolts) and all stay.
50
+ FLECK_SIZE = 0.02
51
+ FLECK_FACES = 0.01
52
+ FEW_FLECKS = 3
53
+ FLECKS_AT_MOST = 0.25
54
+ FLECK_FACES_AT_MOST = 0.05
55
+ # Points closer than this share of the model's diagonal are one point.
56
+ WELD = 1e-4
57
+ KEEP_TYPES = {'MESH', 'EMPTY', 'ARMATURE'}
58
+
59
+
60
+ def write_result(doc):
61
+ doc['seconds'] = round(time.time() - STARTED, 2)
62
+ doc['blender'] = bpy.app.version_string
63
+ doc['warnings'] = WARNINGS
64
+ doc['steps'] = STEPS
65
+ with open(ARGS['result'], 'w', encoding='utf-8') as f:
66
+ json.dump(doc, f)
67
+
68
+
69
+ def fail(error):
70
+ write_result({'ok': False, 'error': error})
71
+ sys.exit(3)
72
+
73
+
74
+ def step(op, detail):
75
+ STEPS.append({'op': op, 'detail': detail})
76
+
77
+
78
+ def meshes():
79
+ return [o for o in bpy.context.scene.objects if o.type == 'MESH']
80
+
81
+
82
+ def measure():
83
+ lo = np.full(3, np.inf)
84
+ hi = np.full(3, -np.inf)
85
+ triangles = 0
86
+ for obj in meshes():
87
+ mesh = obj.data
88
+ mesh.calc_loop_triangles()
89
+ triangles += len(mesh.loop_triangles)
90
+ count = len(mesh.vertices)
91
+ if not count:
92
+ continue
93
+ co = np.empty(count * 3, dtype=np.float64)
94
+ mesh.vertices.foreach_get('co', co)
95
+ m = np.array(obj.matrix_world)
96
+ world = co.reshape(-1, 3) @ m[:3, :3].T + m[:3, 3]
97
+ lo = np.minimum(lo, world.min(axis=0))
98
+ hi = np.maximum(hi, world.max(axis=0))
99
+ if not np.isfinite(lo).all():
100
+ return {'triangles': triangles, 'meshes': len(meshes()), 'size': None}, None, None
101
+ d = hi - lo
102
+ size = {'width': round(float(d[0]), 4), 'height': round(float(d[2]), 4), 'depth': round(float(d[1]), 4)}
103
+ return {'triangles': triangles, 'meshes': len(meshes()), 'size': size}, Vector(lo.tolist()), Vector(hi.tolist())
104
+
105
+
106
+ def moves():
107
+ """Why the geometry must stay as it came, or None."""
108
+ if any(o.type == 'ARMATURE' for o in bpy.context.scene.objects):
109
+ return 'it is rigged'
110
+ if bpy.data.actions:
111
+ return 'it is animated'
112
+ if any(o.data.shape_keys for o in meshes()):
113
+ return 'it has shape keys'
114
+ return None
115
+
116
+
117
+ def bake_transforms():
118
+ """Every mesh in world space with no parent, and the empties gone."""
119
+ for obj in meshes():
120
+ world = obj.matrix_world.copy()
121
+ obj.parent = None
122
+ if obj.data.users > 1:
123
+ obj.data = obj.data.copy()
124
+ obj.data.transform(world)
125
+ obj.matrix_world = Matrix.Identity(4)
126
+ for obj in [o for o in bpy.context.scene.objects if o.type == 'EMPTY']:
127
+ bpy.data.objects.remove(obj, do_unlink=True)
128
+
129
+
130
+ def island_size(faces):
131
+ """The diagonal of a part's box."""
132
+ co = np.array([v.co[:] for g in faces for v in g.verts])
133
+ return float(np.linalg.norm(co.max(axis=0) - co.min(axis=0)))
134
+
135
+
136
+ def clean_mesh(obj, diag, generated):
137
+ """Drops loose points and edges and degenerate faces; for a generated
138
+ mesh also welds doubled points, takes off its flecks and winds every
139
+ face outward. Answers what it did."""
140
+ bm = bmesh.new()
141
+ bm.from_mesh(obj.data)
142
+ welded = 0
143
+ if generated:
144
+ before_v = len(bm.verts)
145
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=max(1e-7, WELD * diag))
146
+ welded = before_v - len(bm.verts)
147
+ bmesh.ops.dissolve_degenerate(bm, edges=bm.edges, dist=max(1e-8, 1e-6 * diag))
148
+ loose_v = [v for v in bm.verts if not v.link_faces]
149
+ loose_e = [e for e in bm.edges if not e.link_faces]
150
+ bmesh.ops.delete(bm, geom=loose_e, context='EDGES')
151
+ bmesh.ops.delete(bm, geom=[v for v in loose_v if v.is_valid], context='VERTS')
152
+ # The parts of the mesh that touch nothing else.
153
+ bm.faces.index_update()
154
+ seen = set()
155
+ islands = []
156
+ for f in bm.faces:
157
+ if f.index in seen:
158
+ continue
159
+ stack = [f]
160
+ part = []
161
+ seen.add(f.index)
162
+ while stack:
163
+ g = stack.pop()
164
+ part.append(g)
165
+ for e in g.edges:
166
+ for h in e.link_faces:
167
+ if h.index not in seen:
168
+ seen.add(h.index)
169
+ stack.append(h)
170
+ islands.append(part)
171
+ total = len(bm.faces)
172
+ flecks = []
173
+ kept_parts = False
174
+ if generated and len(islands) > 1:
175
+ for part in islands:
176
+ if len(part) < FLECK_FACES * total and island_size(part) < FLECK_SIZE * diag:
177
+ flecks.append(part)
178
+ if len(flecks) > FEW_FLECKS and (len(flecks) > FLECKS_AT_MOST * len(islands) or sum(len(p) for p in flecks) > FLECK_FACES_AT_MOST * total):
179
+ kept_parts = True
180
+ flecks = []
181
+ if flecks:
182
+ bmesh.ops.delete(bm, geom=[g for part in flecks for g in part], context='FACES')
183
+ if generated:
184
+ bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
185
+ bm.to_mesh(obj.data)
186
+ bm.free()
187
+ obj.data.update()
188
+ return {'welded': welded, 'loose': len(loose_v) + len(loose_e), 'flecks': len(flecks), 'small_parts': kept_parts}
189
+
190
+
191
+ def scale_to(size, lo, hi):
192
+ """The uniform factor that gives the model the asked size, or None."""
193
+ if not size:
194
+ return None
195
+ d = hi - lo
196
+ have = {'width': d.x, 'height': d.z, 'depth': d.y, 'longest': max(d.x, d.y, d.z)}
197
+ for key in ('height', 'width', 'depth', 'longest'):
198
+ want = size.get(key)
199
+ if isinstance(want, (int, float)) and want > 0 and have[key] > 1e-9:
200
+ return key, want / have[key]
201
+ return None
202
+
203
+
204
+ def place(pivot, lo, hi):
205
+ if pivot == 'keep':
206
+ return None
207
+ centre = (lo + hi) / 2
208
+ shift = Vector((-centre.x, -centre.y, -lo.z if pivot == 'base' else -centre.z))
209
+ if shift.length < 1e-9:
210
+ return None
211
+ for obj in meshes():
212
+ obj.data.transform(Matrix.Translation(shift))
213
+ return shift
214
+
215
+
216
+ def decimate(budget, triangles):
217
+ if not budget or triangles <= budget:
218
+ return None
219
+ ratio = max(0.01, min(1.0, budget * 0.97 / triangles))
220
+ for obj in meshes():
221
+ mod = obj.modifiers.new('nw_decimate', 'DECIMATE')
222
+ mod.decimate_type = 'COLLAPSE'
223
+ mod.ratio = ratio
224
+ mod.use_collapse_triangulate = True
225
+ with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj]):
226
+ bpy.ops.object.modifier_apply(modifier=mod.name)
227
+ return ratio
228
+
229
+
230
+ def principled_of(mat):
231
+ tree = getattr(mat, 'node_tree', None)
232
+ if tree is None:
233
+ return None
234
+ return next((n for n in tree.nodes if n.bl_idname == 'ShaderNodeBsdfPrincipled'), None)
235
+
236
+
237
+ def textures_and_materials(max_texture):
238
+ """Each texture held to the class's longest side, and what each material
239
+ is: whether it is a Principled BSDF glTF carries, its textures, and the
240
+ problems the gate should hear of."""
241
+ problems = []
242
+ resized = []
243
+ for img in bpy.data.images:
244
+ if img.type != 'IMAGE':
245
+ continue
246
+ w, h = img.size[0], img.size[1]
247
+ if w == 0 or h == 0:
248
+ problems.append(f'the texture {img.name} has no pixels (it is missing)')
249
+ continue
250
+ long = max(w, h)
251
+ if max_texture and long > max_texture:
252
+ k = max_texture / long
253
+ img.scale(max(1, round(w * k)), max(1, round(h * k)))
254
+ if img.packed_file is not None or not img.filepath:
255
+ img.pack()
256
+ resized.append(f'{img.name} {w}x{h} to {img.size[0]}x{img.size[1]}')
257
+ if resized:
258
+ step('textures', f'held to {max_texture} px: {", ".join(resized[:6])}')
259
+ materials = []
260
+ used = set()
261
+ for obj in meshes():
262
+ textured = False
263
+ for slot in obj.material_slots:
264
+ mat = slot.material
265
+ if mat is None or mat.name in used:
266
+ continue
267
+ used.add(mat.name)
268
+ bsdf = principled_of(mat)
269
+ images = sorted({n.image.name for n in (mat.node_tree.nodes if mat.node_tree else []) if n.bl_idname == 'ShaderNodeTexImage' and n.image})
270
+ textured = textured or bool(images)
271
+ info = {'name': mat.name, 'principled': bsdf is not None, 'textures': images}
272
+ if bsdf is None:
273
+ problems.append(f'the material {mat.name} is not a Principled BSDF, so glTF carries little of it')
274
+ materials.append(info)
275
+ if not obj.material_slots or all(s.material is None for s in obj.material_slots):
276
+ problems.append(f'{obj.name} has no material')
277
+ if textured and not obj.data.uv_layers:
278
+ problems.append(f'{obj.name} is textured but has no UVs')
279
+ for d in dropped_nodes(meshes()):
280
+ problems.append(f'glTF drops the nodes {", ".join(d["nodes"])} of {d["material"]}')
281
+ return materials, problems
282
+
283
+
284
+ def main():
285
+ source = ARGS['in_glb']
286
+ if not os.path.isfile(source):
287
+ fail(f'there is no file at {source}')
288
+ bpy.ops.wm.read_factory_settings(use_empty=True)
289
+ try:
290
+ result = bpy.ops.import_scene.gltf(filepath=source)
291
+ except Exception as e:
292
+ fail(f'the GLB did not import: {str(e).strip().splitlines()[-1][:300]}')
293
+ if 'FINISHED' not in result:
294
+ fail('the GLB did not import')
295
+ dropped = [o for o in bpy.context.scene.objects if o.type not in KEEP_TYPES]
296
+ for obj in dropped:
297
+ bpy.data.objects.remove(obj, do_unlink=True)
298
+ if dropped:
299
+ step('cleanup', f'removed {len(dropped)} objects that are not the model (cameras, lights, curves)')
300
+ if not meshes():
301
+ fail('the GLB has no mesh')
302
+ before, lo, hi = measure()
303
+ frozen = moves()
304
+ if frozen:
305
+ step('cleanup', f'geometry kept as it is: {frozen}')
306
+ else:
307
+ bake_transforms()
308
+ before_clean, lo, hi = measure()
309
+ diag = (hi - lo).length or 1.0
310
+ generated = bool(ARGS.get('generated'))
311
+ removed = {'welded': 0, 'loose': 0, 'flecks': 0, 'small_parts': False}
312
+ for obj in meshes():
313
+ for k, v in clean_mesh(obj, diag, generated).items():
314
+ removed[k] = (removed[k] or v) if k == 'small_parts' else removed[k] + v
315
+ for obj in [o for o in meshes() if not o.data.polygons]:
316
+ bpy.data.objects.remove(obj, do_unlink=True)
317
+ if not meshes():
318
+ fail('nothing of the mesh is left once its loose points and flecks are taken off')
319
+ if generated:
320
+ kept = '; its many small parts kept as its own' if removed['small_parts'] else ''
321
+ step('cleanup', f'welded {removed["welded"]} doubled points, removed {removed["loose"]} loose points and edges and {removed["flecks"]} floating flecks, faces wound outward{kept}')
322
+ else:
323
+ step('cleanup', f'removed {removed["loose"]} loose points and edges and the faces with no area; its own points, parts and normals kept')
324
+ _, lo, hi = measure()
325
+ scaled = scale_to(ARGS.get('size'), lo, hi)
326
+ if scaled:
327
+ key, k = scaled
328
+ for obj in meshes():
329
+ obj.data.transform(Matrix.Scale(k, 4))
330
+ step('size', f'scaled {k:.4g}x to the {key} asked ({ARGS["size"][key]} m)')
331
+ _, lo, hi = measure()
332
+ shift = place(ARGS.get('pivot') or 'base', lo, hi)
333
+ if shift:
334
+ step('pivot', f'origin at the {"base" if ARGS.get("pivot", "base") == "base" else "centre"}: moved {shift.length:.3g} m')
335
+ now, _, _ = measure()
336
+ ratio = decimate(ARGS.get('budget'), now['triangles'])
337
+ if ratio:
338
+ after_dec, _, _ = measure()
339
+ step('decimate', f'{now["triangles"]} to {after_dec["triangles"]} triangles for the budget of {ARGS["budget"]} (collapse {ratio:.3f})')
340
+ materials, problems = textures_and_materials(ARGS.get('max_texture'))
341
+ after, _, _ = measure()
342
+ out = ARGS['out_glb']
343
+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
344
+ picked = [o for o in bpy.context.scene.objects if o.type in KEEP_TYPES]
345
+ try:
346
+ export(out, picked, WARNINGS)
347
+ except Exception as e:
348
+ fail(f'the glTF export failed: {type(e).__name__}: {e}')
349
+ if not os.path.isfile(out) or os.path.getsize(out) == 0:
350
+ fail('the glTF exporter wrote no file')
351
+ write_result({'ok': True, 'before': before, 'after': after, 'materials': materials, 'problems': problems, 'frozen': frozen, 'out_glb': out})
352
+
353
+
354
+ try:
355
+ main()
356
+ except SystemExit:
357
+ raise
358
+ except BaseException as e:
359
+ write_result({'ok': False, 'error': f'{type(e).__name__}: {e}', 'traceback': traceback.format_exc()})
360
+ raise
@@ -0,0 +1,167 @@
1
+ # Converts a model file from outside (FBX, OBJ, STL, PLY, USD, and Collada
2
+ # where the running Blender still reads it) into one GLB, for asset_import:
3
+ # the game loads only glTF, and Blender reads every format a free library or
4
+ # a generator hands out. run.mjs starts it like runner.py, with args
5
+ # { in, out_glb, result }; the answer is { ok, objects, meshes, warnings,
6
+ # error? } in args.result. The export is runner.py's own (nw_export.py), so a
7
+ # converted model and a modelled one leave in the same shape.
8
+ # Written for Blender 4.2 to 5.1. Collada left Blender in 5.0; asking for it
9
+ # there says so instead of failing without a reason.
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import sys
15
+ import time
16
+ import traceback
17
+
18
+ import bpy
19
+
20
+ sys.dont_write_bytecode = True
21
+ HERE = os.path.dirname(os.path.realpath(__file__))
22
+ if HERE not in sys.path:
23
+ sys.path.append(HERE)
24
+
25
+ from nw_export import export # noqa: E402
26
+
27
+ ARGS = json.load(open(sys.argv[sys.argv.index('--') + 1], encoding='utf-8'))
28
+ STARTED = time.time()
29
+ WARNINGS = []
30
+
31
+ # Extension to (operator path, keyword arguments). Each importer keeps the
32
+ # file's own axes and units except where the format has none (STL and PLY
33
+ # are unitless and usually millimetres or metres; asset_import sizes them).
34
+ IMPORTERS = {
35
+ '.fbx': ('import_scene.fbx', {}),
36
+ '.obj': ('wm.obj_import', {}),
37
+ '.stl': ('wm.stl_import', {}),
38
+ '.ply': ('wm.ply_import', {}),
39
+ '.usd': ('wm.usd_import', {}),
40
+ '.usda': ('wm.usd_import', {}),
41
+ '.usdc': ('wm.usd_import', {}),
42
+ '.usdz': ('wm.usd_import', {}),
43
+ '.dae': ('wm.collada_import', {}),
44
+ '.glb': ('import_scene.gltf', {}),
45
+ '.gltf': ('import_scene.gltf', {}),
46
+ }
47
+
48
+ MESHY = {'MESH', 'CURVE', 'SURFACE', 'FONT', 'META'}
49
+ EXPORT_TYPES = MESHY | {'EMPTY', 'ARMATURE'}
50
+
51
+
52
+ def write_result(doc):
53
+ doc['seconds'] = round(time.time() - STARTED, 2)
54
+ doc['blender'] = bpy.app.version_string
55
+ doc['warnings'] = WARNINGS
56
+ with open(ARGS['result'], 'w', encoding='utf-8') as f:
57
+ json.dump(doc, f)
58
+
59
+
60
+ def fail(error):
61
+ write_result({'ok': False, 'objects': 0, 'meshes': 0, 'error': error})
62
+ sys.exit(3)
63
+
64
+
65
+ def last_line(error):
66
+ """The exception itself from an operator's error, whose message carries the add-on's whole traceback."""
67
+ lines = [l.strip() for l in str(error).splitlines() if l.strip() and not l.strip().startswith('Location:')]
68
+ found = next((l for l in reversed(lines) if re.match(r'^[A-Za-z_.]+(Error|Exception)\b', l)), None)
69
+ return (found or (lines[-1] if lines else type(error).__name__))[:300]
70
+
71
+
72
+ def patch_cycles_light():
73
+ probe = bpy.data.lights.new('nw_probe', 'POINT')
74
+ try:
75
+ settings = type(getattr(probe, 'cycles', None))
76
+ if settings is type(None) or hasattr(probe.cycles, 'cast_shadow'):
77
+ return False
78
+ settings.cast_shadow = bpy.props.BoolProperty(name='cast_shadow', default=True)
79
+ return True
80
+ except Exception:
81
+ return False
82
+ finally:
83
+ bpy.data.lights.remove(probe)
84
+
85
+
86
+ def operator(path):
87
+ group, name = path.split('.')
88
+ op = getattr(getattr(bpy.ops, group), name)
89
+ try:
90
+ op.get_rna_type()
91
+ except Exception:
92
+ return None
93
+ return op
94
+
95
+
96
+ def main():
97
+ source = ARGS['in']
98
+ ext = os.path.splitext(source)[1].lower()
99
+ if ext not in IMPORTERS:
100
+ fail(f'convert.py reads {", ".join(sorted(IMPORTERS))}; "{os.path.basename(source)}" is none of them')
101
+ if not os.path.isfile(source):
102
+ fail(f'there is no file at {source}')
103
+ path, kwargs = IMPORTERS[ext]
104
+ op = operator(path)
105
+ if op is None:
106
+ if ext == '.dae':
107
+ fail(f'Blender {bpy.app.version_string} no longer reads Collada (.dae); it left Blender in 5.0. Ask for another format (glTF, FBX or OBJ) or use Blender 4.5 to convert it')
108
+ fail(f'this Blender has no importer for {ext}')
109
+
110
+ bpy.ops.wm.read_factory_settings(use_empty=True)
111
+ # A file's own folder holds its textures (an OBJ's .mtl, an FBX's maps).
112
+ os.chdir(os.path.dirname(os.path.realpath(source)))
113
+ before = set(bpy.data.objects)
114
+ try:
115
+ result = op(filepath=source, **kwargs)
116
+ except Exception as e:
117
+ # Blender 5.1's FBX importer stops on any light in the file: it sets
118
+ # a Cycles light setting that 5.1 no longer has. The setting is put
119
+ # back for this run and the import tried once more.
120
+ if ext == '.fbx' and 'cast_shadow' in str(e) and patch_cycles_light():
121
+ WARNINGS.append('the FBX has lights, which this Blender\'s FBX importer trips on; converted with a stand-in setting (lights are not exported)')
122
+ for obj in [o for o in bpy.data.objects if o not in before]:
123
+ bpy.data.objects.remove(obj, do_unlink=True)
124
+ try:
125
+ result = op(filepath=source, **kwargs)
126
+ except Exception as again:
127
+ fail(f'the {ext} importer failed: {last_line(again)}')
128
+ else:
129
+ fail(f'the {ext} importer failed: {last_line(e)}')
130
+ if 'FINISHED' not in result:
131
+ fail(f'the {ext} importer did not finish ({", ".join(sorted(result))})')
132
+ made = [o for o in bpy.data.objects if o not in before]
133
+ bpy.context.view_layer.update()
134
+ picked = []
135
+ for obj in made:
136
+ if obj.type not in EXPORT_TYPES:
137
+ continue
138
+ try:
139
+ if not obj.visible_get():
140
+ continue
141
+ except Exception:
142
+ continue
143
+ picked.append(obj)
144
+ meshes = sum(1 for o in picked if o.type in MESHY)
145
+ if not meshes:
146
+ fail(f'the {ext} file has no mesh to convert')
147
+ out = ARGS['out_glb']
148
+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
149
+ try:
150
+ export(out, picked, WARNINGS)
151
+ except Exception as e:
152
+ fail(f'the glTF export failed: {type(e).__name__}: {e}')
153
+ if not os.path.isfile(out) or os.path.getsize(out) == 0:
154
+ fail('the glTF exporter wrote no file')
155
+ missing = sorted({img.name for img in bpy.data.images if img.source == 'FILE' and img.filepath and not img.packed_file and not os.path.isfile(bpy.path.abspath(img.filepath))})
156
+ if missing:
157
+ WARNINGS.append(f'textures the file names but that were not found beside it: {", ".join(missing[:8])}')
158
+ write_result({'ok': True, 'objects': len(picked), 'meshes': meshes, 'out_glb': out})
159
+
160
+
161
+ try:
162
+ main()
163
+ except SystemExit:
164
+ raise
165
+ except BaseException as e:
166
+ write_result({'ok': False, 'objects': 0, 'meshes': 0, 'error': f'{type(e).__name__}: {e}', 'traceback': traceback.format_exc()})
167
+ raise