@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,224 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- The build measures each file's wire bytes with the deploy's brotli.
2
+ import { brotliCompressSync, constants } from 'node:zlib';
3
+ import { WebIO, type Accessor, type Document, type Mesh, type Node } from '@gltf-transform/core';
4
+ import { ALL_EXTENSIONS, KHRMeshQuantization, type InstancedMesh } from '@gltf-transform/extensions';
5
+ import { MeshoptDecoder } from 'meshoptimizer';
6
+ import { compressGlb } from './glbCompression';
7
+ import { hashImmutableBytes } from '../immutable';
8
+ import { nameBlob, nameMeshoptBlob, type BlobOptions, type NamedBlob } from '../blobs';
9
+ import { entryFootprints, obstructsEntry } from '@wildshard/format/entryGeometry';
10
+ import type { ShardEntryways } from '@wildshard/format/entryways';
11
+ import { visitGlbTriangles } from '@wildshard/format/product';
12
+
13
+ /** The brotli size a phone pays for a file over the wire: the deploy's own encoding, quality 3 (Vercel's responses match it
14
+ * byte for byte). */
15
+ export function brotliBytes(bytes: Uint8Array): number {
16
+ return brotliCompressSync(bytes, { params: { [constants.BROTLI_PARAM_QUALITY]: 3, [constants.BROTLI_PARAM_SIZE_HINT]: bytes.length } }).length;
17
+ }
18
+
19
+ const quantized = (accessor: Accessor, array: Int16Array<ArrayBuffer> | Int8Array<ArrayBuffer> | Uint8Array<ArrayBuffer>): void => {
20
+ accessor.setArray(array).setNormalized(true);
21
+ };
22
+
23
+ /** compactClearGlb's picks this process has made (null: the input was kept) */
24
+ const cleared = new Map<string, Uint8Array | null>();
25
+ /** compactPhoneGlb's picks this process has made (null: the input was kept) */
26
+ const compacted = new Map<string, Uint8Array | null>();
27
+
28
+ /**
29
+ * iPhone downloads I3: a phone-tier baked model with 16-bit positions, 8-bit normals and 8-bit colours
30
+ * (KHR_mesh_quantization), with or without meshopt (EXT_meshopt_compression): whichever of the input, the quantized
31
+ * file and the packed one has the fewest brotli bytes ships. The positions sit on the mesh's own grid: a uniform scale and a translation on its node dequantize
32
+ * them (`createOwnedGeometry` bakes that node transform back into float positions). An instanced node
33
+ * (EXT_mesh_gpu_instancing) keeps its identity transform: the grid folds into every instance's translation and scale
34
+ * instead (the instance applies after the vertex). A meshopt input is decoded first and competes as it was. Only a file
35
+ * with exactly one mesh on one identity-space node, float positions and no skin, morph target or animation is compacted
36
+ * (channels already quantized stay as they are); every other file, and every channel but POSITION / NORMAL / COLOR_0, passes through unchanged.
37
+ * `each`: a bank of named meshes, each on its own root identity node (a rest pool), puts every node on its own grid.
38
+ */
39
+ export async function compactPhoneGlb(input: Uint8Array, options: { readonly contain?: true; readonly each?: true } = {}): Promise<Uint8Array> {
40
+ // the pick is a pure function of the bytes: a producer that prepares its output again (a test's second prepareOutput, a
41
+ // rebuild in one process) reuses it instead of re-running the meshopt and brotli trials; a hit hands back its own copy
42
+ const key = `${options.contain === true ? 'contain' : 'grid'}${options.each === true ? '-each' : ''}:${hashImmutableBytes(input)}`, known = compacted.get(key);
43
+ if (known === null) return input;
44
+ if (known !== undefined) return Uint8Array.from(known);
45
+ const result = await compactOnce(input, options);
46
+ compacted.set(key, result === input ? null : Uint8Array.from(result));
47
+ return result;
48
+ }
49
+
50
+ /** Put one root mesh node on its own uniform grid (16-bit positions, Int8 normals, Uint8 colours in [0, 1]); false,
51
+ * changing nothing, when its mesh cannot be (no float vec3 positions, morph targets, or instances that will not fold). */
52
+ function gridNode(doc: Document, node: Node, mesh: Mesh, contain: boolean): boolean {
53
+ const primitives = mesh.listPrimitives();
54
+ if (primitives.length === 0 || primitives.some(primitive => primitive.listTargets().length > 0)) return false;
55
+ // one uniform grid for the whole mesh (a non-uniform scale would bend its normals)
56
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity], point: number[] = [];
57
+ for (const primitive of primitives) {
58
+ const position = primitive.getAttribute('POSITION');
59
+ if (position === null || position.getComponentType() !== 5126 || position.getElementSize() !== 3) return false;
60
+ // Unnormalized float storage is already decoded; normalized channels keep getElement.
61
+ const values = position.getNormalized() ? null : position.getArray(), count = position.getCount();
62
+ for (let i = 0; i < count; i++) {
63
+ if (values === null) position.getElement(i, point);
64
+ for (let axis = 0; axis < 3; axis++) { const value = (values === null ? point[axis] : values[i * 3 + axis]) ?? 0; min[axis] = Math.min(min[axis] ?? 0, value); max[axis] = Math.max(max[axis] ?? 0, value); }
65
+ }
66
+ }
67
+ const mid = (axis: number): number => ((min[axis] ?? 0) + (max[axis] ?? 0)) / 2;
68
+ const centre: [number, number, number] = [mid(0), mid(1), mid(2)];
69
+ const half = Math.max(...[0, 1, 2].map(axis => ((max[axis] ?? 0) - (min[axis] ?? 0)) / 2), 1e-6);
70
+ const instances = node.getExtension<InstancedMesh>('EXT_mesh_gpu_instancing');
71
+ if (instances !== null && !foldGrid(doc, instances, centre, half)) return false;
72
+ const done = new Set<Accessor>();
73
+ for (const primitive of primitives) {
74
+ const position = primitive.getAttribute('POSITION'), normal = primitive.getAttribute('NORMAL'), colour = primitive.getAttribute('COLOR_0');
75
+ if (position !== null && !done.has(position)) {
76
+ const count = position.getCount(), values = position.getNormalized() ? null : position.getArray();
77
+ const out = new Int16Array(count * 3);
78
+ for (let i = 0; i < count; i++) {
79
+ if (values === null) position.getElement(i, point);
80
+ for (let axis = 0; axis < 3; axis++) {
81
+ let q = Math.round((((values === null ? point[axis] : values[i * 3 + axis]) ?? 0) - (centre[axis] ?? 0)) / half * 32767);
82
+ // `contain`: a grid step never carries a vertex past the mesh's own bounds (a placed tile's cell edge, ±250 m)
83
+ if (contain) {
84
+ const at = (step: number): number => step / 32767 * half + (centre[axis] ?? 0);
85
+ while (q > -32767 && at(q) > (max[axis] ?? 0)) q--;
86
+ while (q < 32767 && at(q) < (min[axis] ?? 0)) q++;
87
+ }
88
+ out[i * 3 + axis] = q;
89
+ }
90
+ }
91
+ quantized(position, out); done.add(position);
92
+ }
93
+ if (normal !== null && !done.has(normal) && normal.getComponentType() === 5126 && normal.getElementSize() === 3) {
94
+ const count = normal.getCount(), values = normal.getNormalized() ? null : normal.getArray();
95
+ const out = new Int8Array(count * 3);
96
+ for (let i = 0; i < count; i++) {
97
+ if (values === null) normal.getElement(i, point);
98
+ for (let c = 0; c < 3; c++) out[i * 3 + c] = Math.round(Math.max(-1, Math.min(1, (values === null ? point[c] : values[i * 3 + c]) ?? 0)) * 127);
99
+ }
100
+ quantized(normal, out); done.add(normal);
101
+ }
102
+ if (colour !== null && !done.has(colour) && colour.getComponentType() === 5126) {
103
+ const width = colour.getElementSize(), values = colour.getArray();
104
+ if (values !== null && Array.from(values).every(value => value >= 0 && value <= 1)) {
105
+ const out = new Uint8Array(colour.getCount() * width);
106
+ for (let i = 0; i < out.length; i++) out[i] = Math.round((values[i] ?? 0) * 255);
107
+ quantized(colour, out); done.add(colour);
108
+ }
109
+ }
110
+ }
111
+ if (instances === null) node.setTranslation(centre).setScale([half, half, half]);
112
+ // a native-attribute file (its intake restores each channel's declared storage) declares the new storage too
113
+ const extras = node.getExtras(), native: unknown = extras['nativeAttributes'];
114
+ if (typeof native === 'object' && native !== null) {
115
+ const stored: Readonly<Record<string, readonly [string, boolean]>> = { POSITION: ['Int16Array', true], NORMAL: ['Int8Array', true], COLOR_0: ['Uint8Array', true] };
116
+ const rows = Object.fromEntries(Object.entries(native).map(([name, row]: [string, unknown]) => {
117
+ if (typeof row !== 'object' || row === null || !('semantic' in row) || typeof row.semantic !== 'string') return [name, row];
118
+ const accessor = primitives[0]?.getAttribute(row.semantic), next = stored[row.semantic];
119
+ return [name, accessor !== null && accessor !== undefined && done.has(accessor) && next !== undefined ? { ...row, storage: next[0], normalized: next[1] } : row];
120
+ }));
121
+ node.setExtras({ ...extras, nativeAttributes: rows });
122
+ }
123
+ return true;
124
+ }
125
+
126
+ async function compactOnce(input: Uint8Array, options: { readonly contain?: true; readonly each?: true }): Promise<Uint8Array> {
127
+ await MeshoptDecoder.ready;
128
+ const io = new WebIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
129
+ const doc = await io.readBinary(Uint8Array.from(input)), root = doc.getRoot();
130
+ const used = new Set(root.listExtensionsUsed().map(extension => extension.extensionName));
131
+ const nodes = root.listNodes().filter(node => node.getMesh() !== null), node = nodes[0], mesh = node?.getMesh();
132
+ if (root.listSkins().length > 0 || root.listAnimations().length > 0 || node === undefined || mesh === null || mesh === undefined) return input;
133
+ if (options.each !== true && (nodes.length !== 1 || root.listMeshes().length !== 1
134
+ || node.getMatrix().some((value, i) => value !== (i % 5 === 0 ? 1 : 0)) || node.getParentNode() !== null)) return input;
135
+ if (options.each === true) {
136
+ // `each`: every mesh on its own root identity node, each node gridded alone (a rest-pool bank of named shapes)
137
+ const meshes = new Set(nodes.map(row => row.getMesh()));
138
+ if (meshes.size !== nodes.length || nodes.some(row => row.getParentNode() !== null || row.getExtension('EXT_mesh_gpu_instancing') !== null
139
+ || row.getMatrix().some((value, i) => value !== (i % 5 === 0 ? 1 : 0)))) return input;
140
+ for (const row of nodes) { const own = row.getMesh(); if (own === null || !gridNode(doc, row, own, options.contain === true)) return input; }
141
+ } else if (!gridNode(doc, node, mesh, options.contain === true)) return input;
142
+ if (!used.has('KHR_mesh_quantization')) doc.createExtension(KHRMeshQuantization).setRequired(true);
143
+ // a meshopt input was decoded on read: the quantized file is written plain, and packed again below
144
+ for (const extension of root.listExtensionsUsed()) if (extension.extensionName === 'EXT_meshopt_compression') extension.dispose();
145
+ // the quantized file with and without meshopt: a triangle soup often packs better under brotli alone
146
+ const plain = await io.writeBinary(doc), packed = compressGlb(plain);
147
+ const sizes = [input, plain, packed].map(bytes => ({ bytes, size: brotliBytes(bytes) }));
148
+ return sizes.reduce((best, row) => row.size < best.size ? row : best).bytes;
149
+ }
150
+
151
+ /** Name a built GLB the way a phone-geometry producer ships it (I3): `compactPhoneGlb`'s pick when it compacts the file,
152
+ * else the lossless meshopt pick of a `meshopt: true` source (`nameMeshoptBlob`). */
153
+ export async function nameCompactBlob(name: string, bytes: Uint8Array, options: BlobOptions = {}): Promise<NamedBlob> {
154
+ const compact = await compactPhoneGlb(bytes);
155
+ return compact === bytes ? nameMeshoptBlob(name, bytes, options) : nameBlob(name, 'glb', compact, options);
156
+ }
157
+
158
+ /** `compactPhoneGlb` for a placed tile beside the cell's entryways: rounding onto the grid may lift a road-height vertex by
159
+ * under half a step, which the entryway clearance check (format/entryClearance) rightly refuses, so a tile whose compact
160
+ * triangles obstruct an entry footprint its exact ones did not keeps its exact bytes. Its grid never carries a vertex past
161
+ * the tile's own bounds (`contain`), which the cell's draw-bounds check holds to ±250 m. */
162
+ export async function compactClearGlb(input: Uint8Array, entryways: readonly Pick<ShardEntryways[number], 'edge' | 'width'>[]): Promise<Uint8Array> {
163
+ // the pick (and its two triangle walks) is a pure function of the bytes and the entryways: kept for the process, as
164
+ // compactPhoneGlb keeps its own (a producer that prepares its output again reuses it; a hit hands back its own copy)
165
+ const key = `${hashImmutableBytes(input)}:${JSON.stringify(entryways.map(row => [row.edge, row.width]))}`, known = cleared.get(key);
166
+ if (known === null) return input;
167
+ if (known !== undefined) return Uint8Array.from(known);
168
+ const compact = await compactPhoneGlb(input, { contain: true });
169
+ if (compact === input) { cleared.set(key, null); return input; }
170
+ const rectangles = entryFootprints(entryways);
171
+ const obstructs = (bytes: Uint8Array): boolean => {
172
+ let hit = false;
173
+ visitGlbTriangles(bytes, triangle => { if (!hit && rectangles.some(rect => obstructsEntry(triangle, rect))) hit = true; });
174
+ return hit;
175
+ };
176
+ const result = obstructs(compact) && !obstructs(input) ? input : compact;
177
+ cleared.set(key, result === input ? null : Uint8Array.from(result));
178
+ return result;
179
+ }
180
+
181
+ /** `nameCompactBlob` over a set of shapes: one hash has one logical name (emitNamedBlobs), so a shape whose compacted bytes
182
+ * equal an earlier one's (two shapes that differ only below the grid step) keeps its meshopt pick instead. */
183
+ export async function nameCompactBlobs(shapes: readonly (readonly [string, Uint8Array])[]): Promise<NamedBlob[]> {
184
+ const named = await Promise.all(shapes.map(([name, bytes]) => nameCompactBlob(name, bytes))), seen = new Set<string>();
185
+ const out: NamedBlob[] = [];
186
+ for (const [i, blob] of named.entries()) {
187
+ const shape = shapes[i];
188
+ if (shape === undefined) throw new Error('Missing compact shape');
189
+ if (seen.has(blob.file.hash)) out.push(await nameMeshoptBlob(shape[0], shape[1]));
190
+ else { seen.add(blob.file.hash); out.push(blob); }
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /** Fold a grid (`centre`, uniform `half`) into each instance: T' = T + R(S * centre), S' = S * half, so that
196
+ * T' R S' q = T R S (half q + centre). Refuses (false) instance rows that are not plain float TRS. */
197
+ function foldGrid(doc: Document, instances: InstancedMesh, centre: readonly [number, number, number], half: number): boolean {
198
+ const t = instances.getAttribute('TRANSLATION'), r = instances.getAttribute('ROTATION'), s = instances.getAttribute('SCALE');
199
+ const rows = [t, r, s].filter((row): row is Accessor => row !== null);
200
+ const count = rows[0]?.getCount() ?? 0;
201
+ if (count === 0 || rows.some(row => row.getComponentType() !== 5126 || row.getCount() !== count)) return false;
202
+ const translation = new Float32Array(count * 3), scale = new Float32Array(count * 3), at: number[] = [], q: number[] = [], k: number[] = [];
203
+ for (let i = 0; i < count; i++) {
204
+ if (t === null) at.splice(0, 3, 0, 0, 0); else t.getElement(i, at);
205
+ if (r === null) q.splice(0, 4, 0, 0, 0, 1); else r.getElement(i, q);
206
+ if (s === null) k.splice(0, 3, 1, 1, 1); else s.getElement(i, k);
207
+ const [x, y, z, w] = [q[0] ?? 0, q[1] ?? 0, q[2] ?? 0, q[3] ?? 1];
208
+ const v = [0, 1, 2].map(axis => (k[axis] ?? 1) * (centre[axis] ?? 0));
209
+ const [vx, vy, vz] = [v[0] ?? 0, v[1] ?? 0, v[2] ?? 0];
210
+ // v + 2 q.xyz x (q.xyz x v + w v)
211
+ const cx = y * vz - z * vy + w * vx, cy = z * vx - x * vz + w * vy, cz = x * vy - y * vx + w * vz;
212
+ const rotated = [vx + 2 * (y * cz - z * cy), vy + 2 * (z * cx - x * cz), vz + 2 * (x * cy - y * cx)];
213
+ for (let axis = 0; axis < 3; axis++) {
214
+ translation[i * 3 + axis] = (at[axis] ?? 0) + (rotated[axis] ?? 0);
215
+ scale[i * 3 + axis] = (k[axis] ?? 1) * half;
216
+ }
217
+ }
218
+ const buffer = doc.getRoot().listBuffers()[0] ?? null;
219
+ for (const [name, array, previous] of [['TRANSLATION', translation, t], ['SCALE', scale, s]] as const) {
220
+ instances.setAttribute(name, doc.createAccessor().setType('VEC3').setArray(array).setBuffer(buffer));
221
+ if (previous !== null && previous.listParents().length <= 1) previous.dispose();
222
+ }
223
+ return true;
224
+ }
@@ -0,0 +1,119 @@
1
+ /** Portable AssemblyScript compiler and structural Binaryen metering, pinned by SDK dependencies. */
2
+ import binaryen from 'binaryen';
3
+ import { loadAssemblyScriptCompiler } from '../assemblyscriptCompiler.mjs';
4
+ import type { AssemblyScriptMemo } from './assemblyscriptMemoPort';
5
+
6
+ interface Compiler { main: (args: string[], options: { readFile: (name: string) => string | null; writeFile: (name: string, contents: string | Uint8Array) => void }) => Promise<{ error: Error | null; stderr?: { toString: () => string } }> }
7
+ function isCompiler(value: unknown): value is Compiler { return typeof value === 'object' && value !== null && 'main' in value && typeof value.main === 'function'; }
8
+ type Form = string | Form[];
9
+ function isForm(value: Form | undefined): value is Form[] { return Array.isArray(value); }
10
+
11
+ const FEATURES = binaryen.Features.MutableGlobals | binaryen.Features.SignExt | binaryen.Features.NontrappingFPToInt | binaryen.Features.BulkMemory;
12
+ /** Tokenise Binaryen's own WAT output, keeping quoted data opaque. */
13
+ function tokens(text: string): string[] { return text.match(/"(?:\\.|[^"\\])*"|[()]|[^\s()]+/g) ?? []; }
14
+
15
+ function tree(words: string[], cursor: { pos: number }): Form[] {
16
+ if (words[cursor.pos++] !== '(') throw new Error('Invalid Binaryen text');
17
+ const result: Form[] = [];
18
+ while (words[cursor.pos] !== ')') {
19
+ if (cursor.pos >= words.length) throw new Error('Truncated Binaryen text');
20
+ if (words[cursor.pos] === '(') result.push(tree(words, cursor));
21
+ else { const word = words[cursor.pos++]; if (word === undefined) throw new Error('Truncated Binaryen text'); result.push(word); }
22
+ }
23
+ cursor.pos++; return result;
24
+ }
25
+
26
+ function wat(value: Form): string { return Array.isArray(value) ? `(${value.map(wat).join(' ')})` : value; }
27
+
28
+ function finite(node: Form): Form {
29
+ if (!Array.isArray(node)) return node;
30
+ const rewritten = node.map(finite), op = rewritten[0];
31
+ if (typeof op === 'string' && /^f(?:32|64)\./.test(op) && !/^f(?:32|64)\.(?:store|eq|ne|lt|gt|le|ge)$/.test(op)) return ['call', op.startsWith('f32.') ? '$__finite32' : '$__finite64', rewritten];
32
+ return rewritten;
33
+ }
34
+
35
+ function loops(node: Form, cost: number): void {
36
+ if (!Array.isArray(node)) return;
37
+ for (const child of node) loops(child, cost);
38
+ if (node[0] === 'loop') {
39
+ let at = typeof node[1] === 'string' ? 2 : 1;
40
+ if (isForm(node[at]) && node[at]?.[0] === 'result') at++;
41
+ node.splice(at, 0, ['call', '$__meter_fuel', ['i32.const', String(cost)]]);
42
+ }
43
+ }
44
+ /** No optimization is run after instrumentation: admission verifies these exact structural guards. */
45
+ export function instrumentScript(bytes: Uint8Array): Uint8Array {
46
+ const module = binaryen.readBinary(bytes);
47
+ try {
48
+ module.setFeatures(FEATURES);
49
+ if (!module.validate()) throw new Error('Unsupported Wasm features');
50
+ const form = tree(tokens(module.emitText()), { pos: 0 });
51
+ const originals = form.filter((n) => Array.isArray(n) && n[0] === 'func');
52
+ const wrappers: Form[][] = [];
53
+ for (let index = 0; index < originals.length; index++) {
54
+ const fn = originals[index];
55
+ if (!Array.isArray(fn) || typeof fn[1] !== 'string') throw new Error('Unnamed function');
56
+ const name = fn[1], impl = `$__impl_${index}`;
57
+ const cost = bytes.length * 4 + 128 * originals.length + 1024;
58
+ for (let i = 2; i < fn.length; i++) { const part = fn[i]; if (part !== undefined) fn[i] = finite(part); }
59
+ loops(fn, cost);
60
+ const params = fn.filter((n) => Array.isArray(n) && n[0] === 'param');
61
+ const results = fn.filter((n) => Array.isArray(n) && n[0] === 'result');
62
+ let at = 2;
63
+ while (isForm(fn[at]) && ['param', 'result', 'local', 'type'].includes(String(fn[at]?.[0]))) at++;
64
+ fn.splice(at, 0, ['call', '$__meter_fuel', ['i32.const', String(cost)]]);
65
+ fn[1] = impl;
66
+ const wrapper: Form[] = ['func', name, ...params, ...results];
67
+ const types = params.flatMap((p) => Array.isArray(p) ? p.slice(1).filter((n) => typeof n === 'string' && !n.startsWith('$')) : []);
68
+ const args = types.map((_, i) => ['local.get', String(i)]);
69
+ const call = ['call', impl, ...args];
70
+ if (results.length > 0) {
71
+ const result = results[0]; if (!Array.isArray(result) || typeof result[1] !== 'string') throw new Error('Invalid result');
72
+ wrapper.push(['local', result[1]]);
73
+ wrapper.push(['call', '$__meter_enter'], ['local.set', String(types.length), call], ['call', '$__meter_leave'], ['local.get', String(types.length)]);
74
+ } else wrapper.push(['call', '$__meter_enter'], call, ['call', '$__meter_leave']);
75
+ wrappers.push(wrapper);
76
+ }
77
+ form.splice(1, 0,
78
+ ['import', '"env"', '"enter"', ['func', '$__meter_enter']],
79
+ ['import', '"env"', '"leave"', ['func', '$__meter_leave']],
80
+ ['import', '"env"', '"fuel"', ['func', '$__meter_fuel', ['param', 'i32']]],
81
+ ['import', '"env"', '"finite32"', ['func', '$__finite32', ['param', 'f32'], ['result', 'f32']]],
82
+ ['import', '"env"', '"finite64"', ['func', '$__finite64', ['param', 'f64'], ['result', 'f64']]],
83
+ );
84
+ for (let i = 0; i < module.getNumGlobals(); i++) {
85
+ const global = binaryen.getGlobalInfo(module.getGlobalByIndex(i));
86
+ if (global.mutable) form.push(['export', `"__state_${i}"`, ['global', `$${global.name}`]]);
87
+ }
88
+ form.push(...wrappers);
89
+ const metered = binaryen.parseText(wat(form));
90
+ try { metered.setFeatures(FEATURES); if (!metered.validate()) throw new Error('Invalid instrumented module'); return metered.emitBinary(); }
91
+ finally { metered.dispose(); }
92
+ } finally { module.dispose(); }
93
+ }
94
+ /** Build source in-memory; no native compiler or Rust toolchain. ABI/compiler versions are pinned in package.json.
95
+ */
96
+ export async function compileScript(source: string, options: { abi?: 0 | 1; maximumPages?: number; sources?: Readonly<Record<string, string>>; compileMemo?: AssemblyScriptMemo } = {}): Promise<Uint8Array> {
97
+ const maximumPages = options.maximumPages ?? (options.abi === 1 ? 1 : 64);
98
+ const ceiling = options.abi === 1 ? 4 : 64;
99
+ if (!Number.isSafeInteger(maximumPages) || maximumPages < 1 || maximumPages > ceiling) throw new Error(`Script maximumPages must be 1..${ceiling}`);
100
+ const sources = new Map(Object.entries(options.sources ?? {}));
101
+ if (sources.size > 64 || [...sources].some(([name, text]) => name === 'main.ts' || !/^(?:[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\.ts$/u.test(name) || typeof text !== 'string')) throw new Error('Invalid virtual AssemblyScript sources');
102
+ // asc's declaration bundle globally changes Array.at to return T, unsound in host JS.
103
+ // Keep its portable ambient declarations inside the author compiler, not the host type program.
104
+ const compiler = await loadAssemblyScriptCompiler();
105
+ if (!isCompiler(compiler)) throw new Error('Invalid pinned AssemblyScript compiler');
106
+ const args = ['main.ts', '--outFile', 'main.wasm', '--runtime', 'stub', '--importMemory', '--initialMemory', String(options.abi === 1 ? maximumPages : 1), '--maximumMemory', String(maximumPages), '--exportStart', '__start', '--disable', 'bulk-memory', '-O3'];
107
+ const generate = async (): Promise<Uint8Array> => {
108
+ let bytes: Uint8Array = new Uint8Array();
109
+ const result = await compiler.main(args, {
110
+ readFile: (name) => name === 'main.ts' ? source : sources.get(name) ?? null,
111
+ writeFile: (name, contents) => { if (name === 'main.wasm' && contents instanceof Uint8Array) bytes = contents; },
112
+ });
113
+ if (result.error || bytes.length === 0) throw new Error(`AssemblyScript compile failed: ${result.error?.message ?? 'no output'}${result.stderr === undefined ? '' : `\n${result.stderr.toString()}`}`);
114
+ return bytes;
115
+ };
116
+ const bytes = options.compileMemo === undefined ? await generate()
117
+ : await options.compileMemo(args, new Map([['main.ts', source], ...sources]), generate);
118
+ return instrumentScript(bytes);
119
+ }
@@ -0,0 +1,75 @@
1
+ /** Explicit ABI v2 compiler; v0/v1 callers and their module hashes never enter
2
+ * this path. No optimization runs after the verified finite/fuel passes. */
3
+ import binaryen from 'binaryen';
4
+ import { loadAssemblyScriptCompiler } from '../assemblyscriptCompiler.mjs';
5
+ import type { AssemblyScriptMemo } from './assemblyscriptMemoPort';
6
+ import { instrumentV2Finite } from './v2Finite';
7
+ import { instrumentV2Fuel } from './v2Fuel';
8
+ import type { V2Lane } from '@wildshard/format/scriptFuelV2';
9
+ import { readV2Module } from '@wildshard/format/scriptModuleV2';
10
+ import { admitScriptV2,SCRIPT_V2_REVISIONS } from '@wildshard/format/scriptAdmissionV2';
11
+
12
+ interface Compiler { main: (args: string[],options: { readFile: (name: string) => string | null; writeFile: (name: string,contents: string | Uint8Array) => void }) => Promise<{ error: Error | null; stderr?: { toString: () => string } }> }
13
+ function compiler(value: unknown): value is Compiler { return typeof value === 'object' && value !== null && 'main' in value && typeof value.main === 'function'; }
14
+ function localStartAndAbort(bytes: Uint8Array): Uint8Array {
15
+ const image = binaryen.readBinary(bytes);
16
+ try {
17
+ image.setFeatures(binaryen.Features.MutableGlobals | binaryen.Features.SignExt | binaryen.Features.NontrappingFPToInt);
18
+ const imports = Array.from({ length: image.getNumFunctions() },(_,i) => binaryen.getFunctionInfo(image.getFunctionByIndex(i))).filter(fn => fn.body === 0);
19
+ for (const fn of imports) {
20
+ if (fn.module === 'env' && fn.base === '__v2_fuel' && fn.results === binaryen.i32 && binaryen.expandType(fn.params).length === 0) {
21
+ if (Array.from({ length: image.getNumExports() },(_,i) => binaryen.getExportInfo(image.getExportByIndex(i))).some(value => value.name === '__v2_fuel')) throw new Error('Reserved v2 fuel intrinsic export');
22
+ // The opaque authoring marker survives AS optimization. The meter
23
+ // replaces this local placeholder with a private-global read and
24
+ // removes the marker export before executable admission.
25
+ image.removeFunction(fn.name);image.addFunction(fn.name,fn.params,fn.results,[],image.i32.const(0));image.addFunctionExport(fn.name,'__v2_fuel');continue;
26
+ }
27
+ if (fn.module !== 'env' || fn.base !== 'abort' || fn.results !== binaryen.none || binaryen.expandType(fn.params).length !== 4 || binaryen.expandType(fn.params).some(type => type !== binaryen.i32)) throw new Error('ABI v2 forbids guest function imports');
28
+ image.removeFunction(fn.name); image.addFunction(fn.name,fn.params,fn.results,[],image.unreachable());
29
+ }
30
+ const exports = Array.from({ length: image.getNumExports() },(_,i) => binaryen.getExportInfo(image.getExportByIndex(i)));
31
+ const start = exports.find(value => value.name === '__v2_start'), init = exports.find(value => value.name === 'ws_init');
32
+ if (start !== undefined) {
33
+ if (init === undefined) throw new Error('Missing v2 init');
34
+ const entry = image.getFunction(init.value), info = binaryen.getFunctionInfo(entry);
35
+ const body = image.block(null,[image.call(start.value,[],binaryen.none),info.body],info.results);
36
+ image.removeFunction(info.name); image.addFunction(info.name,info.params,info.results,info.vars,body); image.removeExport('__v2_start');
37
+ }
38
+ if (!image.validate()) throw new Error('Invalid v2 local initialization'); return image.emitBinary();
39
+ } finally { image.dispose(); }
40
+ }
41
+ /** Source exports the H0b signatures, including the final i32 fuel parameter
42
+ * and i32 result for each work entry. Generated wrappers return the real fuel
43
+ * remainder rather than trusting the authored result. */
44
+ export async function compileScriptV2(source: string,options: { maximumPages?: number; ioBytes?: number; lane?: V2Lane; sources?: Readonly<Record<string,string>>; compilerRevision?: number; compileMemo?: AssemblyScriptMemo } = {}): Promise<Uint8Array> {
45
+ if (options.compilerRevision !== undefined && options.compilerRevision !== SCRIPT_V2_REVISIONS.compiler) throw new Error('Unsupported v2 compiler revision');
46
+ const pages = options.maximumPages ?? 1;
47
+ if (!Number.isInteger(pages) || pages < 1 || pages > 4) throw new Error('V2 fixed memory must be 1..4 pages');
48
+ const sources = new Map(Object.entries(options.sources ?? {}));
49
+ if (sources.size > 64 || [...sources].some(([name,value]) => name === 'main.ts' || !/^(?:[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\.ts$/u.test(name) || typeof value !== 'string')) throw new Error('Invalid v2 virtual sources');
50
+ const asc = await loadAssemblyScriptCompiler(); if (!compiler(asc)) throw new Error('Invalid pinned AssemblyScript compiler');
51
+ const compile = async (memoryBase: number): Promise<Uint8Array> => {
52
+ const args = ['main.ts','--outFile','v2.wasm','--runtime','stub','--importMemory','--noExportMemory','--initialMemory',String(pages),'--maximumMemory',String(pages),'--memoryBase',String(memoryBase),'--exportStart','__v2_start','--disable','bulk-memory','-O3'];
53
+ const generate = async (): Promise<Uint8Array> => {
54
+ let bytes: Uint8Array = new Uint8Array();
55
+ const result = await asc.main(args,{
56
+ readFile: name => name === 'main.ts' ? source : sources.get(name) ?? null,
57
+ writeFile: (name,value) => { if (name === 'v2.wasm' && value instanceof Uint8Array) bytes = value; },
58
+ });
59
+ if (result.error || bytes.length === 0) throw new Error(`V2 AssemblyScript compile failed: ${result.error?.message ?? 'no output'}${result.stderr?.toString() ?? ''}`);
60
+ return bytes;
61
+ };
62
+ const bytes = options.compileMemo === undefined ? await generate()
63
+ : await options.compileMemo(args, new Map([['main.ts', source], ...sources]), generate);
64
+ return localStartAndAbort(bytes);
65
+ };
66
+ // Discover the literal IO base without executing the getter. Compile again
67
+ // with all static data and the AS stack/heap beyond the entire host IO range.
68
+ const first = readV2Module(await compile(0)), entry = first.exports.get('ws_io'), code = first.bodies[entry?.index ?? -1]?.code;
69
+ const io = code?.[0]?.literal, ioBytes = options.ioBytes ?? 656;
70
+ if (entry?.kind !== 0 || code?.length !== 2 || code[0]?.op !== 0x41 || code[1]?.op !== 0x0b || typeof io !== 'number' || io < 0 || io%8 !== 0
71
+ || !Number.isSafeInteger(ioBytes) || ioBytes < 656 || ioBytes > pages*65536-io) throw new Error('V2 IO does not fit fixed memory');
72
+ const reserved = await compile(Math.ceil((io+ioBytes)/16)*16);
73
+ const output = instrumentV2Fuel(instrumentV2Finite(reserved),options), admitted = admitScriptV2(output,{ ioBytes,...(options.lane === undefined ? {} : { lane: options.lane }) });
74
+ if (admitted.io !== io) throw new Error('V2 IO getter depends on compiler allocation'); return output;
75
+ }
@@ -0,0 +1,84 @@
1
+ import * as v from 'valibot';
2
+ import { readColliderRows, poseOf, placeCollider } from '@wildshard/engine/models/colliders';
3
+ import type { AuthorPlacement, ColliderDesc, ContactSurface } from './placement';
4
+
5
+ const finite = v.pipe(v.number(), v.finite());
6
+ const Vec = v.strictObject({ x: finite, y: finite, z: finite });
7
+
8
+ const sourceSchemas: (surfaces: readonly ContactSurface[]) => { Surface: v.PicklistSchema<readonly ContactSurface[], undefined>; Collider: v.VariantSchema<"kind", [v.StrictObjectSchema<{ readonly hx: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly hy: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly hz: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly yaw: v.ExactOptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, undefined>; readonly rot: v.ExactOptionalSchema<v.StrictObjectSchema<{ readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly w: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; }, undefined>, undefined>; readonly surface: v.ExactOptionalSchema<v.PicklistSchema<readonly ContactSurface[], undefined>, undefined>; readonly kind: v.LiteralSchema<"box", undefined>; }, undefined>, v.StrictObjectSchema<{ readonly halfHeight: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly radius: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly yaw: v.ExactOptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, undefined>; readonly rot: v.ExactOptionalSchema<v.StrictObjectSchema<{ readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly w: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; }, undefined>, undefined>; readonly surface: v.ExactOptionalSchema<v.PicklistSchema<readonly ContactSurface[], undefined>, undefined>; readonly kind: v.LiteralSchema<"capsule", undefined>; }, undefined>, v.StrictObjectSchema<{ readonly radius: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly yaw: v.ExactOptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, undefined>; readonly rot: v.ExactOptionalSchema<v.StrictObjectSchema<{ readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly w: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; }, undefined>, undefined>; readonly surface: v.ExactOptionalSchema<v.PicklistSchema<readonly ContactSurface[], undefined>, undefined>; readonly kind: v.LiteralSchema<"ball", undefined>; }, undefined>, v.StrictObjectSchema<{ readonly points: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, undefined>; readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly yaw: v.ExactOptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, undefined>; readonly rot: v.ExactOptionalSchema<v.StrictObjectSchema<{ readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly w: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; }, undefined>, undefined>; readonly surface: v.ExactOptionalSchema<v.PicklistSchema<readonly ContactSurface[], undefined>, undefined>; readonly kind: v.LiteralSchema<"hull", undefined>; }, undefined>, v.StrictObjectSchema<{ readonly vertices: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, undefined>; readonly indices: v.ArraySchema<v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>; readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly yaw: v.ExactOptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, undefined>; readonly rot: v.ExactOptionalSchema<v.StrictObjectSchema<{ readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly w: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; }, undefined>, undefined>; readonly surface: v.ExactOptionalSchema<v.PicklistSchema<readonly ContactSurface[], undefined>, undefined>; readonly kind: v.LiteralSchema<"trimesh", undefined>; }, undefined>, v.StrictObjectSchema<{ readonly kind: v.LiteralSchema<"treads", undefined>; readonly from: v.StrictObjectSchema<{ readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; }, undefined>; readonly to: v.StrictObjectSchema<{ readonly x: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly y: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly z: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; }, undefined>; readonly width: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>; readonly count: v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>]>; readonly surface: v.ExactOptionalSchema<v.PicklistSchema<readonly ContactSurface[], undefined>, undefined>; }, undefined>], undefined>; } = (surfaces: readonly ContactSurface[]) => {
9
+ const Surface = v.picklist(surfaces);
10
+ const Placed = { x: finite, y: finite, z: finite, yaw: v.exactOptional(finite), rot: v.exactOptional(v.strictObject({ x: finite, y: finite, z: finite, w: finite })), surface: v.exactOptional(Surface) };
11
+ const Collider = v.variant('kind', [
12
+ v.strictObject({ kind: v.literal('box'), ...Placed, hx: finite, hy: finite, hz: finite }),
13
+ v.strictObject({ kind: v.literal('capsule'), ...Placed, halfHeight: finite, radius: finite }),
14
+ v.strictObject({ kind: v.literal('ball'), ...Placed, radius: finite }),
15
+ v.strictObject({ kind: v.literal('hull'), ...Placed, points: v.array(finite) }),
16
+ v.strictObject({ kind: v.literal('trimesh'), ...Placed, vertices: v.array(finite), indices: v.array(v.pipe(finite, v.integer(), v.minValue(0))) }),
17
+ v.strictObject({ kind: v.literal('treads'), from: Vec, to: Vec, width: finite, count: v.pipe(finite, v.integer(), v.minValue(1)), surface: v.exactOptional(Surface) }),
18
+ ]);
19
+ return { Surface, Collider };
20
+ };
21
+
22
+ /** Exact recorded contact grammar for an explicit authored surface vocabulary. */
23
+ export type SourceColliderSchemas = ReturnType<typeof sourceSchemas>;
24
+ /** Build strict recorded shapes without creating a collider, registry or physics world. */
25
+ export function sourceColliderSchemas(surfaces: readonly ContactSurface[]): SourceColliderSchemas { return sourceSchemas(surfaces); }
26
+ /** One admitted source shape; numeric buffers remain ordinary owned arrays. */
27
+ export type SourceCollider = v.InferOutput<SourceColliderSchemas['Collider']>;
28
+
29
+ /** A captured author registry piece, before any runtime registration or resource borrowing. */
30
+ export interface RecordedPhysicsPiece {
31
+ id: string; name: string; category: string; file: string; colliders: SourceCollider[]; active: boolean;
32
+ surface?: ContactSurface; colliderOwner?: string;
33
+ follows?: { matrix: number[]; rotation: boolean } | undefined;
34
+ }
35
+ /** Admit recorded world-frame pieces with the exact identity-frame rule for followed pieces. */
36
+ export function recordedPhysicsPieces(input: unknown, surfaces: readonly ContactSurface[]): RecordedPhysicsPiece[] {
37
+ const { Surface, Collider } = sourceColliderSchemas(surfaces);
38
+ const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
39
+ return v.parse(v.array(v.strictObject({ id: v.string(), name: v.string(), category: v.string(), file: v.string(),
40
+ colliders: v.array(Collider), active: v.boolean(), surface: v.exactOptional(Surface), colliderOwner: v.exactOptional(v.string()),
41
+ follows: v.optional(v.strictObject({ matrix: v.pipe(v.array(finite),
42
+ v.check(matrix => matrix.length === 16 && matrix.every((value, index) => value === identity[index]), 'a baked followed piece rests at the world frame')),
43
+ rotation: v.boolean() })) })), input);
44
+ }
45
+ /** Admit finite recorded points with strict coordinate ownership. */
46
+ export function recordedPhysicsPoints(input: unknown): { x: number; y: number; z: number }[] { return v.parse(v.array(Vec), input); }
47
+ /** Admit source contacts, optionally requiring the exact original recorded count. */
48
+ export function recordedColliderRows(input: unknown, surfaces: readonly ContactSurface[], length?: number): SourceCollider[] {
49
+ const schema = v.array(sourceColliderSchemas(surfaces).Collider);
50
+ if (length === undefined) return v.parse(schema, input);
51
+ if (!Number.isSafeInteger(length) || length < 0) throw new Error('Invalid recorded contact count');
52
+ return v.parse(v.pipe(schema, v.length(length)), input);
53
+ }
54
+
55
+ /** Explicit authored shape/surface vocabulary, enforced before any geometry lane is borrowed. */
56
+ export interface AuthorContactPolicy {
57
+ readonly kinds: readonly ColliderDesc['kind'][];
58
+ readonly surfaces: readonly ContactSurface[];
59
+ readonly requireSurface?: boolean;
60
+ }
61
+
62
+ /** Admit fresh bounded contact rows with the native strict grammar and owned numeric lane copies. */
63
+ export function admitContactRows(rows: readonly unknown[], policy: AuthorContactPolicy): ColliderDesc[] {
64
+ return readColliderRows(rows, policy);
65
+ }
66
+
67
+ /** Compile an ordered contact batch at one authored pose using the native matrix/quaternion/scale law. */
68
+ export function placeContactRows(rows: readonly ColliderDesc[], placement: AuthorPlacement<object>): ColliderDesc[] {
69
+ const pose = poseOf(placement);
70
+ return rows.map(row => placeCollider(row, pose));
71
+ }
72
+
73
+ /** Compile authored stair contacts with the native block order and exact arithmetic.
74
+ * This returns data only; registration, Rapier shapes and collision queries remain engine-owned. */
75
+ export function treadBoxRows(d: Extract<ColliderDesc, { kind: 'treads' }>): Extract<ColliderDesc, { kind: 'box' }>[] {
76
+ const dx = d.to.x - d.from.x, dz = d.to.z - d.from.z, run = Math.hypot(dx, dz) / d.count, rise = (d.to.y - d.from.y) / d.count;
77
+ const yaw = Math.atan2(dx, dz);
78
+ const out: Extract<ColliderDesc, { kind: 'box' }>[] = [];
79
+ for (let i = 0; i < d.count; i++) {
80
+ const f = (i + 0.5) / d.count, top = d.from.y + rise * (i + 1), hy = Math.max(0.01, (top - d.from.y) / 2);
81
+ out.push({ kind: 'box', x: d.from.x + dx * f, y: d.from.y + hy, z: d.from.z + dz * f, hx: d.width / 2, hy, hz: run / 2, yaw, ...(d.surface === undefined ? {} : { surface: d.surface }) });
82
+ }
83
+ return out;
84
+ }