@wildshard/sdk 0.0.1 → 0.2.3

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 (687) hide show
  1. package/GUIDE.md +790 -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 +46 -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 +24 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +196 -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 +292 -0
  365. package/src/cli/report.ts +16 -0
  366. package/src/cli/shardfile/command.ts +50 -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/arenaView.ts +15 -0
  394. package/src/sharddev/as/groupBankV2.ts +36 -0
  395. package/src/sharddev/as/groupStepV2.ts +13 -0
  396. package/src/sharddev/as/ws.ts +30 -0
  397. package/src/sharddev/as/wsV2.ts +180 -0
  398. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  399. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  400. package/src/sharddev/assetHandle.ts +84 -0
  401. package/src/sharddev/assetOwner.ts +70 -0
  402. package/src/sharddev/assetScope.ts +30 -0
  403. package/src/sharddev/assets.ts +21 -0
  404. package/src/sharddev/audio.ts +9 -0
  405. package/src/sharddev/audioEncode.ts +211 -0
  406. package/src/sharddev/author.ts +3 -0
  407. package/src/sharddev/authorError.ts +28 -0
  408. package/src/sharddev/authorManifest.ts +39 -0
  409. package/src/sharddev/bake/annulus.ts +19 -0
  410. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  411. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  412. package/src/sharddev/bake/authoredWorld.ts +201 -0
  413. package/src/sharddev/bake/basisEncoder.ts +95 -0
  414. package/src/sharddev/bake/basisGlb.ts +85 -0
  415. package/src/sharddev/bake/basisTool.ts +74 -0
  416. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  417. package/src/sharddev/bake/byteCodec.ts +33 -0
  418. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  419. package/src/sharddev/bake/coarseCopy.ts +59 -0
  420. package/src/sharddev/bake/colliders.ts +87 -0
  421. package/src/sharddev/bake/compactGlb.ts +224 -0
  422. package/src/sharddev/bake/compileScript.ts +119 -0
  423. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  424. package/src/sharddev/bake/contactRows.ts +84 -0
  425. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  426. package/src/sharddev/bake/export.ts +67 -0
  427. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  428. package/src/sharddev/bake/farImpostor.ts +120 -0
  429. package/src/sharddev/bake/forest.ts +100 -0
  430. package/src/sharddev/bake/format-hook.mjs +2 -0
  431. package/src/sharddev/bake/generatorGlb.ts +23 -0
  432. package/src/sharddev/bake/geometryBounds.ts +77 -0
  433. package/src/sharddev/bake/geometryError.ts +48 -0
  434. package/src/sharddev/bake/glb.ts +355 -0
  435. package/src/sharddev/bake/glbCompression.ts +143 -0
  436. package/src/sharddev/bake/gltfSource.ts +59 -0
  437. package/src/sharddev/bake/groundMap.ts +142 -0
  438. package/src/sharddev/bake/image.ts +20 -0
  439. package/src/sharddev/bake/isleMap.ts +64 -0
  440. package/src/sharddev/bake/json.mjs +84 -0
  441. package/src/sharddev/bake/keyedSky.ts +47 -0
  442. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  443. package/src/sharddev/bake/kinds.ts +137 -0
  444. package/src/sharddev/bake/lightSources.ts +31 -0
  445. package/src/sharddev/bake/mapAssembly.ts +84 -0
  446. package/src/sharddev/bake/mapRaster.ts +173 -0
  447. package/src/sharddev/bake/mapRest.ts +57 -0
  448. package/src/sharddev/bake/mapScenes.ts +234 -0
  449. package/src/sharddev/bake/materialGraph.ts +32 -0
  450. package/src/sharddev/bake/meadow.ts +27 -0
  451. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  452. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  453. package/src/sharddev/bake/nativeLattice.ts +178 -0
  454. package/src/sharddev/bake/nativeRaster.ts +106 -0
  455. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  456. package/src/sharddev/bake/navigation-json.mjs +38 -0
  457. package/src/sharddev/bake/navigation.ts +113 -0
  458. package/src/sharddev/bake/navigationAsset.ts +18 -0
  459. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  460. package/src/sharddev/bake/normalizeRig.ts +80 -0
  461. package/src/sharddev/bake/phoneAstc.ts +93 -0
  462. package/src/sharddev/bake/placeholders.ts +581 -0
  463. package/src/sharddev/bake/placement.ts +80 -0
  464. package/src/sharddev/bake/portableBytes.ts +18 -0
  465. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  466. package/src/sharddev/bake/practiceCourse.ts +49 -0
  467. package/src/sharddev/bake/primitives.ts +96 -0
  468. package/src/sharddev/bake/props.ts +443 -0
  469. package/src/sharddev/bake/questPlacement.ts +98 -0
  470. package/src/sharddev/bake/rawTexture.ts +26 -0
  471. package/src/sharddev/bake/riderArms.ts +97 -0
  472. package/src/sharddev/bake/rig.ts +95 -0
  473. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  474. package/src/sharddev/bake/signPlacements.ts +25 -0
  475. package/src/sharddev/bake/simplifier.ts +52 -0
  476. package/src/sharddev/bake/skinned.ts +312 -0
  477. package/src/sharddev/bake/slabChunks.ts +149 -0
  478. package/src/sharddev/bake/slabs.ts +263 -0
  479. package/src/sharddev/bake/source-loader.mjs +55 -0
  480. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  481. package/src/sharddev/bake/species.ts +368 -0
  482. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  483. package/src/sharddev/bake/splatGround.ts +141 -0
  484. package/src/sharddev/bake/staticMaterials.ts +171 -0
  485. package/src/sharddev/bake/terrain.ts +195 -0
  486. package/src/sharddev/bake/texture.ts +33 -0
  487. package/src/sharddev/bake/textureWasm.ts +81 -0
  488. package/src/sharddev/bake/tileEncoder.ts +11 -0
  489. package/src/sharddev/bake/tileGrid.ts +62 -0
  490. package/src/sharddev/bake/v2Finite.ts +160 -0
  491. package/src/sharddev/bake/v2Fuel.ts +71 -0
  492. package/src/sharddev/bake/wholePartition.ts +74 -0
  493. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  494. package/src/sharddev/bake/world.ts +173 -0
  495. package/src/sharddev/bake/worldCollision.ts +128 -0
  496. package/src/sharddev/bake/worldGeometry.ts +237 -0
  497. package/src/sharddev/bake/worldGlb.ts +123 -0
  498. package/src/sharddev/bake/worldImage.ts +12 -0
  499. package/src/sharddev/bake/worldLod.ts +128 -0
  500. package/src/sharddev/bake/worldRows.ts +102 -0
  501. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  502. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  503. package/src/sharddev/bake.ts +193 -0
  504. package/src/sharddev/bakePublication.ts +31 -0
  505. package/src/sharddev/behaviourSource.ts +94 -0
  506. package/src/sharddev/bin/wildshard.mjs +7 -0
  507. package/src/sharddev/blobBytes.ts +65 -0
  508. package/src/sharddev/blobs.ts +138 -0
  509. package/src/sharddev/bootInventory.ts +129 -0
  510. package/src/sharddev/bossProfiles.ts +18 -0
  511. package/src/sharddev/buildBehaviour.ts +77 -0
  512. package/src/sharddev/buildCacheMetrics.ts +17 -0
  513. package/src/sharddev/buildDecisionScripts.ts +122 -0
  514. package/src/sharddev/check.ts +117 -0
  515. package/src/sharddev/checkProject.ts +126 -0
  516. package/src/sharddev/cli.ts +191 -0
  517. package/src/sharddev/clientChannels.ts +169 -0
  518. package/src/sharddev/clientScripts.ts +10 -0
  519. package/src/sharddev/commons.ts +77 -0
  520. package/src/sharddev/commonsCosts.ts +11 -0
  521. package/src/sharddev/compileMovers.ts +11 -0
  522. package/src/sharddev/configBoundary.ts +6 -0
  523. package/src/sharddev/cookInput.ts +40 -0
  524. package/src/sharddev/crowds.ts +6 -0
  525. package/src/sharddev/decisionBindingMap.ts +11 -0
  526. package/src/sharddev/decisionScriptBindings.ts +117 -0
  527. package/src/sharddev/decisionScripts.ts +28 -0
  528. package/src/sharddev/decisionSource.ts +51 -0
  529. package/src/sharddev/dev.ts +113 -0
  530. package/src/sharddev/director.ts +26 -0
  531. package/src/sharddev/directorAbi.ts +77 -0
  532. package/src/sharddev/discoveryDocument.ts +97 -0
  533. package/src/sharddev/draft.ts +11 -0
  534. package/src/sharddev/eliteEntryRows.ts +29 -0
  535. package/src/sharddev/entries.ts +76 -0
  536. package/src/sharddev/entryReads.ts +73 -0
  537. package/src/sharddev/executeBundle.ts +55 -0
  538. package/src/sharddev/finds.ts +5 -0
  539. package/src/sharddev/formatJsonSchema.ts +3 -0
  540. package/src/sharddev/generationCache.ts +257 -0
  541. package/src/sharddev/generationRecipe.ts +94 -0
  542. package/src/sharddev/handwritten.ts +110 -0
  543. package/src/sharddev/immutable.ts +14 -0
  544. package/src/sharddev/interactions.ts +38 -0
  545. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  546. package/src/sharddev/kit/geometryPack.ts +110 -0
  547. package/src/sharddev/ledger.ts +13 -0
  548. package/src/sharddev/looks/tileField.ts +67 -0
  549. package/src/sharddev/materialGraphFiles.ts +57 -0
  550. package/src/sharddev/materials.ts +574 -0
  551. package/src/sharddev/measure.ts +18 -0
  552. package/src/sharddev/modes.ts +115 -0
  553. package/src/sharddev/moverPrograms.ts +213 -0
  554. package/src/sharddev/movers.ts +75 -0
  555. package/src/sharddev/nativePopulationRows.ts +46 -0
  556. package/src/sharddev/newProject.ts +247 -0
  557. package/src/sharddev/noise.ts +54 -0
  558. package/src/sharddev/outputProduct.ts +188 -0
  559. package/src/sharddev/outputRuntime.ts +66 -0
  560. package/src/sharddev/performancePolicy.ts +18 -0
  561. package/src/sharddev/phasedBoss.ts +34 -0
  562. package/src/sharddev/physics.ts +194 -0
  563. package/src/sharddev/platformSections.ts +42 -0
  564. package/src/sharddev/plumbing.ts +8 -0
  565. package/src/sharddev/productOutput.ts +128 -0
  566. package/src/sharddev/project.ts +337 -0
  567. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  568. package/src/sharddev/projectDecisions.ts +66 -0
  569. package/src/sharddev/projectEntryProof.ts +32 -0
  570. package/src/sharddev/projectGeneration.ts +219 -0
  571. package/src/sharddev/projectInputFiles.ts +47 -0
  572. package/src/sharddev/projectManifest.ts +108 -0
  573. package/src/sharddev/projectMap.ts +35 -0
  574. package/src/sharddev/projectOutput.ts +242 -0
  575. package/src/sharddev/projectPolicy.ts +17 -0
  576. package/src/sharddev/projectSections.ts +27 -0
  577. package/src/sharddev/questGraph.ts +25 -0
  578. package/src/sharddev/quests.ts +65 -0
  579. package/src/sharddev/random.ts +61 -0
  580. package/src/sharddev/refusals.ts +234 -0
  581. package/src/sharddev/reportCard.ts +13 -0
  582. package/src/sharddev/returnProjectionV2.ts +81 -0
  583. package/src/sharddev/rows.ts +192 -0
  584. package/src/sharddev/runtimeImports.ts +38 -0
  585. package/src/sharddev/runtimeMirrors.ts +39 -0
  586. package/src/sharddev/runtimePerformance.ts +38 -0
  587. package/src/sharddev/scene.ts +321 -0
  588. package/src/sharddev/sceneAnimation.ts +54 -0
  589. package/src/sharddev/sceneAudio.ts +64 -0
  590. package/src/sharddev/sceneDeclarations.ts +100 -0
  591. package/src/sharddev/sceneGraph.ts +139 -0
  592. package/src/sharddev/sceneTransform.ts +12 -0
  593. package/src/sharddev/schemaValidation.ts +61 -0
  594. package/src/sharddev/sections.ts +47 -0
  595. package/src/sharddev/shardSource.ts +59 -0
  596. package/src/sharddev/sourceReader.ts +26 -0
  597. package/src/sharddev/spawns.ts +38 -0
  598. package/src/sharddev/species/clips.ts +24 -0
  599. package/src/sharddev/species.ts +29 -0
  600. package/src/sharddev/speciesBrains.ts +19 -0
  601. package/src/sharddev/synth.ts +66 -0
  602. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  603. package/src/sharddev/test/compileSimV2.ts +21 -0
  604. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  605. package/src/sharddev/test/scriptScenario.ts +249 -0
  606. package/src/sharddev/test/scriptSource.ts +12 -0
  607. package/src/sharddev/version.ts +4 -0
  608. package/src/sharddev/weapons/bowProfile.ts +20 -0
  609. package/src/sharddev/weapons/firearmRows.ts +11 -0
  610. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  611. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  612. package/src/sharddev/worldScenes.ts +308 -0
  613. package/src/sharddev/worldSource.ts +82 -0
  614. package/src/shards/_template/README.md +78 -0
  615. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  616. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  617. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  618. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  619. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  620. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  621. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  622. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  623. package/src/shards/_template/behaviour/boss.as +39 -0
  624. package/src/shards/_template/behaviour/door.as +32 -0
  625. package/src/shards/_template/behaviour/hooks.json +129 -0
  626. package/src/shards/_template/behaviour/idle.as +75 -0
  627. package/src/shards/_template/behaviour/items.as +22 -0
  628. package/src/shards/_template/card/landscape.jpg +0 -0
  629. package/src/shards/_template/card/portrait.jpg +0 -0
  630. package/src/shards/_template/card/thumb.jpg +0 -0
  631. package/src/shards/_template/data/audio.json +45 -0
  632. package/src/shards/_template/data/bossDecision.json +83 -0
  633. package/src/shards/_template/data/budgets.json +70 -0
  634. package/src/shards/_template/data/card.json +281 -0
  635. package/src/shards/_template/data/clientScripts.json +987 -0
  636. package/src/shards/_template/data/creatures.json +65 -0
  637. package/src/shards/_template/data/director.json +39 -0
  638. package/src/shards/_template/data/encounters.json +96 -0
  639. package/src/shards/_template/data/items.json +172 -0
  640. package/src/shards/_template/data/layout.json +66 -0
  641. package/src/shards/_template/data/ledger.json +32 -0
  642. package/src/shards/_template/data/look.json +521 -0
  643. package/src/shards/_template/data/map.json +64 -0
  644. package/src/shards/_template/data/moves.json +16 -0
  645. package/src/shards/_template/data/placeholder.json +8 -0
  646. package/src/shards/_template/data/plumbing.json +32 -0
  647. package/src/shards/_template/data/quests.json +223 -0
  648. package/src/shards/_template/data/rows.json +423 -0
  649. package/src/shards/_template/data/skins.json +66 -0
  650. package/src/shards/_template/data/spawn.json +6 -0
  651. package/src/shards/_template/data/targets.json +150 -0
  652. package/src/shards/_template/data/text.json +12 -0
  653. package/src/shards/_template/data/ui.json +33 -0
  654. package/src/shards/_template/data/water.json +13 -0
  655. package/src/shards/_template/generators/behaviour.ts +34 -0
  656. package/src/shards/_template/generators/boss.ts +29 -0
  657. package/src/shards/_template/generators/buildOptions.ts +2 -0
  658. package/src/shards/_template/generators/cell.ts +224 -0
  659. package/src/shards/_template/generators/districts.ts +215 -0
  660. package/src/shards/_template/generators/farLook.ts +15 -0
  661. package/src/shards/_template/generators/generate.ts +27 -0
  662. package/src/shards/_template/generators/ground.ts +15 -0
  663. package/src/shards/_template/generators/kit.ts +69 -0
  664. package/src/shards/_template/generators/landscape.ts +59 -0
  665. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  666. package/src/shards/_template/generators/mapInputs.ts +10 -0
  667. package/src/shards/_template/generators/product.ts +100 -0
  668. package/src/shards/_template/generators/productOutput.ts +18 -0
  669. package/src/shards/_template/generators/props.ts +9 -0
  670. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  671. package/src/shards/_template/generators/terrain.ts +17 -0
  672. package/src/shards/_template/generators/world.ts +630 -0
  673. package/src/shards/_template/hero.json +10 -0
  674. package/src/shards/_template/look/entry-reads.json +20 -0
  675. package/src/shards/_template/manifest.json +281 -0
  676. package/src/shards/_template/shard.config.ts +10 -0
  677. package/src/shared/health.ts +10 -0
  678. package/src/tools/build-web.ts +59 -0
  679. package/src/tsconfig.json +30 -0
  680. package/src/web/app.tsx +53 -0
  681. package/src/web/index.html +12 -0
  682. package/src/web/main.tsx +10 -0
  683. package/src/web/tsconfig.json +13 -0
  684. package/tsconfig.author.json +23 -0
  685. package/tsconfig.commons.json +21 -0
  686. package/tsconfig.json +47 -0
  687. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,173 @@
