@carbonenginejs/runtime-resource 0.8.0 → 0.9.1

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 (297) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +31 -29
  3. package/README.md +67 -548
  4. package/dist/CjsMotherLode.js +1271 -1271
  5. package/dist/CjsResMan.js +3005 -3005
  6. package/dist/CjsResManQueue.js +214 -214
  7. package/dist/CjsResource.js +566 -566
  8. package/dist/CjsResourceSource.js +68 -59
  9. package/dist/CjsResourceSource.js.map +1 -1
  10. package/dist/_virtual/_rollupPluginBabelHelpers.js +153 -153
  11. package/dist/format/CjsBlueReader.js +269 -269
  12. package/dist/format/CjsFormat.js +197 -192
  13. package/dist/format/CjsFormat.js.map +1 -1
  14. package/dist/format/CjsReader.js +18 -18
  15. package/dist/format/CjsResourceProbe.js +277 -277
  16. package/dist/format/payloadContract.js +173 -173
  17. package/dist/formats/black/CjsBlackFormat.js +278 -278
  18. package/dist/formats/black/core/CjsBlackBinaryReader.js +157 -153
  19. package/dist/formats/black/core/CjsBlackBinaryReader.js.map +1 -1
  20. package/dist/formats/black/core/CjsBlackPropertyReaders.js +387 -382
  21. package/dist/formats/black/core/CjsBlackPropertyReaders.js.map +1 -1
  22. package/dist/formats/black/core/CjsBlackReader.js +639 -639
  23. package/dist/formats/black/core/CjsBlackSchemaRegistry.js +437 -433
  24. package/dist/formats/black/core/CjsBlackSchemaRegistry.js.map +1 -1
  25. package/dist/formats/black/core/black-schema-v1-2026-07-23.json.js +4 -0
  26. package/dist/formats/black/core/black-schema-v1-2026-07-23.json.js.map +1 -0
  27. package/dist/formats/black/core/blackConstants.js +7 -7
  28. package/dist/formats/black/core/blackDefinitions.js +10 -10
  29. package/dist/formats/black/core/blackDefinitions.js.map +1 -1
  30. package/dist/formats/black/core/blackEnums.js +6 -6
  31. package/dist/formats/black/core/blackSchema.js +3 -3
  32. package/dist/formats/black/core/blackVersion.js +22 -22
  33. package/dist/formats/black/core/helpers.js +182 -182
  34. package/dist/formats/black/core/schema.js +4 -4
  35. package/dist/formats/black/index.js +2 -2
  36. package/dist/formats/bnk/CjsBnkFormat.js +125 -125
  37. package/dist/formats/bnk/core/graph.js +140 -140
  38. package/dist/formats/bnk/core/helpers.js +409 -409
  39. package/dist/formats/bnk/core/musicNodes.js +493 -489
  40. package/dist/formats/bnk/core/musicNodes.js.map +1 -1
  41. package/dist/formats/bnk/core/soundbanksInfo.js +246 -246
  42. package/dist/formats/bnk/index.js +2 -2
  43. package/dist/formats/cmf/CjsCmfFormat.js +497 -497
  44. package/dist/formats/cmf/core/binary.js +123 -118
  45. package/dist/formats/cmf/core/binary.js.map +1 -1
  46. package/dist/formats/cmf/core/buffers.js +233 -233
  47. package/dist/formats/cmf/core/constants.js +47 -47
  48. package/dist/formats/cmf/core/gr2Anim.js +453 -453
  49. package/dist/formats/cmf/core/helpers.js +287 -287
  50. package/dist/formats/cmf/core/pack.js +276 -276
  51. package/dist/formats/cmf/core/schema.js +364 -364
  52. package/dist/formats/cmf/core/shared.js +268 -268
  53. package/dist/formats/cmf/core/writer.js +517 -517
  54. package/dist/formats/cmf/index.js +2 -2
  55. package/dist/formats/dds/CjsDdsFormat.js +200 -193
  56. package/dist/formats/dds/CjsDdsFormat.js.map +1 -1
  57. package/dist/formats/dds/core/bc6h.js +288 -288
  58. package/dist/formats/dds/core/bc7.js +256 -251
  59. package/dist/formats/dds/core/bc7.js.map +1 -1
  60. package/dist/formats/dds/core/helpers.js +815 -815
  61. package/dist/formats/dds/index.js +2 -2
  62. package/dist/formats/fbx/CjsFbxFormat.js +266 -266
  63. package/dist/formats/fbx/core/helpers.js +3911 -3901
  64. package/dist/formats/fbx/core/helpers.js.map +1 -1
  65. package/dist/formats/fbx/index.js +2 -2
  66. package/dist/formats/flac/CjsFlacFormat.js +93 -87
  67. package/dist/formats/flac/CjsFlacFormat.js.map +1 -1
  68. package/dist/formats/flac/core/helpers.js +295 -295
  69. package/dist/formats/flac/index.js +2 -2
  70. package/dist/formats/gif/CjsGifFormat.js +92 -87
  71. package/dist/formats/gif/CjsGifFormat.js.map +1 -1
  72. package/dist/formats/gif/core/helpers.js +360 -360
  73. package/dist/formats/gif/index.js +2 -2
  74. package/dist/formats/gltf/CjsGltfFormat.js +290 -290
  75. package/dist/formats/gltf/core/helpers.js +292 -292
  76. package/dist/formats/gltf/core/json.js +79 -79
  77. package/dist/formats/gltf/core/parser.js +666 -666
  78. package/dist/formats/gltf/core/targets.js +163 -163
  79. package/dist/formats/gltf/index.js +2 -2
  80. package/dist/formats/gr2/CjsGr2Format.js +46 -0
  81. package/dist/formats/gr2/CjsGr2Format.js.map +1 -0
  82. package/dist/formats/gr2/core/CjsFormatGr2.js +273 -0
  83. package/dist/formats/gr2/core/CjsFormatGr2.js.map +1 -0
  84. package/dist/formats/gr2/core/bitknit2.js +280 -0
  85. package/dist/formats/gr2/core/bitknit2.js.map +1 -0
  86. package/dist/formats/gr2/core/curves.js +1047 -0
  87. package/dist/formats/gr2/core/curves.js.map +1 -0
  88. package/dist/formats/gr2/core/gsf.js +72 -0
  89. package/dist/formats/gr2/core/gsf.js.map +1 -0
  90. package/dist/formats/gr2/core/helpers.js +332 -0
  91. package/dist/formats/gr2/core/helpers.js.map +1 -0
  92. package/dist/formats/gr2/core/json.js +622 -0
  93. package/dist/formats/gr2/core/json.js.map +1 -0
  94. package/dist/formats/gr2/core/oodle1.js +388 -0
  95. package/dist/formats/gr2/core/oodle1.js.map +1 -0
  96. package/dist/formats/gr2/core/reader.js +617 -0
  97. package/dist/formats/gr2/core/reader.js.map +1 -0
  98. package/dist/formats/gr2/core/tangents.js +48 -0
  99. package/dist/formats/gr2/core/tangents.js.map +1 -0
  100. package/dist/formats/gr2/core/targets.js +351 -0
  101. package/dist/formats/gr2/core/targets.js.map +1 -0
  102. package/dist/formats/gr2/index.js +3 -0
  103. package/dist/formats/gr2/index.js.map +1 -0
  104. package/dist/formats/index.js +30 -23
  105. package/dist/formats/index.js.map +1 -1
  106. package/dist/formats/jpeg/CjsJpegFormat.js +212 -206
  107. package/dist/formats/jpeg/CjsJpegFormat.js.map +1 -1
  108. package/dist/formats/jpeg/core/helpers.js +350 -350
  109. package/dist/formats/jpeg/core/jpeg.js +387 -377
  110. package/dist/formats/jpeg/core/jpeg.js.map +1 -1
  111. package/dist/formats/jpeg/index.js +2 -2
  112. package/dist/formats/mp3/CjsMp3Format.js +197 -192
  113. package/dist/formats/mp3/CjsMp3Format.js.map +1 -1
  114. package/dist/formats/mp3/core/helpers.js +338 -338
  115. package/dist/formats/mp3/index.js +2 -2
  116. package/dist/formats/mp4/CjsMp4Format.js +197 -191
  117. package/dist/formats/mp4/CjsMp4Format.js.map +1 -1
  118. package/dist/formats/mp4/core/helpers.js +449 -449
  119. package/dist/formats/mp4/index.js +2 -2
  120. package/dist/formats/obj/CjsObjFormat.js +253 -253
  121. package/dist/formats/obj/core/helpers.js +573 -573
  122. package/dist/formats/obj/core/json.js +64 -64
  123. package/dist/formats/obj/core/parser.js +321 -321
  124. package/dist/formats/obj/index.js +2 -2
  125. package/dist/formats/ogg/CjsOggFormat.js +94 -88
  126. package/dist/formats/ogg/CjsOggFormat.js.map +1 -1
  127. package/dist/formats/ogg/core/helpers.js +387 -387
  128. package/dist/formats/ogg/core/imdct.js +178 -178
  129. package/dist/formats/ogg/core/vorbis.js +1004 -999
  130. package/dist/formats/ogg/core/vorbis.js.map +1 -1
  131. package/dist/formats/ogg/index.js +2 -2
  132. package/dist/formats/png/CjsPngFormat.js +201 -195
  133. package/dist/formats/png/CjsPngFormat.js.map +1 -1
  134. package/dist/formats/png/core/helpers.js +583 -583
  135. package/dist/formats/png/index.js +2 -2
  136. package/dist/formats/red/CjsRedFormat.js +261 -261
  137. package/dist/formats/red/core/CjsRedReader.js +194 -194
  138. package/dist/formats/red/core/blackDefinitions.js +3 -3
  139. package/dist/formats/red/core/helpers.js +139 -139
  140. package/dist/formats/red/core/redGraph.js +68 -68
  141. package/dist/formats/red/core/schema.js +4 -4
  142. package/dist/formats/red/index.js +2 -2
  143. package/dist/formats/stl/CjsStlFormat.js +365 -365
  144. package/dist/formats/stl/core/helpers.js +261 -261
  145. package/dist/formats/stl/core/json.js +51 -51
  146. package/dist/formats/stl/core/stl.js +634 -629
  147. package/dist/formats/stl/core/stl.js.map +1 -1
  148. package/dist/formats/stl/core/targets.js +163 -163
  149. package/dist/formats/stl/index.js +2 -2
  150. package/dist/formats/tga/CjsTgaFormat.js +197 -192
  151. package/dist/formats/tga/CjsTgaFormat.js.map +1 -1
  152. package/dist/formats/tga/core/helpers.js +446 -446
  153. package/dist/formats/tga/index.js +2 -2
  154. package/dist/formats/wav/CjsWavFormat.js +198 -192
  155. package/dist/formats/wav/CjsWavFormat.js.map +1 -1
  156. package/dist/formats/wav/core/helpers.js +328 -328
  157. package/dist/formats/wav/index.js +2 -2
  158. package/dist/formats/webm/CjsWebmFormat.js +197 -191
  159. package/dist/formats/webm/CjsWebmFormat.js.map +1 -1
  160. package/dist/formats/webm/core/helpers.js +537 -537
  161. package/dist/formats/webm/index.js +2 -2
  162. package/dist/formats/webp/CjsWebpFormat.js +91 -86
  163. package/dist/formats/webp/CjsWebpFormat.js.map +1 -1
  164. package/dist/formats/webp/core/helpers.js +214 -214
  165. package/dist/formats/webp/index.js +2 -2
  166. package/dist/formats/wem/CjsWemFormat.js +242 -241
  167. package/dist/formats/wem/CjsWemFormat.js.map +1 -1
  168. package/dist/formats/wem/core/bitStream.js +259 -259
  169. package/dist/formats/wem/core/codebookLibrary.js +164 -164
  170. package/dist/formats/wem/core/helpers.js +417 -417
  171. package/dist/formats/wem/core/packedCodebooksAotuv603.js +30 -30
  172. package/dist/formats/wem/core/ptadpcm.js +77 -77
  173. package/dist/formats/wem/core/resolve.js +121 -121
  174. package/dist/formats/wem/core/wemToOgg.js +485 -485
  175. package/dist/formats/wem/index.js +2 -2
  176. package/dist/formats/yaml/CjsYamlFormat.js +89 -83
  177. package/dist/formats/yaml/CjsYamlFormat.js.map +1 -1
  178. package/dist/formats/yaml/core/CjsYamlReader.js +311 -305
  179. package/dist/formats/yaml/core/CjsYamlReader.js.map +1 -1
  180. package/dist/formats/yaml/core/helpers.js +160 -160
  181. package/dist/formats/yaml/index.js +2 -2
  182. package/dist/index.js +49 -48
  183. package/dist/index.js.map +1 -1
  184. package/dist/resourcePath.js +18 -18
  185. package/dist/resourceStates.js +9 -9
  186. package/dist/resources/AudioGeometryResData.js +47 -47
  187. package/dist/resources/GStateBindingCallbackData.js +31 -31
  188. package/dist/resources/MeshDecalData.js +37 -37
  189. package/dist/resources/MeshDecalLodData.js +34 -34
  190. package/dist/resources/Tr2EffectRes.js +71 -71
  191. package/dist/resources/Tr2GrannyIntersectionResult.js +60 -60
  192. package/dist/resources/Tr2GrannyStateRes.js +44 -44
  193. package/dist/resources/Tr2ImageRes.js +114 -114
  194. package/dist/resources/Tr2LightProfileRes.js +40 -40
  195. package/dist/resources/Tr2MaterialArea.js +34 -34
  196. package/dist/resources/Tr2MaterialMesh.js +31 -31
  197. package/dist/resources/Tr2MaterialRes.js +34 -34
  198. package/dist/resources/Tr2ShaderPermutation.js +43 -43
  199. package/dist/resources/Tr2TextureLodManager.js +80 -80
  200. package/dist/resources/Tr2TextureLodUpdateRequest.js +37 -37
  201. package/dist/resources/Tr2TexturePackChannel.js +37 -37
  202. package/dist/resources/Tr2TexturePipeline.js +52 -52
  203. package/dist/resources/Tr2TexturePipelineParams.js +34 -34
  204. package/dist/resources/Tr2TexturePipelineStepCompress.js +40 -40
  205. package/dist/resources/Tr2TexturePipelineStepGenerateMips.js +22 -0
  206. package/dist/resources/Tr2TexturePipelineStepGenerateMips.js.map +1 -0
  207. package/dist/resources/Tr2TexturePipelineStepLimitSize.js +34 -34
  208. package/dist/resources/Tr2TexturePipelineStepLoad.js +31 -31
  209. package/dist/resources/Tr2TexturePipelineStepPack.js +43 -43
  210. package/dist/resources/TriGeometryRes.js +239 -239
  211. package/dist/resources/TriGeometryResAreaData.js +59 -59
  212. package/dist/resources/TriGeometryResJointData.js +38 -38
  213. package/dist/resources/TriGeometryResLodData.js +88 -88
  214. package/dist/resources/TriGeometryResMeshData.js +63 -63
  215. package/dist/resources/TriGeometryResSkeletonData.js +34 -34
  216. package/dist/resources/TriGrannyRes.js +43 -43
  217. package/dist/resources/TriJointBinding.js +38 -38
  218. package/dist/resources/TriMorphTargetGeometryConstants.js +46 -46
  219. package/dist/resources/TriRtGeometryConstants.js +88 -88
  220. package/dist/resources/TriTextureRes.js +304 -304
  221. package/dist/resources/enums.js +18 -18
  222. package/dist/resources/resourceBoundary.js +47 -47
  223. package/dist/resources/texturePipelineBehavior.js +308 -308
  224. package/dist/texture/CjsTextureArrayRes.js +406 -406
  225. package/dist/texture/CjsTextureParameterProxy.js +133 -133
  226. package/docs/README.md +73 -0
  227. package/docs/architecture.md +86 -0
  228. package/docs/concepts/resource-lifecycle.md +217 -0
  229. package/docs/formats/README.md +105 -0
  230. package/docs/formats/gr2.md +161 -0
  231. package/{FORMAT-PROVENANCE.md → docs/formats/provenance.md} +173 -155
  232. package/docs/formats/stl.md +37 -0
  233. package/docs/formats/wwise.md +44 -0
  234. package/docs/reference/classes/README.md +33 -0
  235. package/docs/reference/classes/core.md +106 -0
  236. package/docs/reference/classes/dropped.md +46 -0
  237. package/docs/reference/classes/formats.md +522 -0
  238. package/docs/reference/classes/resources.md +346 -0
  239. package/docs/reference/classes/texture.md +26 -0
  240. package/docs/reference/events.md +92 -0
  241. package/docs/reference/motherlode-cache.md +244 -0
  242. package/docs/reference/queues.md +102 -0
  243. package/docs/reference/reload.md +107 -0
  244. package/docs/reference/texture-arrays.md +113 -0
  245. package/docs/reference/texture-pipeline.md +53 -0
  246. package/docs/roadmap.md +104 -0
  247. package/format-notices/black/LICENSE +21 -21
  248. package/format-notices/black/NOTICE +47 -47
  249. package/format-notices/bnk/LICENSE +21 -21
  250. package/format-notices/bnk/NOTICE +20 -20
  251. package/format-notices/cmf/LICENSE +21 -21
  252. package/format-notices/cmf/NOTICE +36 -36
  253. package/format-notices/dds/LICENSE +21 -21
  254. package/format-notices/dds/NOTICE +14 -14
  255. package/format-notices/fbx/LICENSE +21 -21
  256. package/format-notices/fbx/NOTICE +14 -14
  257. package/format-notices/flac/LICENSE +21 -21
  258. package/format-notices/flac/NOTICE +14 -14
  259. package/format-notices/gif/LICENSE +21 -21
  260. package/format-notices/gif/NOTICE +14 -14
  261. package/format-notices/gltf/LICENSE +21 -21
  262. package/format-notices/gltf/NOTICE +27 -27
  263. package/format-notices/gr2/LICENSE +21 -0
  264. package/format-notices/gr2/NOTICE +60 -0
  265. package/format-notices/gr2/THIRD-PARTY-NOTICES.md +93 -0
  266. package/format-notices/jpeg/LICENSE +21 -21
  267. package/format-notices/jpeg/NOTICE +14 -14
  268. package/format-notices/mp3/LICENSE +21 -21
  269. package/format-notices/mp3/NOTICE +14 -14
  270. package/format-notices/mp4/LICENSE +21 -21
  271. package/format-notices/mp4/NOTICE +14 -14
  272. package/format-notices/obj/LICENSE +21 -21
  273. package/format-notices/obj/NOTICE +26 -26
  274. package/format-notices/ogg/LICENSE +21 -21
  275. package/format-notices/ogg/NOTICE +28 -28
  276. package/format-notices/png/LICENSE +21 -21
  277. package/format-notices/png/NOTICE +14 -14
  278. package/format-notices/red/LICENSE +21 -21
  279. package/format-notices/red/NOTICE +31 -31
  280. package/format-notices/stl/LICENSE +21 -21
  281. package/format-notices/stl/NOTICE +21 -21
  282. package/format-notices/tga/LICENSE +21 -21
  283. package/format-notices/tga/NOTICE +14 -14
  284. package/format-notices/wav/LICENSE +21 -21
  285. package/format-notices/wav/NOTICE +14 -14
  286. package/format-notices/webm/LICENSE +21 -21
  287. package/format-notices/webm/NOTICE +14 -14
  288. package/format-notices/webp/LICENSE +21 -21
  289. package/format-notices/webp/NOTICE +14 -14
  290. package/format-notices/wem/LICENSE +57 -57
  291. package/format-notices/wem/NOTICE +33 -33
  292. package/format-notices/yaml/LICENSE +21 -21
  293. package/format-notices/yaml/NOTICE +44 -44
  294. package/package.json +52 -51
  295. package/dist/formats/black/core/black-schema-v1-2026-07-11.json.js +0 -4
  296. package/dist/formats/black/core/black-schema-v1-2026-07-11.json.js.map +0 -1
  297. package/resource-lifecycle.md +0 -679
