fast-mesh-wasm 0.5.3 → 0.7.0

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 (40) hide show
  1. package/README.md +2 -1
  2. package/dist/{client-f895H_yB.js → client-DFgvktkT.js} +183 -10
  3. package/dist/{client-D7yfPOyU.d.ts → client-nvmbhtn-.d.ts} +87 -14
  4. package/dist/{engine-BcJ5W6kS.js → engine-BL5_sWAf.js} +21 -6
  5. package/dist/io.d.ts +218 -5
  6. package/dist/io.js +3121 -12
  7. package/dist/{mesh-B3QP93wx.d.ts → mesh-BHTFxsXc.d.ts} +5 -2
  8. package/dist/{mesh-hPWBQPaN.js → mesh-DIWD2F5-.js} +51 -2
  9. package/dist/node.d.ts +2 -2
  10. package/dist/node.js +3 -2
  11. package/dist/{protocol-Dt0zgang.d.ts → protocol-DFR0JDAS.d.ts} +9 -1
  12. package/dist/r3f.d.ts +3 -3
  13. package/dist/r3f.js +2 -2
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{scene-CXtM_bxV.js → scene-DUsj6uJD.js} +421 -29
  16. package/dist/{scene-like-Dq9_SaUL.d.ts → scene-like-CR_Dpohm.d.ts} +999 -133
  17. package/dist/{store-CIW19oCh.d.ts → store-8HWG90Jg.d.ts} +14 -3
  18. package/dist/{store-C9h7GFFl.js → store-BAzHRRkt.js} +18 -2
  19. package/dist/store.d.ts +3 -3
  20. package/dist/store.js +1 -1
  21. package/dist/three.d.ts +2 -2
  22. package/dist/three.js +1 -1
  23. package/dist/views-BSy-Qeg8.js +584 -0
  24. package/dist/wasm/fast_mesh_wasm.d.ts +21 -1
  25. package/dist/wasm/fast_mesh_wasm.js +50 -1
  26. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  27. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +3 -0
  28. package/dist/wasm-threads/fast_mesh_wasm.d.ts +21 -1
  29. package/dist/wasm-threads/fast_mesh_wasm.js +50 -1
  30. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  31. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +3 -0
  32. package/dist/web.d.ts +2 -2
  33. package/dist/web.js +3 -2
  34. package/dist/worker-engine.d.ts +5 -3
  35. package/dist/worker-engine.js +1 -1
  36. package/dist/worker-entry.js +1 -1
  37. package/dist/worker.d.ts +1 -1
  38. package/dist/worker.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/views-mp7Mf8CQ.js +0 -209
