@margoengine/loaders 0.1.0 → 1.0.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 (82) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +4 -4
  3. package/README.md +1666 -1198
  4. package/dist/crease.d.ts +7 -0
  5. package/dist/crease.js +67 -0
  6. package/dist/dae-common.js +1 -1
  7. package/dist/dae-kinematics.d.ts +65 -0
  8. package/dist/dae-kinematics.js +461 -0
  9. package/dist/dae.d.ts +9 -4
  10. package/dist/dae.js +16 -5
  11. package/dist/dxf-hatch.d.ts +8 -0
  12. package/dist/dxf-hatch.js +346 -0
  13. package/dist/dxf-leaders.d.ts +59 -0
  14. package/dist/dxf-leaders.js +258 -0
  15. package/dist/dxf.d.ts +42 -1
  16. package/dist/dxf.js +226 -15
  17. package/dist/engine.d.ts +5 -0
  18. package/dist/engine.js +3 -0
  19. package/dist/gcode.d.ts +37 -0
  20. package/dist/gcode.js +91 -0
  21. package/dist/geometry.d.ts +1 -1
  22. package/dist/index.d.ts +1 -1
  23. package/dist/mtl.d.ts +8 -3
  24. package/dist/mtl.js +91 -10
  25. package/dist/nrrd.d.ts +12 -5
  26. package/dist/nrrd.js +68 -26
  27. package/dist/obj.d.ts +3 -1
  28. package/dist/obj.js +7 -1
  29. package/dist/render.d.ts +9 -4
  30. package/dist/render.js +31 -3
  31. package/dist/shared/asset-url.js +82 -82
  32. package/dist/shared/crc32.d.ts +2 -2
  33. package/dist/shared/crc32.js +47 -47
  34. package/dist/shared/errors.js +36 -36
  35. package/dist/shared/inflate.js +284 -284
  36. package/dist/shared/normals.js +26 -26
  37. package/dist/shared/scene-scope.js +54 -54
  38. package/dist/shared/trailing-data.js +45 -42
  39. package/dist/threemf-beam-reader.d.ts +19 -0
  40. package/dist/threemf-beam-reader.js +165 -0
  41. package/dist/threemf-beams.d.ts +52 -0
  42. package/dist/threemf-beams.js +268 -0
  43. package/dist/threemf-boolean-read.d.ts +10 -0
  44. package/dist/threemf-boolean-read.js +113 -0
  45. package/dist/threemf-boolean.d.ts +59 -0
  46. package/dist/threemf-boolean.js +20 -0
  47. package/dist/threemf-csg.d.ts +14 -0
  48. package/dist/threemf-csg.js +193 -0
  49. package/dist/threemf-displacement-read.d.ts +8 -0
  50. package/dist/threemf-displacement-read.js +213 -0
  51. package/dist/threemf-displacement.d.ts +71 -0
  52. package/dist/threemf-displacement.js +18 -0
  53. package/dist/threemf-evaluate.d.ts +36 -0
  54. package/dist/threemf-evaluate.js +86 -0
  55. package/dist/threemf-functions.d.ts +33 -0
  56. package/dist/threemf-functions.js +359 -0
  57. package/dist/threemf-lattice-mesh.d.ts +9 -0
  58. package/dist/threemf-lattice-mesh.js +115 -0
  59. package/dist/threemf-lattice.js +10 -145
  60. package/dist/threemf-levelset.d.ts +23 -0
  61. package/dist/threemf-levelset.js +105 -0
  62. package/dist/threemf-materials.d.ts +89 -2
  63. package/dist/threemf-materials.js +194 -11
  64. package/dist/threemf-mesh.d.ts +21 -6
  65. package/dist/threemf-mesh.js +266 -45
  66. package/dist/threemf-secure.d.ts +50 -0
  67. package/dist/threemf-secure.js +153 -0
  68. package/dist/threemf-tessellate.d.ts +37 -0
  69. package/dist/threemf-tessellate.js +277 -0
  70. package/dist/threemf-volume-colour.d.ts +25 -0
  71. package/dist/threemf-volume-colour.js +233 -0
  72. package/dist/threemf-volume-sample.d.ts +8 -0
  73. package/dist/threemf-volume-sample.js +65 -0
  74. package/dist/threemf-volumetric-read.d.ts +15 -0
  75. package/dist/threemf-volumetric-read.js +539 -0
  76. package/dist/threemf-volumetric.d.ts +177 -0
  77. package/dist/threemf-volumetric.js +28 -0
  78. package/dist/threemf.d.ts +73 -4
  79. package/dist/threemf.js +235 -41
  80. package/dist/types.d.ts +18 -0
  81. package/dist/workers/usd.js +1 -1
  82. package/package.json +291 -246
package/dist/threemf.js CHANGED
@@ -16,7 +16,33 @@ export const THREEMF_UNITS = {
16
16
  foot: 0.3048,
17
17
  meter: 1,
18
18
  };
