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,1352 @@
1
+ // asset_import: the one way a file from outside comes into assets/. It reads
2
+ // what asset_fetch, asset_job or the browser left in quarantine, refuses what
3
+ // may not be used (before writing anything), converts and optimises it for
4
+ // its kind, writes it into assets/, and records it in assets.lock.json with
5
+ // its source, licence and every step taken.
6
+ //
7
+ // model one GLB through gltf.mjs (Blender converts the other formats
8
+ // and, when it is here, cleans every model up first: cleanup.py
9
+ // drops what draws nothing (and on a generated mesh welds it,
10
+ // takes off its floating flecks and winds it outward), sizes it,
11
+ // sets its origin, decimates it to the class's triangles, holds
12
+ // its textures to the class's size and says what its materials
13
+ // are), then a contact sheet through sheet.py
14
+ // material each map resized and named <name>_color, _normal, _rough, _ao,
15
+ // and _metal, _displacement, _opacity when it has them; held to
16
+ // the brief's texel density at its real size before anything is
17
+ // written (inspect.mjs)
18
+ // texture one picture resized
19
+ // hdri .hdr or .exr kept, its upper and lower colours measured; a 2:1
20
+ // picture (image_generate's panorama) written as .hdr in linear
21
+ // light, so the config's sky can be it
22
+ // audio .ogg, .mp3 or .wav; converted to .ogg when ffmpeg is on PATH
23
+ // lut a .cube, parse-checked
24
+ // splat a Gaussian splat environment (.spz, .ply or .splat) as one
25
+ // .spz (splat.mjs): turned upright, in metres, its floor at
26
+ // y = 0, counted and held to the size a planet carries; with its
27
+ // collider (collider.mjs) baked into the same frame beside it as
28
+ // <name>_collider.glb. A creator's own scan comes in with capture
29
+ // (after they said so in a card), a generated world from
30
+ // environment_job with its frame and its credit
31
+ //
32
+ // Every model, material and texture it writes is inspected (inspect.mjs):
33
+ // the maps it has, its texel density against the brief, its seam score and
34
+ // what KTX2 makes of it; the report is in the answer and the ledger. KTX2
35
+ // textures (each map in the codec it holds up in, ktx2.mjs) and meshopt
36
+ // geometry are written unless the last Publish found the live server or
37
+ // player without them (targets.mjs, publish contract 4); then they are
38
+ // estimated, or measured when asked (ktx2: "measure"), and recorded, and the
39
+ // answer says why.
40
+ //
41
+ // Everything it needs from outside (Blender, the image tool, ffmpeg) comes in
42
+ // through `deps`, so the checks run it with fakes.
43
+
44
+ import { randomBytes } from 'node:crypto'
45
+ import fs from 'node:fs'
46
+ import fsp from 'node:fs/promises'
47
+ import { createRequire } from 'node:module'
48
+ import path from 'node:path'
49
+ import { fileURLToPath } from 'node:url'
50
+ import { ASSETS_TOTAL_MB, ASSET_KINDS, CREDITS_SHOWN, SPLAT_LIMITS, TEXTURE_BUDGETS, TRIANGLE_BUDGETS, assetKindOf, briefDensityFor, isPublishablePath, licenseVerdict, mapSide, planetSplats } from '../../schema/dist/index.js'
51
+ import { decodeImage } from '../reference/decode.mjs'
52
+ import { readBrief, recordPick } from './brief.mjs'
53
+ import { bindArmOcclusion, boundsOf, optimiseModel, readGltf, sizeText, validateFile } from './gltf.mjs'
54
+ import { encodeHdr, exrHeader, measureFloat, measureHdr } from './hdr.mjs'
55
+ import { imageSize } from './imageOps.mjs'
56
+ import { densityVerdict, inspectMaterial, inspectModelDoc, inspectPicture, ktx2Record, materialFiles, reportLines } from './inspect.mjs'
57
+ import { ktx2For } from './ktx2.mjs'
58
+ import { ownedLicenseRefusal, putEntries, readLedger, recordAsset, today } from './ledger.mjs'
59
+ import { decodersFor } from './targets.mjs'
60
+ import { seamScore } from './tile.mjs'
61
+ import { MAX_TRIANGLES as COLLIDER_TRIANGLES, prepareCollider } from './collider.mjs'
62
+ import { footprintOverlap } from './footprint.mjs'
63
+ import { encodeSpz, readSplat, splatCountOf, splatStats, transformSplat } from './splat.mjs'
64
+ import { webLookOnlyAmong } from '../reference/web.mjs'
65
+
66
+ const require = createRequire(import.meta.url)
67
+ const { DOWNLOAD_TYPES, QUARANTINE, blockedHost, checkFile, readManifest } = require('../downloads.cjs')
68
+ const here = path.dirname(fileURLToPath(import.meta.url))
69
+
70
+ /** BLENDER's programs: convert.py turns fbx, obj, stl, ply, usd and dae
71
+ * into a GLB; cleanup.py cleans a model from outside up for the game;
72
+ * sheet.py renders the contact sheets and scores the model. The path of
73
+ * convert.py comes from tools/blender.mjs (CONVERT) when it says, else from
74
+ * the folder they live in. */
75
+ const blenderTool = await import('../tools/blender.mjs').catch(() => null)
76
+ export const CONVERT = blenderTool?.CONVERT ?? path.join(here, '..', 'blender', 'convert.py')
77
+ export const CLEANUP = path.join(here, '..', 'blender', 'cleanup.py')
78
+ export const SHEET = path.join(here, '..', 'blender', 'sheet.py')
79
+
80
+ const MB = 1024 * 1024
81
+ const MODEL_ORDER = ['.glb', '.gltf', '.fbx', '.obj', '.usdz', '.usd', '.usda', '.usdc', '.dae', '.stl', '.ply', '.3mf']
82
+ const BLENDER_FORMATS = new Set(['.fbx', '.obj', '.usdz', '.usd', '.usda', '.usdc', '.dae', '.stl', '.ply'])
83
+ const IMAGES = new Set(['.png', '.jpg', '.jpeg', '.webp'])
84
+ const AUDIO = new Set(['.ogg', '.mp3', '.wav', '.flac'])
85
+
86
+ const slash = (p) => p.split(path.sep).join('/')
87
+ const fail = (text) => ({ text, isError: true })
88
+ const round = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d
89
+ const mb = (b) => (b / MB).toFixed(b < MB ? 2 : 1)
90
+
91
+ function realOrSelf(p) {
92
+ let head = path.resolve(p)
93
+ const rest = []
94
+ for (;;) {
95
+ try {
96
+ return path.join(fs.realpathSync(head), ...rest)
97
+ } catch {
98
+ const up = path.dirname(head)
99
+ if (up === head) return path.resolve(p)
100
+ rest.unshift(path.basename(head))
101
+ head = up
102
+ }
103
+ }
104
+ }
105
+ const within = (root, target) => {
106
+ const rel = path.relative(root, target)
107
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)
108
+ }
109
+
110
+ /** Every file under a folder, as absolute paths, dotfiles and the source
111
+ * record left out. */
112
+ async function listFiles(dir) {
113
+ const out = []
114
+ const walk = async (d) => {
115
+ for (const e of await fsp.readdir(d, { withFileTypes: true }).catch(() => [])) {
116
+ if (e.name.startsWith('.') || e.name === 'source.json') continue
117
+ const abs = path.join(d, e.name)
118
+ if (e.isDirectory()) await walk(abs)
119
+ else if (e.isFile()) out.push(abs)
120
+ }
121
+ }
122
+ await walk(dir)
123
+ return out.sort()
124
+ }
125
+
126
+ /** What `from` names in quarantine: { abs, isDir, entry, source, sourceDir }
127
+ * or { error }. */
128
+ export async function resolveFrom(projectRoot, from) {
129
+ const root = realOrSelf(projectRoot)
130
+ const q = realOrSelf(path.join(root, QUARANTINE))
131
+ if (!fs.existsSync(q)) return { error: 'Nothing is in quarantine yet: fetch something with asset_fetch, or download it in the browser, first.' }
132
+ const manifest = readManifest(root)
133
+ let entry = manifest.files.find((f) => f.id === from) ?? null
134
+ let abs
135
+ if (entry) abs = realOrSelf(path.join(q, entry.file))
136
+ else {
137
+ const plain = String(from).replace(/\\/g, '/')
138
+ abs = realOrSelf(path.isAbsolute(from) ? from : plain.startsWith('.nowhere/') ? path.join(root, plain) : path.join(q, plain))
139
+ }
140
+ if (!within(q, abs)) {
141
+ const ids = manifest.files.map((f) => f.id).slice(-12)
142
+ return { error: `"${from}" is not inside .nowhere/quarantine/: asset_import takes only what was fetched or downloaded there.${ids.length ? ` In quarantine: ${ids.join(', ')}.` : ''}` }
143
+ }
144
+ let st
145
+ try {
146
+ st = await fsp.stat(abs)
147
+ } catch {
148
+ const ids = manifest.files.map((f) => f.id).slice(-12)
149
+ return { error: `Nothing in quarantine is called "${from}".${ids.length ? ` In quarantine: ${ids.join(', ')}.` : ''}` }
150
+ }
151
+ // The record of where it came from: the item's source.json, the nearest one
152
+ // up from the file inside quarantine.
153
+ let source = null
154
+ let sourceDir = null
155
+ for (let d = st.isDirectory() ? abs : path.dirname(abs); within(q, d) || d === q; d = path.dirname(d)) {
156
+ const candidate = path.join(d, 'source.json')
157
+ if (fs.existsSync(candidate)) {
158
+ try {
159
+ source = JSON.parse(await fsp.readFile(candidate, 'utf8'))
160
+ sourceDir = d
161
+ } catch {
162
+ return { error: `${slash(path.relative(root, candidate))} is not valid JSON, so where this came from is unknown.` }
163
+ }
164
+ break
165
+ }
166
+ if (d === q) break
167
+ }
168
+ if (!entry) {
169
+ const rel = slash(path.relative(q, abs))
170
+ entry = manifest.files.find((f) => f.file === rel || rel.startsWith(`${f.file}/`) || rel.startsWith(`${f.id}/`)) ?? null
171
+ }
172
+ // Named by its id or by its path in quarantine, a download that failed its
173
+ // check stays there.
174
+ if (entry && entry.ok === false) return { error: `${entry.name ?? from} failed its check (${entry.problem}), so it stays in quarantine.` }
175
+ return { abs, isDir: st.isDirectory(), entry, source, sourceDir, root, q }
176
+ }
177
+
178
+ /** The licence to record, or the sentence that refuses the import. */
179
+ export function licenseFor({ source, given, confirmedShareAlike }) {
180
+ const base = source?.license && typeof source.license.spdx === 'string' ? { ...source.license } : null
181
+ if (!base && !given?.spdx) {
182
+ return {
183
+ error:
184
+ 'This file has no recorded source (it came from the browser, not asset_fetch): read its licence page first, then pass license { spdx, url, author, title, credit } (for example { "spdx": "CC0-1.0", "url": "<licence page>", "title": "...", "author": "..." }).',
185
+ }
186
+ }
187
+ // The creator's own, the studio's and a paid generator's licences are
188
+ // recorded by the drop, nw_blender and asset_job; a download carries the
189
+ // one on its page.
190
+ if (!base) {
191
+ const owned = ownedLicenseRefusal(given.spdx)
192
+ if (owned) return { error: `Not imported: ${owned}` }
193
+ }
194
+ const license = base ?? { spdx: given.spdx, ...(given.url ? { url: given.url } : {}) }
195
+ if (!license.credit && given?.credit) license.credit = given.credit
196
+ if (confirmedShareAlike === true) license.confirmedByCreator = true
197
+ const verdict = licenseVerdict(license)
198
+ if (!verdict.ok) {
199
+ const how =
200
+ verdict.code === 'ledger:credit'
201
+ ? ' Pass license.credit: the line visitors would see, e.g. "Boat" by J. Doe (https://...), CC BY 4.0.'
202
+ : verdict.code === 'ledger:sa-unconfirmed'
203
+ ? ' Ask the creator with nw_ask (kind choice), in the screen language, whether to accept that; only after a yes, import again with confirmedShareAlike: true.'
204
+ : ' Pick another file: a CC0 one from asset_search is never a problem.'
205
+ return { error: `Not imported: ${verdict.reason}.${how}` }
206
+ }
207
+ return { license: { checkedAt: today(), ...license }, credit: verdict.credit }
208
+ }
209
+
210
+ /** A creator's own scan: theirs, as their drop into the studio is
211
+ * (LicenseRef-Creator-Declared), recorded as the creator's. Only after the
212
+ * creator said in a card that they made it; a file that came with a source
213
+ * record came from somewhere else, and keeps that record's licence. */
214
+ export function captureLicense(resolved) {
215
+ if (resolved.source?.license?.spdx) {
216
+ return { error: `Not imported as a capture: it came from ${resolved.source.provider ?? 'a source'} with a source record (${resolved.source.license.spdx}), so it is not the creator's own scan. Import it without capture.` }
217
+ }
218
+ // A download names where it came from: someone's scan on a gallery site is
219
+ // theirs, whatever a card says, and comes in with the licence on its page.
220
+ const from = [resolved.entry?.url, resolved.entry?.referrer].find((u) => typeof u === 'string' && u.trim())
221
+ if (from) {
222
+ return { error: `Not imported as a capture: it was downloaded from ${from.slice(0, 200)}, so it is not the creator's own scan. Import it without capture, with the licence its page gives (license, and license.credit when it asks for credit).` }
223
+ }
224
+ const title = String(resolved.entry?.name ?? path.basename(resolved.abs)).slice(0, 200)
225
+ return {
226
+ license: { checkedAt: today(), spdx: 'LicenseRef-Creator-Declared' },
227
+ credit: false,
228
+ origin: 'creator',
229
+ source: { provider: 'creator', title, ...(resolved.entry?.at ? { fetchedAt: String(resolved.entry.at) } : {}) },
230
+ }
231
+ }
232
+
233
+ /** Where the target is, or why it cannot be one. */
234
+ function targetFor(root, as, { kind, replace }) {
235
+ const clean = String(as ?? '').replace(/\\/g, '/').replace(/^\.\//, '')
236
+ const m = /^assets\/([A-Za-z0-9][A-Za-z0-9_-]{0,63})(\.[A-Za-z0-9]+)?$/.exec(clean)
237
+ if (!m) return { error: `as "${as}" is not assets/<name>${kind === 'material' ? '' : '.<ext>'} (letters, digits, _ and -; one file directly inside assets/).` }
238
+ return { rel: clean, stem: m[1], ext: (m[2] ?? '').toLowerCase(), abs: path.join(root, 'assets', `${m[1]}${m[2] ?? ''}`), replace }
239
+ }
240
+
241
+ /** The ledger's `source` for what came in. */
242
+ function sourceRecord(resolved, given) {
243
+ const s = resolved.source
244
+ const e = resolved.entry
245
+ const valid = (u) => {
246
+ try {
247
+ return new URL(u).protocol.startsWith('http') ? u : undefined
248
+ } catch {
249
+ return undefined
250
+ }
251
+ }
252
+ if (s) {
253
+ return {
254
+ provider: String(s.provider ?? 'web').slice(0, 40),
255
+ ...(s.id ? { id: String(s.id).slice(0, 200) } : {}),
256
+ ...(valid(s.url) ? { url: s.url } : {}),
257
+ ...(s.author ? { author: String(s.author).slice(0, 120) } : {}),
258
+ ...(s.title ? { title: String(s.title).slice(0, 200) } : {}),
259
+ ...(s.host ? { host: String(s.host).slice(0, 200) } : {}),
260
+ ...(s.fetchedAt ? { fetchedAt: String(s.fetchedAt) } : {}),
261
+ }
262
+ }
263
+ return {
264
+ provider: 'web',
265
+ ...(valid(e?.url) ? { url: e.url } : valid(given?.url) ? { url: given.url } : {}),
266
+ ...(given?.author ? { author: String(given.author).slice(0, 120) } : {}),
267
+ ...(given?.title || e?.name ? { title: String(given?.title ?? e.name).slice(0, 200) } : {}),
268
+ ...(e?.host ? { host: String(e.host).slice(0, 200) } : {}),
269
+ ...(e?.at ? { fetchedAt: String(e.at) } : {}),
270
+ }
271
+ }
272
+
273
+ /** A recorded host this file may not come from, or null. */
274
+ function blockedOrigin(resolved) {
275
+ const candidates = [resolved.source?.url, resolved.source?.host && `https://${resolved.source.host}/`, resolved.entry?.url, resolved.entry?.referrer, resolved.entry?.host && `https://${resolved.entry.host}/`]
276
+ return candidates.find((u) => typeof u === 'string' && u && blockedHost(u)) ?? null
277
+ }
278
+
279
+ async function writeInto(work, target, bytesOrFile) {
280
+ await fsp.mkdir(path.dirname(target), { recursive: true })
281
+ const temp = path.join(work, `out-${randomBytes(4).toString('hex')}`)
282
+ if (typeof bytesOrFile === 'string') await fsp.copyFile(bytesOrFile, temp)
283
+ else await fsp.writeFile(temp, bytesOrFile)
284
+ await fsp.rename(temp, target)
285
+ }
286
+
287
+ /** Picks the model file in a folder: the most usable format first. */
288
+ function pickModel(files) {
289
+ for (const ext of MODEL_ORDER) {
290
+ const hits = files.filter((f) => path.extname(f).toLowerCase() === ext)
291
+ if (hits.length) return { file: hits[0], others: hits.length - 1 }
292
+ }
293
+ return null
294
+ }
295
+
296
+ /** The role a material map plays, by its file name or what the source said. */
297
+ export function roleOf(file, roles = {}) {
298
+ const name = path.basename(file).toLowerCase()
299
+ if (roles[name]) return roles[name]
300
+ if (/preview|thumb|sphere|swatch/.test(name)) return null
301
+ // Metal, displacement and opacity by the name's last word, past its
302
+ // resolution and format ("MetalPlates006_1K-JPG_Metalness", "x_disp_2k"):
303
+ // an asset's own name may hold those words ("metal_plate_diff").
304
+ const last = name.replace(/\.[a-z0-9]+$/, '').split(/[^a-z0-9]+/).filter((w) => w && !/^(\d+k|jpe?g|png|exr|webp|gl|dx)$/.test(w)).pop() ?? ''
305
+ if (/^(metal|metalness|metallic)$/.test(last)) return 'metal'
306
+ if (/^(disp|displacement|height)$/.test(last)) return 'displacement'
307
+ if (/^(opacity|alpha)$/.test(last)) return 'opacity'
308
+ if (/(nor_gl|normalgl|normal_gl|normal-gl)/.test(name)) return 'normal'
309
+ if (/(nor_dx|normaldx|normal_dx|normal-dx)/.test(name)) return 'normal-dx'
310
+ if (/(^|[^a-z])(normal|nrm|nor)([^a-z]|$)/.test(name)) return 'normal'
311
+ if (/(rough|roughness)/.test(name)) return 'rough'
312
+ if (/(ambientocclusion|ambient_occlusion|occlusion|(^|[^a-z])ao([^a-z]|$))/.test(name)) return 'ao'
313
+ if (/(diff|diffuse|albedo|basecolor|base_color|base-color|(^|[^a-z])col(or)?([^a-z]|$))/.test(name)) return 'color'
314
+ return null
315
+ }
316
+
317
+ function rubricLines(rubric) {
318
+ if (!rubric || typeof rubric !== 'object') return []
319
+ const part = (k) => (rubric[k] && typeof rubric[k].score === 'number' ? `${k} ${rubric[k].score}/5${rubric[k].note ? ` (${rubric[k].note})` : ''}` : null)
320
+ const lines = []
321
+ const parts = ['silhouette', 'bevel', 'materials', 'budget'].map(part).filter(Boolean)
322
+ if (parts.length) lines.push(`rubric: ${parts.join(', ')}`)
323
+ if (rubric.fixFirst) lines.push(`fix first: ${rubric.fixFirst}`)
324
+ return lines
325
+ }
326
+
327
+ /** The download check (downloads.cjs checkFile) on a file about to be used,
328
+ * or null when it passes. The manifest's verdict covers only what the
329
+ * browser saved under its own name; a file curl saved, or one unpacked from
330
+ * an archive, is looked at here. Types the check does not know (.usd, .cube)
331
+ * are checked by what reads them. */
332
+ async function contentProblem(file) {
333
+ if (!DOWNLOAD_TYPES[path.extname(file).toLowerCase()]) return null
334
+ const r = await checkFile(file)
335
+ return r.ok ? null : `${path.basename(file)} failed its check (${r.problem}), so it stays in quarantine.`
336
+ }
337
+
338
+ /**
339
+ * The import itself. Answers a ToolResult; never throws.
340
+ */
341
+ export async function importAsset(args, ctx, deps) {
342
+ if (!ctx?.projectRoot) return fail('No project is open, so there is nowhere to import into.')
343
+ const resolved = await resolveFrom(ctx.projectRoot, args.from)
344
+ if (resolved.error) return fail(resolved.error)
345
+ const { root } = resolved
346
+
347
+ const blocked = blockedOrigin(resolved)
348
+ if (blocked) return fail(`Not imported: it was recorded as coming from ${new URL(blocked).hostname}, and ArtStation, Pinterest and Behance are for the creator's eyes only; their terms forbid feeding their images to AI tools.`)
349
+
350
+ // What is being imported: the target's extension says, else the source's kind.
351
+ const asExt = (/\.[A-Za-z0-9]+$/.exec(String(args.as ?? ''))?.[0] ?? '').toLowerCase()
352
+ const kind = asExt ? (assetKindOf(`x${asExt}`) ?? 'unknown') : 'material'
353
+ if (kind === 'unknown') return fail(`as "${args.as}" has an extension a planet does not carry. Use .glb for a model, assets/<name> for a material, .hdr or .exr for an HDRI, .ogg or .mp3 for a sound, .cube for a LUT, .spz for a splat.`)
354
+ if (kind === 'model' && asExt !== '.glb') return fail(`A model comes in as one GLB: use as "assets/<name>.glb".`)
355
+
356
+ // A creator's own scan carries no licence page: it is theirs, which only
357
+ // they can say (an nw_ask choice card), and only a splat comes in so.
358
+ if (args.capture === true && kind !== 'splat') return fail('capture is for a splat the creator scanned themselves (as "assets/<name>.spz"); anything else comes in with the licence on its page.')
359
+ const lic = args.capture === true ? captureLicense(resolved) : licenseFor({ source: resolved.source, given: args.license, confirmedShareAlike: args.confirmedShareAlike })
360
+ if (lic.error) return fail(lic.error)
361
+
362
+ const files = resolved.isDir ? await listFiles(resolved.abs) : [resolved.abs]
363
+ if (files.length === 0) return fail(`"${args.from}" holds no files.`)
364
+ // A web reference kept to look at only never becomes one of the space's files.
365
+ const web = await webLookOnlyAmong(root, files)
366
+ if (web) return fail(`Not imported: ${path.basename(web.file)} is a web reference kept to look at only (${web.why}), so it never goes into the space. Build what it shows, or use a CC0 or public-domain picture.`)
367
+
368
+ const target = targetFor(root, args.as, { kind })
369
+ if (target.error) return fail(target.error)
370
+
371
+ const work = path.join(root, '.nowhere', 'import', `${Date.now()}-${randomBytes(3).toString('hex')}`)
372
+ await fsp.mkdir(work, { recursive: true })
373
+ // What to write for the server and the player this project publishes to:
374
+ // what the last Publish found (targets.mjs), or a check's own decoders.
375
+ const decoders = decodersFor(ctx.projectRoot, deps.decoders ? { live: deps.decoders, sides: {} } : {})
376
+ const common = {
377
+ args,
378
+ ctx,
379
+ deps,
380
+ resolved,
381
+ files,
382
+ target,
383
+ license: lic.license,
384
+ needsCredit: lic.credit,
385
+ work,
386
+ decoders,
387
+ source: lic.source ?? sourceRecord(resolved, args.license),
388
+ ...(lic.origin ? { origin: lic.origin } : {}),
389
+ }
390
+ try {
391
+ if (kind === 'model') return await importModel(common)
392
+ if (kind === 'material') return await importMaterial(common)
393
+ if (kind === 'texture') return await importTexture(common)
394
+ if (kind === 'hdri') return await importHdri(common)
395
+ if (kind === 'audio') return await importAudio(common)
396
+ if (kind === 'lut') return await importLut(common)
397
+ if (kind === 'splat') return await importSplat(common)
398
+ return fail(`Nothing imports ${kind} files yet.`)
399
+ } catch (err) {
400
+ return fail(`asset_import failed: ${err?.message ?? err}`)
401
+ } finally {
402
+ await fsp.rm(work, { recursive: true, force: true })
403
+ }
404
+ }
405
+
406
+ const exists = (abs) => fs.existsSync(abs)
407
+ const existingRefusal = (rel) => fail(`${rel} already exists. Pass replace: true to overwrite it, or pick another name.`)
408
+
409
+ function originOf(resolved) {
410
+ if (resolved.source?.generation || ['meshy', 'fal', 'tripo', 'worldlabs'].includes(resolved.source?.provider)) return 'generated'
411
+ return 'download'
412
+ }
413
+
414
+ function generationOf(resolved) {
415
+ const g = resolved.source?.generation
416
+ if (!g) return undefined
417
+ return { vendor: String(g.vendor), model: String(g.model ?? ''), prompt: String(g.prompt ?? '').slice(0, 2000), job: String(g.job ?? ''), usd: Number(g.usd) || 0 }
418
+ }
419
+
420
+ const SHA = /^[0-9a-f]{64}$/
421
+
422
+ /** What a generated file was made from, as its job recorded it: the whole
423
+ * prompt's hash and the project pictures it started from (a reference's
424
+ * crop, a picture made for it), for the entry's meta. */
425
+ function provenanceOf(resolved) {
426
+ const p = resolved.source?.provenance
427
+ if (!p || typeof p !== 'object') return null
428
+ const inputs = (Array.isArray(p.inputs) ? p.inputs : []).filter((i) => typeof i?.path === 'string' && SHA.test(String(i.sha256))).slice(0, 8)
429
+ return { ...(SHA.test(String(p.promptSha256)) ? { promptSha256: p.promptSha256 } : {}), inputs }
430
+ }
431
+
432
+ const stepsFor = (resolved, args, more) => [
433
+ { op: 'asset_import', at: new Date().toISOString(), detail: `from ${slash(path.relative(resolved.q, resolved.abs))}${args.class ? `, class ${args.class}` : ''}`.slice(0, 400) },
434
+ ...more.map((s) => ({ op: String(s.op).slice(0, 40), at: new Date().toISOString(), detail: String(s.detail).slice(0, 400) })),
435
+ ].slice(0, 50)
436
+
437
+ async function record(c, rel, kind, extra = {}) {
438
+ const provenance = provenanceOf(c.resolved)
439
+ // What it was made from that the ledger keeps (a crop, a picture made for it).
440
+ const from = (provenance?.inputs ?? []).map((i) => i.path).filter((p) => /^(assets|blender)\//.test(p))
441
+ const r = await recordAsset(c.ctx.projectRoot, rel, {
442
+ kind,
443
+ origin: c.origin ?? originOf(c.resolved),
444
+ license: c.license,
445
+ source: c.source,
446
+ ...(generationOf(c.resolved) ? { generation: generationOf(c.resolved) } : {}),
447
+ ...(from.length ? { derivedFrom: from } : {}),
448
+ steps: stepsFor(c.resolved, c.args, extra.steps ?? []),
449
+ ...(extra.meta || provenance ? { meta: { ...(extra.meta ?? {}), ...(provenance ? { provenance } : {}) } } : {}),
450
+ })
451
+ return r
452
+ }
453
+
454
+ const creditNote = (c) =>
455
+ !c.needsCredit
456
+ ? ''
457
+ : CREDITS_SHOWN
458
+ ? ` It is ${c.license.spdx}: the planet shows its credit line ("${c.license.credit}") to visitors, from the ledger, and a server or player from before publish contract 4 refuses it until they can.`
459
+ : ` It is ${c.license.spdx}: it works in the studio, but publishing refuses it until planets can show credits to visitors (decision D2). Prefer a CC0 file for anything that must ship.`
460
+
461
+ // ---------------------------------------------------------------- model
462
+
463
+ const pad = (n) => String(n).padStart(2, '0')
464
+ /** A render folder's name as nw_blender writes its own (yyyymmdd-hhmmss),
465
+ * -2, -3 after a second taken already, so the gate reads the newest. */
466
+ function renderStamp(base, d = new Date()) {
467
+ const now = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
468
+ let names = []
469
+ try {
470
+ names = fs.readdirSync(base)
471
+ } catch {
472
+ // the first render of this model
473
+ }
474
+ const taken = names.filter((n) => n === now || n.startsWith(`${now}-`)).map((n) => (n === now ? 1 : Number(n.slice(now.length + 1)) || 1))
475
+ return taken.length ? `${now}-${Math.max(...taken) + 1}` : now
476
+ }
477
+
478
+ /** cleanup.py on a GLB, when Blender is here: { file, result, line } of the
479
+ * cleaned copy, or { line } that says why the model goes on as it came. */
480
+ async function cleanUp(c, found, file, className, maxTexture) {
481
+ if (!found?.path || found.error || !exists(CLEANUP)) return { line: 'not cleaned up in Blender (Blender not found): sized and simplified by the glTF pipeline only' }
482
+ const out = path.join(c.work, 'cleaned.glb')
483
+ const run = await c.deps.runBlender({
484
+ bin: found.path,
485
+ script: CLEANUP,
486
+ // A generator's mesh is welded and has its flecks taken off; a library's keeps its own.
487
+ args: { in_glb: file, out_glb: out, result: path.join(c.work, 'cleanup-result.json'), budget: TRIANGLE_BUDGETS[className] ?? TRIANGLE_BUDGETS.prop, max_texture: maxTexture, size: c.args.size ?? null, pivot: c.args.pivot ?? 'base', generated: originOf(c.resolved) === 'generated' },
488
+ cwd: path.join(c.work, 'blender'),
489
+ timeoutMs: 240_000,
490
+ })
491
+ const r = run?.result
492
+ if (!r?.ok || !exists(out)) {
493
+ const why = r?.ok ? 'it wrote no GLB' : (r?.error ?? (run?.timedOut ? 'it did not finish within 4 minutes' : 'Blender gave no answer'))
494
+ return { line: `the Blender cleanup did not run (${String(why).slice(0, 200)}): sized and simplified by the glTF pipeline only` }
495
+ }
496
+ const checked = await validateFile(out)
497
+ if (checked.numErrors > 0) return { line: `the Blender cleanup's GLB did not pass the glTF validator (${checked.errors[0] ?? 'an error'}), so the model goes on as it came` }
498
+ const before = r.before?.triangles
499
+ const after = r.after?.triangles
500
+ return { file: out, result: r, line: `cleaned up in Blender ${r.blender ?? found.version ?? ''}: ${before ?? '?'} to ${after ?? '?'} triangles`.replace(/ {2}/g, ' ') }
501
+ }
502
+
503
+ async function importModel(c) {
504
+ const { args, deps, files, target, work } = c
505
+ if (exists(target.abs) && !args.replace) return existingRefusal(target.rel)
506
+ const picked = pickModel(files)
507
+ if (!picked) return fail(`No model file in "${args.from}" (looked for ${MODEL_ORDER.join(', ')}).`)
508
+ const ext = path.extname(picked.file).toLowerCase()
509
+ const bad = await contentProblem(picked.file)
510
+ if (bad) return fail(bad)
511
+ const lines = []
512
+ let validation = null
513
+ let sourceFile = picked.file
514
+ if (ext === '.3mf') return fail('This file is .3mf, which the import does not convert. Pick the GLB or FBX download, or export it as GLB in Blender.')
515
+ const found = await deps.findBlender().catch(() => null)
516
+ if (BLENDER_FORMATS.has(ext)) {
517
+ if (found?.error || !found?.path) return fail(`This file is ${ext}; Blender (4.2 or later) converts it. Or pick the GLB download.`)
518
+ const out = path.join(work, 'converted.glb')
519
+ const run = await deps.runBlender({ bin: found.path, script: CONVERT, args: { in: picked.file, out_glb: out, result: path.join(work, 'convert-result.json') }, cwd: path.join(work, 'blender'), timeoutMs: 180_000 })
520
+ if (!run?.result?.ok || !exists(out)) {
521
+ const why = run?.result?.error ?? (run?.timedOut ? 'it did not finish within 3 minutes' : `Blender stopped without an answer (${String(run?.stderr ?? run?.error ?? '').trim().split('\n').slice(-2).join(' ').slice(0, 200)})`)
522
+ return fail(`Blender could not convert ${path.basename(picked.file)}: ${why}`)
523
+ }
524
+ lines.push(`converted from ${ext} with Blender ${found.version ?? ''}`.trim() + (run.result.warnings?.length ? ` (${run.result.warnings.slice(0, 3).join('; ')})` : ''))
525
+ sourceFile = out
526
+ }
527
+ validation = await validateFile(sourceFile)
528
+ if (validation.numErrors > 0) {
529
+ return fail(`The model did not pass the glTF validator, so nothing was written (${validation.numErrors} errors). The first ones:\n${validation.errors.slice(0, 5).map((e) => `- ${e}`).join('\n')}`)
530
+ }
531
+ const sourceBytes = (BLENDER_FORMATS.has(ext) ? [picked.file] : files).reduce((n, f) => n + (fs.statSync(f).size ?? 0), 0)
532
+ const className = args.class ?? 'prop'
533
+ const maxTexture = args.maxTexture ?? TEXTURE_BUDGETS[className] ?? TEXTURE_BUDGETS.prop
534
+ // Every model from outside is cleaned up in Blender before the pipeline
535
+ // sizes, simplifies, checks and records it.
536
+ const cleaned = await cleanUp(c, found, sourceFile, className, maxTexture)
537
+ if (cleaned.file) sourceFile = cleaned.file
538
+ let doc
539
+ try {
540
+ doc = await readGltf(sourceFile)
541
+ } catch (err) {
542
+ return fail(`The model could not be read: ${err.message}.`)
543
+ }
544
+ // Poly Haven's ao is the red channel of the _arm map its glTF binds only
545
+ // as metallicRoughness.
546
+ const armBound = c.resolved.source?.provider === 'polyhaven' ? bindArmOcclusion(doc) : 0
547
+ const armLine = armBound ? `the _arm map's red channel bound as occlusion on ${armBound} ${armBound === 1 ? 'material' : 'materials'} (Poly Haven packs ao, rough and metal in it and binds only the last two)` : null
548
+ const result = await optimiseModel({
549
+ doc,
550
+ className,
551
+ size: args.size,
552
+ pivot: args.pivot,
553
+ maxTexture: args.maxTexture,
554
+ simplify: args.simplify,
555
+ // Sized by the cleanup to what was asked, it is in metres now.
556
+ statedMetres: c.resolved.source?.meta?.units === 'm' || (!!cleaned.file && !!args.size),
557
+ imageOps: deps.imageOps,
558
+ workDir: path.join(work, 'textures'),
559
+ // ktx2 "off" keeps the textures pictures; the geometry is the sides'
560
+ // call. A download whose textures are KTX2 already is then refused for
561
+ // that reason, not for the sides (offWhy).
562
+ decoders: c.decoders.ktx2 && args.ktx2 === 'off' ? { ...c.decoders, ktx2: false, offWhy: KTX2_OFF } : c.decoders,
563
+ })
564
+ if (!result.ok) return fail(result.error)
565
+ const r = result.report
566
+ // Inspected before it is written: its maps, and its texel density against
567
+ // the brief, which refuses it under half the target.
568
+ const mode = ktx2Mode(c)
569
+ const report = await inspectModelDoc(doc, { file: target.rel, projectRoot: c.ctx.projectRoot, ktx2: mode === 'measure', rpc: c.ctx.rpc })
570
+ if (report.density?.verdict === 'refuse' && !args.belowTarget) return fail(densityRefusal(`${target.rel} at its ${r.after.textures.map((t) => `${t.width ?? '?'} px`).join(', ')} textures`, report.density))
571
+ await writeInto(work, target.abs, result.glb)
572
+
573
+ // The contact sheet: how it looks, with the rubric when Blender scores it.
574
+ const images = []
575
+ const sheetLines = []
576
+ let rubric = null
577
+ if (found?.path && !found.error && exists(SHEET)) {
578
+ const base = path.join(c.ctx.projectRoot, '.nowhere', 'renders', target.stem)
579
+ const outDir = path.join(base, renderStamp(base))
580
+ const expect = args.size ? Object.fromEntries(['height', 'width', 'depth'].filter((k) => typeof args.size[k] === 'number').map((k) => [k, args.size[k]])) : null
581
+ // Blender reads neither meshopt nor KTX2: the sheet is of the copy
582
+ // without them (gltf.mjs blenderCopy), which looks the same.
583
+ let sheetGlb = target.abs
584
+ if (result.plainGlb) {
585
+ sheetGlb = path.join(work, 'sheet-source.glb')
586
+ await fsp.writeFile(sheetGlb, result.plainGlb)
587
+ }
588
+ const sheet = await deps.runBlender({
589
+ bin: found.path,
590
+ script: SHEET,
591
+ args: { glb: sheetGlb, out_dir: outDir, size: 512, closeup: null, render: true, engines: null, result: path.join(work, 'sheet-result.json'), class: className, expect, budget: TRIANGLE_BUDGETS[className] ?? TRIANGLE_BUDGETS.prop },
592
+ cwd: path.join(work, 'blender'),
593
+ timeoutMs: 240_000,
594
+ })
595
+ const res = sheet?.result
596
+ if (res?.ok && res.sheets) {
597
+ for (const file of [res.sheets.color_model ?? res.sheets.color, res.sheets.clay_model ?? res.sheets.clay]) {
598
+ try {
599
+ if (file) images.push({ data: (await fsp.readFile(file)).toString('base64'), mime: 'image/jpeg' })
600
+ } catch {
601
+ // the text says where the renders are
602
+ }
603
+ }
604
+ sheetLines.push(`contact sheets (colour, then clay) in ${slash(path.relative(c.ctx.projectRoot, outDir))}: front, side, back; three-quarter, top, close-up, with a 1.75 m figure.`)
605
+ sheetLines.push(...rubricLines(res.rubric))
606
+ if (res.rubric) rubric = Object.fromEntries(['silhouette', 'bevel', 'materials', 'budget'].map((k) => [k, res.rubric[k]?.score ?? null]))
607
+ } else {
608
+ sheetLines.push(`No contact sheet (the render run failed: ${String(res?.error ?? sheet?.error ?? 'no answer').slice(0, 160)}): place it and look with nw_view.`)
609
+ }
610
+ } else {
611
+ sheetLines.push('No contact sheet (Blender not found): place it and look with nw_view.')
612
+ }
613
+
614
+ const cleanupSteps = (cleaned.result?.steps ?? []).map((s) => ({ op: `blender ${s.op}`, detail: s.detail }))
615
+ const problems = cleaned.result?.problems ?? []
616
+ const rec = await record(c, target.rel, 'model', {
617
+ steps: [...(lines.length ? [{ op: 'convert', detail: lines[0] }] : []), { op: 'cleanup', detail: cleaned.line }, ...cleanupSteps, ...(armLine ? [{ op: 'occlusion', detail: armLine }] : []), ...r.steps],
618
+ // The same shape nw_blender records, so either kind of model reads alike,
619
+ // with what the cleanup found for the gate.
620
+ meta: {
621
+ triangles: r.after.triangles,
622
+ size_m: r.bounds ? { width: r.bounds.size[0], height: r.bounds.size[1], depth: r.bounds.size[2] } : null,
623
+ class: className,
624
+ ...(rubric ? { rubric } : {}),
625
+ cleanup: cleaned.result ? { blender: true, before: cleaned.result.before?.triangles ?? null, problems: problems.slice(0, 8) } : { blender: false },
626
+ ...(report.densityPx ? { texel_density: report.densityPx } : {}),
627
+ maps: Object.fromEntries(report.materials.map((m) => [m.name, Object.keys(m.maps)])),
628
+ ...(report.untextured.length ? { untextured: report.untextured } : {}),
629
+ ...(c.decoders.meshopt ? { meshopt: { bytes: r.bytes, written: true } } : r.meshoptBytes ? { meshopt: { bytes: r.meshoptBytes, written: false } } : {}),
630
+ ...(Object.keys(ktx2Record(report)).length ? { ktx2: ktx2Record(report) } : {}),
631
+ },
632
+ })
633
+ const pickNote = await pickInto(c, 'model')
634
+
635
+ const text = [
636
+ `Imported ${target.rel} (${mb(r.bytes)} MB, from ${mb(sourceBytes)} MB) as a ${className}: ${r.after.triangles.toLocaleString('en-US')} triangles (budget ${r.budget.toLocaleString('en-US')}), ${r.after.meshes} ${r.after.meshes === 1 ? 'mesh' : 'meshes'}, ${r.after.materials} ${r.after.materials === 1 ? 'material' : 'materials'}, ${r.after.textures.length} textures${r.after.textures.length ? ` (${r.after.textures.map((t) => `${t.width ?? '?'}x${t.height ?? '?'}`).join(', ')})` : ''}.`,
637
+ r.bounds ? `size: ${sizeText(r.bounds.size)}; lowest point y = ${r.bounds.min[1]}` : 'size: unknown',
638
+ `licence: ${c.license.spdx}${c.license.credit ? `, credit "${c.license.credit}"` : ''}${c.source.title ? `; "${c.source.title}"` : ''}${c.source.author ? ` by ${c.source.author}` : ''}`,
639
+ ...lines.map((l) => `- ${l}`),
640
+ `- ${cleaned.line}`,
641
+ ...cleanupSteps.map((s) => `- ${s.op}: ${s.detail}`),
642
+ ...(armLine ? [`- occlusion: ${armLine}`] : []),
643
+ ...(problems.length ? [`materials and textures to look at: ${problems.slice(0, 6).join('; ')}`] : []),
644
+ ...r.steps.map((s) => `- ${s.op}: ${s.detail}`),
645
+ ...(r.warnings.length || validation.warnings.length ? [`validator warnings: ${[...validation.warnings, ...r.warnings].slice(0, 5).join('; ')}`] : []),
646
+ c.decoders.why ? `${c.decoders.why}${r.meshoptBytes ? ` meshopt would make it ${mb(r.meshoptBytes)} MB.` : ''}` : null,
647
+ pickNote,
648
+ '',
649
+ `Inspection (asset_inspect "${target.rel}" runs it again):`,
650
+ ...reportLines(report),
651
+ '',
652
+ rec.ok ? `Recorded in assets.lock.json; CREDITS.md updated.${creditNote(c)}` : `The file is in, but the ledger could not record it: ${rec.error}`,
653
+ picked.others ? `(${picked.others} other ${ext} file(s) in the folder were not used; name one in from to pick it.)` : null,
654
+ ...sheetLines,
655
+ `Use it: place it in scene.json with "normalize": false (it is already at its real size, which the studio would otherwise change to 3 m when over 12 m or under 0.375 m), or load it in code with ctx.assets.model('${target.rel}').`,
656
+ ].filter(Boolean)
657
+ return { text: text.join('\n'), ...(images.length ? { images } : {}) }
658
+ }
659
+
660
+ // ---------------------------------------------------------------- pictures
661
+
662
+ /** Resizes one picture into the project; answers what was written. */
663
+ async function placePicture(c, from, rel, maxSize) {
664
+ const bad = await contentProblem(from)
665
+ if (bad) return { error: bad }
666
+ const ext = path.extname(rel).toLowerCase()
667
+ const abs = path.join(c.ctx.projectRoot, ...rel.split('/'))
668
+ const temp = path.join(c.work, `pic-${randomBytes(3).toString('hex')}${ext}`)
669
+ const r = await c.deps.imageOps.resize(from, temp, { maxSize, format: ext === '.jpg' ? 'jpg' : 'png' })
670
+ if (r.error) return { error: `${path.basename(from)} could not be written as ${rel}: ${r.error}. Use the PNG or JPG download.` }
671
+ const bytes = (await fsp.stat(temp)).size
672
+ if (bytes > ASSET_KINDS.texture.fileMb * MB) {
673
+ return { error: `${rel} would be ${mb(bytes)} MB, over the ${ASSET_KINDS.texture.fileMb} MB a texture may weigh; import it with a smaller maxTexture.` }
674
+ }
675
+ await writeInto(c.work, abs, temp)
676
+ return { rel, width: r.width, height: r.height, bytes, how: r.how, resized: r.resized }
677
+ }
678
+
679
+ /** The longest side a material's maps or a texture keep: maxTexture, else
680
+ * the class's, else 2048 (a ground seen up close is fetched at 2k, and is
681
+ * kept so; a smaller picture is never made bigger). */
682
+ const pictureMax = (args) => args.maxTexture ?? (args.class ? TEXTURE_BUDGETS[args.class] : TEXTURE_BUDGETS.terrain) ?? 2048
683
+
684
+ const pictureExt = (file) => {
685
+ const e = path.extname(file).toLowerCase()
686
+ return e === '.jpeg' || e === '.jpg' ? '.jpg' : e === '.webp' ? '.png' : '.png'
687
+ }
688
+
689
+ /** What one tile of a material covers, in metres, [width, height]: the
690
+ * import's tileSize, else what the library says (Poly Haven in millimetres,
691
+ * ambientCG in centimetres), else the brief's material, else null. */
692
+ function tileOf(c, brief) {
693
+ const given = c.args.tileSize
694
+ if (typeof given === 'number') return [given, given]
695
+ if (Array.isArray(given)) return [given[0], given[1]]
696
+ const meta = c.resolved.source?.meta ?? {}
697
+ if (Array.isArray(meta.dimensions_mm) && meta.dimensions_mm[0] > 0) return [Math.round(meta.dimensions_mm[0]) / 1000, Math.round(meta.dimensions_mm[1] ?? meta.dimensions_mm[0]) / 1000]
698
+ if (Array.isArray(meta.dimensions_cm) && meta.dimensions_cm[0] > 0) return [meta.dimensions_cm[0] / 100, (meta.dimensions_cm[1] ?? meta.dimensions_cm[0]) / 100]
699
+ const fromBrief = brief?.materials.find((m) => m.name === c.target.stem)?.tileMetres
700
+ return fromBrief ? [fromBrief, fromBrief] : null
701
+ }
702
+
703
+ /** Why no KTX2 is written when the import itself said so. */
704
+ const KTX2_OFF = 'this import was asked for ktx2 "off", which keeps textures as the pictures they came as.'
705
+
706
+ /** 'write' where both sides take KTX2 (decodersFor), 'measure' when asked to
707
+ * (or 'off'), 'estimate' otherwise: the GPU bytes by arithmetic, nothing
708
+ * encoded. */
709
+ function ktx2Mode(c) {
710
+ const live = c.decoders.ktx2
711
+ if (c.args.ktx2 === 'off') return 'off'
712
+ if (live) return 'write'
713
+ return c.args.ktx2 === 'measure' ? 'measure' : 'estimate'
714
+ }
715
+
716
+ /** The sentence that refuses a texture under half the brief's density, with the ways out. */
717
+ const densityRefusal = (what, v) =>
718
+ `Not imported: ${what} would be ${v.words}. Fetch it at a higher resolution (asset_fetch with resolution "2k" or "4k"), let one tile cover less (a smaller tileSize, so it repeats more), or, if the brief's target is wrong for this surface, correct brief.json; belowTarget: true imports it as it is.`
719
+
720
+ /** The brief's sources gain what came from a library. */
721
+ async function pickInto(c, kind) {
722
+ const s = c.resolved.source
723
+ if (!s?.provider || !s.id || !['polyhaven', 'ambientcg', 'polypizza'].includes(s.provider)) return null
724
+ return recordPick(c.ctx.projectRoot, { id: `${s.provider}:${s.id}`, kind, as: kind === 'material' ? `assets/${c.target.stem}` : c.target.rel, ...(/^[124]k$/.test(s.meta?.resolution ?? '') ? { resolution: s.meta.resolution } : {}), at: today() })
725
+ }
726
+
727
+ /** A map written as KTX2 from the picture placePicture would have written,
728
+ * stored bottom row first, as a .ktx2 on its own is (ktx2.mjs). */
729
+ async function placeKtx2(c, from, rel, role) {
730
+ const pic = await decodeImage(await fsp.readFile(from), { mime: /\.jpe?g$/i.test(from) ? 'image/jpeg' : 'image/png', maxEdge: 8192, rpc: c.ctx.rpc })
731
+ if (!pic.ok) return { error: `${path.basename(from)} could not be read for KTX2: ${pic.error}` }
732
+ let alpha = false
733
+ for (let i = 3; i < pic.data.length && !alpha; i += 4) alpha = pic.data[i] < 255
734
+ const r = await ktx2For(pic, { role, alpha, flipY: true })
735
+ if (!r.ok) return { error: `${rel} could not be encoded as KTX2: ${r.error}` }
736
+ await writeInto(c.work, path.join(c.ctx.projectRoot, ...rel.split('/')), Buffer.from(r.bytes))
737
+ return { rel, width: pic.width, height: pic.height, bytes: r.bytes.byteLength, how: `KTX2 ${r.mode.toUpperCase()}: ${r.why}`, resized: false, ktx2: r }
738
+ }
739
+
740
+ async function importMaterial(c) {
741
+ const { args, files, target } = c
742
+ const roles = {}
743
+ for (const f of c.resolved.source?.files ?? []) if (f?.role && f?.path) roles[path.basename(f.path).toLowerCase()] = f.role
744
+ const maps = {}
745
+ let dx = null
746
+ for (const f of files.filter((f) => IMAGES.has(path.extname(f).toLowerCase()))) {
747
+ const role = roleOf(f, roles)
748
+ if (role === 'normal-dx') dx ??= f
749
+ else if (role && !maps[role]) maps[role] = f
750
+ }
751
+ if (!maps.normal && dx) maps.normal = dx
752
+ if (!maps.color) return fail(`No colour map in "${args.from}" (a file named like _color, _diff, _albedo or _basecolor). Found: ${files.map((f) => path.basename(f)).slice(0, 12).join(', ')}.`)
753
+ const maxSize = pictureMax(args)
754
+ const mode = ktx2Mode(c)
755
+
756
+ // Held to the brief before anything is written: the colour map's size
757
+ // once resized, over what one tile covers.
758
+ const briefRead = await readBrief(c.ctx.projectRoot)
759
+ const brief = briefRead.status === 'ok' ? briefRead.brief : null
760
+ const tile = tileOf(c, brief)
761
+ const colourSize = imageSize(await fsp.readFile(maps.color))
762
+ if (tile && colourSize) {
763
+ const v = densityVerdict(Math.min(colourSize.width, maxSize) / tile[0], briefDensityFor(brief, `assets/${target.stem}`))
764
+ if (v.verdict === 'refuse' && !args.belowTarget) return fail(densityRefusal(`${target.stem}'s colour map at ${Math.min(colourSize.width, maxSize)} px over ${tile[0]} m`, v))
765
+ }
766
+
767
+ const extFor = (file) => (mode === 'write' ? '.ktx2' : pictureExt(file))
768
+ const plan = Object.entries(maps).map(([role, file]) => ({ role, file, rel: `assets/${target.stem}_${role}${extFor(file)}` }))
769
+ // One name is one set of maps: any map the name holds, in any format,
770
+ // makes it taken, and a replace leaves only the maps it writes.
771
+ const taken = materialFiles(c.ctx.projectRoot, target.stem)
772
+ if (taken.length && !args.replace) return existingRefusal(taken.join(', '))
773
+ const placed = []
774
+ // A map KTX2 cannot hold (over the encoder's 12 megapixels, or no encoder
775
+ // here) is written as the picture it came as, and the answer says so.
776
+ const kept = []
777
+ for (const p of plan) {
778
+ let r
779
+ if (mode === 'write') {
780
+ // Resized first (as a picture), then encoded.
781
+ const temp = path.join(c.work, `map-${p.role}${pictureExt(p.file)}`)
782
+ const sized = await c.deps.imageOps.resize(p.file, temp, { maxSize, format: pictureExt(p.file) === '.jpg' ? 'jpg' : 'png' })
783
+ if (sized.error) return fail(`${path.basename(p.file)} could not be resized: ${sized.error}`)
784
+ r = await placeKtx2(c, temp, p.rel, p.role)
785
+ if (r.error) {
786
+ const rel = `assets/${target.stem}_${p.role}${pictureExt(p.file)}`
787
+ kept.push(`${rel}: ${r.error}`)
788
+ const pic = await placePicture(c, p.file, rel, maxSize)
789
+ if (pic.error) return fail(pic.error)
790
+ placed.push({ ...p, ...pic, rel })
791
+ continue
792
+ }
793
+ } else r = await placePicture(c, p.file, p.rel, maxSize)
794
+ if (r.error) return fail(r.error)
795
+ placed.push({ ...p, ...r })
796
+ }
797
+ const stale = taken.filter((rel) => !placed.some((p) => p.rel === rel))
798
+
799
+ // The maps of the set it replaces that it did not write over go, with
800
+ // their ledger entries and credit lines.
801
+ if (stale.length) {
802
+ for (const rel of stale) await fsp.rm(path.join(c.ctx.projectRoot, ...rel.split('/')), { force: true })
803
+ const gone = await putEntries(c.ctx.projectRoot, { remove: stale })
804
+ if (!gone.ok) return fail(`The new maps are in, but the ledger still lists the old ones (${stale.join(', ')}): ${gone.error}`)
805
+ }
806
+
807
+ // What was written, inspected: maps, density at its real size, the seam,
808
+ // and what KTX2 makes (or would make) of each map.
809
+ const written = Object.fromEntries(placed.map((p) => [p.role, path.join(c.ctx.projectRoot, ...p.rel.split('/'))]))
810
+ const report = await inspectMaterial(c.ctx.projectRoot, target.stem, { tileMetres: tile, brief, ktx2: mode === 'measure', rpc: c.ctx.rpc, files: written })
811
+ const k2 = ktx2Record(report)
812
+ for (const p of placed) {
813
+ const seen = report.maps?.[p.role]
814
+ const rec = await record(c, p.rel, 'texture', {
815
+ steps: [{ op: 'texture', detail: `${p.role} map, ${p.width ?? '?'}x${p.height ?? '?'} (${p.resized ? `resized to at most ${maxSize} px by ${p.how}` : p.how})` }, ...(k2[p.role] ? [{ op: 'ktx2', detail: `measured, not written: ${k2[p.role].mode.toUpperCase()} ${k2[p.role].bytes} bytes` }] : [])],
816
+ meta: {
817
+ role: p.role,
818
+ material: target.stem,
819
+ width: p.width,
820
+ height: p.height,
821
+ ...(dx && p.file === dx ? { normal: 'directx' } : {}),
822
+ ...(tile ? { tile_m: tile } : {}),
823
+ ...(tile && p.width ? { texel_density: Math.round(p.width / tile[0]) } : {}),
824
+ ...(p.role === 'color' && report.seam ? { seam: report.seam.score } : {}),
825
+ ...(p.ktx2 ? { ktx2: { mode: p.ktx2.mode, written: true, ...(p.ktx2.measured?.[p.ktx2.mode] ?? {}) } } : k2[p.role] ? { ktx2: { ...k2[p.role], written: false } } : seen?.gpu ? { gpu: seen.gpu } : {}),
826
+ },
827
+ })
828
+ if (!rec.ok) return fail(`${p.rel} is in, but the ledger could not record it: ${rec.error}`)
829
+ }
830
+ const picked = await pickInto(c, 'material')
831
+ const path_ = (role) => placed.find((p) => p.role === role)?.rel
832
+ // At its real size when the tile's is known: the surface's metres over the tile's.
833
+ const rep = tile ? `[surfaceWidth / ${tile[0]}, surfaceDepth / ${tile[1]}]` : '[4, 4]'
834
+ const tex = (role, color) => (path_(role) ? `ctx.assets.texture('${path_(role)}', { ${color ? '' : 'color: false, '}repeat: ${rep} })` : null)
835
+ const slots = [
836
+ `map: ${tex('color', true)}`,
837
+ path_('normal') ? `normalMap: ${tex('normal', false)}${dx && maps.normal === dx ? ', normalScale: new THREE.Vector2(1, -1) /* a DirectX normal map */' : ''}` : null,
838
+ path_('rough') ? `roughnessMap: ${tex('rough', false)}` : null,
839
+ path_('ao') ? `aoMap: ${tex('ao', false)}` : null,
840
+ path_('metal') ? `metalnessMap: ${tex('metal', false)}, metalness: 1` : null,
841
+ path_('displacement') ? `displacementMap: ${tex('displacement', false)}, displacementScale: 0 /* its height in metres; only on a mesh dense enough to move */` : null,
842
+ path_('opacity') ? `alphaMap: ${tex('opacity', false)}, transparent: true` : null,
843
+ ].filter(Boolean)
844
+ const text = [
845
+ `Imported the material ${target.stem}: ${placed.map((p) => `${p.rel} (${p.width ?? '?'}x${p.height ?? '?'}, ${mb(p.bytes)} MB${p.resized ? '' : `, ${p.how}`})`).join('; ')}.`,
846
+ `licence: ${c.license.spdx}${c.source.title ? `; "${c.source.title}"` : ''}${c.source.author ? ` by ${c.source.author}` : ''}. Recorded in assets.lock.json; CREDITS.md updated.${creditNote(c)}`,
847
+ ...(dx && maps.normal === dx ? ['Its normal map is DirectX style (green flipped); the snippet flips it back with normalScale.'] : []),
848
+ ...(stale.length ? [`It replaces the set the name held: ${stale.join(', ')} ${stale.length === 1 ? 'is' : 'are'} gone, with ${stale.length === 1 ? 'its' : 'their'} ledger ${stale.length === 1 ? 'entry' : 'entries'} and credit.`] : []),
849
+ ...(kept.length ? [`Not written as KTX2, so kept as ${kept.length === 1 ? 'a picture' : 'pictures'}: ${kept.join('; ')}.`] : []),
850
+ ...(picked ? [picked] : []),
851
+ '',
852
+ `Inspection (asset_inspect "assets/${target.stem}" runs it again):`,
853
+ ...(report.error ? [report.error] : reportLines(report)),
854
+ ...(mode === 'estimate' ? [`${c.decoders.why ?? 'KTX2 is not written.'} The range above is arithmetic; asset_import with ktx2 "measure" (or asset_inspect with ktx2) encodes each map and measures it.`] : []),
855
+ '',
856
+ `Use it (ctx.assets is there in every Oda host; repeat is how many times it tiles across the UVs${tile ? `; one tile is ${tile[0]} x ${tile[1]} m, so on a surface whose UVs span 0 to 1, its size in metres over that keeps the texture at its real size and its texel density` : ''}):`,
857
+ '```ts',
858
+ ...(tile ? ['const [surfaceWidth, surfaceDepth] = [/* the surface in metres */]'] : []),
859
+ `const ground = new THREE.MeshStandardNodeMaterial({`,
860
+ ...slots.map((s) => ` ${s},`),
861
+ `})`,
862
+ '```',
863
+ ]
864
+ return { text: text.join('\n'), ...(report.sheet ? { images: [{ mime: 'image/png', data: report.sheet }] } : {}) }
865
+ }
866
+
867
+ async function importTexture(c) {
868
+ const { args, files, target } = c
869
+ if (exists(target.abs) && !args.replace) return existingRefusal(target.rel)
870
+ const picture = files.find((f) => IMAGES.has(path.extname(f).toLowerCase()))
871
+ if (!picture) return fail(`No picture (png, jpg, webp) in "${args.from}".`)
872
+ if (!['.png', '.jpg', '.ktx2'].includes(target.ext)) return fail(`A single texture comes in as .png, .jpg or .ktx2: use as "assets/${target.stem}.ktx2" (or .jpg, .png).`)
873
+ // KTX2 only where the sides this project publishes to decode it, and not
874
+ // when this import was asked to keep pictures.
875
+ if (target.ext === '.ktx2' && !c.decoders.ktx2) return fail(`Not imported: ${c.decoders.why ?? 'KTX2 is not written here.'} Import it as "assets/${target.stem}.png" or .jpg.`)
876
+ if (target.ext === '.ktx2' && args.ktx2 === 'off') return fail(`Not imported: ${KTX2_OFF} Import it as "assets/${target.stem}.png" or .jpg, or leave ktx2 at "auto" to have it as KTX2.`)
877
+ const maxSize = pictureMax(args)
878
+ // What image_generate made it as: a panorama wraps left to right only, a
879
+ // card is cut out and has no seam.
880
+ const made = c.resolved.source?.meta?.kind
881
+ const role = (made === 'panorama' || made === 'card' ? made : null) ?? roleOf(picture) ?? c.resolved.source?.role ?? null
882
+ let r
883
+ if (target.ext === '.ktx2') {
884
+ // Resized first (as a picture), then encoded in the codec its role holds up in.
885
+ const temp = path.join(c.work, `tex${pictureExt(picture)}`)
886
+ const sized = await c.deps.imageOps.resize(picture, temp, { maxSize, format: pictureExt(picture) === '.jpg' ? 'jpg' : 'png' })
887
+ if (sized.error) return fail(`${path.basename(picture)} could not be resized: ${sized.error}`)
888
+ r = await placeKtx2(c, temp, target.rel, role === 'normal-dx' ? 'normal' : (role ?? 'color'))
889
+ } else r = await placePicture(c, picture, target.rel, maxSize)
890
+ if (r.error) return fail(r.error)
891
+ // Inspected as written: its values, its seam (a tile; a card with
892
+ // transparency has none), its density when its tile's size is given.
893
+ const mode = ktx2Mode(c)
894
+ const briefRead = await readBrief(c.ctx.projectRoot)
895
+ const picture_ = await inspectPicture(target.abs, { role: role ?? 'color', seam: true, ktx2: mode === 'measure', rpc: c.ctx.rpc })
896
+ const tile = typeof args.tileSize === 'number' ? args.tileSize : Array.isArray(args.tileSize) ? args.tileSize[0] : null
897
+ const density = tile && r.width ? densityVerdict(r.width / tile, briefDensityFor(briefRead.status === 'ok' ? briefRead.brief : null, target.rel)) : null
898
+ const report = { kind: 'texture', picture: picture_, density, brief: briefRead.status === 'ok' ? 'ok' : 'none' }
899
+ const rec = await record(c, target.rel, 'texture', {
900
+ steps: [{ op: 'texture', detail: `${r.width ?? '?'}x${r.height ?? '?'} (${r.resized ? `resized to at most ${maxSize} px by ${r.how}` : r.how})` }],
901
+ meta: {
902
+ width: r.width,
903
+ height: r.height,
904
+ ...(role ? { role } : {}),
905
+ ...(picture_.seam ? { seam: picture_.seam.score } : {}),
906
+ ...(tile ? { tile_m: [tile, tile], texel_density: Math.round(r.width / tile) } : {}),
907
+ ...(r.ktx2
908
+ ? { ktx2: { mode: r.ktx2.mode, bytes: r.bytes, written: true, ...(r.ktx2.measured?.[r.ktx2.mode] ?? {}) } }
909
+ : picture_.ktx2?.mode
910
+ ? { ktx2: { mode: picture_.ktx2.mode, bytes: picture_.ktx2.bytes, written: false, ...(picture_.ktx2.measured?.[picture_.ktx2.mode] ?? {}) } }
911
+ : {}),
912
+ },
913
+ })
914
+ if (!rec.ok) return fail(`${target.rel} is in, but the ledger could not record it: ${rec.error}`)
915
+ const color = !role || ['color', 'panorama', 'card'].includes(role)
916
+ const use =
917
+ role === 'panorama'
918
+ ? `It is a sky. To make it the sky and the light, import it again as "assets/${target.stem}.hdr" (asset_import writes a 2:1 picture as the Radiance file the config's hdri sky reads); as a picture it is ctx.assets.texture('${target.rel}', { wrap: 'clamp' }).`
919
+ : role === 'card'
920
+ ? `Use it: ctx.assets.texture('${target.rel}', { wrap: 'clamp' }) as the map of a plane's material with alphaTest (its cut edge) or transparent: true (its soft edge); a card faces the visitor, so keep it where it is seen from the front.`
921
+ : `Use it: ctx.assets.texture('${target.rel}'${color ? '' : ', { color: false }'}) as a material's ${color ? 'map' : `${role}Map`}.`
922
+ return {
923
+ text: [
924
+ `Imported ${target.rel} (${r.width ?? '?'}x${r.height ?? '?'}, ${mb(r.bytes)} MB${r.resized ? '' : `, ${r.how}`}), ${c.license.spdx}. Recorded in assets.lock.json.${creditNote(c)}`,
925
+ `Inspection (asset_inspect "${target.rel}" runs it again):`,
926
+ ...reportLines(report),
927
+ use,
928
+ ].join('\n'),
929
+ ...(picture_.sheet ? { images: [{ mime: 'image/png', data: picture_.sheet }] } : {}),
930
+ }
931
+ }
932
+
933
+ // ---------------------------------------------------------------- HDRI
934
+
935
+ async function measureExr(buf) {
936
+ const head = exrHeader(buf)
937
+ if (!head.ok) throw new Error(head.error)
938
+ const three = await import('three')
939
+ const { EXRLoader } = await import('three/examples/jsm/loaders/EXRLoader.js')
940
+ const loader = new EXRLoader()
941
+ loader.setDataType(three.FloatType)
942
+ // The loader reads an ArrayBuffer through a DataView: a Node Buffer is a
943
+ // view into a larger pool, so its own bytes are copied out first.
944
+ const t = loader.parse(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))
945
+ // EXR rows are stored bottom first in what three hands back (flipY false).
946
+ return measureFloat(t.data, t.width, t.height, { channels: t.data.length / (t.width * t.height), rowsTopFirst: t.flipY === true })
947
+ }
948
+
949
+ /** A 2:1 picture (a generated panorama, an equirectangular photograph) as
950
+ * the .hdr the config's sky reads: its pixels in linear light, its left
951
+ * edge into its right scored as a panorama's seam. */
952
+ async function importPanorama(c, picture) {
953
+ const { args, target } = c
954
+ if (target.ext !== '.hdr') return fail(`A sky from a picture comes in as Radiance: use as "assets/${target.stem}.hdr".`)
955
+ const bad = await contentProblem(picture)
956
+ if (bad) return fail(bad)
957
+ // maxTexture makes it smaller: a sky that only lights (a splat's
958
+ // panorama, background false) needs no more than 1024 across.
959
+ const pic = await decodeImage(await fsp.readFile(picture), { mime: /\.jpe?g$/i.test(picture) ? 'image/jpeg' : 'image/png', maxEdge: Math.min(8192, args.maxTexture ?? 8192), rpc: c.ctx.rpc })
960
+ if (!pic.ok) return fail(`${path.basename(picture)} could not be read: ${pic.error}`)
961
+ if (Math.abs(pic.width / pic.height - 2) > 0.02) return fail(`${path.basename(picture)} is ${pic.width}x${pic.height}; a sky picture is equirectangular, twice as wide as it is tall. Make it with image_generate kind panorama, which fits it to 2:1.`)
962
+ const bytes = encodeHdr(pic)
963
+ if (bytes.length > ASSET_KINDS.hdri.fileMb * MB) return fail(`As Radiance it would be ${mb(bytes.length)} MB, over the ${ASSET_KINDS.hdri.fileMb} MB an HDRI may weigh. Import it with a smaller picture.`)
964
+ const seam = seamScore(pic, { axes: 'x' })
965
+ const measured = measureHdr(bytes)
966
+ await writeInto(c.work, target.abs, bytes)
967
+ const rec = await record(c, target.rel, 'hdri', {
968
+ steps: [{ op: 'hdri', detail: `${pic.width}x${pic.height} ${path.extname(picture).slice(1)} as Radiance, linear light; upper half ${measured.top}, lower half ${measured.bottom}; left into right seam ${seam.score}` }],
969
+ meta: { hdri: { top: measured.top, bottom: measured.bottom }, width: pic.width, height: pic.height, seam: seam.score, role: 'panorama' },
970
+ })
971
+ if (!rec.ok) return fail(`${target.rel} is in, but the ledger could not record it: ${rec.error}`)
972
+ const sky = { kind: 'hdri', asset: target.rel, top: measured.top, bottom: measured.bottom }
973
+ return {
974
+ text: [
975
+ `Imported ${target.rel} (${mb(bytes.length)} MB, ${pic.width}x${pic.height}) from ${path.basename(picture)}, ${c.license.spdx}: the picture in linear light as a Radiance file, so the sky can be it. Recorded in assets.lock.json.${creditNote(c)}`,
976
+ `Its left edge into its right: ${seam.words}.${seam.verdict === 'seam' ? ' The sky shows that line where the two edges meet: make it again with image_generate kind panorama.' : ''}`,
977
+ `An 8-bit picture holds nothing brighter than white, so as a sky it lights the way an overcast one does; the sun's light is the config's sun. intensity in the sky value scales it, by the brief's numbers.`,
978
+ `Its upper half averages ${measured.top} and its lower half ${measured.bottom} (what the gradient fallbacks show until it loads).`,
979
+ 'Make it the sky and the light with look_apply:',
980
+ '```json',
981
+ JSON.stringify({ set: { sky } }, null, 2),
982
+ '```',
983
+ ].join('\n'),
984
+ }
985
+ }
986
+
987
+ async function importHdri(c) {
988
+ const { args, files, target } = c
989
+ if (exists(target.abs) && !args.replace) return existingRefusal(target.rel)
990
+ const file = files.find((f) => path.extname(f).toLowerCase() === target.ext) ?? files.find((f) => ['.hdr', '.exr'].includes(path.extname(f).toLowerCase()))
991
+ // A picture and no HDR file: a generated panorama, made the sky.
992
+ const picture = !file ? files.find((f) => IMAGES.has(path.extname(f).toLowerCase())) : null
993
+ if (picture) return importPanorama(c, picture)
994
+ if (!file) return fail(`No .hdr or .exr in "${args.from}".`)
995
+ if (path.extname(file).toLowerCase() !== target.ext) return fail(`The HDRI is ${path.extname(file)}; HDRIs keep their format: use as "assets/${target.stem}${path.extname(file).toLowerCase()}".`)
996
+ const bad = await contentProblem(file)
997
+ if (bad) return fail(bad)
998
+ const bytes = (await fsp.stat(file)).size
999
+ if (bytes > ASSET_KINDS.hdri.fileMb * MB) return fail(`${path.basename(file)} is ${mb(bytes)} MB, over the ${ASSET_KINDS.hdri.fileMb} MB an HDRI may weigh. Fetch it at 1k or 2k.`)
1000
+ const buf = await fsp.readFile(file)
1001
+ let measured = null
1002
+ let why = null
1003
+ try {
1004
+ measured = target.ext === '.hdr' ? measureHdr(buf) : await measureExr(buf)
1005
+ } catch (err) {
1006
+ why = err.message
1007
+ }
1008
+ // A .hdr that does not parse is not a picture a planet can light with.
1009
+ if (!measured && target.ext === '.hdr') return fail(`${path.basename(file)} is not a Radiance picture the sky can read (${why}), so nothing was written. Fetch it again, or pick the .exr.`)
1010
+ await writeInto(c.work, target.abs, file)
1011
+ const meta = measured ? { hdri: { top: measured.top, bottom: measured.bottom }, width: measured.width, height: measured.height } : undefined
1012
+ const rec = await record(c, target.rel, 'hdri', { steps: [{ op: 'hdri', detail: measured ? `${measured.width}x${measured.height}, upper half ${measured.top}, lower half ${measured.bottom}` : `kept as it is; not measured (${why})` }], meta })
1013
+ if (!rec.ok) return fail(`${target.rel} is in, but the ledger could not record it: ${rec.error}`)
1014
+ const pickNote = await pickInto(c, 'hdri')
1015
+ // Unmeasured, the tool picks no colours: placeholders the brief fills.
1016
+ const sky = { kind: 'hdri', asset: target.rel, top: measured?.top ?? '<top hex from the brief>', bottom: measured?.bottom ?? '<bottom hex from the brief>' }
1017
+ return {
1018
+ text: [
1019
+ `Imported ${target.rel} (${mb(bytes)} MB${measured ? `, ${measured.width}x${measured.height}` : ''}), ${c.license.spdx}. Recorded in assets.lock.json.${creditNote(c)}`,
1020
+ measured
1021
+ ? `Its upper half averages ${measured.top} and its lower half ${measured.bottom} (what the gradient fallbacks show until it loads).`
1022
+ : `It could not be measured (${why}): fill top and bottom below with the brief's sky colours (what is painted until the picture loads) before you apply it.`,
1023
+ 'Make it the sky and the light with look_apply:',
1024
+ '```json',
1025
+ JSON.stringify({ set: { sky } }, null, 2),
1026
+ '```',
1027
+ 'Or light only, painting nothing behind the scene: add "background": false. In code: ctx.assets.hdri(path).',
1028
+ ...(pickNote ? [pickNote] : []),
1029
+ ].join('\n'),
1030
+ }
1031
+ }
1032
+
1033
+ // ---------------------------------------------------------------- audio
1034
+
1035
+ async function importAudio(c) {
1036
+ const { args, files, target, deps, work } = c
1037
+ if (exists(target.abs) && !args.replace) return existingRefusal(target.rel)
1038
+ const file = files.find((f) => AUDIO.has(path.extname(f).toLowerCase()))
1039
+ if (!file) return fail(`No sound (.ogg, .mp3, .wav, .flac) in "${args.from}".`)
1040
+ const bad = await contentProblem(file)
1041
+ if (bad) return fail(bad)
1042
+ const fromExt = path.extname(file).toLowerCase()
1043
+ let out = file
1044
+ let how = 'kept as it is'
1045
+ if (fromExt !== target.ext) {
1046
+ if (target.ext !== '.ogg') return fail(`The sound is ${fromExt}; it can be kept as ${fromExt} or converted to .ogg: use as "assets/${target.stem}.ogg".`)
1047
+ const ff = await deps.ffmpeg?.()
1048
+ if (!ff) return fail(`The sound is ${fromExt} and ffmpeg is not on PATH to convert it to .ogg. Keep it as ${fromExt === '.flac' ? '.ogg (install ffmpeg)' : fromExt} instead.`)
1049
+ out = path.join(work, `${target.stem}.ogg`)
1050
+ const r = await deps.run(ff, ['-y', '-hide_banner', '-loglevel', 'error', '-i', file, '-vn', '-c:a', 'libvorbis', '-q:a', '5', out], 300_000)
1051
+ if (r.code !== 0 || !exists(out)) return fail(`ffmpeg could not convert ${path.basename(file)}: ${(r.stderr || r.error || '').trim().slice(0, 200)}`)
1052
+ how = 'converted to Ogg Vorbis (quality 5) with ffmpeg'
1053
+ }
1054
+ const bytes = (await fsp.stat(out)).size
1055
+ if (bytes > ASSET_KINDS.audio.fileMb * MB) return fail(`${target.rel} would be ${mb(bytes)} MB, over the ${ASSET_KINDS.audio.fileMb} MB one sound may weigh. Trim it, or convert it to .ogg.`)
1056
+ await writeInto(work, target.abs, out)
1057
+ const rec = await record(c, target.rel, 'audio', { steps: [{ op: 'audio', detail: how }] })
1058
+ if (!rec.ok) return fail(`${target.rel} is in, but the ledger could not record it: ${rec.error}`)
1059
+ return {
1060
+ text: [
1061
+ `Imported ${target.rel} (${mb(bytes)} MB, ${how}), ${c.license.spdx}. Recorded in assets.lock.json.${creditNote(c)}`,
1062
+ `Use it: const s = ctx.assets.sound('${target.rel}', { loop: true, volume: 0.6 }); s.play(). Pass at: someObject for a sound that comes from somewhere; browsers start sound only after the visitor's first key or click. A planet carries at most ${ASSET_KINDS.audio.fileMb} MB per sound and 20 MB of sound in all.`,
1063
+ ].join('\n'),
1064
+ }
1065
+ }
1066
+
1067
+ // ---------------------------------------------------------------- LUT
1068
+
1069
+ /** Whether a .cube is one the look can use: { size } or { error }. */
1070
+ export function checkCube(text) {
1071
+ if (/^\s*LUT_1D_SIZE/m.test(text)) return { error: 'it is a 1D LUT; the look takes 3D LUTs (LUT_3D_SIZE)' }
1072
+ const m = /^\s*LUT_3D_SIZE\s+(\d+)\s*$/m.exec(text)
1073
+ if (!m) return { error: 'it has no LUT_3D_SIZE line' }
1074
+ const size = Number(m[1])
1075
+ if (size < 2 || size > 64) return { error: `its size is ${size}; 2 to 64 is what the look takes` }
1076
+ let rows = 0
1077
+ for (const line of text.split(/\r?\n/)) {
1078
+ const t = line.trim()
1079
+ if (!t || t.startsWith('#') || /^[A-Z][A-Z0-9_]*(\s|$)/.test(t)) continue
1080
+ const parts = t.split(/\s+/)
1081
+ if (parts.length !== 3 || parts.some((p) => !Number.isFinite(Number(p)))) return { error: `a data line is not three numbers ("${t.slice(0, 40)}")` }
1082
+ rows++
1083
+ }
1084
+ if (rows !== size ** 3) return { error: `it has ${rows} colours; a ${size}-cube needs ${size ** 3}` }
1085
+ return { size }
1086
+ }
1087
+
1088
+ async function importLut(c) {
1089
+ const { args, files, target } = c
1090
+ if (exists(target.abs) && !args.replace) return existingRefusal(target.rel)
1091
+ const file = files.find((f) => path.extname(f).toLowerCase() === '.cube')
1092
+ if (!file) return fail(`No .cube LUT in "${args.from}".`)
1093
+ const bytes = (await fsp.stat(file)).size
1094
+ if (bytes > ASSET_KINDS.lut.fileMb * MB) return fail(`${path.basename(file)} is ${mb(bytes)} MB, over the ${ASSET_KINDS.lut.fileMb} MB a LUT may weigh.`)
1095
+ const checked = checkCube(await fsp.readFile(file, 'utf8'))
1096
+ if (checked.error) return fail(`${path.basename(file)} is not a LUT the look can use: ${checked.error}.`)
1097
+ await writeInto(c.work, target.abs, file)
1098
+ const rec = await record(c, target.rel, 'lut', { steps: [{ op: 'lut', detail: `${checked.size}-cube, parse-checked` }], meta: { size: checked.size } })
1099
+ if (!rec.ok) return fail(`${target.rel} is in, but the ledger could not record it: ${rec.error}`)
1100
+ return {
1101
+ text: [
1102
+ `Imported ${target.rel} (a ${checked.size} x ${checked.size} x ${checked.size} LUT), ${c.license.spdx}. Recorded in assets.lock.json.${creditNote(c)}`,
1103
+ 'Grade with it through look_apply:',
1104
+ '```json',
1105
+ JSON.stringify({ set: { look: { grade: { lut: { asset: target.rel, intensity: 1 } } } } }, null, 2),
1106
+ '```',
1107
+ ].join('\n'),
1108
+ }
1109
+ }
1110
+
1111
+ // ---------------------------------------------------------------- splat
1112
+
1113
+ const SPLAT_SOURCES = ['.spz', '.ply', '.splat']
1114
+
1115
+ /** The splat file in what came in: an .spz first, then a .ply, then a .splat. */
1116
+ function pickSplat(files) {
1117
+ for (const ext of SPLAT_SOURCES) {
1118
+ const hit = files.find((f) => path.extname(f).toLowerCase() === ext)
1119
+ if (hit) return hit
1120
+ }
1121
+ return null
1122
+ }
1123
+
1124
+ /** Every file under assets/ now, as the planet would carry them. */
1125
+ async function assetsBytes(root, leaving = []) {
1126
+ let total = 0
1127
+ const dir = path.join(root, 'assets')
1128
+ for (const name of await fsp.readdir(dir).catch(() => [])) {
1129
+ const rel = `assets/${name}`
1130
+ if (leaving.includes(rel) || !isPublishablePath(rel)) continue
1131
+ try {
1132
+ total += (await fsp.stat(path.join(dir, name))).size
1133
+ } catch {
1134
+ // gone since the listing
1135
+ }
1136
+ }
1137
+ return total
1138
+ }
1139
+
1140
+ /** The collider the splat came with or was given: a quarantine file (a GLB)
1141
+ * and the frame it is in, or null when there is none, or { error }. */
1142
+ async function colliderFor(c) {
1143
+ const given = c.args.collider
1144
+ if (typeof given === 'string' && given.trim()) {
1145
+ if (/^assets\//.test(given.trim())) return { error: `${given} is in the project already: pass it to ctx.assets.splat as its collider, with nothing to import.` }
1146
+ const r = await resolveFrom(c.ctx.projectRoot, given.trim())
1147
+ if (r.error) return { error: `The collider: ${r.error}` }
1148
+ const files = r.isDir ? await listFiles(r.abs) : [r.abs]
1149
+ const file = files.find((f) => /\.(glb|gltf)$/i.test(f))
1150
+ if (!file) return { error: `The collider "${given}" holds no GLB or glTF.` }
1151
+ // A collider of its own source keeps that source's licence.
1152
+ const lic = r.source?.license?.spdx ? licenseFor({ source: r.source, given: null }) : null
1153
+ if (lic?.error) return { error: `The collider: ${lic.error}` }
1154
+ return { file, frame: c.args.colliderFrame ?? 'splat', license: lic?.license ?? null, source: r.source ? sourceRecord(r, null) : null, resolved: r.source ? r : null, from: given.trim() }
1155
+ }
1156
+ // One that came in the same folder (environment_job's collider.glb).
1157
+ const beside = c.files.find((f) => /\.(glb|gltf)$/i.test(f))
1158
+ return beside ? { file: beside, frame: c.args.colliderFrame ?? 'splat', license: null, source: null, from: slash(path.relative(c.resolved.q, beside)) } : null
1159
+ }
1160
+
1161
+ const fmt = (n) => Number(n).toLocaleString('en-US')
1162
+ const metres = (v) => `${Math.round(v * 100) / 100}`
1163
+ const boxText = (b) => `x ${metres(b.min[0])} to ${metres(b.max[0])}, y ${metres(b.min[1])} to ${metres(b.max[1])}, z ${metres(b.min[2])} to ${metres(b.max[2])} m`
1164
+
1165
+ /** What was measured of splats in the real preview (the CLI's page, the
1166
+ * look's defaults, headless Chrome on an Apple M5 Pro at 1280 x 720, the
1167
+ * camera walking inside the splat, 2026-10-24), for the answers. */
1168
+ const SPLAT_MEASURED = 'Measured in the preview on an Apple M5 Pro desktop (look defaults, 1280 x 720, walking inside it), steady fps on WebGPU and WebGL 2: 195k splats about 55 and 40, 500k 33 and 19, 1M 19 and 10, 2M 9.5 and 5; phones were not measured.'
1169
+
1170
+ /** The walk map (collider.mjs walkMap) in words: where the walker gets to
1171
+ * from the spawn, and where the floor ends. */
1172
+ function walkLines(walk, spawn) {
1173
+ if (!walk) return ['- Its walk could not be mapped (a collider too large or too detailed to sample): walk it with nw_play and read fell.']
1174
+ const out = []
1175
+ const at = (e) => `x ${metres(e.at[0])}, z ${metres(e.at[2])}${Math.abs(e.at[1] - walk.start[1]) > 0.3 ? ` (${metres(e.at[1] - walk.start[1])} m up)` : ''}`
1176
+ out.push(
1177
+ `- walking: from the spawn [${spawn.join(', ')}] the walker's middle reaches about ${walk.area} m2 of floor, x ${metres(walk.bounds.min[0])} to ${metres(walk.bounds.max[0])}, z ${metres(walk.bounds.min[1])} to ${metres(walk.bounds.max[1])} (0.25 m cells).`,
1178
+ )
1179
+ if (!walk.spawnOnFloor) {
1180
+ out.push(`- The spawn [${spawn.join(', ')}] is over no floor of this collider: the walker would fall. Set config.player.spawn to [${walk.start[0]}, ${metres(walk.start[1] + 1)}, ${walk.start[2]}], the nearest floor to it.`)
1181
+ }
1182
+ const edges = walk.openEdges ?? []
1183
+ if (edges.length === 0) {
1184
+ out.push(`- Its floor is closed near walking height: nowhere does it end over nothing.`)
1185
+ } else {
1186
+ const walked = edges.filter((e) => e.walked)
1187
+ out.push(
1188
+ `- Its floor ends with nothing under it (or only the side of something, or a drop of more than 2 m) along about ${walk.openEdge} m${walked.length ? `, ${walked.length === edges.length ? 'all' : 'some'} of it on the walk from the spawn` : ', none on a step-by-step walk from the spawn (a generated collider\'s clutter can still carry a walker there)'}, the nearest first: ${edges.map((e) => `near ${at(e)}, ${e.length} m`).join('; ')}${walk.openPieces > edges.length ? `; and ${walk.openPieces - edges.length} more pieces` : ''}. ctx.assets.splat holds the walker at those edges, as a wall would, and puts it back where it last stood if it is thrown past one; edges 'open' lets it walk off. A floor in the collider there, or the space's ground, is what lets a visitor go on.`,
1189
+ )
1190
+ }
1191
+ return out
1192
+ }
1193
+
1194
+ async function importSplat(c) {
1195
+ const { args, files, target, work, resolved } = c
1196
+ const root = c.ctx.projectRoot
1197
+ const colliderRel = `assets/${target.stem}_collider.glb`
1198
+ if (exists(target.abs) && !args.replace) return existingRefusal(target.rel)
1199
+ const file = pickSplat(files)
1200
+ if (!file) return fail(`No splat in "${args.from}" (looked for ${SPLAT_SOURCES.join(', ')}). A mesh scan (.obj, .glb) comes in as a model.`)
1201
+ const sourceBytes = (await fsp.stat(file)).size
1202
+ const tooMany = (count) =>
1203
+ fail(`${path.basename(file)} holds ${fmt(count)} splats; a planet draws at most ${fmt(SPLAT_LIMITS.count)} in one file. ${SPLAT_MEASURED} Export it smaller (World Labs gives 500k; most capture apps can thin a scan).`)
1204
+
1205
+ const raw0 = await fsp.readFile(file)
1206
+ // Counted from the header first, so a file far past the limit is never decoded.
1207
+ const said = splatCountOf(raw0, path.basename(file))
1208
+ if (said !== null && said > SPLAT_LIMITS.count) return tooMany(said)
1209
+ let s
1210
+ try {
1211
+ s = await readSplat(raw0, path.basename(file))
1212
+ } catch (err) {
1213
+ return fail(`${path.basename(file)} is not a splat this import reads: ${err?.message ?? err}`)
1214
+ }
1215
+ if (s.count > SPLAT_LIMITS.count) return tooMany(s.count)
1216
+ // Every splat file in a planet is drawn at once, so they count together.
1217
+ const elsewhere = planetSplats((await readLedger(root)).files, [target.rel])
1218
+ if (elsewhere + s.count > SPLAT_LIMITS.planetCount) {
1219
+ return fail(`With it the planet's splat files would hold ${fmt(elsewhere + s.count)} splats in all (${fmt(elsewhere)} already in), past the ${fmt(SPLAT_LIMITS.planetCount)} a planet may draw. Use a smaller export, or replace the splat already there.`)
1220
+ }
1221
+
1222
+ // Its frame: what the source says (a World Labs world brings its own),
1223
+ // else what was asked, else the y-down frame most captures are in.
1224
+ const frame = resolved.source?.frame && typeof resolved.source.frame === 'object' ? resolved.source.frame : {}
1225
+ const orientation = args.orientation ?? (frame.orientation === 'y-up' || frame.orientation === 'y-down' ? frame.orientation : 'y-down')
1226
+ const flip = orientation === 'y-down'
1227
+ const scale = args.scale ?? (Number.isFinite(frame.scale) && frame.scale > 0 ? frame.scale : 1)
1228
+ transformSplat(s, { flip, scale })
1229
+ const raw = splatStats(s)
1230
+ let groundY
1231
+ let groundWhy
1232
+ if (typeof args.ground === 'number') {
1233
+ groundY = args.ground
1234
+ groundWhy = `y = ${metres(args.ground)} (as asked)`
1235
+ } else if (args.ground === 'keep') {
1236
+ groundY = 0
1237
+ groundWhy = 'kept where the file has it'
1238
+ } else if (args.ground !== 'auto' && Number.isFinite(frame.ground)) {
1239
+ // A source's ground is in its own y-down metric frame (World Labs:
1240
+ // ground_plane_offset, subtracted after the scale), so a half turn
1241
+ // negates it, and a scale other than the source's moves it with the rest.
1242
+ const rescale = scale / (Number.isFinite(frame.scale) && frame.scale > 0 ? frame.scale : 1)
1243
+ groundY = (flip ? -frame.ground : frame.ground) * rescale
1244
+ groundWhy = `the source's ground plane (${metres(frame.ground)} m in its frame${Math.abs(rescale - 1) > 1e-9 ? `, ${metres(frame.ground * rescale)} m at this scale` : ''})`
1245
+ } else {
1246
+ groundY = raw.floorY
1247
+ groundWhy = `the lowest of its solid splats (2nd percentile), y = ${metres(raw.floorY)} before`
1248
+ }
1249
+ const cx = args.center ? (raw.core.min[0] + raw.core.max[0]) / 2 : 0
1250
+ const cz = args.center ? (raw.core.min[2] + raw.core.max[2]) / 2 : 0
1251
+ const offset = [-cx, -groundY, -cz]
1252
+ transformSplat(s, { offset })
1253
+ const stats = splatStats(s)
1254
+ const bytes = encodeSpz(s)
1255
+ if (bytes.byteLength > ASSET_KINDS.splat.fileMb * MB) {
1256
+ return fail(`As .spz it would be ${mb(bytes.byteLength)} MB, over the ${ASSET_KINDS.splat.fileMb} MB one splat file may weigh (${fmt(s.count)} splats with colour detail of degree ${s.shDegree}). Use a smaller export (World Labs' 500k), or thin the scan.`)
1257
+ }
1258
+
1259
+ // The collider, in the same frame, before anything is written, walked from
1260
+ // the space's spawn inside its map (World's own edge, 0.4 m in).
1261
+ const collider = await colliderFor(c)
1262
+ if (collider?.error) return fail(collider.error)
1263
+ let col = null
1264
+ const config = await fsp
1265
+ .readFile(path.join(root, 'game.config.json'), 'utf8')
1266
+ .then((t) => JSON.parse(t))
1267
+ .catch(() => null)
1268
+ const given = config?.player?.spawn
1269
+ const spawn = Array.isArray(given) && given.length === 3 && given.every(Number.isFinite) ? given : [0, 1, 0]
1270
+ const limit = Number.isFinite(config?.tiles) && config.tiles > 0 ? mapSide(config.tiles) / 2 - 0.4 : Infinity
1271
+ if (collider) {
1272
+ const t = collider.frame === 'space' ? {} : { flip, scale, offset }
1273
+ col = await prepareCollider(collider.file, { ...t, start: spawn, limit })
1274
+ if (!col.ok) return fail(`The collider ${collider.from}: ${col.error}. Nothing was written.`)
1275
+ if (exists(path.join(root, ...colliderRel.split('/'))) && !args.replace) return existingRefusal(colliderRel)
1276
+ }
1277
+
1278
+ // What the planet would carry with these in it (they replace their own names).
1279
+ const others = await assetsBytes(root, [target.rel, colliderRel])
1280
+ const total = others + bytes.byteLength + (col ? col.glb.byteLength : 0)
1281
+ if (total > ASSETS_TOTAL_MB * MB) {
1282
+ return fail(`With it the planet's files would come to ${mb(total)} MB, over the ${ASSETS_TOTAL_MB} MB a planet carries (the splat is ${mb(bytes.byteLength)} MB${col ? `, its collider ${mb(col.glb.byteLength)} MB` : ''}). Use a smaller export, or take something else out.`)
1283
+ }
1284
+
1285
+ await writeInto(work, target.abs, Buffer.from(bytes))
1286
+ const frameRecord = { orientation, scale: Math.round(scale * 1e6) / 1e6, offset: offset.map((v) => Math.round(v * 1000) / 1000) }
1287
+ const splatSteps = [
1288
+ { op: 'splat', detail: `${fmt(s.count)} splats from ${path.basename(file)} (${s.from}, ${mb(sourceBytes)} MB), colour detail degree ${s.shDegree}` },
1289
+ { op: 'frame', detail: `${flip ? 'turned upright (y-down to y-up), ' : ''}${scale !== 1 ? `scaled ${frameRecord.scale} to metres, ` : ''}floor at y = 0 from ${groundWhy}${args.center ? ', centred on x and z' : ''}` },
1290
+ { op: 'spz', detail: `written as SPZ version 3 (gzip), ${mb(bytes.byteLength)} MB` },
1291
+ ]
1292
+ const rec = await record(c, target.rel, 'splat', {
1293
+ steps: splatSteps,
1294
+ meta: {
1295
+ count: s.count,
1296
+ shDegree: s.shDegree,
1297
+ bounds_m: stats.bounds,
1298
+ core_m: stats.core,
1299
+ frame: frameRecord,
1300
+ phone: s.count <= SPLAT_LIMITS.phoneCount,
1301
+ ...(col ? { collider: colliderRel } : {}),
1302
+ ...(col?.walk ? { walk: { spawn, start: col.walk.start, spawnOnFloor: col.walk.spawnOnFloor, area_m2: col.walk.area, bounds: col.walk.bounds, openEdge_m: col.walk.openEdge, openEdges: col.walk.openEdges } } : {}),
1303
+ ...(resolved.source?.meta && typeof resolved.source.meta === 'object' ? { source: resolved.source.meta } : {}),
1304
+ },
1305
+ })
1306
+ if (!rec.ok) return fail(`${target.rel} is in, but the ledger could not record it: ${rec.error}`)
1307
+
1308
+ const lines = [
1309
+ `Imported ${target.rel}: ${fmt(s.count)} splats, colour detail degree ${s.shDegree}, ${mb(bytes.byteLength)} MB (from ${mb(sourceBytes)} MB ${s.from}), ${c.license.spdx}.${creditNote(c)}`,
1310
+ `- frame: ${splatSteps[1].detail}. Its splats now span ${boxText(stats.bounds)}; the solid core (1st to 99th percentile) ${boxText(stats.core)}.`,
1311
+ s.count > SPLAT_LIMITS.phoneCount
1312
+ ? `- ${fmt(s.count)} splats is past the ${fmt(SPLAT_LIMITS.phoneCount)} World Labs exports for lighter devices: take this splat as one for desktops. ${SPLAT_MEASURED}`
1313
+ : `- ${fmt(s.count)} splats: within the ${fmt(SPLAT_LIMITS.phoneCount)} World Labs exports for lighter devices (a vendor's size; phones were not measured). ${SPLAT_MEASURED}`,
1314
+ ]
1315
+ if (col) {
1316
+ await writeInto(work, path.join(root, ...colliderRel.split('/')), Buffer.from(col.glb))
1317
+ // A collider of its own source is recorded as that source's (its licence,
1318
+ // its origin, its generation); one that came with the splat, as the splat's.
1319
+ const own = collider.resolved ? { resolved: collider.resolved, license: collider.license, source: collider.source, origin: undefined } : {}
1320
+ const colRec = await record({ ...c, ...own }, colliderRel, 'model', {
1321
+ steps: [{ op: 'collider', detail: `for ${target.rel}, from ${collider.from}, ${collider.frame === 'space' ? 'already in the space frame' : 'in the splat frame'}` }, ...col.steps],
1322
+ meta: { role: 'collider', for: target.rel, triangles: col.triangles, size_m: col.bounds ? { width: col.bounds.size[0], height: col.bounds.size[1], depth: col.bounds.size[2] } : null },
1323
+ })
1324
+ lines.push(`- collider ${colliderRel}: ${fmt(col.triangles)} triangles${col.before !== col.triangles ? ` (from ${fmt(col.before)})` : ''}, ${mb(col.glb.byteLength)} MB, spanning ${col.bounds ? boxText(col.bounds) : 'nothing'}.${colRec.ok ? '' : ` The ledger could not record it: ${colRec.error}`}`)
1325
+ if (col.bounds && footprintOverlap(col.bounds, stats.core) < 0.5) {
1326
+ lines.push(`- The collider covers less than half of the splat's footprint, or lies beside it: they may not line up. Look at both with nw_view; a collider made over the imported splat comes in with colliderFrame "space".`)
1327
+ }
1328
+ if (col.bounds && (col.bounds.min[1] > 0.5 || col.bounds.max[1] < -0.5)) lines.push(`- The collider does not reach the splat's floor (y = 0): its lowest point is at ${metres(col.bounds.min[1])} m.`)
1329
+ lines.push(...walkLines(col.walk, spawn))
1330
+ } else {
1331
+ lines.push(`- No collider: the walker falls through a splat. Import one with collider (a GLB in quarantine: a box or a floor made in Blender over this splat, with colliderFrame "space"), or stand the walker on the config's ground plate.`)
1332
+ }
1333
+ lines.push(
1334
+ `- The planet's files now come to ${mb(total)} MB of ${ASSETS_TOTAL_MB} MB${total > SPLAT_LIMITS.planetMb * MB ? `, past the ${SPLAT_LIMITS.planetMb} MB a planet with splats aims for so it loads in a few seconds: a smaller export (World Labs' 500k) or fewer other files bring it down` : ''}.`,
1335
+ )
1336
+ const pano = files.find((f) => /pano/i.test(path.basename(f)) && IMAGES.has(path.extname(f).toLowerCase()))
1337
+ if (pano) {
1338
+ const qPano = slash(path.relative(resolved.q, pano))
1339
+ lines.push(`- Its panorama is in quarantine as ${qPano}: to light the walker and the props with the world's own light, import it as the sky (asset_import from "${qPano}" as "assets/${target.stem}_pano.hdr" with maxTexture 1024) and apply it with background false, so the splat stays what is seen.`)
1340
+ }
1341
+ lines.push(
1342
+ 'Use it in code: one group holds the splat, its collider (drawn by nothing) and, with light, a probe measured from the splat for everything else in it:',
1343
+ '```ts',
1344
+ `const room = ctx.assets!.splat('${target.rel}', {${col ? ` collider: '${colliderRel}',` : ''} light: true })`,
1345
+ `world.add('${target.stem}', room${col ? ', { solid: true, climb: false }' : ''})`,
1346
+ '```',
1347
+ `With no ground under it, set the config's ground to { "kind": "none" } so the plate neither shows nor holds the walker${col ? ": the collider is the floor, and where its floor ends the walker is held (edges 'hold', the default; edges 'open' lets it walk off and fall)" : ''}. A splat is drawn in the colours it was captured or generated in: look.toneMapping "none" with exposure 1 shows them as they are, and any other tone curve grades it with the rest of the space, as the brief says. It casts and takes no shadow, and the fog does not reach it.`,
1348
+ )
1349
+ return { text: lines.join('\n') }
1350
+ }
1351
+
1352
+ export { boundsOf, TRIANGLE_BUDGETS, imageSize }