@wildshard/sdk 0.0.1 → 0.2.4

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 (688) hide show
  1. package/GUIDE.md +895 -0
  2. package/README.md +13 -5
  3. package/bin/wildshard.mjs +38 -0
  4. package/lint/declaration-config.d.mts +2 -0
  5. package/lint/declaration-config.mjs +19 -0
  6. package/lint/engine-plugin.d.mts +2 -0
  7. package/lint/engine-plugin.mjs +40 -0
  8. package/lint/host-callbacks.d.mts +6 -0
  9. package/lint/host-callbacks.mjs +123 -0
  10. package/lint/host-files.d.mts +1 -0
  11. package/lint/host-files.mjs +7 -0
  12. package/lint/layer-exports.d.mts +2 -0
  13. package/lint/layer-exports.mjs +21 -0
  14. package/lint/legacy-line-basis.json +995 -0
  15. package/lint/nine-tiling-baseline.json +35 -0
  16. package/lint/ratchet.json +11 -0
  17. package/lint/runtime-files.d.mts +12 -0
  18. package/lint/runtime-files.json +16 -0
  19. package/lint/runtime-files.mjs +69 -0
  20. package/lint/runtime-performance.d.mts +6 -0
  21. package/lint/runtime-performance.mjs +184 -0
  22. package/lint/sdk-plugin.d.mts +4 -0
  23. package/lint/sdk-plugin.mjs +134 -0
  24. package/lint/shardfile-boundaries.d.mts +10 -0
  25. package/lint/shardfile-boundaries.mjs +122 -0
  26. package/lint/tile-bake-debt.json +556 -0
  27. package/package.json +365 -3
  28. package/scripts/agent-parity.mjs +1524 -0
  29. package/scripts/agent-sync.mjs +518 -0
  30. package/scripts/apfs-clone.mjs +67 -0
  31. package/scripts/assert-store-layout.mjs +23 -0
  32. package/scripts/astc6-phone-cap.d.mts +3 -0
  33. package/scripts/astc6-phone-cap.mjs +137 -0
  34. package/scripts/audit-assets.d.mts +10 -0
  35. package/scripts/audit-assets.mjs +151 -0
  36. package/scripts/bake/coatFiles.d.mts +6 -0
  37. package/scripts/bake/coatFiles.mjs +37 -0
  38. package/scripts/bake/environment.d.mts +2 -0
  39. package/scripts/bake/environment.mjs +58 -0
  40. package/scripts/bake/far-proxies.mjs +45 -0
  41. package/scripts/bake/keyed-sky.d.mts +4 -0
  42. package/scripts/bake/keyed-sky.mjs +34 -0
  43. package/scripts/bake/movers.mjs +56 -0
  44. package/scripts/bake/nativeWorld.d.mts +6 -0
  45. package/scripts/bake/nativeWorld.mjs +43 -0
  46. package/scripts/bake/navmeshGround.ts +22 -0
  47. package/scripts/bake/near-placeholder.mjs +331 -0
  48. package/scripts/bake/placeholderShards.mjs +41 -0
  49. package/scripts/bake/skins.mjs +15 -0
  50. package/scripts/bake/template-skins.mjs +33 -0
  51. package/scripts/bake/viewmodelBytes.ts +26 -0
  52. package/scripts/bake/viewmodelPage.ts +11 -0
  53. package/scripts/bake/worldHost.d.mts +35 -0
  54. package/scripts/bake/worldHost.mjs +110 -0
  55. package/scripts/bake-astc6.cache.json +80 -0
  56. package/scripts/bake-astc6.far-reach.cache.json +23 -0
  57. package/scripts/bake-astc6.list.json +111 -0
  58. package/scripts/bake-astc6.mjs +279 -0
  59. package/scripts/bake-astc6.nalati-grasslands.cache.json +42 -0
  60. package/scripts/bake-catalogue.mjs +44 -0
  61. package/scripts/bake-check.mjs +54 -0
  62. package/scripts/bake-chunk.mjs +124 -0
  63. package/scripts/bake-cloud-field.mjs +24 -0
  64. package/scripts/bake-coats.mjs +110 -0
  65. package/scripts/bake-data-maps.d.mts +24 -0
  66. package/scripts/bake-data-maps.mjs +72 -0
  67. package/scripts/bake-entry-programs.mjs +117 -0
  68. package/scripts/bake-geometry.mjs +106 -0
  69. package/scripts/bake-hybrid-tiles.mjs +28 -0
  70. package/scripts/bake-ktx2.cache.json +276 -0
  71. package/scripts/bake-ktx2.list.json +365 -0
  72. package/scripts/bake-ktx2.mjs +477 -0
  73. package/scripts/bake-map-glb.mjs +127 -0
  74. package/scripts/bake-map-rest.d.mts +7 -0
  75. package/scripts/bake-map-rest.mjs +50 -0
  76. package/scripts/bake-maps.mjs +200 -0
  77. package/scripts/bake-navmesh.mjs +259 -0
  78. package/scripts/bake-packs.mjs +129 -0
  79. package/scripts/bake-pickups.mjs +102 -0
  80. package/scripts/bake-query-terrain.mjs +64 -0
  81. package/scripts/bake-recurve-pool.mjs +16 -0
  82. package/scripts/bake-section-schemas.d.mts +3 -0
  83. package/scripts/bake-template-shardfile.mjs +32 -0
  84. package/scripts/bake-textures.mjs +80 -0
  85. package/scripts/bake-viewmodel-sets.json +45 -0
  86. package/scripts/bake-viewmodel-sets.mjs +137 -0
  87. package/scripts/bake-voxel-ao.mjs +119 -0
  88. package/scripts/bake-water-ripples.mjs +25 -0
  89. package/scripts/blender/README.md +129 -0
  90. package/scripts/blender/build.sh +166 -0
  91. package/scripts/blender/lib/export-scene.mjs +129 -0
  92. package/scripts/blender/lib/glb-digest.mjs +188 -0
  93. package/scripts/blender/lib/glb.py +68 -0
  94. package/scripts/blender/lib/save_blend.py +17 -0
  95. package/scripts/blender/lib/world_fixture.py +55 -0
  96. package/scripts/blender/targets.json +591 -0
  97. package/scripts/build-sdk.mjs +95 -0
  98. package/scripts/build-shardfiles.d.mts +7 -0
  99. package/scripts/build-shardfiles.mjs +206 -0
  100. package/scripts/capture-hero.mjs +137 -0
  101. package/scripts/check-lift-review.mjs +23 -0
  102. package/scripts/chromium-keychain-check.mjs +139 -0
  103. package/scripts/chromium-keychain.d.mts +1 -0
  104. package/scripts/chromium-keychain.mjs +5 -0
  105. package/scripts/compile-script.d.mts +3 -0
  106. package/scripts/compile-script.mjs +8 -0
  107. package/scripts/creature-color.mjs +255 -0
  108. package/scripts/decide/calibrate.py +127 -0
  109. package/scripts/decide/calibration/2026-10-03/labels-s1.tsv +281 -0
  110. package/scripts/decide/calibration/2026-10-03/labels-s2.tsv +97 -0
  111. package/scripts/decide/calibration/2026-10-03/labels-s3.tsv +48 -0
  112. package/scripts/decide/calibration/2026-10-03/labels-s3b.tsv +26 -0
  113. package/scripts/decide/calibration/2026-10-03/res-capture-status-v1.jsonl +376 -0
  114. package/scripts/decide/calibration/2026-10-03/res-text-garbled-strings.jsonl +48 -0
  115. package/scripts/decide/calibration/2026-10-03/res-text-garbled-v1.jsonl +73 -0
  116. package/scripts/decide/decide.py +262 -0
  117. package/scripts/decide/decide.sh +50 -0
  118. package/scripts/decide/layer-purity-pilot.mjs +41 -0
  119. package/scripts/decide/sets/capture-status.json +46 -0
  120. package/scripts/decide/sets/layer-purity.json +28 -0
  121. package/scripts/decide/sets/text-garbled.json +17 -0
  122. package/scripts/decide/test_decide.py +37 -0
  123. package/scripts/docs.mjs +15 -0
  124. package/scripts/entry-reads/crawl.ts +152 -0
  125. package/scripts/entry-reads/tsconfig.json +25 -0
  126. package/scripts/gen-format-schema.d.mts +2 -0
  127. package/scripts/gen-format-schema.mjs +21 -0
  128. package/scripts/gen-host-catalogue.d.mts +14 -0
  129. package/scripts/gen-host-catalogue.mjs +108 -0
  130. package/scripts/gen-shard-layout-doc.d.mts +4 -0
  131. package/scripts/gen-shard-layout-doc.mjs +55 -0
  132. package/scripts/gen-shards.d.mts +17 -0
  133. package/scripts/gen-shards.mjs +311 -0
  134. package/scripts/goldens/capture-inputs.d.mts +4 -0
  135. package/scripts/goldens/capture-inputs.mjs +34 -0
  136. package/scripts/goldens/colour_shift.py +27 -0
  137. package/scripts/goldens/native-residency.d.mts +10 -0
  138. package/scripts/goldens/native-residency.mjs +104 -0
  139. package/scripts/goldens/plot-inputs.d.mts +12 -0
  140. package/scripts/goldens/plot-inputs.mjs +46 -0
  141. package/scripts/gpu-texmem.mjs +98 -0
  142. package/scripts/horizon-matte/config.py +24 -0
  143. package/scripts/horizon-matte/encode.py +91 -0
  144. package/scripts/horizon-matte/key.py +141 -0
  145. package/scripts/horizon-matte/mkjobs.py +33 -0
  146. package/scripts/horizon-matte/mkjobs_day2.py +11 -0
  147. package/scripts/horizon-matte/overlap.py +80 -0
  148. package/scripts/horizon-matte/run_codex.py +57 -0
  149. package/scripts/horizon-matte/stitch.py +133 -0
  150. package/scripts/img2mesh/CC0.md +105 -0
  151. package/scripts/img2mesh/README.md +209 -0
  152. package/scripts/img2mesh/ab_board.py +102 -0
  153. package/scripts/img2mesh/birds/birds.json +255 -0
  154. package/scripts/img2mesh/birds/birds_atlas.py +150 -0
  155. package/scripts/img2mesh/birds/birds_fix_preview.mjs +103 -0
  156. package/scripts/img2mesh/birds/birds_fix_render.py +75 -0
  157. package/scripts/img2mesh/birds/birds_pack.py +110 -0
  158. package/scripts/img2mesh/birds/birds_phone_b.py +112 -0
  159. package/scripts/img2mesh/birds/birds_post.py +550 -0
  160. package/scripts/img2mesh/birds/birds_render.py +125 -0
  161. package/scripts/img2mesh/birds/birds_sheet.py +33 -0
  162. package/scripts/img2mesh/birds/birds_view.py +60 -0
  163. package/scripts/img2mesh/board.py +100 -0
  164. package/scripts/img2mesh/build_cc0.sh +52 -0
  165. package/scripts/img2mesh/build_driftwood.sh +12 -0
  166. package/scripts/img2mesh/build_faces.sh +53 -0
  167. package/scripts/img2mesh/build_props.py +81 -0
  168. package/scripts/img2mesh/cc0_export.py +186 -0
  169. package/scripts/img2mesh/driftwood_post.py +571 -0
  170. package/scripts/img2mesh/e304_faces.sh +67 -0
  171. package/scripts/img2mesh/face_remaster.py +911 -0
  172. package/scripts/img2mesh/face_views.py +95 -0
  173. package/scripts/img2mesh/faces-e304.json +9 -0
  174. package/scripts/img2mesh/faces.json +30 -0
  175. package/scripts/img2mesh/head_cut.py +100 -0
  176. package/scripts/img2mesh/hi3d_paint.py +94 -0
  177. package/scripts/img2mesh/hi3d_refine.py +161 -0
  178. package/scripts/img2mesh/hunyuan_cpu_rasterizer.sh +42 -0
  179. package/scripts/img2mesh/pine_hollow_phone.sh +13 -0
  180. package/scripts/img2mesh/props/coral-arch.json +32 -0
  181. package/scripts/img2mesh/props/ember-furnace.json +30 -0
  182. package/scripts/img2mesh/props/night-market-gate.json +10 -0
  183. package/scripts/img2mesh/render_still.py +86 -0
  184. package/scripts/img2mesh/rig_strip.mjs +46 -0
  185. package/scripts/img2mesh/rig_transfer.mjs +104 -0
  186. package/scripts/img2mesh/split_sheet.py +48 -0
  187. package/scripts/img2mesh/trellis_batch.py +110 -0
  188. package/scripts/img2mesh/versus_board.py +114 -0
  189. package/scripts/import-bundle.d.mts +2 -0
  190. package/scripts/import-bundle.mjs +20 -0
  191. package/scripts/ktx2-ab-board.py +133 -0
  192. package/scripts/ktx2-ab.mjs +111 -0
  193. package/scripts/ktx2-settings.mjs +18 -0
  194. package/scripts/land.d.mts +14 -0
  195. package/scripts/land.mjs +809 -0
  196. package/scripts/lint-dispatch.mjs +14 -0
  197. package/scripts/map-bake-frames.d.mts +4 -0
  198. package/scripts/map-bake-frames.mjs +23 -0
  199. package/scripts/map-geometry.d.mts +9 -0
  200. package/scripts/map-geometry.mjs +29 -0
  201. package/scripts/map-world.mjs +162 -0
  202. package/scripts/mockup-local.sh +46 -0
  203. package/scripts/music/export-midi.mjs +68 -0
  204. package/scripts/music/gen/analyze.py +308 -0
  205. package/scripts/music/gen/audio_jobs.py +46 -0
  206. package/scripts/music/gen/briefs.json +51 -0
  207. package/scripts/music/gen/build_page.py +334 -0
  208. package/scripts/music/gen/folk.json +3187 -0
  209. package/scripts/music/gen/gen_ace_step.py +156 -0
  210. package/scripts/music/gen/gen_heartmula.py +187 -0
  211. package/scripts/music/gen/gen_minimax.py +143 -0
  212. package/scripts/music/gen/gen_sao.py +122 -0
  213. package/scripts/music/gen/gen_sao_small.py +104 -0
  214. package/scripts/music/gen/gen_sfx.py +98 -0
  215. package/scripts/music/gen/gen_sfx_ezaudio.py +112 -0
  216. package/scripts/music/gen/gen_sfx_moss.py +112 -0
  217. package/scripts/music/gen/models.json +61 -0
  218. package/scripts/music/gen/nalati-jobs.json +104 -0
  219. package/scripts/music/gen/nalati-score-build.json +119 -0
  220. package/scripts/music/gen/nalati-score.json +3448 -0
  221. package/scripts/music/gen/ob7-fit-decisions.json +38 -0
  222. package/scripts/music/gen/ob7-score-jobs.json +152 -0
  223. package/scripts/music/gen/ob7-sfx-jobs.json +897 -0
  224. package/scripts/music/gen/ob7_build.py +469 -0
  225. package/scripts/music/gen/ob7_generate.py +67 -0
  226. package/scripts/music/gen/ob7_run.sh +42 -0
  227. package/scripts/music/gen/orchestral.json +3187 -0
  228. package/scripts/music/gen/own_score.py +486 -0
  229. package/scripts/music/gen/ph-jobs.json +27 -0
  230. package/scripts/music/gen/ph_page.py +222 -0
  231. package/scripts/music/gen/piano.json +3175 -0
  232. package/scripts/music/gen/rank_v3.py +248 -0
  233. package/scripts/music/gen/sfx-best.json +2486 -0
  234. package/scripts/music/gen/sfx-ezaudio.json +4082 -0
  235. package/scripts/music/gen/sfx-jobs.json +57 -0
  236. package/scripts/music/gen/sfx-minimax-jobs.json +16 -0
  237. package/scripts/music/gen/sfx-minimax.json +289 -0
  238. package/scripts/music/gen/sfx-moss.json +4082 -0
  239. package/scripts/music/gen/sfx-nalati-b3-jobs.json +17 -0
  240. package/scripts/music/gen/sfx-nalati-jobs.json +338 -0
  241. package/scripts/music/gen/sfx-nalati.json +11202 -0
  242. package/scripts/music/gen/sfx-nd-jobs.json +57 -0
  243. package/scripts/music/gen/sfx-nd-moss.json +2097 -0
  244. package/scripts/music/gen/sfx-nd-sa3-medium.json +2097 -0
  245. package/scripts/music/gen/sfx-nd-summary.json +38 -0
  246. package/scripts/music/gen/sfx-peaks.json +7 -0
  247. package/scripts/music/gen/sfx-ph-jobs.json +169 -0
  248. package/scripts/music/gen/sfx-ph-moss.json +6564 -0
  249. package/scripts/music/gen/sfx-ph-sa3-medium.json +7239 -0
  250. package/scripts/music/gen/sfx-ph-summary.json +63 -0
  251. package/scripts/music/gen/sfx-sa3-medium.json +4082 -0
  252. package/scripts/music/gen/sfx-sa3.json +4082 -0
  253. package/scripts/music/gen/sfx-summary.json +107 -0
  254. package/scripts/music/gen/sfx_build.py +332 -0
  255. package/scripts/music/gen/sfx_merge.py +255 -0
  256. package/scripts/music/gen/sfx_minimax.py +61 -0
  257. package/scripts/music/gen/sfx_nalati.py +331 -0
  258. package/scripts/music/gen/sfx_sprite.py +424 -0
  259. package/scripts/music/gen/stems.py +539 -0
  260. package/scripts/music/gen/test_loop_meter.py +29 -0
  261. package/scripts/music/gen/test_ob7_provenance.py +77 -0
  262. package/scripts/music/gen/v3-folk-build.json +148 -0
  263. package/scripts/music/gen/v3-folk.json +1818 -0
  264. package/scripts/music/gen/v3-jobs.json +145 -0
  265. package/scripts/music/gen/v3-orchestral-build.json +148 -0
  266. package/scripts/music/gen/v3-orchestral.json +1813 -0
  267. package/scripts/music/gen/v3-ph-folk-build.json +94 -0
  268. package/scripts/music/gen/v3-ph-folk.json +1806 -0
  269. package/scripts/music/gen/v3-ph-orchestral-build.json +94 -0
  270. package/scripts/music/gen/v3-ph-orchestral.json +1824 -0
  271. package/scripts/music/gen/v3-ph-piano-build.json +94 -0
  272. package/scripts/music/gen/v3-ph-piano.json +1818 -0
  273. package/scripts/music/gen/v3-piano-build.json +148 -0
  274. package/scripts/music/gen/v3-piano.json +1813 -0
  275. package/scripts/music/wildshard-theme.mid +0 -0
  276. package/scripts/music/wildshard-trailer30.mid +0 -0
  277. package/scripts/named-blob-output.d.mts +8 -0
  278. package/scripts/named-blob-output.mjs +48 -0
  279. package/scripts/pack-all.mjs +15 -0
  280. package/scripts/pid-lock.d.mts +1 -0
  281. package/scripts/pid-lock.mjs +63 -0
  282. package/scripts/practice/bake_dummy.py +53 -0
  283. package/scripts/practice/build_dummies.sh +43 -0
  284. package/scripts/practice/dummy_parts.py +568 -0
  285. package/scripts/practice/dummy_rig_gate.py +139 -0
  286. package/scripts/practice/gate_sheet.py +36 -0
  287. package/scripts/practice/generate_dummy_unimate.py +132 -0
  288. package/scripts/practice/pack_dummy.mjs +59 -0
  289. package/scripts/practice/repair_dummy_weights.mjs +68 -0
  290. package/scripts/practice/rig_dummy.py +828 -0
  291. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  292. package/scripts/preparation-seed.mjs +15 -0
  293. package/scripts/prepare-basis-tool.mjs +6 -0
  294. package/scripts/prepare-product.d.mts +14 -0
  295. package/scripts/prepare-product.mjs +101 -0
  296. package/scripts/product-build-tools.d.mts +3 -0
  297. package/scripts/product-build-tools.json +3 -0
  298. package/scripts/product-build-tools.mjs +31 -0
  299. package/scripts/publish-public.mjs +7 -0
  300. package/scripts/push-tables.d.mts +1 -0
  301. package/scripts/push-tables.mjs +28 -0
  302. package/scripts/record-shard-mounts.mjs +133 -0
  303. package/scripts/sdk-externals.d.mts +2 -0
  304. package/scripts/sdk-externals.mjs +2 -0
  305. package/scripts/section-inventory.ts +209 -0
  306. package/scripts/select-candidate.mjs +15 -0
  307. package/scripts/shard-build-pool.d.mts +4 -0
  308. package/scripts/shard-build-pool.mjs +53 -0
  309. package/scripts/shard-line-baseline.json +17 -0
  310. package/scripts/shard-milestones.d.mts +15 -0
  311. package/scripts/shard-milestones.mjs +105 -0
  312. package/scripts/shard-output-report.d.mts +9 -0
  313. package/scripts/shard-output-report.mjs +85 -0
  314. package/scripts/shard-platform-cli.mjs +93 -0
  315. package/scripts/shard-progress.mjs +212 -0
  316. package/scripts/shard-timelapse.py +102 -0
  317. package/scripts/shardfile-cold-boot.mjs +79 -0
  318. package/scripts/shardfile-vite.d.mts +4 -0
  319. package/scripts/shardfile-vite.mjs +20 -0
  320. package/scripts/simplify-models.mjs +24 -0
  321. package/scripts/site-facts.mjs +88 -0
  322. package/scripts/test-template-gate.mjs +44 -0
  323. package/scripts/test_golden_compare.py +68 -0
  324. package/scripts/tex-tiers.cache.json +181 -0
  325. package/scripts/tex-tiers.mjs +240 -0
  326. package/scripts/texmem-probe.mjs +184 -0
  327. package/scripts/unused-assets.mjs +173 -0
  328. package/scripts/vite-tmp.d.mts +23 -0
  329. package/scripts/vite-tmp.mjs +157 -0
  330. package/scripts/wave-line-baselines.json +32 -0
  331. package/scripts/wildshard.d.mts +4 -0
  332. package/scripts/wildshard.mjs +105 -0
  333. package/scripts/witness-checkpoints.d.mts +10 -0
  334. package/scripts/witness-checkpoints.mjs +84 -0
  335. package/scripts/witness-generation.d.mts +10 -0
  336. package/scripts/witness-generation.mjs +45 -0
  337. package/scripts/witness-manifests.d.mts +8 -0
  338. package/scripts/witness-manifests.mjs +157 -0
  339. package/scripts/worktree-ignore.d.mts +4 -0
  340. package/scripts/worktree-ignore.mjs +36 -0
  341. package/scripts/worktree-reap.mjs +214 -0
  342. package/scripts/worktree.mjs +396 -0
  343. package/scripts/worldclaw/capture-front.sh +28 -0
  344. package/scripts/worldclaw/design-template.md +62 -0
  345. package/scripts/worldclaw/spec-map.py +92 -0
  346. package/scripts/worldclaw/spec.ts +96 -0
  347. package/skills/wildshard/SKILL.md +50 -0
  348. package/skills/wildshard-goldens/SKILL.md +54 -0
  349. package/skills/wildshard-mockup-to-model/SKILL.md +56 -0
  350. package/skills/wildshard-upgrade/SKILL.md +47 -0
  351. package/src/.oxfmtrc.json +50 -0
  352. package/src/.oxlintrc.json +173 -0
  353. package/src/cli/account/account.ts +199 -0
  354. package/src/cli/account/command.ts +193 -0
  355. package/src/cli/account/key.ts +154 -0
  356. package/src/cli/args.ts +97 -0
  357. package/src/cli/audio/audio.ts +39 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +204 -0
  361. package/src/cli/hero/adopt.ts +103 -0
  362. package/src/cli/hero/hero.ts +112 -0
  363. package/src/cli/hero/stamp.ts +298 -0
  364. package/src/cli/main.ts +291 -0
  365. package/src/cli/report.ts +20 -0
  366. package/src/cli/shardfile/command.ts +49 -0
  367. package/src/cli/shardfile/shardfile.ts +192 -0
  368. package/src/cli/upload/api.ts +246 -0
  369. package/src/cli/upload/compress.ts +55 -0
  370. package/src/cli/upload/hero.ts +62 -0
  371. package/src/cli/upload/placement.ts +115 -0
  372. package/src/cli/upload/provenance.ts +192 -0
  373. package/src/cli/upload/signature.ts +30 -0
  374. package/src/cli/upload/upload.ts +269 -0
  375. package/src/cli/upload/validate.ts +74 -0
  376. package/src/cli/upload/wire.ts +147 -0
  377. package/src/cli/version.ts +63 -0
  378. package/src/commons/bake/portableMath.ts +187 -0
  379. package/src/commons/catalogue.ts +10 -0
  380. package/src/commons/courseProgram.ts +32 -0
  381. package/src/commons/practiceCourse.ts +16 -0
  382. package/src/commons/scripts/abi.as +14 -0
  383. package/src/commons/scripts/bridge.as +14 -0
  384. package/src/commons/scripts/course.as +63 -0
  385. package/src/scripts/ask-new.sh +29 -0
  386. package/src/scripts/asks.mjs +141 -0
  387. package/src/scripts/herdr-prompt.sh +34 -0
  388. package/src/scripts/herdr-question-open.sh +67 -0
  389. package/src/scripts/md-wrap.mjs +229 -0
  390. package/src/server/app.ts +19 -0
  391. package/src/server/serve.ts +49 -0
  392. package/src/sharddev/admission.ts +7 -0
  393. package/src/sharddev/agentFiles.ts +127 -0
  394. package/src/sharddev/arenaView.ts +15 -0
  395. package/src/sharddev/as/groupBankV2.ts +36 -0
  396. package/src/sharddev/as/groupStepV2.ts +13 -0
  397. package/src/sharddev/as/ws.ts +30 -0
  398. package/src/sharddev/as/wsV2.ts +180 -0
  399. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  400. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  401. package/src/sharddev/assetHandle.ts +84 -0
  402. package/src/sharddev/assetOwner.ts +70 -0
  403. package/src/sharddev/assetScope.ts +30 -0
  404. package/src/sharddev/assets.ts +21 -0
  405. package/src/sharddev/audio.ts +9 -0
  406. package/src/sharddev/audioEncode.ts +211 -0
  407. package/src/sharddev/author.ts +3 -0
  408. package/src/sharddev/authorError.ts +28 -0
  409. package/src/sharddev/authorManifest.ts +39 -0
  410. package/src/sharddev/bake/annulus.ts +19 -0
  411. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  412. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  413. package/src/sharddev/bake/authoredWorld.ts +201 -0
  414. package/src/sharddev/bake/basisEncoder.ts +95 -0
  415. package/src/sharddev/bake/basisGlb.ts +85 -0
  416. package/src/sharddev/bake/basisTool.ts +74 -0
  417. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  418. package/src/sharddev/bake/byteCodec.ts +33 -0
  419. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  420. package/src/sharddev/bake/coarseCopy.ts +59 -0
  421. package/src/sharddev/bake/colliders.ts +87 -0
  422. package/src/sharddev/bake/compactGlb.ts +224 -0
  423. package/src/sharddev/bake/compileScript.ts +119 -0
  424. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  425. package/src/sharddev/bake/contactRows.ts +84 -0
  426. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  427. package/src/sharddev/bake/export.ts +67 -0
  428. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  429. package/src/sharddev/bake/farImpostor.ts +120 -0
  430. package/src/sharddev/bake/forest.ts +100 -0
  431. package/src/sharddev/bake/format-hook.mjs +2 -0
  432. package/src/sharddev/bake/generatorGlb.ts +23 -0
  433. package/src/sharddev/bake/geometryBounds.ts +77 -0
  434. package/src/sharddev/bake/geometryError.ts +48 -0
  435. package/src/sharddev/bake/glb.ts +355 -0
  436. package/src/sharddev/bake/glbCompression.ts +143 -0
  437. package/src/sharddev/bake/gltfSource.ts +59 -0
  438. package/src/sharddev/bake/groundMap.ts +142 -0
  439. package/src/sharddev/bake/image.ts +20 -0
  440. package/src/sharddev/bake/isleMap.ts +64 -0
  441. package/src/sharddev/bake/json.mjs +84 -0
  442. package/src/sharddev/bake/keyedSky.ts +47 -0
  443. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  444. package/src/sharddev/bake/kinds.ts +137 -0
  445. package/src/sharddev/bake/lightSources.ts +31 -0
  446. package/src/sharddev/bake/mapAssembly.ts +84 -0
  447. package/src/sharddev/bake/mapRaster.ts +173 -0
  448. package/src/sharddev/bake/mapRest.ts +57 -0
  449. package/src/sharddev/bake/mapScenes.ts +234 -0
  450. package/src/sharddev/bake/materialGraph.ts +32 -0
  451. package/src/sharddev/bake/meadow.ts +27 -0
  452. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  453. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  454. package/src/sharddev/bake/nativeLattice.ts +178 -0
  455. package/src/sharddev/bake/nativeRaster.ts +106 -0
  456. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  457. package/src/sharddev/bake/navigation-json.mjs +38 -0
  458. package/src/sharddev/bake/navigation.ts +113 -0
  459. package/src/sharddev/bake/navigationAsset.ts +18 -0
  460. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  461. package/src/sharddev/bake/normalizeRig.ts +80 -0
  462. package/src/sharddev/bake/phoneAstc.ts +93 -0
  463. package/src/sharddev/bake/placeholders.ts +581 -0
  464. package/src/sharddev/bake/placement.ts +80 -0
  465. package/src/sharddev/bake/portableBytes.ts +18 -0
  466. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  467. package/src/sharddev/bake/practiceCourse.ts +49 -0
  468. package/src/sharddev/bake/primitives.ts +96 -0
  469. package/src/sharddev/bake/props.ts +443 -0
  470. package/src/sharddev/bake/questPlacement.ts +98 -0
  471. package/src/sharddev/bake/rawTexture.ts +26 -0
  472. package/src/sharddev/bake/riderArms.ts +97 -0
  473. package/src/sharddev/bake/rig.ts +95 -0
  474. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  475. package/src/sharddev/bake/signPlacements.ts +25 -0
  476. package/src/sharddev/bake/simplifier.ts +52 -0
  477. package/src/sharddev/bake/skinned.ts +312 -0
  478. package/src/sharddev/bake/slabChunks.ts +149 -0
  479. package/src/sharddev/bake/slabs.ts +263 -0
  480. package/src/sharddev/bake/source-loader.mjs +55 -0
  481. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  482. package/src/sharddev/bake/species.ts +368 -0
  483. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  484. package/src/sharddev/bake/splatGround.ts +141 -0
  485. package/src/sharddev/bake/staticMaterials.ts +171 -0
  486. package/src/sharddev/bake/terrain.ts +195 -0
  487. package/src/sharddev/bake/texture.ts +33 -0
  488. package/src/sharddev/bake/textureWasm.ts +81 -0
  489. package/src/sharddev/bake/tileEncoder.ts +11 -0
  490. package/src/sharddev/bake/tileGrid.ts +62 -0
  491. package/src/sharddev/bake/v2Finite.ts +160 -0
  492. package/src/sharddev/bake/v2Fuel.ts +71 -0
  493. package/src/sharddev/bake/wholePartition.ts +74 -0
  494. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  495. package/src/sharddev/bake/world.ts +173 -0
  496. package/src/sharddev/bake/worldCollision.ts +128 -0
  497. package/src/sharddev/bake/worldGeometry.ts +237 -0
  498. package/src/sharddev/bake/worldGlb.ts +123 -0
  499. package/src/sharddev/bake/worldImage.ts +12 -0
  500. package/src/sharddev/bake/worldLod.ts +128 -0
  501. package/src/sharddev/bake/worldRows.ts +102 -0
  502. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  503. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  504. package/src/sharddev/bake.ts +193 -0
  505. package/src/sharddev/bakePublication.ts +31 -0
  506. package/src/sharddev/behaviourSource.ts +94 -0
  507. package/src/sharddev/bin/wildshard.mjs +7 -0
  508. package/src/sharddev/blobBytes.ts +65 -0
  509. package/src/sharddev/blobs.ts +138 -0
  510. package/src/sharddev/bootInventory.ts +129 -0
  511. package/src/sharddev/bossProfiles.ts +18 -0
  512. package/src/sharddev/buildBehaviour.ts +77 -0
  513. package/src/sharddev/buildCacheMetrics.ts +17 -0
  514. package/src/sharddev/buildDecisionScripts.ts +122 -0
  515. package/src/sharddev/check.ts +118 -0
  516. package/src/sharddev/checkProject.ts +127 -0
  517. package/src/sharddev/cli.ts +200 -0
  518. package/src/sharddev/clientChannels.ts +169 -0
  519. package/src/sharddev/clientScripts.ts +10 -0
  520. package/src/sharddev/commons.ts +77 -0
  521. package/src/sharddev/commonsCosts.ts +11 -0
  522. package/src/sharddev/compileMovers.ts +11 -0
  523. package/src/sharddev/configBoundary.ts +6 -0
  524. package/src/sharddev/cookInput.ts +40 -0
  525. package/src/sharddev/crowds.ts +6 -0
  526. package/src/sharddev/decisionBindingMap.ts +11 -0
  527. package/src/sharddev/decisionScriptBindings.ts +117 -0
  528. package/src/sharddev/decisionScripts.ts +28 -0
  529. package/src/sharddev/decisionSource.ts +51 -0
  530. package/src/sharddev/dev.ts +113 -0
  531. package/src/sharddev/director.ts +26 -0
  532. package/src/sharddev/directorAbi.ts +77 -0
  533. package/src/sharddev/discoveryDocument.ts +97 -0
  534. package/src/sharddev/draft.ts +11 -0
  535. package/src/sharddev/eliteEntryRows.ts +29 -0
  536. package/src/sharddev/entries.ts +76 -0
  537. package/src/sharddev/entryReads.ts +73 -0
  538. package/src/sharddev/executeBundle.ts +55 -0
  539. package/src/sharddev/finds.ts +5 -0
  540. package/src/sharddev/formatJsonSchema.ts +3 -0
  541. package/src/sharddev/generationCache.ts +257 -0
  542. package/src/sharddev/generationRecipe.ts +94 -0
  543. package/src/sharddev/handwritten.ts +110 -0
  544. package/src/sharddev/immutable.ts +14 -0
  545. package/src/sharddev/interactions.ts +38 -0
  546. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  547. package/src/sharddev/kit/geometryPack.ts +110 -0
  548. package/src/sharddev/ledger.ts +13 -0
  549. package/src/sharddev/looks/tileField.ts +67 -0
  550. package/src/sharddev/materialGraphFiles.ts +57 -0
  551. package/src/sharddev/materials.ts +574 -0
  552. package/src/sharddev/measure.ts +18 -0
  553. package/src/sharddev/modes.ts +115 -0
  554. package/src/sharddev/moverPrograms.ts +213 -0
  555. package/src/sharddev/movers.ts +75 -0
  556. package/src/sharddev/nativePopulationRows.ts +46 -0
  557. package/src/sharddev/newProject.ts +226 -0
  558. package/src/sharddev/noise.ts +54 -0
  559. package/src/sharddev/outputProduct.ts +188 -0
  560. package/src/sharddev/outputRuntime.ts +66 -0
  561. package/src/sharddev/performancePolicy.ts +29 -0
  562. package/src/sharddev/phasedBoss.ts +34 -0
  563. package/src/sharddev/physics.ts +194 -0
  564. package/src/sharddev/platformSections.ts +42 -0
  565. package/src/sharddev/plumbing.ts +8 -0
  566. package/src/sharddev/productOutput.ts +128 -0
  567. package/src/sharddev/project.ts +337 -0
  568. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  569. package/src/sharddev/projectDecisions.ts +66 -0
  570. package/src/sharddev/projectEntryProof.ts +32 -0
  571. package/src/sharddev/projectGeneration.ts +219 -0
  572. package/src/sharddev/projectInputFiles.ts +47 -0
  573. package/src/sharddev/projectManifest.ts +108 -0
  574. package/src/sharddev/projectMap.ts +35 -0
  575. package/src/sharddev/projectOutput.ts +242 -0
  576. package/src/sharddev/projectPolicy.ts +17 -0
  577. package/src/sharddev/projectSections.ts +27 -0
  578. package/src/sharddev/questGraph.ts +25 -0
  579. package/src/sharddev/quests.ts +65 -0
  580. package/src/sharddev/random.ts +61 -0
  581. package/src/sharddev/refusals.ts +304 -0
  582. package/src/sharddev/reportCard.ts +13 -0
  583. package/src/sharddev/returnProjectionV2.ts +81 -0
  584. package/src/sharddev/rows.ts +192 -0
  585. package/src/sharddev/runtimeImports.ts +38 -0
  586. package/src/sharddev/runtimeMirrors.ts +39 -0
  587. package/src/sharddev/runtimePerformance.ts +38 -0
  588. package/src/sharddev/scene.ts +321 -0
  589. package/src/sharddev/sceneAnimation.ts +54 -0
  590. package/src/sharddev/sceneAudio.ts +64 -0
  591. package/src/sharddev/sceneDeclarations.ts +100 -0
  592. package/src/sharddev/sceneGraph.ts +139 -0
  593. package/src/sharddev/sceneTransform.ts +12 -0
  594. package/src/sharddev/schemaValidation.ts +61 -0
  595. package/src/sharddev/sections.ts +47 -0
  596. package/src/sharddev/shardSource.ts +59 -0
  597. package/src/sharddev/sourceReader.ts +26 -0
  598. package/src/sharddev/spawns.ts +38 -0
  599. package/src/sharddev/species/clips.ts +24 -0
  600. package/src/sharddev/species.ts +29 -0
  601. package/src/sharddev/speciesBrains.ts +19 -0
  602. package/src/sharddev/synth.ts +66 -0
  603. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  604. package/src/sharddev/test/compileSimV2.ts +21 -0
  605. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  606. package/src/sharddev/test/scriptScenario.ts +249 -0
  607. package/src/sharddev/test/scriptSource.ts +12 -0
  608. package/src/sharddev/version.ts +4 -0
  609. package/src/sharddev/weapons/bowProfile.ts +20 -0
  610. package/src/sharddev/weapons/firearmRows.ts +11 -0
  611. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  612. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  613. package/src/sharddev/worldScenes.ts +308 -0
  614. package/src/sharddev/worldSource.ts +82 -0
  615. package/src/shards/_template/README.md +78 -0
  616. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  617. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  618. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  619. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  620. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  621. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  622. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  623. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  624. package/src/shards/_template/behaviour/boss.as +39 -0
  625. package/src/shards/_template/behaviour/door.as +32 -0
  626. package/src/shards/_template/behaviour/hooks.json +129 -0
  627. package/src/shards/_template/behaviour/idle.as +75 -0
  628. package/src/shards/_template/behaviour/items.as +22 -0
  629. package/src/shards/_template/card/landscape.jpg +0 -0
  630. package/src/shards/_template/card/portrait.jpg +0 -0
  631. package/src/shards/_template/card/thumb.jpg +0 -0
  632. package/src/shards/_template/data/audio.json +45 -0
  633. package/src/shards/_template/data/bossDecision.json +83 -0
  634. package/src/shards/_template/data/budgets.json +70 -0
  635. package/src/shards/_template/data/card.json +281 -0
  636. package/src/shards/_template/data/clientScripts.json +987 -0
  637. package/src/shards/_template/data/creatures.json +65 -0
  638. package/src/shards/_template/data/director.json +39 -0
  639. package/src/shards/_template/data/encounters.json +96 -0
  640. package/src/shards/_template/data/items.json +172 -0
  641. package/src/shards/_template/data/layout.json +66 -0
  642. package/src/shards/_template/data/ledger.json +32 -0
  643. package/src/shards/_template/data/look.json +521 -0
  644. package/src/shards/_template/data/map.json +64 -0
  645. package/src/shards/_template/data/moves.json +16 -0
  646. package/src/shards/_template/data/placeholder.json +8 -0
  647. package/src/shards/_template/data/plumbing.json +32 -0
  648. package/src/shards/_template/data/quests.json +223 -0
  649. package/src/shards/_template/data/rows.json +423 -0
  650. package/src/shards/_template/data/skins.json +66 -0
  651. package/src/shards/_template/data/spawn.json +6 -0
  652. package/src/shards/_template/data/targets.json +150 -0
  653. package/src/shards/_template/data/text.json +12 -0
  654. package/src/shards/_template/data/ui.json +33 -0
  655. package/src/shards/_template/data/water.json +13 -0
  656. package/src/shards/_template/generators/behaviour.ts +34 -0
  657. package/src/shards/_template/generators/boss.ts +29 -0
  658. package/src/shards/_template/generators/buildOptions.ts +2 -0
  659. package/src/shards/_template/generators/cell.ts +224 -0
  660. package/src/shards/_template/generators/districts.ts +215 -0
  661. package/src/shards/_template/generators/farLook.ts +15 -0
  662. package/src/shards/_template/generators/generate.ts +27 -0
  663. package/src/shards/_template/generators/ground.ts +15 -0
  664. package/src/shards/_template/generators/kit.ts +69 -0
  665. package/src/shards/_template/generators/landscape.ts +59 -0
  666. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  667. package/src/shards/_template/generators/mapInputs.ts +10 -0
  668. package/src/shards/_template/generators/product.ts +100 -0
  669. package/src/shards/_template/generators/productOutput.ts +18 -0
  670. package/src/shards/_template/generators/props.ts +9 -0
  671. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  672. package/src/shards/_template/generators/terrain.ts +17 -0
  673. package/src/shards/_template/generators/world.ts +630 -0
  674. package/src/shards/_template/hero.json +10 -0
  675. package/src/shards/_template/look/entry-reads.json +20 -0
  676. package/src/shards/_template/manifest.json +281 -0
  677. package/src/shards/_template/shard.config.ts +10 -0
  678. package/src/shared/health.ts +10 -0
  679. package/src/tools/build-web.ts +59 -0
  680. package/src/tsconfig.json +30 -0
  681. package/src/web/app.tsx +53 -0
  682. package/src/web/index.html +12 -0
  683. package/src/web/main.tsx +10 -0
  684. package/src/web/tsconfig.json +13 -0
  685. package/tsconfig.author.json +23 -0
  686. package/tsconfig.commons.json +21 -0
  687. package/tsconfig.json +47 -0
  688. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,142 @@
