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,184 @@
1
+ // Which model and effort each session of a production runs on. The creator
2
+ // does not choose: the router does, from policy.json. Decisions (reading the
3
+ // request, the vision, the plan, the critic) run on a top-tier model,
4
+ // because a large verifier helps a small generator and a small one hurts a
5
+ // large one; build tasks start as low on the ladder as their checks allow,
6
+ // because a narrow task a tool can verify is what a small model does well
7
+ // (QA run T1-run3: Claude Haiku 5.5 built a running island for $0.47, and
8
+ // failed where nothing checked it). A failed attempt without measured
9
+ // progress climbs one rung, effort before model; progress keeps the rung.
10
+ //
11
+ // The creator's model picker is only a ceiling, and only when they turn on
12
+ // "never above this model": rungs whose model costs more per output token
13
+ // are dropped, and a decision above it runs on the ceiling model at high.
14
+ // Effort is always set, because Opus 5.5 and Haiku 5.5 run at medium when it
15
+ // is not, and never past the model's own effortCeiling (models.json).
16
+
17
+ import { readFileSync } from 'node:fs'
18
+ import { EFFORTS } from '../depth.mjs'
19
+ import { MODELS } from '../shared.mjs'
20
+
21
+ export const POLICY = JSON.parse(readFileSync(new URL('./policy.json', import.meta.url), 'utf8'))
22
+
23
+ /** Every model of models.json by id, whatever its provider. */
24
+ function modelTable(models) {
25
+ const list = Array.isArray(models) ? models : (models?.providers ?? []).flatMap((p) => p.models.map((m) => ({ ...m, provider: p.id })))
26
+ return new Map(list.map((m) => [m.id, m]))
27
+ }
28
+
29
+ const outPrice = (m) => (Array.isArray(m?.price) ? Number(m.price[1]) : Infinity)
30
+ const usd = (n) => `$${Number(n).toFixed(2)}`
31
+
32
+ /** An effort no deeper than the model takes. */
33
+ export function clampEffort(effort, model) {
34
+ const ceiling = EFFORTS.includes(model?.effortCeiling) ? model.effortCeiling : 'max'
35
+ const i = EFFORTS.indexOf(effort)
36
+ return EFFORTS[Math.min(i < 0 ? EFFORTS.indexOf('high') : i, EFFORTS.indexOf(ceiling))]
37
+ }
38
+
39
+ /** The checks that verify something besides the always-on ones. */
40
+ const toolChecks = (task) => (task?.accept?.checks ?? []).filter((c) => c.kind !== 'markers' && c.kind !== 'ownership')
41
+
42
+ /**
43
+ * @param {{ policy?: object, models?: object, ceiling?: string | null, depth?: { effort: string } | null }} options
44
+ */
45
+ export function createRouter({ policy = POLICY, models = MODELS, ceiling = null, depth = null } = {}) {
46
+ const table = modelTable(models)
47
+ const byId = (id) => {
48
+ const m = table.get(id)
49
+ if (!m) throw new Error(`The routing policy names ${id}, which models.json does not have.`)
50
+ return m
51
+ }
52
+ for (const rung of policy.rungs) byId(rung.model)
53
+ for (const d of Object.values(policy.decisions)) for (const s of [d, d.max, d.stuck].filter(Boolean)) byId(s.model)
54
+
55
+ // A ceiling that is not one of Claude's models (or is unknown) cannot
56
+ // bound a Claude production, so it is not applied.
57
+ const cap = ceiling && table.get(ceiling)?.provider === 'anthropic' ? table.get(ceiling) : null
58
+ const allowed = policy.rungs.map((r, i) => ({ ...r, i })).filter((r) => !cap || outPrice(byId(r.model)) <= outPrice(cap))
59
+ // Nothing on the ladder fits under the ceiling: its cheapest rung, on the ceiling model.
60
+ const rungs = allowed.length > 0 ? allowed : [{ model: cap.id, effort: 'high', tier: 'small', i: 0 }]
61
+ const rules = policy.rules ?? {}
62
+
63
+ const card = (m) => ({ id: m.id, name: m.name, price: m.price, thinking: m.thinking ?? null, effortCeiling: m.effortCeiling ?? 'max' })
64
+ const pickAt = (i, why) => {
65
+ const r = rungs.find((x) => x.i === i) ?? rungs[0]
66
+ const m = byId(r.model)
67
+ return { rung: r.i, model: card(m), effort: clampEffort(r.effort, m), why }
68
+ }
69
+ /** The highest allowed rung at or below `want`, else the lowest allowed. */
70
+ const fit = (want) => [...rungs].reverse().find((r) => r.i <= want)?.i ?? rungs[0].i
71
+ const above = (i) => rungs.find((r) => r.i > i)?.i ?? null
72
+
73
+ const router = {
74
+ ceiling: cap ? card(cap) : null,
75
+ rungs: rungs.map((r) => pickAt(r.i, 'ladder')),
76
+
77
+ /** A decision session's model: the phase's default, Fable at max depth
78
+ * or for a stuck critic, never above the ceiling. */
79
+ decision(phase, { stuck = false } = {}) {
80
+ const d = policy.decisions[phase]
81
+ if (!d) throw new Error(`No routing for the ${phase} decision.`)
82
+ let spec = d
83
+ let why = `${phase}: the policy's default`
84
+ if (d.max && depth?.effort === 'max') [spec, why] = [d.max, `${phase} on a request at max depth`]
85
+ if (d.stuck && stuck) [spec, why] = [d.stuck, `${phase}: the critic was stuck`]
86
+ let m = byId(spec.model)
87
+ let effort = spec.effort
88
+ if (cap && outPrice(m) > outPrice(cap)) {
89
+ m = cap
90
+ effort = 'high'
91
+ why += `, held to the ceiling (${cap.name})`
92
+ }
93
+ return { rung: null, model: card(m), effort: clampEffort(effort, m), why }
94
+ },
95
+
96
+ /** Where a build task starts: its tier, raised when its checks cannot
97
+ * hold a small model to the goal, when it integrates other tasks'
98
+ * work, and for QA. `board` tells integration from the task's deps. */
99
+ start(task, board = null) {
100
+ const tiers = policy.tiers
101
+ let want = tiers[task?.tier] ?? tiers.mid
102
+ const why = [`tier ${task?.tier ?? 'mid'}`]
103
+ if (want < tiers.mid && task?.tier === 'small') {
104
+ const checks = toolChecks(task)
105
+ const goal = checks.some((c) => (rules.goalKinds ?? []).includes(c.kind))
106
+ if (checks.length < (rules.smallNeedsChecks ?? 2) || !goal) {
107
+ want = tiers.mid
108
+ why.push('too few checks to hold a small model to the goal')
109
+ }
110
+ }
111
+ const byTask = new Map((board?.tasks ?? []).map((t) => [t.id, t]))
112
+ const integrates = task?.role === 'builder' && (task.integrates === true || (task.deps ?? []).some((d) => byTask.get(d) && byTask.get(d).role !== 'builder'))
113
+ if (integrates && want < tiers[rules.integrationAtLeast ?? 'mid']) {
114
+ want = tiers[rules.integrationAtLeast ?? 'mid']
115
+ why.push('it integrates other tasks')
116
+ }
117
+ if (task?.role === 'qa' && want < tiers[rules.qaAtLeast ?? 'mid']) {
118
+ want = tiers[rules.qaAtLeast ?? 'mid']
119
+ why.push('QA')
120
+ }
121
+ const i = fit(want)
122
+ if (i < want) why.push(`held to the ceiling (${cap?.name ?? 'the ladder'})`)
123
+ return { ...pickAt(i, why.join(', ')), resume: false, escalated: false }
124
+ },
125
+
126
+ /** The next attempt after a failed gate, or null when the task has no
127
+ * round left. Measured progress keeps the rung (at most twice on one
128
+ * rung); anything else climbs one. The same model goes on in the same
129
+ * session while its prompt stayed under the long-prompt line (Haiku
130
+ * 5.5 bills a prompt over 100K tokens five times higher), else a fresh
131
+ * session gets a handoff. */
132
+ next(task) {
133
+ const attempts = task?.attempts ?? []
134
+ if (attempts.length >= (task?.roundLimit ?? 1)) return null
135
+ const last = attempts.at(-1)
136
+ if (!last) return router.start(task)
137
+ const cur = Number.isInteger(last.rung) ? last.rung : fit(policy.tiers.mid)
138
+ const onRung = attempts.filter((a) => a.rung === cur).length
139
+ const progress = last.gate?.progress ?? null
140
+ let i = cur
141
+ let why
142
+ if (progress === 'better' && onRung < (rules.sameRungWhileBetter ?? 2)) why = 'measured progress, so the same rung'
143
+ else {
144
+ const up = above(cur)
145
+ if (up === null) why = 'no rung left above, so the same rung'
146
+ else {
147
+ i = up
148
+ why = `no measured progress (${progress ?? 'no gate'}), one rung up`
149
+ }
150
+ }
151
+ const pick = pickAt(i, why)
152
+ const first = attempts[0]?.rung
153
+ const sameModel = pick.model.id === last.model
154
+ const short = !(Number(last.peakPrompt) > (rules.resumeUnderTokens ?? 100_000))
155
+ const resume = sameModel && short && typeof last.sessionId === 'string' && last.sessionId !== ''
156
+ return {
157
+ ...pick,
158
+ resume,
159
+ escalated: Number.isInteger(first) && pick.rung > first,
160
+ ...(sameModel && !short ? { why: `${why}; its last prompt passed ${rules.resumeUnderTokens ?? 100_000} tokens, so a fresh session` } : {}),
161
+ }
162
+ },
163
+
164
+ /** The ladder, the prices and the rules in words, for PLAN. */
165
+ describe() {
166
+ const out = ['Rungs (a build task starts at its tier and climbs one rung after a failed attempt without measured progress):']
167
+ for (const r of rungs) {
168
+ const m = byId(r.model)
169
+ const p = Array.isArray(m.price) ? `${usd(m.price[0])} in, ${usd(m.price[1])} out per million tokens` : 'no price'
170
+ out.push(`- rung ${r.i}: ${m.name} at ${clampEffort(r.effort, m)} (${r.tier}; ${p})`)
171
+ }
172
+ const t = policy.tiers
173
+ out.push(`Tiers: small starts at rung ${fit(t.small)}, mid at ${fit(t.mid)}, top at ${fit(t.top)}.`)
174
+ out.push(
175
+ `A small task needs at least ${rules.smallNeedsChecks ?? 2} tool checks besides markers and ownership, one of them ${(rules.goalKinds ?? []).join(', ')}, or it starts at mid; a builder task that integrates other tasks and every QA task start at mid at least.`,
176
+ )
177
+ const d = router.decision('plan')
178
+ out.push(`Decisions (interpret, vision, plan) and the critic run on ${d.model.name} at ${d.effort}; triage and the report on ${router.decision('report').model.name}.`)
179
+ if (cap) out.push(`The creator's ceiling: up to ${cap.name}.`)
180
+ return out.join('\n')
181
+ },
182
+ }
183
+ return router
184
+ }
@@ -0,0 +1,243 @@
1
+ // The seams between roles: one file per kind of interface (the materials in
2
+ // src/look/index.ts, the audio in src/audio/index.ts) that the builder
3
+ // imports from the start and the director alone writes. Until the task that
4
+ // makes the interface passes, a seam is a stub with the interface's names
5
+ // (mid-grey materials, an audio that plays nothing), so the blockout builds
6
+ // and runs without waiting for the look or the sound; when the producing
7
+ // task passes, the seam becomes one line that re-exports the role's own
8
+ // module. A module reaches the game only through its seam, and only after
9
+ // its task passed, so a half-made look never breaks another role's build.
10
+ //
11
+ // The placements seam (src/placements/index.ts) is the same for the models:
12
+ // the blockout adds each stand-in through its place(), and when a modeller
13
+ // task ends with its model in hand (passed or kept), the director writes the
14
+ // model in at its placement, measured from the file itself (where its base
15
+ // or top is, at its real size), so the game shows it with no task of the
16
+ // builder's in between.
17
+ //
18
+ // A stub is a placeholder, not a look: its first line is the marker, and
19
+ // the final gate fails while any file still starts with it.
20
+
21
+ import fs from 'node:fs'
22
+ import fsp from 'node:fs/promises'
23
+ import path from 'node:path'
24
+ import { SEAM_PATHS, relPath } from './board.mjs'
25
+ import { writeAtomic } from './store.mjs'
26
+
27
+ export const STUB_MARK = '// nowhere:seam-stub'
28
+ export const SEAM_MARK = '// nowhere:seam'
29
+ export const PLACEMENTS_SEAM = SEAM_PATHS.placements
30
+
31
+ /** The seam file of an interface. */
32
+ export const seamOf = (inf) => SEAM_PATHS[inf.kind]
33
+
34
+ /** The import specifier from the seam to the role's module. */
35
+ function specifier(inf) {
36
+ const seam = seamOf(inf)
37
+ const rel = path.posix.relative(path.posix.dirname(seam), relPath(inf.module)).replace(/\.(m?[jt]sx?)$/, '')
38
+ return rel.startsWith('.') ? rel : `./${rel}`
39
+ }
40
+
41
+ /** The stub text of an interface's seam. */
42
+ export function stubFor(inf) {
43
+ const head = [
44
+ STUB_MARK,
45
+ `// The director's placeholder for ${inf.id}, which task ${inf.producer} makes in ${relPath(inf.module)}.`,
46
+ '// It keeps the game building until that task passes, then becomes one line',
47
+ '// that re-exports the module. Import from this file; never edit it.',
48
+ ]
49
+ if (inf.kind === 'materials') {
50
+ return [
51
+ ...head,
52
+ "import { MeshStandardNodeMaterial } from 'three/webgpu'",
53
+ '',
54
+ '// Mid grey, so nothing here passes for a colour of the brief.',
55
+ 'const placeholder = () => new MeshStandardNodeMaterial({ color: 0x808080, roughness: 0.8 })',
56
+ '',
57
+ ...inf.names.map((n) => `export const ${n} = placeholder()`),
58
+ '',
59
+ ].join('\n')
60
+ }
61
+ return [
62
+ ...head,
63
+ '',
64
+ 'export interface GameAudio {',
65
+ ' readonly events: readonly string[]',
66
+ ' play(event: string, opts?: { at?: [number, number, number]; gain?: number }): void',
67
+ ' update(dt: number, listener?: { position: [number, number, number]; forward: [number, number, number] }): void',
68
+ ' dispose(): void',
69
+ '}',
70
+ '',
71
+ `const EVENTS: readonly string[] = ${JSON.stringify(inf.names)}`,
72
+ '',
73
+ 'export function createAudio(_ctx: { input: { pressed(code: string): boolean } }): GameAudio {',
74
+ ' return { events: EVENTS, play() {}, update() {}, dispose() {} }',
75
+ '}',
76
+ '',
77
+ 'export async function renderOffline(_event: string, _sampleRate?: number): Promise<Float32Array> {',
78
+ ' return new Float32Array(0)',
79
+ '}',
80
+ '',
81
+ ].join('\n')
82
+ }
83
+
84
+ /** The seam once its module is ready. */
85
+ export const flippedFor = (inf) => `${SEAM_MARK}: the director's file. ${inf.id} is made by task ${inf.producer} in ${relPath(inf.module)}.\nexport * from '${specifier(inf)}'\n`
86
+
87
+ const write = (projectRoot, inf, text) => writeAtomic(path.join(projectRoot, seamOf(inf)), text)
88
+
89
+ /** Writes every interface's stub. Returns the seams written. */
90
+ export async function writeSeams(projectRoot, interfaces = []) {
91
+ const out = []
92
+ for (const inf of interfaces) {
93
+ if (!seamOf(inf)) continue
94
+ await write(projectRoot, inf, stubFor(inf))
95
+ out.push(seamOf(inf))
96
+ }
97
+ return out
98
+ }
99
+
100
+ /** Points the seam at the role's module. */
101
+ export const flipSeam = (projectRoot, inf) => write(projectRoot, inf, flippedFor(inf))
102
+ /** Puts the stub back. */
103
+ export const stubSeam = (projectRoot, inf) => write(projectRoot, inf, stubFor(inf))
104
+
105
+ /** Whether the seam is pointed at its module now. */
106
+ export function isFlipped(projectRoot, inf) {
107
+ try {
108
+ return fs.readFileSync(path.join(projectRoot, seamOf(inf)), 'utf8').startsWith(SEAM_MARK + ':')
109
+ } catch {
110
+ return false
111
+ }
112
+ }
113
+
114
+ // ---------------------------------------------------------------- the placements
115
+
116
+ const r3 = (n) => Math.round(n * 1000) / 1000
117
+
118
+ /**
119
+ * The placements seam: place(ctx, world, id, standIn, opts) adds what
120
+ * stands at a placement as world.add would. `made` maps a placement id to
121
+ * the model that took it over: { asset, at (the point of the model that
122
+ * meets the stand-in, in the file's own metres), anchor, task, size }.
123
+ * The model keeps its real size; its anchor (its base, or its top) goes
124
+ * where the stand-in's was, at the centre of the stand-in's footprint, and
125
+ * it turns as the stand-in turned. The marker stays a stub's while any
126
+ * placement still shows its stand-in.
127
+ */
128
+ export function placementsFor(placements = [], made = {}) {
129
+ const left = placements.filter((p) => !made[p.id])
130
+ const ids = placements.map((p) => p.id)
131
+ const models = placements.filter((p) => made[p.id]).map((p) => {
132
+ const m = made[p.id]
133
+ const size = Array.isArray(m.size) ? `, ${m.size.map((n) => r3(n)).join(' x ')} m` : ''
134
+ return ` ${JSON.stringify(p.id)}: { asset: ${JSON.stringify(m.asset)}, at: [${m.at.map(r3).join(', ')}], anchor: '${m.anchor}' }, // task ${m.task}${size}`
135
+ })
136
+ return [
137
+ left.length ? STUB_MARK : `${SEAM_MARK}: the director's file.`,
138
+ "// The director's placements: what stands at each of the blockout's placements.",
139
+ '// place() adds the stand-in the code hands it until the model made for that',
140
+ "// placement is ready; then that model, in the stand-in's place, at its real",
141
+ '// size. Add every stand-in of a placement through place(); never edit this file.',
142
+ ...(left.length ? [`// Still stand-ins: ${left.map((p) => p.id).join(', ')}.`] : []),
143
+ "import * as THREE from 'three/webgpu'",
144
+ "import type { GameContext, Instance, SpawnOptions, World } from '@nowhere/sdk'",
145
+ '',
146
+ `export const PLACEMENTS: readonly string[] = ${JSON.stringify(ids)}`,
147
+ '',
148
+ "type Made = { asset: string; at: [number, number, number]; anchor: 'base' | 'top' }",
149
+ '',
150
+ '/** The models made so far, by placement. */',
151
+ `const MADE: Record<string, Made> = {${models.length ? `\n${models.join('\n')}\n` : ''}}`,
152
+ '',
153
+ '/**',
154
+ ' * Adds what stands at placement `id`, as world.add(id, standIn, opts) would:',
155
+ " * the model made for it once it is ready, else the stand-in. The model's",
156
+ " * group keeps the stand-in's origin and turn, so code that moves it moves",
157
+ ' * it as it moved the stand-in.',
158
+ ' */',
159
+ 'export function place(ctx: GameContext, world: World, id: string, standIn: THREE.Object3D, opts: SpawnOptions = {}): Instance {',
160
+ ' const made = MADE[id]',
161
+ ' if (!made || !ctx.assets) {',
162
+ ' standIn.userData.placement = id',
163
+ ' return world.add(id, standIn, opts)',
164
+ ' }',
165
+ ' // The stand-in where world.add would have put it, and its bounds there.',
166
+ ' const { position, rotation, scale, ...rest } = opts',
167
+ ' if (position) standIn.position.fromArray(position)',
168
+ ' if (rotation) standIn.rotation.fromArray(rotation)',
169
+ " if (typeof scale === 'number') standIn.scale.setScalar(scale)",
170
+ ' else if (scale) standIn.scale.fromArray(scale)',
171
+ ' standIn.updateMatrixWorld(true)',
172
+ ' const box = new THREE.Box3().setFromObject(standIn)',
173
+ " const meet = box.isEmpty() ? standIn.position.clone() : new THREE.Vector3((box.min.x + box.max.x) / 2, made.anchor === 'top' ? box.max.y : box.min.y, (box.min.z + box.max.z) / 2)",
174
+ ' const group = new THREE.Group()',
175
+ ' group.position.copy(standIn.position)',
176
+ ' group.quaternion.copy(standIn.quaternion)',
177
+ ' const local = meet.sub(standIn.position).applyQuaternion(standIn.quaternion.clone().invert())',
178
+ ' const model = ctx.assets.model(made.asset)',
179
+ ' model.position.set(local.x - made.at[0], local.y - made.at[1], local.z - made.at[2])',
180
+ ' group.add(model)',
181
+ ' group.userData.placement = id',
182
+ ' group.userData.placementModel = made.asset',
183
+ ' return world.add(id, group, rest)',
184
+ '}',
185
+ '',
186
+ ].join('\n')
187
+ }
188
+
189
+ /** Writes the placements seam as `made` has it. */
190
+ export const writePlacements = (projectRoot, placements, made = {}) => writeAtomic(path.join(projectRoot, PLACEMENTS_SEAM), placementsFor(placements, made))
191
+
192
+ /**
193
+ * Where a model's anchor is, from the file itself: the centre of its
194
+ * footprint at its base (or its top), in the file's own metres, with its
195
+ * size. { at, size } or { error }.
196
+ */
197
+ export async function anchorOf(projectRoot, rel, anchor = 'base') {
198
+ try {
199
+ const { boundsOf, readGltf } = await import('../assets/gltf.mjs')
200
+ const b = boundsOf(await readGltf(path.join(projectRoot, relPath(rel))))
201
+ if (!b || !b.size.some((n) => n > 0)) return { error: `${relPath(rel)} has no geometry to place` }
202
+ return { at: [(b.min[0] + b.max[0]) / 2, anchor === 'top' ? b.max[1] : b.min[1], (b.min[2] + b.max[2]) / 2], size: b.size }
203
+ } catch (err) {
204
+ return { error: `${relPath(rel)} could not be read as a model: ${String(err?.message ?? err).split('\n')[0]}` }
205
+ }
206
+ }
207
+
208
+ /** The nw_eval code that answers true when every placement in `ids` stands
209
+ * in the running game through place() (the seam tags what it adds), else
210
+ * { missing }. */
211
+ export const placementsProbe = (ids) =>
212
+ `const want = ${JSON.stringify(ids)}; const seen = new Set(); (world?.root ?? root)?.traverse?.((o) => { const p = o.userData?.placement; if (typeof p === 'string') seen.add(p) }); const missing = want.filter((id) => !seen.has(id)); return missing.length === 0 ? true : { missing }`
213
+
214
+ /** Every file under src/ that is still a stub. */
215
+ export async function stubsLeft(projectRoot) {
216
+ const found = []
217
+ const walk = async (rel) => {
218
+ let entries = []
219
+ try {
220
+ entries = await fsp.readdir(path.join(projectRoot, rel), { withFileTypes: true })
221
+ } catch {
222
+ return
223
+ }
224
+ for (const e of entries) {
225
+ const child = `${rel}/${e.name}`
226
+ if (e.isDirectory()) {
227
+ if (e.name !== 'node_modules') await walk(child)
228
+ } else if (/\.(m?[jt]sx?)$/.test(e.name)) {
229
+ try {
230
+ const handle = await fsp.open(path.join(projectRoot, child), 'r')
231
+ const buf = Buffer.alloc(STUB_MARK.length)
232
+ await handle.read(buf, 0, buf.length, 0)
233
+ await handle.close()
234
+ if (buf.toString('utf8') === STUB_MARK) found.push(child)
235
+ } catch {
236
+ // unreadable: not a stub this can tell
237
+ }
238
+ }
239
+ }
240
+ }
241
+ await walk('src')
242
+ return found
243
+ }