@wildshard/sdk 0.0.0 → 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 +14 -4
  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 +371 -4
  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,97 @@
1
+ import { forearm, gloveFist, riderArm } from '@wildshard/engine/player/firstPersonArms';
2
+ import { Color, Vector3, BufferGeometry, BufferAttribute, DynamicDrawUsage } from 'three';
3
+ import { parse } from 'valibot';
4
+ import { ReinPresentationSchema, type ReinPresentationRows, type ReinRibbonRows } from '@wildshard/format/riding';
5
+
6
+ /** Own a linear author colour: numeric hex retains the native sRGB conversion; triples are already linear. */
7
+ export function bakeArmColour(value: number | readonly [number, number, number]): Color {
8
+ return typeof value === 'number' ? new Color(value).convertSRGBToLinear().multiplyScalar(1) : new Color(...value);
9
+ }
10
+
11
+ /** Independent colours in the original arm palette order, without a live view or shared mutable palette. */
12
+ export function bakeArmPalette(style: Parameters<typeof gloveFist>[0]): Record<keyof Parameters<typeof gloveFist>[0], Color> {
13
+ return {
14
+ leather: bakeArmColour(style.leather), leatherLight: bakeArmColour(style.leatherLight), leatherDark: bakeArmColour(style.leatherDark), leatherEdge: bakeArmColour(style.leatherEdge),
15
+ thread: bakeArmColour(style.thread), jade: bakeArmColour(style.jade), jadeDark: bakeArmColour(style.jadeDark), fleece: bakeArmColour(style.fleece),
16
+ fleeceShade: bakeArmColour(style.fleeceShade), fleeceDeep: bakeArmColour(style.fleeceDeep), wool: bakeArmColour(style.wool), woolShade: bakeArmColour(style.woolShade),
17
+ red: bakeArmColour(style.red), redDeep: bakeArmColour(style.redDeep), redLine: bakeArmColour(style.redLine), gold: bakeArmColour(style.gold),
18
+ };
19
+ }
20
+
21
+ /** A gloved first-person fist from an arm style (the engine's held-view fist law), for a held weapon's rest pool bake.
22
+ * Returns owned geometry and its wrist frame; nothing is drawn or installed. */
23
+ export function bakeGloveFist(style: Parameters<typeof gloveFist>[0], opts: Parameters<typeof gloveFist>[1]): ReturnType<typeof gloveFist> {
24
+ return gloveFist(style, opts);
25
+ }
26
+
27
+ /** A rider's sleeved arm from an arm style (the engine's held-view arm law), for a held weapon's rest pool bake. */
28
+ export function bakeRiderArm(style: Parameters<typeof riderArm>[0], length?: number, seed?: number): ReturnType<typeof riderArm> {
29
+ return riderArm(style, length, seed);
30
+ }
31
+
32
+ /** Construct owned fist/forearm geometry in the supplied grip direction, without a view or owner. */
33
+ export function bakeForearm(...args: Parameters<typeof forearm>): ReturnType<typeof forearm> { return forearm(...args); }
34
+
35
+ /** Admit the complete numeric strap/attachment policy without installing a riding view. */
36
+ export function reinPresentationRows(input: unknown): ReinPresentationRows { return parse(ReinPresentationSchema, input); }
37
+
38
+ function reinRgb(value: readonly number[]): [number, number, number] {
39
+ const [r, g, b] = value;
40
+ if (value.length !== 3 || r === undefined || g === undefined || b === undefined || !value.every(Number.isFinite)) throw new Error('Invalid rein colour');
41
+ return [r, g, b];
42
+ }
43
+ function reinCatmull(out: Vector3, p0: Vector3, p1: Vector3, p2: Vector3, p3: Vector3, t: number, tangent: boolean): Vector3 {
44
+ const t2 = t * t, t3 = t2 * t;
45
+ const f = (a: number, b: number, c: number, d: number): number => tangent
46
+ ? 0.5 * ((-a + c) + 2 * (2 * a - 5 * b + 4 * c - d) * t + 3 * (-a + 3 * b - 3 * c + d) * t2)
47
+ : 0.5 * (2 * b + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t2 + (-a + 3 * b - 3 * c + d) * t3);
48
+ return out.set(f(p0.x, p1.x, p2.x, p3.x), f(p0.y, p1.y, p2.y, p3.y), f(p0.z, p1.z, p2.z, p3.z));
49
+ }
50
+
51
+ /** Bake the two camera-space straps from six Catmull-Rom anchors each.
52
+ * Returns owned position/normal/colour/index channels; no material or view is constructed. */
53
+ export function bakeReinsGeometry(rows: ReinPresentationRows, paths: readonly (readonly Vector3[])[]): BufferGeometry {
54
+ if (paths.length !== 2 || paths.some(path => path.length !== 6 || path.some(point => ![point.x, point.y, point.z].every(Number.isFinite))))
55
+ throw new Error('Rein bake requires two finite six-anchor paths');
56
+ if (!Number.isInteger(rows.span) || rows.span < 1 || rows.span > 64 || !Number.isFinite(rows.halfWidth) || rows.halfWidth <= 0) throw new Error('Invalid rein dimensions');
57
+ const SEG = rows.span * 3;
58
+ const LEATHER = new Color(...reinRgb(rows.colour)), LEATHER_EDGE = new Color(...reinRgb(rows.edge));
59
+ const verts = 2 * (SEG + 1) * 2;
60
+ const pos = new Float32Array(verts * 3);
61
+ const nrm = new Float32Array(verts * 3), col = new Float32Array(verts * 3), idx: number[] = [];
62
+ for (let v = 0; v < verts; v++) {
63
+ nrm[v * 3 + 2] = 1;
64
+ const c = v % 2 === 0 ? LEATHER_EDGE : LEATHER;
65
+ col[v * 3] = c.r; col[v * 3 + 1] = c.g; col[v * 3 + 2] = c.b;
66
+ }
67
+ for (let r = 0; r < 2; r++) {
68
+ const o = r * (SEG + 1) * 2;
69
+ for (let i = 0; i < SEG; i++) { const a = o + i * 2; idx.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); }
70
+ }
71
+ const g = new BufferGeometry();
72
+ const attr = new BufferAttribute(pos, 3);
73
+ attr.setUsage(DynamicDrawUsage);
74
+ g.setAttribute('position', attr);
75
+ g.setAttribute('normal', new BufferAttribute(nrm, 3));
76
+ g.setAttribute('color', new BufferAttribute(col, 3));
77
+ g.setIndex(idx);
78
+ for (const [r, path] of paths.entries()) fillBakedRein(pos, r, path, rows);
79
+ return g;
80
+ }
81
+ function fillBakedRein(pos: Float32Array, r: number, K: readonly Vector3[], rows: ReinRibbonRows): void {
82
+ const _p = new Vector3(), _t = new Vector3(), _s = new Vector3();
83
+ const SPAN = rows.span, SEG = SPAN * 3;
84
+ const o = r * (SEG + 1) * 2;
85
+ for (let i = 0; i <= SEG; i++) {
86
+ const span = Math.min(2, Math.floor(i / SPAN)), t = (i - span * SPAN) / SPAN;
87
+ const p0 = K[span], p1 = K[span + 1], p2 = K[span + 2], p3 = K[span + 3];
88
+ if (p0 === undefined || p1 === undefined || p2 === undefined || p3 === undefined) continue;
89
+ reinCatmull(_p, p0, p1, p2, p3, t, false);
90
+ reinCatmull(_t, p0, p1, p2, p3, t, true);
91
+ // a flat strap turned to the eye: its width across the tangent and the line of sight
92
+ _s.crossVectors(_t, _p).normalize().multiplyScalar(rows.halfWidth);
93
+ const k = (o + i * 2) * 3;
94
+ pos[k] = _p.x + _s.x; pos[k + 1] = _p.y + _s.y; pos[k + 2] = _p.z + _s.z;
95
+ pos[k + 3] = _p.x - _s.x; pos[k + 4] = _p.y - _s.y; pos[k + 5] = _p.z - _s.z;
96
+ }
97
+ }
@@ -0,0 +1,95 @@
1
+ import { WebIO, type Accessor, type Document } from '@gltf-transform/core';
2
+ import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
3
+ import { MeshoptDecoder } from 'meshoptimizer';
4
+ import * as THREE from 'three';
5
+
6
+ /** Authoring rest data from a retained skinned GLB; no animation, renderer, scene service or game is installed. */
7
+ export interface RigRest {
8
+ readonly geometry: THREE.BufferGeometry;
9
+ readonly bones: readonly { readonly name: string; readonly pos: readonly [number, number, number] }[];
10
+ readonly colourImage: Uint8Array;
11
+ }
12
+ /** Normalize quantized GLTF channels into the Float32 geometry the Three loader supplies to authoring tools. */
13
+ function attribute(accessor: Accessor | null, label: string): THREE.BufferAttribute {
14
+ if (accessor === null) throw new Error(`Rig lacks ${label}`);
15
+ const size = accessor.getElementSize(), array = new Float32Array(accessor.getCount() * size), element: number[] = [];
16
+ for (let index = 0; index < accessor.getCount(); index++) {
17
+ accessor.getElement(index, element);
18
+ for (let channel = 0; channel < size; channel++) array[index * size + channel] = element[channel] ?? 0;
19
+ }
20
+ return new THREE.BufferAttribute(array, size);
21
+ }
22
+ /** Read one triangle skin's rest geometry, ordered world-space joints and embedded colour atlas in plain Node.
23
+ * Meshopt and embedded WebP are admitted through their GLTF extensions. Multi-skin/multi-primitive input refuses;
24
+ * callers that need a composed rig must author that composition explicitly. UVs and mesh-local positions stay unchanged. */
25
+ export async function readRigRest(glb: Uint8Array): Promise<RigRest> {
26
+ const document = await readDocument(glb);
27
+ const nodes = document.getRoot().listNodes().filter(node => node.getSkin() !== null && node.getMesh() !== null);
28
+ if (nodes.length !== 1) throw new Error('Rig requires one skinned node');
29
+ const node = nodes[0], skin = node?.getSkin(), primitives = node?.getMesh()?.listPrimitives();
30
+ if (skin === undefined || skin === null || primitives?.length !== 1) throw new Error('Rig requires one skinned primitive');
31
+ const primitive = primitives[0];
32
+ if (primitive?.getMode() !== 4) throw new Error('Rig requires triangles');
33
+ const geometry = new THREE.BufferGeometry();
34
+ for (const [name, channel] of [['position', 'POSITION'], ['normal', 'NORMAL'], ['uv', 'TEXCOORD_0']] as const) geometry.setAttribute(name, attribute(primitive.getAttribute(channel), channel));
35
+ const array = primitive.getIndices()?.getArray();
36
+ if (array?.length === undefined) throw new Error('Rig requires triangle indices');
37
+ geometry.setIndex(Array.from(array));
38
+ const colourImage = primitive.getMaterial()?.getBaseColorTexture()?.getImage();
39
+ if (colourImage === undefined || colourImage === null) throw new Error('Rig requires embedded colour atlas');
40
+ const bones = skin.listJoints().map(joint => ({ name: joint.getName(), pos: joint.getWorldTranslation() }));
41
+ return { geometry, bones, colourImage: new Uint8Array(colourImage) };
42
+ }
43
+
44
+ /** Local authored transform, including the named parent; no inverse-bind or geometry approximation. */
45
+ export interface RigTransform {
46
+ readonly name: string;
47
+ readonly parent: string | null;
48
+ readonly position: readonly number[];
49
+ readonly quaternion: readonly number[];
50
+ readonly scale: readonly number[];
51
+ }
52
+ /** Original standard Three clips and local node transforms, without meshes, textures or playback services. */
53
+ export interface RigMotion {
54
+ readonly clips: readonly THREE.AnimationClip[];
55
+ readonly nodes: readonly RigTransform[];
56
+ }
57
+ async function readDocument(glb: Uint8Array): Promise<Document> {
58
+ if (glb.length < 20 || glb.length > 64_000_000) throw new Error('Rig requires bounded GLB bytes');
59
+ const header = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
60
+ if (header.getUint32(0, true) !== 0x46546c67 || header.getUint32(4, true) !== 2 || header.getUint32(8, true) !== glb.byteLength) throw new Error('Rig requires complete GLB 2 bytes');
61
+ await MeshoptDecoder.ready;
62
+ return new WebIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder }).readBinary(glb);
63
+ }
64
+ /** Decode GLB transform animation into standard Three tracks, preserving Float32 keys and STEP/LINEAR interpolation.
65
+ * Stable named targets are required. Morph channels, cubic splines and normalized/integer animation accessors refuse;
66
+ * they require their own exact compiler. Geometry and embedded images are never decoded into rendering resources. */
67
+ export async function readRigMotion(glb: Uint8Array): Promise<RigMotion> {
68
+ const root = (await readDocument(glb)).getRoot();
69
+ if (root.listNodes().length > 4096 || root.listAnimations().length > 32) throw new Error('Rig motion exceeds node/clip cap');
70
+ const nodes = root.listNodes().map(node => ({ name: node.getName(), parent: node.getParentNode()?.getName() ?? null,
71
+ position: [...node.getTranslation()], quaternion: [...node.getRotation()], scale: [...node.getScale()] }));
72
+ const clips = root.listAnimations().map(animation => {
73
+ if (animation.listChannels().length > 256) throw new Error('Rig animation exceeds track cap');
74
+ const bindings = new Set<string>();
75
+ const tracks = animation.listChannels().map(channel => {
76
+ const target = channel.getTargetNode(), path = channel.getTargetPath(), sampler = channel.getSampler();
77
+ const name = target?.getName(), input = sampler?.getInput(), output = sampler?.getOutput(), interpolation = sampler?.getInterpolation();
78
+ if (!name || !/^[a-z0-9_-]{1,128}$/iu.test(name) || nodes.filter(node => node.name === name).length !== 1 || path !== 'translation' && path !== 'rotation' && path !== 'scale') throw new Error('Rig animation requires a distinct named transform target');
79
+ const property = path === 'translation' ? 'position' : path === 'rotation' ? 'quaternion' : 'scale';
80
+ const binding = `${name}.${property}`;
81
+ if (bindings.has(binding)) throw new Error('Duplicate rig animation binding'); bindings.add(binding);
82
+ const times = input?.getArray(), values = output?.getArray(), size = path === 'rotation' ? 4 : 3;
83
+ if (!(times instanceof Float32Array) || !(values instanceof Float32Array) || input?.getType() !== 'SCALAR' || input.getNormalized() || output?.getNormalized() || output?.getElementSize() !== size ||
84
+ times.length === 0 || times.length > 4097 || values.length !== times.length * size ||
85
+ times.some((time, index) => !Number.isFinite(time) || time < 0 || time > 60 || index > 0 && time <= (times[index - 1] ?? Infinity)) || values.some(value => !Number.isFinite(value))) throw new Error('Invalid bounded rig animation keys');
86
+ if (interpolation !== 'LINEAR' && interpolation !== 'STEP') throw new Error('Rig animation requires standard linear or step interpolation');
87
+ const mode = interpolation === 'STEP' ? THREE.InterpolateDiscrete : THREE.InterpolateLinear;
88
+ return path === 'rotation' ? new THREE.QuaternionKeyframeTrack(binding, Float32Array.from(times), Float32Array.from(values), mode) :
89
+ new THREE.VectorKeyframeTrack(binding, Float32Array.from(times), Float32Array.from(values), mode);
90
+ });
91
+ tracks.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
92
+ return new THREE.AnimationClip(animation.getName(), -1, tracks);
93
+ });
94
+ return { clips, nodes };
95
+ }
@@ -0,0 +1,40 @@
1
+ import * as v from 'valibot';
2
+
3
+ /** Authored back-plane deformation, before any vertex or renderer exists. */
4
+ export interface AuthorHullFlap {
5
+ yMin: number; y0: number; z0: number; slope: number; keep: number; bulge: number;
6
+ }
7
+ /** Ordered source family, recolouring recipes and optional measured fur tones. */
8
+ export interface AuthorHullRecipe<Palette extends string> {
9
+ label: string;
10
+ rigs: string[];
11
+ hulls: Record<string, string>;
12
+ coats: Record<string, {
13
+ palette: Palette;
14
+ source: [string, string];
15
+ keys: [string, string, string];
16
+ measured?: Record<string, Record<string, [number, number, number]>>;
17
+ }>;
18
+ flaps?: Record<string, AuthorHullFlap>;
19
+ fur?: Record<string, Record<string, { rim: [number, number, number]; sheenColor: [number, number, number] }>>;
20
+ }
21
+
22
+ /** Admit an owned source recipe against the caller's finite palette vocabulary.
23
+ * All object boundaries are strict; optional records stay absent and every
24
+ * scalar is finite. This is source admission, independent of tier resources. */
25
+ export function riggedHullRecipeRows<const Palettes extends readonly [string, ...string[]]>(
26
+ input: unknown, palettes: Palettes,
27
+ ): AuthorHullRecipe<Palettes[number]> {
28
+ const num = v.pipe(v.number(), v.finite()), rgb = v.tuple([num, num, num]);
29
+ const flap = v.strictObject({ yMin: num, y0: num, z0: num, slope: num, keep: num, bulge: num });
30
+ const coat = v.strictObject({
31
+ palette: v.picklist(palettes), source: v.tuple([v.string(), v.string()]),
32
+ keys: v.tuple([v.string(), v.string(), v.string()]),
33
+ measured: v.exactOptional(v.record(v.string(), v.record(v.string(), rgb))),
34
+ });
35
+ return v.parse(v.strictObject({
36
+ label: v.string(), rigs: v.array(v.string()), hulls: v.record(v.string(), v.string()),
37
+ coats: v.record(v.string(), coat), flaps: v.exactOptional(v.record(v.string(), flap)),
38
+ fur: v.exactOptional(v.record(v.string(), v.record(v.string(), v.strictObject({ rim: rgb, sheenColor: rgb })))),
39
+ }), input);
40
+ }
@@ -0,0 +1,25 @@
1
+ import * as v from 'valibot';
2
+
3
+ /** Ordered recorded surface slot, before text selection or geometry creation. */
4
+ export interface RecordedSignSlot {
5
+ at: [number, number, number];
6
+ normal: [number, number, number];
7
+ size: number;
8
+ color: number;
9
+ blade: boolean;
10
+ }
11
+
12
+ /** Read explicitly named strict sign groups from an authored record path.
13
+ * Enclosing records retain their native strip behavior. Slot numbers use the
14
+ * original numeric grammar; finiteness and size bounds belong to the bake. */
15
+ export function recordedSignGroups<const Groups extends readonly string[]>(
16
+ input: unknown, groups: Groups, path?: readonly string[],
17
+ ): Record<Groups[number], RecordedSignSlot[]>;
18
+ export function recordedSignGroups(input: unknown, groups: readonly string[], path: readonly string[] = []): Record<string, RecordedSignSlot[]> {
19
+ const vector = v.tuple([v.number(), v.number(), v.number()]);
20
+ const slot = v.strictObject({ at: vector, normal: vector, size: v.number(), color: v.number(), blade: v.boolean() });
21
+ let value = input;
22
+ for (const key of path) value = v.parse(v.object({ [key]: v.unknown() }), value)[key];
23
+ const entries = Object.fromEntries(groups.map(key => [key, v.array(slot)]));
24
+ return v.parse(v.strictObject(entries), value);
25
+ }
@@ -0,0 +1,52 @@
1
+ import { BufferAttribute, BufferGeometry, type InterleavedBufferAttribute } from 'three';
2
+ import { MeshoptSimplifier } from 'meshoptimizer/simplifier';
3
+
4
+ await MeshoptSimplifier.ready;
5
+
6
+ /** Preserve an author's explicit asynchronous readiness boundary before compiling owned geometry. */
7
+ export function prepareGeometrySimplifier(): Promise<void> { return MeshoptSimplifier.ready; }
8
+
9
+ /** Author bakes simplify through the SDK (shard generators import only three, the SDK and commons): meshoptimizer's
10
+ * simplifier on an indexed position set, keeping every surface within `error` metres. Borders are free unless
11
+ * `lockBorder`. Returns the kept triangle indices. */
12
+ export function simplifyWithin(indices: Uint32Array, positions: Float32Array, error: number, lockBorder = false): Uint32Array {
13
+ const scale = MeshoptSimplifier.getScale(positions, 3);
14
+ return MeshoptSimplifier.simplify(indices, positions, 3, 0, error / scale, lockBorder ? ['LockBorder'] : [])[0];
15
+ }
16
+
17
+ /** Preserve painted colour/normal features while targeting a declared vertex budget. */
18
+ export interface PaintedReduction {
19
+ readonly vertices: number; readonly colourWeight: number; readonly normalWeight: number; readonly error: number;
20
+ }
21
+ /** Reduce indexed position/normal/colour geometry and compact kept vertices in first-use order.
22
+ * Reads numeric accessor values, returns detached Float32 channels and Uint32 indices;
23
+ * the caller retains its source and owns the result. Other channels are intentionally omitted. */
24
+ export function simplifyPaintedGeometry(g: BufferGeometry, options: PaintedReduction): BufferGeometry {
25
+ const { vertices: verts, colourWeight, normalWeight, error } = options;
26
+ const p = g.getAttribute('position'), n = g.getAttribute('normal'), c = g.getAttribute('color'), src = g.getIndex();
27
+ if (src === null) throw new Error('Painted geometry reduction requires an index');
28
+ const count = p.count, pos = new Float32Array(count * 3), attr = new Float32Array(count * 6);
29
+ for (let i = 0; i < count; i++) {
30
+ pos[i * 3] = p.getX(i); pos[i * 3 + 1] = p.getY(i); pos[i * 3 + 2] = p.getZ(i);
31
+ attr.set([c.getX(i), c.getY(i), c.getZ(i), n.getX(i), n.getY(i), n.getZ(i)], i * 6);
32
+ }
33
+ const index = Uint32Array.from({ length: src.count }, (_, i) => src.getX(i));
34
+ const target = Math.round(index.length * (verts / count) / 3) * 3;
35
+ const [kept] = MeshoptSimplifier.simplifyWithAttributes(index, pos, 3, attr, 6, [colourWeight, colourWeight, colourWeight, normalWeight, normalWeight, normalWeight], null, target, error);
36
+ const remap = new Int32Array(count).fill(-1), order: number[] = [], out = new Uint32Array(kept.length);
37
+ for (let i = 0; i < kept.length; i++) {
38
+ const v = kept[i] ?? 0;
39
+ let m = remap[v] ?? -1;
40
+ if (m < 0) { m = order.length; remap[v] = m; order.push(v); }
41
+ out[i] = m;
42
+ }
43
+ const take = (a: BufferAttribute | InterleavedBufferAttribute): BufferAttribute => {
44
+ const o = new Float32Array(order.length * 3);
45
+ order.forEach((v, i) => { o[i * 3] = a.getX(v); o[i * 3 + 1] = a.getY(v); o[i * 3 + 2] = a.getZ(v); });
46
+ return new BufferAttribute(o, 3);
47
+ };
48
+ const d = new BufferGeometry();
49
+ d.setAttribute('position', take(p)); d.setAttribute('normal', take(n)); d.setAttribute('color', take(c));
50
+ d.setIndex(new BufferAttribute(out, 1));
51
+ return d;
52
+ }
@@ -0,0 +1,312 @@
1
+ import { Float32BufferAttribute, InterpolateDiscrete, InterpolateLinear, Matrix4, PropertyBinding, Uint16BufferAttribute, type AnimationClip, type BufferAttribute, type BufferGeometry, type Material, type MeshStandardMaterial } from 'three';
2
+ import type { GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js';
3
+ import { MeshoptEncoder } from 'meshoptimizer/encoder';
4
+ import type { RiggedHullBook, RiggedHullUrls } from '@wildshard/format/riggedHulls';
5
+
6
+ /** Complete authored rigged-hull family and tier resources, admitted by the product's defining grammar. */
7
+ export type AuthorRiggedHullBook = RiggedHullBook;
8
+ /** Ordered authored geometry, coat and attachment references without a live hull or material owner. */
9
+ export type AuthorRiggedHullUrls = RiggedHullUrls;
10
+
11
+ /**
12
+ * Build-time only (SHARD-PLATFORM M3, the offline skinned-model bake): a shard's generator reads a source GLB offline
13
+ * (`readSourceModel`), runs its own processing on it (fit, retarget, merge, strip, recolour, re-skin: a generator function in
14
+ * the shard's folder), and writes the result as a standard skinned glTF (`skinnedGlb`): a joint hierarchy with inverse
15
+ * bind matrices, `JOINTS_0` / `WEIGHTS_0`, the animations as glTF channels and the shard's own JSON beside it. The client
16
+ * only loads it (`@wildshard/engine/game/plugin/geometry` skinnedModel / creatureBodies), bit-exact: every float32 channel, the joint bind positions as JSON
17
+ * doubles, the weights as written (never renormalized) and an authored triangle soup restored. Every accessor rides
18
+ * EXT_meshopt_compression (lossless: the vertex and index-sequence codecs return the exact bytes), about half the floats.
19
+ *
20
+ * A part's base-colour map rides inside the GLB as the source's exact image bytes (never re-encoded), so the client decodes
21
+ * it as it decoded the source, and the engine's KTX2 bake (`scripts/bake-ktx2.mjs`, geometry bytes untouched) makes its GPU
22
+ * stand-in exactly as it did for the source. (A shardfile asset declares its textures separately: `parseGlb` refuses
23
+ * embedded images, so a textured skinned bake is for a trusted runtime's own loads.)
24
+ */
25
+
26
+ type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
27
+ /** A source GLB's base-colour image as its exact bytes (never decoded offline) and its glTF sampler. */
28
+ export interface RawTexture {
29
+ readonly image: Uint8Array; readonly mimeType: string;
30
+ readonly sampler: { readonly magFilter?: number; readonly minFilter?: number; readonly wrapS?: number; readonly wrapT?: number };
31
+ }
32
+ /** A source model read offline: three's own GLTFLoader scene (the identical intake the runtime used), textures as bytes. */
33
+ export interface SourceModel {
34
+ readonly gltf: GLTF;
35
+ /** The base-colour texture a loaded material had in the file, or null. */
36
+ texture: (material: Material) => RawTexture | null;
37
+ }
38
+
39
+ const MAGIC = 0x46546c67, JSON_CHUNK = 0x4e4f534a, BIN_CHUNK = 0x004e4942;
40
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);
41
+ const records = (value: unknown): Record<string, unknown>[] => Array.isArray(value) ? value.filter(isRecord) : [];
42
+ const integer = (value: unknown): number | undefined => typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined;
43
+
44
+ /** Split a GLB into its JSON document and binary chunk. */
45
+ function splitGlb(bytes: Uint8Array): { doc: Record<string, unknown>; bin: Uint8Array } {
46
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
47
+ if (bytes.length < 20 || view.getUint32(0, true) !== MAGIC || view.getUint32(4, true) !== 2) throw new Error('Source model is not a GLB 2.0');
48
+ const length = view.getUint32(12, true);
49
+ if (view.getUint32(16, true) !== JSON_CHUNK || 20 + length > bytes.length) throw new Error('Source GLB has no JSON chunk');
50
+ const doc: unknown = JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + length)));
51
+ if (!isRecord(doc)) throw new Error('Source GLB JSON is not an object');
52
+ let bin: Uint8Array = new Uint8Array(0);
53
+ if (20 + length + 8 <= bytes.length && view.getUint32(24 + length, true) === BIN_CHUNK) bin = bytes.subarray(28 + length, 28 + length + view.getUint32(20 + length, true));
54
+ return { doc, bin };
55
+ }
56
+ /** Assemble a GLB from a JSON document and a binary chunk. */
57
+ function joinGlb(doc: unknown, bin: Uint8Array): Uint8Array {
58
+ const raw = new TextEncoder().encode(JSON.stringify(doc)), length = Math.ceil(raw.length / 4) * 4, binLength = Math.ceil(bin.length / 4) * 4;
59
+ const bytes = new Uint8Array(20 + length + (bin.length > 0 ? 8 + binLength : 0)), view = new DataView(bytes.buffer);
60
+ view.setUint32(0, MAGIC, true); view.setUint32(4, 2, true); view.setUint32(8, bytes.length, true);
61
+ view.setUint32(12, length, true); view.setUint32(16, JSON_CHUNK, true); bytes.fill(32, 20, 20 + length); bytes.set(raw, 20);
62
+ if (bin.length > 0) { view.setUint32(20 + length, binLength, true); view.setUint32(24 + length, BIN_CHUNK, true); bytes.set(bin, 28 + length); }
63
+ return bytes;
64
+ }
65
+ const TEXTURE_EXTENSIONS = ['EXT_texture_webp', 'KHR_texture_basisu', 'EXT_texture_avif'];
66
+
67
+ /**
68
+ * Read a source GLB offline through three's GLTFLoader and the meshopt decoder, the same intake as the engine's
69
+ * `loadRigFile`, so the shard's own intake code sees identical attributes. Textures are not decoded (Node has no image
70
+ * decoder): each material's base-colour image comes back as its bytes through `texture(material)`.
71
+ */
72
+ export async function readSourceModel(bytes: Uint8Array): Promise<SourceModel> {
73
+ const { doc, bin } = splitGlb(bytes), images = records(doc['images']), textures = records(doc['textures']), samplers = records(doc['samplers']);
74
+ const views = records(doc['bufferViews']);
75
+ const rawTexture = (index: number | undefined): RawTexture | null => {
76
+ const texture = index === undefined ? undefined : textures[index];
77
+ if (texture === undefined) return null;
78
+ const extensions = isRecord(texture['extensions']) ? texture['extensions'] : {};
79
+ let source = integer(texture['source']);
80
+ for (const name of TEXTURE_EXTENSIONS) { const ext = extensions[name]; if (isRecord(ext) && integer(ext['source']) !== undefined) source = integer(ext['source']); }
81
+ const image = source === undefined ? undefined : images[source], view = image === undefined ? undefined : views[integer(image['bufferView']) ?? -1];
82
+ if (image === undefined || view === undefined || typeof image['mimeType'] !== 'string') throw new Error('Source texture must be an embedded image');
83
+ const offset = integer(view['byteOffset']) ?? 0, length = integer(view['byteLength']) ?? 0, sampler = samplers[integer(texture['sampler']) ?? -1] ?? {};
84
+ const pick = (key: string): Record<string, number> => { const value = integer(sampler[key]); return value === undefined ? {} : { [key]: value }; };
85
+ return { image: bin.slice(offset, offset + length), mimeType: image['mimeType'], sampler: { ...pick('magFilter'), ...pick('minFilter'), ...pick('wrapS'), ...pick('wrapT') } };
86
+ };
87
+ const materials = records(doc['materials']);
88
+ const baseColor = materials.map((material) => {
89
+ const pbr = isRecord(material['pbrMetallicRoughness']) ? material['pbrMetallicRoughness'] : {}, info = pbr['baseColorTexture'];
90
+ return rawTexture(isRecord(info) ? integer(info['index']) : undefined);
91
+ });
92
+ // The loader never sees a texture: every texture reference goes (the images stay as unused bytes in the binary chunk).
93
+ const strip = (value: unknown): unknown => {
94
+ if (Array.isArray(value)) return value.map(strip);
95
+ if (!isRecord(value)) return value;
96
+ return Object.fromEntries(Object.entries(value).filter(([key, entry]) => !(key.endsWith('Texture') && isRecord(entry))).map(([key, entry]) => [key, strip(entry)]));
97
+ };
98
+ const stripped: Record<string, unknown> = { ...doc, materials: materials.map(strip) };
99
+ for (const key of ['textures', 'images', 'samplers']) Reflect.deleteProperty(stripped, key);
100
+ for (const key of ['extensionsUsed', 'extensionsRequired']) {
101
+ const list = doc[key];
102
+ if (Array.isArray(list)) stripped[key] = list.filter((name: unknown) => typeof name !== 'string' || !TEXTURE_EXTENSIONS.includes(name));
103
+ }
104
+ const [{ GLTFLoader }, { MeshoptDecoder }] = await Promise.all([import('three/examples/jsm/loaders/GLTFLoader.js'), import('three/examples/jsm/libs/meshopt_decoder.module.js')]);
105
+ const input = joinGlb(stripped, bin);
106
+ const gltf = await new GLTFLoader().setMeshoptDecoder(MeshoptDecoder).parseAsync(Uint8Array.from(input).buffer, '');
107
+ return {
108
+ gltf,
109
+ texture: (material) => {
110
+ const index = gltf.parser.associations.get(material)?.materials;
111
+ return index === undefined ? null : baseColor[index] ?? null;
112
+ },
113
+ };
114
+ }
115
+
116
+ /** A joint: its name, its parent's name (null for a root) and its bind position in the model's space (BoneDef's shape). */
117
+ export interface SkinnedBone { readonly name: string; readonly parent: string | null; readonly pos: readonly [number, number, number] }
118
+ /** A skinned part: a geometry with `skinIndex` / `skinWeight` over the bake's bones, its material and its map. */
119
+ export interface SkinnedPart {
120
+ /** Packed attributes, every channel written as baked (float32 but for `skinIndex`; non-glTF channels as `_NAME`). */
121
+ readonly geometry: BufferGeometry;
122
+ /** Its colour, opacity, metalness, roughness and side become the part's glTF material. */
123
+ readonly material: MeshStandardMaterial;
124
+ /** The base-colour map: the source's exact image bytes and sampler. */
125
+ readonly texture?: RawTexture;
126
+ /** The part's mesh and node name (default `<bake name>.<part index>`). */
127
+ readonly name?: string;
128
+ }
129
+ /**
130
+ * One skinned model to bake (`skinnedGlb`): its skeleton, its parts skinned over it, its clips and the shard's extras. The
131
+ * runtime reads the GLB back bit-exact with the game's `skinnedModel` (`@wildshard/engine/game/plugin/geometry`), a creature body
132
+ * with `creatureBodies`.
133
+ */
134
+ export interface SkinnedBake {
135
+ /** The model's name: an unnamed part's mesh and node are named `<name>.<part index>`. */
136
+ readonly name: string;
137
+ /** The skeleton, uniquely named, each parent before its children: every part's `skinIndex` indexes this list. */
138
+ readonly bones: readonly SkinnedBone[];
139
+ /** The skinned meshes, each its own mesh and node over the one skin. */
140
+ readonly parts: readonly SkinnedPart[];
141
+ /** Bone animations (`<bone>.position|quaternion|scale` tracks, linear or step). */
142
+ readonly clips?: readonly AnimationClip[];
143
+ /** The shard's own JSON beside the model (dims, look numbers), read back as `extras`. */
144
+ readonly extras?: Json;
145
+ }
146
+ /** The bake's output: the GLB. */
147
+ export interface SkinnedOutput { readonly glb: Uint8Array }
148
+
149
+ const SEMANTICS: Readonly<Record<string, string>> = { position: 'POSITION', normal: 'NORMAL', tangent: 'TANGENT', uv: 'TEXCOORD_0', uv1: 'TEXCOORD_1', color: 'COLOR_0', skinIndex: 'JOINTS_0', skinWeight: 'WEIGHTS_0' };
150
+ type Typed = Float32Array | Uint32Array | Uint16Array | Uint8Array | Int16Array | Int8Array;
151
+ const COMPONENT = (array: unknown): number => array instanceof Float32Array ? 5126 : array instanceof Uint32Array ? 5125 : array instanceof Uint16Array ? 5123
152
+ : array instanceof Uint8Array ? 5121 : array instanceof Int16Array ? 5122 : array instanceof Int8Array ? 5120 : 0;
153
+ const TYPES = ['', 'SCALAR', 'VEC2', 'VEC3', 'VEC4'];
154
+ const MESHOPT = 'EXT_meshopt_compression';
155
+ await MeshoptEncoder.ready;
156
+ const BOUNDED = new Set(['POSITION']);
157
+
158
+ /** One vertex's bytes across every channel: equal keys are bit-identical vertices. */
159
+ function weld(attributes: readonly (readonly [string, BufferAttribute])[], count: number): { index: number[]; first: number[] } {
160
+ const seen = new Map<string, number>(), index: number[] = [], first: number[] = [];
161
+ const bytes = attributes.map(([, a]) => { const array = a.array as Typed; return { u8: new Uint8Array(array.buffer, array.byteOffset, array.byteLength), size: array.BYTES_PER_ELEMENT * a.itemSize }; });
162
+ for (let v = 0; v < count; v++) {
163
+ let key = '';
164
+ for (const { u8, size } of bytes) for (let b = v * size; b < v * size + size; b++) key += String.fromCodePoint(u8[b] ?? 0);
165
+ let at = seen.get(key);
166
+ if (at === undefined) { at = first.length; seen.set(key, at); first.push(v); }
167
+ index.push(at);
168
+ }
169
+ return { index, first };
170
+ }
171
+
172
+ /**
173
+ * Write a deterministic skinned GLB. A non-indexed part is welded losslessly (bit-identical vertices shared, the soup
174
+ * restored by the loader); weights are written as given; a map's image bytes are embedded unchanged.
175
+ */
176
+ export function skinnedGlb(bake: SkinnedBake): SkinnedOutput {
177
+ const chunks: Uint8Array[] = [], views: Json[] = [], accessors: Json[] = [];
178
+ let offset = 0;
179
+ const view = (bytes: Uint8Array): number => {
180
+ const padded = new Uint8Array(Math.ceil(bytes.length / 4) * 4); padded.set(bytes);
181
+ views.push({ buffer: 0, byteOffset: offset, byteLength: bytes.length }); chunks.push(padded); offset += padded.length; return views.length - 1;
182
+ };
183
+ // a lossless meshopt view: its bytes on the data-less fallback buffer 1, their encoding in buffer 0
184
+ let fallback = 0;
185
+ const packed = (bytes: Uint8Array, count: number, stride: number, mode: 'ATTRIBUTES' | 'INDICES'): number => {
186
+ const encoded = MeshoptEncoder.encodeGltfBuffer(bytes, count, stride, mode), padded = new Uint8Array(Math.ceil(encoded.length / 4) * 4); padded.set(encoded);
187
+ views.push({ buffer: 1, byteOffset: fallback, byteLength: bytes.length, extensions: { [MESHOPT]: { buffer: 0, byteOffset: offset, byteLength: encoded.length, byteStride: stride, count, mode } } });
188
+ chunks.push(padded); offset += padded.length; fallback += Math.ceil(bytes.length / 4) * 4; return views.length - 1;
189
+ };
190
+ const accessor = (array: Typed, width: number, normalized: boolean, bounds: boolean, mode: 'ATTRIBUTES' | 'INDICES' = 'ATTRIBUTES'): number => {
191
+ const component = COMPONENT(array), count = array.length / width, stride = array.BYTES_PER_ELEMENT * width;
192
+ if (component === 0 || !Number.isInteger(count) || count === 0) throw new Error('Invalid skinned GLB channel');
193
+ const bytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
194
+ const lossless = mode === 'INDICES' ? stride === 2 || stride === 4 : stride % 4 === 0 && stride <= 256;
195
+ const a: Record<string, Json> = { bufferView: lossless ? packed(bytes, count, stride, mode) : view(bytes), componentType: component, count, type: width === 16 ? 'MAT4' : TYPES[width] ?? 'SCALAR' };
196
+ if (normalized) a['normalized'] = true;
197
+ if (bounds) {
198
+ const min = Array.from({ length: width }, () => Infinity), max = Array.from({ length: width }, () => -Infinity);
199
+ array.forEach((value, i) => { const c = i % width; min[c] = Math.min(min[c] ?? Infinity, value); max[c] = Math.max(max[c] ?? -Infinity, value); });
200
+ a['min'] = min; a['max'] = max;
201
+ }
202
+ accessors.push(a); return accessors.length - 1;
203
+ };
204
+ const { bones } = bake, names = new Map(bones.map((bone, i) => [bone.name, i]));
205
+ if (bones.length === 0 || names.size !== bones.length) throw new Error('Skinned bake needs uniquely named bones');
206
+ bones.forEach((bone, i) => {
207
+ const parent = bone.parent === null ? -1 : names.get(bone.parent) ?? Infinity;
208
+ if (parent >= i || bone.pos.some((n) => !Number.isFinite(n))) throw new Error(`Skinned bone ${bone.name}: its parent must come before it`);
209
+ });
210
+ // the joints: nodes after the parts' mesh nodes, each at its offset from its parent, its exact bind position in extras
211
+ const partNodes = bake.parts.length, joint = (i: number): number => partNodes + i, nodes: Json[] = [];
212
+ const meshes: Json[] = [], materials: Json[] = [], images: Json[] = [], textures: Json[] = [], samplers: Json[] = [], imageOf = new Map<RawTexture, number>();
213
+ const used = new Set<string>();
214
+ bake.parts.forEach((part, p) => {
215
+ const { geometry, material, texture } = part, position = geometry.getAttribute('position');
216
+ if (!geometry.hasAttribute('position') || !geometry.hasAttribute('skinIndex') || !geometry.hasAttribute('skinWeight')) throw new Error('A skinned part needs position, skinIndex and skinWeight');
217
+ const channels = Object.keys(geometry.attributes).sort().map((name) => {
218
+ const a = geometry.getAttribute(name);
219
+ if (!('isBufferAttribute' in a) || a.count !== position.count || a.array.length !== a.count * a.itemSize) throw new Error(`Skinned part channel ${name} must be a packed attribute`);
220
+ return [name, a] as const;
221
+ });
222
+ const skin = geometry.getAttribute('skinIndex');
223
+ if (!(skin.array instanceof Uint16Array || skin.array instanceof Uint8Array) || skin.itemSize !== 4 || Array.from(skin.array).some((j) => j >= bones.length)) throw new Error('skinIndex must be 4 unsigned joints within the bones');
224
+ const weights = geometry.getAttribute('skinWeight');
225
+ if (!(weights.array instanceof Float32Array) || weights.itemSize !== 4) throw new Error('skinWeight must be 4 float32 weights');
226
+ const source = geometry.getIndex(), soup = source === null, welded = soup ? weld(channels, position.count) : null;
227
+ const attributes: Record<string, Json> = {}, renamed: Record<string, Json> = {};
228
+ for (const [name, a] of channels) {
229
+ let semantic = SEMANTICS[name];
230
+ if (semantic === undefined) { semantic = `_${name.replaceAll(/[^A-Za-z0-9]/g, '_').toUpperCase()}`; renamed[semantic] = name; }
231
+ if (semantic !== 'JOINTS_0' && !semantic.startsWith('_') && !(a.array instanceof Float32Array)) throw new Error(`Skinned part channel ${name} must be float32`);
232
+ const array = a.array as Typed, width = a.itemSize;
233
+ const out = welded === null ? array : (() => {
234
+ const copy = new (array.constructor as new (n: number) => Typed)(welded.first.length * width);
235
+ welded.first.forEach((v, i) => { for (let c = 0; c < width; c++) copy[i * width + c] = array[v * width + c] ?? 0; });
236
+ return copy;
237
+ })();
238
+ attributes[semantic] = accessor(out, width, a.normalized, BOUNDED.has(semantic));
239
+ }
240
+ const indexValues = welded?.index ?? Array.from(source?.array ?? []), vertices = welded?.first.length ?? position.count;
241
+ const indices = vertices > 65535 ? Uint32Array.from(indexValues) : Uint16Array.from(indexValues);
242
+ const extras: Record<string, Json> = {};
243
+ if (soup) extras['soup'] = true;
244
+ if (Object.keys(renamed).length > 0) extras['attributes'] = renamed;
245
+ const primitive: Record<string, Json> = { attributes, indices: accessor(indices, 1, false, false, 'INDICES'), material: materials.length };
246
+ if (Object.keys(extras).length > 0) primitive['extras'] = { wildshard: extras };
247
+ const pbr: Record<string, Json> = { baseColorFactor: [...material.color, material.opacity], metallicFactor: material.metalness, roughnessFactor: material.roughness };
248
+ if (texture !== undefined) {
249
+ if (!['image/webp', 'image/png', 'image/jpeg'].includes(texture.mimeType) || texture.image.length === 0) throw new Error(`Skinned texture must be a WebP, PNG or JPEG image (${texture.mimeType})`);
250
+ let index = imageOf.get(texture);
251
+ if (index === undefined) {
252
+ images.push({ bufferView: view(texture.image), mimeType: texture.mimeType });
253
+ samplers.push({ ...texture.sampler });
254
+ const image = images.length - 1, ext = texture.mimeType === 'image/webp' ? 'EXT_texture_webp' : null;
255
+ if (ext !== null) used.add(ext);
256
+ textures.push(ext === null ? { sampler: samplers.length - 1, source: image } : { sampler: samplers.length - 1, extensions: { [ext]: { source: image } } });
257
+ index = textures.length - 1; imageOf.set(texture, index);
258
+ }
259
+ pbr['baseColorTexture'] = { index };
260
+ }
261
+ materials.push({ name: material.name, pbrMetallicRoughness: pbr, doubleSided: material.side === 2 });
262
+ meshes.push({ name: part.name ?? `${bake.name}.${String(p)}`, primitives: [primitive] });
263
+ nodes.push({ name: part.name ?? `${bake.name}.${String(p)}`, mesh: p, skin: 0 });
264
+ });
265
+ bones.forEach((bone) => {
266
+ const parent = bone.parent === null ? undefined : bones[names.get(bone.parent) ?? -1];
267
+ const children = bones.flatMap((child, c) => child.parent === bone.name ? [joint(c)] : []);
268
+ const node: Record<string, Json> = { name: bone.name, translation: bone.pos.map((n, c) => n - (parent?.pos[c] ?? 0)), extras: { wildshard: { bind: [...bone.pos] } } };
269
+ if (children.length > 0) node['children'] = children;
270
+ nodes.push(node);
271
+ });
272
+ const inverse = new Float32Array(bones.length * 16), m = new Matrix4();
273
+ bones.forEach((bone, i) => { m.makeTranslation(-bone.pos[0], -bone.pos[1], -bone.pos[2]); inverse.set(m.elements, i * 16); });
274
+ const skin = { name: bake.name, joints: bones.map((_, i) => joint(i)), inverseBindMatrices: accessor(inverse, 16, false, false) };
275
+ const animations: Json[] = (bake.clips ?? []).map((clip) => {
276
+ const samplerRows: Json[] = [], channelRows: Json[] = [];
277
+ for (const track of clip.tracks) {
278
+ const parsed = PropertyBinding.parseTrackName(track.name), node = names.get(parsed.nodeName);
279
+ const path = parsed.propertyName === 'position' ? 'translation' : parsed.propertyName === 'quaternion' ? 'rotation' : parsed.propertyName === 'scale' ? 'scale' : null;
280
+ const interpolation = track.getInterpolation() === InterpolateLinear ? 'LINEAR' : track.getInterpolation() === InterpolateDiscrete ? 'STEP' : null;
281
+ if (node === undefined || path === null || interpolation === null) throw new Error(`Skinned clip ${clip.name}: unsupported track ${track.name}`);
282
+ const width = path === 'rotation' ? 4 : 3, times = Float32Array.from(track.times), values = Float32Array.from(track.values);
283
+ samplerRows.push({ input: accessor(times, 1, false, true), output: accessor(values, width, false, false), interpolation });
284
+ channelRows.push({ sampler: samplerRows.length - 1, target: { node: joint(node), path } });
285
+ }
286
+ return { name: clip.name, samplers: samplerRows, channels: channelRows };
287
+ });
288
+ const roots = bones.flatMap((bone, i) => bone.parent === null ? [joint(i)] : []);
289
+ const doc: Record<string, Json> = {
290
+ asset: { version: '2.0', generator: 'wildshard-skinned-v1', extras: { wildshard: bake.extras ?? null } },
291
+ scene: 0, scenes: [{ name: bake.name, nodes: [...bake.parts.map((_, p) => p), ...roots] }], nodes, meshes, materials, skins: [skin], accessors, bufferViews: views,
292
+ buffers: fallback === 0 ? [{ byteLength: offset }] : [{ byteLength: offset }, { byteLength: fallback, extensions: { [MESHOPT]: { fallback: true } } }],
293
+ };
294
+ if (fallback > 0) used.add(MESHOPT);
295
+ if (animations.length > 0) doc['animations'] = animations;
296
+ if (images.length > 0) { doc['images'] = images; doc['samplers'] = samplers; doc['textures'] = textures; }
297
+ if (used.size > 0) { doc['extensionsUsed'] = [...used].sort(); doc['extensionsRequired'] = [...used].sort(); }
298
+ const bin = new Uint8Array(offset); let at = 0;
299
+ for (const chunk of chunks) { bin.set(chunk, at); at += chunk.length; }
300
+ return { glb: joinGlb(doc, bin) };
301
+ }
302
+
303
+ /** Bind every triangle rigidly to the bone `boneOf` names for its centroid (bone indices in the caller's skeleton order). */
304
+ export function bindRigid(g: BufferGeometry, boneOf: (x: number, y: number, z: number) => number): BufferGeometry {
305
+ const p = g.getAttribute('position'), n = p.count, index = new Uint16Array(n * 4), weight = new Float32Array(n * 4);
306
+ for (let t = 0; t + 2 < n; t += 3) {
307
+ const bone = boneOf((p.getX(t) + p.getX(t + 1) + p.getX(t + 2)) / 3, (p.getY(t) + p.getY(t + 1) + p.getY(t + 2)) / 3, (p.getZ(t) + p.getZ(t + 1) + p.getZ(t + 2)) / 3);
308
+ for (let v = t; v < t + 3; v++) { index[v * 4] = bone; weight[v * 4] = 1; }
309
+ }
310
+ g.setAttribute('skinIndex', new Uint16BufferAttribute(index, 4)); g.setAttribute('skinWeight', new Float32BufferAttribute(weight, 4));
311
+ return g;
312
+ }