@margoengine/loaders 0.0.0-stage → 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 (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
package/dist/vtk.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type LoadedGeometry, type ParseLimits } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ /** Options of parseVTK: the shared size limits (ParseLimits). */
4
+ export interface VTKOptions extends ParseLimits {
5
+ }
6
+ /**
7
+ * Parses a legacy VTK file (`# vtk DataFile Version` 1.0 to 5.1, ASCII or BINARY) holding `DATASET POLYDATA`.
8
+ * Convex POLYGONS are fanned and concave ones ear-clipped, TRIANGLE_STRIPS unrolled
9
+ * with alternating winding, VERTICES and LINES ignored (a file with only those is returned as a point cloud).
10
+ * Point NORMALS, COLOR_SCALARS, TEXTURE_COORDINATES (v turned so 0 is the image's top) and single-component SCALARS
11
+ * are read; cell data is skipped.
12
+ */
13
+ export declare function parseVTK(input: BinaryInput, options?: VTKOptions): LoadedGeometry;
package/dist/vtk.js ADDED
@@ -0,0 +1,234 @@
1
+ import { concaveTriangles } from './polygon.js';
2
+ import { Reader, integerOf } from './vtk-reader.js';
3
+ import { LoaderError } from './types.js';
4
+ import { checkCount, latin1, limits, toBytes, uints } from './util.js';
5
+ const F = 'VTK';
6
+ /**
7
+ * Parses a legacy VTK file (`# vtk DataFile Version` 1.0 to 5.1, ASCII or BINARY) holding `DATASET POLYDATA`.
8
+ * Convex POLYGONS are fanned and concave ones ear-clipped, TRIANGLE_STRIPS unrolled
9
+ * with alternating winding, VERTICES and LINES ignored (a file with only those is returned as a point cloud).
10
+ * Point NORMALS, COLOR_SCALARS, TEXTURE_COORDINATES (v turned so 0 is the image's top) and single-component SCALARS
11
+ * are read; cell data is skipped.
12
+ */
13
+ export function parseVTK(input, options = {}) {
14
+ const bytes = toBytes(input, F), limit = limits(options, F);
15
+ const head = latin1(bytes, 0, Math.min(bytes.length, 1024));
16
+ const firstLine = /^# vtk DataFile Version (\d+)\.(\d+)/.exec(head);
17
+ if (!firstLine)
18
+ throw new LoaderError(F, 'header', 'missing "# vtk DataFile Version" line');
19
+ const major = Number(firstLine[1]);
20
+ const lines = head.split('\n');
21
+ if (lines.length < 3)
22
+ throw new LoaderError(F, 'truncated', 'header ends early');
23
+ const mode = lines[2].trim().toUpperCase();
24
+ if (mode !== 'ASCII' && mode !== 'BINARY')
25
+ throw new LoaderError(F, 'header', `third line must be ASCII or BINARY, got "${lines[2].trim().slice(0, 32)}"`);
26
+ const maxValues = Math.max(limit.maxVertices * 4, limit.maxTriangles * 4);
27
+ const reader = new Reader(bytes, mode === 'BINARY', maxValues);
28
+ reader.line();
29
+ reader.line();
30
+ reader.line();
31
+ let positions, normals, colors, uvs;
32
+ // Null prototype: SCALARS names come from the file (`SCALARS __proto__ float` swapped a plain object's prototype).
33
+ const attributes = Object.create(null);
34
+ const indices = uints();
35
+ let pointCount = 0, section = 'none', sectionCount = 0, dataset = false;
36
+ const toFloat32 = (values, stride, take) => {
37
+ const count = values.length / stride, out = new Float32Array(count * take);
38
+ for (let i = 0; i < count; i++)
39
+ for (let a = 0; a < take; a++)
40
+ out[i * take + a] = values[i * stride + a];
41
+ return out;
42
+ };
43
+ const triangleLimit = (extra) => {
44
+ if (indices.length / 3 + extra > limit.maxTriangles)
45
+ throw new LoaderError(F, 'limit', `triangle count exceeds the limit of ${limit.maxTriangles}`);
46
+ };
47
+ const emitCell = (kind, cell, start, size) => {
48
+ for (let k = start; k < start + size; k++) {
49
+ const index = cell[k];
50
+ if (!Number.isSafeInteger(index) || index < 0 || index >= 0xffffffff)
51
+ throw new LoaderError(F, 'range', `${kind} index ${index} is not a valid point index`);
52
+ }
53
+ if (kind === 'POLYGONS') {
54
+ if (size < 3)
55
+ return;
56
+ triangleLimit(size - 2);
57
+ // vtkPolygon may be concave; its corners must index read points to be clipped (a bad index fails below).
58
+ const corners = Array.from({ length: size }, (_, k) => cell[start + k]), clipped = size > 3 && positions && corners.every((index) => index < pointCount)
59
+ ? concaveTriangles(positions, corners)
60
+ : null;
61
+ if (clipped)
62
+ for (let t = 0; t < clipped.length; t += 3)
63
+ indices.push3(corners[clipped[t]], corners[clipped[t + 1]], corners[clipped[t + 2]]);
64
+ else
65
+ for (let k = 2; k < size; k++)
66
+ indices.push3(cell[start], cell[start + k - 1], cell[start + k]);
67
+ }
68
+ else if (kind === 'TRIANGLE_STRIPS') {
69
+ triangleLimit(Math.max(0, size - 2));
70
+ for (let k = 0; k + 2 < size; k++) {
71
+ const a = cell[start + k], b = cell[start + k + 1], c = cell[start + k + 2];
72
+ if (a === b || b === c || a === c)
73
+ continue;
74
+ if (k % 2)
75
+ indices.push3(b, a, c);
76
+ else
77
+ indices.push3(a, b, c);
78
+ }
79
+ }
80
+ };
81
+ for (let tokens = reader.keyword(); tokens; tokens = reader.keyword()) {
82
+ const key = tokens[0].toUpperCase();
83
+ const what = tokens.join(' ').slice(0, 64);
84
+ if (key === 'DATASET') {
85
+ if ((tokens[1] ?? '').toUpperCase() !== 'POLYDATA')
86
+ throw new LoaderError(F, 'unsupported', `only DATASET POLYDATA is supported, got ${tokens[1] ?? 'nothing'}`);
87
+ dataset = true;
88
+ }
89
+ else if (key === 'POINTS') {
90
+ pointCount = checkCount(integerOf(tokens[1], 'point count'), limit.maxVertices, F, 'point');
91
+ positions = toFloat32(reader.values(tokens[2] ?? 'float', pointCount * 3, what), 3, 3);
92
+ }
93
+ else if (key === 'METADATA') {
94
+ for (let line = reader.line(); line !== null && line.trim(); line = reader.line())
95
+ ;
96
+ }
97
+ else if (key === 'VERTICES' || key === 'LINES' || key === 'POLYGONS' || key === 'TRIANGLE_STRIPS') {
98
+ const cells = integerOf(tokens[1], `${key} count`), size = integerOf(tokens[2], `${key} size`);
99
+ if (major >= 5) {
100
+ // 5.x: "POLYGONS <offsets> <connectivity>", then OFFSETS and CONNECTIVITY arrays.
101
+ const offsetsLine = reader.keyword();
102
+ if (offsetsLine?.[0]?.toUpperCase() !== 'OFFSETS')
103
+ throw new LoaderError(F, 'syntax', `expected OFFSETS after ${key}`);
104
+ const offsets = reader.values(offsetsLine[1] ?? 'vtktypeint64', cells, `${key} offsets`);
105
+ const connectivityLine = reader.keyword();
106
+ if (connectivityLine?.[0]?.toUpperCase() !== 'CONNECTIVITY')
107
+ throw new LoaderError(F, 'syntax', `expected CONNECTIVITY after ${key} offsets`);
108
+ const connectivity = reader.values(connectivityLine[1] ?? 'vtktypeint64', size, `${key} connectivity`);
109
+ for (let c = 0; c + 1 < cells; c++) {
110
+ const start = offsets[c], end = offsets[c + 1];
111
+ if (!(Number.isSafeInteger(start) && Number.isSafeInteger(end) && start >= 0 && end >= start && end <= size))
112
+ throw new LoaderError(F, 'range', `${key} offsets are not increasing within the connectivity array`);
113
+ emitCell(key, connectivity, start, end - start);
114
+ }
115
+ }
116
+ else {
117
+ const data = reader.values('int', size, key);
118
+ let p = 0;
119
+ for (let c = 0; c < cells; c++) {
120
+ if (p >= size)
121
+ throw new LoaderError(F, 'range', `${key} declares ${cells} cells but its size ${size} runs out at cell ${c}`);
122
+ const count = data[p];
123
+ if (!Number.isSafeInteger(count) || count < 0 || p + 1 + count > size)
124
+ throw new LoaderError(F, 'range', `${key} cell ${c} has an invalid point count ${count}`);
125
+ emitCell(key, data, p + 1, count);
126
+ p += 1 + count;
127
+ }
128
+ if (p !== size)
129
+ throw new LoaderError(F, 'range', `${key} size ${size} does not match its cells (${p})`);
130
+ }
131
+ }
132
+ else if (key === 'POINT_DATA' || key === 'CELL_DATA') {
133
+ section = key === 'POINT_DATA' ? 'point' : 'cell';
134
+ sectionCount = integerOf(tokens[1], `${key} count`);
135
+ if (sectionCount > maxValues)
136
+ throw new LoaderError(F, 'limit', `${key} count ${sectionCount} exceeds the limit`);
137
+ if (section === 'point' && positions && sectionCount !== pointCount)
138
+ throw new LoaderError(F, 'range', `POINT_DATA ${sectionCount} does not match POINTS ${pointCount}`);
139
+ }
140
+ else if (key === 'SCALARS') {
141
+ if (section === 'none')
142
+ throw new LoaderError(F, 'syntax', 'SCALARS outside POINT_DATA or CELL_DATA');
143
+ const components = tokens[3] ? integerOf(tokens[3], 'SCALARS component count') : 1;
144
+ if (components < 1 || components > 4)
145
+ throw new LoaderError(F, 'range', `SCALARS component count ${components} must be 1 to 4`);
146
+ // LOOKUP_TABLE is required by the legacy format but optional in practice; peek for it.
147
+ const mark = reader.mark();
148
+ if (reader.keyword()?.[0]?.toUpperCase() !== 'LOOKUP_TABLE')
149
+ reader.reset(mark);
150
+ const values = reader.values(tokens[2] ?? 'float', sectionCount * components, what);
151
+ if (section === 'point' && components === 1)
152
+ attributes[tokens[1]] = Float32Array.from(values);
153
+ }
154
+ else if (key === 'LOOKUP_TABLE') {
155
+ const size = integerOf(tokens[2], 'LOOKUP_TABLE size');
156
+ reader.values(reader.binary ? 'unsigned_char' : 'float', size * 4, what);
157
+ }
158
+ else if (key === 'COLOR_SCALARS') {
159
+ if (section === 'none')
160
+ throw new LoaderError(F, 'syntax', 'COLOR_SCALARS outside POINT_DATA or CELL_DATA');
161
+ const components = integerOf(tokens[2], 'COLOR_SCALARS component count');
162
+ if (components < 1 || components > 4)
163
+ throw new LoaderError(F, 'range', `COLOR_SCALARS component count ${components} must be 1 to 4`);
164
+ const values = reader.values(reader.binary ? 'unsigned_char' : 'float', sectionCount * components, what);
165
+ if (section === 'point' && components >= 3) {
166
+ colors = toFloat32(values, components, 3);
167
+ if (reader.binary)
168
+ for (let i = 0; i < colors.length; i++)
169
+ colors[i] /= 255;
170
+ }
171
+ }
172
+ else if (key === 'NORMALS' || key === 'VECTORS') {
173
+ const values = reader.values(tokens[2] ?? 'float', sectionCount * 3, what);
174
+ if (section === 'point' && key === 'NORMALS')
175
+ normals = toFloat32(values, 3, 3);
176
+ }
177
+ else if (key === 'TEXTURE_COORDINATES') {
178
+ const dimension = integerOf(tokens[2], 'TEXTURE_COORDINATES dimension');
179
+ if (dimension < 1 || dimension > 3)
180
+ throw new LoaderError(F, 'range', `TEXTURE_COORDINATES dimension ${dimension} must be 1 to 3`);
181
+ const values = reader.values(tokens[3] ?? 'float', sectionCount * dimension, what);
182
+ if (section === 'point' && dimension >= 2) {
183
+ // VTK puts t = 0 at the image's bottom (OpenGL's convention); Margo puts v = 0 at the top.
184
+ uvs = toFloat32(values, dimension, 2);
185
+ for (let i = 1; i < uvs.length; i += 2)
186
+ uvs[i] = 1 - uvs[i];
187
+ }
188
+ }
189
+ else if (key === 'TENSORS' || key === 'TENSORS6') {
190
+ reader.values(tokens[2] ?? 'float', sectionCount * (key === 'TENSORS' ? 9 : 6), what);
191
+ }
192
+ else if (key === 'GLOBAL_IDS' || key === 'PEDIGREE_IDS') {
193
+ reader.values(tokens[2] ?? 'int', sectionCount, what);
194
+ }
195
+ else if (key === 'FIELD') {
196
+ const arrays = integerOf(tokens[2], 'FIELD array count');
197
+ for (let a = 0; a < arrays; a++) {
198
+ const array = reader.keyword();
199
+ if (!array)
200
+ throw new LoaderError(F, 'truncated', 'file ends inside FIELD');
201
+ if (array[0].toUpperCase() === 'METADATA') {
202
+ for (let line = reader.line(); line !== null && line.trim(); line = reader.line())
203
+ ;
204
+ a--;
205
+ continue;
206
+ }
207
+ const components = integerOf(array[1], 'FIELD component count'), tuples = integerOf(array[2], 'FIELD tuple count');
208
+ reader.values(array[3] ?? 'float', components * tuples, `FIELD array ${array[0].slice(0, 32)}`);
209
+ }
210
+ }
211
+ else
212
+ throw new LoaderError(F, 'syntax', `unknown keyword "${tokens[0].slice(0, 32)}"`);
213
+ }
214
+ if (!dataset)
215
+ throw new LoaderError(F, 'header', 'missing DATASET line');
216
+ if (!positions)
217
+ throw new LoaderError(F, 'syntax', 'missing POINTS');
218
+ const triangles = indices.result();
219
+ for (let i = 0; i < triangles.length; i++)
220
+ if (!(triangles[i] < pointCount))
221
+ throw new LoaderError(F, 'range', `cell index ${triangles[i]} is outside 0..${pointCount - 1}`);
222
+ const result = { kind: triangles.length ? 'mesh' : 'points', positions };
223
+ if (normals)
224
+ result.normals = normals;
225
+ if (colors)
226
+ result.colors = colors;
227
+ if (uvs)
228
+ result.uvs = uvs;
229
+ if (triangles.length)
230
+ result.indices = triangles;
231
+ if (Object.keys(attributes).length)
232
+ result.attributes = attributes;
233
+ return result;
234
+ }
@@ -0,0 +1,17 @@
1
+ import { BinaryReader } from './sfnt-reader.js';
2
+ import { type LoaderErrorCode } from './types.js';
3
+ /** Throws the web font decoder's error. */
4
+ export declare function woffError(detail: string, code?: LoaderErrorCode, cause?: unknown): never;
5
+ /** The 255UInt16 variable-length integer. */
6
+ export declare function read255(r: BinaryReader): number;
7
+ /** The rebuilt `glyf` and `loca` tables of a transformed `glyf`, and the `loca` format they use (0 short, 1 long). */
8
+ export declare function rebuildGlyf(data: Uint8Array, limit: number): {
9
+ glyf: Uint8Array;
10
+ loca: Uint8Array;
11
+ format: number;
12
+ };
13
+ /**
14
+ * The `hmtx` table of its WOFF2 transform (version 1): left side bearings the encoder left out are each glyph's xMin
15
+ * in the font's `glyf` table.
16
+ */
17
+ export declare function rebuildHmtx(data: Uint8Array, metrics: number, glyphCount: number, glyf: Uint8Array, loca: Uint8Array, format: number): Uint8Array;
@@ -0,0 +1,215 @@
1
+ // WOFF2's transformed 'glyf', 'loca' and 'hmtx' tables back to the OpenType ones, clean room from W3C "WOFF File
2
+ // Format 2.0" (V. Levantovsky, ed., Recommendation, 8 August 2024, https://www.w3.org/TR/WOFF2/), sections 5.1 to 5.4.
3
+ import { BinaryReader } from './sfnt-reader.js';
4
+ import { LoaderError } from './types.js';
5
+ /** Throws the web font decoder's error. */
6
+ export function woffError(detail, code = 'header', cause) {
7
+ throw new LoaderError('WOFF', code, `${detail}; ${code === 'limit' ? 'raise maxBytes if you trust the file' : 'the web font is damaged or malformed, export it again'}`, { cause });
8
+ }
9
+ /** The 255UInt16 variable-length integer. */
10
+ export function read255(r) {
11
+ const code = r.u8();
12
+ return code === 253 ? r.u16() : code === 255 ? r.u8() + 253 : code === 254 ? r.u8() + 506 : code;
13
+ }
14
+ const take = (r, length) => {
15
+ const bytes = r.slice(r.pos, length).bytes;
16
+ r.pos += length;
17
+ return bytes;
18
+ };
19
+ /** A growing big-endian buffer that refuses to pass `limit` bytes. */
20
+ class Output {
21
+ constructor(limit) {
22
+ this.limit = limit;
23
+ this.buffer = new Uint8Array(4096);
24
+ this.length = 0;
25
+ }
26
+ room(bytes) {
27
+ const at = this.length, end = at + bytes;
28
+ if (end > this.limit)
29
+ woffError(`the rebuilt 'glyf' table passes maxBytes (${this.limit})`, 'limit');
30
+ if (end > this.buffer.length) {
31
+ const grown = new Uint8Array(Math.max(end, this.buffer.length * 2));
32
+ grown.set(this.buffer);
33
+ this.buffer = grown;
34
+ }
35
+ this.length = end;
36
+ return at;
37
+ }
38
+ u8(v) {
39
+ const at = this.room(1);
40
+ this.buffer[at] = v;
41
+ }
42
+ u16(v) {
43
+ this.u8((v >> 8) & 255);
44
+ this.u8(v & 255);
45
+ }
46
+ bytes(data) {
47
+ const at = this.room(data.length);
48
+ this.buffer.set(data, at);
49
+ }
50
+ result() {
51
+ return this.buffer.subarray(0, this.length);
52
+ }
53
+ }
54
+ /** One point's coordinate deltas from its flag's low 7 bits and the glyph stream (section 5.2, "Triplet Encoding"). */
55
+ function triplet(code, r) {
56
+ // The lowest bit is the sign of the first coordinate present, the next one of y: set means positive.
57
+ const x = (v) => (code & 1 ? v : -v), y = (v) => (code & 2 ? v : -v);
58
+ if (code < 10)
59
+ return [0, x(((code & 14) << 7) + r.u8())];
60
+ if (code < 20)
61
+ return [x((((code - 10) & 14) << 7) + r.u8()), 0];
62
+ if (code < 84) {
63
+ const b = code - 20, byte = r.u8();
64
+ return [x(1 + (b & 0x30) + (byte >> 4)), y(1 + ((b & 0x0c) << 2) + (byte & 15))];
65
+ }
66
+ if (code < 120) {
67
+ const b = code - 84, high = 1 + (Math.floor(b / 12) << 8), dx = high + r.u8();
68
+ return [x(dx), y(1 + (((b % 12) >> 2) << 8) + r.u8())];
69
+ }
70
+ if (code < 124) {
71
+ const first = r.u8(), middle = r.u8();
72
+ return [x((first << 4) + (middle >> 4)), y(((middle & 15) << 8) + r.u8())];
73
+ }
74
+ const dx = r.u16();
75
+ return [x(dx), y(r.u16())];
76
+ }
77
+ /** The rebuilt `glyf` and `loca` tables of a transformed `glyf`, and the `loca` format they use (0 short, 1 long). */
78
+ export function rebuildGlyf(data, limit) {
79
+ const header = new BinaryReader(data);
80
+ header.u16();
81
+ const options = header.u16(), count = header.u16(), indexFormat = header.u16(), sizes = Array.from({ length: 7 }, () => header.u32());
82
+ const [contourStream, pointStream, flagStream, glyphStream, compositeStream, boxStream, instructionStream] = sizes.map((size) => new BinaryReader(take(header, size)));
83
+ const overlap = options & 1 ? take(header, (count + 7) >> 3) : undefined, boxed = take(boxStream, ((count + 31) >> 5) * 4), bit = (map, i) => (map[i >> 3] & (0x80 >> (i & 7))) !== 0, out = new Output(limit), offsets = new Uint32Array(count + 1);
84
+ const instructions = () => {
85
+ const length = read255(glyphStream);
86
+ out.u16(length);
87
+ out.bytes(take(instructionStream, length));
88
+ };
89
+ for (let glyph = 0; glyph < count; glyph++) {
90
+ offsets[glyph] = out.length;
91
+ const contours = contourStream.i16(), box = bit(boxed, glyph) ? take(boxStream, 8) : undefined;
92
+ if (contours === 0) {
93
+ if (box)
94
+ woffError(`empty glyph ${glyph} carries a bounding box`);
95
+ continue;
96
+ }
97
+ if (contours < 0) {
98
+ if (contours !== -1 || !box)
99
+ woffError(`composite glyph ${glyph} has no bounding box or a bad contour count`);
100
+ out.u16(0xffff);
101
+ out.bytes(box);
102
+ const start = compositeStream.pos;
103
+ let flags, hinted = false;
104
+ do {
105
+ flags = compositeStream.u16();
106
+ hinted ||= (flags & 0x100) !== 0;
107
+ // Glyph index, two arguments (words or bytes) and the optional scale, x/y scale or 2x2 transform.
108
+ compositeStream.skip(2 + (flags & 1 ? 4 : 2) + (flags & 8 ? 2 : flags & 0x40 ? 4 : flags & 0x80 ? 8 : 0));
109
+ } while (flags & 0x20);
110
+ out.bytes(compositeStream.bytes.subarray(start, compositeStream.pos));
111
+ if (hinted)
112
+ instructions();
113
+ }
114
+ else {
115
+ const ends = [];
116
+ let points = 0;
117
+ for (let c = 0; c < contours; c++) {
118
+ points += read255(pointStream);
119
+ if (points < 1 || points > 65536)
120
+ woffError(`glyph ${glyph} has an impossible number of points`, 'range');
121
+ ends.push(points - 1);
122
+ }
123
+ const flags = take(flagStream, points), xs = [], ys = [];
124
+ let x = 0, y = 0, xMin = 32767, yMin = 32767, xMax = -32768, yMax = -32768;
125
+ for (let i = 0; i < points; i++) {
126
+ const [dx, dy] = triplet(flags[i] & 127, glyphStream);
127
+ x += dx;
128
+ y += dy;
129
+ if (dx < -32768 ||
130
+ dx > 32767 ||
131
+ dy < -32768 ||
132
+ dy > 32767 ||
133
+ x < -32768 ||
134
+ x > 32767 ||
135
+ y < -32768 ||
136
+ y > 32767)
137
+ woffError(`glyph ${glyph} leaves the 16-bit coordinate range`, 'range');
138
+ xs.push(dx);
139
+ ys.push(dy);
140
+ xMin = Math.min(xMin, x);
141
+ yMin = Math.min(yMin, y);
142
+ xMax = Math.max(xMax, x);
143
+ yMax = Math.max(yMax, y);
144
+ }
145
+ out.u16(contours);
146
+ if (box)
147
+ out.bytes(box);
148
+ else
149
+ for (const v of [xMin, yMin, xMax, yMax])
150
+ out.u16(v);
151
+ for (const end of ends)
152
+ out.u16(end);
153
+ instructions();
154
+ // 'glyf' simple glyph: flags (on curve, short and same-or-sign bits), then all x deltas, then all y deltas.
155
+ for (let i = 0; i < points; i++) {
156
+ let flag = flags[i] & 128 ? 0 : 1;
157
+ if (i === 0 && overlap && bit(overlap, glyph))
158
+ flag |= 0x40;
159
+ for (const [delta, short, same] of [
160
+ [xs[i], 2, 16],
161
+ [ys[i], 4, 32],
162
+ ])
163
+ if (delta === 0)
164
+ flag |= same;
165
+ else if (delta >= -255 && delta <= 255)
166
+ flag |= short | (delta > 0 ? same : 0);
167
+ out.u8(flag);
168
+ }
169
+ for (const list of [xs, ys])
170
+ for (const delta of list)
171
+ if (delta >= -255 && delta <= 255) {
172
+ if (delta)
173
+ out.u8(Math.abs(delta));
174
+ }
175
+ else
176
+ out.u16(delta);
177
+ }
178
+ // Short 'loca' offsets are halved, so every glyph ends on an even byte.
179
+ if (out.length & 1)
180
+ out.u8(0);
181
+ }
182
+ offsets[count] = out.length;
183
+ // A short 'loca' reaches 131070 bytes; a font the rebuild grows past that gets the long one.
184
+ const format = indexFormat === 0 && out.length <= 0x1fffe ? 0 : 1, loca = new Uint8Array((count + 1) * (format ? 4 : 2)), view = new DataView(loca.buffer);
185
+ offsets.forEach((offset, i) => (format ? view.setUint32(i * 4, offset) : view.setUint16(i * 2, offset / 2)));
186
+ return { glyf: out.result(), loca, format };
187
+ }
188
+ /**
189
+ * The `hmtx` table of its WOFF2 transform (version 1): left side bearings the encoder left out are each glyph's xMin
190
+ * in the font's `glyf` table.
191
+ */
192
+ export function rebuildHmtx(data, metrics, glyphCount, glyf, loca, format) {
193
+ const r = new BinaryReader(data), flags = r.u8();
194
+ if (!(flags & 3) || flags & 0xfc)
195
+ woffError("the transformed 'hmtx' flags are invalid");
196
+ if (metrics < 1 || metrics > glyphCount)
197
+ woffError("'hhea' gives an impossible number of horizontal metrics", 'range');
198
+ const advances = Array.from({ length: metrics }, () => r.u16()), bearings = flags & 1 ? undefined : Array.from({ length: metrics }, () => r.u16()), trailing = flags & 2 ? undefined : Array.from({ length: glyphCount - metrics }, () => r.u16()), offsets = new BinaryReader(loca), glyphs = new BinaryReader(glyf);
199
+ const xMin = (glyph) => {
200
+ offsets.seek(glyph * (format ? 4 : 2));
201
+ const start = format ? offsets.u32() : offsets.u16() * 2, end = format ? offsets.u32() : offsets.u16() * 2;
202
+ if (end <= start)
203
+ return 0;
204
+ glyphs.seek(start + 2);
205
+ return glyphs.u16();
206
+ };
207
+ const out = new Uint8Array(metrics * 4 + (glyphCount - metrics) * 2), view = new DataView(out.buffer);
208
+ for (let i = 0; i < metrics; i++) {
209
+ view.setUint16(i * 4, advances[i]);
210
+ view.setUint16(i * 4 + 2, bearings ? bearings[i] : xMin(i));
211
+ }
212
+ for (let i = metrics; i < glyphCount; i++)
213
+ view.setUint16(metrics * 4 + (i - metrics) * 2, trailing ? trailing[i - metrics] : xMin(i));
214
+ return out;
215
+ }
@@ -0,0 +1,10 @@
1
+ import { type LoadedGeometry } from './types.js';
2
+ import type { BinaryInput } from './util.js';
3
+ import { type USDOptions } from './usdz.js';
4
+ /**
5
+ * parseUSDZ in a worker: same LoadedGeometry, its arrays transferred back. A whole ArrayBuffer input moves to the
6
+ * worker and is detached here (pass a copy to keep it). Runs on this thread when Workers are unavailable.
7
+ */
8
+ export declare function parseUSDZInWorker(input: BinaryInput, options?: USDOptions): Promise<LoadedGeometry>;
9
+ /** parseUSDA in a worker; see parseUSDZInWorker. */
10
+ export declare function parseUSDAInWorker(input: string | BinaryInput, options?: USDOptions): Promise<LoadedGeometry>;
package/dist/worker.js ADDED
@@ -0,0 +1,93 @@
1
+ import { LoaderError } from "./types.js";
2
+ import { parseUSDA, parseUSDZ } from "./usdz.js";
3
+ //#region ../shared/worker.js
4
+ /** Every ArrayBuffer (behind typed arrays too) and ImageBitmap reachable from value, once each. */
5
+ function transferables(root, out = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set()) {
6
+ const stack = [root];
7
+ while (stack.length) {
8
+ const value = stack.pop();
9
+ if (!value || typeof value !== "object" || seen.has(value)) continue;
10
+ seen.add(value);
11
+ if (ArrayBuffer.isView(value)) {
12
+ if (value.buffer instanceof ArrayBuffer) out.add(value.buffer);
13
+ } else if (value instanceof ArrayBuffer) out.add(value);
14
+ else if (typeof ImageBitmap !== "undefined" && value instanceof ImageBitmap) out.add(value);
15
+ else if (value instanceof Map) for (const [k, v] of value) stack.push(k, v);
16
+ else for (const key in value) stack.push(value[key]);
17
+ }
18
+ return out;
19
+ }
20
+ /** Bytes as an ArrayBuffer to post: a whole ArrayBuffer moves (the caller's copy is detached), anything else is copied. */
21
+ function movable(input) {
22
+ if (input instanceof ArrayBuffer) return input;
23
+ if (ArrayBuffer.isView(input)) return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength);
24
+ if (typeof input === "string") return input;
25
+ throw new TypeError("Expected an ArrayBuffer, typed array or string");
26
+ }
27
+ /** True when this context can start a worker (browsers, including inside a worker); false during SSR and in Node. */
28
+ var canUseWorker = () => typeof Worker === "function" && typeof globalThis.location !== "undefined";
29
+ var errors = {
30
+ TypeError,
31
+ RangeError,
32
+ SyntaxError
33
+ };
34
+ /** A worker's {name, message} as an Error; only the listed names map to their classes (own keys, so not `constructor`). */
35
+ var reviveError = ({ name, message }) => new (Object.hasOwn(errors, name) ? errors[name] : Error)(typeof message === "string" ? message : "Parser worker failed");
36
+ /** Post one job to a fresh worker and resolve its result. Aborting terminates the worker. revive rebuilds package error classes. */
37
+ function runWorker(url, message, signal, revive) {
38
+ signal?.throwIfAborted();
39
+ return new Promise((resolve, reject) => {
40
+ const worker = new Worker(url, { name: "margoengine-parser" });
41
+ const done = () => {
42
+ worker.onmessage = worker.onerror = worker.onmessageerror = null;
43
+ worker.terminate();
44
+ signal?.removeEventListener("abort", abort);
45
+ };
46
+ const fail = (error) => {
47
+ done();
48
+ reject(error);
49
+ };
50
+ const abort = () => fail(signal.reason ?? new DOMException("Aborted", "AbortError"));
51
+ signal?.addEventListener("abort", abort, { once: true });
52
+ worker.onerror = (event) => {
53
+ event.preventDefault?.();
54
+ fail(/* @__PURE__ */ new Error("Parser worker failed: " + (event.message || "unknown error")));
55
+ };
56
+ worker.onmessageerror = () => fail(/* @__PURE__ */ new Error("Parser worker reply could not be deserialized"));
57
+ worker.onmessage = ({ data }) => {
58
+ done();
59
+ if (!data || typeof data !== "object") reject(/* @__PURE__ */ new TypeError("Parser worker sent an invalid reply"));
60
+ else if (data.error) reject(revive?.(data.error) ?? reviveError(data.error));
61
+ else resolve(data.result);
62
+ };
63
+ try {
64
+ worker.postMessage(message, [...transferables(message)]);
65
+ } catch (error) {
66
+ fail(error);
67
+ }
68
+ });
69
+ }
70
+ //#endregion
71
+ //#region src/worker.ts
72
+ var workerURL = () => new URL("./workers/usd.js?no-inline",
73
+ import.meta.url
74
+ );
75
+ var revive = (e) => e.name === "LoaderError" ? Object.assign(new LoaderError(e.format, e.code, ""), { message: e.message }) : void 0;
76
+ var run = (format, input, { signal, ...options }) => runWorker(workerURL(), {
77
+ format,
78
+ input: movable(input),
79
+ options
80
+ }, signal, revive);
81
+ /**
82
+ * parseUSDZ in a worker: same LoadedGeometry, its arrays transferred back. A whole ArrayBuffer input moves to the
83
+ * worker and is detached here (pass a copy to keep it). Runs on this thread when Workers are unavailable.
84
+ */
85
+ async function parseUSDZInWorker(input, options = {}) {
86
+ return canUseWorker() ? run("usdz", input, options) : parseUSDZ(input, options);
87
+ }
88
+ /** parseUSDA in a worker; see parseUSDZInWorker. */
89
+ async function parseUSDAInWorker(input, options = {}) {
90
+ return canUseWorker() ? run("usda", input, options) : parseUSDA(input, options);
91
+ }
92
+ //#endregion
93
+ export { parseUSDAInWorker, parseUSDZInWorker };
@@ -0,0 +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){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
+ `,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
+ `);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))})();