1
+ import * as v from 'valibot';
2
+ import type { BakedTerrain } from './terrain';
3
+ import type { BakedProps } from './props';
4
+ import { decodeTerrainTile } from '@wildshard/format/terrainTileBytes';
5
+ import { MapRaster } from './mapRaster';
6
+ import { paintMapGeometry } from './mapScenes';
7
+ import { isleStyleSchema, stylizeIsle } from './isleMap';
8
+
9
+ const hexColour = v.pipe(v.string(), v.regex(/^#[a-fA-F0-9]{6}$/u));
10
+ const palette = v.pipe(v.array(v.object({ match: hexColour, fill: hexColour, edge: v.exactOptional(hexColour) })), v.minLength(1), v.maxLength(256));
11
+ const styleSchema = v.object({ kind: v.literal('ground'), classes: palette, sourceGain: v.optional(v.number(), 1), shade: v.optional(v.number(), .5),
12
+ void: v.optional(v.union([hexColour, v.literal('transparent')])), rim: v.exactOptional(hexColour),
13
+ water: v.exactOptional(v.object({ below: v.number(), fill: hexColour, within: v.exactOptional(v.object({ x0: v.number(), x1: v.number(), z0: v.number(), z1: v.number() })) })),
14
+ raised: v.exactOptional(v.object({ bump: v.number(), classes: palette })) });
15
+ type Style = v.InferOutput<typeof styleSchema>;
16
+ const voidStyleSchema = v.pipe(v.object({ kind: v.literal('void'),
17
+ void: v.optional(v.union([hexColour, v.literal('transparent')])),
18
+ stone: v.pipe(v.array(hexColour), v.minLength(1), v.maxLength(65)),
19
+ stoneBands: v.pipe(v.array(v.number()), v.maxLength(64)), grass: hexColour, rim: hexColour,
20
+ sourceGain: v.optional(v.number(), 1), shade: v.optional(v.number(), .5) }),
21
+ v.check(style => style.stone.length === style.stoneBands.length + 1, 'Void map bands need one more stone colour'));
22
+ const sceneStyleSchema = v.union([styleSchema, voidStyleSchema, isleStyleSchema]);
23
+ type Triple = readonly [number, number, number];
24
+ const byte = (value: number): number => Math.max(0, Math.min(255, Math.round(value)));
25
+ function item<T>(values: ArrayLike<T>, index: number): T { const value = values[index]; if (value === undefined) throw new Error('Incomplete map geometry'); return value; }
26
+ const triple = (values: ArrayLike<number>): Triple => [item(values, 0), item(values, 1), item(values, 2)];
27
+ const hex = (value: string): Triple => [Number.parseInt(value.slice(1, 3), 16), Number.parseInt(value.slice(3, 5), 16), Number.parseInt(value.slice(5, 7), 16)];
28
+
29
+ function stylize(raster: MapRaster, style: Style): Uint8Array {
30
+ const { size, height, colour } = raster, out = new Uint8Array(size * size * 4);
31
+ // CI6: a palette's nearest class for a byte colour, and a parsed hex colour, are pure: each is worked out once per map
32
+ // (the class search ran up to five times a pixel, each reparsing every class's hex) with the same first-nearest pick
33
+ const parsed = new Map<string, Triple>(), hexOf = (value: string): Triple => { let rgb = parsed.get(value); if (rgb === undefined) { rgb = hex(value); parsed.set(value, rgb); } return rgb; };
34
+ const picks = new Map<Style['classes'], Map<number, Style['classes'][number]>>();
35
+ const nearest = (rgb: Triple, rows: Style['classes']): Style['classes'][number] => {
36
+ let known = picks.get(rows); if (known === undefined) { known = new Map(); picks.set(rows, known); }
37
+ const key = item(rgb, 0) * 65536 + item(rgb, 1) * 256 + item(rgb, 2), seen = known.get(key); if (seen !== undefined) return seen;
38
+ const row = rows.reduce((best, candidate) => {
39
+ const match = hexOf(candidate.match), distance = match.reduce((sum, c, k) => sum + (c - item(rgb, k)) ** 2, 0);
40
+ return distance < best.distance ? { row: candidate, distance } : best;
41
+ }, { row: item(rows, 0), distance: Infinity }).row;
42
+ known.set(key, row); return row;
43
+ };
44
+ const valid = (at: number): boolean => at >= 0 && at < height.length && height[at] !== -2147483648;
45
+ const sourceColour = (at: number): Triple => triple(Array.from(colour.subarray(at * 3, at * 3 + 3), c => byte(c * style.sourceGain)));
46
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
47
+ const at = y * size + x, h = item(height, at) / 65536, rgb = sourceColour(at);
48
+ const neighbours = [x > 0 ? at - 1 : -1, x + 1 < size ? at + 1 : -1, y > 0 ? at - size : -1, y + 1 < size ? at + size : -1];
49
+ const border = neighbours.some(other => !valid(other));
50
+ if (!valid(at)) {
51
+ if (style.void !== 'transparent') { const bg = hexOf(style.void ?? item(style.classes, 0).fill); for (let k = 0; k < 3; k++) out[at * 4 + k] = item(bg, k); out[at * 4 + 3] = 255; }
52
+ continue;
53
+ }
54
+ const row = nearest(rgb, style.classes); let fill = hexOf(row.fill);
55
+ if (style.water !== undefined && h < style.water.below) {
56
+ const w = style.water.within, wx = 250 - (x + .5) * 500 / size, wz = 250 - (y + .5) * 500 / size;
57
+ if (w === undefined || wx >= w.x0 && wx <= w.x1 && wz >= w.z0 && wz <= w.z1) fill = hexOf(style.water.fill);
58
+ }
59
+ if (border && style.rim !== undefined) fill = hexOf(style.rim);
60
+ else if (row.edge !== undefined && neighbours.some(other => valid(other) && nearest(sourceColour(other), style.classes) !== row)) fill = hexOf(row.edge);
61
+ const raisedStyle = style.raised;
62
+ if (raisedStyle !== undefined) {
63
+ const around: number[] = [];
64
+ for (const dz of [-7, 0, 7]) for (const dx of [-7, 0, 7]) {
65
+ const px = x + dx, py = y + dz, other = py * size + px;
66
+ if (px >= 0 && px < size && py >= 0 && py < size && valid(other)) around.push(item(height, other));
67
+ }
68
+ around.sort((a, b) => a - b);
69
+ const ground = around[Math.floor(around.length / 2)] ?? item(height, at);
70
+ if (item(height, at) - ground > raisedStyle.bump * 65536) {
71
+ const raised = nearest(rgb, raisedStyle.classes), edge = raised.edge;
72
+ if (edge === undefined) throw new Error('Raised map palette needs edges');
73
+ fill = hexOf(neighbours.some(other => valid(other) && item(height, at) - item(height, other) > raisedStyle.bump * 32768) ? edge : raised.fill);
74
+ }
75
+ }
76
+ const left = valid(at - 1) && x > 0 ? item(height, at - 1) : item(height, at), top = valid(at - size) ? item(height, at - size) : item(height, at);
77
+ const relief = Math.max(-80, Math.min(80, Math.trunc((left + top - item(height, at) * 2) / 512))), shade = 256 + Math.trunc(relief * style.shade);
78
+ for (let k = 0; k < 3; k++) out[at * 4 + k] = byte(Math.trunc(item(fill, k) * shade / 256)); out[at * 4 + 3] = 255;
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** The retained void palette: classify actual colour/height, ink occupied edges and keep exact integer relief. */
84
+ function stylizeVoid(raster: MapRaster, style: v.InferOutput<typeof voidStyleSchema>): Uint8Array {
85
+ const { size, height, colour } = raster, out = new Uint8Array(size * size * 4);
86
+ const valid = (at: number): boolean => at >= 0 && at < height.length && height[at] !== -2147483648;
87
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
88
+ const at = y * size + x;
89
+ if (!valid(at)) {
90
+ if (style.void !== 'transparent') {
91
+ const bg = hex(style.void ?? '#282e33');
92
+ for (let k = 0; k < 3; k++) out[at * 4 + k] = item(bg, k);
93
+ out[at * 4 + 3] = 255;
94
+ }
95
+ continue;
96
+ }
97
+ const h = item(height, at), rgb = triple(Array.from(colour.subarray(at * 3, at * 3 + 3), c => byte(c * style.sourceGain)));
98
+ const neighbours = [x > 0 ? at - 1 : -1, x + 1 < size ? at + 1 : -1, y > 0 ? at - size : -1, y + 1 < size ? at + size : -1];
99
+ const band = style.stoneBands.filter(b => h / 65536 >= b).length;
100
+ const fill = hex(neighbours.some(other => !valid(other)) ? style.rim
101
+ : rgb[1] > rgb[0] && rgb[1] > rgb[2] * 1.15 ? style.grass : item(style.stone, band));
102
+ const left = valid(at - 1) && x > 0 ? item(height, at - 1) : h, top = valid(at - size) ? item(height, at - size) : h;
103
+ const relief = Math.max(-80, Math.min(80, Math.trunc((left + top - h * 2) / 512))), shade = 256 + Math.trunc(relief * style.shade);
104
+ for (let k = 0; k < 3; k++) out[at * 4 + k] = byte(Math.trunc(item(fill, k) * shade / 256));
105
+ out[at * 4 + 3] = 255;
106
+ }
107
+ return out;
108
+ }
109
+
110
+ /** Paint the existing 500 m, +Z north/-X east ground map from actual L0 terrain and placed GLB triangles.
111
+ * Returns RGBA8 bytes, not a file; the project writer supplies the normal lossless WebP and source identity. */
112
+ export async function rasterGroundMap(terrain: Pick<BakedTerrain, 'terrain' | 'assets'>, props: Pick<BakedProps, 'props' | 'assets'>, style: unknown, clip: { clipBelow?: number | null; clipAbove?: number | null } = {}): Promise<{ pixels: Uint8Array; triangles: number }> {
113
+ const admitted = v.parse(styleSchema, style), raster = new MapRaster(1000, { clipBelow: clip.clipBelow ?? -Infinity, clipAbove: clip.clipAbove ?? Infinity });
114
+ const read = (assets: ReadonlyMap<string, Uint8Array>, hash: string): Uint8Array => { const bytes = assets.get(hash); if (bytes === undefined) throw new Error('Missing map source geometry'); return bytes; };
115
+ for (const tile of terrain.terrain.tiles) if (tile.lod === 0) raster.terrain(decodeTerrainTile(read(terrain.assets, tile.file)));
116
+ for (const tile of props.props.tiles) if (tile.lod === 0) for (const hash of [tile.file, ...tile.additionalFiles ?? []]) await raster.glb(read(props.assets, hash));
117
+ for (const panel of props.props.panels) if (panel.visible) await raster.glb(read(props.assets, panel.file));
118
+ if (raster.triangles === 0) throw new Error('Data map is empty');
119
+ return { pixels: stylize(raster, admitted), triangles: raster.triangles };
120
+ }
121
+
122
+
123
+ /** Explicit owned geometry/JSON readers for a source program; no file or public-directory resolver is installed. */
124
+ export interface SceneMapBytes {
125
+ input: (file: string) => Uint8Array;
126
+ model?: (url: string) => Uint8Array;
127
+ json: (file: string) => unknown;
128
+ bytes: (file: string) => Uint8Array;
129
+ }
130
+ /** Paint declared L0 terrain, GLBs and private scenes with the existing ground, void or island palette.
131
+ * Returns the original 1000-square RGBA lattice from caller-owned inputs, without image/stamp publication.
132
+ * GR9: `output` paints one declared output of a multi-output folder from its own `glbs`, in its own row's `style` (else the
133
+ * folder's) leaving out its `exclude` node prefixes, as the script painter (`scripts/bake-data-maps.mjs`) did. */
134
+ export async function rasterSceneMap(settings: unknown, data: SceneMapBytes, options: { readonly output?: string; readonly glbs?: readonly string[] } = {}): Promise<{ pixels: Uint8Array; triangles: number }> {
135
+ const admitted = v.parse(v.object({ style: sceneStyleSchema, clipBelow: v.exactOptional(v.nullable(v.number())), clipAbove: v.exactOptional(v.nullable(v.number())),
136
+ outputs: v.exactOptional(v.record(v.string(), v.unknown())) }), settings);
137
+ const own = options.output === undefined ? undefined : admitted.outputs?.[options.output];
138
+ const style = typeof own === 'object' && own !== null && 'style' in own ? v.parse(sceneStyleSchema, own.style) : admitted.style;
139
+ const raster = new MapRaster(1000, { clipBelow: admitted.clipBelow ?? -Infinity, clipAbove: admitted.clipAbove ?? Infinity });
140
+ await paintMapGeometry(raster, settings, data, { ...(options.output === undefined ? {} : { output: options.output }), ...(options.glbs === undefined ? {} : { glbs: options.glbs }) });
141
+ return { pixels: style.kind === 'void' ? stylizeVoid(raster, style) : style.kind === 'isle' ? stylizeIsle(raster, style) : stylize(raster, style), triangles: raster.triangles };
142
+ }
@@ -0,0 +1,20 @@
1
+ import sharp from 'sharp';
2
+ import { worldImageInfo } from './worldImage';
3
+
4
+ /** Bounded, unpremultiplied RGBA raster in source row order; consumers explicitly choose any vertical flip. */
5
+ export interface ImagePixels { readonly width: number; readonly height: number; readonly pixels: Uint8ClampedArray }
6
+ /** Decode a still PNG/JPEG/WebP in Node with the SDK's pinned Sharp decoder, without a DOM or renderer. */
7
+ export async function readImagePixels(bytes: Uint8Array, options: { flipY?: boolean } = {}): Promise<ImagePixels> {
8
+ const info = await worldImageInfo(bytes);
9
+ const raster = sharp(bytes, { limitInputPixels: 4096 * 4096, animated: false, failOn: 'warning' });
10
+ if (options.flipY === true) raster.flip();
11
+ const decoded = await raster.ensureAlpha().raw({ depth: 'uchar' }).toBuffer({ resolveWithObject: true });
12
+ if (decoded.info.width !== info.width || decoded.info.height !== info.height || decoded.info.channels !== 4 || decoded.data.length !== info.width * info.height * 4) throw new Error('Decoded raster differs from admitted dimensions');
13
+ return { width: info.width, height: info.height, pixels: new Uint8ClampedArray(decoded.data) };
14
+ }
15
+ /** Encode exactly the supplied bounded RGBA raster as a deterministic lossless PNG at build time. */
16
+ export async function writeImagePixels(image: ImagePixels): Promise<Uint8Array> {
17
+ const { width, height, pixels } = image;
18
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > 4096 || height > 4096 || pixels.length !== width * height * 4) throw new Error('Invalid bounded RGBA raster');
19
+ return new Uint8Array(await sharp(pixels, { raw: { width, height, channels: 4 } }).png().toBuffer());
20
+ }
@@ -0,0 +1,64 @@
1
+ import * as v from 'valibot';
2
+ import type { MapRaster } from './mapRaster';
3
+
4
+ // GR7: the island palette of the retired script painter (scripts/map-painter.mjs, `kind: 'isle'`), so a source program
5
+ // paints Driftwood's map through `rasterSceneMap` with the same integer arithmetic and the same pixels.
6
+ const hexColour = v.pipe(v.string(), v.regex(/^#[a-fA-F0-9]{6}$/u));
7
+ /** The island palette: sea, shallows and grass bands by height, then sand, paths, rock, crowns and decks read from the
8
+ * source colours (hex `#rrggbb`; heights in metres). */
9
+ export interface IsleStyle {
10
+ readonly kind: 'isle'; readonly void?: string; readonly deepBelow: number; readonly waterBelow: number; readonly pathAbove: number;
11
+ readonly sea: string; readonly shallow: string; readonly grass: string[]; readonly grassBands: number[]; readonly sand?: string;
12
+ readonly path: string; readonly rock: string; readonly crown: string; readonly deck: string; readonly sourceGain: number; readonly shade: number;
13
+ }
14
+ /** The island palette's admission. */
15
+ export const isleStyleSchema: v.GenericSchema<unknown, IsleStyle> = v.object({ kind: v.literal('isle'), void: v.exactOptional(v.union([hexColour, v.literal('transparent')])),
16
+ deepBelow: v.number(), waterBelow: v.number(), pathAbove: v.number(), sea: hexColour, shallow: hexColour,
17
+ grass: v.pipe(v.array(hexColour), v.minLength(1), v.maxLength(65)), grassBands: v.pipe(v.array(v.number()), v.maxLength(64)),
18
+ sand: v.exactOptional(hexColour), path: hexColour, rock: hexColour, crown: hexColour, deck: hexColour,
19
+ sourceGain: v.optional(v.number(), 1), shade: v.optional(v.number(), .5) });
20
+
21
+ const byte = (value: number): number => Math.max(0, Math.min(255, Math.round(value)));
22
+ function item<T>(values: ArrayLike<T>, index: number): T { const value = values[index]; if (value === undefined) throw new Error('Incomplete map geometry'); return value; }
23
+ const hex = (value: string): readonly [number, number, number] =>
24
+ [Number.parseInt(value.slice(1, 3), 16), Number.parseInt(value.slice(3, 5), 16), Number.parseInt(value.slice(5, 7), 16)];
25
+
26
+ /** The island palette over a painted raster: RGBA8, exact integer relief. Classification never changes occupied coverage. */
27
+ export function stylizeIsle(raster: Pick<MapRaster, 'size' | 'height' | 'colour'>, style: IsleStyle): Uint8Array {
28
+ const { size, height, colour } = raster, out = new Uint8Array(size * size * 4);
29
+ const valid = (at: number): boolean => at >= 0 && at < height.length && height[at] !== -2147483648;
30
+ const level = (at: number): number => item(height, at) / 65536;
31
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
32
+ const at = y * size + x;
33
+ if (!valid(at)) {
34
+ if (style.void !== 'transparent') { const bg = hex(style.void ?? style.sea); for (let k = 0; k < 3; k++) out[at * 4 + k] = item(bg, k); out[at * 4 + 3] = 255; }
35
+ continue;
36
+ }
37
+ const h = level(at), rgb = Array.from(colour.subarray(at * 3, at * 3 + 3), c => byte(c * style.sourceGain));
38
+ const neighbours = [x > 0 ? at - 1 : -1, x + 1 < size ? at + 1 : -1, y > 0 ? at - size : -1, y + 1 < size ? at + size : -1];
39
+ let fill = hex(h < style.deepBelow ? style.sea : h < style.waterBelow ? style.shallow : item(style.grass, style.grassBands.filter(b => h >= b).length));
40
+ // the island's authored sand, paths, timber and crowns stay readable from the source vertex colours
41
+ if (style.sand !== undefined && h >= style.waterBelow) {
42
+ const r = item(rgb, 0) / 255, g = item(rgb, 1) / 255, b = item(rgb, 2) / 255;
43
+ const saturation = (Math.max(r, g, b) - Math.min(r, g, b)) / Math.max(r, g, b, .001);
44
+ const green = g > r * 1.05 && g > b * 1.1, sand = r > .55 && g > .45 && b < g * .85 && !green;
45
+ const wood = r > g * 1.12 && r > .25 && r < .75 && saturation > .3 && !green;
46
+ const heights = neighbours.filter(valid).map(level), slope = Math.max(0, ...heights.map(value => Math.abs(h - value))) * size / 500;
47
+ let low = h;
48
+ for (const dz of [-7, 0, 7]) for (const dx of [-7, 0, 7]) {
49
+ const px = x + dx, py = y + dz, other = py * size + px;
50
+ if (px >= 0 && px < size && py >= 0 && py < size && valid(other)) low = Math.min(low, level(other));
51
+ }
52
+ const raised = h - low;
53
+ if (sand) fill = hex(h > style.pathAbove ? style.path : style.sand);
54
+ else if (!green && (saturation < .28 || slope > 1.4)) fill = hex(style.rock);
55
+ if (green && raised > 1.5) fill = hex(style.crown);
56
+ if (wood || !green && low < -.5 && raised > .4) fill = hex(style.deck);
57
+ }
58
+ const left = valid(at - 1) && x > 0 ? item(height, at - 1) : item(height, at), top = valid(at - size) ? item(height, at - size) : item(height, at);
59
+ const relief = Math.max(-80, Math.min(80, Math.trunc((left + top - item(height, at) * 2) / 512))), shade = 256 + Math.trunc(relief * style.shade);
60
+ for (let k = 0; k < 3; k++) out[at * 4 + k] = byte(Math.trunc(item(fill, k) * shade / 256));
61
+ out[at * 4 + 3] = 255;
62
+ }
63
+ return out;
64
+ }
@@ -0,0 +1,84 @@
1
+ // Emit one retained authoring function's JSON or explicit byte product. I/O belongs to this Node driver.
2
+ // node --import ./src/sharddev/bake/source-loader.mjs src/sharddev/bake/json.mjs <entry> <exported-function> <output>
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Only the build driver writes the generated JSON output.
4
+ import { lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- Source and output paths must stay in the isolated tree.
6
+ import { dirname, isAbsolute, resolve, sep } from 'node:path';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- Import the explicitly named retained authoring recipe.
8
+ import { pathToFileURL } from 'node:url';
9
+ // oxlint-disable-next-line import/no-nodejs-modules -- This executable reads its explicit producer arguments.
10
+ import process from 'node:process';
11
+ import { assertJsonRows, jsonOutputGuard } from '@wildshard/engine/scripts/json-output-guard.mjs';
12
+
13
+ const args = process.argv.slice(2);
14
+ const entry = args.at(0), binding = args.at(1), output = args.at(2);
15
+ const binary = args.length === 4 && args.at(3) === '--bytes';
16
+ const multiple = args.length === 4 && args.at(3) === '--files';
17
+ if ((!binary && !multiple && args.length !== 3) || entry === undefined || binding === undefined || output === undefined) throw new Error('generate-json: entry, function and output required');
18
+ const root = process.cwd(), guard = jsonOutputGuard(root), sourceOwner = entry.split('/').at(2);
19
+ /** Restrict source and destination to explicit regular paths in the isolated generation tree. @param {string} path */
20
+ function confined(path) {
21
+ if (isAbsolute(path) || path.includes('\\') || path.split('/').some(part => part === '' || part === '.' || part === '..')) throw new Error('generate-json: path must stay inside the generation tree');
22
+ const parts = path.split('/');
23
+ for (let length = 1; length <= parts.length; length++) {
24
+ const prefix = resolve(root, ...parts.slice(0, length));
25
+ try {
26
+ // Canonical existing prefixes need only exact path probes, not ancestor
27
+ // metadata reads that look like recursive content scans to the recorder.
28
+ if (realpathSync.native(prefix) !== prefix) throw new Error('generate-json: symlink refused');
29
+ } catch (error) {
30
+ // A dangling or looping link cannot canonicalize. Retain the original
31
+ // lstat refusal before accepting any missing output path.
32
+ try { if (lstatSync(prefix).isSymbolicLink()) throw new Error('generate-json: symlink refused', { cause: error }); }
33
+ catch (statError) { if (!(statError instanceof Error && 'code' in statError && statError.code === 'ENOENT')) throw statError; }
34
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;
35
+ }
36
+ }
37
+ const target = resolve(root, path);
38
+ if (!target.startsWith(root + sep)) throw new Error('generate-json: escaping path refused');
39
+ return target;
40
+ }
41
+ const source = confined(entry), destination = confined(output);
42
+ /** @type {unknown} */
43
+ const author = await import(pathToFileURL(source).href);
44
+ if (author === null || typeof author !== 'object' || !(binding in author)) throw new Error('generate-json: named authoring function required');
45
+ const generate = Reflect.get(author, binding);
46
+ if (typeof generate !== 'function') throw new Error('generate-json: named authoring function required');
47
+ /** Byte recipes receive only a confined, read-only asset reader. @param {string} url */
48
+ function readAsset(url) {
49
+ if (typeof url !== 'string' || !url.startsWith('/assets/')) throw new Error('generate-json: asset URL required');
50
+ return new Uint8Array(readFileSync(confined(`public${url}`)));
51
+ }
52
+ /** An author-only file recipe reads only its own explicit authored files, never trusted runtime or another shard.
53
+ * @param {string} path */
54
+ function readSource(path) {
55
+ const owner = sourceOwner, parts = typeof path === 'string' ? path.split('/') : [];
56
+ if (owner === undefined || parts.at(0) !== 'src' || parts.at(1) !== 'shards' || parts.at(2) !== owner || !['generators', 'data', 'assets', 'quests', 'behaviour', 'blender'].includes(parts.at(3) ?? '')) throw new Error('generate-json: own authored input required');
57
+ return new Uint8Array(readFileSync(confined(path)));
58
+ }
59
+ /** @type {unknown} */
60
+ const value = binary ? await generate(readAsset) : multiple ? await generate(readSource) : await generate();
61
+ if (multiple) {
62
+ const owner = entry.split('/').at(2), project = `src/shards/${owner}`;
63
+ if (owner === undefined || !entry.startsWith(`${project}/generators/`) || output !== project || !(value instanceof Map) || value.size === 0 || value.size > 512) throw new Error('generate-json: bounded own-project file map required');
64
+ /** @type {[string, Uint8Array][]} */
65
+ const files = [];
66
+ // Admit every path and byte value before writing any output.
67
+ for (const item of value.entries()) {
68
+ /** @type {unknown} */
69
+ const name = item[0], bytes = item[1];
70
+ if (typeof name !== 'string' || !(bytes instanceof Uint8Array) || bytes.length > 25_000_000) throw new Error('generate-json: relative byte outputs required');
71
+ const path = confined(`${output}/${name}`); guard(path, bytes); files.push([path, bytes]);
72
+ }
73
+ for (const [path, bytes] of files) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, bytes); }
74
+ } else if (binary) {
75
+ if (!(value instanceof Uint8Array)) throw new Error('generate-json: byte recipe must return Uint8Array');
76
+ guard(destination, value);
77
+ mkdirSync(dirname(destination), { recursive: true }); writeFileSync(destination, value);
78
+ } else {
79
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') throw new Error('generate-json: authoring function returned no JSON data');
80
+ assertJsonRows(value, output);
81
+ const bytes = JSON.stringify(value); guard(destination, bytes);
82
+ mkdirSync(dirname(destination), { recursive: true });
83
+ writeFileSync(destination, `${bytes}\n`);
84
+ }
@@ -0,0 +1,47 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Preserve the native build-only gzip byte contract.
2
+ import { gzipSync } from 'node:zlib';
3
+ import { DataUtils } from 'three';
4
+
5
+ /** Keep the shipped gzip OS marker stable across Darwin and Linux producers: the level-9 gzip of a sky's planes, the same
6
+ * bytes for the same input, zlib and Node. The build's memo of it is `ProjectGenerationContext.encodeGainKey`. */
7
+ export function encodeGainKey(data: Uint16Array): Uint8Array {
8
+ const bytes = gzipSync(new Uint8Array(data.buffer, data.byteOffset, data.byteLength), { level: 9 });
9
+ bytes[9] = 19;
10
+ return bytes;
11
+ }
12
+
13
+ /** Pack display colour/gain planes into owned RGB half texels with the original unrounded horizon means. */
14
+ export function packGainKey(color: Uint8Array, gain: Uint8Array, width: number, height: number): { data: Uint16Array<ArrayBuffer>; horizon: number[] } {
15
+ if (color.length !== width * height * 4 || gain.length !== color.length) throw new Error('Sky plane sizes differ');
16
+ const lin = new Float32Array(256), lut = new Uint16Array(65536);
17
+ const f32 = new Float32Array(1), u32 = new Uint32Array(f32.buffer);
18
+ const half = (value: number): number => {
19
+ f32[0] = value; const x = u32[0];
20
+ if (x === undefined) throw new Error('Missing half-float word');
21
+ const e = ((x >>> 23) & 255) - 112, m = x & 0x7fffff;
22
+ if (e >= 31) return 0x7bff;
23
+ if (e <= 0) return e < -10 ? 0 : ((((m | 0x800000) >>> (1 - e)) + 0x1000) >>> 13);
24
+ return (e << 10) + ((m + 0x1000) >>> 13);
25
+ };
26
+ for (let c = 0; c < 256; c++) { const s = c / 255; lin[c] = s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }
27
+ for (let g = 0; g < 256; g++) for (let c = 0; c < 256; c++) {
28
+ const linear = lin[c]; if (linear === undefined) throw new Error('Missing linear colour');
29
+ lut[g * 256 + c] = half(Math.min(65504, linear * 2 ** (g / 255 * 16)));
30
+ }
31
+ const data = new Uint16Array(width * height * 3), horizon = [0, 0, 0], row = Math.floor(height * 0.47);
32
+ for (let p = 0; p < width * height; p++) {
33
+ const i = p * 4, gainByte = gain[i];
34
+ if (gainByte === undefined) throw new Error('Missing gain texel');
35
+ const at = gainByte * 256;
36
+ for (let c = 0; c < 3; c++) {
37
+ const colorByte = color[i + c]; if (colorByte === undefined) throw new Error('Missing colour texel');
38
+ const value = lut[at + colorByte]; if (value === undefined) throw new Error('Missing gain lookup');
39
+ data[p * 3 + c] = value;
40
+ if (Math.floor(p / width) === row && p % width % 4 === 0) {
41
+ const sum = horizon[c]; if (sum === undefined) throw new Error('Missing horizon channel');
42
+ horizon[c] = sum + DataUtils.fromHalfFloat(value);
43
+ }
44
+ }
45
+ }
46
+ return { data, horizon: horizon.map(c => c / Math.ceil(width / 4)) };
47
+ }
@@ -0,0 +1,39 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- The build-only memo keys the exact transform by content.
2
+ import { createHash, randomBytes } from 'node:crypto';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- The memo lives in the CI-cached gen root, outside the product.
4
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- The default memo root is the user's cache folder.
6
+ import { homedir } from 'node:os';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- Memo paths are joined, never read from input.
8
+ import { resolve } from 'node:path';
9
+ import { encodeGainKey } from './keyedSky';
10
+
11
+ const sha = (bytes: string | Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
12
+ // CI6: the gzip is most of a keyed sky's bake (1.4 s of Pine's product worker, on its critical path) and its input is the
13
+ // sky art, which rarely changes. Every byte the transform depends on is in the key; a hit re-hashes its body. The memo is a
14
+ // build capability (ProjectGenerationContext.encodeGainKey): a shard.config.ts bundle never reaches file access itself.
15
+ const codec = sha(JSON.stringify({ schema: 'gain-key-gzip/1', node: process.version, zlib: process.versions.zlib, platform: process.platform,
16
+ arch: process.arch, level: 9, implementation: encodeGainKey.toString() }));
17
+
18
+ /** `encodeGainKey` with an exact memo in the gen cache: the same bytes for the same planes; a missing, corrupt or
19
+ * unwritable memo runs the gzip. */
20
+ export function encodeGainKeyMemo(data: Uint16Array): Uint8Array {
21
+ const memoRoot = process.env['WILDSHARD_GAIN_KEY_CACHE'] ?? resolve(homedir(), '.cache/wildshard/gen/gain-key/1');
22
+ const input = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
23
+ const key = sha(`${codec}\0${input.byteLength}\0${sha(input)}`), body = resolve(memoRoot, `${key}.bin`), meta = resolve(memoRoot, `${key}.json`);
24
+ try {
25
+ const saved: unknown = JSON.parse(readFileSync(meta, 'utf8'));
26
+ if (typeof saved === 'object' && saved !== null && 'key' in saved && saved.key === key && 'hash' in saved && typeof saved.hash === 'string') {
27
+ const bytes = readFileSync(body);
28
+ if (sha(bytes) === saved.hash) return new Uint8Array(bytes);
29
+ }
30
+ } catch { /* no memo yet, or a damaged one: compute */ }
31
+ const bytes = encodeGainKey(data), suffix = `.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
32
+ try {
33
+ mkdirSync(memoRoot, { recursive: true });
34
+ writeFileSync(body + suffix, bytes, { flag: 'wx' }); renameSync(body + suffix, body);
35
+ writeFileSync(meta + suffix, JSON.stringify({ key, hash: sha(bytes) }), { flag: 'wx' }); renameSync(meta + suffix, meta);
36
+ } catch { /* the memo is optional: storage never changes the build */ }
37
+ finally { for (const file of [body + suffix, meta + suffix]) try { rmSync(file, { force: true }); } catch { /* own temporaries only */ } }
38
+ return bytes;
39
+ }
@@ -0,0 +1,137 @@
1
+ import { Color, BoxGeometry, BufferAttribute, BufferGeometry, DoubleSide, InstancedMesh, Matrix4, Material, NormalBlending, LessEqualDepth, Mesh, MeshBasicMaterial, MeshStandardMaterial, type Object3D } from 'three';
2
+ import { staticGlb, type GlbPrimitive } from './glb';
3
+ import { tileGridTransform, type TileGrid } from './worldGeometry';
4
+
5
+ /**
6
+ * Build-time only (SHARD-PLATFORM SF72): a code-built world piece baked as instanced kinds. Each non-empty kind is one GLB
7
+ * node (its geometry and EXT_mesh_gpu_instancing transforms, one draw each, never multi-draw); its row says how the client
8
+ * draws it (`@wildshard/engine/game/shardfile/bakedKinds`). The colliders are the builder's own, as JSON keeps them (a `-0` yaw is
9
+ * `0`, as the rows' JSON holds it). Promoted from Signal Dunes' baker; any shard's generators use it.
10
+ */
11
+
12
+ /** A kind row's extra fields: plain JSON a shard's client reads back (a lit-by-fire flag, a named client material). */
13
+ export type KindExtra = Readonly<Record<string, string | number | boolean>>;
14
+ /** One baked instanced kind: the GLB node's name, its instance count and the material the client draws it in. */
15
+ export interface BakedKind {
16
+ name: string; count: number; color: number; roughness: number; metalness: number; flat: boolean; emissive: number; emissiveIntensity: number;
17
+ vertexColors: boolean; doubleSided: boolean;
18
+ readonly [extra: string]: string | number | boolean;
19
+ }
20
+ /** A collider row as a piece declares it (the physics registry's descriptor shape); the bake keeps it as given. */
21
+ export interface KindCollider { readonly kind: string; readonly yaw?: number }
22
+ /** A piece's bake: the GLB bytes and its rows (`data/<piece>.json`, with the GLB's content hash). */
23
+ export interface PieceBake<C extends KindCollider = KindCollider> { glb: Uint8Array; kinds: BakedKind[]; colliders: C[] }
24
+
25
+ /** Optional immutable row metadata and custom vertex channels retained by the kind baker. */
26
+ export interface KindBakeOptions {
27
+ /** Original typed channels in application accessors (see staticGlb); omitted preserves old bytes. */
28
+ nativeAttributes?: true;
29
+ /** Preserve float32 instance matrices and colours without a TRS round trip. */
30
+ exactInstances?: true;
31
+ /** Keep the original index type, including non-indexed shapes; omitted preserves old bytes. */
32
+ compactIndex?: true;
33
+ /** Plain application rows on each GLB node (source ordinals for exact library reconstruction). */
34
+ nodeExtras?: (kind: string, mesh: InstancedMesh) => GlbPrimitive['extras'];
35
+ /** The extra row fields a kind's material carries (a shard's own flags); equal extras are part of a kind's look. */
36
+ extra?: (material: MeshStandardMaterial) => KindExtra;
37
+ /** Custom vertex channels to keep, glTF semantic → geometry channel (`{ _SHK: 'shk' }`); a kind without the channel skips it. */
38
+ attributes?: Readonly<Record<string, string>>;
39
+ /** I3: a one-instance kind whose positions are already unnormalized Int16 on this grid (`gridPositions`): its node
40
+ * carries the instance times the grid's dequantizing transform and records the instance as its exact pose. */
41
+ grid?: (kind: string, mesh: InstancedMesh) => TileGrid | undefined;
42
+ }
43
+
44
+ /** Colliders as the JSON rows keep them (a `-0` yaw is `0`). */
45
+ export const colliderRows = <C extends KindCollider>(colliders: readonly C[]): C[] => colliders.map((c) => c.yaw === 0 ? { ...c, yaw: 0 } : c);
46
+
47
+ const isInstancedMesh = (mesh: Mesh): mesh is InstancedMesh => mesh instanceof InstancedMesh;
48
+
49
+ const custom = (geometry: BufferGeometry, attributes: Readonly<Record<string, string>> | undefined): Record<string, string> | undefined => {
50
+ const kept = Object.entries(attributes ?? {}).filter(([, channel]) => geometry.hasAttribute(channel));
51
+ return kept.length === 0 ? undefined : Object.fromEntries(kept);
52
+ };
53
+
54
+ /** Bake named ordinary or instanced meshes into one GLB (`name` is its scene name, e.g. `sunscar.rocks`) and their kind rows. */
55
+ export function bakeKinds<C extends KindCollider>(name: string, meshes: readonly (readonly [string, Mesh])[], colliders: readonly C[], options: KindBakeOptions = {}): PieceBake<C> {
56
+ const kinds: BakedKind[] = [], primitives: GlbPrimitive[] = [];
57
+ for (const [kind, mesh] of meshes) {
58
+ const instanced = isInstancedMesh(mesh), count = instanced ? mesh.count : 1;
59
+ if (count === 0) continue;
60
+ // The legacy byte path rejects tint; exact mode preserves the instance colour buffer.
61
+ if (instanced && mesh.instanceColor !== null && options.exactInstances !== true) throw new Error(`${name}.${kind}: per-instance colours are not baked`);
62
+ const instances = instanced ? Array.from({ length: count }, (_, i) => { const m = new Matrix4(); mesh.getMatrixAt(i, m); return m; }) : undefined;
63
+ const instanceColours = instanced && options.exactInstances === true && mesh.instanceColor !== null ? Array.from({ length: count }, (_, i) => { const colour = new Color(); mesh.getColorAt(i, colour); return colour; }) : undefined;
64
+ const material = Array.isArray(mesh.material) ? undefined : mesh.material;
65
+ if (!(material instanceof MeshStandardMaterial) && !(material instanceof MeshBasicMaterial)) throw new Error(`${name}.${kind}: one standard or basic material per kind`);
66
+ const nativeAttributes = instanced ? options.nativeAttributes : true, compactIndex = instanced ? options.compactIndex : true;
67
+ if (material instanceof MeshBasicMaterial && instanced) throw new Error(`${name}.${kind}: unlit kinds require ordinary meshes`);
68
+ if (!instanced && (material.transparent || material.opacity !== 1 || material.alphaTest !== 0 || material.wireframe || !material.depthTest || !material.depthWrite || !material.toneMapped || !material.fog)) throw new Error(`${name}.${kind}: unsupported ordinary material state`);
69
+ if (!instanced) {
70
+ if (mesh.type !== 'Mesh' || !mesh.visible || mesh.castShadow || mesh.receiveShadow || mesh.renderOrder !== 0 || mesh.layers.mask !== 1 || mesh.animations.length > 0 || Object.keys(mesh.geometry.morphAttributes).length > 0 || mesh.geometry.drawRange.start !== 0 || mesh.geometry.drawRange.count !== Infinity) throw new Error(`${name}.${kind}: unsupported ordinary mesh state`);
71
+ if (!['MeshStandardMaterial', 'MeshBasicMaterial'].includes(material.type) || !material.colorWrite || material.blending !== NormalBlending || material.depthFunc !== LessEqualDepth || material.alphaHash || material.alphaToCoverage || material.premultipliedAlpha || material.dithering || material.polygonOffset || material.stencilWrite || material.clippingPlanes !== null || material.precision !== null || material.side !== 0 && material.side !== DoubleSide) throw new Error(`${name}.${kind}: unsupported ordinary material state`);
72
+ if (material.onBeforeCompile !== Material.prototype.onBeforeCompile) throw new Error(`${name}.${kind}: material callbacks are runtime code`);
73
+ for (const [channel, attribute] of Object.entries(mesh.geometry.attributes)) {
74
+ if (!['position', 'normal', 'color', 'uv', 'tangent'].includes(channel) || !(attribute instanceof BufferAttribute) || !(attribute.array instanceof Float32Array) || attribute.normalized) throw new Error(`${name}.${kind}: ordinary kinds require portable float32 channels`);
75
+ }
76
+ if (material.aoMap !== null || material.lightMap !== null || material.envMap !== null || (material instanceof MeshBasicMaterial && material.specularMap !== null)
77
+ || (material instanceof MeshStandardMaterial && (material.emissiveMap !== null || material.bumpMap !== null || material.displacementMap !== null))) throw new Error(`${name}.${kind}: textures must be external KTX2 declarations`);
78
+ }
79
+ mesh.updateWorldMatrix(true, false);
80
+ const explicit = custom(mesh.geometry, options.attributes);
81
+ const automatic = nativeAttributes === true ? Object.fromEntries(Object.keys(mesh.geometry.attributes)
82
+ .filter(key => !['position', 'normal', 'color', 'uv', 'tangent'].includes(key) && !Object.values(explicit ?? {}).includes(key))
83
+ .map((key, index) => [`_WS_CHANNEL_${index}`, key])) : undefined;
84
+ const customAttributes = automatic === undefined ? explicit : { ...automatic, ...explicit };
85
+ const extras = instanced ? options.nodeExtras?.(kind, mesh) : undefined;
86
+ const grid = instanced ? options.grid?.(kind, mesh) : undefined;
87
+ if (grid !== undefined && (instances?.length !== 1 || instances[0] === undefined || instanceColours !== undefined)) throw new Error(`${name}.${kind}: a gridded kind has exactly one instance`);
88
+ const placement = grid === undefined || instances?.[0] === undefined ? (instances === undefined ? { transform: mesh.matrixWorld } : { instances })
89
+ : { transform: instances[0].clone().multiply(tileGridTransform(grid)), pose: instances[0], meshoptReady: true as const, quantizedChannels: true as const, nativeOnce: true as const };
90
+ primitives.push({ geometry: mesh.geometry, material, ...placement, castShadow: false,
91
+ ...(!instanced || grid !== undefined || options.exactInstances === undefined ? {} : { exactInstances: options.exactInstances }),
92
+ ...(instanceColours === undefined ? {} : { instanceColours }),
93
+ ...(nativeAttributes === undefined ? {} : { nativeAttributes }),
94
+ ...(compactIndex === undefined ? {} : { compactIndex }),
95
+ ...(extras === undefined ? {} : { extras }),
96
+ ...(customAttributes === undefined ? {} : { customAttributes }) });
97
+ kinds.push({ name: kind, count, color: material.color.getHex(), roughness: material instanceof MeshStandardMaterial ? material.roughness : 1, metalness: material instanceof MeshStandardMaterial ? material.metalness : 0, flat: material instanceof MeshStandardMaterial && material.flatShading,
98
+ emissive: material instanceof MeshStandardMaterial ? material.emissive.getHex() : 0, emissiveIntensity: material instanceof MeshStandardMaterial ? material.emissiveIntensity : 1, vertexColors: material.vertexColors, doubleSided: material.side === DoubleSide,
99
+ ...(material instanceof MeshStandardMaterial ? options.extra?.(material) : {}),
100
+ ...(instanced ? {} : { mesh: true, colorR: material.color.r, colorG: material.color.g, colorB: material.color.b,
101
+ ...(material instanceof MeshStandardMaterial ? { emissiveR: material.emissive.r, emissiveG: material.emissive.g, emissiveB: material.emissive.b } : {}) }),
102
+ ...(material instanceof MeshBasicMaterial ? { unlit: true } : {}) });
103
+ }
104
+ return { glb: staticGlb(primitives, name), kinds, colliders: colliderRows(colliders) };
105
+ }
106
+
107
+ /** A material's look as the kind rows keep it: meshes in equal-looking materials share a kind. */
108
+ const look = (m: MeshStandardMaterial, extra: KindBakeOptions['extra']): string => JSON.stringify([m.color.getHex(), m.roughness, m.metalness, m.flatShading, m.emissive.getHex(),
109
+ m.emissiveIntensity, m.vertexColors, m.side, extra?.(m) ?? {}]);
110
+ /** A geometry's shape: a box is the unit box (its size goes in the instance's scale); a parametric one by its parameters. */
111
+ const shape = (g: BufferGeometry): string => g instanceof BoxGeometry ? 'box' : 'parameters' in g ? `${g.type}${JSON.stringify(g.parameters)}` : g.uuid;
112
+
113
+ const isGeometry = (g: unknown): g is BufferGeometry => g instanceof BufferGeometry;
114
+
115
+ /**
116
+ * A built group's meshes folded into instanced kinds, in first-seen order: every box of one look becomes an instance of
117
+ * one unit box (its size in the instance's scale, the same vertices); any other geometry is one kind per shape and look.
118
+ * Every instance keeps its mesh's world transform. Kinds are named `<n>-<geometry type>`.
119
+ */
120
+ export function foldKinds(root: Object3D, options: Pick<KindBakeOptions, 'extra'> = {}): (readonly [string, InstancedMesh])[] {
121
+ root.updateMatrixWorld(true);
122
+ const unit = new BoxGeometry(1, 1, 1), groups = new Map<string, { geometry: BufferGeometry; material: MeshStandardMaterial; matrices: Matrix4[] }>();
123
+ root.traverse((node) => {
124
+ if (!(node instanceof Mesh)) return;
125
+ const material: unknown = node.material, geometry: unknown = node.geometry;
126
+ if (!(material instanceof MeshStandardMaterial) || !isGeometry(geometry)) throw new Error('fold: one standard material per mesh');
127
+ const key = `${shape(geometry)}|${look(material, options.extra)}`, matrix = node.matrixWorld.clone();
128
+ if (geometry instanceof BoxGeometry) matrix.multiply(new Matrix4().makeScale(geometry.parameters.width, geometry.parameters.height, geometry.parameters.depth));
129
+ const group = groups.get(key) ?? { geometry: geometry instanceof BoxGeometry ? unit : geometry, material, matrices: [] };
130
+ group.matrices.push(matrix); groups.set(key, group);
131
+ });
132
+ return [...groups.values()].map((group, n) => {
133
+ const mesh = new InstancedMesh(group.geometry, group.material, group.matrices.length);
134
+ group.matrices.forEach((m, i) => { mesh.setMatrixAt(i, m); });
135
+ return [`${String(n)}-${group.geometry.type}`, mesh] as const;
136
+ });
137
+ }
@@ -0,0 +1,31 @@
1
+ import { Color, Vector3 } from 'three';
2
+ import { array, check, maxLength, parse, pipe } from 'valibot';
3
+ import { LightPoolRowSchema } from '@wildshard/format/lightEmitters';
4
+
5
+ /** Ordered numeric author input for a static irradiance bake; colours are already linear. */
6
+ export interface AuthoredLightEmitter {
7
+ id: string;
8
+ at: [number, number, number];
9
+ colour: [number, number, number];
10
+ gain: number;
11
+ radius: number;
12
+ cut: number;
13
+ initially?: boolean;
14
+ }
15
+
16
+ /** A detached light source, without a renderer uniform or mutable emitter host. */
17
+ export interface BakedLightSource {
18
+ at: Vector3;
19
+ color: Color;
20
+ k: number;
21
+ r: number;
22
+ cut: number;
23
+ }
24
+
25
+ /** Admit the original bounded pool contract and materialise its initial sources in authored order. */
26
+ export function bakeLightSources(input: readonly AuthoredLightEmitter[]): BakedLightSource[] {
27
+ const rows = parse(pipe(array(LightPoolRowSchema), maxLength(16384),
28
+ check(values => new Set(values.map(row => row.id)).size === values.length, 'Unique emitter ids')), input);
29
+ return rows.map(row => ({ at: new Vector3(...row.at), color: new Color().setRGB(...row.colour),
30
+ k: row.initially ? row.gain : 0, r: row.radius, cut: row.cut }));
31
+ }