@@ -1,517 +1,517 @@
1
- import { MeshoptEncoder } from 'meshoptimizer/encoder';
2
- import { STRUCT_SIZE, FILE_SIGNATURE, FILE_VERSION, SectionType, SectionCompression, MeshTopology, AnimationChannelTargetType, Interpolation, ElementType, Usage } from './constants.js';
3
- import { crc32 } from './binary.js';
4
-
5
- /**
6
- * Binary CMF v1 writer.
7
- *
8
- * Mirrors CarbonEngine's `cmf::BuildFile`: the object graph is flattened into
9
- * the Data section as structs with self-relative tagged span offsets
10
- * (depth-first in member order, 8-byte chunk alignment, identical leaf chunks
11
- * deduplicated), GPU buffers referenced by BufferViews become one section
12
- * each (remapped to section indices in first-encounter order, meshoptimizer
13
- * compressed by default), optional metadata flattens into a trailing section,
14
- * and the header CRC covers everything after the crc32 field.
15
- */
16
-
17
- const textEncoder = new TextEncoder();
18
- let encoderReady = false;
19
- MeshoptEncoder.ready.then(() => {
20
- encoderReady = true;
21
- });
22
- function writeError(message) {
23
- const error = new Error(`CMF write: ${message}`);
24
- error.code = "CJS_FORMAT_WRITE_ERROR";
25
- return error;
26
- }
27
- function enumValue(names, value, label) {
28
- if (typeof value === "number") return value;
29
- const index = names.indexOf(value);
30
- if (index >= 0) return index;
31
- const unknown = /^Unknown\((\d+)\)$/u.exec(String(value ?? ""));
32
- if (unknown) return Number(unknown[1]);
33
- throw writeError(`unknown ${label} value ${JSON.stringify(value)}`);
34
- }
35
-
36
- /**
37
- * Growable little-endian struct buffer with tagged span support.
38
- */
39
- class Flattener {
40
- #bytes = new Uint8Array(1024);
41
- #view = new DataView(this.#bytes.buffer);
42
- #chunkCache = new Map();
43
- size = 0;
44
- #ensure(capacity) {
45
- if (capacity <= this.#bytes.length) return;
46
- let next = this.#bytes.length * 2;
47
- while (next < capacity) next *= 2;
48
- const grown = new Uint8Array(next);
49
- grown.set(this.#bytes.subarray(0, this.size));
50
- this.#bytes = grown;
51
- this.#view = new DataView(grown.buffer);
52
- }
53
- reserve(byteLength) {
54
- const offset = this.size;
55
- this.#ensure(offset + byteLength);
56
- this.#bytes.fill(0, offset, offset + byteLength);
57
- this.size = offset + byteLength;
58
- return offset;
59
- }
60
- reserveAligned(byteLength, alignment = 8) {
61
- const padded = Math.ceil(this.size / alignment) * alignment;
62
- this.#ensure(padded);
63
- this.#bytes.fill(0, this.size, padded);
64
- this.size = padded;
65
- return this.reserve(byteLength);
66
- }
67
- u8(offset, value) {
68
- this.#view.setUint8(offset, value);
69
- }
70
- u16(offset, value) {
71
- this.#view.setUint16(offset, value, true);
72
- }
73
- u32(offset, value) {
74
- this.#view.setUint32(offset, value >>> 0, true);
75
- }
76
- f32(offset, value) {
77
- this.#view.setFloat32(offset, value || 0, true);
78
- }
79
- i64(offset, value) {
80
- this.#view.setBigInt64(offset, BigInt(value), true);
81
- }
82
- u64(offset, value) {
83
- this.#view.setBigUint64(offset, BigInt(value), true);
84
- }
85
- setBytes(offset, bytes) {
86
- this.#bytes.set(bytes, offset);
87
- }
88
-
89
- /**
90
- * Write a span field and append its element chunk.
91
- *
92
- * `writeElement(flattener, offset, element)` may itself append nested
93
- * chunks; leaf chunks (`dedup: true`) are shared when byte-identical,
94
- * matching the reference writer.
95
- */
96
- span(fieldOffset, elements, elementSize, writeElement, {
97
- dedup = false
98
- } = {}) {
99
- const count = elements ? elements.length : 0;
100
- const byteSize = count * elementSize;
101
- if (byteSize === 0) {
102
- // tagged self-relative offset of 0 keeps span pointers valid
103
- this.i64(fieldOffset, 1);
104
- this.u64(fieldOffset + 8, 0);
105
- return;
106
- }
107
- if (dedup) {
108
- const scratch = new Flattener();
109
- const scratchOffset = scratch.reserve(byteSize);
110
- for (let i = 0; i < count; i++) writeElement(scratch, scratchOffset + i * elementSize, elements[i]);
111
- const chunk = scratch.bytes();
112
- const key = chunkKey(chunk);
113
- const cached = this.#chunkCache.get(key);
114
- if (cached !== undefined && bytesEqual(this.#bytes, cached, chunk)) {
115
- this.i64(fieldOffset, cached - fieldOffset | 1);
116
- this.u64(fieldOffset + 8, byteSize);
117
- return;
118
- }
119
- const chunkOffset = this.reserveAligned(byteSize);
120
- this.setBytes(chunkOffset, chunk);
121
- this.#chunkCache.set(key, chunkOffset);
122
- this.i64(fieldOffset, chunkOffset - fieldOffset | 1);
123
- this.u64(fieldOffset + 8, byteSize);
124
- return;
125
- }
126
- const chunkOffset = this.reserveAligned(byteSize);
127
- this.i64(fieldOffset, chunkOffset - fieldOffset | 1);
128
- this.u64(fieldOffset + 8, byteSize);
129
- for (let i = 0; i < count; i++) writeElement(this, chunkOffset + i * elementSize, elements[i]);
130
- }
131
- string(fieldOffset, value) {
132
- const encoded = textEncoder.encode(value || "");
133
- this.span(fieldOffset, encoded, 1, (buffer, offset, byte) => buffer.u8(offset, byte), {
134
- dedup: true
135
- });
136
- }
137
- bytes() {
138
- return this.#bytes.slice(0, this.size);
139
- }
140
- }
141
- function chunkKey(bytes) {
142
- let hash = 2166136261 >>> 0;
143
- for (let i = 0; i < bytes.length; i++) {
144
- hash = Math.imul(hash, 16777619) >>> 0;
145
- hash = (hash ^ bytes[i]) >>> 0;
146
- }
147
- return `${bytes.length}:${hash}`;
148
- }
149
- function bytesEqual(target, offset, chunk) {
150
- for (let i = 0; i < chunk.length; i++) {
151
- if (target[offset + i] !== chunk[i]) return false;
152
- }
153
- return true;
154
- }
155
- function writeBounds(buffer, offset, bounds) {
156
- const min = bounds?.min || [0, 0, 0];
157
- const max = bounds?.max || [0, 0, 0];
158
- for (let i = 0; i < 3; i++) buffer.f32(offset + i * 4, min[i]);
159
- for (let i = 0; i < 3; i++) buffer.f32(offset + 12 + i * 4, max[i]);
160
- }
161
- function writeBufferView(buffer, offset, view, remap) {
162
- const size = view?.size || 0;
163
- const index = view?.index || 0;
164
- buffer.u32(offset, size === 0 ? index : remap.get(index) ?? index);
165
- buffer.u32(offset + 4, view?.offset || 0);
166
- buffer.u32(offset + 8, size);
167
- buffer.u32(offset + 12, view?.stride || 0);
168
- }
169
- function writeVertexElement(buffer, offset, element) {
170
- buffer.u8(offset, enumValue(Usage, element.usage, "vertex usage"));
171
- buffer.u8(offset + 1, element.usageIndex || 0);
172
- buffer.u8(offset + 2, enumValue(ElementType, element.type, "element type"));
173
- buffer.u8(offset + 3, element.elementCount || 0);
174
- buffer.u32(offset + 4, element.offset || 0);
175
- }
176
- function writeData(buffer, offset, graph, remap) {
177
- const writeMesh = (target, meshOffset, mesh) => {
178
- target.string(meshOffset, mesh.name);
179
- target.span(meshOffset + 16, mesh.decl || [], STRUCT_SIZE.VertexElement, writeVertexElement, {
180
- dedup: true
181
- });
182
- target.span(meshOffset + 32, mesh.lods || [], STRUCT_SIZE.MeshLod, (lodTarget, lodOffset, lod) => {
183
- writeBufferView(lodTarget, lodOffset, lod.vb, remap);
184
- writeBufferView(lodTarget, lodOffset + 16, lod.ib, remap);
185
- lodTarget.span(lodOffset + 32, lod.areas || [], STRUCT_SIZE.LodMeshArea, (areaTarget, areaOffset, area) => {
186
- areaTarget.u32(areaOffset, area.firstElement || 0);
187
- areaTarget.u32(areaOffset + 4, area.elementCount || 0);
188
- }, {
189
- dedup: true
190
- });
191
- lodTarget.span(lodOffset + 48, lod.morphTargets || [], STRUCT_SIZE.LodMorphTarget, (morphTarget, morphOffset, morph) => {
192
- writeBufferView(morphTarget, morphOffset, morph.vb, remap);
193
- });
194
- lodTarget.u32(lodOffset + 64, lod.threshold ?? 0xffffffff);
195
- });
196
- target.span(meshOffset + 48, mesh.areas || [], STRUCT_SIZE.MeshArea, (areaTarget, areaOffset, area) => {
197
- areaTarget.string(areaOffset, area.name);
198
- writeBounds(areaTarget, areaOffset + 16, area.bounds);
199
- areaTarget.span(areaOffset + 40, area.bones || [], 2, (boneTarget, boneOffset, bone) => boneTarget.u16(boneOffset, bone), {
200
- dedup: true
201
- });
202
- areaTarget.u8(areaOffset + 56, area.affectedByBones ? 1 : 0);
203
- areaTarget.u8(areaOffset + 57, area.affectedByMorphTargets ? 1 : 0);
204
- });
205
- target.span(meshOffset + 64, mesh.boneBindings || [], STRUCT_SIZE.BoneBinding, (bindingTarget, bindingOffset, binding) => {
206
- bindingTarget.string(bindingOffset, binding.name);
207
- writeBounds(bindingTarget, bindingOffset + 16, binding.bounds);
208
- });
209
- target.span(meshOffset + 80, mesh.morphTargets?.decl || [], STRUCT_SIZE.VertexElement, writeVertexElement, {
210
- dedup: true
211
- });
212
- target.span(meshOffset + 96, mesh.morphTargets?.targets || [], STRUCT_SIZE.MorphTarget, (morphTarget, morphOffset, morph) => {
213
- morphTarget.string(morphOffset, morph.name);
214
- morphTarget.f32(morphOffset + 16, morph.maxDisplacement || 0);
215
- });
216
- target.span(meshOffset + 112, mesh.uvDensities || [], 4, (densityTarget, densityOffset, value) => densityTarget.f32(densityOffset, value), {
217
- dedup: true
218
- });
219
- writeBounds(target, meshOffset + 128, mesh.bounds);
220
- const occlusion = mesh.audioOcclusionMesh || {};
221
- target.span(meshOffset + 152, occlusion.vertices || [], 12, (vertexTarget, vertexOffset, vertex) => {
222
- for (let i = 0; i < 3; i++) vertexTarget.f32(vertexOffset + i * 4, vertex[i]);
223
- }, {
224
- dedup: true
225
- });
226
- target.span(meshOffset + 168, occlusion.indices || [], 2, (indexTarget, indexOffset, index) => indexTarget.u16(indexOffset, index), {
227
- dedup: true
228
- });
229
- writeBounds(target, meshOffset + 184, occlusion.bounds);
230
- target.u8(meshOffset + 208, enumValue(MeshTopology, mesh.topology ?? "TriangleList", "topology"));
231
- target.u8(meshOffset + 209, mesh.skeleton === null || mesh.skeleton === undefined ? 0xff : mesh.skeleton);
232
- };
233
- const writeSkeleton = (target, skeletonOffset, skeleton) => {
234
- if ((skeleton.bones || []).some(bone => typeof bone !== "string")) {
235
- throw writeError("skeleton bones must be name strings; GR2-shaped skeletons need conversion (use writeShared) before writing");
236
- }
237
- target.string(skeletonOffset, skeleton.name);
238
- target.span(skeletonOffset + 16, skeleton.bones || [], 16, (boneTarget, boneOffset, bone) => boneTarget.string(boneOffset, bone));
239
- target.span(skeletonOffset + 32, skeleton.parents || [], 4, (parentTarget, parentOffset, parent) => parentTarget.u32(parentOffset, parent), {
240
- dedup: true
241
- });
242
- target.span(skeletonOffset + 48, skeleton.restTransforms || [], STRUCT_SIZE.Transform, (transformTarget, transformOffset, transform) => {
243
- const position = transform.position || [0, 0, 0];
244
- const rotation = transform.rotation || [0, 0, 0, 1];
245
- const scale = transform.scale || [1, 1, 1];
246
- for (let i = 0; i < 3; i++) transformTarget.f32(transformOffset + i * 4, position[i]);
247
- for (let i = 0; i < 4; i++) transformTarget.f32(transformOffset + 12 + i * 4, rotation[i]);
248
- for (let i = 0; i < 3; i++) transformTarget.f32(transformOffset + 28 + i * 4, scale[i]);
249
- }, {
250
- dedup: true
251
- });
252
- target.span(skeletonOffset + 64, skeleton.invBindTransforms || [], 64, (matrixTarget, matrixOffset, matrix) => {
253
- for (let i = 0; i < 16; i++) matrixTarget.f32(matrixOffset + i * 4, matrix[i]);
254
- }, {
255
- dedup: true
256
- });
257
- target.span(skeletonOffset + 80, skeleton.boneMasks || [], STRUCT_SIZE.BoneMask, (maskTarget, maskOffset, mask) => {
258
- maskTarget.string(maskOffset, mask.name);
259
- maskTarget.span(maskOffset + 16, mask.weights || [], STRUCT_SIZE.BoneWeight, (weightTarget, weightOffset, weight) => {
260
- weightTarget.u32(weightOffset, weight.index || 0);
261
- weightTarget.f32(weightOffset + 4, weight.weight ?? 1);
262
- }, {
263
- dedup: true
264
- });
265
- });
266
- };
267
- const writeAnimation = (target, animationOffset, animation) => {
268
- target.string(animationOffset, animation.name);
269
- target.span(animationOffset + 16, animation.channels || [], STRUCT_SIZE.AnimationChannel, (channelTarget, channelOffset, channel) => {
270
- channelTarget.string(channelOffset, channel.target);
271
- channelTarget.u8(channelOffset + 16, enumValue(AnimationChannelTargetType, channel.targetType, "channel target type"));
272
- channelTarget.u32(channelOffset + 20, channel.curveIndex || 0);
273
- });
274
- target.span(animationOffset + 32, animation.curves || [], STRUCT_SIZE.AnimationCurve, (curveTarget, curveOffset, curve) => {
275
- curveTarget.u8(curveOffset, curve.valueDimension || 0);
276
- curveTarget.u8(curveOffset + 1, enumValue(Interpolation, curve.interpolation, "interpolation"));
277
- curveTarget.u8(curveOffset + 2, enumValue(ElementType, curve.knotType, "knot type"));
278
- curveTarget.u8(curveOffset + 3, enumValue(ElementType, curve.valueType, "value type"));
279
- curveTarget.u32(curveOffset + 4, curve.knotCount || 0);
280
- curveTarget.span(curveOffset + 8, curve.knots || [], 1, (knotTarget, knotOffset, knot) => knotTarget.u8(knotOffset, knot), {
281
- dedup: true
282
- });
283
- curveTarget.span(curveOffset + 24, curve.values || [], 1, (valueTarget, valueOffset, value) => valueTarget.u8(valueOffset, value), {
284
- dedup: true
285
- });
286
- });
287
- target.f32(animationOffset + 48, animation.duration || 0);
288
- };
289
- buffer.span(offset, graph.meshes || [], STRUCT_SIZE.Mesh, writeMesh);
290
- buffer.span(offset + 16, graph.skeletons || [], STRUCT_SIZE.Skeleton, writeSkeleton);
291
- buffer.span(offset + 32, graph.animations || [], STRUCT_SIZE.Animation, writeAnimation);
292
- }
293
-
294
- /**
295
- * Collect BufferView usage in reference-writer order and decide per-buffer
296
- * compression (conflicting stride/kind across views falls back to None).
297
- */
298
- function collectBufferRecords(graph, compress) {
299
- const records = [];
300
- const recordsByIndex = new Map();
301
- const visit = (view, compression) => {
302
- if (!view || !view.size) return;
303
- const existing = recordsByIndex.get(view.index);
304
- if (!existing) {
305
- const record = {
306
- index: view.index,
307
- stride: view.stride || 0,
308
- compression: compress ? compression : "None"
309
- };
310
- records.push(record);
311
- recordsByIndex.set(view.index, record);
312
- } else if (existing.stride !== (view.stride || 0) || (compress ? compression : "None") !== existing.compression) {
313
- existing.stride = 0;
314
- existing.compression = "None";
315
- }
316
- };
317
- for (const mesh of graph.meshes || []) {
318
- for (const lod of mesh.lods || []) {
319
- visit(lod.vb, "MeshOptimizerVertexBuffer");
320
- visit(lod.ib, "MeshOptimizerIndexBuffer");
321
- for (const morph of lod.morphTargets || []) {
322
- visit(morph.vb, "MeshOptimizerVertexBuffer");
323
- }
324
- }
325
- }
326
- return records;
327
- }
328
- function resolveBufferBytes(graph, record) {
329
- const buffers = graph.buffers || [];
330
- const entry = buffers.find?.(buffer => buffer && buffer.index === record.index) ?? buffers[record.index];
331
- const data = entry?.data ?? (entry instanceof Uint8Array ? entry : null);
332
- if (!data) {
333
- throw writeError(`no buffer data supplied for BufferView index ${record.index}`);
334
- }
335
- return data instanceof Uint8Array ? data : new Uint8Array(data);
336
- }
337
- function compressBuffer(bytes, record) {
338
- if (record.compression === "None" || bytes.byteLength === 0) {
339
- return {
340
- data: bytes,
341
- compression: "None",
342
- gpuAlignment: record.stride
343
- };
344
- }
345
- if (!encoderReady) {
346
- throw writeError("compressed output requires writeAsync/WriteAsync so meshoptimizer can initialize (or pass compress: false)");
347
- }
348
- if (record.compression === "MeshOptimizerVertexBuffer") {
349
- if (record.stride === 0 || bytes.byteLength % record.stride !== 0) {
350
- return {
351
- data: bytes,
352
- compression: "None",
353
- gpuAlignment: record.stride
354
- };
355
- }
356
- const count = bytes.byteLength / record.stride;
357
- const data = MeshoptEncoder.encodeVertexBuffer(bytes, count, record.stride);
358
- return {
359
- data,
360
- compression: "MeshOptimizerVertexBuffer",
361
- gpuAlignment: record.stride
362
- };
363
- }
364
-
365
- // index buffers: meshopt encodes triangle lists of u32; u16 sources widen
366
- const stride = record.stride;
367
- if (stride !== 2 && stride !== 4 || bytes.byteLength % stride !== 0) {
368
- return {
369
- data: bytes,
370
- compression: "None",
371
- gpuAlignment: stride
372
- };
373
- }
374
- const count = bytes.byteLength / stride;
375
- if (count % 3 !== 0) {
376
- return {
377
- data: bytes,
378
- compression: "None",
379
- gpuAlignment: stride
380
- };
381
- }
382
- let source = bytes;
383
- if (stride === 2) {
384
- const wide = new Uint32Array(count);
385
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
386
- for (let i = 0; i < count; i++) wide[i] = view.getUint16(i * 2, true);
387
- source = new Uint8Array(wide.buffer);
388
- }
389
- const data = MeshoptEncoder.encodeIndexBuffer(source, count, 4);
390
- return {
391
- data,
392
- compression: "MeshOptimizerIndexBuffer",
393
- gpuAlignment: stride
394
- };
395
- }
396
-
397
- /**
398
- * Serialize a CMF-native graph into .cmf bytes.
399
- *
400
- * @param {object} graph Native graph: `{ meshes, skeletons, animations, metadata?, buffers? }`
401
- * where `buffers` supplies uncompressed GPU bytes for each BufferView
402
- * `index` (as `{ index, data }` entries or an index-keyed array).
403
- * @param {object} [options] `compress` (default false for the sync writer)
404
- * enables meshoptimizer vertex/index compression.
405
- * @returns {Uint8Array} Complete .cmf file bytes.
406
- */
407
- function writeCmf(graph, options = {}) {
408
- if (!graph || typeof graph !== "object") {
409
- throw writeError("input graph must be an object");
410
- }
411
- const compress = options.compress === true;
412
- const records = collectBufferRecords(graph, compress);
413
- const compressed = records.map(record => {
414
- const bytes = resolveBufferBytes(graph, record);
415
- return {
416
- record,
417
- ...compressBuffer(bytes, record),
418
- uncompressedSize: bytes.byteLength
419
- };
420
- });
421
- const remap = new Map(records.map((record, position) => [record.index, position + 1]));
422
- const data = new Flattener();
423
- data.reserve(STRUCT_SIZE.Data);
424
- writeData(data, 0, graph, remap);
425
- const dataBytes = data.bytes();
426
- let metadataBytes = null;
427
- if (graph.metadata && (graph.metadata.entries || []).length) {
428
- const metadata = new Flattener();
429
- metadata.reserve(STRUCT_SIZE.Metadata);
430
- metadata.span(0, graph.metadata.entries, STRUCT_SIZE.MetadataEntry, (target, offset, entry) => {
431
- target.string(offset, entry.key);
432
- target.string(offset + 16, entry.value);
433
- });
434
- metadataBytes = metadata.bytes();
435
- }
436
- const sections = [{
437
- type: "Data",
438
- compression: "None",
439
- gpuAlignment: 0,
440
- compressedSize: dataBytes.byteLength,
441
- uncompressedSize: dataBytes.byteLength,
442
- data: dataBytes
443
- }];
444
- for (const entry of compressed) {
445
- sections.push({
446
- type: "GpuBuffer",
447
- compression: entry.compression,
448
- gpuAlignment: entry.gpuAlignment,
449
- compressedSize: entry.data.byteLength,
450
- uncompressedSize: entry.uncompressedSize,
451
- data: entry.data
452
- });
453
- }
454
- if (metadataBytes) {
455
- sections.push({
456
- type: "Metadata",
457
- compression: "None",
458
- gpuAlignment: 0,
459
- compressedSize: metadataBytes.byteLength,
460
- uncompressedSize: metadataBytes.byteLength,
461
- data: metadataBytes
462
- });
463
- }
464
- const header = new Flattener();
465
- header.reserve(STRUCT_SIZE.Header);
466
- header.u32(0, FILE_SIGNATURE);
467
- header.u32(4, FILE_VERSION);
468
- header.span(16, sections, STRUCT_SIZE.Section, () => {});
469
- const headerSize = header.size;
470
- header.u32(8, headerSize);
471
- let offset = headerSize;
472
- const sectionOffsets = sections.map(section => {
473
- offset = Math.ceil(offset / 8) * 8;
474
- const sectionOffset = offset;
475
- offset += section.compressedSize;
476
- return sectionOffset;
477
- });
478
- const sectionsChunk = headerSize - sections.length * STRUCT_SIZE.Section;
479
- sections.forEach((section, index) => {
480
- const base = sectionsChunk + index * STRUCT_SIZE.Section;
481
- header.u32(base, sectionOffsets[index]);
482
- header.u32(base + 4, section.compressedSize);
483
- header.u32(base + 8, section.uncompressedSize);
484
- header.u16(base + 12, section.gpuAlignment || 0);
485
- header.u8(base + 14, enumValue(SectionType, section.type, "section type"));
486
- header.u8(base + 15, enumValue(SectionCompression, section.compression, "section compression"));
487
- });
488
- const total = offset;
489
- const file = new Uint8Array(total);
490
- file.set(header.bytes(), 0);
491
- sections.forEach((section, index) => {
492
- file.set(section.data, sectionOffsets[index]);
493
- });
494
- const checksum = crc32(file, 16, file.byteLength);
495
- new DataView(file.buffer).setUint32(12, checksum, true);
496
- return file;
497
- }
498
-
499
- /**
500
- * Serialize a CMF-native graph asynchronously with compression enabled by
501
- * default (awaits meshoptimizer encoder initialization).
502
- *
503
- * @param {object} graph Native graph (see `writeCmf`).
504
- * @param {object} [options] `compress` defaults to true.
505
- * @returns {Promise<Uint8Array>} Complete .cmf file bytes.
506
- */
507
- async function writeCmfAsync(graph, options = {}) {
508
- await MeshoptEncoder.ready;
509
- encoderReady = true;
510
- return writeCmf(graph, {
511
- ...options,
512
- compress: options.compress !== false
513
- });
514
- }
515
-
516
- export { writeCmf, writeCmfAsync };
517
- //# sourceMappingURL=writer.js.map
1
+ import { MeshoptEncoder } from 'meshoptimizer/encoder';
2
+ import { STRUCT_SIZE, FILE_SIGNATURE, FILE_VERSION, SectionType, SectionCompression, MeshTopology, AnimationChannelTargetType, Interpolation, ElementType, Usage } from './constants.js';
3
+ import { crc32 } from './binary.js';
4
+
5
+ /**
6
+ * Binary CMF v1 writer.
7
+ *
8
+ * Mirrors CarbonEngine's `cmf::BuildFile`: the object graph is flattened into
9
+ * the Data section as structs with self-relative tagged span offsets
10
+ * (depth-first in member order, 8-byte chunk alignment, identical leaf chunks
11
+ * deduplicated), GPU buffers referenced by BufferViews become one section
12
+ * each (remapped to section indices in first-encounter order, meshoptimizer
13
+ * compressed by default), optional metadata flattens into a trailing section,
14
+ * and the header CRC covers everything after the crc32 field.
15
+ */
16
+
17
+ const textEncoder = new TextEncoder();
18
+ let encoderReady = false;
19
+ MeshoptEncoder.ready.then(() => {
20
+ encoderReady = true;
21
+ });
22
+ function writeError(message) {
23
+ const error = new Error(`CMF write: ${message}`);
24
+ error.code = "CJS_FORMAT_WRITE_ERROR";
25
+ return error;
26
+ }
27
+ function enumValue(names, value, label) {
28
+ if (typeof value === "number") return value;
29
+ const index = names.indexOf(value);
30
+ if (index >= 0) return index;
31
+ const unknown = /^Unknown\((\d+)\)$/u.exec(String(value ?? ""));
32
+ if (unknown) return Number(unknown[1]);
33
+ throw writeError(`unknown ${label} value ${JSON.stringify(value)}`);
34
+ }
35
+
36
+ /**
37
+ * Growable little-endian struct buffer with tagged span support.
38
+ */
39
+ class Flattener {
40
+ #bytes = new Uint8Array(1024);
41
+ #view = new DataView(this.#bytes.buffer);
42
+ #chunkCache = new Map();
43
+ size = 0;
44
+ #ensure(capacity) {
45
+ if (capacity <= this.#bytes.length) return;
46
+ let next = this.#bytes.length * 2;
47
+ while (next < capacity) next *= 2;
48
+ const grown = new Uint8Array(next);
49
+ grown.set(this.#bytes.subarray(0, this.size));
50
+ this.#bytes = grown;
51
+ this.#view = new DataView(grown.buffer);
52
+ }
53
+ reserve(byteLength) {
54
+ const offset = this.size;
55
+ this.#ensure(offset + byteLength);
56
+ this.#bytes.fill(0, offset, offset + byteLength);
57
+ this.size = offset + byteLength;
58
+ return offset;
59
+ }
60
+ reserveAligned(byteLength, alignment = 8) {
61
+ const padded = Math.ceil(this.size / alignment) * alignment;
62
+ this.#ensure(padded);
63
+ this.#bytes.fill(0, this.size, padded);
64
+ this.size = padded;
65
+ return this.reserve(byteLength);
66
+ }
67
+ u8(offset, value) {
68
+ this.#view.setUint8(offset, value);
69
+ }
70
+ u16(offset, value) {
71
+ this.#view.setUint16(offset, value, true);
72
+ }
73
+ u32(offset, value) {
74
+ this.#view.setUint32(offset, value >>> 0, true);
75
+ }
76
+ f32(offset, value) {
77
+ this.#view.setFloat32(offset, value || 0, true);
78
+ }
79
+ i64(offset, value) {
80
+ this.#view.setBigInt64(offset, BigInt(value), true);
81
+ }
82
+ u64(offset, value) {
83
+ this.#view.setBigUint64(offset, BigInt(value), true);
84
+ }
85
+ setBytes(offset, bytes) {
86
+ this.#bytes.set(bytes, offset);
87
+ }
88
+
89
+ /**
90
+ * Write a span field and append its element chunk.
91
+ *
92
+ * `writeElement(flattener, offset, element)` may itself append nested
93
+ * chunks; leaf chunks (`dedup: true`) are shared when byte-identical,
94
+ * matching the reference writer.
95
+ */
96
+ span(fieldOffset, elements, elementSize, writeElement, {
97
+ dedup = false
98
+ } = {}) {
99
+ const count = elements ? elements.length : 0;
100
+ const byteSize = count * elementSize;
101
+ if (byteSize === 0) {
102
+ // tagged self-relative offset of 0 keeps span pointers valid
103
+ this.i64(fieldOffset, 1);
104
+ this.u64(fieldOffset + 8, 0);
105
+ return;
106
+ }
107
+ if (dedup) {
108
+ const scratch = new Flattener();
109
+ const scratchOffset = scratch.reserve(byteSize);
110
+ for (let i = 0; i < count; i++) writeElement(scratch, scratchOffset + i * elementSize, elements[i]);
111
+ const chunk = scratch.bytes();
112
+ const key = chunkKey(chunk);
113
+ const cached = this.#chunkCache.get(key);
114
+ if (cached !== undefined && bytesEqual(this.#bytes, cached, chunk)) {
115
+ this.i64(fieldOffset, cached - fieldOffset | 1);
116
+ this.u64(fieldOffset + 8, byteSize);
117
+ return;
118
+ }
119
+ const chunkOffset = this.reserveAligned(byteSize);
120
+ this.setBytes(chunkOffset, chunk);
121
+ this.#chunkCache.set(key, chunkOffset);
122
+ this.i64(fieldOffset, chunkOffset - fieldOffset | 1);
123
+ this.u64(fieldOffset + 8, byteSize);
124
+ return;
125
+ }
126
+ const chunkOffset = this.reserveAligned(byteSize);
127
+ this.i64(fieldOffset, chunkOffset - fieldOffset | 1);
128
+ this.u64(fieldOffset + 8, byteSize);
129
+ for (let i = 0; i < count; i++) writeElement(this, chunkOffset + i * elementSize, elements[i]);
130
+ }
131
+ string(fieldOffset, value) {
132
+ const encoded = textEncoder.encode(value || "");
133
+ this.span(fieldOffset, encoded, 1, (buffer, offset, byte) => buffer.u8(offset, byte), {
134
+ dedup: true
135
+ });
136
+ }
137
+ bytes() {
138
+ return this.#bytes.slice(0, this.size);
139
+ }
140
+ }
141
+ function chunkKey(bytes) {
142
+ let hash = 2166136261 >>> 0;
143
+ for (let i = 0; i < bytes.length; i++) {
144
+ hash = Math.imul(hash, 16777619) >>> 0;
145
+ hash = (hash ^ bytes[i]) >>> 0;
146
+ }
147
+ return `${bytes.length}:${hash}`;
148
+ }
149
+ function bytesEqual(target, offset, chunk) {
150
+ for (let i = 0; i < chunk.length; i++) {
151
+ if (target[offset + i] !== chunk[i]) return false;
152
+ }
153
+ return true;
154
+ }
155
+ function writeBounds(buffer, offset, bounds) {
156
+ const min = bounds?.min || [0, 0, 0];
157
+ const max = bounds?.max || [0, 0, 0];
158
+ for (let i = 0; i < 3; i++) buffer.f32(offset + i * 4, min[i]);
159
+ for (let i = 0; i < 3; i++) buffer.f32(offset + 12 + i * 4, max[i]);
160
+ }
161
+ function writeBufferView(buffer, offset, view, remap) {
162
+ const size = view?.size || 0;
163
+ const index = view?.index || 0;
164
+ buffer.u32(offset, size === 0 ? index : remap.get(index) ?? index);
165
+ buffer.u32(offset + 4, view?.offset || 0);
166
+ buffer.u32(offset + 8, size);
167
+ buffer.u32(offset + 12, view?.stride || 0);
168
+ }
169
+ function writeVertexElement(buffer, offset, element) {
170
+ buffer.u8(offset, enumValue(Usage, element.usage, "vertex usage"));
171
+ buffer.u8(offset + 1, element.usageIndex || 0);
172
+ buffer.u8(offset + 2, enumValue(ElementType, element.type, "element type"));
173
+ buffer.u8(offset + 3, element.elementCount || 0);
174
+ buffer.u32(offset + 4, element.offset || 0);
175
+ }
176
+ function writeData(buffer, offset, graph, remap) {
177
+ const writeMesh = (target, meshOffset, mesh) => {
178
+ target.string(meshOffset, mesh.name);
179
+ target.span(meshOffset + 16, mesh.decl || [], STRUCT_SIZE.VertexElement, writeVertexElement, {
180
+ dedup: true
181
+ });
182
+ target.span(meshOffset + 32, mesh.lods || [], STRUCT_SIZE.MeshLod, (lodTarget, lodOffset, lod) => {
183
+ writeBufferView(lodTarget, lodOffset, lod.vb, remap);
184
+ writeBufferView(lodTarget, lodOffset + 16, lod.ib, remap);
185
+ lodTarget.span(lodOffset + 32, lod.areas || [], STRUCT_SIZE.LodMeshArea, (areaTarget, areaOffset, area) => {
186
+ areaTarget.u32(areaOffset, area.firstElement || 0);
187
+ areaTarget.u32(areaOffset + 4, area.elementCount || 0);
188
+ }, {
189
+ dedup: true
190
+ });
191
+ lodTarget.span(lodOffset + 48, lod.morphTargets || [], STRUCT_SIZE.LodMorphTarget, (morphTarget, morphOffset, morph) => {
192
+ writeBufferView(morphTarget, morphOffset, morph.vb, remap);
193
+ });
194
+ lodTarget.u32(lodOffset + 64, lod.threshold ?? 0xffffffff);
195
+ });
196
+ target.span(meshOffset + 48, mesh.areas || [], STRUCT_SIZE.MeshArea, (areaTarget, areaOffset, area) => {
197
+ areaTarget.string(areaOffset, area.name);
198
+ writeBounds(areaTarget, areaOffset + 16, area.bounds);
199
+ areaTarget.span(areaOffset + 40, area.bones || [], 2, (boneTarget, boneOffset, bone) => boneTarget.u16(boneOffset, bone), {
200
+ dedup: true
201
+ });
202
+ areaTarget.u8(areaOffset + 56, area.affectedByBones ? 1 : 0);
203
+ areaTarget.u8(areaOffset + 57, area.affectedByMorphTargets ? 1 : 0);
204
+ });
205
+ target.span(meshOffset + 64, mesh.boneBindings || [], STRUCT_SIZE.BoneBinding, (bindingTarget, bindingOffset, binding) => {
206
+ bindingTarget.string(bindingOffset, binding.name);
207
+ writeBounds(bindingTarget, bindingOffset + 16, binding.bounds);
208
+ });
209
+ target.span(meshOffset + 80, mesh.morphTargets?.decl || [], STRUCT_SIZE.VertexElement, writeVertexElement, {
210
+ dedup: true
211
+ });
212
+ target.span(meshOffset + 96, mesh.morphTargets?.targets || [], STRUCT_SIZE.MorphTarget, (morphTarget, morphOffset, morph) => {
213
+ morphTarget.string(morphOffset, morph.name);
214
+ morphTarget.f32(morphOffset + 16, morph.maxDisplacement || 0);
215
+ });
216
+ target.span(meshOffset + 112, mesh.uvDensities || [], 4, (densityTarget, densityOffset, value) => densityTarget.f32(densityOffset, value), {
217
+ dedup: true
218
+ });
219
+ writeBounds(target, meshOffset + 128, mesh.bounds);
220
+ const occlusion = mesh.audioOcclusionMesh || {};
221
+ target.span(meshOffset + 152, occlusion.vertices || [], 12, (vertexTarget, vertexOffset, vertex) => {
222
+ for (let i = 0; i < 3; i++) vertexTarget.f32(vertexOffset + i * 4, vertex[i]);
223
+ }, {
224
+ dedup: true
225
+ });
226
+ target.span(meshOffset + 168, occlusion.indices || [], 2, (indexTarget, indexOffset, index) => indexTarget.u16(indexOffset, index), {
227
+ dedup: true
228
+ });
229
+ writeBounds(target, meshOffset + 184, occlusion.bounds);
230
+ target.u8(meshOffset + 208, enumValue(MeshTopology, mesh.topology ?? "TriangleList", "topology"));
231
+ target.u8(meshOffset + 209, mesh.skeleton === null || mesh.skeleton === undefined ? 0xff : mesh.skeleton);
232
+ };
233
+ const writeSkeleton = (target, skeletonOffset, skeleton) => {
234
+ if ((skeleton.bones || []).some(bone => typeof bone !== "string")) {
235
+ throw writeError("skeleton bones must be name strings; GR2-shaped skeletons need conversion (use writeShared) before writing");
236
+ }
237
+ target.string(skeletonOffset, skeleton.name);
238
+ target.span(skeletonOffset + 16, skeleton.bones || [], 16, (boneTarget, boneOffset, bone) => boneTarget.string(boneOffset, bone));
239
+ target.span(skeletonOffset + 32, skeleton.parents || [], 4, (parentTarget, parentOffset, parent) => parentTarget.u32(parentOffset, parent), {
240
+ dedup: true
241
+ });
242
+ target.span(skeletonOffset + 48, skeleton.restTransforms || [], STRUCT_SIZE.Transform, (transformTarget, transformOffset, transform) => {
243
+ const position = transform.position || [0, 0, 0];
244
+ const rotation = transform.rotation || [0, 0, 0, 1];
245
+ const scale = transform.scale || [1, 1, 1];
246
+ for (let i = 0; i < 3; i++) transformTarget.f32(transformOffset + i * 4, position[i]);
247
+ for (let i = 0; i < 4; i++) transformTarget.f32(transformOffset + 12 + i * 4, rotation[i]);
248
+ for (let i = 0; i < 3; i++) transformTarget.f32(transformOffset + 28 + i * 4, scale[i]);
249
+ }, {
250
+ dedup: true
251
+ });
252
+ target.span(skeletonOffset + 64, skeleton.invBindTransforms || [], 64, (matrixTarget, matrixOffset, matrix) => {
253
+ for (let i = 0; i < 16; i++) matrixTarget.f32(matrixOffset + i * 4, matrix[i]);
254
+ }, {
255
+ dedup: true
256
+ });
257
+ target.span(skeletonOffset + 80, skeleton.boneMasks || [], STRUCT_SIZE.BoneMask, (maskTarget, maskOffset, mask) => {
258
+ maskTarget.string(maskOffset, mask.name);
259
+ maskTarget.span(maskOffset + 16, mask.weights || [], STRUCT_SIZE.BoneWeight, (weightTarget, weightOffset, weight) => {
260
+ weightTarget.u32(weightOffset, weight.index || 0);
261
+ weightTarget.f32(weightOffset + 4, weight.weight ?? 1);
262
+ }, {
263
+ dedup: true
264
+ });
265
+ });
266
+ };
267
+ const writeAnimation = (target, animationOffset, animation) => {
268
+ target.string(animationOffset, animation.name);
269
+ target.span(animationOffset + 16, animation.channels || [], STRUCT_SIZE.AnimationChannel, (channelTarget, channelOffset, channel) => {
270
+ channelTarget.string(channelOffset, channel.target);
271
+ channelTarget.u8(channelOffset + 16, enumValue(AnimationChannelTargetType, channel.targetType, "channel target type"));
272
+ channelTarget.u32(channelOffset + 20, channel.curveIndex || 0);
273
+ });
274
+ target.span(animationOffset + 32, animation.curves || [], STRUCT_SIZE.AnimationCurve, (curveTarget, curveOffset, curve) => {
275
+ curveTarget.u8(curveOffset, curve.valueDimension || 0);
276
+ curveTarget.u8(curveOffset + 1, enumValue(Interpolation, curve.interpolation, "interpolation"));
277
+ curveTarget.u8(curveOffset + 2, enumValue(ElementType, curve.knotType, "knot type"));
278
+ curveTarget.u8(curveOffset + 3, enumValue(ElementType, curve.valueType, "value type"));
279
+ curveTarget.u32(curveOffset + 4, curve.knotCount || 0);
280
+ curveTarget.span(curveOffset + 8, curve.knots || [], 1, (knotTarget, knotOffset, knot) => knotTarget.u8(knotOffset, knot), {
281
+ dedup: true
282
+ });
283
+ curveTarget.span(curveOffset + 24, curve.values || [], 1, (valueTarget, valueOffset, value) => valueTarget.u8(valueOffset, value), {
284
+ dedup: true
285
+ });
286
+ });
287
+ target.f32(animationOffset + 48, animation.duration || 0);
288
+ };
289
+ buffer.span(offset, graph.meshes || [], STRUCT_SIZE.Mesh, writeMesh);
290
+ buffer.span(offset + 16, graph.skeletons || [], STRUCT_SIZE.Skeleton, writeSkeleton);
291
+ buffer.span(offset + 32, graph.animations || [], STRUCT_SIZE.Animation, writeAnimation);
292
+ }
293
+
294
+ /**
295
+ * Collect BufferView usage in reference-writer order and decide per-buffer
296
+ * compression (conflicting stride/kind across views falls back to None).
297
+ */
298
+ function collectBufferRecords(graph, compress) {
299
+ const records = [];
300
+ const recordsByIndex = new Map();
301
+ const visit = (view, compression) => {
302
+ if (!view || !view.size) return;
303
+ const existing = recordsByIndex.get(view.index);
304
+ if (!existing) {
305
+ const record = {
306
+ index: view.index,
307
+ stride: view.stride || 0,
308
+ compression: compress ? compression : "None"
309
+ };
310
+ records.push(record);
311
+ recordsByIndex.set(view.index, record);
312
+ } else if (existing.stride !== (view.stride || 0) || (compress ? compression : "None") !== existing.compression) {
313
+ existing.stride = 0;
314
+ existing.compression = "None";
315
+ }
316
+ };
317
+ for (const mesh of graph.meshes || []) {
318
+ for (const lod of mesh.lods || []) {
319
+ visit(lod.vb, "MeshOptimizerVertexBuffer");
320
+ visit(lod.ib, "MeshOptimizerIndexBuffer");
321
+ for (const morph of lod.morphTargets || []) {
322
+ visit(morph.vb, "MeshOptimizerVertexBuffer");
323
+ }
324
+ }
325
+ }
326
+ return records;
327
+ }
328
+ function resolveBufferBytes(graph, record) {
329
+ const buffers = graph.buffers || [];
330
+ const entry = buffers.find?.(buffer => buffer && buffer.index === record.index) ?? buffers[record.index];
331
+ const data = entry?.data ?? (entry instanceof Uint8Array ? entry : null);
332
+ if (!data) {
333
+ throw writeError(`no buffer data supplied for BufferView index ${record.index}`);
334
+ }
335
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
336
+ }
337
+ function compressBuffer(bytes, record) {
338
+ if (record.compression === "None" || bytes.byteLength === 0) {
339
+ return {
340
+ data: bytes,
341
+ compression: "None",
342
+ gpuAlignment: record.stride
343
+ };
344
+ }
345
+ if (!encoderReady) {
346
+ throw writeError("compressed output requires writeAsync/WriteAsync so meshoptimizer can initialize (or pass compress: false)");
347
+ }
348
+ if (record.compression === "MeshOptimizerVertexBuffer") {
349
+ if (record.stride === 0 || bytes.byteLength % record.stride !== 0) {
350
+ return {
351
+ data: bytes,
352
+ compression: "None",
353
+ gpuAlignment: record.stride
354
+ };
355
+ }
356
+ const count = bytes.byteLength / record.stride;
357
+ const data = MeshoptEncoder.encodeVertexBuffer(bytes, count, record.stride);
358
+ return {
359
+ data,
360
+ compression: "MeshOptimizerVertexBuffer",
361
+ gpuAlignment: record.stride
362
+ };
363
+ }
364
+
365
+ // index buffers: meshopt encodes triangle lists of u32; u16 sources widen
366
+ const stride = record.stride;
367
+ if (stride !== 2 && stride !== 4 || bytes.byteLength % stride !== 0) {
368
+ return {
369
+ data: bytes,
370
+ compression: "None",
371
+ gpuAlignment: stride
372
+ };
373
+ }
374
+ const count = bytes.byteLength / stride;
375
+ if (count % 3 !== 0) {
376
+ return {
377
+ data: bytes,
378
+ compression: "None",
379
+ gpuAlignment: stride
380
+ };
381
+ }
382
+ let source = bytes;
383
+ if (stride === 2) {
384
+ const wide = new Uint32Array(count);
385
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
386
+ for (let i = 0; i < count; i++) wide[i] = view.getUint16(i * 2, true);
387
+ source = new Uint8Array(wide.buffer);
388
+ }
389
+ const data = MeshoptEncoder.encodeIndexBuffer(source, count, 4);
390
+ return {
391
+ data,
392
+ compression: "MeshOptimizerIndexBuffer",
393
+ gpuAlignment: stride
394
+ };
395
+ }
396
+
397
+ /**
398
+ * Serialize a CMF-native graph into .cmf bytes.
399
+ *
400
+ * @param {object} graph Native graph: `{ meshes, skeletons, animations, metadata?, buffers? }`
401
+ * where `buffers` supplies uncompressed GPU bytes for each BufferView
402
+ * `index` (as `{ index, data }` entries or an index-keyed array).
403
+ * @param {object} [options] `compress` (default false for the sync writer)
404
+ * enables meshoptimizer vertex/index compression.
405
+ * @returns {Uint8Array} Complete .cmf file bytes.
406
+ */
407
+ function writeCmf(graph, options = {}) {
408
+ if (!graph || typeof graph !== "object") {
409
+ throw writeError("input graph must be an object");
410
+ }
411
+ const compress = options.compress === true;
412
+ const records = collectBufferRecords(graph, compress);
413
+ const compressed = records.map(record => {
414
+ const bytes = resolveBufferBytes(graph, record);
415
+ return {
416
+ record,
417
+ ...compressBuffer(bytes, record),
418
+ uncompressedSize: bytes.byteLength
419
+ };
420
+ });
421
+ const remap = new Map(records.map((record, position) => [record.index, position + 1]));
422
+ const data = new Flattener();
423
+ data.reserve(STRUCT_SIZE.Data);
424
+ writeData(data, 0, graph, remap);
425
+ const dataBytes = data.bytes();
426
+ let metadataBytes = null;
427
+ if (graph.metadata && (graph.metadata.entries || []).length) {
428
+ const metadata = new Flattener();
429
+ metadata.reserve(STRUCT_SIZE.Metadata);
430
+ metadata.span(0, graph.metadata.entries, STRUCT_SIZE.MetadataEntry, (target, offset, entry) => {
431
+ target.string(offset, entry.key);
432
+ target.string(offset + 16, entry.value);
433
+ });
434
+ metadataBytes = metadata.bytes();
435
+ }
436
+ const sections = [{
437
+ type: "Data",
438
+ compression: "None",
439
+ gpuAlignment: 0,
440
+ compressedSize: dataBytes.byteLength,
441
+ uncompressedSize: dataBytes.byteLength,
442
+ data: dataBytes
443
+ }];
444
+ for (const entry of compressed) {
445
+ sections.push({
446
+ type: "GpuBuffer",
447
+ compression: entry.compression,
448
+ gpuAlignment: entry.gpuAlignment,
449
+ compressedSize: entry.data.byteLength,
450
+ uncompressedSize: entry.uncompressedSize,
451
+ data: entry.data
452
+ });
453
+ }
454
+ if (metadataBytes) {
455
+ sections.push({
456
+ type: "Metadata",
457
+ compression: "None",
458
+ gpuAlignment: 0,
459
+ compressedSize: metadataBytes.byteLength,
460
+ uncompressedSize: metadataBytes.byteLength,
461
+ data: metadataBytes
462
+ });
463
+ }
464
+ const header = new Flattener();
465
+ header.reserve(STRUCT_SIZE.Header);
466
+ header.u32(0, FILE_SIGNATURE);
467
+ header.u32(4, FILE_VERSION);
468
+ header.span(16, sections, STRUCT_SIZE.Section, () => {});
469
+ const headerSize = header.size;
470
+ header.u32(8, headerSize);
471
+ let offset = headerSize;
472
+ const sectionOffsets = sections.map(section => {
473
+ offset = Math.ceil(offset / 8) * 8;
474
+ const sectionOffset = offset;
475
+ offset += section.compressedSize;
476
+ return sectionOffset;
477
+ });
478
+ const sectionsChunk = headerSize - sections.length * STRUCT_SIZE.Section;
479
+ sections.forEach((section, index) => {
480
+ const base = sectionsChunk + index * STRUCT_SIZE.Section;
481
+ header.u32(base, sectionOffsets[index]);
482
+ header.u32(base + 4, section.compressedSize);
483
+ header.u32(base + 8, section.uncompressedSize);
484
+ header.u16(base + 12, section.gpuAlignment || 0);
485
+ header.u8(base + 14, enumValue(SectionType, section.type, "section type"));
486
+ header.u8(base + 15, enumValue(SectionCompression, section.compression, "section compression"));
487
+ });
488
+ const total = offset;
489
+ const file = new Uint8Array(total);
490
+ file.set(header.bytes(), 0);
491
+ sections.forEach((section, index) => {
492
+ file.set(section.data, sectionOffsets[index]);
493
+ });
494
+ const checksum = crc32(file, 16, file.byteLength);
495
+ new DataView(file.buffer).setUint32(12, checksum, true);
496
+ return file;
497
+ }
498
+
499
+ /**
500
+ * Serialize a CMF-native graph asynchronously with compression enabled by
501
+ * default (awaits meshoptimizer encoder initialization).
502
+ *
503
+ * @param {object} graph Native graph (see `writeCmf`).
504
+ * @param {object} [options] `compress` defaults to true.
505
+ * @returns {Promise<Uint8Array>} Complete .cmf file bytes.
506
+ */
507
+ async function writeCmfAsync(graph, options = {}) {
508
+ await MeshoptEncoder.ready;
509
+ encoderReady = true;
510
+ return writeCmf(graph, {
511
+ ...options,
512
+ compress: options.compress !== false
513
+ });
514
+ }
515
+
516
+ export { writeCmf, writeCmfAsync };
517
+ //# sourceMappingURL=writer.js.map