19
+ /** The namespace of the production extension's `path` and `UUID` attributes. */
20
+ const PRODUCTION = 'http://schemas.microsoft.com/3dmanufacturing/production/2015/06';
19
21
  const IDENTITY = new Float64Array([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
22
+ /** Property resources of the core and materials formats, which share one set of ids. */
23
+ const PROPERTY_RESOURCES = new Set([
24
+ 'basematerials',
25
+ 'colorgroup',
26
+ 'texture2d',
27
+ 'texture2dgroup',
28
+ 'compositematerials',
29
+ 'multiproperties',
30
+ 'pbmetallicdisplayproperties',
31
+ 'pbspeculardisplayproperties',
32
+ 'translucentdisplayproperties',
33
+ 'pbmetallictexturedisplayproperties',
34
+ 'pbspeculartexturedisplayproperties',
35
+ ]);
36
+ /** Resource elements whose content only an extension reads (volumetric, implicit and displacement extensions). */
37
+ const FIELDS = new Set([
38
+ 'image3d',
39
+ 'functionfromimage3d',
40
+ 'implicitfunction',
41
+ 'volumedata',
42
+ 'displacement2d',
43
+ 'normvectorgroup',
44
+ 'disp2dgroup',
45
+ ]);
20
46
  function parseColor(value) {
21
47
  const rgba = hexColor(value?.trim() ?? '');
22
48
  if (!rgba)
@@ -62,16 +88,52 @@ function parseModel(xml, limit, extension, external) {
62
88
  // Null prototype: <metadata name="..."> comes from the file (`__proto__`, `constructor`, `hasOwnProperty`).
63
89
  metadata: Object.create(null),
64
90
  };
65
- const propertyIds = model.propertyIds;
91
+ const propertyIds = model.propertyIds, resourceIds = new Set(),
92
+ /** The namespace each prefix was last declared for. */
93
+ prefixes = new Map();
94
+ /** A production extension attribute, under whatever prefix the part declares for it (`p` when it declares none). */
95
+ const production = (a, local) => {
96
+ for (const key in a) {
97
+ const at = key.indexOf(':');
98
+ if (at < 0 || key.slice(at + 1) !== local)
99
+ continue;
100
+ const prefix = key.slice(0, at);
101
+ if ((prefixes.get(prefix) ?? (prefix === 'p' ? PRODUCTION : '')) === PRODUCTION)
102
+ return a[key];
103
+ }
104
+ return undefined;
105
+ };
66
106
  let object, colors, metadataName, metadataText = '',
67
107
  // 3MF Core 1.4 section 4.1: <metadata> inside an object's or item's <metadatagroup> describes that element, not
68
108
  // the model, so only top-level entries reach the model metadata.
69
- metadataGroups = 0;
109
+ metadataGroups = 0,
110
+ /** Inside a slice stack, whose vertices are the layers' 2D points and no mesh's. */
111
+ sliceStacks = 0,
112
+ /** The depth inside a resource of `FIELDS`. */
113
+ field = 0;
70
114
  let vertexCount = 0, triangleCount = 0, sawModel = false;
71
115
  readXML(xml, {
72
116
  open(name, a) {
117
+ for (const key in a)
118
+ if (key.startsWith('xmlns:'))
119
+ prefixes.set(key.slice(6), a[key]);
120
+ if (field || FIELDS.has(name)) {
121
+ field++;
122
+ extension?.field?.open(model, name, a);
123
+ return;
124
+ }
73
125
  if (extension?.element?.(model, name, a))
74
126
  return;
127
+ if (name === 'slicestack')
128
+ sliceStacks++;
129
+ if (sliceStacks)
130
+ return;
131
+ if (PROPERTY_RESOURCES.has(name) && a.id) {
132
+ // A second resource of one id would silently replace the first.
133
+ if (resourceIds.has(a.id))
134
+ throw new LoaderError(F, 'syntax', `duplicate property resource id ${a.id.slice(0, 32)}`);
135
+ resourceIds.add(a.id);
136
+ }
75
137
  switch (name) {
76
138
  case 'model':
77
139
  if (sawModel)
@@ -113,17 +175,53 @@ function parseModel(xml, limit, extension, external) {
113
175
  id: a.id,
114
176
  name: a.name,
115
177
  type: a.type ?? 'model',
178
+ partNumber: a.partnumber,
179
+ uuid: production(a, 'UUID'),
116
180
  pid: a.pid,
117
181
  pindex: a.pindex === undefined ? undefined : index(a.pindex, 'pindex'),
118
182
  components: [],
183
+ alternatives: [],
119
184
  };
120
185
  model.objects.set(a.id, object);
121
186
  break;
122
187
  }
123
188
  case 'mesh':
189
+ case 'displacementmesh':
124
190
  if (!object)
125
- throw new LoaderError(F, 'syntax', '<mesh> outside <object>');
191
+ throw new LoaderError(F, 'syntax', `<${name}> outside <object>`);
126
192
  object.mesh = { vertices: floats(), triangles: uints(), pid: uints(), p: uints() };
193
+ if (name === 'displacementmesh')
194
+ object.displaced = true;
195
+ break;
196
+ case 'booleanshape':
197
+ case 'boolean': {
198
+ const shape = name === 'boolean' ? object?.boolean : object;
199
+ if (!shape)
200
+ throw new LoaderError(F, 'syntax', `<${name}> outside ${name === 'boolean' ? '<booleanshape>' : '<object>'}`);
201
+ if (!a.objectid)
202
+ throw new LoaderError(F, 'syntax', `<${name}> without objectid`);
203
+ // The extension's own attributes are unqualified, `path` among them.
204
+ const reference = {
205
+ objectId: a.objectid,
206
+ path: a.path ?? production(a, 'path'),
207
+ transform: parseTransform(a.transform),
208
+ };
209
+ if (name === 'boolean')
210
+ object.boolean.operands.push(reference);
211
+ else
212
+ object.boolean = { operation: a.operation ?? 'union', base: reference, operands: [] };
213
+ break;
214
+ }
215
+ case 'beamlattice':
216
+ if (object)
217
+ object.beamLattice = true;
218
+ extension?.open?.(model, name, a);
219
+ break;
220
+ case 'levelset':
221
+ if (!object)
222
+ throw new LoaderError(F, 'syntax', '<levelset> outside <object>');
223
+ object.levelSet = true;
224
+ extension?.open?.(model, name, a);
127
225
  break;
128
226
  case 'vertex': {
129
227
  const mesh = object?.mesh;
@@ -162,20 +260,55 @@ function parseModel(xml, limit, extension, external) {
162
260
  throw new LoaderError(F, 'syntax', '<component> outside <object>');
163
261
  if (!a.objectid)
164
262
  throw new LoaderError(F, 'syntax', '<component> without objectid');
165
- object.components.push({ objectId: a.objectid, path: a['p:path'], transform: parseTransform(a.transform) });
263
+ object.components.push({
264
+ objectId: a.objectid,
265
+ path: production(a, 'path'),
266
+ uuid: production(a, 'UUID'),
267
+ transform: parseTransform(a.transform),
268
+ });
269
+ break;
270
+ }
271
+ case 'alternative': {
272
+ if (!object)
273
+ throw new LoaderError(F, 'syntax', '<alternative> outside <object>');
274
+ if (!a.objectid)
275
+ throw new LoaderError(F, 'syntax', '<alternative> without objectid');
276
+ // The alternatives namespace's own attributes are unqualified, as its schema and sample write them.
277
+ object.alternatives.push({
278
+ objectId: a.objectid,
279
+ path: a.path ?? production(a, 'path'),
280
+ uuid: a.UUID ?? production(a, 'UUID'),
281
+ resolution: a.modelresolution ?? 'fullres',
282
+ });
166
283
  break;
167
284
  }
285
+ case 'build':
286
+ model.buildUUID = production(a, 'UUID');
287
+ break;
168
288
  case 'item':
169
289
  if (!a.objectid)
170
290
  throw new LoaderError(F, 'syntax', '<item> without objectid');
171
- model.items.push({ objectId: a.objectid, path: a['p:path'], transform: parseTransform(a.transform) });
291
+ model.items.push({
292
+ objectId: a.objectid,
293
+ path: production(a, 'path'),
294
+ uuid: production(a, 'UUID'),
295
+ transform: parseTransform(a.transform),
296
+ partNumber: a.partnumber,
297
+ });
172
298
  break;
173
299
  default:
174
300
  extension?.open?.(model, name, a);
175
301
  }
176
302
  },
177
303
  close(name) {
304
+ if (field) {
305
+ field--;
306
+ extension?.field?.close(model, name);
307
+ return;
308
+ }
178
309
  extension?.close?.(model, name);
310
+ if (name === 'slicestack')
311
+ sliceStacks--;
179
312
  if (name === 'object')
180
313
  object = undefined;
181
314
  else if (name === 'basematerials' || name === 'colorgroup')
@@ -209,24 +342,31 @@ export function cornerProperty(model, object, mesh, triangle, corner) {
209
342
  }
210
343
  const normalizePath = (path) => path.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase();
211
344
  /**
212
- * Parses a 3MF package (core specification, plus basematerials and the materials extension colorgroup, and
213
- * production extension `p:path` components). Build item and component
214
- * transforms are baked into the positions, which are converted to meters by default. The result has one
215
- * group per build item object and color; `colors` is present only when some triangle has per-corner colors.
345
+ * Parses a 3MF package (core specification, plus basematerials and the materials extension colorgroup, and the
346
+ * production extension: items and components in other model parts, UUIDs and alternative representations). Build item
347
+ * and component transforms are baked into the positions, which are converted to meters by default. The result has one
348
+ * group per build item object and color; `colors` is present only when some triangle has per-corner colors. A
349
+ * displacement mesh gives its base triangles, in groups marked `displaced`; a volumetric level set or a boolean shape
350
+ * throws `unsupported`.
216
351
  */
217
352
  export async function parse3MF(input, options = {}) {
218
353
  return read3MF(input, options);
219
354
  }
220
355
  /** The reader behind {@link parse3MF}, with the hooks `@margoengine/loaders/threemf-materials` uses. */
221
356
  export async function read3MF(input, options, extension) {
222
- const bytes = toBytes(input, F), limit = limits(options, F), maxDepth = options.maxDepth ?? 32;
357
+ const bytes = toBytes(input, F), limit = limits(options, F), maxDepth = options.maxDepth ?? 32, maxModelParts = options.maxModelParts ?? 65_535;
223
358
  if (!Number.isSafeInteger(maxDepth) || maxDepth < 0)
224
359
  throw new LoaderError(F, 'range', 'maxDepth must be a non-negative integer');
360
+ if (!Number.isSafeInteger(maxModelParts) || maxModelParts < 1)
361
+ throw new LoaderError(F, 'range', 'maxModelParts must be a positive integer');
225
362
  if (options.units !== undefined && options.units !== 'meters' && options.units !== 'file')
226
363
  throw new LoaderError(F, 'range', `units must be "meters" or "file"`);
364
+ if (!['fullres', 'lowres', 'obfuscated', undefined].includes(options.modelResolution))
365
+ throw new LoaderError(F, 'range', 'modelResolution must be "fullres", "lowres" or "obfuscated"');
227
366
  if (bytes.length < 4 || bytes[0] !== 0x50 || bytes[1] !== 0x4b)
228
367
  throw new LoaderError(F, 'header', 'not a ZIP package (missing PK signature)');
229
- const entries = readZipDirectory(bytes, options);
368
+ // A part is an entry, so the entry limit follows the part limit unless the caller sets it.
369
+ const entries = readZipDirectory(bytes, { ...options, maxEntries: options.maxEntries ?? 65_535 });
230
370
  const byPath = new Map();
231
371
  for (const entry of entries)
232
372
  byPath.set(normalizePath(entry.name), entry);
@@ -235,7 +375,11 @@ export async function read3MF(input, options, extension) {
235
375
  const entry = byPath.get(normalizePath(path));
236
376
  if (!entry)
237
377
  throw new LoaderError(F, 'syntax', `package part "${path.slice(0, 128)}" is missing`);
238
- return readZipEntry(bytes, entry, options);
378
+ const data = await readZipEntry(bytes, entry, options);
379
+ // The secure content extension's cipher files start `%3McF`.
380
+ if (data[0] === 0x25 && data[1] === 0x33 && data[2] === 0x4d && data[3] === 0x63 && data[4] === 0x46)
381
+ throw new LoaderError(F, 'unsupported', `package part "${path.slice(0, 128)}" is encrypted; parse3MFKeystore from @margoengine/loaders/threemf-secure reads its key data, and decrypting it is the caller's`);
382
+ return data;
239
383
  };
240
384
  let rootPath = '3D/3dmodel.model';
241
385
  if (byPath.has('_rels/.rels')) {
@@ -247,32 +391,32 @@ export async function read3MF(input, options, extension) {
247
391
  close() { },
248
392
  }, F);
249
393
  }
250
- const models = new Map();
394
+ const models = new Map(),
395
+ /** The package path of each model part. */
396
+ partPaths = new Map();
251
397
  const load = async (path) => {
252
398
  const key = normalizePath(path);
253
399
  let model = models.get(key);
254
400
  if (!model) {
255
- if (models.size >= 1024)
256
- throw new LoaderError(F, 'limit', 'too many model parts');
401
+ if (models.size >= maxModelParts)
402
+ throw new LoaderError(F, 'limit', `package names more than ${maxModelParts} model parts (maxModelParts)`);
257
403
  model = parseModel(decodeXML(await read(path)), limit, extension, options.external);
258
404
  models.set(key, model);
405
+ partPaths.set(model, '/' + byPath.get(key).name.replace(/^\/+/, ''));
259
406
  }
260
407
  return model;
261
408
  };
262
409
  const root = await load(rootPath);
263
- // Load every model part referenced through p:path before the synchronous build walk.
264
- const pending = [root];
265
- while (pending.length) {
266
- const model = pending.pop();
267
- const paths = [
268
- ...model.items.map((i) => i.path),
269
- ...[...model.objects.values()].flatMap((o) => o.components.map((c) => c.path)),
270
- ];
271
- for (const path of paths)
272
- if (path && !models.has(normalizePath(path)))
273
- pending.push(await load(path));
274
- }
275
- await extension?.ready?.(read, { models, loadModelPart: load });
410
+ /** The paths a model part's objects name, in components and alternatives. */
411
+ const named = (model) => [...model.objects.values()].flatMap((o) => [...o.components, ...o.alternatives, ...(o.boolean ? [o.boolean.base, ...o.boolean.operands] : [])].flatMap(({ path }) => (path ? [path] : [])));
412
+ // Load every model part the root names before the synchronous build walk. A part's own build is ignored.
413
+ for (const path of [...root.items.flatMap(({ path }) => (path ? [path] : [])), ...named(root)])
414
+ await load(path);
415
+ for (const model of models.values())
416
+ if (model !== root && named(model).length)
417
+ throw new LoaderError(F, 'syntax', `${partPaths.get(model).slice(0, 128)}: only the root model part may name another part (production extension 3.2)`);
418
+ const partPath = (model) => (model === root ? undefined : partPaths.get(model));
419
+ await extension?.ready?.(read, { models, loadModelPart: load, partPath });
276
420
  throwIfAborted(options.signal, F);
277
421
  const scale = options.units === 'file' ? 1 : THREEMF_UNITS[root.unit];
278
422
  const resolveColors = (model, object, mesh, t) => [0, 1, 2].map((k) => {
@@ -302,8 +446,17 @@ export async function read3MF(input, options, extension) {
302
446
  }
303
447
  }
304
448
  const positions = floats(), indices = uints(), colors = vertexColors ? floats() : undefined, groups = [];
449
+ /** The part number and UUID of the build item being emitted. */
450
+ let itemPartNumber, itemUUID;
451
+ /** What the production extension says of the object being emitted. */
452
+ let identity = {};
453
+ const wanted = options.modelResolution ?? 'fullres';
454
+ /** A built object that is a beam lattice and no triangles, so an empty result can say why. */
455
+ let latticeOnly;
305
456
  const emitMesh = (model, o, mesh, m) => {
306
457
  const vertexCount = mesh.vertices.length / 3, triangleCount = mesh.triangles.length / 3;
458
+ if (!triangleCount && o.beamLattice)
459
+ latticeOnly ??= o.id;
307
460
  if (!vertexCount && !triangleCount)
308
461
  return; // an empty mesh adds nothing; skip the per-instance bookkeeping
309
462
  const tri = mesh.triangles.array, source = mesh.vertices.array;
@@ -328,13 +481,13 @@ export async function read3MF(input, options, extension) {
328
481
  triangleColors.push(c);
329
482
  if (c[0])
330
483
  colored = true;
331
- const key = (c[0] ? c[0].join(',') : '') + suffix(t);
484
+ const own = mesh.flat ? mesh.flat[t] : c[0], key = (own ? own.join(',') : '') + suffix(t);
332
485
  let bucket = buckets.get(key);
333
486
  if (!bucket)
334
- buckets.set(key, (bucket = { color: c[0], triangles: [] }));
487
+ buckets.set(key, (bucket = { color: own, triangles: [] }));
335
488
  bucket.triangles.push(t);
336
489
  }
337
- const unweld = (!!colors && colored) || !!extension;
490
+ const unweld = (!!colors && colored) || (!!extension && !extension.welded);
338
491
  const base = positions.length / 3;
339
492
  if (base + (unweld ? triangleCount * 3 : vertexCount) > limit.maxVertices)
340
493
  throw new LoaderError(F, 'limit', `vertex count after instancing exceeds the limit of ${limit.maxVertices}`);
@@ -365,6 +518,24 @@ export async function read3MF(input, options, extension) {
365
518
  const group = { start, count: indices.length - start, objectId: o.id };
366
519
  if (o.name)
367
520
  group.name = o.name;
521
+ if (o.type !== 'model')
522
+ group.objectType = o.type;
523
+ if (o.partNumber !== undefined)
524
+ group.partNumber = o.partNumber;
525
+ if (o.displaced)
526
+ group.displaced = true;
527
+ if (itemPartNumber !== undefined)
528
+ group.itemPartNumber = itemPartNumber;
529
+ if (itemUUID !== undefined)
530
+ group.itemUUID = itemUUID;
531
+ if (identity.uuid !== undefined)
532
+ group.uuid = identity.uuid;
533
+ if (identity.componentUUID !== undefined)
534
+ group.componentUUID = identity.componentUUID;
535
+ if (identity.alternativeUUID !== undefined)
536
+ group.alternativeUUID = identity.alternativeUUID;
537
+ if (model !== root)
538
+ group.modelPath = partPaths.get(model);
368
539
  if (bucket.color)
369
540
  group.color = [...bucket.color];
370
541
  extension?.group(group, model, o, mesh, bucket.triangles[0]);
@@ -375,7 +546,7 @@ export async function read3MF(input, options, extension) {
375
546
  // Components may reuse an object many times per level: bound the expanded instances, not just the depth, or
376
547
  // fan-out^depth references to an empty object never finish (meshes are also bounded by the vertex limits).
377
548
  let instances = 0;
378
- const emit = (model, id, path, m, depth) => {
549
+ const emit = (model, id, path, m, depth, componentUUID) => {
379
550
  if (depth > maxDepth)
380
551
  throw new LoaderError(F, 'limit', `components nest deeper than ${maxDepth}`);
381
552
  if (++instances > MAX_INSTANCES)
@@ -385,22 +556,43 @@ export async function read3MF(input, options, extension) {
385
556
  throw new LoaderError(F, 'syntax', `object ${id.slice(0, 32)} references itself through its components`);
386
557
  if (o.mesh && o.components.length)
387
558
  throw new LoaderError(F, 'syntax', `object ${id.slice(0, 32)} has both a mesh and components`);
559
+ // Production alternatives: the first one of the resolution asked for stands in for the object, whose own content
560
+ // has the lowest priority.
561
+ const alternative = o.alternatives.find(({ resolution }) => resolution === wanted);
562
+ let [source, shown] = [owner, o];
563
+ if (alternative) {
564
+ [source, shown] = object(owner, alternative.objectId, alternative.path);
565
+ if (shown.alternatives.length)
566
+ throw new LoaderError(F, 'syntax', `alternative object ${shown.id.slice(0, 32)} has alternatives of its own`);
567
+ if (shown.mesh && shown.components.length)
568
+ throw new LoaderError(F, 'syntax', `object ${shown.id.slice(0, 32)} has both a mesh and components`);
569
+ }
570
+ // Core 3MF: an `other` mesh is never output, however it is reached; the type of an object of components is ignored.
571
+ if (shown.mesh && shown.type === 'other')
572
+ return;
573
+ if (shown.boolean && !extension?.booleans)
574
+ throw new LoaderError(F, 'unsupported', `object ${shown.id.slice(0, 32)} is a boolean shape; read the package with parse3MFBoolean from @margoengine/loaders/threemf-boolean`);
575
+ if (shown.levelSet && !extension?.levelSets)
576
+ throw new LoaderError(F, 'unsupported', `object ${shown.id.slice(0, 32)} is a volumetric level set; read the package with parse3MFVolumetric from @margoengine/loaders/threemf-volumetric`);
388
577
  visiting.add(o);
389
- extension?.instance?.(owner, o, m, scale, depth);
390
- if (o.mesh)
391
- emitMesh(owner, o, o.mesh, m);
392
- for (const component of o.components)
393
- emit(owner, component.objectId, component.path, compose(component.transform, m), depth + 1);
578
+ extension?.instance?.(source, shown, m, scale, depth);
579
+ identity = { uuid: o.uuid, componentUUID, alternativeUUID: alternative?.uuid };
580
+ if (shown.mesh)
581
+ emitMesh(source, shown, shown.mesh, m);
582
+ for (const component of shown.components)
583
+ emit(source, component.objectId, component.path, compose(component.transform, m), depth + 1, component.uuid);
394
584
  visiting.delete(o);
395
585
  };
396
586
  for (const item of root.items) {
397
- const [, o] = object(root, item.objectId, item.path);
398
- if (o.type === 'other')
399
- continue;
587
+ itemPartNumber = item.partNumber;
588
+ itemUUID = item.uuid;
400
589
  emit(root, item.objectId, item.path, item.transform, 0);
401
590
  }
402
- if (!indices.length && !extension?.hasGeometry?.())
591
+ if (!indices.length && !extension?.hasGeometry?.()) {
592
+ if (latticeOnly !== undefined)
593
+ throw new LoaderError(F, 'syntax', `the build contains no triangles: object ${latticeOnly.slice(0, 32)} is a beam lattice with none of its own; parse3MFEvaluated from @margoengine/loaders/threemf-evaluate makes them`);
403
594
  throw new LoaderError(F, 'syntax', 'the build contains no triangles');
595
+ }
404
596
  const result = {
405
597
  kind: 'mesh',
406
598
  positions: positions.result(),
@@ -409,6 +601,8 @@ export async function read3MF(input, options, extension) {
409
601
  unit: root.unit,
410
602
  metadata: root.metadata,
411
603
  };
604
+ if (root.buildUUID !== undefined)
605
+ result.buildUUID = root.buildUUID;
412
606
  if (colors)
413
607
  result.colors = colors.result();
414
608
  return result;
package/dist/types.d.ts CHANGED
@@ -8,6 +8,24 @@ export interface LoadedGroup {
8
8
  name?: string;
9
9
  /** Source object id (3MF). */
10
10
  objectId?: string;
11
+ /** The object's `type` when it is not `model`: `solidsupport`, `support` or `surface` (3MF). */
12
+ objectType?: string;
13
+ /** The `partnumber` of the mesh object (3MF). */
14
+ partNumber?: string;
15
+ /** The `partnumber` of the build item that placed it (3MF). */
16
+ itemPartNumber?: string;
17
+ /** The production extension's UUID of the mesh object, or of the object its alternative stands in for (3MF). */
18
+ uuid?: string;
19
+ /** The UUID of the build item that placed it (3MF production extension). */
20
+ itemUUID?: string;
21
+ /** The UUID of the component that placed the mesh object, when a component did (3MF production extension). */
22
+ componentUUID?: string;
23
+ /** The UUID of the alternative read in the object's place (3MF production extension). */
24
+ alternativeUUID?: string;
25
+ /** The model part the mesh came from, when it is not the root model part (3MF production extension). */
26
+ /** 3MF: the triangles are the base of a displacement mesh, whose surface the file moves. */
27
+ displaced?: boolean;
28
+ modelPath?: string;
11
29
  /** Uniform sRGB color in [0,1], `[r, g, b, a]`, when the file gives this group one color. */
12
30
  color?: [number, number, number, number];
13
31
  /** Raw source face properties, including scalar values and owned lists (PLY/OFF). */
@@ -1,3 +1,3 @@
1
- (function(){function e(e,t=new Set,n=new Set){let r=[e];for(;r.length;){let e=r.pop();if(e&&typeof e==`object`&&!n.has(e)){if(n.add(e),ArrayBuffer.isView(e))e.buffer instanceof ArrayBuffer&&t.add(e.buffer);else if(e instanceof ArrayBuffer)t.add(e);else if(typeof ImageBitmap<`u`&&e instanceof ImageBitmap)t.add(e);else if(e instanceof Map)for(let[t,n]of e)r.push(t,n);else for(let t in e)r.push(e[t])}}return t}function t(t){self.onmessage=async({data:n})=>{try{if(!n||typeof n!=`object`)throw TypeError(`Invalid parser worker job; post an object`);let r=await t(n);self.postMessage({result:r},[...e(r)])}catch(e){let t={name:e?.name??`Error`,message:e instanceof Error?e.message:String(e)};try{self.postMessage({error:{...e,...t}})}catch{self.postMessage({error:t})}}}}var n=class extends Error{constructor(e,t,n,r){super(`${e}: ${n}; see https://margoengine.com/errors#loader-${t}`,r),this.name=`LoaderError`,this.format=e,this.code=t,r?.status!==void 0&&(this.status=r.status),r?.retryAfter!==void 0&&(this.retryAfter=r.retryAfter)}},r=8e6,i=16e6;function a(e,t){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new n(t,`range`,`expected an ArrayBuffer or Uint8Array`)}function o(e,t){let a=(e,r,i)=>{if(e===void 0)return r;if(!Number.isSafeInteger(e)||e<0)throw new n(t,`range`,`${i} must be a non-negative integer`);return e};return{maxVertices:a(e?.maxVertices,r,`maxVertices`),maxTriangles:a(e?.maxTriangles,i,`maxTriangles`)}}function s(e,t){if(e?.aborted)throw new n(t,`aborted`,`aborted`)}var c;function l(){c=new Int32Array(2048);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=t&1?3988292384^t>>>1:t>>>1;c[e]=t}for(let e=0;e<256;e++)for(let t=1;t<8;t++){let n=c[(t-1)*256+e];c[t*256+e]=n>>>8^c[n&255]}return c}function u(e,t=0){let n=c??l(),r=e.length,i=r-(r&7),a=~t,o=0;for(;o<i;o+=8)a^=e[o]|e[o+1]<<8|e[o+2]<<16|e[o+3]<<24,a=n[1792+(a&255)]^n[1536+(a>>>8&255)]^n[1280+(a>>>16&255)]^n[1024+(a>>>24)]^n[768+e[o+4]]^n[512+e[o+5]]^n[256+e[o+6]]^n[e[o+7]];for(;o<r;o++)a=n[(a^e[o])&255]^a>>>8;return~a>>>0}var d={deflate:[120,156,3,0,0,0,0,1],"deflate-raw":[3,0],gzip:[31,139,8,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0]},f=new Map;async function p(e,t){try{return await new Response(new Blob([e]).stream().pipeThrough(new DecompressionStream(t))).arrayBuffer(),!0}catch{return!1}}function m(e){if(!(e in d))throw TypeError(`format must be deflate, deflate-raw or gzip (got ${e})`);let t=f.get(e);return t||(t=p(new Uint8Array([...d[e],0]),e),f.set(e,t)),t}async function h(e,t){return!await m(t)||e.byteLength===0?!1:p(e.subarray(0,e.byteLength-1),t)}var g=`ZIP`,_=`ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`,v=new TextDecoder;function y(e,t){if(t&2048||e.every(e=>e<128))return v.decode(e);let n=``;for(let t of e)n+=t<128?String.fromCharCode(t):_[t-128];return n}function b(e,t={}){let r=a(e,g),i=t.maxEntries??1e4;if(s(t.signal,g),Number.isNaN(i))throw new n(g,`range`,`maxEntries must not be NaN`);let o=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.length<22)throw new n(g,`truncated`,`file is too small to be a ZIP archive`);let c=-1;for(let e=r.length-22,t=Math.max(0,r.length-22-65535);e>=t;e--)if(o.getUint32(e,!0)===101010256&&e+22+o.getUint16(e+20,!0)<=r.length){c=e;break}if(c<0)throw new n(g,`zip`,`end of central directory not found (not a ZIP archive or truncated)`);let l=o.getUint16(c+4,!0),u=o.getUint16(c+6,!0),d=o.getUint16(c+10,!0),f=o.getUint32(c+12,!0),p=o.getUint32(c+16,!0);if(d===65535||f===4294967295||p===4294967295)throw new n(g,`unsupported`,`ZIP64 archives are not supported`);if(l!==0||u!==0)throw new n(g,`unsupported`,`multi-disk archives are not supported`);if(d>i)throw new n(g,`limit`,`archive has ${d} entries, more than the limit of ${i}`);if(p+f>c)throw new n(g,`zip`,`central directory lies outside the archive`);let m=[],h=p;for(let e=0;e<d;e++){if(h+46>p+f||o.getUint32(h,!0)!==33639248)throw new n(g,`zip`,`central directory entry ${e} is corrupt`);let t=o.getUint16(h+8,!0),i=o.getUint16(h+10,!0),a=o.getUint16(h+28,!0),s=o.getUint16(h+30,!0),c=o.getUint16(h+32,!0);if(h+46+a+s+c>p+f)throw new n(g,`zip`,`central directory entry ${e} name, extra field or comment overflows`);let l={name:y(r.subarray(h+46,h+46+a),t),method:i,crc32:o.getUint32(h+16,!0),compressedSize:o.getUint32(h+20,!0),size:o.getUint32(h+24,!0),headerOffset:o.getUint32(h+42,!0)};if(t&1)throw new n(g,`unsupported`,`entry "${l.name}" is encrypted`);if(l.compressedSize===4294967295||l.size===4294967295||l.headerOffset===4294967295)throw new n(g,`unsupported`,`ZIP64 entries are not supported`);m.push(l),h+=46+a+s+c}return m}async function x(e,t,r,i,a=`deflate-raw`,o=g){if(typeof DecompressionStream!=`function`)throw new n(o,`unsupported`,`DecompressionStream is not available in this runtime`);let s=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(a)).getReader(),c=new Uint8Array(t),l=0;try{for(;;){if(i?.aborted)throw new n(o,`aborted`,`aborted`);let{done:e,value:a}=await s.read();if(e)break;if(l+a.length>t)throw new n(o,`zip`,`${r} inflates past its declared size of ${t} bytes`);c.set(a,l),l+=a.length}}catch(e){throw s.cancel().catch(()=>{}),e instanceof n?e:new n(o,`zip`,`${r} has corrupt deflate data (${e?.message??e})`)}if(l!==t)throw new n(o,`zip`,`${r} inflated to ${l} bytes, expected ${t}`);if(await h(e,a))throw new n(o,`zip`,`${r} has corrupt deflate data (data after the end of the stream)`);return c}async function S(e,t,r={}){let i=a(e,g),o=r.maxEntryBytes??536870912;if(s(r.signal,g),Number.isNaN(o))throw new n(g,`range`,`maxEntryBytes must not be NaN`);if(t.size>o)throw new n(g,`limit`,`entry "${t.name}" is ${t.size} bytes, more than the limit of ${o}`);let c=r.maxRatio??200;if(!(c>=1))throw new n(g,`range`,`maxRatio must be at least 1`);if(t.method===8&&t.size>1<<20&&t.size>t.compressedSize*c)throw new n(g,`limit`,`entry "${t.name}" expands ${t.compressedSize} bytes to ${t.size}, more than ${c}x (raise maxRatio)`);let l=new DataView(i.buffer,i.byteOffset,i.byteLength),d=t.headerOffset;if(d+30>i.length||l.getUint32(d,!0)!==67324752)throw new n(g,`zip`,`local header of "${t.name}" is missing`);let f=d+30+l.getUint16(d+26,!0)+l.getUint16(d+28,!0),p=f+t.compressedSize;if(p>i.length)throw new n(g,`truncated`,`data of "${t.name}" runs past the end of the archive`);let m=i.subarray(f,p),h;if(t.method===0){if(t.compressedSize!==t.size)throw new n(g,`zip`,`stored entry "${t.name}" has mismatched sizes`);h=m}else if(t.method===8)h=await x(m,t.size,`entry "${t.name}"`,r.signal);else throw new n(g,`unsupported`,`entry "${t.name}" uses compression method ${t.method}; only stored and deflate are supported`);if(u(h)!==t.crc32)throw new n(g,`zip`,`entry "${t.name}" fails its CRC-32 check`);return h}function C(e,t,n){for(let r=0;r+2<t.length;r+=3){let i=t[r]*3,a=t[r+1]*3,o=t[r+2]*3,s=e[a]-e[i],c=e[a+1]-e[i+1],l=e[a+2]-e[i+2],u=e[o]-e[i],d=e[o+1]-e[i+1],f=e[o+2]-e[i+2],p=c*f-l*d,m=l*u-s*f,h=s*d-c*u;for(let e of[i,a,o])n[e]+=p,n[e+1]+=m,n[e+2]+=h}return n}function w(e,t){let n=C(e,t,new Float64Array(e.length)),r=new Float32Array(e.length);for(let e=0;e<r.length;e+=3){let t=Math.hypot(n[e],n[e+1],n[e+2]);t>0&&Number.isFinite(t)?(r[e]=n[e]/t,r[e+1]=n[e+1]/t,r[e+2]=n[e+2]/t):r[e+2]=1}return r}function T(e,t,n=new Float64Array(16)){for(let r=0;r<4;r++)for(let i=0;i<4;i++)n[r*4+i]=e[i]*t[r*4]+e[4+i]*t[r*4+1]+e[8+i]*t[r*4+2]+e[12+i]*t[r*4+3];return n}function E(e,t=new Float64Array(16)){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=n*s-r*o,y=n*c-i*o,b=n*l-a*o,x=r*c-i*s,S=r*l-a*s,C=i*l-a*c,w=u*h-d*m,T=u*g-f*m,E=u*_-p*m,D=d*g-f*h,O=d*_-p*h,k=f*_-p*g,A=v*k-y*O+b*D+x*E-S*T+C*w;if(!A||!Number.isFinite(A))return null;let j=1/A;return t[0]=(s*k-c*O+l*D)*j,t[1]=(i*O-r*k-a*D)*j,t[2]=(h*C-g*S+_*x)*j,t[3]=(f*S-d*C-p*x)*j,t[4]=(c*E-o*k-l*T)*j,t[5]=(n*k-i*E+a*T)*j,t[6]=(g*b-m*C-_*y)*j,t[7]=(u*C-f*b+p*y)*j,t[8]=(o*O-s*E+l*w)*j,t[9]=(r*E-n*O-a*w)*j,t[10]=(m*S-h*b+_*v)*j,t[11]=(d*b-u*S-p*v)*j,t[12]=(s*T-o*D-c*w)*j,t[13]=(n*D-r*T+i*w)*j,t[14]=(h*y-m*x-g*v)*j,t[15]=(u*x-d*y+f*v)*j,t}var D=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,O=`USD`;function k(e,t){throw new n(O,e,t)}var A={a:`\x07`,b:`\b`,f:`\f`,n:`
1
+ (function(){function e(e,t=new Set,n=new Set){let r=[e];for(;r.length;){let e=r.pop();if(e&&typeof e==`object`&&!n.has(e)){if(n.add(e),ArrayBuffer.isView(e))e.buffer instanceof ArrayBuffer&&t.add(e.buffer);else if(e instanceof ArrayBuffer)t.add(e);else if(typeof ImageBitmap<`u`&&e instanceof ImageBitmap)t.add(e);else if(e instanceof Map)for(let[t,n]of e)r.push(t,n);else for(let t in e)r.push(e[t])}}return t}function t(t){self.onmessage=async({data:n})=>{try{if(!n||typeof n!=`object`)throw TypeError(`Invalid parser worker job; post an object`);let r=await t(n);self.postMessage({result:r},[...e(r)])}catch(e){let t={name:e?.name??`Error`,message:e instanceof Error?e.message:String(e)};try{self.postMessage({error:{...e,...t}})}catch{self.postMessage({error:t})}}}}var n=class extends Error{constructor(e,t,n,r){super(`${e}: ${n}; see https://margoengine.com/errors#loader-${t}`,r),this.name=`LoaderError`,this.format=e,this.code=t,r?.status!==void 0&&(this.status=r.status),r?.retryAfter!==void 0&&(this.retryAfter=r.retryAfter)}},r=8e6,i=16e6;function a(e,t){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new n(t,`range`,`expected an ArrayBuffer or Uint8Array`)}function o(e,t){let a=(e,r,i)=>{if(e===void 0)return r;if(!Number.isSafeInteger(e)||e<0)throw new n(t,`range`,`${i} must be a non-negative integer`);return e};return{maxVertices:a(e?.maxVertices,r,`maxVertices`),maxTriangles:a(e?.maxTriangles,i,`maxTriangles`)}}function s(e,t){if(e?.aborted)throw new n(t,`aborted`,`aborted`)}var c;function l(){c=new Int32Array(2048);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=t&1?3988292384^t>>>1:t>>>1;c[e]=t}for(let e=0;e<256;e++)for(let t=1;t<8;t++){let n=c[(t-1)*256+e];c[t*256+e]=n>>>8^c[n&255]}return c}function u(e,t=0){let n=c??l(),r=e.length,i=r-(r&7),a=~t,o=0;for(;o<i;o+=8)a^=e[o]|e[o+1]<<8|e[o+2]<<16|e[o+3]<<24,a=n[1792+(a&255)]^n[1536+(a>>>8&255)]^n[1280+(a>>>16&255)]^n[1024+(a>>>24)]^n[768+e[o+4]]^n[512+e[o+5]]^n[256+e[o+6]]^n[e[o+7]];for(;o<r;o++)a=n[(a^e[o])&255]^a>>>8;return~a>>>0}var d={deflate:[120,156,3,0,0,0,0,1],"deflate-raw":[3,0],gzip:[31,139,8,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0]},f=new Map;async function p(e,t){let n=new Blob([e]).stream().pipeThrough(new DecompressionStream(t)).getReader();try{for(;!(await n.read()).done;);return!0}catch{return!1}}function m(e){if(!(e in d))throw TypeError(`format must be deflate, deflate-raw or gzip (got ${e})`);let t=f.get(e);return t||(t=p(new Uint8Array([...d[e],0]),e),f.set(e,t)),t}async function h(e,t){return!await m(t)||e.byteLength===0?!1:p(e.subarray(0,e.byteLength-1),t)}var g=`ZIP`,_=`ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`,v=new TextDecoder;function y(e,t){if(t&2048||e.every(e=>e<128))return v.decode(e);let n=``;for(let t of e)n+=t<128?String.fromCharCode(t):_[t-128];return n}function b(e,t={}){let r=a(e,g),i=t.maxEntries??1e4;if(s(t.signal,g),Number.isNaN(i))throw new n(g,`range`,`maxEntries must not be NaN`);let o=new DataView(r.buffer,r.byteOffset,r.byteLength);if(r.length<22)throw new n(g,`truncated`,`file is too small to be a ZIP archive`);let c=-1;for(let e=r.length-22,t=Math.max(0,r.length-22-65535);e>=t;e--)if(o.getUint32(e,!0)===101010256&&e+22+o.getUint16(e+20,!0)<=r.length){c=e;break}if(c<0)throw new n(g,`zip`,`end of central directory not found (not a ZIP archive or truncated)`);let l=o.getUint16(c+4,!0),u=o.getUint16(c+6,!0),d=o.getUint16(c+10,!0),f=o.getUint32(c+12,!0),p=o.getUint32(c+16,!0);if(d===65535||f===4294967295||p===4294967295)throw new n(g,`unsupported`,`ZIP64 archives are not supported`);if(l!==0||u!==0)throw new n(g,`unsupported`,`multi-disk archives are not supported`);if(d>i)throw new n(g,`limit`,`archive has ${d} entries, more than the limit of ${i}`);if(p+f>c)throw new n(g,`zip`,`central directory lies outside the archive`);let m=[],h=p;for(let e=0;e<d;e++){if(h+46>p+f||o.getUint32(h,!0)!==33639248)throw new n(g,`zip`,`central directory entry ${e} is corrupt`);let t=o.getUint16(h+8,!0),i=o.getUint16(h+10,!0),a=o.getUint16(h+28,!0),s=o.getUint16(h+30,!0),c=o.getUint16(h+32,!0);if(h+46+a+s+c>p+f)throw new n(g,`zip`,`central directory entry ${e} name, extra field or comment overflows`);let l={name:y(r.subarray(h+46,h+46+a),t),method:i,crc32:o.getUint32(h+16,!0),compressedSize:o.getUint32(h+20,!0),size:o.getUint32(h+24,!0),headerOffset:o.getUint32(h+42,!0)};if(t&1)throw new n(g,`unsupported`,`entry "${l.name}" is encrypted`);if(l.compressedSize===4294967295||l.size===4294967295||l.headerOffset===4294967295)throw new n(g,`unsupported`,`ZIP64 entries are not supported`);m.push(l),h+=46+a+s+c}return m}async function x(e,t,r,i,a=`deflate-raw`,o=g){if(typeof DecompressionStream!=`function`)throw new n(o,`unsupported`,`DecompressionStream is not available in this runtime`);let s=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(a)).getReader(),c=new Uint8Array(t),l=0;try{for(;;){if(i?.aborted)throw new n(o,`aborted`,`aborted`);let{done:e,value:a}=await s.read();if(e)break;if(l+a.length>t)throw new n(o,`zip`,`${r} inflates past its declared size of ${t} bytes`);c.set(a,l),l+=a.length}}catch(e){throw s.cancel().catch(()=>{}),e instanceof n?e:new n(o,`zip`,`${r} has corrupt deflate data (${e?.message??e})`)}if(l!==t)throw new n(o,`zip`,`${r} inflated to ${l} bytes, expected ${t}`);if(await h(e,a))throw new n(o,`zip`,`${r} has corrupt deflate data (data after the end of the stream)`);return c}async function S(e,t,r={}){let i=a(e,g),o=r.maxEntryBytes??536870912;if(s(r.signal,g),Number.isNaN(o))throw new n(g,`range`,`maxEntryBytes must not be NaN`);if(t.size>o)throw new n(g,`limit`,`entry "${t.name}" is ${t.size} bytes, more than the limit of ${o}`);let c=r.maxRatio??200;if(!(c>=1))throw new n(g,`range`,`maxRatio must be at least 1`);if(t.method===8&&t.size>1<<20&&t.size>t.compressedSize*c)throw new n(g,`limit`,`entry "${t.name}" expands ${t.compressedSize} bytes to ${t.size}, more than ${c}x (raise maxRatio)`);let l=new DataView(i.buffer,i.byteOffset,i.byteLength),d=t.headerOffset;if(d+30>i.length||l.getUint32(d,!0)!==67324752)throw new n(g,`zip`,`local header of "${t.name}" is missing`);let f=d+30+l.getUint16(d+26,!0)+l.getUint16(d+28,!0),p=f+t.compressedSize;if(p>i.length)throw new n(g,`truncated`,`data of "${t.name}" runs past the end of the archive`);let m=i.subarray(f,p),h;if(t.method===0){if(t.compressedSize!==t.size)throw new n(g,`zip`,`stored entry "${t.name}" has mismatched sizes`);h=m}else if(t.method===8)h=await x(m,t.size,`entry "${t.name}"`,r.signal);else throw new n(g,`unsupported`,`entry "${t.name}" uses compression method ${t.method}; only stored and deflate are supported`);if(u(h)!==t.crc32)throw new n(g,`zip`,`entry "${t.name}" fails its CRC-32 check`);return h}function C(e,t,n){for(let r=0;r+2<t.length;r+=3){let i=t[r]*3,a=t[r+1]*3,o=t[r+2]*3,s=e[a]-e[i],c=e[a+1]-e[i+1],l=e[a+2]-e[i+2],u=e[o]-e[i],d=e[o+1]-e[i+1],f=e[o+2]-e[i+2],p=c*f-l*d,m=l*u-s*f,h=s*d-c*u;for(let e of[i,a,o])n[e]+=p,n[e+1]+=m,n[e+2]+=h}return n}function w(e,t){let n=C(e,t,new Float64Array(e.length)),r=new Float32Array(e.length);for(let e=0;e<r.length;e+=3){let t=Math.hypot(n[e],n[e+1],n[e+2]);t>0&&Number.isFinite(t)?(r[e]=n[e]/t,r[e+1]=n[e+1]/t,r[e+2]=n[e+2]/t):r[e+2]=1}return r}function T(e,t,n=new Float64Array(16)){for(let r=0;r<4;r++)for(let i=0;i<4;i++)n[r*4+i]=e[i]*t[r*4]+e[4+i]*t[r*4+1]+e[8+i]*t[r*4+2]+e[12+i]*t[r*4+3];return n}function E(e,t=new Float64Array(16)){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=n*s-r*o,y=n*c-i*o,b=n*l-a*o,x=r*c-i*s,S=r*l-a*s,C=i*l-a*c,w=u*h-d*m,T=u*g-f*m,E=u*_-p*m,D=d*g-f*h,O=d*_-p*h,k=f*_-p*g,A=v*k-y*O+b*D+x*E-S*T+C*w;if(!A||!Number.isFinite(A))return null;let j=1/A;return t[0]=(s*k-c*O+l*D)*j,t[1]=(i*O-r*k-a*D)*j,t[2]=(h*C-g*S+_*x)*j,t[3]=(f*S-d*C-p*x)*j,t[4]=(c*E-o*k-l*T)*j,t[5]=(n*k-i*E+a*T)*j,t[6]=(g*b-m*C-_*y)*j,t[7]=(u*C-f*b+p*y)*j,t[8]=(o*O-s*E+l*w)*j,t[9]=(r*E-n*O-a*w)*j,t[10]=(m*S-h*b+_*v)*j,t[11]=(d*b-u*S-p*v)*j,t[12]=(s*T-o*D-c*w)*j,t[13]=(n*D-r*T+i*w)*j,t[14]=(h*y-m*x-g*v)*j,t[15]=(u*x-d*y+f*v)*j,t}var D=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,O=`USD`;function k(e,t){throw new n(O,e,t)}var A={a:`\x07`,b:`\b`,f:`\f`,n:`
2
2
  `,r:`\r`,t:` `,v:`\v`},j=()=>new Float64Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function M(e,t){return(!Array.isArray(e)||e.some(e=>typeof e!=`number`||!Number.isFinite(e))||t!==void 0&&e.length!==t)&&k(`syntax`,`expected a numeric tuple or array`),e}function N(e){return e.some(e=>!Number.isFinite(e)||e<0||e>1)&&k(`range`,`invalid color or opacity primvar values`),e}function P(e,t,n,r,i){let a=`primvars:${t}`,o=e.attrs.get(a);if(o===void 0)return{values:N(i),varying:!1};let s=e.properties.get(a),c=s?.get(`interpolation`)??`constant`;c!==`constant`&&c!==`vertex`&&k(`unsupported`,`unsupported color primvar interpolation ${c}`),(s?.get(`elementSize`)??1)!==1&&k(`unsupported`,`color primvar elementSize must be 1`),Array.isArray(o)||k(`syntax`,`color primvar must be an array`);let l=n===1?M(o):o.flatMap(e=>M(e,n));N(l);let u=e.attrs.get(`${a}:indices`),d=u===void 0?void 0:M(u),f=c===`vertex`?r:1;if((d?.length??l.length/n)!==f&&k(`syntax`,`color primvar length does not match interpolation`),d){let e=[];for(let t of d){(!Number.isSafeInteger(t)||t<0||t>=l.length/n)&&k(`range`,`color primvar index outside values`);for(let r=0;r<n;r++)e.push(l[t*n+r])}return{values:e,varying:c===`vertex`}}return{values:l,varying:c===`vertex`}}function F(e,t,n,r,i,a,o){let s=t.attrs.get(`inputs:${n}.connect`);if(s===void 0){let e=t.attrs.get(`inputs:${n}`);return{values:N(e===void 0?o:r===1&&typeof e==`number`?[e]:M(e,r)),varying:!1}}(!s||typeof s!=`object`||Array.isArray(s)||!(`path`in s)||!s.path.endsWith(`.outputs:result`))&&k(`unsupported`,`color connections require a UsdPrimvarReader result`);let c=a.get(s.path.slice(0,-15)),l=c?.attrs.get(`inputs:varname`);(!c||c.attrs.get(`info:id`)!==`UsdPrimvarReader_float${r===1?``:r}`||typeof l!=`string`||c.attrs.has(`inputs:varname.connect`)||c.attrs.has(`inputs:fallback.connect`))&&k(`unsupported`,`color connections require an unconnected matching UsdPrimvarReader`);let u=c.attrs.get(`inputs:fallback`);return P(e,l,r,i,u===void 0?Array(r).fill(0):r===1&&typeof u==`number`?[u]:M(u,r))}function I(e,t,n){let r=e.attrs.get(`xformOpOrder`);if(r===void 0)return[...e.attrs.keys()].some(e=>e.startsWith(`xformOp:`))&&k(`unsupported`,`transforms require xformOpOrder`),t;(!Array.isArray(r)||r.some(e=>typeof e!=`string`))&&k(`syntax`,`invalid xformOpOrder`);let i=r.lastIndexOf(`!resetXformStack!`),a=i<0?t:n,o=j();for(let t of r.slice(i+1)){let n=t.startsWith(`!invert!`),r=n?t.slice(8):t,i=r.split(`:`)[1]??``,a=e.attrs.get(r);r.startsWith(`xformOp:`)||k(`syntax`,`invalid xformOpOrder entry ${t}`),a===void 0&&k(`syntax`,`xformOpOrder names ${r}, which is not authored`);let s=j();if(i===`transform`)(!Array.isArray(a)||a.length!==4)&&k(`syntax`,`expected a 4x4 transform`),s=new Float64Array(a.flatMap(e=>M(e,4))),(s[3]!==0||s[7]!==0||s[11]!==0||s[15]!==1)&&k(`unsupported`,`only affine transforms are supported`);else if(i===`translate`)s.set(M(a,3),12);else if(i===`scale`){let e=M(a,3);s[0]=e[0],s[5]=e[1],s[10]=e[2]}else if(i===`orient`){let[e,t,n,r]=M(a,4),i=Math.hypot(e,t,n,r);i||k(`range`,`orient quaternion has zero length`);let[o,c,l,u]=[e/i,t/i,n/i,r/i];s.set([1-2*(l*l+u*u),2*(c*l+o*u),2*(c*u-o*l),0,2*(c*l-o*u),1-2*(c*c+u*u),2*(l*u+o*c),0,2*(c*u+o*l),2*(l*u-o*c),1-2*(c*c+l*l),0])}else if(/^rotate([XYZ]|XYZ|XZY|YXZ|YZX|ZXY|ZYX)$/.test(i)){let e=i.slice(6),t=e.length===1?[typeof a==`number`?a:M(a,1)[0]]:M(a,3);t.every(Number.isFinite)||k(`syntax`,`invalid ${r} angle`);for(let n=0;n<e.length;n++){let r=`XYZ`.indexOf(e[n]),i=t[n]*Math.PI/180,a=j(),o=(r+1)%3,c=(r+2)%3,l=Math.cos(i),u=Math.sin(i);a[o*4+o]=l,a[c*4+c]=l,a[o*4+c]=u,a[c*4+o]=-u,s=T(a,s,new Float64Array(16))}}else k(`unsupported`,`unsupported transform ${r}`);n&&(s=E(s)??k(`range`,`${r} cannot be inverted`)),o=T(o,s,new Float64Array(16))}return T(a,o,new Float64Array(16))}function L(e,t={}){let n=t.maxDepth??32;(!Number.isSafeInteger(n)||n<1||n>64)&&k(`range`,`maxDepth must be 1..64`),e.startsWith(`#usda 1.0`)||k(`syntax`,`expected #usda 1.0`);let r=/\s+|#[^\n]*|"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|<[^>]*>|@[\s\S]*?@|[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[A-Za-z_!][\w:!.]*|[{}()[\]=,;]/y,i=0,a,o=0;function c(){if(a)return a;let t=!1;for(;i<e.length;){r.lastIndex=i;let n=r.exec(e);n||k(`syntax`,`invalid token at offset ${i}`),i=r.lastIndex;let o=n[0];if(/^\s|^#/.test(o))t||=o.includes(`
3
3
  `);else return a={text:o,newLine:t}}return a={text:``,newLine:t}}let l=()=>{let e=c().text;return a=void 0,e},u=e=>{let t=e.startsWith(`"""`)||e.startsWith(`'''`)?3:1,n=e.slice(t,-t),r=``,i=0,a;for(;(a=n.indexOf(`\\`,i))>=0;){r+=n.slice(i,a);let e=[];for(;;){let t=n[a+1]===`x`?/^[0-9a-fA-F]{1,2}/.exec(n.slice(a+2,a+4))?.[0]:void 0,r=/^[0-7]{1,3}/.exec(n.slice(a+1,a+4))?.[0];if(t!==void 0)e.push(parseInt(t,16)),a+=2+t.length;else if(r!==void 0)e.push(parseInt(r,8)&255),a+=1+r.length;else break;if(n[a]!==`\\`)break}if(e.length)r+=new TextDecoder().decode(new Uint8Array(e));else{let e=n[a+1]??`\\`;r+=A[e]??e,a+=2}i=a}return r+n.slice(i)},d=e=>e[0]===`"`||e[0]===`'`,f=e=>{l()!==e&&k(`syntax`,`expected ${e}`)},p=e=>{let t=e?Number(e):NaN;return Number.isFinite(t)||k(`range`,`non-finite number`),++o>16e6&&k(`limit`,`numeric values exceed 16 million`),t};function m(r=0){r>n&&k(`limit`,`nested value exceeds maxDepth`);let o=l();if(o===`[`||o===`(`){let t=o===`[`?`]`:`)`,n=e.indexOf(t,i);if(o===`[`&&!a&&n>=0&&/^[\s\d.eE+\-(),]*$/.test(e.slice(i,n))&&!/\([^)]*\(/.test(e.slice(i,n))){let t=e.slice(i,n),r=t.includes(`(`)?[...t.matchAll(/\(([^)]*)\)/g)].map(e=>e[1].split(`,`).map(e=>p(e.trim()))):t.trim()?t.split(`,`).map(e=>p(e.trim())):[];return i=n+1,r}let s=[];for(;c().text!==t;)c().text||k(`syntax`,`unterminated array`),s.push(m(r+1)),c().text===`,`?l():c().text!==t&&k(`syntax`,`expected comma`);return l(),s}if(o===`{`){let e=1;for(;e;){let t=l();t||k(`syntax`,`unterminated dictionary`),e+=t===`{`?1:t===`}`?-1:0}return``}if(d(o))return u(o);if(o.startsWith(`<`))return{path:o.slice(1,-1)};if(o.startsWith(`@`))return t.assets||k(`unsupported`,`external assets and textures are unsupported`),{asset:o.replace(/^@+|@+$/g,``)};if(o===`true`||o===`false`)return o===`true`;if(/^[+-]?(\d|\.\d)/.test(o))return p(o);if(o===`None`)return``;k(`unsupported`,`unsupported value ${o}`)}function h(){let e=new Map;for(f(`(`);c().text!==`)`;){let t=l();t||k(`syntax`,`unterminated metadata`),[`prepend`,`append`,`add`,`delete`,`reorder`].includes(t)&&(t=l()),d(t)?e.set(`doc`,u(t)):t===`references`?(f(`=`),c().text.startsWith(`<`)||k(`unsupported`,`USD composition references to other files is unsupported`),e.set(t,m()),(c().text===`,`||c().text===`;`)&&l()):([`payload`,`subLayers`,`variants`,`variantSets`,`inherits`,`specializes`,`instanceable`,`relocates`].includes(t)&&k(`unsupported`,`USD composition ${t} is unsupported`),f(`=`),e.set(t,m()),(c().text===`,`||c().text===`;`)&&l())}return l(),e}let g=new Map,_=new Map;function v(e,r){r>n&&k(`limit`,`prim hierarchy exceeds maxDepth`);let i=l();i!==`def`&&i!==`class`&&!(t.skipOver&&i===`over`)&&k(`unsupported`,`only defined static prims are supported`);let a=l(),o=d(a)?u(a):m();d(a)&&(a=`Xform`),typeof o!=`string`&&k(`syntax`,`prim name must be a string`);let p=`${e}/${o}`,y=new Map,b=new Map,x=c().text===`(`?h():new Map,S=[];(g.has(p)||_.has(p))&&k(`syntax`,`duplicate prim path`);let C={type:a,name:o,path:p,attrs:y,metadata:x,properties:b,children:S};for(i===`def`?g.set(p,C):i===`class`&&_.set(p,C),f(`{`);c().text!==`}`;){s(t.signal,O);let e=c().text;if(e===`def`||e===`class`||t.skipOver&&e===`over`){let e=v(p,r+1);e&&S.push(e);continue}e||k(`syntax`,`unterminated prim`),(e===`over`||e===`variantSet`)&&k(`unsupported`,`USD composition ${e} is unsupported`);let n=[];for(;c().text!==`=`&&!(n.length>=2&&(c().newLine||c().text===`}`||c().text===`(`));)(!c().text||n.length>8)&&k(`syntax`,`invalid property declaration`),n.push(l());let i=n[n.length-1];i||k(`syntax`,`missing property name`),i.includes(`timeSamples`)&&k(`unsupported`,`animated USD attributes are unsupported`),c().text===`=`&&(l(),y.has(i)&&k(`syntax`,`duplicate property`),y.set(i,m())),c().text===`(`&&b.set(i,h()),c().text===`;`&&l()}return l(),i===`def`?C:void 0}let y=c().text===`(`?h():new Map,b=[];for(;c().text;){let e=v(``,1);e&&b.push(e)}for(let e of g.values()){let t=e.metadata.get(`references`);if(t===void 0)continue;let n=t.path,r=n===void 0?void 0:_.get(n)??g.get(n);r||k(`syntax`,`reference target ${n} not found`),(r.children.length||r.metadata.has(`references`))&&k(`unsupported`,`USD composition references to a prim with children or references is unsupported`);for(let[t,n]of r.attrs)e.attrs.has(t)||e.attrs.set(t,n);for(let[t,n]of r.properties)e.properties.has(t)||e.properties.set(t,n);e.metadata.delete(`references`)}return{metadata:y,roots:b,prims:g}}function R(e,t={}){s(t.signal,O);let n=o(t,O),r=t.maxEntryBytes??67108864;(!Number.isSafeInteger(r)||r<0)&&k(`range`,`invalid maxEntryBytes`);let i=typeof e==`string`?new TextEncoder().encode(e):a(e,O);i.length>r&&k(`limit`,`USDA exceeds maxEntryBytes`);let c;try{c=new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}catch{k(`syntax`,`invalid UTF-8`)}t.units!==void 0&&t.units!==`meters`&&t.units!==`file`&&k(`range`,`units must be meters or file`);let{metadata:l,roots:u,prims:d}=L(c,{maxDepth:t.maxDepth,signal:t.signal}),f=0,p=l.get(`metersPerUnit`)??.01,m=l.get(`upAxis`)??`Y`;(typeof p!=`number`||p<=0||!Number.isFinite(p))&&k(`range`,`invalid metersPerUnit`),m!==`Y`&&m!==`Z`&&k(`unsupported`,`only Y and Z up stages are supported`);let h=t.units===`file`?1:p,g=j();g[0]=h,g[5]=h,g[10]=h,m===`Z`&&(g[5]=0,g[10]=0,g[6]=-h,g[9]=h);let _=[],v=[],y=[],b=[];function x(e,t,r=!1,i){if(r||=e.attrs.get(`visibility`)===`invisible`||e.attrs.get(`purpose`)===`guide`||e.metadata.get(`active`)===!1,r)return;i=e.attrs.get(`material:binding`)??i;let a=I(e,t,g);if(e.type===`Mesh`){(e.attrs.get(`subdivisionScheme`)??`catmullClark`)!==`none`&&k(`unsupported`,`subdivision surfaces are unsupported`);let t=e.attrs.get(`holeIndices`);t!==void 0&&(!Array.isArray(t)||t.length)&&k(`unsupported`,`mesh hole faces are unsupported`),Array.isArray(e.attrs.get(`points`))||k(`syntax`,`mesh has no points`);let r=e.attrs.get(`points`).map(e=>M(e,3)),o=M(e.attrs.get(`faceVertexCounts`)),s=M(e.attrs.get(`faceVertexIndices`));_.length/3+r.length>n.maxVertices&&k(`limit`,`vertex limit exceeded`);let c=a[0]*(a[5]*a[10]-a[6]*a[9])-a[4]*(a[1]*a[10]-a[2]*a[9])+a[8]*(a[1]*a[6]-a[2]*a[5]);(!c||!Number.isFinite(c))&&k(`range`,`singular transform`);let l=v.length,u=_.length/3;for(let[e,t,n]of r)for(let r=0;r<3;r++){let i=Math.fround(a[r]*e+a[4+r]*t+a[8+r]*n+a[12+r]);Number.isFinite(i)||k(`range`,`vertex outside Float32 range`),_.push(i)}let p=e.attrs.get(`orientation`)??`rightHanded`;p!==`rightHanded`&&p!==`leftHanded`&&k(`range`,`invalid orientation`);let m=p===`leftHanded`!=c<0,h=0;for(let e of o){(!Number.isSafeInteger(e)||e<3||h+e>s.length)&&k(`syntax`,`invalid faceVertexCounts`),v.length/3+e-2>n.maxTriangles&&k(`limit`,`triangle limit exceeded`);let t=s.slice(h,h+e);if(h+=e,t.some(e=>!Number.isSafeInteger(e)||e<0||e>=r.length)&&k(`range`,`face index outside points`),e>3){f+=e*e,f>1e7&&k(`limit`,`polygon validation work limit exceeded`);let n=r[t[0]],i=r[t[1]],a=r[t[2]],o=i.map((e,t)=>e-n[t]),s=a.map((e,t)=>e-n[t]),c=[o[1]*s[2]-o[2]*s[1],o[2]*s[0]-o[0]*s[2],o[0]*s[1]-o[1]*s[0]],l=Math.hypot(...c);l||k(`unsupported`,`degenerate polygon`);for(let i=0;i<e;i++){let a=r[t[i]],o=r[t[(i+1)%e]],s=r[t[(i+2)%e]],u=o.map((e,t)=>e-a[t]),d=s.map((e,t)=>e-o[t]);(Math.abs(c.reduce((e,t,r)=>e+t*(a[r]-n[r]),0))>l*1e-5||c[0]*(u[1]*d[2]-u[2]*d[1])+c[1]*(u[2]*d[0]-u[0]*d[2])+c[2]*(u[0]*d[1]-u[1]*d[0])<0)&&k(`unsupported`,`concave or non-planar polygon`);for(let e of t){let t=r[e].map((e,t)=>e-a[t]);c[0]*(u[1]*t[2]-u[2]*t[1])+c[1]*(u[2]*t[0]-u[0]*t[2])+c[2]*(u[0]*t[1]-u[1]*t[0])<-l*1e-10&&k(`unsupported`,`self-intersecting or concave polygon`)}}}for(let n=1;n<e-1;n++)v.push(u+t[0],u+t[m?n+1:n],u+t[m?n:n+1])}h!==s.length&&k(`syntax`,`faceVertexCounts does not match indices`);let g,x,S,C=i;if(C&&typeof C==`object`&&!Array.isArray(C)&&`path`in C){let t=d.get(C.path)?.attrs.get(`outputs:surface.connect`);(!t||typeof t!=`object`||Array.isArray(t)||!(`path`in t))&&k(`unsupported`,`unsupported material binding`);let n=d.get(t.path.split(`.outputs:`)[0]);(!n||n.attrs.get(`info:id`)!==`UsdPreviewSurface`)&&k(`unsupported`,`only UsdPreviewSurface colors are supported`),x=F(e,n,`diffuseColor`,3,r.length,d,[.18,.18,.18]),S=F(e,n,`opacity`,1,r.length,d,[1])}else e.attrs.has(`primvars:displayColor`)&&(x=P(e,`displayColor`,3,r.length,[1,1,1])),e.attrs.has(`primvars:displayOpacity`)&&(S=P(e,`displayOpacity`,1,r.length,[1]));(x||S)&&!x?.varying&&!S?.varying&&(g=[...(x?.values??[1,1,1]).map(D),S?.values[0]??1]),b.push({count:r.length,rgb:x??{values:[1,1,1],varying:!1},opacity:S??{values:[1],varying:!1}}),g?.some(e=>!Number.isFinite(e)||e<0||e>1)&&k(`range`,`invalid display color`),y.push({start:l,count:v.length-l,name:typeof e.attrs.get(`displayName`)==`string`?e.attrs.get(`displayName`):e.name,objectId:e.path,...g?{color:g}:{}})}else[`Xform`,`Scope`,`Material`,`Shader`].includes(e.type)||k(`unsupported`,`unsupported USD prim type ${e.type}`);for(let t of e.children)x(t,a,r,i)}for(let e of u)x(e,g);v.length||k(`unsupported`,`stage contains no polygon meshes`);let S=new Float32Array(_),C=new Uint32Array(v),T,E;if(b.some(e=>e.rgb.varying||e.opacity.varying)){T=new Float32Array(_.length),E=new Float32Array(_.length/3);let e=0;for(let t of b)for(let n=0;n<t.count;n++,e++){for(let r=0;r<3;r++)T[e*3+r]=D(t.rgb.values[(t.rgb.varying?n*3:0)+r]);E[e]=t.opacity.values[t.opacity.varying?n:0]}}return{kind:`mesh`,positions:S,indices:C,normals:w(S,C),groups:y,...T?{colors:T,attributes:{opacity:E}}:{}}}async function z(e,t={}){s(t.signal,O);for(let e of[t.maxEntries??1e4,t.maxEntryBytes??67108864])(!Number.isSafeInteger(e)||e<0)&&k(`range`,`invalid ZIP limit`);let n=a(e,O),r=b(n,t),i=r.reduce((e,t)=>!e||t.headerOffset<e.headerOffset?t:e,void 0);(!i||!/\.(usd|usda|usdc)$/i.test(i.name))&&k(`unsupported`,`USDZ first entry must be its root USD layer`);let o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let e of r)e.method!==0&&k(`unsupported`,`USDZ entries must be stored without compression`),e.headerOffset+30>n.length&&k(`syntax`,`truncated ZIP local header`),(e.headerOffset+30+o.getUint16(e.headerOffset+26,!0)+o.getUint16(e.headerOffset+28,!0))%64&&k(`syntax`,`USDZ entries must be aligned to 64 bytes`);let c=await S(n,i,t);return s(t.signal,O),new TextDecoder().decode(c.subarray(0,8))===`PXR-USDC`&&k(`unsupported`,`binary USDC is unsupported; convert the root layer to USDA with usdcat`),R(c,t)}t(({format:e,input:t,options:n})=>e===`usdz`?z(t,n):R(t,n))})();