1
+ import { WebIO, type Accessor, type Material, type Primitive, type Texture, type TextureInfo } from '@gltf-transform/core';
2
+ import { Matrix3, Matrix4, Vector3 } from 'three';
3
+ import { CELL_ABOVE, CELL_BELOW, CHUNK_HALF } from '@wildshard/format/contentBounds';
4
+ import { parseWorldSource } from '../worldSource';
5
+ import { hashImmutableBytes } from '../immutable';
6
+ import { preflightWorldGlb } from './worldGlb';
7
+ import { worldImageInfo } from './worldImage';
8
+
9
+ /** Retained embedded raster input; the later pinned encoder owns its KTX2 conversion. */
10
+ export interface WorldImage { hash: string; mime: string; width: number; height: number; bytes: Uint8Array }
11
+ /** A material texture use preserves UV0 and sampler data rather than copying pixels into vertex colours. */
12
+ export interface WorldTexture {
13
+ image: string; wrapS: number; wrapT: number; minFilter: number | null; magFilter: number | null;
14
+ /** Authored Three texture intake only: raster rows must be flipped before encoding when true. glTF defaults false. */
15
+ flipY?: boolean;
16
+ /** Original sampler anisotropy; absent preserves the glTF default of one. */
17
+ anisotropy?: number;
18
+ /** Original atlas extent, when captured from a live authored producer. No crop/repack is permitted. */
19
+ width?: number; height?: number;
20
+ }
21
+ /** Source glTF metallic/roughness surface with every supported texture slot and its explicit output material ID. */
22
+ export interface WorldMaterial {
23
+ name: string; id: string; colour: number[]; metalness: number; roughness: number; emissive: number[];
24
+ alpha: string; alphaCutoff: number; doubleSided: boolean; normalScale: number; occlusion: number;
25
+ maps: { colour: WorldTexture | null; normal: WorldTexture | null; metallicRoughness: WorldTexture | null; occlusion: WorldTexture | null; emissive: WorldTexture | null };
26
+ }
27
+ /** Indexed triangle topology, world-local for static geometry and panel-root-local for interactive geometry. */
28
+ export interface WorldPrimitive {
29
+ node: string; objectId: string | null; material: number; terrain: boolean;
30
+ positions: Float64Array; normals: Float32Array | null; colours: Float32Array | null; uv: Float32Array | null; tangents: Float32Array | null; indices: Uint32Array;
31
+ }
32
+ /** Config-selected panel root, its exact world transform and independent local collision/render triangles. */
33
+ export interface WorldPanel { id: string; colliderId: string; node: string; transform: number[]; primitives: WorldPrimitive[] }
34
+ /** Fully normalized, memory-only build input; no GLB node is silently omitted or converted to a heightfield.
35
+ * `undrawn`: the collision primitives under the source's `undrawn` prefix (a baked-tiles row draws them); `far`: the
36
+ * primitives under its `far` prefix (only the far proxy draws them; they never collide). RM8.2 `detail`: the static
37
+ * primitives under its `detail` prefix (also in `static`, drawn only at L0); `coarse`: those under its `coarse` prefix
38
+ * (only the L1 tiles draw them; they never collide). */
39
+ export interface NormalizedWorld { static: WorldPrimitive[]; collision: WorldPrimitive[]; undrawn: WorldPrimitive[]; far: WorldPrimitive[]; detail: WorldPrimitive[]; coarse: WorldPrimitive[]; panels: WorldPanel[]; materials: WorldMaterial[]; images: WorldImage[] }
40
+
41
+ function samples(accessor: Accessor, width: number, count: number): Float32Array {
42
+ if (accessor.getElementSize() !== width || accessor.getCount() !== count) throw new Error('World GLB mismatched attribute shape');
43
+ const values = new Float32Array(width * count), row: number[] = [];
44
+ for (let i = 0; i < count; i++) {
45
+ accessor.getElement(i, row);
46
+ if (row.some((value) => !Number.isFinite(value))) throw new Error('World GLB nonfinite attribute');
47
+ values.set(row, i * width);
48
+ }
49
+ return values;
50
+ }
51
+ function geometry(primitive: Primitive, matrix: Matrix4, world: Matrix4, node: string, material: number, objectId: string | null, terrain: boolean): WorldPrimitive {
52
+ const position = primitive.getAttribute('POSITION');
53
+ if (position?.getType() !== 'VEC3' || position.getComponentType() !== 5126 || position.getCount() === 0 || position.getCount() > 4_000_000) throw new Error(`World GLB node ${node} needs bounded float positions`);
54
+ if (primitive.listSemantics().some((semantic) => !['POSITION', 'NORMAL', 'TEXCOORD_0', 'COLOR_0', 'TANGENT'].includes(semantic))) throw new Error(`World GLB node ${node} has unsupported vertex attributes`);
55
+ const n = position.getCount(), source = samples(position, 3, n), positions = new Float64Array(n * 3), normalMatrix = new Matrix3().getNormalMatrix(matrix), mirrored = matrix.determinant() < 0;
56
+ for (let i = 0; i < n; i++) {
57
+ const point = new Vector3().fromArray(source, i * 3), placed = point.clone().applyMatrix4(world);
58
+ if (![placed.x, placed.y, placed.z].every(Number.isFinite) || Math.abs(placed.x) > CHUNK_HALF || Math.abs(placed.z) > CHUNK_HALF || placed.y < -CELL_BELOW || placed.y > CELL_ABOVE) throw new Error(`World GLB node ${node} lies outside the cell`);
59
+ point.applyMatrix4(matrix); positions.set(point.toArray(), i * 3);
60
+ }
61
+ const attribute = (semantic: string, width: number) => {
62
+ const value = primitive.getAttribute(semantic);
63
+ if (value === null) return null;
64
+ if (value.getComponentType() !== 5126 && (semantic !== 'TEXCOORD_0' || !value.getNormalized() || ![5121, 5123].includes(value.getComponentType()))) throw new Error(`World GLB node ${node} has unsupported ${semantic} encoding`);
65
+ return samples(value, width, n);
66
+ };
67
+ const normals = attribute('NORMAL', 3), uv = attribute('TEXCOORD_0', 2), colour = primitive.getAttribute('COLOR_0');
68
+ const colours = colour === null ? null : samples(colour, colour.getElementSize(), n), tangents = attribute('TANGENT', 4);
69
+ if (colours !== null && (colour === null || ![3, 4].includes(colour.getElementSize()) || (colour.getComponentType() !== 5126 && (!colour.getNormalized() || ![5121, 5123].includes(colour.getComponentType()))) || colours.some((value) => value < 0 || value > 1))) throw new Error(`World GLB node ${node} needs RGB/RGBA colours`);
70
+ if (normals !== null) for (let i = 0; i < n; i++) {
71
+ const normal = new Vector3().fromArray(normals, i * 3).applyMatrix3(normalMatrix);
72
+ if (normal.lengthSq() === 0 || ![normal.x, normal.y, normal.z].every(Number.isFinite)) throw new Error(`World GLB node ${node} has a zero or nonfinite normal`);
73
+ normals.set(normal.normalize().toArray(), i * 3);
74
+ }
75
+ if (tangents !== null) for (let i = 0; i < n; i++) {
76
+ const tangent = new Vector3().fromArray(tangents, i * 4).transformDirection(matrix);
77
+ if (normals === null || Math.abs(tangents[i * 4 + 3] ?? 0) !== 1) throw new Error(`World GLB node ${node} needs normals and signed tangents`);
78
+ const normal = new Vector3().fromArray(normals, i * 3); tangent.addScaledVector(normal, -tangent.dot(normal));
79
+ if (tangent.lengthSq() === 0) throw new Error(`World GLB node ${node} has a degenerate tangent`);
80
+ tangents.set(tangent.normalize().toArray(), i * 4); tangents[i * 4 + 3] = (tangents[i * 4 + 3] ?? 1) * (mirrored ? -1 : 1);
81
+ }
82
+ const index = primitive.getIndices();
83
+ if (index !== null && (index.getType() !== 'SCALAR' || ![5121, 5123, 5125].includes(index.getComponentType()) || index.getNormalized())) throw new Error(`World GLB node ${node} has unsupported triangle indices`);
84
+ const count = index?.getCount() ?? n;
85
+ if (count === 0 || count % 3 !== 0 || count > 12_000_000) throw new Error(`World GLB node ${node} triangle cap`);
86
+ const indices = new Uint32Array(count);
87
+ for (let i = 0; i < count; i++) { const at = index?.getScalar(i) ?? i; if (!Number.isInteger(at) || at < 0 || at >= n) throw new Error(`World GLB node ${node} index outside positions`); indices[i] = at; }
88
+ if (mirrored) for (let i = 0; i < count; i += 3) { const a = indices[i + 1] ?? 0; indices[i + 1] = indices[i + 2] ?? 0; indices[i + 2] = a; }
89
+ return { node, objectId, material, terrain, positions, normals, colours, uv, tangents, indices };
90
+ }
91
+
92
+ /** Normalize one embedded static world GLB without files, renderer allocation, baking or platform collision. */
93
+ export async function normalizeWorldGlb(bytes: Uint8Array, input: unknown, materialIds: readonly string[]): Promise<NormalizedWorld> {
94
+ const source = parseWorldSource(input), intake = preflightWorldGlb(bytes);
95
+ // The binary view requires aligned input; the caller retains its bytes unchanged.
96
+ const document = await new WebIO().readBinary(Uint8Array.from(bytes)), root = document.getRoot(), nodes = root.listNodes();
97
+ if (nodes.length !== intake.matrices.length) throw new Error('World GLB node inventory changed during decode');
98
+ const byName = new Map<string, number>();
99
+ nodes.forEach((node, index) => { const name = node.getName(); if (name !== '') { if (byName.has(name)) throw new Error(`World GLB duplicate node name ${name}`); byName.set(name, index); } });
100
+ const images: WorldImage[] = [], imageHashes = new Map<Texture, string>();
101
+ for (const texture of root.listTextures()) {
102
+ const image = texture.getImage(), mime = texture.getMimeType();
103
+ if (image === null) throw new Error(`World GLB image ${texture.getName()} has missing bytes`);
104
+ const info = await worldImageInfo(image);
105
+ if (info.mime !== mime) throw new Error(`World GLB image ${texture.getName()} has mismatched bytes`);
106
+ const size: [number, number] = [info.width, info.height];
107
+ const hash = hashImmutableBytes(image); imageHashes.set(texture, hash);
108
+ if (!images.some((entry) => entry.hash === hash)) images.push({ hash, mime, width: size[0], height: size[1], bytes: Uint8Array.from(image) });
109
+ }
110
+ const textureUse = (texture: Texture | null, info: TextureInfo | null): WorldTexture | null => {
111
+ if (texture === null) return null;
112
+ const image = imageHashes.get(texture);
113
+ if (image === undefined || info?.getTexCoord() !== 0) throw new Error('World GLB textures require embedded images and UV0');
114
+ const sampler = { image, wrapS: info.getWrapS(), wrapT: info.getWrapT(), minFilter: info.getMinFilter(), magFilter: info.getMagFilter() };
115
+ if (![33071, 33648, 10497].includes(sampler.wrapS) || ![33071, 33648, 10497].includes(sampler.wrapT) || (sampler.minFilter !== null && ![9728, 9729, 9984, 9985, 9986, 9987].includes(sampler.minFilter)) || (sampler.magFilter !== null && ![9728, 9729].includes(sampler.magFilter))) throw new Error('World GLB unsupported texture sampler');
116
+ return sampler;
117
+ };
118
+ const materials: WorldMaterial[] = [], materialIndices = new Map<Material, number>();
119
+ for (const material of root.listMaterials()) {
120
+ const name = material.getName(), id = source.materials[name];
121
+ if (materials.some((row) => row.name === name)) throw new Error(`World GLB duplicate material name ${name}`);
122
+ if (id === undefined || !materialIds.includes(id)) throw new Error(`World GLB material ${name || '(unnamed)'} is unmapped or its output ID is not admitted`);
123
+ const row: WorldMaterial = { name, id, colour: material.getBaseColorFactor(), metalness: material.getMetallicFactor(), roughness: material.getRoughnessFactor(), emissive: material.getEmissiveFactor(), alpha: material.getAlphaMode(), alphaCutoff: material.getAlphaCutoff(), doubleSided: material.getDoubleSided(), normalScale: material.getNormalScale(), occlusion: material.getOcclusionStrength(), maps: {
124
+ colour: textureUse(material.getBaseColorTexture(), material.getBaseColorTextureInfo()), normal: textureUse(material.getNormalTexture(), material.getNormalTextureInfo()), metallicRoughness: textureUse(material.getMetallicRoughnessTexture(), material.getMetallicRoughnessTextureInfo()), occlusion: textureUse(material.getOcclusionTexture(), material.getOcclusionTextureInfo()), emissive: textureUse(material.getEmissiveTexture(), material.getEmissiveTextureInfo()),
125
+ } };
126
+ if (![...row.colour, row.metalness, row.roughness, ...row.emissive, row.occlusion, row.alphaCutoff].every((value) => Number.isFinite(value) && value >= 0 && value <= 1) || !Number.isFinite(row.normalScale) || typeof row.doubleSided !== 'boolean' || !['OPAQUE', 'MASK', 'BLEND'].includes(row.alpha)) throw new Error(`World GLB material ${name} has unsupported factors`);
127
+ materialIndices.set(material, materials.length); materials.push(row);
128
+ }
129
+ for (const name of Object.keys(source.materials)) if (!materials.some((row) => row.name === name)) throw new Error(`World GLB material mapping ${name} has no source material`);
130
+ const selected = (name: string): number => { const id = byName.get(name); if (id === undefined) throw new Error(`World GLB selected node ${name} is missing`); return id; };
131
+ const panelRoots = source.interactive.map((row) => selected(row.node)), stableRoots = Object.keys(source.objects).map(selected);
132
+ const ancestry = (id: number): number[] => { const result = [id]; let parent = intake.parents[id]; while (parent !== undefined) { result.push(parent); parent = intake.parents[parent]; } return result; };
133
+ const ownedRoots = [...panelRoots, ...stableRoots];
134
+ if (ownedRoots.some((id) => ancestry(id).slice(1).some((parent) => ownedRoots.includes(parent)))) throw new Error('World GLB selected object/interactive hierarchies overlap');
135
+ const panels: WorldPanel[] = source.interactive.map((row, i) => ({ ...row, transform: [...(intake.matrices[panelRoots[i] ?? -1]?.elements ?? [])], primitives: [] }));
136
+ const collisionPrefix = source.colliders === 'mesh' ? null : source.colliders.slice(6), collisionRoots = nodes.flatMap((node, index) => collisionPrefix !== null && node.getName().startsWith(collisionPrefix) ? [index] : []);
137
+ if (collisionPrefix !== null && collisionRoots.length === 0) throw new Error(`World GLB collision prefix ${collisionPrefix} matches no nodes`);
138
+ if (collisionRoots.some((id) => ancestry(id).some((parent) => panelRoots.includes(parent))) || panelRoots.some((id) => ancestry(id).some((parent) => collisionRoots.includes(parent)))) throw new Error('World GLB collision-only and interactive hierarchies overlap');
139
+ const normalized: NormalizedWorld = { static: [], collision: [], undrawn: [], far: [], detail: [], coarse: [], panels, materials, images }, undrawnPrefix = source.undrawn, farPrefix = source.far;
140
+ const detailPrefix = source.detail, coarsePrefix = source.coarse, under = (chain: number[], prefix: string | undefined) => prefix !== undefined && chain.some((ancestor) => nodes[ancestor]?.getName().startsWith(prefix));
141
+ let vertices = 0, indices = 0;
142
+ nodes.forEach((node, id) => {
143
+ const mesh = node.getMesh(); if (mesh === null) return;
144
+ const chain = ancestry(id), panelIndex = panelRoots.findIndex((panel) => chain.includes(panel)), panel = panels[panelIndex], world = intake.matrices[id];
145
+ if (world === undefined || node.getName() === '') throw new Error(`World GLB mesh node ${id} needs a unique name`);
146
+ const matrix = panel === undefined ? world : new Matrix4().fromArray(panel.transform).invert().multiply(world);
147
+ const owner = stableRoots.find((selectedId) => chain.includes(selectedId)), objectId = owner === undefined ? null : source.objects[nodes[owner]?.getName() ?? ''] ?? null;
148
+ const collisionOnly = chain.some((ancestor) => collisionRoots.includes(ancestor)), terrain = chain.some((ancestor) => nodes[ancestor]?.getName().startsWith('ws_terrain'));
149
+ for (const primitive of mesh.listPrimitives()) {
150
+ const material = primitive.getMaterial(), materialIndex = material === null ? undefined : materialIndices.get(material);
151
+ if (materialIndex === undefined) throw new Error(`World GLB node ${node.getName()} lacks a mapped material`);
152
+ vertices += primitive.getAttribute('POSITION')?.getCount() ?? 0; indices += primitive.getIndices()?.getCount() ?? primitive.getAttribute('POSITION')?.getCount() ?? 0;
153
+ if (vertices > 4_000_000 || indices > 12_000_000) throw new Error('World GLB expanded geometry cap');
154
+ const output = geometry(primitive, matrix, world, node.getName(), materialIndex, panel?.id ?? objectId, terrain);
155
+ const maps = materials[materialIndex]?.maps;
156
+ if (maps !== undefined && Object.values(maps).some((map) => map !== null) && output.uv === null) throw new Error(`World GLB textured node ${node.getName()} needs UV0`);
157
+ if (panel !== undefined) panel.primitives.push(output);
158
+ else if (collisionOnly) normalized.collision.push(output);
159
+ else if (farPrefix !== undefined && chain.some((ancestor) => nodes[ancestor]?.getName().startsWith(farPrefix))) normalized.far.push(output);
160
+ else if (under(chain, coarsePrefix)) normalized.coarse.push(output);
161
+ else if (undrawnPrefix !== undefined && chain.some((ancestor) => nodes[ancestor]?.getName().startsWith(undrawnPrefix))) { normalized.undrawn.push(output); normalized.collision.push(output); }
162
+ else { normalized.static.push(output); if (under(chain, detailPrefix)) normalized.detail.push(output); if (collisionPrefix === null) normalized.collision.push(output); }
163
+ }
164
+ });
165
+ if (undrawnPrefix !== undefined && normalized.undrawn.length === 0) throw new Error(`World GLB undrawn prefix ${undrawnPrefix} matches no meshes`);
166
+ if (farPrefix !== undefined && normalized.far.length === 0) throw new Error(`World GLB far prefix ${farPrefix} matches no meshes`);
167
+ if (detailPrefix !== undefined && normalized.detail.length === 0) throw new Error(`World GLB detail prefix ${detailPrefix} matches no meshes`);
168
+ if (coarsePrefix !== undefined && normalized.coarse.length === 0) throw new Error(`World GLB coarse prefix ${coarsePrefix} matches no meshes`);
169
+ if (normalized.static.length === 0 || normalized.collision.length === 0 || panels.some((panel) => panel.primitives.length === 0)) throw new Error('World GLB needs static render geometry, selected collision geometry and nonempty interactive panels');
170
+ for (const name of Object.keys(source.objects)) if (![...normalized.static, ...normalized.collision].some((primitive) => primitive.objectId === source.objects[name])) throw new Error(`World GLB selected object ${name} has no geometry`);
171
+ images.sort((a, b) => a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0);
172
+ return normalized;
173
+ }
@@ -0,0 +1,128 @@
1
+ import { encodeMeshCollision, MESH_COLLISION_LIMITS } from '@wildshard/format/meshCollisionBytes';
2
+ import { hashImmutableBytes } from '../immutable';
3
+ import type { NormalizedWorld, WorldPanel, WorldPrimitive } from './world';
4
+
5
+ type Point = readonly [number, number, number];
6
+ interface Chunk { vertices: number[]; indices: number[]; welded: Map<string, number> }
7
+ /** One nonempty 62.5 m collision tile. The hash refers to exact cell-local WMC1 bytes. */
8
+ export interface WorldCollisionTile { x: number; z: number; file: string; triangles: number }
9
+ /** Interactive geometry stays independent of static tiles, in its authored world rest pose. */
10
+ export interface WorldCollisionPanel { id: string; colliderId: string; file: string; triangles: number }
11
+ /** Deterministic collision bake; byte costs and critical-root admission are applied by the compiled product builder. */
12
+ export interface BakedWorldCollision { tiles: WorldCollisionTile[]; panels: WorldCollisionPanel[]; assets: Map<string, Uint8Array> }
13
+
14
+ const SIZE = 62.5, HALF = 250;
15
+ const chunk = (): Chunk => ({ vertices: [], indices: [], welded: new Map() });
16
+ function area(a: Point, b: Point, c: Point): number {
17
+ const ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2], vx = c[0] - a[0], vy = c[1] - a[1], vz = c[2] - a[2];
18
+ return Math.hypot(uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx);
19
+ }
20
+ function append(out: Chunk, a: Point, b: Point, c: Point, node: string): void {
21
+ // A polygon may touch a tile only along an edge. That intersection has no collision area.
22
+ if (area(a, b, c) === 0) return;
23
+ const rounded = [a, b, c].map((p): Point => [Math.fround(p[0]) || 0, Math.fround(p[1]) || 0, Math.fround(p[2]) || 0]);
24
+ const [ra, rb, rc] = rounded;
25
+ if (ra === undefined || rb === undefined || rc === undefined) throw new Error('World collision missing rounded triangle');
26
+ // The source passed Float32 admission below. Clipping can leave an unrepresentable seam sliver.
27
+ if (area(ra, rb, rc) === 0) return;
28
+ if (out.indices.length / 3 >= MESH_COLLISION_LIMITS.triangles) throw new Error(`World collision node ${node} exceeds triangles per chunk`);
29
+ for (const vertex of rounded) {
30
+ const key = vertex.join(','); let index = out.welded.get(key);
31
+ if (index === undefined) {
32
+ index = out.vertices.length / 3;
33
+ if (index >= MESH_COLLISION_LIMITS.vertices) throw new Error(`World collision node ${node} exceeds vertices per chunk`);
34
+ out.welded.set(key, index); out.vertices.push(...vertex);
35
+ }
36
+ out.indices.push(index);
37
+ }
38
+ }
39
+ function clip(polygon: readonly Point[], axis: 0 | 2, boundary: number, greater: boolean): Point[] {
40
+ const result: Point[] = [];
41
+ for (let i = 0; i < polygon.length; i++) {
42
+ const a = polygon[i], b = polygon[(i + 1) % polygon.length]; if (a === undefined || b === undefined) throw new Error('World collision polygon');
43
+ const insideA = greater ? a[axis] >= boundary : a[axis] <= boundary, insideB = greater ? b[axis] >= boundary : b[axis] <= boundary;
44
+ if (insideA) result.push(a);
45
+ if (insideA === insideB) continue;
46
+ // Oppositely wound shared edges interpolate in the same direction, avoiding last-bit seam drift.
47
+ const forward = a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || (a[1] === b[1] && a[2] < b[2])));
48
+ const start = forward ? a : b, end = forward ? b : a;
49
+ const t = (boundary - start[axis]) / (end[axis] - start[axis]);
50
+ const p: [number, number, number] = [start[0] + (end[0] - start[0]) * t, start[1] + (end[1] - start[1]) * t, start[2] + (end[2] - start[2]) * t];
51
+ p[axis] = boundary; result.push(p);
52
+ }
53
+ return result;
54
+ }
55
+ function point(primitive: WorldPrimitive, index: number, transform?: readonly number[]): Point {
56
+ const x = primitive.positions[index * 3], y = primitive.positions[index * 3 + 1], z = primitive.positions[index * 3 + 2];
57
+ if (x === undefined || y === undefined || z === undefined) throw new Error(`World collision node ${primitive.node} has an invalid index`);
58
+ const value: Point = transform === undefined ? [x, y, z] : [
59
+ (transform[0] ?? 0) * x + (transform[4] ?? 0) * y + (transform[8] ?? 0) * z + (transform[12] ?? 0),
60
+ (transform[1] ?? 0) * x + (transform[5] ?? 0) * y + (transform[9] ?? 0) * z + (transform[13] ?? 0),
61
+ (transform[2] ?? 0) * x + (transform[6] ?? 0) * y + (transform[10] ?? 0) * z + (transform[14] ?? 0),
62
+ ];
63
+ if (value.some(v => !Number.isFinite(v) || Math.abs(v) > HALF)) throw new Error(`World collision node ${primitive.node} outside finite cell bounds`);
64
+ return value;
65
+ }
66
+ function transformOf(panel: WorldPanel): { transform: number[]; mirrored: boolean } {
67
+ const m = panel.transform;
68
+ if (m.length !== 16 || m.some(v => !Number.isFinite(v)) || m[3] !== 0 || m[7] !== 0 || m[11] !== 0 || m[15] !== 1) throw new Error(`World collision panel ${panel.id} requires a finite affine transform`);
69
+ const a = m[0] ?? 0, b = m[4] ?? 0, c = m[8] ?? 0, d = m[1] ?? 0, e = m[5] ?? 0, f = m[9] ?? 0, g = m[2] ?? 0, h = m[6] ?? 0, i = m[10] ?? 0;
70
+ const determinant = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
71
+ if (!Number.isFinite(determinant) || determinant === 0) throw new Error(`World collision panel ${panel.id} has a singular transform`);
72
+ return { transform: m, mirrored: determinant < 0 };
73
+ }
74
+ function triangles(primitive: WorldPrimitive, visit: (a: Point, b: Point, c: Point) => void, transform?: readonly number[], mirrored = false): void {
75
+ if (!(primitive.positions instanceof Float64Array) || primitive.positions.length % 3 !== 0 || primitive.positions.length < 9 || primitive.positions.length > 12_000_000
76
+ || !(primitive.indices instanceof Uint32Array) || primitive.indices.length < 3 || primitive.indices.length % 3 !== 0 || primitive.indices.length > 12_000_000) throw new Error(`World collision node ${primitive.node} has malformed bounded geometry`);
77
+ for (let i = 0; i < primitive.indices.length; i += 3) {
78
+ const a = primitive.indices[i], b = primitive.indices[i + 1], c = primitive.indices[i + 2];
79
+ if (a === undefined || b === undefined || c === undefined) throw new Error('World collision missing triangle');
80
+ const pa = point(primitive, a, transform), pb = point(primitive, mirrored ? c : b, transform), pc = point(primitive, mirrored ? b : c, transform);
81
+ if (area(pa, pb, pc) === 0) throw new Error(`World collision node ${primitive.node} has a degenerate triangle`);
82
+ const rounded = [pa, pb, pc].map((p): Point => [Math.fround(p[0]), Math.fround(p[1]), Math.fround(p[2])]);
83
+ const [ra, rb, rc] = rounded;
84
+ if (ra === undefined || rb === undefined || rc === undefined || area(ra, rb, rc) === 0) throw new Error(`World collision node ${primitive.node} has a triangle that collapses at Float32 precision`);
85
+ visit(pa, pb, pc);
86
+ }
87
+ }
88
+ const address = (value: number): number => Math.min(7, Math.floor((value + HALF) / SIZE));
89
+
90
+ /** Partition actual collision triangles at the L0 lattice, weld exact Float32 seams, and bake panels independently.
91
+ * No LOD is applied to collision: a bridge, its underside and its ground survive as separate triangles.
92
+ * Vertical triangles exactly on a lattice line have one owner (the positive-side tile, or the last tile at +250).
93
+ */
94
+ export function bakeWorldCollision(world: Pick<NormalizedWorld, 'collision' | 'panels'>): BakedWorldCollision {
95
+ if (world.collision.length === 0 || world.collision.length > 10000 || world.panels.length > 64) throw new Error('World collision requires bounded static geometry and panels');
96
+ const chunks = new Map<number, Chunk>(), assets = new Map<string, Uint8Array>(), panels: WorldCollisionPanel[] = [];
97
+ let components = 0;
98
+ const bound = (p: WorldPrimitive): void => { components += p.indices.length; if (components > 12_000_000) throw new Error('World collision expanded index cap'); };
99
+ for (const primitive of world.collision) {
100
+ bound(primitive);
101
+ triangles(primitive, (a, b, c) => {
102
+ const x0 = address(Math.min(a[0], b[0], c[0])), x1 = address(Math.max(a[0], b[0], c[0])), z0 = address(Math.min(a[2], b[2], c[2])), z1 = address(Math.max(a[2], b[2], c[2]));
103
+ for (let z = z0; z <= z1; z++) for (let x = x0; x <= x1; x++) {
104
+ let polygon: Point[] = [a, b, c];
105
+ for (const [axis, boundary, greater] of [[0, -HALF + x * SIZE, true], [0, -HALF + (x + 1) * SIZE, false], [2, -HALF + z * SIZE, true], [2, -HALF + (z + 1) * SIZE, false]] as const) polygon = clip(polygon, axis, boundary, greater);
106
+ const key = z * 8 + x, output = chunks.get(key) ?? chunk();
107
+ for (let i = 1; i + 1 < polygon.length; i++) {
108
+ const first = polygon[0], second = polygon[i], third = polygon[i + 1]; if (first === undefined || second === undefined || third === undefined) throw new Error('World collision clipped triangle');
109
+ append(output, first, second, third, primitive.node);
110
+ }
111
+ if (output.indices.length > 0) chunks.set(key, output);
112
+ }
113
+ });
114
+ }
115
+ const store = (data: Chunk): string => {
116
+ const bytes = encodeMeshCollision({ vertices: Float32Array.from(data.vertices), indices: Uint32Array.from(data.indices) }), hash = hashImmutableBytes(bytes);
117
+ assets.set(hash, bytes); return hash;
118
+ };
119
+ const ids = new Set<string>(), colliderIds = new Set<string>();
120
+ for (const panel of world.panels) {
121
+ if (ids.has(panel.id) || colliderIds.has(panel.colliderId) || panel.primitives.length === 0 || panel.primitives.length > 10000) throw new Error(`World collision duplicate or empty panel ${panel.id}`);
122
+ ids.add(panel.id); colliderIds.add(panel.colliderId);
123
+ const output = chunk(), { transform, mirrored } = transformOf(panel);
124
+ for (const primitive of panel.primitives) { bound(primitive); triangles(primitive, (a, b, c) => append(output, a, b, c, primitive.node), transform, mirrored); }
125
+ panels.push({ id: panel.id, colliderId: panel.colliderId, file: store(output), triangles: output.indices.length / 3 });
126
+ }
127
+ return { tiles: [...chunks].sort(([a], [b]) => a - b).map(([key, data]) => ({ x: key % 8, z: Math.floor(key / 8), file: store(data), triangles: data.indices.length / 3 })), panels, assets };
128
+ }
@@ -0,0 +1,237 @@
1
+ import { MeshoptEncoder } from 'meshoptimizer/encoder';
2
+ import { BufferAttribute, BufferGeometry, Float32BufferAttribute, Matrix4, Quaternion, Vector3, type Box3 } from 'three';
3
+ import type { WorldPrimitive } from './world';
4
+ import { floatPositionError } from './geometryError';
5
+
6
+ await MeshoptEncoder.ready;
7
+
8
+ interface Channel { key: string; width: number; data: Float32Array | Float64Array }
9
+ type Vertex = number[];
10
+ function channels(source: WorldPrimitive): Channel[] {
11
+ const n = source.positions.length / 3;
12
+ const rows: Channel[] = [{ key: 'position', width: 3, data: source.positions }];
13
+ for (const [key, data, width] of [['normal', source.normals, 3], ['uv', source.uv, 2], ['color', source.colours, source.colours === null ? 3 : source.colours.length / n], ['tangent', source.tangents, 4]] as const) {
14
+ if (data !== null) rows.push({ key, data, width });
15
+ }
16
+ return rows;
17
+ }
18
+ function cut(input: readonly Vertex[], axis: number, boundary: number, greater: boolean): Vertex[] {
19
+ const output: Vertex[] = [];
20
+ for (let i = 0; i < input.length; i++) {
21
+ const a = input[i], b = input[(i + 1) % input.length];
22
+ if (a === undefined || b === undefined) continue;
23
+ const av = a[axis] ?? 0, bv = b[axis] ?? 0;
24
+ const insideA = greater ? av >= boundary : av <= boundary, insideB = greater ? bv >= boundary : bv <= boundary;
25
+ if (insideA) output.push(a);
26
+ if (insideA !== insideB) {
27
+ // Canonical endpoints keep adjacent tile cuts byte-identical at their shared boundary.
28
+ const [start, end] = av < bv ? [a, b] : [b, a];
29
+ const t = (boundary - (start[axis] ?? 0)) / ((end[axis] ?? 0) - (start[axis] ?? 0));
30
+ const vertex = start.map((value, at) => value + ((end[at] ?? value) - value) * t);
31
+ vertex[axis] = boundary; output.push(vertex);
32
+ }
33
+ }
34
+ return output;
35
+ }
36
+
37
+ function outsideFirstCuts(positions: Float64Array, a: number, b: number, c: number, bounds: readonly [number, number, number, number]): boolean {
38
+ const ax = positions[a * 3] ?? Number.NaN, bx = positions[b * 3] ?? Number.NaN, cx = positions[c * 3] ?? Number.NaN;
39
+ const insideMin = ax >= bounds[0] && bx >= bounds[0] && cx >= bounds[0];
40
+ if (ax < bounds[0] && bx < bounds[0] && cx < bounds[0]) return true;
41
+ if (insideMin && ax > bounds[1] && bx > bounds[1] && cx > bounds[1]) return true;
42
+ // Only inspect z when both earlier x cuts leave every original vertex intact.
43
+ // Otherwise their rounded intersections must still go through the old clipper.
44
+ if (!insideMin || ax > bounds[1] || bx > bounds[1] || cx > bounds[1]) return false;
45
+ const az = positions[a * 3 + 2] ?? Number.NaN, bz = positions[b * 3 + 2] ?? Number.NaN, cz = positions[c * 3 + 2] ?? Number.NaN;
46
+ if (az < bounds[2] && bz < bounds[2] && cz < bounds[2]) return true;
47
+ return az >= bounds[2] && bz >= bounds[2] && cz >= bounds[2] && az > bounds[3] && bz > bounds[3] && cz > bounds[3];
48
+ }
49
+
50
+ /** Clip every authored vertex channel to one tile, preserving vertical faces and both bridge layers.
51
+ * This is offline render geometry clipping; the independent WMC1 baker remains the collision authority. */
52
+ export function worldGeometry(source: WorldPrimitive, bounds?: readonly [number, number, number, number], transform?: readonly number[], storageError?: (metres: number) => void): BufferGeometry {
53
+ const rows = channels(source), output = rows.map(() => [] as number[]), matrix = transform === undefined ? null : new Matrix4().fromArray(transform);
54
+ const vertex = (index: number): Vertex => {
55
+ const values: Vertex = [];
56
+ for (const row of rows) for (const value of row.data.subarray(index * row.width, (index + 1) * row.width)) values.push(value);
57
+ return values;
58
+ };
59
+ for (let i = 0; i < source.indices.length; i += 3) {
60
+ const ai = source.indices[i] ?? 0, bi = source.indices[i + 1] ?? 0, ci = source.indices[i + 2] ?? 0;
61
+ if (bounds !== undefined && outsideFirstCuts(source.positions, ai, bi, ci, bounds)) continue;
62
+ let polygon = [vertex(ai), vertex(bi), vertex(ci)];
63
+ if (bounds !== undefined) for (const [axis, boundary, greater] of [[0, bounds[0], true], [0, bounds[1], false], [2, bounds[2], true], [2, bounds[3], false]] as const) polygon = cut(polygon, axis, boundary, greater);
64
+ for (let at = 1; at + 1 < polygon.length; at++) {
65
+ const a = polygon[0], b = polygon[at], c = polygon[at + 1];
66
+ if (a === undefined || b === undefined || c === undefined) continue;
67
+ const pa = new Vector3().fromArray(a), pb = new Vector3().fromArray(b), pc = new Vector3().fromArray(c);
68
+ if (pb.sub(pa).cross(pc.sub(pa)).lengthSq() === 0) continue;
69
+ for (const point of [a, b, c]) {
70
+ let offset = 0;
71
+ rows.forEach((row, channel) => { output[channel]?.push(...point.slice(offset, offset + row.width)); offset += row.width; });
72
+ }
73
+ }
74
+ }
75
+ const geometry = new BufferGeometry();
76
+ rows.forEach((row, at) => { geometry.setAttribute(row.key, new Float32BufferAttribute(output[at] ?? [], row.width)); });
77
+ if (!geometry.hasAttribute('normal')) geometry.computeVertexNormals();
78
+ if (matrix !== null) geometry.applyMatrix4(matrix);
79
+ if (storageError !== undefined) {
80
+ const positions = output[0] ?? [];
81
+ if (matrix === null) storageError(floatPositionError(positions));
82
+ else {
83
+ const stored = geometry.getAttribute('position'), point = new Vector3();
84
+ let error = 0;
85
+ for (let storedVertex = 0; storedVertex < stored.count; storedVertex++) {
86
+ point.fromArray(positions, storedVertex * 3).applyMatrix4(matrix);
87
+ error = Math.max(error, Math.hypot(point.x - stored.getX(storedVertex), point.y - stored.getY(storedVertex), point.z - stored.getZ(storedVertex)));
88
+ }
89
+ storageError(error);
90
+ }
91
+ }
92
+ return geometry;
93
+ }
94
+
95
+ /** RM8.1: a tile's position grid. One power-of-two step for every tile (1/512 m, coarsened only where a tile is too
96
+ * tall for 16 bits) and an origin on that grid, so a point two tiles share quantizes to the same place in both. */
97
+ export interface TileGrid { origin: readonly [number, number, number]; step: number }
98
+ export function tileGrid(box: Box3): TileGrid {
99
+ const centre = box.getCenter(new Vector3()).toArray(), lo = box.min.toArray(), hi = box.max.toArray();
100
+ for (let step = 1 / 512; step <= 1; step *= 2) {
101
+ const origin = centre.map(value => Math.round(value / step) * step) as [number, number, number];
102
+ if (origin.every((o, axis) => Math.abs((lo[axis] ?? 0) - o) / step <= 32767 && Math.abs((hi[axis] ?? 0) - o) / step <= 32767)) return { origin, step };
103
+ }
104
+ throw new Error('World tile is too large for a 16-bit position grid');
105
+ }
106
+ /** RM8.1e: the grid of a primitive whose graph reads its model-space position (the open plots' hologram, turned about
107
+ * its model origin): origin pinned at that model origin, so the graph's model space is the authored metres times one
108
+ * uniform scale (1 / step) and a turn about the origin, a linear map, comes out the same once the node scales back. */
109
+ export function modelGrid(box: Box3): TileGrid {
110
+ const lo = box.min.toArray(), hi = box.max.toArray();
111
+ for (let step = 1 / 512; step <= 1; step *= 2) {
112
+ if (lo.every(v => Math.abs(v) / step <= 32767) && hi.every(v => Math.abs(v) / step <= 32767)) return { origin: [0, 0, 0], step };
113
+ }
114
+ throw new Error('World primitive is too far from its model origin for a 16-bit position grid');
115
+ }
116
+ /** The node transform that dequantizes a grid's Int16 positions. */
117
+ export function tileGridTransform(grid: TileGrid): Matrix4 {
118
+ return new Matrix4().compose(new Vector3(...grid.origin), new Quaternion(), new Vector3(grid.step, grid.step, grid.step));
119
+ }
120
+
121
+ /** RM8.1: a tile primitive's geometry for the wire. Normals become normalized Int8 and colours normalized Uint16
122
+ * (KHR_mesh_quantization, written by staticGlb's `quantizedChannels`; normals within ~0.5 degree, colours within
123
+ * 1/65535); then every vertex whose channels are all equal is welded into one (uvs and tangents stay exact float32)
124
+ * under a 16-bit index when the vertices fit, a 32-bit one otherwise. A clipped tile was a triangle soup of three
125
+ * float32 vertices a triangle. With a `grid`, positions become unnormalized Int16 on it (within half its step),
126
+ * colours Uint8 (within 1/510), and vertices and triangles are reordered for the vertex cache and for meshopt. */
127
+ export function compactTileGeometry(source: BufferGeometry, grid?: TileGrid): BufferGeometry {
128
+ const keys = Object.keys(source.attributes).sort(), index = source.getIndex(), count = index === null ? source.getAttribute('position').count : index.count;
129
+ const colour = grid === undefined ? 65535 : 255;
130
+ const rows = keys.map((key) => {
131
+ const attribute = source.getAttribute(key), width = attribute.itemSize;
132
+ const quantize = key === 'normal' ? (v: number) => Math.max(-127, Math.min(127, Math.round(v * 127)))
133
+ : key === 'color' ? (v: number) => Math.max(0, Math.min(colour, Math.round(v * colour)))
134
+ : key === 'position' && grid !== undefined ? (v: number, c: number) => {
135
+ const q = Math.round((v - (grid.origin[c] ?? 0)) / grid.step);
136
+ if (Math.abs(q) > 32767) throw new Error('World tile position outside its 16-bit grid'); return q;
137
+ } : null;
138
+ return { key, width, quantize, read: (vertex: number, component: number) => attribute.getComponent(vertex, component), out: [] as number[] };
139
+ });
140
+ const seen = new Map<string, number>(), order: number[] = [];
141
+ const heads = new Map<number, number>(), links: number[] = [];
142
+ const sample = new Float64Array(1), words = new Uint32Array(sample.buffer);
143
+ let numeric = rows.every(row => Number.isSafeInteger(row.width) && row.width > 0), next = 0;
144
+ const hashValues = (values: readonly number[]): number | undefined => {
145
+ let hash = 2166136261;
146
+ for (const value of values) {
147
+ if (typeof value !== 'number') return undefined;
148
+ // String keys equate both zeros and every NaN payload.
149
+ if (value === (value | 0)) hash = Math.imul(hash ^ value, 16777619);
150
+ else if (Number.isNaN(value)) { hash = Math.imul(hash, 16777619); hash = Math.imul(hash ^ 0x7ff80000, 16777619); }
151
+ else {
152
+ sample[0] = value === 0 ? 0 : value;
153
+ hash = Math.imul(hash ^ (words[0] ?? 0), 16777619);
154
+ hash = Math.imul(hash ^ (words[1] ?? 0), 16777619);
155
+ }
156
+ }
157
+ hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b);
158
+ hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);
159
+ return (hash ^ (hash >>> 16)) >>> 0;
160
+ };
161
+ const sameValues = (vertex: number, values: readonly number[]): boolean => {
162
+ let offset = 0;
163
+ for (const row of rows) for (let component = 0; component < row.width; component++) {
164
+ const value = values[offset++], previous = row.out[vertex * row.width + component];
165
+ if (value !== previous && !(typeof value === 'number' && typeof previous === 'number' && Number.isNaN(value) && Number.isNaN(previous))) return false;
166
+ }
167
+ return true;
168
+ };
169
+ const useStrings = (): void => {
170
+ numeric = false; heads.clear(); links.length = 0;
171
+ for (let vertex = 0; vertex < next; vertex++) {
172
+ const values = rows.flatMap(row => row.out.slice(vertex * row.width, (vertex + 1) * row.width));
173
+ seen.set(values.join(','), vertex);
174
+ }
175
+ };
176
+ for (let corner = 0; corner < count; corner++) {
177
+ const vertex = index === null ? corner : index.getX(corner), values: number[] = [];
178
+ for (const row of rows) for (let c = 0; c < row.width; c++) { const v = row.read(vertex, c); values.push(row.quantize === null ? v : row.quantize(v, c)); }
179
+ let at: number | undefined, hash = 0, key = '';
180
+ if (numeric) {
181
+ const found = hashValues(values);
182
+ if (found === undefined) useStrings();
183
+ else {
184
+ hash = found;
185
+ let candidate = heads.get(hash), visited = 0;
186
+ while (candidate !== undefined && candidate >= 0) {
187
+ if (sameValues(candidate, values)) { at = candidate; break; }
188
+ // Preserve bounded lookup cost for adversarial buckets via the original map.
189
+ if (++visited >= 16) { useStrings(); break; }
190
+ candidate = links[candidate];
191
+ }
192
+ }
193
+ }
194
+ if (!numeric) { key = values.join(','); at = seen.get(key); }
195
+ if (at === undefined) {
196
+ at = next++;
197
+ if (numeric) { links[at] = heads.get(hash) ?? -1; heads.set(hash, at); }
198
+ else seen.set(key, at);
199
+ let offset = 0;
200
+ for (const row of rows) { row.out.push(...values.slice(offset, offset + row.width)); offset += row.width; }
201
+ }
202
+ order.push(at);
203
+ }
204
+ // with a grid: triangles in vertex-cache order, vertices in first-use order (meshopt's codecs compress both far better)
205
+ const indices = Uint32Array.from(order), remap = grid === undefined ? null : MeshoptEncoder.reorderMesh(indices, true, true)[0];
206
+ const output = new BufferGeometry();
207
+ for (const row of rows) {
208
+ let values = row.out;
209
+ if (remap !== null) {
210
+ const moved = Array.from({ length: values.length }, () => 0), map = remap;
211
+ for (let old = 0; old < next; old++) for (let c = 0; c < row.width; c++) moved[(map[old] ?? 0) * row.width + c] = values[old * row.width + c] ?? 0;
212
+ values = moved;
213
+ }
214
+ output.setAttribute(row.key, row.key === 'normal' ? new BufferAttribute(Int8Array.from(values), row.width, true)
215
+ : row.key === 'color' ? new BufferAttribute(grid === undefined ? Uint16Array.from(values) : Uint8Array.from(values), row.width, true)
216
+ : row.key === 'position' && grid !== undefined ? new BufferAttribute(Int16Array.from(values), row.width)
217
+ : new Float32BufferAttribute(values, row.width));
218
+ }
219
+ output.setIndex(new BufferAttribute(next <= 65535 ? Uint16Array.from(indices) : indices, 1));
220
+ return output;
221
+ }
222
+
223
+ /** Combine same-material primitives into one draw without changing their authored channels. */
224
+ export function mergeWorldGeometry(parts: readonly BufferGeometry[]): BufferGeometry {
225
+ const first = parts[0]; if (first === undefined) throw new Error('World merge needs geometry');
226
+ const keys = Object.keys(first.attributes).sort(), output = new BufferGeometry();
227
+ for (const part of parts) if (Object.keys(part.attributes).sort().join('/') !== keys.join('/')) throw new Error('World material primitives have incompatible vertex channels');
228
+ for (const key of keys) {
229
+ const width = first.getAttribute(key).itemSize, values: number[] = [];
230
+ for (const part of parts) {
231
+ const row = part.getAttribute(key); if (row.itemSize !== width) throw new Error('World material vertex channel width differs');
232
+ for (let vertex = 0; vertex < row.count; vertex++) for (let c = 0; c < width; c++) values.push(row.getComponent(vertex, c));
233
+ }
234
+ output.setAttribute(key, new Float32BufferAttribute(values, width));
235
+ }
236
+ return output;
237
+ }