package/dist/io.js CHANGED
@@ -1,3 +1,3048 @@
1
+ // src/io/zip.ts
2
+ const DEFAULT_MAX_ZIP_FILE_BYTES = 536870912;
3
+ const DEFAULT_MAX_ZIP_ENTRIES = 4096;
4
+ const LOCAL_FILE_HEADER_SIG = 67324752;
5
+ const CENTRAL_DIR_HEADER_SIG = 33639248;
6
+ const EOCD_SIG = 101010256;
7
+ const ZIP64_EOCD_SIG = 101075792;
8
+ const ZIP64_EOCD_LOCATOR_SIG = 117853008;
9
+ const METHOD_STORE = 0;
10
+ const METHOD_DEFLATE = 8;
11
+ const FLAG_ENCRYPTED = 1;
12
+ const FLAG_DATA_DESCRIPTOR = 8;
13
+ const FLAG_UTF8 = 2048;
14
+ const ZIP64_SENTINEL_U16 = 65535;
15
+ const ZIP64_SENTINEL_U32 = 4294967295;
16
+ const textEncoder$1 = new TextEncoder();
17
+ const textDecoder$5 = new TextDecoder("utf-8", { fatal: false });
18
+ const CRC32_TABLE = (() => {
19
+ const table = /* @__PURE__ */ new Uint32Array(256);
20
+ for (let i = 0; i < 256; i++) {
21
+ let c = i;
22
+ for (let k = 0; k < 8; k++) c = (c & 1) !== 0 ? (3988292384 ^ c >>> 1) >>> 0 : c >>> 1;
23
+ table[i] = c;
24
+ }
25
+ return table;
26
+ })();
27
+ /**
28
+ * Compute standard IEEE 802.3 CRC-32 checksum.
29
+ */
30
+ function crc32(data) {
31
+ let crc = 4294967295;
32
+ for (let i = 0; i < data.length; i++) crc = (CRC32_TABLE[(crc ^ data[i]) & 255] ^ crc >>> 8) >>> 0;
33
+ return (crc ^ 4294967295) >>> 0;
34
+ }
35
+ function getCompressionCtor(kind) {
36
+ const ctor = globalThis[kind];
37
+ return typeof ctor === "function" ? ctor : void 0;
38
+ }
39
+ function throwIfAborted$5(signal) {
40
+ if (signal?.aborted) {
41
+ const reason = signal.reason;
42
+ if (reason instanceof Error) throw reason;
43
+ throw new DOMException("The operation was aborted.", "AbortError");
44
+ }
45
+ }
46
+ /**
47
+ * Reject absolute paths, drive letters, NUL bytes, backslashes, and `..` traversal.
48
+ */
49
+ function validateZipEntryName(name) {
50
+ if (name.length === 0) throw new Error("ZIP archive contains an entry with an empty filename");
51
+ if (name.includes("\0")) throw new Error(`ZIP entry name contains NUL byte: ${JSON.stringify(name)}`);
52
+ if (name.startsWith("/") || name.startsWith("\\")) throw new Error(`ZIP entry name must be relative (unsafe path "${name}")`);
53
+ if (/^[a-zA-Z]:/.test(name)) throw new Error(`ZIP entry name must not contain a drive prefix ("${name}")`);
54
+ if (name.includes("\\")) throw new Error(`ZIP entry name contains backslash ("${name}")`);
55
+ const segments = name.split("/");
56
+ for (let i = 0; i < segments.length; i++) if (segments[i] === "..") throw new Error(`ZIP entry name attempts path traversal ("${name}")`);
57
+ return name;
58
+ }
59
+ function readU64AsSafeNumber(view, offset, label) {
60
+ const lo = view.getUint32(offset, true);
61
+ const val = view.getUint32(offset + 4, true) * 4294967296 + lo;
62
+ if (!Number.isSafeInteger(val)) throw new Error(`ZIP64 ${label} exceeds safe integer range`);
63
+ return val;
64
+ }
65
+ function findEocd(bytes, view) {
66
+ const len = bytes.byteLength;
67
+ if (len < 22) throw new Error("Invalid ZIP archive: file is smaller than End of Central Directory record");
68
+ const minOffset = Math.max(0, len - 22 - 65535);
69
+ let eocdOffset = -1;
70
+ for (let i = len - 22; i >= minOffset; i--) if (bytes[i] === 80 && bytes[i + 1] === 75 && bytes[i + 2] === 5 && bytes[i + 3] === 6) {
71
+ const commentLen = view.getUint16(i + 20, true);
72
+ if (i + 22 + commentLen === len) {
73
+ eocdOffset = i;
74
+ break;
75
+ }
76
+ }
77
+ if (eocdOffset < 0) throw new Error("Invalid ZIP archive: End of Central Directory record not found");
78
+ const diskNumber = view.getUint16(eocdOffset + 4, true);
79
+ const cdDisk = view.getUint16(eocdOffset + 6, true);
80
+ let diskEntries = view.getUint16(eocdOffset + 8, true);
81
+ let totalEntries = view.getUint16(eocdOffset + 10, true);
82
+ let cdSize = view.getUint32(eocdOffset + 12, true);
83
+ let cdOffset = view.getUint32(eocdOffset + 16, true);
84
+ if (diskNumber === ZIP64_SENTINEL_U16 || cdDisk === ZIP64_SENTINEL_U16 || diskEntries === ZIP64_SENTINEL_U16 || totalEntries === ZIP64_SENTINEL_U16 || cdSize === ZIP64_SENTINEL_U32 || cdOffset === ZIP64_SENTINEL_U32) {
85
+ const locOffset = eocdOffset - 20;
86
+ if (locOffset < 0 || view.getUint32(locOffset, true) !== ZIP64_EOCD_LOCATOR_SIG) throw new Error("Invalid ZIP64 archive: missing ZIP64 End of Central Directory Locator");
87
+ const zip64EocdOffset = readU64AsSafeNumber(view, locOffset + 8, "EOCD offset");
88
+ if (zip64EocdOffset + 56 > locOffset || view.getUint32(zip64EocdOffset, true) !== ZIP64_EOCD_SIG) throw new Error("Invalid ZIP64 archive: End of Central Directory record is corrupt");
89
+ diskEntries = readU64AsSafeNumber(view, zip64EocdOffset + 24, "disk entry count");
90
+ totalEntries = readU64AsSafeNumber(view, zip64EocdOffset + 32, "total entry count");
91
+ cdSize = readU64AsSafeNumber(view, zip64EocdOffset + 40, "central directory size");
92
+ cdOffset = readU64AsSafeNumber(view, zip64EocdOffset + 48, "central directory offset");
93
+ } else if (diskNumber !== 0 || cdDisk !== 0 || diskEntries !== totalEntries) throw new Error("Multi-disk ZIP archives are not supported");
94
+ if (cdOffset > eocdOffset || cdOffset + cdSize > eocdOffset) throw new Error("Invalid ZIP archive: Central Directory extends outside archive bounds");
95
+ return {
96
+ totalEntries,
97
+ cdSize,
98
+ cdOffset
99
+ };
100
+ }
101
+ function parseZip64ExtraField(bytes, view, extraStart, extraLen, needUncompressed, needCompressed, needOffset) {
102
+ let pos = extraStart;
103
+ const end = extraStart + extraLen;
104
+ while (pos + 4 <= end) {
105
+ const headerId = view.getUint16(pos, true);
106
+ const dataSize = view.getUint16(pos + 2, true);
107
+ const dataStart = pos + 4;
108
+ if (dataStart + dataSize > end) break;
109
+ if (headerId === 1) {
110
+ let cur = dataStart;
111
+ const out = {};
112
+ if (needUncompressed) {
113
+ if (cur + 8 > dataStart + dataSize) throw new Error("Invalid ZIP64 extra field: truncated uncompressed size");
114
+ out.uncompressed = readU64AsSafeNumber(view, cur, "uncompressed size");
115
+ cur += 8;
116
+ }
117
+ if (needCompressed) {
118
+ if (cur + 8 > dataStart + dataSize) throw new Error("Invalid ZIP64 extra field: truncated compressed size");
119
+ out.compressed = readU64AsSafeNumber(view, cur, "compressed size");
120
+ cur += 8;
121
+ }
122
+ if (needOffset) {
123
+ if (cur + 8 > dataStart + dataSize) throw new Error("Invalid ZIP64 extra field: truncated local header offset");
124
+ out.offset = readU64AsSafeNumber(view, cur, "local header offset");
125
+ }
126
+ return out;
127
+ }
128
+ pos = dataStart + dataSize;
129
+ }
130
+ throw new Error("Invalid ZIP64 entry: required ZIP64 extra field missing");
131
+ }
132
+ function parseCentralDirectory(bytes, view, cdOffset, cdSize, expectedEntries, maxEntries) {
133
+ if (expectedEntries > maxEntries) throw new Error(`ZIP archive has ${expectedEntries} entries, exceeding maximum of ${maxEntries}`);
134
+ const entries = [];
135
+ let pos = cdOffset;
136
+ const end = cdOffset + cdSize;
137
+ while (pos < end) {
138
+ if (entries.length >= maxEntries) throw new Error(`ZIP archive entry count exceeds maximum of ${maxEntries}`);
139
+ if (pos + 46 > end) throw new Error("Invalid ZIP archive: truncated Central Directory entry");
140
+ if (view.getUint32(pos, true) !== CENTRAL_DIR_HEADER_SIG) throw new Error("Invalid ZIP archive: bad Central Directory entry signature");
141
+ const flags = view.getUint16(pos + 8, true);
142
+ const method = view.getUint16(pos + 10, true);
143
+ const entryCrc = view.getUint32(pos + 16, true);
144
+ let compressedSize = view.getUint32(pos + 20, true);
145
+ let uncompressedSize = view.getUint32(pos + 24, true);
146
+ const nameLen = view.getUint16(pos + 28, true);
147
+ const extraLen = view.getUint16(pos + 30, true);
148
+ const commentLen = view.getUint16(pos + 32, true);
149
+ let localHeaderOffset = view.getUint32(pos + 42, true);
150
+ const recordEnd = pos + 46 + nameLen + extraLen + commentLen;
151
+ if (recordEnd > end) throw new Error("Invalid ZIP archive: Central Directory entry extends past directory end");
152
+ const name = validateZipEntryName(textDecoder$5.decode(bytes.subarray(pos + 46, pos + 46 + nameLen)));
153
+ if (uncompressedSize === ZIP64_SENTINEL_U32 || compressedSize === ZIP64_SENTINEL_U32 || localHeaderOffset === ZIP64_SENTINEL_U32) {
154
+ const z64 = parseZip64ExtraField(bytes, view, pos + 46 + nameLen, extraLen, uncompressedSize === ZIP64_SENTINEL_U32, compressedSize === ZIP64_SENTINEL_U32, localHeaderOffset === ZIP64_SENTINEL_U32);
155
+ if (z64.uncompressed !== void 0) uncompressedSize = z64.uncompressed;
156
+ if (z64.compressed !== void 0) compressedSize = z64.compressed;
157
+ if (z64.offset !== void 0) localHeaderOffset = z64.offset;
158
+ }
159
+ entries.push({
160
+ name,
161
+ flags,
162
+ method,
163
+ crc32: entryCrc,
164
+ compressedSize,
165
+ uncompressedSize,
166
+ localHeaderOffset
167
+ });
168
+ pos = recordEnd;
169
+ }
170
+ if (entries.length !== expectedEntries) throw new Error(`Invalid ZIP archive: Central Directory declares ${expectedEntries} entries, found ${entries.length}`);
171
+ return entries;
172
+ }
173
+ /**
174
+ * Inflate raw DEFLATE bytes with hard output-byte limits and abort support.
175
+ * Reads output chunks concurrently while feeding bounded input chunks so a zip
176
+ * bomb fails immediately instead of buffering GBs in memory.
177
+ */
178
+ async function inflateRawBounded(compressed, maxBytes, entryName, signal) {
179
+ throwIfAborted$5(signal);
180
+ const Ctor = getCompressionCtor("DecompressionStream");
181
+ if (!Ctor) throw new Error("DecompressionStream('deflate-raw') is not available in this runtime");
182
+ const stream = new Ctor("deflate-raw");
183
+ const writer = stream.writable.getWriter();
184
+ const reader = stream.readable.getReader();
185
+ const chunks = [];
186
+ let totalOut = 0;
187
+ let failure = null;
188
+ let aborted = false;
189
+ const cancelAll = async (err) => {
190
+ if (aborted) return;
191
+ aborted = true;
192
+ failure = err;
193
+ await Promise.allSettled([reader.cancel(err), writer.abort(err)]);
194
+ };
195
+ const onAbort = () => {
196
+ const err = signal?.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted.", "AbortError");
197
+ cancelAll(err);
198
+ };
199
+ signal?.addEventListener("abort", onAbort, { once: true });
200
+ const writePump = (async () => {
201
+ const CHUNK = 65536;
202
+ try {
203
+ for (let off = 0; off < compressed.byteLength; off += CHUNK) {
204
+ if (aborted) return;
205
+ throwIfAborted$5(signal);
206
+ const slice = compressed.subarray(off, Math.min(off + CHUNK, compressed.byteLength));
207
+ await writer.write(slice);
208
+ }
209
+ if (!aborted) await writer.close();
210
+ } catch (err) {
211
+ if (!aborted) await cancelAll(err);
212
+ }
213
+ })();
214
+ const readPump = (async () => {
215
+ try {
216
+ while (true) {
217
+ const { value, done } = await reader.read();
218
+ if (done) break;
219
+ if (aborted) break;
220
+ throwIfAborted$5(signal);
221
+ if (value && value.byteLength > 0) {
222
+ if (value.byteLength > maxBytes - totalOut) {
223
+ const err = /* @__PURE__ */ new Error(`ZIP entry "${entryName}" exceeds uncompressed limit of ${maxBytes} bytes (zip bomb guard)`);
224
+ await cancelAll(err);
225
+ return;
226
+ }
227
+ totalOut += value.byteLength;
228
+ chunks.push(new Uint8Array(value));
229
+ }
230
+ }
231
+ } catch (err) {
232
+ if (!aborted) await cancelAll(err);
233
+ }
234
+ })();
235
+ try {
236
+ await Promise.all([writePump, readPump]);
237
+ } finally {
238
+ signal?.removeEventListener("abort", onAbort);
239
+ }
240
+ if (failure !== null) throw failure instanceof Error ? failure : new Error(String(failure));
241
+ throwIfAborted$5(signal);
242
+ const out = new Uint8Array(totalOut);
243
+ let pos = 0;
244
+ for (let i = 0; i < chunks.length; i++) {
245
+ out.set(chunks[i], pos);
246
+ pos += chunks[i].byteLength;
247
+ }
248
+ return out;
249
+ }
250
+ async function deflateRaw(data) {
251
+ const Ctor = getCompressionCtor("CompressionStream");
252
+ if (!Ctor) throw new Error("CompressionStream('deflate-raw') is not available in this runtime");
253
+ const stream = new Ctor("deflate-raw");
254
+ const writer = stream.writable.getWriter();
255
+ const reader = stream.readable.getReader();
256
+ const chunks = [];
257
+ let totalOut = 0;
258
+ const writePump = (async () => {
259
+ const CHUNK = 65536;
260
+ for (let off = 0; off < data.byteLength; off += CHUNK) await writer.write(data.subarray(off, Math.min(off + CHUNK, data.byteLength)));
261
+ await writer.close();
262
+ })();
263
+ const readPump = (async () => {
264
+ while (true) {
265
+ const { value, done } = await reader.read();
266
+ if (done) break;
267
+ if (value && value.byteLength > 0) {
268
+ totalOut += value.byteLength;
269
+ chunks.push(new Uint8Array(value));
270
+ }
271
+ }
272
+ })();
273
+ await Promise.all([writePump, readPump]);
274
+ const out = new Uint8Array(totalOut);
275
+ let pos = 0;
276
+ for (let i = 0; i < chunks.length; i++) {
277
+ out.set(chunks[i], pos);
278
+ pos += chunks[i].byteLength;
279
+ }
280
+ return out;
281
+ }
282
+ function locateEntryPayload(bytes, view, cdOffset, cdEntry) {
283
+ const lh = cdEntry.localHeaderOffset;
284
+ if (lh + 30 > cdOffset) throw new Error(`Invalid ZIP entry "${cdEntry.name}": local header offset ${lh} is outside archive data`);
285
+ if (view.getUint32(lh, true) !== LOCAL_FILE_HEADER_SIG) throw new Error(`Invalid ZIP entry "${cdEntry.name}": bad local file header signature`);
286
+ const nameLen = view.getUint16(lh + 26, true);
287
+ const extraLen = view.getUint16(lh + 28, true);
288
+ const dataStart = lh + 30 + nameLen + extraLen;
289
+ if (dataStart > cdOffset) throw new Error(`Invalid ZIP entry "${cdEntry.name}": local file header extends into Central Directory`);
290
+ if (cdEntry.compressedSize > cdOffset - dataStart) throw new Error(`Invalid ZIP entry "${cdEntry.name}": compressed size (${cdEntry.compressedSize}) exceeds available bytes`);
291
+ return bytes.subarray(dataStart, dataStart + cdEntry.compressedSize);
292
+ }
293
+ /**
294
+ * Parse and decompress all entries in a ZIP archive with strict bounds checks.
295
+ */
296
+ async function readZip(bytes, options) {
297
+ const maxFileBytes = options?.maxFileBytes ?? 536870912;
298
+ const maxEntries = options?.maxEntries ?? 4096;
299
+ const maxEntryBytes = options?.maxEntryBytes ?? maxFileBytes;
300
+ const maxTotalBytes = options?.maxTotalUncompressedBytes ?? maxFileBytes;
301
+ const verifyCrc = options?.verifyCrc ?? true;
302
+ const signal = options?.signal;
303
+ throwIfAborted$5(signal);
304
+ if (bytes.byteLength > maxFileBytes) throw new Error(`ZIP archive size (${bytes.byteLength} bytes) exceeds limit of ${maxFileBytes} bytes`);
305
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
306
+ const eocd = findEocd(bytes, view);
307
+ const cdEntries = parseCentralDirectory(bytes, view, eocd.cdOffset, eocd.cdSize, eocd.totalEntries, maxEntries);
308
+ const result = /* @__PURE__ */ new Map();
309
+ let totalUncompressed = 0;
310
+ for (let i = 0; i < cdEntries.length; i++) {
311
+ throwIfAborted$5(signal);
312
+ const entry = cdEntries[i];
313
+ if ((entry.flags & FLAG_ENCRYPTED) !== 0) throw new Error(`ZIP entry "${entry.name}" is encrypted, which is not supported`);
314
+ if (entry.method !== METHOD_STORE && entry.method !== METHOD_DEFLATE) throw new Error(`ZIP entry "${entry.name}" uses unsupported compression method ${entry.method}`);
315
+ const remainingTotal = maxTotalBytes - totalUncompressed;
316
+ const entryBudget = Math.min(maxEntryBytes, remainingTotal);
317
+ if (entry.uncompressedSize > maxEntryBytes) throw new Error(`ZIP entry "${entry.name}" declares ${entry.uncompressedSize} uncompressed bytes, exceeding single-entry limit of ${maxEntryBytes}`);
318
+ if (entry.uncompressedSize > remainingTotal) throw new Error(`ZIP archive uncompressed total exceeds limit of ${maxTotalBytes} bytes`);
319
+ const compressedSlice = locateEntryPayload(bytes, view, eocd.cdOffset, entry);
320
+ let payload;
321
+ if (entry.method === METHOD_STORE) {
322
+ if ((entry.flags & FLAG_DATA_DESCRIPTOR) === 0 && entry.compressedSize !== entry.uncompressedSize) throw new Error(`ZIP STORE entry "${entry.name}" has mismatched sizes (${entry.compressedSize} vs ${entry.uncompressedSize})`);
323
+ if (compressedSlice.byteLength > entryBudget) throw new Error(`ZIP entry "${entry.name}" exceeds uncompressed limit of ${entryBudget} bytes`);
324
+ payload = compressedSlice.slice();
325
+ } else payload = await inflateRawBounded(compressedSlice, entryBudget, entry.name, signal);
326
+ if ((entry.flags & FLAG_DATA_DESCRIPTOR) === 0 && payload.byteLength !== entry.uncompressedSize) throw new Error(`ZIP entry "${entry.name}" decompressed to ${payload.byteLength} bytes, expected ${entry.uncompressedSize}`);
327
+ if (verifyCrc) {
328
+ const actualCrc = crc32(payload);
329
+ if (actualCrc !== entry.crc32) throw new Error(`ZIP entry "${entry.name}" failed CRC-32 check (expected 0x${entry.crc32.toString(16)}, got 0x${actualCrc.toString(16)})`);
330
+ }
331
+ totalUncompressed += payload.byteLength;
332
+ if (totalUncompressed > maxTotalBytes) throw new Error(`ZIP archive uncompressed total (${totalUncompressed} bytes) exceeds limit of ${maxTotalBytes} bytes`);
333
+ result.set(entry.name, payload);
334
+ }
335
+ return result;
336
+ }
337
+ function assembleZip(prepared) {
338
+ let localTotal = 0;
339
+ let cdTotal = 0;
340
+ for (let i = 0; i < prepared.length; i++) {
341
+ const e = prepared[i];
342
+ e.localOffset = localTotal;
343
+ localTotal += 30 + e.nameBytes.byteLength + e.compressedSize;
344
+ cdTotal += 46 + e.nameBytes.byteLength;
345
+ }
346
+ const totalSize = localTotal + cdTotal + 22;
347
+ const out = new Uint8Array(totalSize);
348
+ const view = new DataView(out.buffer);
349
+ let pos = 0;
350
+ for (let i = 0; i < prepared.length; i++) {
351
+ const e = prepared[i];
352
+ view.setUint32(pos, LOCAL_FILE_HEADER_SIG, true);
353
+ view.setUint16(pos + 4, 20, true);
354
+ view.setUint16(pos + 6, FLAG_UTF8, true);
355
+ view.setUint16(pos + 8, e.method, true);
356
+ view.setUint16(pos + 10, 0, true);
357
+ view.setUint16(pos + 12, 21537, true);
358
+ view.setUint32(pos + 14, e.crc, true);
359
+ view.setUint32(pos + 18, e.compressedSize, true);
360
+ view.setUint32(pos + 22, e.uncompressedSize, true);
361
+ view.setUint16(pos + 26, e.nameBytes.byteLength, true);
362
+ view.setUint16(pos + 28, 0, true);
363
+ out.set(e.nameBytes, pos + 30);
364
+ pos += 30 + e.nameBytes.byteLength;
365
+ out.set(e.payload, pos);
366
+ pos += e.compressedSize;
367
+ }
368
+ const cdOffset = pos;
369
+ for (let i = 0; i < prepared.length; i++) {
370
+ const e = prepared[i];
371
+ view.setUint32(pos, CENTRAL_DIR_HEADER_SIG, true);
372
+ view.setUint16(pos + 4, 20, true);
373
+ view.setUint16(pos + 6, 20, true);
374
+ view.setUint16(pos + 8, FLAG_UTF8, true);
375
+ view.setUint16(pos + 10, e.method, true);
376
+ view.setUint16(pos + 12, 0, true);
377
+ view.setUint16(pos + 14, 21537, true);
378
+ view.setUint32(pos + 16, e.crc, true);
379
+ view.setUint32(pos + 20, e.compressedSize, true);
380
+ view.setUint32(pos + 24, e.uncompressedSize, true);
381
+ view.setUint16(pos + 28, e.nameBytes.byteLength, true);
382
+ view.setUint16(pos + 30, 0, true);
383
+ view.setUint16(pos + 32, 0, true);
384
+ view.setUint16(pos + 34, 0, true);
385
+ view.setUint16(pos + 36, 0, true);
386
+ view.setUint32(pos + 38, 0, true);
387
+ view.setUint32(pos + 42, e.localOffset, true);
388
+ out.set(e.nameBytes, pos + 46);
389
+ pos += 46 + e.nameBytes.byteLength;
390
+ }
391
+ view.setUint32(pos, EOCD_SIG, true);
392
+ view.setUint16(pos + 4, 0, true);
393
+ view.setUint16(pos + 6, 0, true);
394
+ view.setUint16(pos + 8, prepared.length, true);
395
+ view.setUint16(pos + 10, prepared.length, true);
396
+ view.setUint32(pos + 12, cdTotal, true);
397
+ view.setUint32(pos + 16, cdOffset, true);
398
+ view.setUint16(pos + 20, 0, true);
399
+ return out;
400
+ }
401
+ /**
402
+ * Create a ZIP archive synchronously using `STORE` (method 0).
403
+ */
404
+ function writeZipSync(entries) {
405
+ if (entries.length > 65535) throw new Error(`writeZipSync supports at most 65535 entries (got ${entries.length})`);
406
+ const seen = /* @__PURE__ */ new Set();
407
+ const prepared = [];
408
+ for (let i = 0; i < entries.length; i++) {
409
+ const entry = entries[i];
410
+ const name = validateZipEntryName(entry.name);
411
+ if (seen.has(name)) throw new Error(`Duplicate ZIP entry name "${name}"`);
412
+ seen.add(name);
413
+ const nameBytes = textEncoder$1.encode(name);
414
+ prepared.push({
415
+ nameBytes,
416
+ payload: entry.data,
417
+ method: METHOD_STORE,
418
+ crc: crc32(entry.data),
419
+ uncompressedSize: entry.data.byteLength,
420
+ compressedSize: entry.data.byteLength,
421
+ localOffset: 0
422
+ });
423
+ }
424
+ return assembleZip(prepared);
425
+ }
426
+ /**
427
+ * Create a ZIP archive, compressing entries with raw DEFLATE when smaller.
428
+ */
429
+ async function writeZip(entries, options) {
430
+ if (entries.length > 65535) throw new Error(`writeZip supports at most 65535 entries (got ${entries.length})`);
431
+ const canDeflate = (options?.compress ?? true) && getCompressionCtor("CompressionStream") !== void 0;
432
+ const seen = /* @__PURE__ */ new Set();
433
+ const prepared = [];
434
+ for (let i = 0; i < entries.length; i++) {
435
+ const entry = entries[i];
436
+ const name = validateZipEntryName(entry.name);
437
+ if (seen.has(name)) throw new Error(`Duplicate ZIP entry name "${name}"`);
438
+ seen.add(name);
439
+ const nameBytes = textEncoder$1.encode(name);
440
+ const shouldCompress = entry.compress ?? canDeflate;
441
+ let payload = entry.data;
442
+ let method = METHOD_STORE;
443
+ if (shouldCompress && canDeflate && entry.data.byteLength > 0) {
444
+ const deflated = await deflateRaw(entry.data);
445
+ if (deflated.byteLength < entry.data.byteLength) {
446
+ payload = deflated;
447
+ method = METHOD_DEFLATE;
448
+ }
449
+ }
450
+ prepared.push({
451
+ nameBytes,
452
+ payload,
453
+ method,
454
+ crc: crc32(entry.data),
455
+ uncompressedSize: entry.data.byteLength,
456
+ compressedSize: payload.byteLength,
457
+ localOffset: 0
458
+ });
459
+ }
460
+ return assembleZip(prepared);
461
+ }
462
+ // src/io/threemf.ts
463
+ const UNIT_TO_MM = {
464
+ micron: .001,
465
+ millimeter: 1,
466
+ centimeter: 10,
467
+ inch: 25.4,
468
+ foot: 304.8,
469
+ meter: 1e3
470
+ };
471
+ const textEncoder = new TextEncoder();
472
+ const textDecoder$4 = new TextDecoder("utf-8");
473
+ function toUint8$3(bytes) {
474
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
475
+ }
476
+ function throwIfAborted$4(signal) {
477
+ if (signal?.aborted) {
478
+ const reason = signal.reason;
479
+ if (reason instanceof Error) throw reason;
480
+ throw new DOMException("The operation was aborted.", "AbortError");
481
+ }
482
+ }
483
+ function decodeXmlUtf8(data, label) {
484
+ let xml = textDecoder$4.decode(data);
485
+ if (xml.charCodeAt(0) === 65279) xml = xml.slice(1);
486
+ if (/<!(?:DOCTYPE|ENTITY)\b/i.test(xml)) throw new Error(`3MF XML "${label}" contains forbidden DOCTYPE or ENTITY declaration`);
487
+ return xml;
488
+ }
489
+ function xmlUnescape(text) {
490
+ if (!text.includes("&")) return text;
491
+ return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|amp|quot|apos);/g, (match, body) => {
492
+ switch (body) {
493
+ case "lt": return "<";
494
+ case "gt": return ">";
495
+ case "amp": return "&";
496
+ case "quot": return "\"";
497
+ case "apos": return "'";
498
+ default: {
499
+ const code = body.charCodeAt(1) === 120 || body.charCodeAt(1) === 88 ? Number.parseInt(body.slice(2), 16) : Number.parseInt(body.slice(1), 10);
500
+ return Number.isFinite(code) && code >= 0 && code <= 1114111 ? String.fromCodePoint(code) : match;
501
+ }
502
+ }
503
+ });
504
+ }
505
+ function xmlEscapeAttr(text) {
506
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
507
+ }
508
+ function localTagName(qName) {
509
+ const idx = qName.indexOf(":");
510
+ return (idx >= 0 ? qName.slice(idx + 1) : qName).toLowerCase();
511
+ }
512
+ /**
513
+ * Scan attributes from a tag's raw attribute slice without allocating per-element
514
+ * objects unless needed. Matches by exact attribute name OR suffix after `:`
515
+ * when `matchLocal` is needed via a callback.
516
+ */
517
+ function parseTagAttrs(attrText, cb) {
518
+ const len = attrText.length;
519
+ let i = 0;
520
+ while (i < len) {
521
+ while (i < len && attrText.charCodeAt(i) <= 32) i++;
522
+ if (i >= len) break;
523
+ const nameStart = i;
524
+ while (i < len && attrText.charCodeAt(i) > 32 && attrText[i] !== "=" && attrText[i] !== "/") i++;
525
+ const rawName = attrText.slice(nameStart, i);
526
+ while (i < len && attrText.charCodeAt(i) <= 32) i++;
527
+ if (i >= len || attrText[i] !== "=") continue;
528
+ i++;
529
+ while (i < len && attrText.charCodeAt(i) <= 32) i++;
530
+ if (i >= len) break;
531
+ const quote = attrText[i];
532
+ if (quote === "\"" || quote === "'") {
533
+ i++;
534
+ const valStart = i;
535
+ const close = attrText.indexOf(quote, valStart);
536
+ if (close < 0) {
537
+ cb(rawName, xmlUnescape(attrText.slice(valStart)));
538
+ break;
539
+ }
540
+ cb(rawName, xmlUnescape(attrText.slice(valStart, close)));
541
+ i = close + 1;
542
+ } else {
543
+ const valStart = i;
544
+ while (i < len && attrText.charCodeAt(i) > 32) i++;
545
+ cb(rawName, xmlUnescape(attrText.slice(valStart, i)));
546
+ }
547
+ }
548
+ }
549
+ /**
550
+ * Streaming, non-backtracking XML tag scanner tailored for 3MF `.model` and `.rels` files.
551
+ */
552
+ function scanXml(xml, cb, signal) {
553
+ const len = xml.length;
554
+ let pos = 0;
555
+ let iter = 0;
556
+ while (pos < len) {
557
+ if ((iter++ & 16383) === 0) throwIfAborted$4(signal);
558
+ const lt = xml.indexOf("<", pos);
559
+ if (lt < 0) break;
560
+ const next = xml.charCodeAt(lt + 1);
561
+ if (next === 63) {
562
+ const endPi = xml.indexOf("?>", lt + 2);
563
+ pos = endPi < 0 ? len : endPi + 2;
564
+ continue;
565
+ }
566
+ if (next === 33) {
567
+ if (xml.startsWith("<!--", lt)) {
568
+ const endComment = xml.indexOf("-->", lt + 4);
569
+ if (endComment < 0) throw new Error("Invalid 3MF XML: unclosed comment");
570
+ pos = endComment + 3;
571
+ continue;
572
+ }
573
+ if (xml.startsWith("<![CDATA[", lt)) {
574
+ const endCdata = xml.indexOf("]]>", lt + 9);
575
+ if (endCdata < 0) throw new Error("Invalid 3MF XML: unclosed CDATA section");
576
+ pos = endCdata + 3;
577
+ continue;
578
+ }
579
+ throw new Error("Invalid 3MF XML: unsupported declaration");
580
+ }
581
+ let i = lt + 1;
582
+ let quoteChar = 0;
583
+ let tagEnd = -1;
584
+ while (i < len) {
585
+ const ch = xml.charCodeAt(i);
586
+ if (quoteChar !== 0) {
587
+ if (ch === quoteChar) quoteChar = 0;
588
+ } else if (ch === 34 || ch === 39) quoteChar = ch;
589
+ else if (ch === 62) {
590
+ tagEnd = i;
591
+ break;
592
+ }
593
+ i++;
594
+ }
595
+ if (tagEnd < 0) throw new Error("Invalid 3MF XML: unclosed tag");
596
+ if (next === 47) {
597
+ const rawClose = xml.slice(lt + 2, tagEnd).trim();
598
+ cb.onClose(localTagName(rawClose));
599
+ pos = tagEnd + 1;
600
+ continue;
601
+ }
602
+ let selfClosing = false;
603
+ let contentEnd = tagEnd;
604
+ if (tagEnd > lt + 1 && xml.charCodeAt(tagEnd - 1) === 47) {
605
+ selfClosing = true;
606
+ contentEnd = tagEnd - 1;
607
+ }
608
+ let nameEnd = lt + 1;
609
+ while (nameEnd < contentEnd && xml.charCodeAt(nameEnd) > 32) nameEnd++;
610
+ const qName = xml.slice(lt + 1, nameEnd);
611
+ const attrText = xml.slice(nameEnd, contentEnd);
612
+ const lname = localTagName(qName);
613
+ cb.onOpen(lname, attrText, selfClosing);
614
+ if (selfClosing) cb.onClose(lname);
615
+ pos = tagEnd + 1;
616
+ }
617
+ }
618
+ function normalizeOpcPath(baseFile, target) {
619
+ const cleaned = target.replaceAll("\\", "/");
620
+ const isRooted = cleaned.startsWith("/");
621
+ const baseParts = isRooted ? [] : baseFile.split("/").slice(0, -1);
622
+ const relParts = (isRooted ? cleaned.slice(1) : cleaned).split("/");
623
+ const out = [...baseParts];
624
+ for (let i = 0; i < relParts.length; i++) {
625
+ const seg = relParts[i];
626
+ if (seg === "" || seg === ".") continue;
627
+ if (seg === "..") {
628
+ if (out.length === 0) throw new Error(`Invalid 3MF OPC path "${target}" escapes archive root`);
629
+ out.pop();
630
+ continue;
631
+ }
632
+ out.push(seg);
633
+ }
634
+ return out.join("/");
635
+ }
636
+ function findZipEntryCaseFallback(entries, path) {
637
+ const direct = entries.get(path);
638
+ if (direct !== void 0) return {
639
+ path,
640
+ data: direct
641
+ };
642
+ const lower = path.toLowerCase();
643
+ for (const [k, v] of entries) if (k.toLowerCase() === lower) return {
644
+ path: k,
645
+ data: v
646
+ };
647
+ return null;
648
+ }
649
+ function parseHexColor(hexRaw) {
650
+ const s = hexRaw.trim();
651
+ if (!s.startsWith("#")) throw new Error(`Invalid 3MF color "${hexRaw}": expected #RRGGBB or #RRGGBBAA`);
652
+ const h = s.slice(1);
653
+ let r;
654
+ let g;
655
+ let b;
656
+ let a = 255;
657
+ if (h.length === 6) {
658
+ const val = Number.parseInt(h, 16);
659
+ if (!Number.isFinite(val)) throw new Error(`Invalid 3MF color "${hexRaw}"`);
660
+ r = val >>> 16 & 255;
661
+ g = val >>> 8 & 255;
662
+ b = val & 255;
663
+ } else if (h.length === 8) {
664
+ const val = Number.parseInt(h, 16);
665
+ if (!Number.isFinite(val)) throw new Error(`Invalid 3MF color "${hexRaw}"`);
666
+ r = val >>> 24 & 255;
667
+ g = val >>> 16 & 255;
668
+ b = val >>> 8 & 255;
669
+ a = val & 255;
670
+ } else if (h.length === 3 || h.length === 4) {
671
+ const rN = Number.parseInt(h[0], 16);
672
+ const gN = Number.parseInt(h[1], 16);
673
+ const bN = Number.parseInt(h[2], 16);
674
+ const aN = h.length === 4 ? Number.parseInt(h[3], 16) : 15;
675
+ if (!Number.isFinite(rN) || !Number.isFinite(gN) || !Number.isFinite(bN) || !Number.isFinite(aN)) throw new Error(`Invalid 3MF color "${hexRaw}"`);
676
+ r = rN * 17;
677
+ g = gN * 17;
678
+ b = bN * 17;
679
+ a = aN * 17;
680
+ } else throw new Error(`Invalid 3MF color "${hexRaw}": unsupported hex length`);
681
+ return ((r & 255) << 24 | (g & 255) << 16 | (b & 255) << 8 | a & 255) >>> 0;
682
+ }
683
+ const IDENTITY_3X4 = new Float64Array([
684
+ 1,
685
+ 0,
686
+ 0,
687
+ 0,
688
+ 1,
689
+ 0,
690
+ 0,
691
+ 0,
692
+ 1,
693
+ 0,
694
+ 0,
695
+ 0
696
+ ]);
697
+ function parseTransform3x4(raw) {
698
+ if (raw === void 0 || raw.trim() === "") return IDENTITY_3X4;
699
+ const parts = raw.trim().split(/\s+/);
700
+ if (parts.length !== 12) throw new Error(`Invalid 3MF transform "${raw}": expected 12 numbers, got ${parts.length}`);
701
+ const out = /* @__PURE__ */ new Float64Array(12);
702
+ for (let i = 0; i < 12; i++) {
703
+ const n = Number(parts[i]);
704
+ if (!Number.isFinite(n)) throw new Error(`Invalid 3MF transform: non-finite number "${parts[i]}"`);
705
+ out[i] = n;
706
+ }
707
+ return out;
708
+ }
709
+ /** Compose affine matrices `child` then `parent`: `(v * child) * parent`. */
710
+ function composeRowAffine(child, parent) {
711
+ const r = /* @__PURE__ */ new Float64Array(12);
712
+ for (let row = 0; row < 3; row++) {
713
+ const a0 = child[row * 3];
714
+ const a1 = child[row * 3 + 1];
715
+ const a2 = child[row * 3 + 2];
716
+ for (let col = 0; col < 3; col++) r[row * 3 + col] = a0 * parent[col] + a1 * parent[3 + col] + a2 * parent[6 + col];
717
+ }
718
+ const t0 = child[9];
719
+ const t1 = child[10];
720
+ const t2 = child[11];
721
+ for (let col = 0; col < 3; col++) r[9 + col] = t0 * parent[col] + t1 * parent[3 + col] + t2 * parent[6 + col] + parent[9 + col];
722
+ return r;
723
+ }
724
+ function det3x3(m) {
725
+ return m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
726
+ }
727
+ function parseIntStrict(raw, label) {
728
+ const n = Number(raw);
729
+ if (!Number.isInteger(n)) throw new Error(`Invalid 3MF integer for ${label}: "${raw}"`);
730
+ return n;
731
+ }
732
+ function parseFloatFinite(raw, label) {
733
+ const n = Number(raw);
734
+ if (!Number.isFinite(n)) throw new Error(`Invalid 3MF number for ${label}: "${raw}"`);
735
+ return n;
736
+ }
737
+ function parseModelXml(modelPath, xml, signal) {
738
+ const materials = /* @__PURE__ */ new Map();
739
+ const objects = /* @__PURE__ */ new Map();
740
+ const buildItems = [];
741
+ let unit;
742
+ let activeMaterialGroupId = null;
743
+ let activeMaterialColors = null;
744
+ let currentObject = null;
745
+ let inResources = false;
746
+ let inBuild = false;
747
+ let inMesh = false;
748
+ let inVertices = false;
749
+ let inTriangles = false;
750
+ let inComponents = false;
751
+ let triPids = [];
752
+ let triP1List = [];
753
+ let triP2List = [];
754
+ let triP3List = [];
755
+ scanXml(xml, {
756
+ onOpen(tag, attrText) {
757
+ if (tag === "model") {
758
+ parseTagAttrs(attrText, (name, value) => {
759
+ if (name === "unit") {
760
+ const lower = value.trim().toLowerCase();
761
+ if (lower in UNIT_TO_MM) unit = lower;
762
+ }
763
+ });
764
+ return;
765
+ }
766
+ if (tag === "resources") {
767
+ inResources = true;
768
+ return;
769
+ }
770
+ if (tag === "build") {
771
+ inBuild = true;
772
+ return;
773
+ }
774
+ if (inResources && (tag === "basematerials" || tag === "colorgroup")) {
775
+ let id = "";
776
+ parseTagAttrs(attrText, (name, value) => {
777
+ if (name === "id") id = value;
778
+ });
779
+ if (id === "") throw new Error(`Invalid 3MF <${tag}> missing id attribute`);
780
+ activeMaterialGroupId = id;
781
+ activeMaterialColors = [];
782
+ materials.set(id, activeMaterialColors);
783
+ return;
784
+ }
785
+ if (activeMaterialColors !== null && (tag === "base" || tag === "color")) {
786
+ let hex;
787
+ parseTagAttrs(attrText, (name, value) => {
788
+ if (name === "displaycolor" || name === "color") hex = value;
789
+ });
790
+ if (hex !== void 0) activeMaterialColors.push(parseHexColor(hex));
791
+ else activeMaterialColors.push(4294967295);
792
+ return;
793
+ }
794
+ if (inResources && tag === "object") {
795
+ let id = "";
796
+ let name = "";
797
+ let pid;
798
+ let pindex;
799
+ parseTagAttrs(attrText, (attrName, value) => {
800
+ if (attrName === "id") id = value;
801
+ else if (attrName === "name" || attrName === "partnumber") {
802
+ if (name === "" || attrName === "name") name = value;
803
+ } else if (attrName === "pid") pid = value;
804
+ else if (attrName === "pindex") pindex = parseIntStrict(value, "object pindex");
805
+ });
806
+ if (id === "") throw new Error("Invalid 3MF <object> missing id attribute");
807
+ currentObject = {
808
+ id,
809
+ name: name || `object-${id}`,
810
+ defaultPid: pid,
811
+ defaultPIndex: pindex
812
+ };
813
+ objects.set(id, currentObject);
814
+ return;
815
+ }
816
+ if (currentObject !== null && tag === "mesh") {
817
+ inMesh = true;
818
+ triPids = [];
819
+ triP1List = [];
820
+ triP2List = [];
821
+ triP3List = [];
822
+ currentObject.mesh = {
823
+ vertices: [],
824
+ triangles: [],
825
+ triPids,
826
+ triP1: /* @__PURE__ */ new Int32Array(0),
827
+ triP2: /* @__PURE__ */ new Int32Array(0),
828
+ triP3: /* @__PURE__ */ new Int32Array(0)
829
+ };
830
+ return;
831
+ }
832
+ if (inMesh && currentObject?.mesh && tag === "vertices") {
833
+ inVertices = true;
834
+ return;
835
+ }
836
+ if (inMesh && currentObject?.mesh && tag === "triangles") {
837
+ inTriangles = true;
838
+ return;
839
+ }
840
+ if (inVertices && currentObject?.mesh && tag === "vertex") {
841
+ let x;
842
+ let y;
843
+ let z;
844
+ parseTagAttrs(attrText, (name, value) => {
845
+ if (name === "x") x = parseFloatFinite(value, "vertex.x");
846
+ else if (name === "y") y = parseFloatFinite(value, "vertex.y");
847
+ else if (name === "z") z = parseFloatFinite(value, "vertex.z");
848
+ });
849
+ if (x === void 0 || y === void 0 || z === void 0) throw new Error("Invalid 3MF <vertex> missing x, y, or z attribute");
850
+ currentObject.mesh.vertices.push(x, y, z);
851
+ return;
852
+ }
853
+ if (inTriangles && currentObject?.mesh && tag === "triangle") {
854
+ let v1 = -1;
855
+ let v2 = -1;
856
+ let v3 = -1;
857
+ let pid;
858
+ let p1 = -1;
859
+ let p2 = -1;
860
+ let p3 = -1;
861
+ parseTagAttrs(attrText, (name, value) => {
862
+ if (name === "v1") v1 = parseIntStrict(value, "triangle.v1");
863
+ else if (name === "v2") v2 = parseIntStrict(value, "triangle.v2");
864
+ else if (name === "v3") v3 = parseIntStrict(value, "triangle.v3");
865
+ else if (name === "pid") pid = value;
866
+ else if (name === "p1") p1 = parseIntStrict(value, "triangle.p1");
867
+ else if (name === "p2") p2 = parseIntStrict(value, "triangle.p2");
868
+ else if (name === "p3") p3 = parseIntStrict(value, "triangle.p3");
869
+ });
870
+ if (v1 < 0 || v2 < 0 || v3 < 0) throw new Error(`Invalid 3MF <triangle> indices (${v1}, ${v2}, ${v3})`);
871
+ currentObject.mesh.triangles.push(v1, v2, v3);
872
+ triPids.push(pid);
873
+ triP1List.push(p1);
874
+ triP2List.push(p2 >= 0 ? p2 : p1);
875
+ triP3List.push(p3 >= 0 ? p3 : p1);
876
+ return;
877
+ }
878
+ if (currentObject !== null && tag === "components") {
879
+ inComponents = true;
880
+ if (!currentObject.components) currentObject.components = [];
881
+ return;
882
+ }
883
+ if (inComponents && currentObject?.components && tag === "component") {
884
+ let objectId = "";
885
+ let transformRaw;
886
+ let path;
887
+ parseTagAttrs(attrText, (name, value) => {
888
+ const lname = localTagName(name);
889
+ if (lname === "objectid") objectId = value;
890
+ else if (lname === "transform") transformRaw = value;
891
+ else if (lname === "path") path = value;
892
+ });
893
+ if (objectId === "") throw new Error("Invalid 3MF <component> missing objectid");
894
+ currentObject.components.push({
895
+ objectId,
896
+ transform: parseTransform3x4(transformRaw),
897
+ path
898
+ });
899
+ return;
900
+ }
901
+ if (inBuild && tag === "item") {
902
+ let objectId = "";
903
+ let transformRaw;
904
+ let path;
905
+ parseTagAttrs(attrText, (name, value) => {
906
+ const lname = localTagName(name);
907
+ if (lname === "objectid") objectId = value;
908
+ else if (lname === "transform") transformRaw = value;
909
+ else if (lname === "path") path = value;
910
+ });
911
+ if (objectId === "") throw new Error("Invalid 3MF <item> missing objectid");
912
+ buildItems.push({
913
+ objectId,
914
+ transform: parseTransform3x4(transformRaw),
915
+ path
916
+ });
917
+ }
918
+ },
919
+ onClose(tag) {
920
+ if (tag === "resources") inResources = false;
921
+ else if (tag === "build") inBuild = false;
922
+ else if (tag === "basematerials" || tag === "colorgroup") {
923
+ if (activeMaterialGroupId !== null) {
924
+ activeMaterialGroupId = null;
925
+ activeMaterialColors = null;
926
+ }
927
+ } else if (tag === "object") {
928
+ currentObject = null;
929
+ inMesh = false;
930
+ inVertices = false;
931
+ inTriangles = false;
932
+ inComponents = false;
933
+ } else if (tag === "mesh") {
934
+ if (currentObject?.mesh) {
935
+ currentObject.mesh.triP1 = Int32Array.from(triP1List);
936
+ currentObject.mesh.triP2 = Int32Array.from(triP2List);
937
+ currentObject.mesh.triP3 = Int32Array.from(triP3List);
938
+ }
939
+ inMesh = false;
940
+ inVertices = false;
941
+ inTriangles = false;
942
+ } else if (tag === "vertices") inVertices = false;
943
+ else if (tag === "triangles") inTriangles = false;
944
+ else if (tag === "components") inComponents = false;
945
+ }
946
+ }, signal);
947
+ for (const obj of objects.values()) {
948
+ const mesh = obj.mesh;
949
+ if (!mesh) continue;
950
+ const vertCount = mesh.vertices.length / 3;
951
+ for (let i = 0; i < mesh.triangles.length; i++) {
952
+ const idx = mesh.triangles[i];
953
+ if (idx < 0 || idx >= vertCount) throw new Error(`Invalid 3MF mesh "${obj.name}": triangle vertex index ${idx} out of range (0..${vertCount - 1})`);
954
+ }
955
+ }
956
+ return {
957
+ path: modelPath,
958
+ unit,
959
+ materials,
960
+ objects,
961
+ buildItems
962
+ };
963
+ }
964
+ function findRootModelPath(entries) {
965
+ const relsEntry = findZipEntryCaseFallback(entries, "_rels/.rels");
966
+ if (relsEntry) {
967
+ const xml = decodeXmlUtf8(relsEntry.data, relsEntry.path);
968
+ let targetPath = null;
969
+ scanXml(xml, {
970
+ onOpen(tag, attrText) {
971
+ if (tag !== "relationship" || targetPath !== null) return;
972
+ let relType = "";
973
+ let target = "";
974
+ parseTagAttrs(attrText, (name, value) => {
975
+ const lname = localTagName(name);
976
+ if (lname === "type") relType = value.trim().toLowerCase();
977
+ else if (lname === "target") target = value.trim();
978
+ });
979
+ if (relType.endsWith("/3dmodel") && target !== "") targetPath = normalizeOpcPath(relsEntry.path, target);
980
+ },
981
+ onClose() {}
982
+ });
983
+ if (targetPath !== null) return targetPath;
984
+ }
985
+ return "3D/3dmodel.model";
986
+ }
987
+ function instantiateMeshObject(model, obj, mesh, transform, scaleToMm, name) {
988
+ const origVertCount = mesh.vertices.length / 3;
989
+ const triCount = mesh.triangles.length / 3;
990
+ const flipWinding = det3x3(transform) < 0;
991
+ const cornerColors = new Uint32Array(triCount * 3);
992
+ const cornerHasColor = new Uint8Array(triCount * 3);
993
+ let anyColor = false;
994
+ for (let t = 0; t < triCount; t++) {
995
+ const pid = mesh.triPids[t] ?? obj.defaultPid;
996
+ if (pid === void 0) continue;
997
+ const group = model.materials.get(pid);
998
+ if (!group || group.length === 0) continue;
999
+ const p1 = mesh.triP1[t] >= 0 ? mesh.triP1[t] : obj.defaultPIndex ?? -1;
1000
+ const p2 = mesh.triP2[t] >= 0 ? mesh.triP2[t] : p1;
1001
+ const p3 = mesh.triP3[t] >= 0 ? mesh.triP3[t] : p1;
1002
+ const cIndices = flipWinding ? [
1003
+ p1,
1004
+ p3,
1005
+ p2
1006
+ ] : [
1007
+ p1,
1008
+ p2,
1009
+ p3
1010
+ ];
1011
+ for (let k = 0; k < 3; k++) {
1012
+ const pi = cIndices[k];
1013
+ if (pi >= 0 && pi < group.length) {
1014
+ cornerColors[t * 3 + k] = group[pi];
1015
+ cornerHasColor[t * 3 + k] = 1;
1016
+ anyColor = true;
1017
+ }
1018
+ }
1019
+ }
1020
+ let outPositions;
1021
+ let outIndices;
1022
+ let outColors = null;
1023
+ if (!anyColor) {
1024
+ outPositions = new Float64Array(origVertCount * 3);
1025
+ for (let v = 0; v < origVertCount; v++) {
1026
+ const x = mesh.vertices[v * 3];
1027
+ const y = mesh.vertices[v * 3 + 1];
1028
+ const z = mesh.vertices[v * 3 + 2];
1029
+ outPositions[v * 3] = (transform[0] * x + transform[3] * y + transform[6] * z + transform[9]) * scaleToMm;
1030
+ outPositions[v * 3 + 1] = (transform[1] * x + transform[4] * y + transform[7] * z + transform[10]) * scaleToMm;
1031
+ outPositions[v * 3 + 2] = (transform[2] * x + transform[5] * y + transform[8] * z + transform[11]) * scaleToMm;
1032
+ }
1033
+ outIndices = new Uint32Array(triCount * 3);
1034
+ for (let t = 0; t < triCount; t++) {
1035
+ const a = mesh.triangles[t * 3];
1036
+ const b = mesh.triangles[t * 3 + 1];
1037
+ const c = mesh.triangles[t * 3 + 2];
1038
+ if (flipWinding) {
1039
+ outIndices[t * 3] = a;
1040
+ outIndices[t * 3 + 1] = c;
1041
+ outIndices[t * 3 + 2] = b;
1042
+ } else {
1043
+ outIndices[t * 3] = a;
1044
+ outIndices[t * 3 + 1] = b;
1045
+ outIndices[t * 3 + 2] = c;
1046
+ }
1047
+ }
1048
+ } else {
1049
+ const vertAssigned = new Uint8Array(origVertCount);
1050
+ const vertColor = new Uint32Array(origVertCount);
1051
+ const cloneLookup = /* @__PURE__ */ new Map();
1052
+ const extraSrcVert = [];
1053
+ const extraColors = [];
1054
+ outIndices = new Uint32Array(triCount * 3);
1055
+ for (let t = 0; t < triCount; t++) {
1056
+ const a = mesh.triangles[t * 3];
1057
+ const b = mesh.triangles[t * 3 + 1];
1058
+ const c = mesh.triangles[t * 3 + 2];
1059
+ const triVerts = flipWinding ? [
1060
+ a,
1061
+ c,
1062
+ b
1063
+ ] : [
1064
+ a,
1065
+ b,
1066
+ c
1067
+ ];
1068
+ for (let k = 0; k < 3; k++) {
1069
+ const origV = triVerts[k];
1070
+ const col = cornerHasColor[t * 3 + k] !== 0 ? cornerColors[t * 3 + k] : 4294967295;
1071
+ if (vertAssigned[origV] === 0) {
1072
+ vertAssigned[origV] = 1;
1073
+ vertColor[origV] = col;
1074
+ outIndices[t * 3 + k] = origV;
1075
+ } else if (vertColor[origV] === col) outIndices[t * 3 + k] = origV;
1076
+ else {
1077
+ let mapForV = cloneLookup.get(origV);
1078
+ if (!mapForV) {
1079
+ mapForV = /* @__PURE__ */ new Map();
1080
+ cloneLookup.set(origV, mapForV);
1081
+ }
1082
+ let clonedIdx = mapForV.get(col);
1083
+ if (clonedIdx === void 0) {
1084
+ clonedIdx = origVertCount + extraSrcVert.length;
1085
+ extraSrcVert.push(origV);
1086
+ extraColors.push(col);
1087
+ mapForV.set(col, clonedIdx);
1088
+ }
1089
+ outIndices[t * 3 + k] = clonedIdx;
1090
+ }
1091
+ }
1092
+ }
1093
+ const totalVerts = origVertCount + extraSrcVert.length;
1094
+ outPositions = new Float64Array(totalVerts * 3);
1095
+ outColors = new Uint8Array(totalVerts * 4);
1096
+ const writeTransformedVert = (dstIdx, srcOrigIdx, rgba) => {
1097
+ const x = mesh.vertices[srcOrigIdx * 3];
1098
+ const y = mesh.vertices[srcOrigIdx * 3 + 1];
1099
+ const z = mesh.vertices[srcOrigIdx * 3 + 2];
1100
+ outPositions[dstIdx * 3] = (transform[0] * x + transform[3] * y + transform[6] * z + transform[9]) * scaleToMm;
1101
+ outPositions[dstIdx * 3 + 1] = (transform[1] * x + transform[4] * y + transform[7] * z + transform[10]) * scaleToMm;
1102
+ outPositions[dstIdx * 3 + 2] = (transform[2] * x + transform[5] * y + transform[8] * z + transform[11]) * scaleToMm;
1103
+ outColors[dstIdx * 4] = rgba >>> 24 & 255;
1104
+ outColors[dstIdx * 4 + 1] = rgba >>> 16 & 255;
1105
+ outColors[dstIdx * 4 + 2] = rgba >>> 8 & 255;
1106
+ outColors[dstIdx * 4 + 3] = rgba & 255;
1107
+ };
1108
+ for (let v = 0; v < origVertCount; v++) {
1109
+ const rgba = vertAssigned[v] !== 0 ? vertColor[v] : 4294967295;
1110
+ writeTransformedVert(v, v, rgba);
1111
+ }
1112
+ for (let e = 0; e < extraSrcVert.length; e++) writeTransformedVert(origVertCount + e, extraSrcVert[e], extraColors[e]);
1113
+ }
1114
+ return {
1115
+ name,
1116
+ positions: outPositions,
1117
+ indices: outIndices,
1118
+ placement: new Float64Array([
1119
+ 1,
1120
+ 0,
1121
+ 0,
1122
+ 0,
1123
+ 0,
1124
+ 1,
1125
+ 0,
1126
+ 0,
1127
+ 0,
1128
+ 0,
1129
+ 1,
1130
+ 0,
1131
+ 0,
1132
+ 0,
1133
+ 0,
1134
+ 1
1135
+ ]),
1136
+ colors: outColors,
1137
+ uvs: null
1138
+ };
1139
+ }
1140
+ /**
1141
+ * Parse a 3MF archive into {@link ImportedMesh} records scaled to millimeters.
1142
+ */
1143
+ async function import3MF(bytes, options) {
1144
+ throwIfAborted$4(options?.signal);
1145
+ const archive = await readZip(toUint8$3(bytes), {
1146
+ maxFileBytes: options?.maxFileBytes,
1147
+ signal: options?.signal
1148
+ });
1149
+ const contentTypes = findZipEntryCaseFallback(archive, "[Content_Types].xml");
1150
+ if (contentTypes) decodeXmlUtf8(contentTypes.data, contentTypes.path);
1151
+ const rootPath = findRootModelPath(archive);
1152
+ const modelCache = /* @__PURE__ */ new Map();
1153
+ const loadModel = (modelPath) => {
1154
+ const cached = modelCache.get(modelPath);
1155
+ if (cached) return cached;
1156
+ const found = findZipEntryCaseFallback(archive, modelPath);
1157
+ if (!found) throw new Error(`3MF archive is missing model file "${modelPath}"`);
1158
+ const xml = decodeXmlUtf8(found.data, found.path);
1159
+ const parsed = parseModelXml(found.path, xml, options?.signal);
1160
+ modelCache.set(modelPath, parsed);
1161
+ return parsed;
1162
+ };
1163
+ const rootModel = loadModel(rootPath);
1164
+ const rootUnitScale = UNIT_TO_MM[rootModel.unit ?? "millimeter"];
1165
+ const results = [];
1166
+ const stackKeys = /* @__PURE__ */ new Set();
1167
+ const visitObject = (model, objectId, worldTransform, inheritedScale) => {
1168
+ throwIfAborted$4(options?.signal);
1169
+ if (stackKeys.size >= 256) throw new Error("3MF component hierarchy exceeds maximum recursion depth (256)");
1170
+ const key = `${model.path}#${objectId}`;
1171
+ if (stackKeys.has(key)) throw new Error(`3MF cyclic component reference detected at "${key}"`);
1172
+ const obj = model.objects.get(objectId);
1173
+ if (!obj) throw new Error(`3MF references unknown object id "${objectId}" in "${model.path}"`);
1174
+ const modelScale = options?.unitScale ?? (model.unit !== void 0 ? UNIT_TO_MM[model.unit] : inheritedScale);
1175
+ stackKeys.add(key);
1176
+ try {
1177
+ if (obj.mesh) results.push(instantiateMeshObject(model, obj, obj.mesh, worldTransform, modelScale, obj.name));
1178
+ if (obj.components) for (let i = 0; i < obj.components.length; i++) {
1179
+ const comp = obj.components[i];
1180
+ const targetModel = comp.path ? loadModel(normalizeOpcPath(model.path, comp.path)) : model;
1181
+ const combined = composeRowAffine(comp.transform, worldTransform);
1182
+ visitObject(targetModel, comp.objectId, combined, modelScale);
1183
+ }
1184
+ } finally {
1185
+ stackKeys.delete(key);
1186
+ }
1187
+ };
1188
+ for (let i = 0; i < rootModel.buildItems.length; i++) {
1189
+ const item = rootModel.buildItems[i];
1190
+ visitObject(item.path ? loadModel(normalizeOpcPath(rootModel.path, item.path)) : rootModel, item.objectId, item.transform, rootUnitScale);
1191
+ }
1192
+ return results;
1193
+ }
1194
+ const CONTENT_TYPES_XML = textEncoder.encode("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\n <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\n <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\n</Types>\n");
1195
+ const ROOT_RELS_XML = textEncoder.encode("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\n <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\n</Relationships>\n");
1196
+ function isIdentityMatrix4(m) {
1197
+ return m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 0 && m[4] === 0 && m[5] === 1 && m[6] === 0 && m[7] === 0 && m[8] === 0 && m[9] === 0 && m[10] === 1 && m[11] === 0 && m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1;
1198
+ }
1199
+ function isAffineMatrix4(m) {
1200
+ return Math.abs(m[3]) <= 1e-12 && Math.abs(m[7]) <= 1e-12 && Math.abs(m[11]) <= 1e-12 && Math.abs(m[15] - 1) <= 1e-12;
1201
+ }
1202
+ function formatHexColor(r, g, b, a) {
1203
+ const hex2 = (n) => (n & 255).toString(16).toUpperCase().padStart(2, "0");
1204
+ return a === 255 ? `#${hex2(r)}${hex2(g)}${hex2(b)}` : `#${hex2(r)}${hex2(g)}${hex2(b)}${hex2(a)}`;
1205
+ }
1206
+ function buildThreeMfEntries(scene, meshes, options) {
1207
+ const list = Array.isArray(meshes) ? meshes : [meshes];
1208
+ const unit = options?.unit ?? "millimeter";
1209
+ const invUnitScale = 1 / UNIT_TO_MM[unit];
1210
+ const applyPlacement = options?.applyPlacement !== false;
1211
+ const includeColors = options?.vertexColors !== false;
1212
+ const compress = options?.compress !== false;
1213
+ const baseName = options?.name ?? "mesh";
1214
+ const colorList = [];
1215
+ const colorToIndex = /* @__PURE__ */ new Map();
1216
+ const getColorIndex = (r, g, b, a) => {
1217
+ const key = ((r & 255) << 24 | (g & 255) << 16 | (b & 255) << 8 | a & 255) >>> 0;
1218
+ let idx = colorToIndex.get(key);
1219
+ if (idx === void 0) {
1220
+ idx = colorList.length;
1221
+ colorList.push(formatHexColor(r, g, b, a));
1222
+ colorToIndex.set(key, idx);
1223
+ }
1224
+ return idx;
1225
+ };
1226
+ const objects = [];
1227
+ let hasAnyColors = false;
1228
+ for (let mIdx = 0; mIdx < list.length; mIdx++) {
1229
+ const handle = list[mIdx];
1230
+ const views = scene.views(handle);
1231
+ const rawPos = views.positions().slice();
1232
+ const rawIdx = views.indices().slice();
1233
+ const rawCol = views.colors();
1234
+ const vertexSlots = rawPos.length / 3;
1235
+ const triSlots = rawIdx.length / 3;
1236
+ const colorsCopy = includeColors && rawCol !== null && rawCol !== void 0 && rawCol.length >= 4 / 3 * rawPos.length ? rawCol.slice() : null;
1237
+ const remap = new Int32Array(vertexSlots).fill(-1);
1238
+ const kept = new Uint32Array(rawIdx.length);
1239
+ let triangles = 0;
1240
+ let vertices = 0;
1241
+ for (let t = 0; t < triSlots; t++) {
1242
+ const a = rawIdx[3 * t];
1243
+ const b = rawIdx[3 * t + 1];
1244
+ const c = rawIdx[3 * t + 2];
1245
+ if (a === 0 && b === 0 && c === 0) continue;
1246
+ for (const v of [
1247
+ a,
1248
+ b,
1249
+ c
1250
+ ]) {
1251
+ if (v >= vertexSlots) throw new Error(`fast-mesh-wasm/io: triangle ${t} indexes missing vertex ${v}`);
1252
+ if (remap[v] === -1) remap[v] = vertices++;
1253
+ }
1254
+ kept[3 * triangles] = remap[a];
1255
+ kept[3 * triangles + 1] = remap[b];
1256
+ kept[3 * triangles + 2] = remap[c];
1257
+ triangles++;
1258
+ }
1259
+ const outPos = new Float32Array(3 * vertices);
1260
+ const outColors = colorsCopy !== null ? new Uint8Array(4 * vertices) : null;
1261
+ for (let v = 0; v < vertexSlots; v++) {
1262
+ const to = remap[v];
1263
+ if (to === -1) continue;
1264
+ outPos[3 * to] = rawPos[3 * v];
1265
+ outPos[3 * to + 1] = rawPos[3 * v + 1];
1266
+ outPos[3 * to + 2] = rawPos[3 * v + 2];
1267
+ if (outColors !== null && colorsCopy !== null) {
1268
+ outColors[4 * to] = colorsCopy[4 * v];
1269
+ outColors[4 * to + 1] = colorsCopy[4 * v + 1];
1270
+ outColors[4 * to + 2] = colorsCopy[4 * v + 2];
1271
+ outColors[4 * to + 3] = colorsCopy[4 * v + 3];
1272
+ }
1273
+ }
1274
+ let itemTransformAttr = "";
1275
+ if (applyPlacement) {
1276
+ const m = scene.matrix4(handle);
1277
+ if (!isIdentityMatrix4(m)) {
1278
+ if (isAffineMatrix4(m)) itemTransformAttr = ` transform="${[
1279
+ m[0],
1280
+ m[1],
1281
+ m[2],
1282
+ m[4],
1283
+ m[5],
1284
+ m[6],
1285
+ m[8],
1286
+ m[9],
1287
+ m[10],
1288
+ m[12] * invUnitScale,
1289
+ m[13] * invUnitScale,
1290
+ m[14] * invUnitScale
1291
+ ].join(" ")}"`;
1292
+ else for (let i = 0; i < outPos.length; i += 3) {
1293
+ const x = outPos[i];
1294
+ const y = outPos[i + 1];
1295
+ const z = outPos[i + 2];
1296
+ outPos[i] = m[0] * x + m[4] * y + m[8] * z + m[12];
1297
+ outPos[i + 1] = m[1] * x + m[5] * y + m[9] * z + m[13];
1298
+ outPos[i + 2] = m[2] * x + m[6] * y + m[10] * z + m[14];
1299
+ }
1300
+ }
1301
+ }
1302
+ if (outColors !== null && triangles > 0) hasAnyColors = true;
1303
+ const objName = list.length === 1 ? baseName : `${baseName}-${mIdx + 1}`;
1304
+ objects.push({
1305
+ id: mIdx + 1,
1306
+ name: objName,
1307
+ positions: outPos,
1308
+ colors: outColors,
1309
+ indices: kept.subarray(0, 3 * triangles),
1310
+ itemTransformAttr
1311
+ });
1312
+ }
1313
+ const colorGroupId = 1;
1314
+ if (hasAnyColors) for (let i = 0; i < objects.length; i++) objects[i].id = i + 2;
1315
+ const bodyParts = [];
1316
+ for (let i = 0; i < objects.length; i++) {
1317
+ const obj = objects[i];
1318
+ const vertCount = obj.positions.length / 3;
1319
+ const triCount = obj.indices.length / 3;
1320
+ let vertColorIds = null;
1321
+ if (obj.colors !== null && triCount > 0) {
1322
+ vertColorIds = new Uint32Array(vertCount);
1323
+ for (let v = 0; v < vertCount; v++) vertColorIds[v] = getColorIndex(obj.colors[4 * v], obj.colors[4 * v + 1], obj.colors[4 * v + 2], obj.colors[4 * v + 3]);
1324
+ }
1325
+ bodyParts.push(` <object id="${obj.id}" name="${xmlEscapeAttr(obj.name)}" type="model">\n <mesh>
1326
+ <vertices>
1327
+ `);
1328
+ for (let v = 0; v < vertCount; v++) {
1329
+ const x = obj.positions[3 * v] * invUnitScale;
1330
+ const y = obj.positions[3 * v + 1] * invUnitScale;
1331
+ const z = obj.positions[3 * v + 2] * invUnitScale;
1332
+ bodyParts.push(` <vertex x="${x}" y="${y}" z="${z}"/>\n`);
1333
+ }
1334
+ bodyParts.push(" </vertices>\n <triangles>\n");
1335
+ for (let t = 0; t < triCount; t++) {
1336
+ const a = obj.indices[3 * t];
1337
+ const b = obj.indices[3 * t + 1];
1338
+ const c = obj.indices[3 * t + 2];
1339
+ if (vertColorIds !== null) {
1340
+ const ca = vertColorIds[a];
1341
+ const cb = vertColorIds[b];
1342
+ const cc = vertColorIds[c];
1343
+ if (ca === cb && cb === cc) bodyParts.push(` <triangle v1="${a}" v2="${b}" v3="${c}" pid="${colorGroupId}" p1="${ca}"/>\n`);
1344
+ else bodyParts.push(` <triangle v1="${a}" v2="${b}" v3="${c}" pid="${colorGroupId}" p1="${ca}" p2="${cb}" p3="${cc}"/>\n`);
1345
+ } else bodyParts.push(` <triangle v1="${a}" v2="${b}" v3="${c}"/>\n`);
1346
+ }
1347
+ bodyParts.push(" </triangles>\n </mesh>\n </object>\n");
1348
+ }
1349
+ const xmlParts = ["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", `<model unit="${unit}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"` + (hasAnyColors ? " xmlns:m=\"http://schemas.microsoft.com/3dmanufacturing/material/2015/02\"" : "") + ">\n <resources>\n"];
1350
+ if (hasAnyColors) {
1351
+ xmlParts.push(` <m:colorgroup id="${colorGroupId}">\n`);
1352
+ for (let i = 0; i < colorList.length; i++) xmlParts.push(` <m:color color="${colorList[i]}"/>\n`);
1353
+ xmlParts.push(" </m:colorgroup>\n");
1354
+ }
1355
+ for (let i = 0; i < bodyParts.length; i++) xmlParts.push(bodyParts[i]);
1356
+ xmlParts.push(" </resources>\n <build>\n");
1357
+ for (let i = 0; i < objects.length; i++) xmlParts.push(` <item objectid="${objects[i].id}"${objects[i].itemTransformAttr}/>\n`);
1358
+ xmlParts.push(" </build>\n</model>\n");
1359
+ const modelBytes = textEncoder.encode(xmlParts.join(""));
1360
+ return [
1361
+ {
1362
+ name: "[Content_Types].xml",
1363
+ data: CONTENT_TYPES_XML,
1364
+ compress
1365
+ },
1366
+ {
1367
+ name: "_rels/.rels",
1368
+ data: ROOT_RELS_XML,
1369
+ compress
1370
+ },
1371
+ {
1372
+ name: "3D/3dmodel.model",
1373
+ data: modelBytes,
1374
+ compress
1375
+ }
1376
+ ];
1377
+ }
1378
+ /**
1379
+ * Export one or more scene meshes as a compressed 3MF archive.
1380
+ */
1381
+ async function export3MF(scene, meshes, options) {
1382
+ return writeZip(buildThreeMfEntries(scene, meshes, options), { compress: options?.compress ?? true });
1383
+ }
1384
+ /**
1385
+ * Export one or more scene meshes synchronously as an uncompressed (`STORE`) 3MF archive.
1386
+ */
1387
+ function export3MFSync(scene, meshes, options) {
1388
+ return writeZipSync(buildThreeMfEntries(scene, meshes, options));
1389
+ }
1390
+ // src/io/ply.ts
1391
+ const DEFAULT_MAX_BYTES$2 = 536870912;
1392
+ const textDecoder$3 = new TextDecoder("utf-8");
1393
+ function toUint8$2(bytes) {
1394
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
1395
+ }
1396
+ function throwIfAborted$3(signal) {
1397
+ if (signal?.aborted) {
1398
+ const reason = signal.reason;
1399
+ if (reason instanceof Error) throw reason;
1400
+ throw new DOMException("The operation was aborted.", "AbortError");
1401
+ }
1402
+ }
1403
+ function normalizeScalarType(raw) {
1404
+ switch (raw) {
1405
+ case "char":
1406
+ case "int8": return {
1407
+ type: "char",
1408
+ bytes: 1
1409
+ };
1410
+ case "uchar":
1411
+ case "uint8": return {
1412
+ type: "uchar",
1413
+ bytes: 1
1414
+ };
1415
+ case "short":
1416
+ case "int16": return {
1417
+ type: "short",
1418
+ bytes: 2
1419
+ };
1420
+ case "ushort":
1421
+ case "uint16": return {
1422
+ type: "ushort",
1423
+ bytes: 2
1424
+ };
1425
+ case "int":
1426
+ case "int32": return {
1427
+ type: "int",
1428
+ bytes: 4
1429
+ };
1430
+ case "uint":
1431
+ case "uint32": return {
1432
+ type: "uint",
1433
+ bytes: 4
1434
+ };
1435
+ case "float":
1436
+ case "float32": return {
1437
+ type: "float",
1438
+ bytes: 4
1439
+ };
1440
+ case "double":
1441
+ case "float64": return {
1442
+ type: "double",
1443
+ bytes: 8
1444
+ };
1445
+ default: throw new Error(`Invalid PLY property type "${raw}"`);
1446
+ }
1447
+ }
1448
+ function readScalar(view, offset, type, littleEndian) {
1449
+ switch (type) {
1450
+ case "char": return view.getInt8(offset);
1451
+ case "uchar": return view.getUint8(offset);
1452
+ case "short": return view.getInt16(offset, littleEndian);
1453
+ case "ushort": return view.getUint16(offset, littleEndian);
1454
+ case "int": return view.getInt32(offset, littleEndian);
1455
+ case "uint": return view.getUint32(offset, littleEndian);
1456
+ case "float": return view.getFloat32(offset, littleEndian);
1457
+ case "double": return view.getFloat64(offset, littleEndian);
1458
+ }
1459
+ }
1460
+ function isFloatType(type) {
1461
+ return type === "float" || type === "double";
1462
+ }
1463
+ function colorByteFromScalar(value, type) {
1464
+ if (!Number.isFinite(value)) return 255;
1465
+ if (isFloatType(type)) return Math.round((value < 0 ? 0 : value > 1 ? 1 : value) * 255);
1466
+ if (value <= 0) return 0;
1467
+ if (value >= 255) return 255;
1468
+ return Math.round(value);
1469
+ }
1470
+ function findHeaderEnd(bytes) {
1471
+ const maxHeaderScan = Math.min(bytes.byteLength, 1048576);
1472
+ let lineStart = 0;
1473
+ let pos = 0;
1474
+ while (pos < maxHeaderScan) {
1475
+ const b = bytes[pos];
1476
+ if (b === 10 || b === 13) {
1477
+ const lineEnd = pos;
1478
+ let nextPos = pos + 1;
1479
+ if (b === 13 && nextPos < maxHeaderScan && bytes[nextPos] === 10) nextPos++;
1480
+ if (textDecoder$3.decode(bytes.subarray(lineStart, lineEnd)).trim() === "end_header") return {
1481
+ headerText: textDecoder$3.decode(bytes.subarray(0, lineStart)),
1482
+ bodyOffset: nextPos
1483
+ };
1484
+ lineStart = nextPos;
1485
+ pos = nextPos;
1486
+ continue;
1487
+ }
1488
+ pos++;
1489
+ }
1490
+ if (bytes.byteLength <= maxHeaderScan) {
1491
+ if (textDecoder$3.decode(bytes.subarray(lineStart)).trim() === "end_header") return {
1492
+ headerText: textDecoder$3.decode(bytes.subarray(0, lineStart)),
1493
+ bodyOffset: bytes.byteLength
1494
+ };
1495
+ }
1496
+ throw new Error("Invalid PLY file: missing end_header marker");
1497
+ }
1498
+ function parseHeader(bytes) {
1499
+ const { headerText, bodyOffset } = findHeaderEnd(bytes);
1500
+ const lines = headerText.split(/\r?\n/);
1501
+ let idx = 0;
1502
+ while (idx < lines.length && lines[idx].trim() === "") idx++;
1503
+ if (idx >= lines.length || lines[idx].trim() !== "ply") throw new Error("Invalid PLY file: missing leading 'ply' magic line");
1504
+ idx++;
1505
+ let format = null;
1506
+ const elements = [];
1507
+ let currentElement = null;
1508
+ for (; idx < lines.length; idx++) {
1509
+ const trimmed = lines[idx].trim();
1510
+ if (trimmed === "") continue;
1511
+ const tokens = trimmed.split(/\s+/);
1512
+ const kw = tokens[0];
1513
+ if (kw === "comment" || kw === "obj_info") continue;
1514
+ if (kw === "format") {
1515
+ if (tokens.length < 3) throw new Error(`Invalid PLY format line: "${trimmed}"`);
1516
+ if (tokens[1] !== "ascii" && tokens[1] !== "binary_little_endian" && tokens[1] !== "binary_big_endian") throw new Error(`Unsupported PLY format "${tokens[1]}"`);
1517
+ if (tokens[2] !== "1.0") throw new Error(`Unsupported PLY format version "${tokens[2]}"`);
1518
+ format = tokens[1];
1519
+ continue;
1520
+ }
1521
+ if (kw === "element") {
1522
+ if (tokens.length !== 3) throw new Error(`Invalid PLY element line: "${trimmed}"`);
1523
+ const count = Number(tokens[2]);
1524
+ if (!Number.isInteger(count) || count < 0) throw new Error(`Invalid PLY element count "${tokens[2]}" for ${tokens[1]}`);
1525
+ currentElement = {
1526
+ name: tokens[1],
1527
+ count,
1528
+ properties: []
1529
+ };
1530
+ elements.push(currentElement);
1531
+ continue;
1532
+ }
1533
+ if (kw === "property") {
1534
+ if (!currentElement) throw new Error(`Invalid PLY property outside element: "${trimmed}"`);
1535
+ if (tokens[1] === "list") {
1536
+ if (tokens.length !== 5) throw new Error(`Invalid PLY list property: "${trimmed}"`);
1537
+ const ct = normalizeScalarType(tokens[2]);
1538
+ const it = normalizeScalarType(tokens[3]);
1539
+ currentElement.properties.push({
1540
+ kind: "list",
1541
+ name: tokens[4],
1542
+ countType: ct.type,
1543
+ countBytes: ct.bytes,
1544
+ itemType: it.type,
1545
+ itemBytes: it.bytes
1546
+ });
1547
+ } else {
1548
+ if (tokens.length !== 3) throw new Error(`Invalid PLY scalar property: "${trimmed}"`);
1549
+ const st = normalizeScalarType(tokens[1]);
1550
+ currentElement.properties.push({
1551
+ kind: "scalar",
1552
+ name: tokens[2],
1553
+ type: st.type,
1554
+ bytes: st.bytes
1555
+ });
1556
+ }
1557
+ continue;
1558
+ }
1559
+ throw new Error(`Unknown PLY header directive "${kw}"`);
1560
+ }
1561
+ if (format === null) throw new Error("Invalid PLY header: missing 'format' line");
1562
+ return {
1563
+ format,
1564
+ elements,
1565
+ bodyOffset
1566
+ };
1567
+ }
1568
+ function analyzeVertexProperties(props) {
1569
+ const indexOfScalar = (...names) => {
1570
+ for (const candidate of names) for (let i = 0; i < props.length; i++) if (props[i].kind === "scalar" && props[i].name === candidate) return i;
1571
+ return -1;
1572
+ };
1573
+ const xIdx = indexOfScalar("x");
1574
+ const yIdx = indexOfScalar("y");
1575
+ const zIdx = indexOfScalar("z");
1576
+ if (xIdx < 0 || yIdx < 0 || zIdx < 0) throw new Error("PLY vertex element must define scalar properties x, y, and z");
1577
+ const nxIdx = indexOfScalar("nx");
1578
+ const nyIdx = indexOfScalar("ny");
1579
+ const nzIdx = indexOfScalar("nz");
1580
+ const hasNormals = nxIdx >= 0 && nyIdx >= 0 && nzIdx >= 0;
1581
+ let uIdx = indexOfScalar("u");
1582
+ let vIdx = indexOfScalar("v");
1583
+ if (uIdx < 0 || vIdx < 0) {
1584
+ uIdx = indexOfScalar("s");
1585
+ vIdx = indexOfScalar("t");
1586
+ }
1587
+ if (uIdx < 0 || vIdx < 0) {
1588
+ uIdx = indexOfScalar("texture_u");
1589
+ vIdx = indexOfScalar("texture_v");
1590
+ }
1591
+ const hasUvs = uIdx >= 0 && vIdx >= 0;
1592
+ const rIdx = indexOfScalar("red", "r");
1593
+ const gIdx = indexOfScalar("green", "g");
1594
+ const bIdx = indexOfScalar("blue", "b");
1595
+ const aIdx = indexOfScalar("alpha", "a");
1596
+ const hasColors = rIdx >= 0 && gIdx >= 0 && bIdx >= 0;
1597
+ return {
1598
+ xIdx,
1599
+ yIdx,
1600
+ zIdx,
1601
+ nxIdx,
1602
+ nyIdx,
1603
+ nzIdx,
1604
+ uIdx,
1605
+ vIdx,
1606
+ rIdx,
1607
+ gIdx,
1608
+ bIdx,
1609
+ aIdx,
1610
+ hasNormals,
1611
+ hasUvs,
1612
+ hasColors,
1613
+ hasAlpha: hasColors && aIdx >= 0
1614
+ };
1615
+ }
1616
+ function findFaceVertexIndicesProp(props) {
1617
+ for (let i = 0; i < props.length; i++) {
1618
+ const p = props[i];
1619
+ if (p.kind === "list" && (p.name === "vertex_indices" || p.name === "vertex_index")) return i;
1620
+ }
1621
+ return -1;
1622
+ }
1623
+ function checkVertexFinite(vIdx, x, y, z) {
1624
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) throw new Error(`Invalid PLY vertex ${vIdx}: position contains non-finite coordinate`);
1625
+ }
1626
+ function checkNormalFinite(vIdx, nx, ny, nz) {
1627
+ if (!Number.isFinite(nx) || !Number.isFinite(ny) || !Number.isFinite(nz)) throw new Error(`Invalid PLY vertex ${vIdx}: normal contains non-finite value`);
1628
+ }
1629
+ function checkUvFinite(vIdx, u, v) {
1630
+ if (!Number.isFinite(u) || !Number.isFinite(v)) throw new Error(`Invalid PLY vertex ${vIdx}: UV contains non-finite value`);
1631
+ }
1632
+ function parseAsciiBody(bodyBytes, elements, signal) {
1633
+ const body = textDecoder$3.decode(bodyBytes);
1634
+ const len = body.length;
1635
+ let pos = 0;
1636
+ const readLineTokens = (elementName, rowIdx) => {
1637
+ while (pos < len) {
1638
+ let lineEnd = body.indexOf("\n", pos);
1639
+ if (lineEnd < 0) lineEnd = len;
1640
+ const line = body.slice(pos, lineEnd).trim();
1641
+ pos = lineEnd < len ? lineEnd + 1 : len;
1642
+ if (line === "") continue;
1643
+ return line.split(/\s+/);
1644
+ }
1645
+ throw new Error(`PLY body ends early while reading ${elementName} row ${rowIdx}`);
1646
+ };
1647
+ let positions = /* @__PURE__ */ new Float64Array(0);
1648
+ let normals = null;
1649
+ let uvs = null;
1650
+ let colors = null;
1651
+ const indicesList = [];
1652
+ let vertexCount = 0;
1653
+ let hasVertexElement = false;
1654
+ for (let eIdx = 0; eIdx < elements.length; eIdx++) {
1655
+ const el = elements[eIdx];
1656
+ throwIfAborted$3(signal);
1657
+ if (el.name === "vertex") {
1658
+ hasVertexElement = true;
1659
+ vertexCount = el.count;
1660
+ const layout = analyzeVertexProperties(el.properties);
1661
+ positions = new Float64Array(vertexCount * 3);
1662
+ normals = layout.hasNormals ? new Float32Array(vertexCount * 3) : null;
1663
+ uvs = layout.hasUvs ? new Float32Array(vertexCount * 2) : null;
1664
+ colors = layout.hasColors ? new Uint8Array(vertexCount * 4) : null;
1665
+ const hasListProps = el.properties.some((p) => p.kind === "list");
1666
+ for (let v = 0; v < vertexCount; v++) {
1667
+ if ((v & 16383) === 0) throwIfAborted$3(signal);
1668
+ const toks = readLineTokens("vertex", v);
1669
+ let tokOffsets = null;
1670
+ if (hasListProps) {
1671
+ tokOffsets = new Array(el.properties.length);
1672
+ let cur = 0;
1673
+ for (let p = 0; p < el.properties.length; p++) {
1674
+ tokOffsets[p] = cur;
1675
+ if (el.properties[p].kind === "list") {
1676
+ if (cur >= toks.length) throw new Error(`PLY vertex ${v} line ends early`);
1677
+ const cnt = Number(toks[cur]);
1678
+ if (!Number.isInteger(cnt) || cnt < 0) throw new Error(`Invalid list length in PLY vertex ${v}`);
1679
+ cur += 1 + cnt;
1680
+ } else cur += 1;
1681
+ }
1682
+ if (cur > toks.length) throw new Error(`PLY vertex ${v} line ends early`);
1683
+ } else if (toks.length < el.properties.length) throw new Error(`PLY vertex ${v} has ${toks.length} values, expected at least ${el.properties.length}`);
1684
+ const valAt = (propIdx) => {
1685
+ const tIdx = tokOffsets ? tokOffsets[propIdx] : propIdx;
1686
+ return Number(toks[tIdx]);
1687
+ };
1688
+ const x = valAt(layout.xIdx);
1689
+ const y = valAt(layout.yIdx);
1690
+ const z = valAt(layout.zIdx);
1691
+ checkVertexFinite(v, x, y, z);
1692
+ positions[v * 3] = x;
1693
+ positions[v * 3 + 1] = y;
1694
+ positions[v * 3 + 2] = z;
1695
+ if (normals !== null) {
1696
+ const nx = valAt(layout.nxIdx);
1697
+ const ny = valAt(layout.nyIdx);
1698
+ const nz = valAt(layout.nzIdx);
1699
+ checkNormalFinite(v, nx, ny, nz);
1700
+ normals[v * 3] = nx;
1701
+ normals[v * 3 + 1] = ny;
1702
+ normals[v * 3 + 2] = nz;
1703
+ }
1704
+ if (uvs !== null) {
1705
+ const uCoord = valAt(layout.uIdx);
1706
+ const vCoord = valAt(layout.vIdx);
1707
+ checkUvFinite(v, uCoord, vCoord);
1708
+ uvs[v * 2] = uCoord;
1709
+ uvs[v * 2 + 1] = vCoord;
1710
+ }
1711
+ if (colors !== null) {
1712
+ const rProp = el.properties[layout.rIdx];
1713
+ const gProp = el.properties[layout.gIdx];
1714
+ const bProp = el.properties[layout.bIdx];
1715
+ colors[v * 4] = colorByteFromScalar(valAt(layout.rIdx), rProp.type);
1716
+ colors[v * 4 + 1] = colorByteFromScalar(valAt(layout.gIdx), gProp.type);
1717
+ colors[v * 4 + 2] = colorByteFromScalar(valAt(layout.bIdx), bProp.type);
1718
+ colors[v * 4 + 3] = layout.hasAlpha ? colorByteFromScalar(valAt(layout.aIdx), el.properties[layout.aIdx].type) : 255;
1719
+ }
1720
+ }
1721
+ continue;
1722
+ }
1723
+ if (el.name === "face") {
1724
+ const listPropIdx = findFaceVertexIndicesProp(el.properties);
1725
+ if (el.count > 0 && listPropIdx < 0) throw new Error("PLY face element is missing 'vertex_indices' or 'vertex_index' list property");
1726
+ for (let f = 0; f < el.count; f++) {
1727
+ if ((f & 16383) === 0) throwIfAborted$3(signal);
1728
+ const toks = readLineTokens("face", f);
1729
+ let cur = 0;
1730
+ let faceVerts = null;
1731
+ for (let p = 0; p < el.properties.length; p++) if (el.properties[p].kind === "scalar") {
1732
+ if (cur >= toks.length) throw new Error(`PLY face ${f} ends early`);
1733
+ cur++;
1734
+ } else {
1735
+ if (cur >= toks.length) throw new Error(`PLY face ${f} ends early`);
1736
+ const k = Number(toks[cur++]);
1737
+ if (!Number.isInteger(k) || cur + k > toks.length) throw new Error(`PLY face ${f} list length (${k}) is truncated or invalid`);
1738
+ if (p === listPropIdx) {
1739
+ if (k < 3) throw new Error(`Invalid PLY face ${f}: vertex count ${k} is less than 3`);
1740
+ faceVerts = new Array(k);
1741
+ for (let j = 0; j < k; j++) {
1742
+ const vi = Number(toks[cur + j]);
1743
+ if (!Number.isInteger(vi) || vi < 0 || vi >= vertexCount) throw new Error(`Invalid PLY face ${f} index ${vi} is out of range (0..${vertexCount - 1})`);
1744
+ faceVerts[j] = vi;
1745
+ }
1746
+ }
1747
+ cur += k;
1748
+ }
1749
+ if (faceVerts !== null) {
1750
+ const v0 = faceVerts[0];
1751
+ for (let j = 1; j < faceVerts.length - 1; j++) indicesList.push(v0, faceVerts[j], faceVerts[j + 1]);
1752
+ }
1753
+ }
1754
+ continue;
1755
+ }
1756
+ for (let r = 0; r < el.count; r++) {
1757
+ if ((r & 16383) === 0) throwIfAborted$3(signal);
1758
+ readLineTokens(el.name, r);
1759
+ }
1760
+ }
1761
+ if (!hasVertexElement) throw new Error("PLY file does not declare a 'vertex' element");
1762
+ return {
1763
+ positions,
1764
+ normals,
1765
+ uvs,
1766
+ colors,
1767
+ indices: Uint32Array.from(indicesList)
1768
+ };
1769
+ }
1770
+ function parseBinaryBody(bytes, bodyOffset, elements, littleEndian, signal) {
1771
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1772
+ let at = bodyOffset;
1773
+ const totalLen = bytes.byteLength;
1774
+ let positions = /* @__PURE__ */ new Float64Array(0);
1775
+ let normals = null;
1776
+ let uvs = null;
1777
+ let colors = null;
1778
+ const indicesList = [];
1779
+ let vertexCount = 0;
1780
+ let hasVertexElement = false;
1781
+ const skipElement = (el) => {
1782
+ const fixedStride = el.properties.every((p) => p.kind === "scalar") ? el.properties.reduce((acc, p) => acc + p.bytes, 0) : -1;
1783
+ if (fixedStride >= 0) {
1784
+ const needed = el.count * fixedStride;
1785
+ if (at + needed > totalLen) throw new Error(`PLY binary payload ends early in element "${el.name}"`);
1786
+ at += needed;
1787
+ return;
1788
+ }
1789
+ for (let r = 0; r < el.count; r++) {
1790
+ if ((r & 16383) === 0) throwIfAborted$3(signal);
1791
+ for (let p = 0; p < el.properties.length; p++) {
1792
+ const prop = el.properties[p];
1793
+ if (prop.kind === "scalar") {
1794
+ if (at + prop.bytes > totalLen) throw new Error(`PLY binary payload ends early in "${el.name}"`);
1795
+ at += prop.bytes;
1796
+ } else {
1797
+ if (at + prop.countBytes > totalLen) throw new Error(`PLY binary payload ends early in "${el.name}"`);
1798
+ const k = readScalar(view, at, prop.countType, littleEndian);
1799
+ at += prop.countBytes;
1800
+ if (!Number.isInteger(k) || k < 0 || at + k * prop.itemBytes > totalLen) throw new Error(`PLY binary list ends early or invalid length in "${el.name}"`);
1801
+ at += k * prop.itemBytes;
1802
+ }
1803
+ }
1804
+ }
1805
+ };
1806
+ for (let eIdx = 0; eIdx < elements.length; eIdx++) {
1807
+ const el = elements[eIdx];
1808
+ throwIfAborted$3(signal);
1809
+ if (el.name === "vertex") {
1810
+ hasVertexElement = true;
1811
+ vertexCount = el.count;
1812
+ const layout = analyzeVertexProperties(el.properties);
1813
+ positions = new Float64Array(vertexCount * 3);
1814
+ normals = layout.hasNormals ? new Float32Array(vertexCount * 3) : null;
1815
+ uvs = layout.hasUvs ? new Float32Array(vertexCount * 2) : null;
1816
+ colors = layout.hasColors ? new Uint8Array(vertexCount * 4) : null;
1817
+ if (el.properties.every((p) => p.kind === "scalar")) {
1818
+ const propOffsets = new Int32Array(el.properties.length);
1819
+ const propTypes = [];
1820
+ let stride = 0;
1821
+ for (let p = 0; p < el.properties.length; p++) {
1822
+ const sp = el.properties[p];
1823
+ propOffsets[p] = stride;
1824
+ propTypes.push(sp.type);
1825
+ stride += sp.bytes;
1826
+ }
1827
+ if (at + vertexCount * stride > totalLen) throw new Error(`PLY binary vertex section ends early (need ${vertexCount * stride} bytes, have ${totalLen - at})`);
1828
+ for (let v = 0; v < vertexCount; v++) {
1829
+ if ((v & 16383) === 0) throwIfAborted$3(signal);
1830
+ const x = readScalar(view, at + propOffsets[layout.xIdx], propTypes[layout.xIdx], littleEndian);
1831
+ const y = readScalar(view, at + propOffsets[layout.yIdx], propTypes[layout.yIdx], littleEndian);
1832
+ const z = readScalar(view, at + propOffsets[layout.zIdx], propTypes[layout.zIdx], littleEndian);
1833
+ checkVertexFinite(v, x, y, z);
1834
+ positions[v * 3] = x;
1835
+ positions[v * 3 + 1] = y;
1836
+ positions[v * 3 + 2] = z;
1837
+ if (normals !== null) {
1838
+ const nx = readScalar(view, at + propOffsets[layout.nxIdx], propTypes[layout.nxIdx], littleEndian);
1839
+ const ny = readScalar(view, at + propOffsets[layout.nyIdx], propTypes[layout.nyIdx], littleEndian);
1840
+ const nz = readScalar(view, at + propOffsets[layout.nzIdx], propTypes[layout.nzIdx], littleEndian);
1841
+ checkNormalFinite(v, nx, ny, nz);
1842
+ normals[v * 3] = nx;
1843
+ normals[v * 3 + 1] = ny;
1844
+ normals[v * 3 + 2] = nz;
1845
+ }
1846
+ if (uvs !== null) {
1847
+ const uCoord = readScalar(view, at + propOffsets[layout.uIdx], propTypes[layout.uIdx], littleEndian);
1848
+ const vCoord = readScalar(view, at + propOffsets[layout.vIdx], propTypes[layout.vIdx], littleEndian);
1849
+ checkUvFinite(v, uCoord, vCoord);
1850
+ uvs[v * 2] = uCoord;
1851
+ uvs[v * 2 + 1] = vCoord;
1852
+ }
1853
+ if (colors !== null) {
1854
+ const rT = propTypes[layout.rIdx];
1855
+ const gT = propTypes[layout.gIdx];
1856
+ const bT = propTypes[layout.bIdx];
1857
+ colors[v * 4] = colorByteFromScalar(readScalar(view, at + propOffsets[layout.rIdx], rT, littleEndian), rT);
1858
+ colors[v * 4 + 1] = colorByteFromScalar(readScalar(view, at + propOffsets[layout.gIdx], gT, littleEndian), gT);
1859
+ colors[v * 4 + 2] = colorByteFromScalar(readScalar(view, at + propOffsets[layout.bIdx], bT, littleEndian), bT);
1860
+ colors[v * 4 + 3] = layout.hasAlpha ? colorByteFromScalar(readScalar(view, at + propOffsets[layout.aIdx], propTypes[layout.aIdx], littleEndian), propTypes[layout.aIdx]) : 255;
1861
+ }
1862
+ at += stride;
1863
+ }
1864
+ } else {
1865
+ const rowValues = new Float64Array(el.properties.length);
1866
+ for (let v = 0; v < vertexCount; v++) {
1867
+ if ((v & 16383) === 0) throwIfAborted$3(signal);
1868
+ for (let p = 0; p < el.properties.length; p++) {
1869
+ const prop = el.properties[p];
1870
+ if (prop.kind === "scalar") {
1871
+ if (at + prop.bytes > totalLen) throw new Error("PLY binary vertex section ends early");
1872
+ rowValues[p] = readScalar(view, at, prop.type, littleEndian);
1873
+ at += prop.bytes;
1874
+ } else {
1875
+ if (at + prop.countBytes > totalLen) throw new Error("PLY binary vertex list count ends early");
1876
+ const k = readScalar(view, at, prop.countType, littleEndian);
1877
+ at += prop.countBytes;
1878
+ if (!Number.isInteger(k) || k < 0 || at + k * prop.itemBytes > totalLen) throw new Error("PLY binary vertex list payload ends early");
1879
+ at += k * prop.itemBytes;
1880
+ }
1881
+ }
1882
+ const x = rowValues[layout.xIdx];
1883
+ const y = rowValues[layout.yIdx];
1884
+ const z = rowValues[layout.zIdx];
1885
+ checkVertexFinite(v, x, y, z);
1886
+ positions[v * 3] = x;
1887
+ positions[v * 3 + 1] = y;
1888
+ positions[v * 3 + 2] = z;
1889
+ if (normals !== null) {
1890
+ const nx = rowValues[layout.nxIdx];
1891
+ const ny = rowValues[layout.nyIdx];
1892
+ const nz = rowValues[layout.nzIdx];
1893
+ checkNormalFinite(v, nx, ny, nz);
1894
+ normals[v * 3] = nx;
1895
+ normals[v * 3 + 1] = ny;
1896
+ normals[v * 3 + 2] = nz;
1897
+ }
1898
+ if (uvs !== null) {
1899
+ const uCoord = rowValues[layout.uIdx];
1900
+ const vCoord = rowValues[layout.vIdx];
1901
+ checkUvFinite(v, uCoord, vCoord);
1902
+ uvs[v * 2] = uCoord;
1903
+ uvs[v * 2 + 1] = vCoord;
1904
+ }
1905
+ if (colors !== null) {
1906
+ colors[v * 4] = colorByteFromScalar(rowValues[layout.rIdx], el.properties[layout.rIdx].type);
1907
+ colors[v * 4 + 1] = colorByteFromScalar(rowValues[layout.gIdx], el.properties[layout.gIdx].type);
1908
+ colors[v * 4 + 2] = colorByteFromScalar(rowValues[layout.bIdx], el.properties[layout.bIdx].type);
1909
+ colors[v * 4 + 3] = layout.hasAlpha ? colorByteFromScalar(rowValues[layout.aIdx], el.properties[layout.aIdx].type) : 255;
1910
+ }
1911
+ }
1912
+ }
1913
+ continue;
1914
+ }
1915
+ if (el.name === "face") {
1916
+ const listPropIdx = findFaceVertexIndicesProp(el.properties);
1917
+ if (el.count > 0 && listPropIdx < 0) throw new Error("PLY face element is missing 'vertex_indices' or 'vertex_index' list property");
1918
+ for (let f = 0; f < el.count; f++) {
1919
+ if ((f & 16383) === 0) throwIfAborted$3(signal);
1920
+ for (let p = 0; p < el.properties.length; p++) {
1921
+ const prop = el.properties[p];
1922
+ if (prop.kind === "scalar") {
1923
+ if (at + prop.bytes > totalLen) throw new Error("PLY binary face section ends early");
1924
+ at += prop.bytes;
1925
+ } else {
1926
+ if (at + prop.countBytes > totalLen) throw new Error("PLY binary face count ends early");
1927
+ const k = readScalar(view, at, prop.countType, littleEndian);
1928
+ at += prop.countBytes;
1929
+ if (!Number.isInteger(k) || k < 0) throw new Error(`Invalid PLY face ${f} list count ${k}`);
1930
+ if (at + k * prop.itemBytes > totalLen) throw new Error(`PLY binary face ${f} ends early (declared ${k} items, ${totalLen - at} bytes remaining)`);
1931
+ if (p === listPropIdx) {
1932
+ if (k < 3) throw new Error(`Invalid PLY face ${f}: vertex count ${k} is less than 3`);
1933
+ const v0 = readScalar(view, at, prop.itemType, littleEndian);
1934
+ if (!Number.isInteger(v0) || v0 < 0 || v0 >= vertexCount) throw new Error(`Invalid PLY face ${f} index ${v0} is out of range (0..${vertexCount - 1})`);
1935
+ let prev = readScalar(view, at + prop.itemBytes, prop.itemType, littleEndian);
1936
+ if (!Number.isInteger(prev) || prev < 0 || prev >= vertexCount) throw new Error(`Invalid PLY face ${f} index ${prev} is out of range (0..${vertexCount - 1})`);
1937
+ for (let j = 2; j < k; j++) {
1938
+ const curr = readScalar(view, at + j * prop.itemBytes, prop.itemType, littleEndian);
1939
+ if (!Number.isInteger(curr) || curr < 0 || curr >= vertexCount) throw new Error(`Invalid PLY face ${f} index ${curr} is out of range (0..${vertexCount - 1})`);
1940
+ indicesList.push(v0, prev, curr);
1941
+ prev = curr;
1942
+ }
1943
+ }
1944
+ at += k * prop.itemBytes;
1945
+ }
1946
+ }
1947
+ }
1948
+ continue;
1949
+ }
1950
+ skipElement(el);
1951
+ }
1952
+ if (!hasVertexElement) throw new Error("PLY file does not declare a 'vertex' element");
1953
+ return {
1954
+ positions,
1955
+ normals,
1956
+ uvs,
1957
+ colors,
1958
+ indices: Uint32Array.from(indicesList)
1959
+ };
1960
+ }
1961
+ /**
1962
+ * Parse an ASCII or binary (little- or big-endian) PLY file into an {@link ImportedMesh}.
1963
+ */
1964
+ function importPLY(bytes, options) {
1965
+ throwIfAborted$3(options?.signal);
1966
+ const u8 = toUint8$2(bytes);
1967
+ const maxBytes = options?.maxFileBytes ?? DEFAULT_MAX_BYTES$2;
1968
+ if (u8.byteLength > maxBytes) throw new Error(`PLY file size (${u8.byteLength} bytes) exceeds limit of ${maxBytes} bytes`);
1969
+ const header = parseHeader(u8);
1970
+ const parsed = header.format === "ascii" ? parseAsciiBody(u8.subarray(header.bodyOffset), header.elements, options?.signal) : parseBinaryBody(u8, header.bodyOffset, header.elements, header.format === "binary_little_endian", options?.signal);
1971
+ return {
1972
+ name: options?.name ?? "mesh",
1973
+ positions: parsed.positions,
1974
+ indices: parsed.indices,
1975
+ placement: new Float64Array([
1976
+ 1,
1977
+ 0,
1978
+ 0,
1979
+ 0,
1980
+ 0,
1981
+ 1,
1982
+ 0,
1983
+ 0,
1984
+ 0,
1985
+ 0,
1986
+ 1,
1987
+ 0,
1988
+ 0,
1989
+ 0,
1990
+ 0,
1991
+ 1
1992
+ ]),
1993
+ colors: parsed.colors,
1994
+ uvs: parsed.uvs,
1995
+ normals: parsed.normals
1996
+ };
1997
+ }
1998
+ // src/io/stl.ts
1999
+ const DEFAULT_MAX_BYTES$1 = 536870912;
2000
+ const textDecoder$2 = new TextDecoder("utf-8");
2001
+ function toUint8$1(bytes) {
2002
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
2003
+ }
2004
+ function throwIfAborted$2(signal) {
2005
+ if (signal?.aborted) {
2006
+ const reason = signal.reason;
2007
+ if (reason instanceof Error) throw reason;
2008
+ throw new DOMException("The operation was aborted.", "AbortError");
2009
+ }
2010
+ }
2011
+ function isProbablyAsciiStl(bytes) {
2012
+ const probeLen = Math.min(bytes.byteLength, 512);
2013
+ let i = 0;
2014
+ if (probeLen >= 3 && bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) i = 3;
2015
+ while (i < probeLen && (bytes[i] === 32 || bytes[i] === 9 || bytes[i] === 10 || bytes[i] === 13)) i++;
2016
+ if (i + 5 > probeLen) return false;
2017
+ if (bytes[i] !== 115 || bytes[i + 1] !== 111 || bytes[i + 2] !== 108 || bytes[i + 3] !== 105 || bytes[i + 4] !== 100) return false;
2018
+ if (i + 5 < probeLen) {
2019
+ const after = bytes[i + 5];
2020
+ if (after !== 32 && after !== 9 && after !== 10 && after !== 13) return false;
2021
+ }
2022
+ for (let k = i; k < probeLen; k++) {
2023
+ const c = bytes[k];
2024
+ if (c === 0 || c < 32 && c !== 9 && c !== 10 && c !== 13) return false;
2025
+ }
2026
+ return true;
2027
+ }
2028
+ var VertexWelder = class {
2029
+ positions;
2030
+ count = 0;
2031
+ head;
2032
+ next;
2033
+ mask;
2034
+ scratchBuf = /* @__PURE__ */ new ArrayBuffer(12);
2035
+ scratchF32 = new Float32Array(this.scratchBuf);
2036
+ scratchI32 = new Int32Array(this.scratchBuf);
2037
+ constructor(maxVertices) {
2038
+ this.positions = new Float64Array(maxVertices * 3);
2039
+ let cap = 16;
2040
+ const target = Math.max(16, maxVertices);
2041
+ while (cap < target) cap <<= 1;
2042
+ this.mask = cap - 1;
2043
+ this.head = new Int32Array(cap).fill(-1);
2044
+ this.next = new Int32Array(maxVertices).fill(-1);
2045
+ }
2046
+ intern(xRaw, yRaw, zRaw) {
2047
+ const x = xRaw === 0 ? 0 : xRaw;
2048
+ const y = yRaw === 0 ? 0 : yRaw;
2049
+ const z = zRaw === 0 ? 0 : zRaw;
2050
+ this.scratchF32[0] = x;
2051
+ this.scratchF32[1] = y;
2052
+ this.scratchF32[2] = z;
2053
+ const h = (Math.imul(this.scratchI32[0], 73856093) ^ Math.imul(this.scratchI32[1], 19349663) ^ Math.imul(this.scratchI32[2], 83492791)) >>> 0 & this.mask;
2054
+ let idx = this.head[h];
2055
+ while (idx !== -1) {
2056
+ const base = idx * 3;
2057
+ if (this.positions[base] === x && this.positions[base + 1] === y && this.positions[base + 2] === z) return idx;
2058
+ idx = this.next[idx];
2059
+ }
2060
+ const newIdx = this.count++;
2061
+ const base = newIdx * 3;
2062
+ this.positions[base] = x;
2063
+ this.positions[base + 1] = y;
2064
+ this.positions[base + 2] = z;
2065
+ this.next[newIdx] = this.head[h];
2066
+ this.head[h] = newIdx;
2067
+ return newIdx;
2068
+ }
2069
+ finish() {
2070
+ return this.positions.subarray(0, this.count * 3).slice();
2071
+ }
2072
+ };
2073
+ function parseBinaryStl(bytes, view, triCount, options) {
2074
+ const signal = options?.signal;
2075
+ const dedup = options?.deduplicateVertices === true;
2076
+ const maxVerts = triCount * 3;
2077
+ const indices = new Uint32Array(maxVerts);
2078
+ if (!dedup) {
2079
+ const positions = new Float64Array(maxVerts * 3);
2080
+ let offset = 84;
2081
+ for (let t = 0; t < triCount; t++) {
2082
+ if ((t & 16383) === 0) throwIfAborted$2(signal);
2083
+ for (let v = 0; v < 3; v++) {
2084
+ const vo = offset + 12 + v * 12;
2085
+ const x = view.getFloat32(vo, true);
2086
+ const y = view.getFloat32(vo + 4, true);
2087
+ const z = view.getFloat32(vo + 8, true);
2088
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) throw new Error(`Invalid binary STL vertex at triangle ${t}: non-finite coordinate`);
2089
+ const vi = t * 3 + v;
2090
+ positions[vi * 3] = x;
2091
+ positions[vi * 3 + 1] = y;
2092
+ positions[vi * 3 + 2] = z;
2093
+ indices[vi] = vi;
2094
+ }
2095
+ offset += 50;
2096
+ }
2097
+ return {
2098
+ name: options?.name ?? "mesh",
2099
+ positions,
2100
+ indices,
2101
+ placement: new Float64Array([
2102
+ 1,
2103
+ 0,
2104
+ 0,
2105
+ 0,
2106
+ 0,
2107
+ 1,
2108
+ 0,
2109
+ 0,
2110
+ 0,
2111
+ 0,
2112
+ 1,
2113
+ 0,
2114
+ 0,
2115
+ 0,
2116
+ 0,
2117
+ 1
2118
+ ]),
2119
+ colors: null,
2120
+ uvs: null
2121
+ };
2122
+ }
2123
+ const welder = new VertexWelder(maxVerts);
2124
+ let offset = 84;
2125
+ for (let t = 0; t < triCount; t++) {
2126
+ if ((t & 16383) === 0) throwIfAborted$2(signal);
2127
+ for (let v = 0; v < 3; v++) {
2128
+ const vo = offset + 12 + v * 12;
2129
+ const x = view.getFloat32(vo, true);
2130
+ const y = view.getFloat32(vo + 4, true);
2131
+ const z = view.getFloat32(vo + 8, true);
2132
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) throw new Error(`Invalid binary STL vertex at triangle ${t}: non-finite coordinate`);
2133
+ indices[t * 3 + v] = welder.intern(x, y, z);
2134
+ }
2135
+ offset += 50;
2136
+ }
2137
+ return {
2138
+ name: options?.name ?? "mesh",
2139
+ positions: welder.finish(),
2140
+ indices,
2141
+ placement: new Float64Array([
2142
+ 1,
2143
+ 0,
2144
+ 0,
2145
+ 0,
2146
+ 0,
2147
+ 1,
2148
+ 0,
2149
+ 0,
2150
+ 0,
2151
+ 0,
2152
+ 1,
2153
+ 0,
2154
+ 0,
2155
+ 0,
2156
+ 0,
2157
+ 1
2158
+ ]),
2159
+ colors: null,
2160
+ uvs: null
2161
+ };
2162
+ }
2163
+ function parseAsciiStl(bytes, options) {
2164
+ const signal = options?.signal;
2165
+ let text = textDecoder$2.decode(bytes);
2166
+ if (text.charCodeAt(0) === 65279) text = text.slice(1);
2167
+ let solidName = "mesh";
2168
+ const coords = [];
2169
+ let len = text.length;
2170
+ let pos = 0;
2171
+ let sawSolid = false;
2172
+ let sawEndSolid = false;
2173
+ let iter = 0;
2174
+ let facetVertCount = 0;
2175
+ let inFacet = false;
2176
+ let inLoop = false;
2177
+ while (pos < len) {
2178
+ if ((iter++ & 16383) === 0) throwIfAborted$2(signal);
2179
+ let nl = text.indexOf("\n", pos);
2180
+ if (nl < 0) nl = len;
2181
+ const line = text.slice(pos, nl).trim();
2182
+ pos = nl < len ? nl + 1 : len;
2183
+ if (line === "") continue;
2184
+ if (!sawSolid) {
2185
+ if (line.startsWith("solid") && (line.length === 5 || line.charCodeAt(5) <= 32)) {
2186
+ sawSolid = true;
2187
+ const n = line.slice(5).trim();
2188
+ if (n.length > 0) solidName = n;
2189
+ continue;
2190
+ }
2191
+ throw new Error("Invalid ASCII STL: missing leading 'solid' header");
2192
+ }
2193
+ if (line.startsWith("vertex") && line.length > 6 && line.charCodeAt(6) <= 32) {
2194
+ if (!inLoop) throw new Error("Invalid ASCII STL: 'vertex' outside 'outer loop'");
2195
+ const parts = line.slice(6).trim().split(/\s+/);
2196
+ if (parts.length < 3) throw new Error(`Invalid ASCII STL vertex line: "${line}"`);
2197
+ const x = Number(parts[0]);
2198
+ const y = Number(parts[1]);
2199
+ const z = Number(parts[2]);
2200
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) throw new Error(`Invalid ASCII STL vertex coordinates: "${line}"`);
2201
+ coords.push(x, y, z);
2202
+ facetVertCount++;
2203
+ continue;
2204
+ }
2205
+ if (line.startsWith("facet") && (line.length === 5 || line.charCodeAt(5) <= 32)) {
2206
+ inFacet = true;
2207
+ facetVertCount = 0;
2208
+ continue;
2209
+ }
2210
+ if (line.startsWith("outer loop") || line === "outer") {
2211
+ inLoop = true;
2212
+ continue;
2213
+ }
2214
+ if (line === "endloop") {
2215
+ inLoop = false;
2216
+ continue;
2217
+ }
2218
+ if (line === "endfacet") {
2219
+ if (!inFacet || facetVertCount !== 3) throw new Error(`Invalid ASCII STL facet: expected 3 vertices, got ${facetVertCount}`);
2220
+ inFacet = false;
2221
+ inLoop = false;
2222
+ continue;
2223
+ }
2224
+ if (line.startsWith("endsolid")) {
2225
+ sawEndSolid = true;
2226
+ break;
2227
+ }
2228
+ }
2229
+ if (!sawSolid) throw new Error("Invalid ASCII STL: missing 'solid' header");
2230
+ if (inFacet || inLoop || !sawEndSolid) throw new Error("Invalid ASCII STL: file ends early before 'endsolid'");
2231
+ const rawVertCount = coords.length / 3;
2232
+ const triCount = rawVertCount / 3;
2233
+ const dedup = options?.deduplicateVertices === true;
2234
+ const meshName = options?.name ?? solidName;
2235
+ if (!dedup) {
2236
+ const positions = Float64Array.from(coords);
2237
+ const indices = new Uint32Array(rawVertCount);
2238
+ for (let i = 0; i < rawVertCount; i++) indices[i] = i;
2239
+ return {
2240
+ name: meshName,
2241
+ positions,
2242
+ indices,
2243
+ placement: new Float64Array([
2244
+ 1,
2245
+ 0,
2246
+ 0,
2247
+ 0,
2248
+ 0,
2249
+ 1,
2250
+ 0,
2251
+ 0,
2252
+ 0,
2253
+ 0,
2254
+ 1,
2255
+ 0,
2256
+ 0,
2257
+ 0,
2258
+ 0,
2259
+ 1
2260
+ ]),
2261
+ colors: null,
2262
+ uvs: null
2263
+ };
2264
+ }
2265
+ const welder = new VertexWelder(rawVertCount);
2266
+ const indices = new Uint32Array(triCount * 3);
2267
+ for (let i = 0; i < rawVertCount; i++) {
2268
+ if ((i & 16383) === 0) throwIfAborted$2(signal);
2269
+ indices[i] = welder.intern(coords[i * 3], coords[i * 3 + 1], coords[i * 3 + 2]);
2270
+ }
2271
+ return {
2272
+ name: meshName,
2273
+ positions: welder.finish(),
2274
+ indices,
2275
+ placement: new Float64Array([
2276
+ 1,
2277
+ 0,
2278
+ 0,
2279
+ 0,
2280
+ 0,
2281
+ 1,
2282
+ 0,
2283
+ 0,
2284
+ 0,
2285
+ 0,
2286
+ 1,
2287
+ 0,
2288
+ 0,
2289
+ 0,
2290
+ 0,
2291
+ 1
2292
+ ]),
2293
+ colors: null,
2294
+ uvs: null
2295
+ };
2296
+ }
2297
+ /**
2298
+ * Parse a binary or ASCII STL payload into an {@link ImportedMesh}.
2299
+ */
2300
+ function importSTL(bytes, options) {
2301
+ throwIfAborted$2(options?.signal);
2302
+ const u8 = toUint8$1(bytes);
2303
+ const maxBytes = options?.maxFileBytes ?? DEFAULT_MAX_BYTES$1;
2304
+ if (u8.byteLength > maxBytes) throw new Error(`STL file size (${u8.byteLength} bytes) exceeds limit of ${maxBytes} bytes`);
2305
+ if (u8.byteLength >= 84) {
2306
+ const view = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
2307
+ const triCount = view.getUint32(80, true);
2308
+ const expected = 84 + 50 * triCount;
2309
+ if (expected === u8.byteLength) return parseBinaryStl(u8, view, triCount, options);
2310
+ if (isProbablyAsciiStl(u8)) return parseAsciiStl(u8, options);
2311
+ throw new Error(`binary STL: the header says ${triCount} triangles (${expected} bytes), but the file has ${u8.byteLength} bytes`);
2312
+ }
2313
+ if (isProbablyAsciiStl(u8)) return parseAsciiStl(u8, options);
2314
+ throw new Error(`Invalid STL file: expected ASCII STL or at least 84-byte binary STL header (got ${u8.byteLength} bytes)`);
2315
+ }
2316
+ // src/io/obj.ts
2317
+ const DEFAULT_MAX_BYTES = 536870912;
2318
+ const textDecoder$1 = new TextDecoder("utf-8");
2319
+ function toUint8(bytes) {
2320
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
2321
+ }
2322
+ function throwIfAborted$1(signal) {
2323
+ if (signal?.aborted) {
2324
+ const reason = signal.reason;
2325
+ if (reason instanceof Error) throw reason;
2326
+ throw new DOMException("The operation was aborted.", "AbortError");
2327
+ }
2328
+ }
2329
+ function resolveObjIndex(rawStr, countSoFar, kind) {
2330
+ const n = Number(rawStr);
2331
+ if (!Number.isInteger(n)) throw new Error(`Invalid OBJ ${kind} index "${rawStr}"`);
2332
+ if (n === 0) throw new Error(`Invalid OBJ index "0" (OBJ indices are 1-based)`);
2333
+ if (kind === "vertex" && countSoFar === 0) throw new Error(`OBJ vertex index "${rawStr}" appears before the first vertex`);
2334
+ const resolved = n > 0 ? n - 1 : countSoFar + n;
2335
+ if (resolved < 0) throw new Error(`OBJ negative ${kind} index "${rawStr}" points before the first ${kind} (available ${countSoFar})`);
2336
+ if (resolved >= countSoFar) throw new Error(`OBJ ${kind} index "${rawStr}" is out of range (resolved ${resolved}, available ${countSoFar})`);
2337
+ return resolved;
2338
+ }
2339
+ function clampByte(n) {
2340
+ if (n <= 0) return 0;
2341
+ if (n >= 255) return 255;
2342
+ return Math.round(n);
2343
+ }
2344
+ /**
2345
+ * Parse a Wavefront OBJ file into one or more {@link ImportedMesh} records.
2346
+ */
2347
+ function importOBJ(bytes, options) {
2348
+ throwIfAborted$1(options?.signal);
2349
+ const u8 = toUint8(bytes);
2350
+ const maxBytes = options?.maxFileBytes ?? DEFAULT_MAX_BYTES;
2351
+ if (u8.byteLength > maxBytes) throw new Error(`OBJ file size (${u8.byteLength} bytes) exceeds limit of ${maxBytes} bytes`);
2352
+ let text = textDecoder$1.decode(u8);
2353
+ if (text.charCodeAt(0) === 65279) text = text.slice(1);
2354
+ const positions = [];
2355
+ const rawColors = [];
2356
+ const vertexHasColor = [];
2357
+ let maxColorVal = 0;
2358
+ let anyVertexHasColor = false;
2359
+ const uvs = [];
2360
+ const normals = [];
2361
+ const mergeGroups = options?.mergeGroups === true;
2362
+ const groups = [];
2363
+ let currentGroup = {
2364
+ name: options?.name ?? "mesh",
2365
+ triCorners: []
2366
+ };
2367
+ let hasExplicitName = false;
2368
+ const flushGroup = () => {
2369
+ if (currentGroup.triCorners.length > 0) groups.push(currentGroup);
2370
+ };
2371
+ const len = text.length;
2372
+ let pos = 0;
2373
+ let iter = 0;
2374
+ while (pos < len) {
2375
+ if ((iter++ & 16383) === 0) throwIfAborted$1(options?.signal);
2376
+ let line = "";
2377
+ while (pos < len) {
2378
+ let nl = text.indexOf("\n", pos);
2379
+ if (nl < 0) nl = len;
2380
+ let chunk = text.slice(pos, nl);
2381
+ if (chunk.endsWith("\r")) chunk = chunk.slice(0, -1);
2382
+ pos = nl < len ? nl + 1 : len;
2383
+ if (chunk.endsWith("\\")) line += chunk.slice(0, -1) + " ";
2384
+ else {
2385
+ line += chunk;
2386
+ break;
2387
+ }
2388
+ }
2389
+ const hashIdx = line.indexOf("#");
2390
+ const stripped = (hashIdx >= 0 ? line.slice(0, hashIdx) : line).trim();
2391
+ if (stripped === "") continue;
2392
+ const tokens = stripped.split(/\s+/);
2393
+ const cmd = tokens[0];
2394
+ if (cmd === "v") {
2395
+ if (tokens.length < 4) throw new Error(`Invalid OBJ vertex line: "${stripped}"`);
2396
+ const x = Number(tokens[1]);
2397
+ const y = Number(tokens[2]);
2398
+ const z = Number(tokens[3]);
2399
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) throw new Error(`Invalid OBJ vertex coordinates: "${stripped}"`);
2400
+ positions.push(x, y, z);
2401
+ if (tokens.length >= 7) {
2402
+ const r = Number(tokens[4]);
2403
+ const g = Number(tokens[5]);
2404
+ const b = Number(tokens[6]);
2405
+ const a = tokens.length >= 8 ? Number(tokens[7]) : NaN;
2406
+ if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || tokens.length >= 8 && !Number.isFinite(a)) throw new Error(`Invalid OBJ vertex color: "${stripped}"`);
2407
+ anyVertexHasColor = true;
2408
+ vertexHasColor.push(1);
2409
+ rawColors.push(r, g, b, tokens.length >= 8 ? a : NaN);
2410
+ if (r > maxColorVal) maxColorVal = r;
2411
+ if (g > maxColorVal) maxColorVal = g;
2412
+ if (b > maxColorVal) maxColorVal = b;
2413
+ if (Number.isFinite(a) && a > maxColorVal) maxColorVal = a;
2414
+ } else {
2415
+ vertexHasColor.push(0);
2416
+ rawColors.push(0, 0, 0, 0);
2417
+ }
2418
+ continue;
2419
+ }
2420
+ if (cmd === "vt") {
2421
+ if (tokens.length < 3) throw new Error(`Invalid OBJ texture coordinate line: "${stripped}"`);
2422
+ const u = Number(tokens[1]);
2423
+ const v = Number(tokens[2]);
2424
+ if (!Number.isFinite(u) || !Number.isFinite(v)) throw new Error(`Invalid OBJ texture coordinate: "${stripped}"`);
2425
+ uvs.push(u, v);
2426
+ continue;
2427
+ }
2428
+ if (cmd === "vn") {
2429
+ if (tokens.length < 4) throw new Error(`Invalid OBJ normal line: "${stripped}"`);
2430
+ const nx = Number(tokens[1]);
2431
+ const ny = Number(tokens[2]);
2432
+ const nz = Number(tokens[3]);
2433
+ if (!Number.isFinite(nx) || !Number.isFinite(ny) || !Number.isFinite(nz)) throw new Error(`Invalid OBJ normal values: "${stripped}"`);
2434
+ normals.push(nx, ny, nz);
2435
+ continue;
2436
+ }
2437
+ if (cmd === "f") {
2438
+ const faceVertsCount = tokens.length - 1;
2439
+ if (faceVertsCount < 3) throw new Error(`Invalid OBJ face with fewer than 3 vertices: "${stripped}"`);
2440
+ const vCount = positions.length / 3;
2441
+ const vtCount = uvs.length / 2;
2442
+ const vnCount = normals.length / 3;
2443
+ const corners = new Array(faceVertsCount);
2444
+ for (let i = 0; i < faceVertsCount; i++) {
2445
+ const tok = tokens[i + 1];
2446
+ const slash1 = tok.indexOf("/");
2447
+ if (slash1 < 0) corners[i] = {
2448
+ v: resolveObjIndex(tok, vCount, "vertex"),
2449
+ vt: -1,
2450
+ vn: -1
2451
+ };
2452
+ else {
2453
+ const vIdx = resolveObjIndex(tok.slice(0, slash1), vCount, "vertex");
2454
+ const slash2 = tok.indexOf("/", slash1 + 1);
2455
+ if (slash2 < 0) {
2456
+ const vtStr = tok.slice(slash1 + 1);
2457
+ const vtIdx = vtStr.length > 0 ? resolveObjIndex(vtStr, vtCount, "texcoord") : -1;
2458
+ corners[i] = {
2459
+ v: vIdx,
2460
+ vt: vtIdx,
2461
+ vn: -1
2462
+ };
2463
+ } else {
2464
+ const vtStr = tok.slice(slash1 + 1, slash2);
2465
+ const vnStr = tok.slice(slash2 + 1);
2466
+ if (tok.indexOf("/", slash2 + 1) >= 0) throw new Error(`Invalid OBJ face token "${tok}"`);
2467
+ const vtIdx = vtStr.length > 0 ? resolveObjIndex(vtStr, vtCount, "texcoord") : -1;
2468
+ const vnIdx = vnStr.length > 0 ? resolveObjIndex(vnStr, vnCount, "normal") : -1;
2469
+ corners[i] = {
2470
+ v: vIdx,
2471
+ vt: vtIdx,
2472
+ vn: vnIdx
2473
+ };
2474
+ }
2475
+ }
2476
+ }
2477
+ const c0 = corners[0];
2478
+ for (let i = 1; i < faceVertsCount - 1; i++) currentGroup.triCorners.push(c0, corners[i], corners[i + 1]);
2479
+ continue;
2480
+ }
2481
+ if (!mergeGroups && (cmd === "o" || cmd === "g")) {
2482
+ const nextName = stripped.slice(1).trim();
2483
+ if (currentGroup.triCorners.length > 0) {
2484
+ flushGroup();
2485
+ currentGroup = {
2486
+ name: nextName || options?.name || `mesh-${groups.length + 1}`,
2487
+ triCorners: []
2488
+ };
2489
+ hasExplicitName = nextName.length > 0;
2490
+ } else if (nextName.length > 0 && (!hasExplicitName || cmd === "o")) {
2491
+ currentGroup.name = nextName;
2492
+ hasExplicitName = true;
2493
+ }
2494
+ }
2495
+ }
2496
+ flushGroup();
2497
+ if (groups.length === 0) throw new Error("OBJ file contains no faces");
2498
+ let vertColorBytes = null;
2499
+ if (anyVertexHasColor) {
2500
+ const scale = maxColorVal > 1 ? 1 : 255;
2501
+ const totalV = positions.length / 3;
2502
+ vertColorBytes = new Uint8Array(totalV * 4);
2503
+ for (let v = 0; v < totalV; v++) if (vertexHasColor[v] !== 0) {
2504
+ const r = rawColors[v * 4];
2505
+ const g = rawColors[v * 4 + 1];
2506
+ const b = rawColors[v * 4 + 2];
2507
+ const aRaw = rawColors[v * 4 + 3];
2508
+ vertColorBytes[v * 4] = clampByte(r * scale);
2509
+ vertColorBytes[v * 4 + 1] = clampByte(g * scale);
2510
+ vertColorBytes[v * 4 + 2] = clampByte(b * scale);
2511
+ vertColorBytes[v * 4 + 3] = Number.isFinite(aRaw) ? clampByte(aRaw * scale) : 255;
2512
+ } else {
2513
+ vertColorBytes[v * 4] = 255;
2514
+ vertColorBytes[v * 4 + 1] = 255;
2515
+ vertColorBytes[v * 4 + 2] = 255;
2516
+ vertColorBytes[v * 4 + 3] = 255;
2517
+ }
2518
+ }
2519
+ const results = [];
2520
+ if (options?.positionsOnly === true) {
2521
+ const outPos = Float64Array.from(positions);
2522
+ const identity = new Float64Array([
2523
+ 1,
2524
+ 0,
2525
+ 0,
2526
+ 0,
2527
+ 0,
2528
+ 1,
2529
+ 0,
2530
+ 0,
2531
+ 0,
2532
+ 0,
2533
+ 1,
2534
+ 0,
2535
+ 0,
2536
+ 0,
2537
+ 0,
2538
+ 1
2539
+ ]);
2540
+ for (let gIdx = 0; gIdx < groups.length; gIdx++) {
2541
+ throwIfAborted$1(options?.signal);
2542
+ const group = groups[gIdx];
2543
+ const cornerCount = group.triCorners.length;
2544
+ const outIndices = new Uint32Array(cornerCount);
2545
+ for (let i = 0; i < cornerCount; i++) outIndices[i] = group.triCorners[i].v;
2546
+ results.push({
2547
+ name: group.name,
2548
+ positions: gIdx === 0 ? outPos : outPos.slice(),
2549
+ indices: outIndices,
2550
+ placement: identity.slice(),
2551
+ colors: null,
2552
+ uvs: null
2553
+ });
2554
+ }
2555
+ return results;
2556
+ }
2557
+ for (let gIdx = 0; gIdx < groups.length; gIdx++) {
2558
+ throwIfAborted$1(options?.signal);
2559
+ const group = groups[gIdx];
2560
+ const cornerCount = group.triCorners.length;
2561
+ const outIndices = new Uint32Array(cornerCount);
2562
+ let hasGroupUvs = false;
2563
+ let hasGroupNormals = false;
2564
+ let hasGroupColors = false;
2565
+ for (let i = 0; i < cornerCount; i++) {
2566
+ const c = group.triCorners[i];
2567
+ if (c.vt >= 0) hasGroupUvs = true;
2568
+ if (c.vn >= 0) hasGroupNormals = true;
2569
+ if (vertColorBytes !== null && vertexHasColor[c.v] !== 0) hasGroupColors = true;
2570
+ }
2571
+ const buckets = /* @__PURE__ */ new Map();
2572
+ const outVertCorners = [];
2573
+ for (let i = 0; i < cornerCount; i++) {
2574
+ const c = group.triCorners[i];
2575
+ const normVt = hasGroupUvs ? c.vt : -1;
2576
+ const normVn = hasGroupNormals ? c.vn : -1;
2577
+ let list = buckets.get(c.v);
2578
+ let found = -1;
2579
+ if (list) {
2580
+ for (let k = 0; k < list.length; k++) if (list[k].vt === normVt && list[k].vn === normVn) {
2581
+ found = list[k].outIdx;
2582
+ break;
2583
+ }
2584
+ } else {
2585
+ list = [];
2586
+ buckets.set(c.v, list);
2587
+ }
2588
+ if (found < 0) {
2589
+ found = outVertCorners.length;
2590
+ outVertCorners.push({
2591
+ v: c.v,
2592
+ vt: normVt,
2593
+ vn: normVn
2594
+ });
2595
+ list.push({
2596
+ vt: normVt,
2597
+ vn: normVn,
2598
+ outIdx: found
2599
+ });
2600
+ }
2601
+ outIndices[i] = found;
2602
+ }
2603
+ const vertCount = outVertCorners.length;
2604
+ const outPos = new Float64Array(vertCount * 3);
2605
+ const outUvs = hasGroupUvs ? new Float32Array(vertCount * 2) : null;
2606
+ const outNormals = hasGroupNormals ? new Float32Array(vertCount * 3) : null;
2607
+ const outColors = hasGroupColors && vertColorBytes !== null ? new Uint8Array(vertCount * 4) : null;
2608
+ for (let i = 0; i < vertCount; i++) {
2609
+ const c = outVertCorners[i];
2610
+ outPos[i * 3] = positions[c.v * 3];
2611
+ outPos[i * 3 + 1] = positions[c.v * 3 + 1];
2612
+ outPos[i * 3 + 2] = positions[c.v * 3 + 2];
2613
+ if (outUvs !== null) {
2614
+ if (c.vt >= 0) {
2615
+ outUvs[i * 2] = uvs[c.vt * 2];
2616
+ outUvs[i * 2 + 1] = uvs[c.vt * 2 + 1];
2617
+ }
2618
+ }
2619
+ if (outNormals !== null) {
2620
+ if (c.vn >= 0) {
2621
+ outNormals[i * 3] = normals[c.vn * 3];
2622
+ outNormals[i * 3 + 1] = normals[c.vn * 3 + 1];
2623
+ outNormals[i * 3 + 2] = normals[c.vn * 3 + 2];
2624
+ }
2625
+ }
2626
+ if (outColors !== null && vertColorBytes !== null) {
2627
+ outColors[i * 4] = vertColorBytes[c.v * 4];
2628
+ outColors[i * 4 + 1] = vertColorBytes[c.v * 4 + 1];
2629
+ outColors[i * 4 + 2] = vertColorBytes[c.v * 4 + 2];
2630
+ outColors[i * 4 + 3] = vertColorBytes[c.v * 4 + 3];
2631
+ }
2632
+ }
2633
+ results.push({
2634
+ name: group.name,
2635
+ positions: outPos,
2636
+ indices: outIndices,
2637
+ placement: new Float64Array([
2638
+ 1,
2639
+ 0,
2640
+ 0,
2641
+ 0,
2642
+ 0,
2643
+ 1,
2644
+ 0,
2645
+ 0,
2646
+ 0,
2647
+ 0,
2648
+ 1,
2649
+ 0,
2650
+ 0,
2651
+ 0,
2652
+ 0,
2653
+ 1
2654
+ ]),
2655
+ colors: outColors,
2656
+ uvs: outUvs,
2657
+ ...outNormals !== null ? { normals: outNormals } : {}
2658
+ });
2659
+ }
2660
+ return results;
2661
+ }
2662
+ // src/io/stream.ts
2663
+ const DEFAULT_MAX_FILE_BYTES = DEFAULT_MAX_ZIP_FILE_BYTES;
2664
+ const PROGRESS_INTERVAL_MS = 16;
2665
+ const textDecoder = new TextDecoder("utf-8", { fatal: false });
2666
+ function createAbortError(signal) {
2667
+ const reason = signal?.reason;
2668
+ if (reason instanceof Error) return reason;
2669
+ return new DOMException("The operation was aborted.", "AbortError");
2670
+ }
2671
+ function throwIfAborted(signal) {
2672
+ if (signal?.aborted) throw createAbortError(signal);
2673
+ }
2674
+ function combineSignals(a, b) {
2675
+ if (!a && !b) return {
2676
+ signal: void 0,
2677
+ cleanup: () => {}
2678
+ };
2679
+ if (a && !b) return {
2680
+ signal: a,
2681
+ cleanup: () => {}
2682
+ };
2683
+ if (!a && b) return {
2684
+ signal: b,
2685
+ cleanup: () => {}
2686
+ };
2687
+ if (a === b) return {
2688
+ signal: a,
2689
+ cleanup: () => {}
2690
+ };
2691
+ const ctrl = new AbortController();
2692
+ const onAbortA = () => ctrl.abort(a.reason);
2693
+ const onAbortB = () => ctrl.abort(b.reason);
2694
+ if (a.aborted) {
2695
+ ctrl.abort(a.reason);
2696
+ return {
2697
+ signal: ctrl.signal,
2698
+ cleanup: () => {}
2699
+ };
2700
+ }
2701
+ if (b.aborted) {
2702
+ ctrl.abort(b.reason);
2703
+ return {
2704
+ signal: ctrl.signal,
2705
+ cleanup: () => {}
2706
+ };
2707
+ }
2708
+ a.addEventListener("abort", onAbortA, { once: true });
2709
+ b.addEventListener("abort", onAbortB, { once: true });
2710
+ return {
2711
+ signal: ctrl.signal,
2712
+ cleanup: () => {
2713
+ a.removeEventListener("abort", onAbortA);
2714
+ b.removeEventListener("abort", onAbortB);
2715
+ }
2716
+ };
2717
+ }
2718
+ function formatFromExtension(filename) {
2719
+ if (!filename) return null;
2720
+ const clean = filename.split(/[?#]/, 1)[0].trim().toLowerCase();
2721
+ const dot = clean.lastIndexOf(".");
2722
+ if (dot < 0) return null;
2723
+ switch (clean.slice(dot)) {
2724
+ case ".3mf": return "threemf";
2725
+ case ".ply": return "ply";
2726
+ case ".stl": return "stl";
2727
+ case ".obj": return "obj";
2728
+ case ".gltf": return "gltf";
2729
+ case ".glb": return "glb";
2730
+ default: return null;
2731
+ }
2732
+ }
2733
+ function hasBinaryBytes(bytes) {
2734
+ const limit = Math.min(bytes.byteLength, 1024);
2735
+ for (let i = 0; i < limit; i++) {
2736
+ const c = bytes[i];
2737
+ if (c === 0 || c < 32 && c !== 9 && c !== 10 && c !== 13) return true;
2738
+ }
2739
+ return false;
2740
+ }
2741
+ /**
2742
+ * Detect a mesh file format from header magic bytes and/or filename extension.
2743
+ */
2744
+ function detectMeshFormat(bytesOrFilename, filename) {
2745
+ if (typeof bytesOrFilename === "string") return formatFromExtension(bytesOrFilename);
2746
+ const u8 = bytesOrFilename === void 0 || bytesOrFilename === null ? null : bytesOrFilename instanceof Uint8Array ? bytesOrFilename : new Uint8Array(bytesOrFilename);
2747
+ if (u8 && u8.byteLength >= 4) {
2748
+ if (u8[0] === 80 && u8[1] === 75 && (u8[2] === 3 && u8[3] === 4 || u8[2] === 5 && u8[3] === 6)) return "threemf";
2749
+ if (u8[0] === 103 && u8[1] === 108 && u8[2] === 84 && u8[3] === 70) return "glb";
2750
+ if (u8[0] === 112 && u8[1] === 108 && u8[2] === 121 && (u8[3] === 10 || u8[3] === 13)) return "ply";
2751
+ }
2752
+ const byExt = formatFromExtension(filename);
2753
+ if (byExt !== null) return byExt;
2754
+ if (!u8 || u8.byteLength === 0) return null;
2755
+ if (u8.byteLength >= 84) {
2756
+ if (84 + new DataView(u8.buffer, u8.byteOffset, u8.byteLength).getUint32(80, true) * 50 === u8.byteLength) return "stl";
2757
+ }
2758
+ if (!hasBinaryBytes(u8)) {
2759
+ let head = textDecoder.decode(u8.subarray(0, Math.min(u8.byteLength, 2048)));
2760
+ if (head.charCodeAt(0) === 65279) head = head.slice(1);
2761
+ const trimmed = head.trimStart();
2762
+ if (trimmed.startsWith("{")) return "gltf";
2763
+ if (trimmed.startsWith("solid") && (trimmed.length === 5 || trimmed.charCodeAt(5) <= 32)) return "stl";
2764
+ const lines = trimmed.split(/\r?\n/, 20);
2765
+ for (let i = 0; i < lines.length; i++) {
2766
+ const l = lines[i].trim();
2767
+ if (l === "" || l.startsWith("#")) continue;
2768
+ if (/^(?:v|vt|vn|vp|f|o|g|mtllib|usemtl|s)\s/.test(l)) return "obj";
2769
+ break;
2770
+ }
2771
+ }
2772
+ return null;
2773
+ }
2774
+ function normalizeFormatOption(format) {
2775
+ return format === "3mf" ? "threemf" : format;
2776
+ }
2777
+ function nowMs() {
2778
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
2779
+ }
2780
+ function createThrottledEmitter(onProgress) {
2781
+ if (!onProgress) return { emit: () => {} };
2782
+ let lastEmit = -Infinity;
2783
+ return { emit(progress, force = false) {
2784
+ const now = nowMs();
2785
+ if (force || now - lastEmit >= PROGRESS_INTERVAL_MS) {
2786
+ lastEmit = now;
2787
+ onProgress(progress);
2788
+ }
2789
+ } };
2790
+ }
2791
+ function isReadableStream(source) {
2792
+ return typeof source === "object" && source !== null && typeof source.getReader === "function";
2793
+ }
2794
+ function isBlobLike(source) {
2795
+ return typeof source === "object" && source !== null && typeof source.size === "number" && typeof source.arrayBuffer === "function";
2796
+ }
2797
+ async function readStreamSource(source, maxFileBytes, emit, signal) {
2798
+ throwIfAborted(signal);
2799
+ if (source instanceof Uint8Array || source instanceof ArrayBuffer) {
2800
+ const u8 = source instanceof Uint8Array ? source : new Uint8Array(source);
2801
+ if (u8.byteLength > maxFileBytes) throw new Error(`Mesh payload size (${u8.byteLength} bytes) exceeds limit of ${maxFileBytes} bytes`);
2802
+ emit({
2803
+ bytesRead: u8.byteLength,
2804
+ totalBytes: u8.byteLength,
2805
+ stage: "reading"
2806
+ }, true);
2807
+ return {
2808
+ bytes: u8,
2809
+ bytesRead: u8.byteLength,
2810
+ totalBytes: u8.byteLength
2811
+ };
2812
+ }
2813
+ let totalBytes = null;
2814
+ let stream = null;
2815
+ if (isBlobLike(source)) {
2816
+ totalBytes = source.size;
2817
+ if (totalBytes > maxFileBytes) throw new Error(`Mesh file size (${totalBytes} bytes) exceeds limit of ${maxFileBytes} bytes`);
2818
+ if (typeof source.stream === "function") stream = source.stream();
2819
+ else {
2820
+ const buf = await source.arrayBuffer();
2821
+ throwIfAborted(signal);
2822
+ const u8 = new Uint8Array(buf);
2823
+ if (u8.byteLength > maxFileBytes) throw new Error(`Mesh file size (${u8.byteLength} bytes) exceeds limit of ${maxFileBytes} bytes`);
2824
+ emit({
2825
+ bytesRead: u8.byteLength,
2826
+ totalBytes,
2827
+ stage: "reading"
2828
+ }, true);
2829
+ return {
2830
+ bytes: u8,
2831
+ bytesRead: u8.byteLength,
2832
+ totalBytes
2833
+ };
2834
+ }
2835
+ } else if (isReadableStream(source)) stream = source;
2836
+ else throw new Error("parseMeshStream: unsupported source (expected ReadableStream, Blob, Uint8Array, or ArrayBuffer)");
2837
+ const reader = stream.getReader();
2838
+ const chunks = [];
2839
+ let bytesRead = 0;
2840
+ const onAbort = () => {
2841
+ chunks.length = 0;
2842
+ reader.cancel(createAbortError(signal)).catch(() => {});
2843
+ };
2844
+ signal?.addEventListener("abort", onAbort, { once: true });
2845
+ emit({
2846
+ bytesRead: 0,
2847
+ totalBytes,
2848
+ stage: "reading"
2849
+ }, true);
2850
+ try {
2851
+ while (true) {
2852
+ throwIfAborted(signal);
2853
+ const { value, done } = await reader.read();
2854
+ if (done) break;
2855
+ throwIfAborted(signal);
2856
+ if (value && value.byteLength > 0) {
2857
+ if (value.byteLength > maxFileBytes - bytesRead) {
2858
+ chunks.length = 0;
2859
+ await reader.cancel().catch(() => {});
2860
+ throw new Error(`Mesh stream exceeds maximum size limit of ${maxFileBytes} bytes`);
2861
+ }
2862
+ bytesRead += value.byteLength;
2863
+ chunks.push(new Uint8Array(value));
2864
+ emit({
2865
+ bytesRead,
2866
+ totalBytes,
2867
+ stage: "reading"
2868
+ });
2869
+ }
2870
+ }
2871
+ } catch (err) {
2872
+ chunks.length = 0;
2873
+ await reader.cancel(err).catch(() => {});
2874
+ throw err;
2875
+ } finally {
2876
+ signal?.removeEventListener("abort", onAbort);
2877
+ }
2878
+ throwIfAborted(signal);
2879
+ const resolvedTotal = totalBytes ?? bytesRead;
2880
+ emit({
2881
+ bytesRead,
2882
+ totalBytes: resolvedTotal,
2883
+ stage: "reading"
2884
+ }, true);
2885
+ if (chunks.length === 1 && chunks[0].byteLength === bytesRead) {
2886
+ const single = chunks[0];
2887
+ chunks.length = 0;
2888
+ return {
2889
+ bytes: single,
2890
+ bytesRead,
2891
+ totalBytes: resolvedTotal
2892
+ };
2893
+ }
2894
+ const assembled = new Uint8Array(bytesRead);
2895
+ let off = 0;
2896
+ for (let i = 0; i < chunks.length; i++) {
2897
+ assembled.set(chunks[i], off);
2898
+ off += chunks[i].byteLength;
2899
+ }
2900
+ chunks.length = 0;
2901
+ return {
2902
+ bytes: assembled,
2903
+ bytesRead,
2904
+ totalBytes: resolvedTotal
2905
+ };
2906
+ }
2907
+ /**
2908
+ * Stream, detect format, and parse a mesh from a `ReadableStream`, `Blob`/`File`,
2909
+ * `Uint8Array`, or `ArrayBuffer` without loading Worker/Wasm state.
2910
+ */
2911
+ async function parseMeshStream(source, options, onProgress, signal) {
2912
+ const maxFileBytes = options?.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
2913
+ const combined = combineSignals(options?.signal, signal);
2914
+ const activeSignal = combined.signal;
2915
+ const { emit } = createThrottledEmitter(onProgress);
2916
+ let rawBytes = null;
2917
+ try {
2918
+ const read = await readStreamSource(source, maxFileBytes, emit, activeSignal);
2919
+ rawBytes = read.bytes;
2920
+ const totalBytes = read.totalBytes;
2921
+ throwIfAborted(activeSignal);
2922
+ const filename = options?.filename ?? (typeof File !== "undefined" && source instanceof File ? source.name : void 0);
2923
+ const format = options?.format ? normalizeFormatOption(options.format) : detectMeshFormat(rawBytes, filename);
2924
+ if (format === null) throw new Error(`Unable to detect mesh format${filename ? ` for "${filename}"` : ""}`);
2925
+ emit({
2926
+ bytesRead: read.bytesRead,
2927
+ totalBytes,
2928
+ stage: "parsing"
2929
+ }, true);
2930
+ switch (format) {
2931
+ case "threemf": return await import3MF(rawBytes, {
2932
+ maxFileBytes,
2933
+ unitScale: options?.unitScale,
2934
+ signal: activeSignal
2935
+ });
2936
+ case "ply": return [importPLY(rawBytes, {
2937
+ maxFileBytes,
2938
+ signal: activeSignal
2939
+ })];
2940
+ case "stl": return [importSTL(rawBytes, {
2941
+ deduplicateVertices: options?.deduplicateVertices,
2942
+ maxFileBytes,
2943
+ signal: activeSignal
2944
+ })];
2945
+ case "obj": return importOBJ(rawBytes, {
2946
+ mergeGroups: options?.mergeGroups,
2947
+ maxFileBytes,
2948
+ signal: activeSignal
2949
+ });
2950
+ case "gltf":
2951
+ case "glb": return await importGLTFAsync(rawBytes, {
2952
+ resolveBuffer: options?.resolveBuffer,
2953
+ decoderModule: options?.decoderModule,
2954
+ wasmBinary: options?.wasmBinary
2955
+ });
2956
+ }
2957
+ } finally {
2958
+ rawBytes = null;
2959
+ combined.cleanup();
2960
+ }
2961
+ }
2962
+ function isWorkerSceneTarget(scene) {
2963
+ const candidate = scene;
2964
+ return typeof candidate.status === "function" && typeof candidate.idOf === "function";
2965
+ }
2966
+ async function raceWithAbort(promise, signal) {
2967
+ throwIfAborted(signal);
2968
+ if (!signal) return promise;
2969
+ return new Promise((resolve, reject) => {
2970
+ const onAbort = () => {
2971
+ reject(createAbortError(signal));
2972
+ };
2973
+ signal.addEventListener("abort", onAbort, { once: true });
2974
+ promise.then((val) => {
2975
+ signal.removeEventListener("abort", onAbort);
2976
+ resolve(val);
2977
+ }, (err) => {
2978
+ signal.removeEventListener("abort", onAbort);
2979
+ reject(err);
2980
+ });
2981
+ });
2982
+ }
2983
+ /**
2984
+ * Stream, parse, and upload meshes into either a synchronous {@link Scene} or
2985
+ * an asynchronous {@link WorkerScene}, emitting `"reading"`, `"parsing"`, and
2986
+ * `"building_bvh"` progress stages. Cleans up partial meshes on abort or error.
2987
+ */
2988
+ async function loadMeshStream(scene, source, options, onProgress, signal) {
2989
+ const combined = combineSignals(options?.signal, signal);
2990
+ const activeSignal = combined.signal;
2991
+ const { emit } = createThrottledEmitter(onProgress);
2992
+ let latestBytes = 0;
2993
+ let latestTotal = null;
2994
+ const forwardProgress = (p) => {
2995
+ latestBytes = p.bytesRead;
2996
+ latestTotal = p.totalBytes;
2997
+ onProgress?.(p);
2998
+ };
2999
+ const added = [];
3000
+ const workerMode = isWorkerSceneTarget(scene);
3001
+ try {
3002
+ const parsed = await parseMeshStream(source, {
3003
+ ...options,
3004
+ signal: activeSignal
3005
+ }, onProgress ? forwardProgress : void 0);
3006
+ throwIfAborted(activeSignal);
3007
+ if (onProgress) emit({
3008
+ bytesRead: latestBytes,
3009
+ totalBytes: latestTotal ?? latestBytes,
3010
+ stage: "building_bvh"
3011
+ }, true);
3012
+ for (let i = 0; i < parsed.length; i++) {
3013
+ throwIfAborted(activeSignal);
3014
+ const mesh = parsed[i];
3015
+ const handle = scene.addMesh(mesh.positions, mesh.indices, mesh.uvs !== null ? { uvs: mesh.uvs } : void 0);
3016
+ added.push(handle);
3017
+ if (workerMode) {
3018
+ const ws = scene;
3019
+ const measurePromise = ws.measure(handle);
3020
+ measurePromise.catch(() => {});
3021
+ try {
3022
+ await raceWithAbort(measurePromise, activeSignal);
3023
+ } catch (err) {
3024
+ if (activeSignal?.aborted) throw err;
3025
+ try {
3026
+ const st = ws.status(`mesh:${ws.idOf(handle)}`);
3027
+ if (st.status === "error" && st.error) throw st.error;
3028
+ } catch (statusErr) {
3029
+ if (statusErr !== err && statusErr instanceof Error) throw statusErr;
3030
+ }
3031
+ throw err;
3032
+ }
3033
+ }
3034
+ }
3035
+ throwIfAborted(activeSignal);
3036
+ return added;
3037
+ } catch (err) {
3038
+ for (let i = 0; i < added.length; i++) try {
3039
+ scene.removeMesh(added[i]);
3040
+ } catch {}
3041
+ throw err;
3042
+ } finally {
3043
+ combined.cleanup();
3044
+ }
3045
+ }
1
3046
  // src/io/index.ts
2
3047
  /**
3
3048
  * Reads the mesh's views, copies them (views borrow wasm memory and die on
@@ -213,8 +3258,9 @@ function exportOBJ(scene, mesh, options) {
213
3258
  const snap = snapshot(scene, mesh, options);
214
3259
  const name = options?.name ?? "mesh";
215
3260
  const vertices = snap.positions.length / 3;
3261
+ const useColors = snap.colors !== null && options?.vertexColors !== false;
216
3262
  const parts = [`o ${name}\n`];
217
- for (let v = 0; v < vertices; v++) if (snap.colors !== null) {
3263
+ for (let v = 0; v < vertices; v++) if (useColors && snap.colors !== null) {
218
3264
  const r = (snap.colors[4 * v] / 255).toPrecision(8);
219
3265
  const g = (snap.colors[4 * v + 1] / 255).toPrecision(8);
220
3266
  const b = (snap.colors[4 * v + 2] / 255).toPrecision(8);
@@ -239,6 +3285,7 @@ function exportPLY(scene, mesh, options) {
239
3285
  const vertices = snap.positions.length / 3;
240
3286
  const useNormals = snap.normals !== null;
241
3287
  const useColors = snap.colors !== null;
3288
+ const useUvs = snap.uvs !== null;
242
3289
  const header = [
243
3290
  "ply",
244
3291
  `format ${options?.binary === false ? "ascii 1.0" : "binary_little_endian 1.0"}`,
@@ -257,6 +3304,7 @@ function exportPLY(scene, mesh, options) {
257
3304
  "property uchar blue",
258
3305
  "property uchar alpha"
259
3306
  ] : [],
3307
+ ...useUvs ? ["property float s", "property float t"] : [],
260
3308
  `element face ${snap.triangles}`,
261
3309
  "property list uchar uint vertex_indices",
262
3310
  "end_header",
@@ -268,13 +3316,14 @@ function exportPLY(scene, mesh, options) {
268
3316
  let line = `${snap.positions[3 * v]} ${snap.positions[3 * v + 1]} ${snap.positions[3 * v + 2]}`;
269
3317
  if (useNormals) line += ` ${snap.normals[3 * v]} ${snap.normals[3 * v + 1]} ${snap.normals[3 * v + 2]}`;
270
3318
  if (useColors) line += ` ${snap.colors?.[4 * v]} ${snap.colors?.[4 * v + 1]} ${snap.colors?.[4 * v + 2]} ${snap.colors?.[4 * v + 3]}`;
3319
+ if (useUvs) line += ` ${snap.uvs[2 * v]} ${snap.uvs[2 * v + 1]}`;
271
3320
  parts.push(`${line}\n`);
272
3321
  }
273
3322
  for (let t = 0; t < snap.triangles; t++) parts.push(`3 ${snap.indices[3 * t]} ${snap.indices[3 * t + 1]} ${snap.indices[3 * t + 2]}\n`);
274
3323
  return new TextEncoder().encode(parts.join(""));
275
3324
  }
276
3325
  const head = new TextEncoder().encode(header);
277
- const body = new Uint8Array(vertices * (4 * (3 + (useNormals ? 3 : 0)) + (useColors ? 4 : 0)) + snap.triangles * 13);
3326
+ const body = new Uint8Array(vertices * (4 * (3 + (useNormals ? 3 : 0) + (useUvs ? 2 : 0)) + (useColors ? 4 : 0)) + snap.triangles * 13);
278
3327
  const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
279
3328
  let at = 0;
280
3329
  for (let v = 0; v < vertices; v++) {
@@ -295,6 +3344,11 @@ function exportPLY(scene, mesh, options) {
295
3344
  body[at + 3] = snap.colors?.[4 * v + 3] ?? 0;
296
3345
  at += 4;
297
3346
  }
3347
+ if (useUvs) {
3348
+ view.setFloat32(at, snap.uvs[2 * v], true);
3349
+ view.setFloat32(at + 4, snap.uvs[2 * v + 1], true);
3350
+ at += 8;
3351
+ }
298
3352
  }
299
3353
  for (let t = 0; t < snap.triangles; t++) {
300
3354
  view.setUint8(at, 3);
@@ -613,14 +3667,13 @@ async function exportGLTFDraco(scene, mesh, options) {
613
3667
  /** Validates the quantization/level/order options before the module loads. */
614
3668
  function encodeSettings(options) {
615
3669
  const bits = options?.quantizationBits;
616
- checkedQuantizationBits(bits?.texCoord, "texCoord", 12);
617
3670
  const level = options?.compressionLevel ?? 5;
618
3671
  if (!Number.isInteger(level) || level < 0 || level > 10) throw new Error(`Draco: the compression level must be an integer from 0 to 10 (got ${options?.compressionLevel})`);
619
3672
  return {
620
3673
  positionBits: checkedQuantizationBits(bits?.position, "position", 14),
621
3674
  normalBits: checkedQuantizationBits(bits?.normal, "normal", 10),
622
3675
  colorBits: checkedQuantizationBits(bits?.color, "color", 8),
623
- uvBits: checkedQuantizationBits(bits?.uv, "uv", 16),
3676
+ uvBits: checkedQuantizationBits(bits?.uv, "uv", checkedQuantizationBits(bits?.texCoord, "texCoord", 16)),
624
3677
  level,
625
3678
  preserveFaceOrder: options?.preserveFaceOrder === true
626
3679
  };
@@ -1042,7 +4095,7 @@ async function readPrimitiveDraco(doc, buffers, spec, usedNames, decoderOfOption
1042
4095
  const decoded = decodeDracoMesh(module, buffer.subarray(base, end), what, positionId, uvAttr === void 0 ? null : uvAttr);
1043
4096
  const { positions, indices } = decoded;
1044
4097
  const plainUvs = spec.primitive.attributes["TEXCOORD_0"];
1045
- const uvs = decoded.uvs ?? (typeof plainUvs === "number" && doc.accessors?.[plainUvs]?.bufferView !== void 0 ? readUvs(doc, buffers, plainUvs, positions.length / 3, name) : null);
4098
+ const uvs = decoded.uvs !== null ? { uvs: decoded.uvs } : typeof plainUvs === "number" && (doc.accessors?.[plainUvs]?.bufferView !== void 0 || doc.accessors?.[plainUvs]?.sparse !== void 0) ? readUvsUnlessSkipped(doc, buffers, plainUvs, positions.length / 3, name) : NO_UVS;
1046
4099
  const world = spec.world;
1047
4100
  for (let i = 0; i < positions.length; i += 3) {
1048
4101
  const x = positions[i];
@@ -1058,7 +4111,7 @@ async function readPrimitiveDraco(doc, buffers, spec, usedNames, decoderOfOption
1058
4111
  indices,
1059
4112
  placement: world.slice(),
1060
4113
  colors: null,
1061
- uvs
4114
+ ...uvs
1062
4115
  };
1063
4116
  }
1064
4117
  /** The asset JSON, checked to be an object before the importers read it. */
@@ -1356,14 +4409,14 @@ function readPrimitive(doc, buffers, node, mesh, primitive, world, usedNames) {
1356
4409
  positions[i + 2] = world[2] * x + world[6] * y + world[10] * z + world[14];
1357
4410
  }
1358
4411
  const colors = typeof primitive.attributes["COLOR_0"] === "number" ? readColors(doc, buffers, primitive.attributes["COLOR_0"], positions.length / 3, name) : null;
1359
- const uvs = typeof primitive.attributes["TEXCOORD_0"] === "number" ? readUvs(doc, buffers, primitive.attributes["TEXCOORD_0"], positions.length / 3, name) : null;
4412
+ const uvs = typeof primitive.attributes["TEXCOORD_0"] === "number" ? readUvsUnlessSkipped(doc, buffers, primitive.attributes["TEXCOORD_0"], positions.length / 3, name) : NO_UVS;
1360
4413
  return {
1361
4414
  name,
1362
4415
  positions,
1363
4416
  indices,
1364
4417
  placement: world.slice(),
1365
4418
  colors,
1366
- uvs
4419
+ ...uvs
1367
4420
  };
1368
4421
  }
1369
4422
  /** The deduplicated mesh name: the node name, else the mesh name, else `"mesh"`. */
@@ -1436,20 +4489,76 @@ function accessorCount(doc, primitive, name) {
1436
4489
  if (accessor === void 0) throw new Error(`glTF: "${name}" has a primitive without POSITION`);
1437
4490
  return accessor.count;
1438
4491
  }
4492
+ /** The `uvs` and `uvsSkipped` fields of a primitive without `TEXCOORD_0`. */
4493
+ const NO_UVS = { uvs: null };
4494
+ /**
4495
+ * Why glTF's `TEXCOORD_0` accessor `index` cannot be read, or `null` when it
4496
+ * can. Core glTF 2.0 allows float and normalized `u8`/`u16`;
4497
+ * `KHR_mesh_quantization` adds `i8`/`i16` and the integer types without
4498
+ * `normalized`. A missing accessor, or one of the wrong shape, is malformed
4499
+ * rather than unsupported: {@link readUvs} throws on it.
4500
+ */
4501
+ function uvSkipReason(doc, index) {
4502
+ const accessor = doc.accessors?.[index];
4503
+ if (accessor === void 0) return null;
4504
+ if (accessor.sparse !== void 0) return "TEXCOORD_0 is a sparse accessor, which is not supported";
4505
+ const { componentType: type, normalized } = accessor;
4506
+ if (type === 5126 || (type === 5121 || type === 5123) && normalized === true) return null;
4507
+ if (type !== 5120 && type !== 5121 && type !== 5122 && type !== 5123) return `TEXCOORD_0 has component type ${type}, which glTF does not allow for it`;
4508
+ if (doc.extensionsUsed?.includes(QUANTIZATION) || doc.extensionsRequired?.includes(QUANTIZATION)) return null;
4509
+ return `TEXCOORD_0 is ${`${normalized === true ? "normalized" : "non-normalized"} ${COMPONENT_NAME[type]}`}, which glTF allows only with ${QUANTIZATION}`;
4510
+ }
4511
+ const QUANTIZATION = "KHR_mesh_quantization";
4512
+ const COMPONENT_NAME = {
4513
+ 5120: "i8",
4514
+ 5121: "u8",
4515
+ 5122: "i16",
4516
+ 5123: "u16"
4517
+ };
4518
+ /** {@link readUvs}, or no UVs and the reason when the accessor is unsupported. */
4519
+ function readUvsUnlessSkipped(doc, buffers, index, vertices, name) {
4520
+ const uvsSkipped = uvSkipReason(doc, index);
4521
+ return uvsSkipped === null ? { uvs: readUvs(doc, buffers, index, vertices, name) } : {
4522
+ uvs: null,
4523
+ uvsSkipped
4524
+ };
4525
+ }
1439
4526
  function readUvs(doc, buffers, index, vertices, name) {
1440
4527
  const data = accessorData(doc, buffers, index, "TEXCOORD_0");
1441
- if (data.components !== 2 || data.componentType !== 5126 && data.componentType !== 5121 && data.componentType !== 5123) throw new Error(`glTF: "${name}" has TEXCOORD_0 with ${data.components} ${data.size}-byte components (float, u8 or u16 VEC2)`);
4528
+ if (data.components !== 2) throw new Error(`glTF: "${name}" has TEXCOORD_0 with ${data.components} ${data.size}-byte components (VEC2 expected)`);
1442
4529
  if (data.count !== vertices) throw new Error(`glTF: "${name}" has ${data.count} UVs for ${vertices} vertices`);
1443
4530
  const out = new Float32Array(2 * vertices);
1444
4531
  if (data.buffer.length === 0) return out;
4532
+ const normalized = doc.accessors?.[index]?.normalized === true;
1445
4533
  for (let i = 0; i < vertices; i++) for (let c = 0; c < 2; c++) {
1446
- const at = data.base + i * data.stride + c * data.size;
1447
- const v = data.componentType === 5126 ? data.view.getFloat32(at, true) : data.componentType === 5121 ? data.view.getUint8(at) / 255 : data.view.getUint16(at, true) / 65535;
4534
+ const v = uvComponent(data, data.base + i * data.stride + c * data.size, normalized);
1448
4535
  if (!Number.isFinite(v)) throw new Error(`glTF: "${name}" has a non-finite UV at vertex ${i}`);
1449
4536
  out[2 * i + c] = v;
1450
4537
  }
1451
4538
  return out;
1452
4539
  }
4540
+ /** One UV component at byte `at`, by glTF's accessor equations: float as stored, integers as stored or normalized. */
4541
+ function uvComponent(data, at, normalized) {
4542
+ switch (data.componentType) {
4543
+ case 5120: {
4544
+ const c = data.view.getInt8(at);
4545
+ return normalized ? Math.max(c / 127, -1) : c;
4546
+ }
4547
+ case 5121: {
4548
+ const c = data.view.getUint8(at);
4549
+ return normalized ? c / 255 : c;
4550
+ }
4551
+ case 5122: {
4552
+ const c = data.view.getInt16(at, true);
4553
+ return normalized ? Math.max(c / 32767, -1) : c;
4554
+ }
4555
+ case 5123: {
4556
+ const c = data.view.getUint16(at, true);
4557
+ return normalized ? c / 65535 : c;
4558
+ }
4559
+ default: return data.view.getFloat32(at, true);
4560
+ }
4561
+ }
1453
4562
  function readColors(doc, buffers, index, vertices, name) {
1454
4563
  const data = accessorData(doc, buffers, index, "COLOR_0");
1455
4564
  if (data.components !== 3 && data.components !== 4 || data.componentType !== 5121 && data.componentType !== 5126) throw new Error(`glTF: "${name}" has COLOR_0 with ${data.components} ${data.size}-byte components (u8 or float VEC3/VEC4)`);
@@ -1476,4 +4585,4 @@ function readColors(doc, buffers, index, vertices, name) {
1476
4585
  }
1477
4586
  return out;
1478
4587
  }
1479
- export { decodeDraco, encodeDraco, exportGLTF, exportOBJ, exportPLY, exportSTL, importGLTF, importGLTFAsync };
4588
+ export { DEFAULT_MAX_ZIP_ENTRIES, DEFAULT_MAX_ZIP_FILE_BYTES, crc32, decodeDraco, detectMeshFormat, encodeDraco, export3MF, export3MFSync, exportGLTF, exportOBJ, exportPLY, exportSTL, import3MF, importGLTF, importGLTFAsync, importOBJ, importPLY, importSTL, loadMeshStream, parseMeshStream, readZip, validateZipEntryName, writeZip, writeZipSync };