@margoengine/loaders 0.0.0-stage → 0.1.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 (184) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1198 -3
  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/dae-animation.d.ts +66 -0
  17. package/dist/dae-animation.js +266 -0
  18. package/dist/dae-common.d.ts +95 -0
  19. package/dist/dae-common.js +226 -0
  20. package/dist/dae-controllers.d.ts +57 -0
  21. package/dist/dae-controllers.js +164 -0
  22. package/dist/dae-pose.d.ts +131 -0
  23. package/dist/dae-pose.js +381 -0
  24. package/dist/dae-scene.d.ts +203 -0
  25. package/dist/dae-scene.js +279 -0
  26. package/dist/dae.d.ts +161 -0
  27. package/dist/dae.js +633 -0
  28. package/dist/detect.d.ts +20 -0
  29. package/dist/detect.js +72 -0
  30. package/dist/dxf.d.ts +81 -0
  31. package/dist/dxf.js +774 -0
  32. package/dist/engine.d.ts +36 -0
  33. package/dist/engine.js +117 -0
  34. package/dist/font-opentype.d.ts +14 -0
  35. package/dist/font-opentype.js +33 -0
  36. package/dist/font-woff.d.ts +23 -0
  37. package/dist/font-woff.js +293 -0
  38. package/dist/font.d.ts +41 -0
  39. package/dist/font.js +26 -0
  40. package/dist/gcode.d.ts +55 -0
  41. package/dist/gcode.js +278 -0
  42. package/dist/geo-model.d.ts +84 -0
  43. package/dist/geo-model.js +220 -0
  44. package/dist/geo-mvt.d.ts +15 -0
  45. package/dist/geo-mvt.js +302 -0
  46. package/dist/geo-shp.d.ts +15 -0
  47. package/dist/geo-shp.js +234 -0
  48. package/dist/geo-xml.d.ts +6 -0
  49. package/dist/geo-xml.js +165 -0
  50. package/dist/geo.d.ts +8 -0
  51. package/dist/geo.js +59 -0
  52. package/dist/geometry.d.ts +60 -0
  53. package/dist/geometry.js +273 -0
  54. package/dist/index.d.ts +54 -0
  55. package/dist/index.js +28 -0
  56. package/dist/kmz.d.ts +78 -0
  57. package/dist/kmz.js +173 -0
  58. package/dist/las.d.ts +92 -0
  59. package/dist/las.js +110 -0
  60. package/dist/ldraw.d.ts +118 -0
  61. package/dist/ldraw.js +474 -0
  62. package/dist/load.d.ts +72 -0
  63. package/dist/load.js +205 -0
  64. package/dist/lottie.d.ts +154 -0
  65. package/dist/lottie.js +893 -0
  66. package/dist/lwo.d.ts +81 -0
  67. package/dist/lwo.js +454 -0
  68. package/dist/lzf.d.ts +13 -0
  69. package/dist/lzf.js +56 -0
  70. package/dist/materialx.d.ts +120 -0
  71. package/dist/materialx.js +563 -0
  72. package/dist/md2.d.ts +52 -0
  73. package/dist/md2.js +112 -0
  74. package/dist/mmcif.d.ts +14 -0
  75. package/dist/mmcif.js +246 -0
  76. package/dist/mmd.d.ts +244 -0
  77. package/dist/mmd.js +958 -0
  78. package/dist/mocap.d.ts +71 -0
  79. package/dist/mocap.js +178 -0
  80. package/dist/molecule-common.d.ts +4 -0
  81. package/dist/molecule-common.js +54 -0
  82. package/dist/mtl.d.ts +120 -0
  83. package/dist/mtl.js +469 -0
  84. package/dist/normals.d.ts +7 -0
  85. package/dist/normals.js +31 -0
  86. package/dist/nrrd.d.ts +63 -0
  87. package/dist/nrrd.js +743 -0
  88. package/dist/nurbs.d.ts +118 -0
  89. package/dist/nurbs.js +265 -0
  90. package/dist/obj.d.ts +143 -0
  91. package/dist/obj.js +456 -0
  92. package/dist/off.d.ts +10 -0
  93. package/dist/off.js +155 -0
  94. package/dist/outline-font.d.ts +87 -0
  95. package/dist/outline-font.js +110 -0
  96. package/dist/outline.d.ts +20 -0
  97. package/dist/outline.js +215 -0
  98. package/dist/pcd.d.ts +34 -0
  99. package/dist/pcd.js +258 -0
  100. package/dist/pdb.d.ts +67 -0
  101. package/dist/pdb.js +126 -0
  102. package/dist/ply.d.ts +35 -0
  103. package/dist/ply.js +392 -0
  104. package/dist/polygon.d.ts +9 -0
  105. package/dist/polygon.js +49 -0
  106. package/dist/prwm.d.ts +24 -0
  107. package/dist/prwm.js +114 -0
  108. package/dist/render.d.ts +27 -0
  109. package/dist/render.js +153 -0
  110. package/dist/sfnt-cff.d.ts +37 -0
  111. package/dist/sfnt-cff.js +749 -0
  112. package/dist/sfnt-layout.d.ts +24 -0
  113. package/dist/sfnt-layout.js +266 -0
  114. package/dist/sfnt-reader.d.ts +28 -0
  115. package/dist/sfnt-reader.js +87 -0
  116. package/dist/sfnt-variation.d.ts +40 -0
  117. package/dist/sfnt-variation.js +318 -0
  118. package/dist/shared/asset-url.js +82 -0
  119. package/dist/shared/crc32.d.ts +2 -0
  120. package/dist/shared/crc32.js +47 -0
  121. package/dist/shared/errors.js +36 -0
  122. package/dist/shared/inflate.js +284 -0
  123. package/dist/shared/normals.js +26 -0
  124. package/dist/shared/scene-scope.js +56 -0
  125. package/dist/shared/trailing-data.js +42 -0
  126. package/dist/stl.d.ts +64 -0
  127. package/dist/stl.js +309 -0
  128. package/dist/svg.d.ts +90 -0
  129. package/dist/svg.js +1007 -0
  130. package/dist/tds.d.ts +2 -0
  131. package/dist/tds.js +2 -0
  132. package/dist/textures.d.ts +42 -0
  133. package/dist/textures.js +53 -0
  134. package/dist/threemf-lattice.d.ts +139 -0
  135. package/dist/threemf-lattice.js +514 -0
  136. package/dist/threemf-materials.d.ts +75 -0
  137. package/dist/threemf-materials.js +314 -0
  138. package/dist/threemf-mesh.d.ts +60 -0
  139. package/dist/threemf-mesh.js +201 -0
  140. package/dist/threemf.d.ts +101 -0
  141. package/dist/threemf.js +415 -0
  142. package/dist/tilt.d.ts +62 -0
  143. package/dist/tilt.js +186 -0
  144. package/dist/tmx.d.ts +151 -0
  145. package/dist/tmx.js +394 -0
  146. package/dist/ttf.d.ts +78 -0
  147. package/dist/ttf.js +568 -0
  148. package/dist/types.d.ts +90 -0
  149. package/dist/types.js +35 -0
  150. package/dist/usd.d.ts +2 -0
  151. package/dist/usd.js +2 -0
  152. package/dist/usd.worker.d.ts +1 -0
  153. package/dist/usdz.d.ts +50 -0
  154. package/dist/usdz.js +646 -0
  155. package/dist/util.d.ts +75 -0
  156. package/dist/util.js +241 -0
  157. package/dist/vdb.d.ts +111 -0
  158. package/dist/vdb.js +663 -0
  159. package/dist/vrml.d.ts +53 -0
  160. package/dist/vrml.js +532 -0
  161. package/dist/vtk-cells.d.ts +29 -0
  162. package/dist/vtk-cells.js +211 -0
  163. package/dist/vtk-legacy.d.ts +57 -0
  164. package/dist/vtk-legacy.js +439 -0
  165. package/dist/vtk-reader.d.ts +19 -0
  166. package/dist/vtk-reader.js +134 -0
  167. package/dist/vtk-xml.d.ts +96 -0
  168. package/dist/vtk-xml.js +578 -0
  169. package/dist/vtk.d.ts +13 -0
  170. package/dist/vtk.js +234 -0
  171. package/dist/woff-glyf.d.ts +17 -0
  172. package/dist/woff-glyf.js +215 -0
  173. package/dist/worker.d.ts +10 -0
  174. package/dist/worker.js +93 -0
  175. package/dist/workers/usd.js +3 -0
  176. package/dist/xfile.d.ts +99 -0
  177. package/dist/xfile.js +706 -0
  178. package/dist/xml.d.ts +107 -0
  179. package/dist/xml.js +843 -0
  180. package/dist/xyz.d.ts +16 -0
  181. package/dist/xyz.js +110 -0
  182. package/dist/zip.d.ts +38 -0
  183. package/dist/zip.js +150 -0
  184. package/package.json +246 -6
@@ -0,0 +1,318 @@
1
+ import { fontError } from './sfnt-reader.js';
2
+ const tail = (r, offset) => r.slice(offset, r.length - offset);
3
+ const f2 = (r) => r.i16() / 16384;
4
+ /** a*b/c of 16.16 integers, rounded half away from zero (all three fit 2^17, so the product is exact in a double). */
5
+ const mulDiv = (a, b, c) => {
6
+ const q = (a * b) / c;
7
+ return Math.sign(q) * Math.round(Math.abs(q));
8
+ };
9
+ /** Internal OpenType ItemVariationStore, shared by CFF2 blending and HVAR widths. */
10
+ export class FontItemStore {
11
+ constructor(reader, coordinates) {
12
+ this.reader = reader;
13
+ reader.seek(0);
14
+ if (reader.u16() !== 1)
15
+ fontError('ItemVariationStore format must be 1');
16
+ const regionOffset = reader.u32(), count = reader.u16();
17
+ reader.check(reader.pos, count * 4);
18
+ this.offsets = Array.from({ length: count }, () => reader.u32());
19
+ const regions = tail(reader, regionOffset), axes = regions.u16(), n = regions.u16();
20
+ if (axes !== coordinates.length)
21
+ fontError('variation region axis count differs from fvar');
22
+ regions.check(regions.pos, n * axes * 6);
23
+ this.regions = Array.from({ length: n }, () => {
24
+ let scalar = 1;
25
+ for (let a = 0; a < axes; a++) {
26
+ const start = f2(regions), peak = f2(regions), end = f2(regions), v = coordinates[a];
27
+ // Invalid/cross-zero supports do not participate for this axis, per OpenType.
28
+ if (start > peak || peak > end || (start < 0 && end > 0 && peak !== 0) || peak === 0)
29
+ continue;
30
+ if (v < start || v > end)
31
+ scalar = 0;
32
+ else if (v !== peak)
33
+ scalar *= v < peak ? (v - start) / (peak - start) : (end - v) / (end - peak);
34
+ }
35
+ return scalar;
36
+ });
37
+ }
38
+ row(outer) {
39
+ if (!Number.isInteger(outer) || outer < 0 || outer >= this.offsets.length)
40
+ fontError('variation data index is invalid');
41
+ if (this.offsets[outer] === 0)
42
+ return { r: this.reader.slice(0, 0), count: 0, weights: [], long: false, wordCount: 0 };
43
+ const r = tail(this.reader, this.offsets[outer]);
44
+ const count = r.u16(), words = r.u16(), regions = r.u16();
45
+ const long = !!(words & 0x8000), wordCount = words & 0x7fff;
46
+ if (wordCount > regions)
47
+ fontError('variation word count exceeds region count');
48
+ r.check(r.pos, regions * 2);
49
+ const weights = Array.from({ length: regions }, () => {
50
+ const i = r.u16();
51
+ if (i >= this.regions.length)
52
+ fontError('variation region index is invalid');
53
+ return this.regions[i];
54
+ });
55
+ return { r, count, weights, long, wordCount };
56
+ }
57
+ weights(outer) {
58
+ return this.row(outer).weights;
59
+ }
60
+ delta(outer, inner) {
61
+ const { r, count, weights, long, wordCount } = this.row(outer);
62
+ if (count === 0 && weights.length === 0 && this.offsets[outer] === 0)
63
+ return 0;
64
+ if (!Number.isInteger(inner) || inner < 0 || inner >= count)
65
+ fontError('variation delta-set index is invalid');
66
+ const stride = wordCount * (long ? 4 : 2) + (weights.length - wordCount) * (long ? 2 : 1);
67
+ r.skip(inner * stride);
68
+ let value = 0;
69
+ for (let i = 0; i < weights.length; i++)
70
+ value += weights[i] * (i < wordCount ? (long ? r.i32() : r.i16()) : long ? r.i16() : r.i8());
71
+ return value;
72
+ }
73
+ }
74
+ function mappedIndex(r, offset, index) {
75
+ if (!offset)
76
+ return [0, index];
77
+ const map = tail(r, offset), format = map.u8(), entry = map.u8();
78
+ if (format !== 0 && format !== 1)
79
+ fontError('DeltaSetIndexMap format is unsupported', 'unsupported');
80
+ const count = format === 0 ? map.u16() : map.u32(), size = ((entry >> 4) & 3) + 1, bits = (entry & 15) + 1;
81
+ if (!count || bits > size * 8 || entry & 0xc0)
82
+ fontError('DeltaSetIndexMap encoding is invalid');
83
+ map.skip(Math.min(index, count - 1) * size);
84
+ let value = 0;
85
+ for (let i = 0; i < size; i++)
86
+ value = value * 256 + map.u8();
87
+ return [Math.floor(value / 2 ** bits), value % 2 ** bits];
88
+ }
89
+ /** Internal normalized instance, metrics and glyph tuple variations. */
90
+ export class FontVariations {
91
+ constructor(tables, glyphCount, values = {}) {
92
+ this.axes = [];
93
+ this.coordinates = [];
94
+ /** 16.16 normalized coordinates before the final F2Dot14 step. */
95
+ this.fixed = [];
96
+ const fvar = tables.get('fvar');
97
+ if (fvar) {
98
+ fvar.seek(0);
99
+ if (fvar.u16() !== 1)
100
+ fontError('fvar major version is unsupported', 'unsupported');
101
+ fvar.u16();
102
+ const offset = fvar.u16();
103
+ fvar.u16();
104
+ const count = fvar.u16(), size = fvar.u16();
105
+ if (size < 20)
106
+ fontError('fvar axis record is too small');
107
+ fvar.check(offset, count * size);
108
+ for (let i = 0; i < count; i++) {
109
+ fvar.seek(offset + i * size);
110
+ const tag = fvar.tag(), min = fvar.i32(), def = fvar.i32(), max = fvar.i32();
111
+ const axis = { tag, min: min / 65536, default: def / 65536, max: max / 65536 };
112
+ if (axis.min > axis.default || axis.default > axis.max || this.axes.some((a) => a.tag === axis.tag))
113
+ fontError('fvar axis bounds or tags are invalid');
114
+ const user = values[axis.tag] ?? axis.default;
115
+ if (!Number.isFinite(user))
116
+ fontError('variation axis value is not finite', 'range');
117
+ // OpenType "Coordinate scales and normalization": the user value as 16.16 Fixed, clamped, then the default
118
+ // normalization in 16.16 (kept here as a 16.16 integer until the final F2Dot14 step below).
119
+ const v = Math.max(min, Math.min(max, Math.round(user * 65536)));
120
+ this.axes.push(axis);
121
+ this.fixed.push(v === def ? 0 : v < def ? -mulDiv(def - v, 65536, def - min) : mulDiv(v - def, 65536, max - def));
122
+ }
123
+ }
124
+ for (const key of Object.keys(values))
125
+ if (!this.axes.some((a) => a.tag === key))
126
+ fontError(`variation axis ${key} is absent from fvar`, 'range');
127
+ const avar = tables.get('avar');
128
+ if (avar) {
129
+ avar.seek(0);
130
+ const major = avar.u16();
131
+ avar.u16();
132
+ avar.u16();
133
+ if (major !== 1 || avar.u16() !== this.axes.length)
134
+ fontError('avar version or axis count is invalid');
135
+ for (let i = 0; i < this.axes.length; i++) {
136
+ const count = avar.u16(), pairs = [];
137
+ avar.check(avar.pos, count * 4);
138
+ // OpenType avar: a record whose from (or to) does not increase on the last kept one may be ignored; a map
139
+ // without all of -1 to -1, 0 to 0 and 1 to 1 (an empty map included) leaves the axis unmodified.
140
+ // Map values are F2Dot14, widened to 16.16 (x4) so the interpolation runs in 16.16 like the normalization.
141
+ for (let j = 0; j < count; j++) {
142
+ const p = [avar.i16() * 4, avar.i16() * 4], last = pairs[pairs.length - 1];
143
+ if (!last || (p[0] > last[0] && p[1] >= last[1]))
144
+ pairs.push(p);
145
+ }
146
+ if (![-65536, 0, 65536].every((v) => pairs.some((p) => p[0] === v && p[1] === v)))
147
+ continue;
148
+ for (let j = 1; j < pairs.length; j++) {
149
+ const v = this.fixed[i];
150
+ if (v >= pairs[j - 1][0] && v <= pairs[j][0]) {
151
+ this.fixed[i] =
152
+ pairs[j - 1][1] +
153
+ mulDiv(v - pairs[j - 1][0], pairs[j][1] - pairs[j - 1][1], pairs[j][0] - pairs[j - 1][0]);
154
+ break;
155
+ }
156
+ }
157
+ }
158
+ }
159
+ // The final normalized coordinate is F2Dot14: (v + 2) >> 2 of the 16.16 value (OpenType, same section).
160
+ for (const v of this.fixed)
161
+ this.coordinates.push(((v + 2) >> 2) / 16384);
162
+ const hvar = tables.get('HVAR');
163
+ if (hvar) {
164
+ hvar.seek(0);
165
+ if (hvar.u16() !== 1)
166
+ fontError('HVAR version is unsupported', 'unsupported');
167
+ hvar.u16();
168
+ const store = hvar.u32(), map = hvar.u32();
169
+ this.hvar = { reader: hvar, store: new FontItemStore(tail(hvar, store), this.coordinates), map };
170
+ }
171
+ const gvar = tables.get('gvar');
172
+ if (gvar) {
173
+ gvar.seek(0);
174
+ if (gvar.u16() !== 1)
175
+ fontError('gvar version is unsupported', 'unsupported');
176
+ gvar.u16();
177
+ const axes = gvar.u16(), shared = gvar.u16(), sharedOffset = gvar.u32(), glyphs = gvar.u16(), flags = gvar.u16(), base = gvar.u32();
178
+ if (axes !== this.axes.length || glyphs !== glyphCount)
179
+ fontError('gvar axis or glyph count differs from font');
180
+ gvar.check(gvar.pos, (glyphs + 1) * (flags & 1 ? 4 : 2));
181
+ const offsets = Array.from({ length: glyphs + 1 }, () => (flags & 1 ? gvar.u32() : 2 * gvar.u16()));
182
+ for (let i = 0; i < glyphs; i++)
183
+ if (offsets[i] > offsets[i + 1])
184
+ fontError('gvar offsets are not monotone');
185
+ gvar.check(base, offsets[glyphs]);
186
+ const tuplesReader = tail(gvar, sharedOffset);
187
+ tuplesReader.check(0, shared * axes * 2);
188
+ const tuples = Array.from({ length: shared }, () => Array.from({ length: axes }, () => f2(tuplesReader)));
189
+ this.gvar = { reader: gvar, offsets, tuples, base };
190
+ }
191
+ }
192
+ advance(glyph) {
193
+ if (!this.hvar)
194
+ return undefined;
195
+ return this.hvar.store.delta(...mappedIndex(this.hvar.reader, this.hvar.map, glyph));
196
+ }
197
+ get hasGlyphVariations() {
198
+ return !!this.gvar;
199
+ }
200
+ deltas(glyph, points, ends, composite = false) {
201
+ const count = points.length + 4, dx = new Array(count).fill(0), dy = new Array(count).fill(0), g = this.gvar;
202
+ if (!g || g.offsets[glyph] === g.offsets[glyph + 1])
203
+ return [dx, dy];
204
+ const r = g.reader.slice(g.base + g.offsets[glyph], g.offsets[glyph + 1] - g.offsets[glyph]);
205
+ const flags = r.u16(), dataOffset = r.u16(), headers = [];
206
+ const tuple = () => Array.from({ length: this.axes.length }, () => f2(r));
207
+ for (let i = 0; i < (flags & 0xfff); i++) {
208
+ const size = r.u16(), index = r.u16(), peak = index & 0x8000 ? tuple() : g.tuples[index & 0xfff];
209
+ if (!peak)
210
+ fontError('gvar shared tuple index is invalid');
211
+ const start = index & 0x4000 ? tuple() : undefined, end = index & 0x4000 ? tuple() : undefined;
212
+ headers.push({ size, index, peak, start, end });
213
+ }
214
+ if (r.pos > dataOffset)
215
+ fontError('gvar tuple headers overlap data');
216
+ r.seek(dataOffset);
217
+ const sharedPoints = flags & 0x8000 ? packedPoints(r, count) : null;
218
+ let pos = r.pos;
219
+ for (const h of headers) {
220
+ const data = r.slice(pos, h.size);
221
+ pos += h.size;
222
+ const selected = h.index & 0x2000 ? packedPoints(data, count) : sharedPoints;
223
+ const n = selected?.length ?? count, x = packedDeltas(data, n), y = packedDeltas(data, n);
224
+ let scalar = 1;
225
+ // The region scalar of the OpenType variations overview; a non-intermediate region spans zero to its peak.
226
+ for (let a = 0; a < this.axes.length; a++) {
227
+ const v = this.coordinates[a], peak = h.peak[a], start = h.start ? h.start[a] : Math.min(peak, 0), end = h.end ? h.end[a] : Math.max(peak, 0);
228
+ if (start > peak || peak > end || (start < 0 && end > 0 && peak !== 0) || peak === 0)
229
+ continue;
230
+ if (v < start || v > end) {
231
+ scalar = 0;
232
+ break;
233
+ }
234
+ if (v !== peak)
235
+ scalar *= v < peak ? (v - start) / (peak - start) : (end - v) / (end - peak);
236
+ }
237
+ if (!scalar)
238
+ continue;
239
+ const xs = new Array(count), ys = new Array(count);
240
+ // A repeated point number carries several deltas, applied cumulatively (OpenType packed point numbers).
241
+ for (let i = 0; i < n; i++) {
242
+ const at = selected?.[i] ?? i;
243
+ xs[at] = (xs[at] ?? 0) + x[i];
244
+ ys[at] = (ys[at] ?? 0) + y[i];
245
+ }
246
+ if (selected && !composite) {
247
+ iup(points, ends, xs, 0);
248
+ iup(points, ends, ys, 1);
249
+ }
250
+ for (let i = 0; i < count; i++) {
251
+ dx[i] += (xs[i] ?? 0) * scalar;
252
+ dy[i] += (ys[i] ?? 0) * scalar;
253
+ }
254
+ }
255
+ return [dx, dy];
256
+ }
257
+ }
258
+ function packedPoints(r, total) {
259
+ let count = r.u8();
260
+ if (!count)
261
+ return null;
262
+ if (count & 0x80)
263
+ count = ((count & 0x7f) << 8) | r.u8();
264
+ if (count > total)
265
+ fontError('gvar point count exceeds glyph points');
266
+ const out = [];
267
+ let value = 0;
268
+ while (out.length < count) {
269
+ const run = r.u8(), n = (run & 0x7f) + 1;
270
+ if (out.length + n > count)
271
+ fontError('gvar point run exceeds its count');
272
+ for (let i = 0; i < n; i++) {
273
+ value += run & 0x80 ? r.u16() : r.u8();
274
+ if (value >= total)
275
+ fontError('gvar point index is invalid');
276
+ out.push(value);
277
+ }
278
+ }
279
+ return out;
280
+ }
281
+ function packedDeltas(r, count) {
282
+ const out = [];
283
+ while (out.length < count) {
284
+ const run = r.u8(), n = (run & 63) + 1;
285
+ if (out.length + n > count)
286
+ fontError('gvar delta run exceeds its count');
287
+ for (let i = 0; i < n; i++)
288
+ out.push(run & 0x80 ? 0 : run & 0x40 ? r.i16() : r.i8());
289
+ }
290
+ return out;
291
+ }
292
+ function iup(points, ends, deltas, axis) {
293
+ let start = 0;
294
+ for (const end of ends) {
295
+ const refs = [];
296
+ for (let i = start; i <= end; i++)
297
+ if (deltas[i] !== undefined)
298
+ refs.push(i);
299
+ if (refs.length === 1)
300
+ for (let i = start; i <= end; i++)
301
+ deltas[i] = deltas[refs[0]];
302
+ else if (refs.length > 1)
303
+ for (let j = 0; j < refs.length; j++) {
304
+ const a = refs[j], b = refs[(j + 1) % refs.length];
305
+ let i = a === end ? start : a + 1;
306
+ while (i !== b) {
307
+ let low = a, high = b;
308
+ if (points[low][axis] > points[high][axis])
309
+ [low, high] = [high, low];
310
+ const lo = points[low][axis], hi = points[high][axis], v = points[i][axis], dl = deltas[low], dh = deltas[high];
311
+ deltas[i] =
312
+ lo === hi ? (dl === dh ? dl : 0) : v <= lo ? dl : v >= hi ? dh : dl + ((dh - dl) * (v - lo)) / (hi - lo);
313
+ i = i === end ? start : i + 1;
314
+ }
315
+ }
316
+ start = end + 1;
317
+ }
318
+ }
@@ -0,0 +1,82 @@
1
+ // URIs read from inside a model file (glTF buffers and images, FBX/MTL texture names, 3MF/USDZ references) are
2
+ // untrusted. They resolve against the file's own URL and must stay inside its directory on the same origin; anything
3
+ // else (absolute or cross-origin URLs, `../` past the base, non-HTTP schemes such as javascript:, file: or blob:) is
4
+ // refused unless it lies under one of the app's `allowedURLs` entries. data: URIs are decoded by each loader within
5
+ // its byte budget and never reach this function.
6
+
7
+ // Encoded separators and encoded dot segments are refused on every branch: some servers decode `..%2F` or `%2e%2e`
8
+ // into a parent step after this check, so a path that looks contained here could leave the directory there.
9
+ // A proxy chain may decode more than once, so the same rule is applied after each decoding round (`%252e%252e`
10
+ // becomes `%2e%2e`, which the rule refuses). A path still changing after 8 rounds is refused.
11
+ // An encoded NUL (`%00`, at any depth, or the NUL itself once decoded) is refused too: it ends the name in C-based
12
+ // file APIs, so `ok%00.png` can name `ok` there (audit 2026-10-28).
13
+ const ENCODED_ESCAPE = /%2f|%5c|%00|\u0000|(^|\/)(\.|%2e){1,2}(\/|$)/i;
14
+
15
+ /** True when the path, at any depth of percent-decoding, holds an encoded separator or a dot segment. */
16
+ function hidesEscape(path) {
17
+ for (let round = 0; round < 8; round++) {
18
+ if (ENCODED_ESCAPE.test(path)) return true;
19
+ const next = path.replace(/%[\da-f]{2}/gi, (triplet) => String.fromCharCode(`0x${triplet.slice(1)}`));
20
+ if (next === path) return false;
21
+ path = next;
22
+ }
23
+ return true;
24
+ }
25
+
26
+ /**
27
+ * True when url lies under the allowedURLs entry prefix. An entry ending in `/` is a directory and matches everything
28
+ * below it; any other entry matches that exact path, or a directory of that name (`/assets` matches `/assets`,
29
+ * `/assets/x.png` and `/assets?v=1`, never `/assets-other`). An entry with a query string matches only that query.
30
+ */
31
+ function underPrefix(url, prefix) {
32
+ let entry;
33
+ try {
34
+ entry = new URL(prefix);
35
+ } catch {
36
+ throw new TypeError(`allowedURLs entry ${String(prefix)} is not an absolute URL; pass a full http(s) URL`);
37
+ }
38
+ if (entry.origin !== url.origin || (entry.protocol !== 'http:' && entry.protocol !== 'https:')) return false;
39
+ if (entry.search && entry.search !== url.search) return false;
40
+ const dir = entry.pathname;
41
+ if (dir.endsWith('/')) return url.pathname.startsWith(dir);
42
+ return url.pathname === dir || url.pathname.startsWith(`${dir}/`);
43
+ }
44
+
45
+ /** Resolve a model-file URI against base (the model's URL), or throw a TypeError naming the refused URL. */
46
+ export function assetURL(uri, base, allowedURLs = [], label = 'Asset') {
47
+ if (typeof uri !== 'string' || !uri || uri.length > 8192)
48
+ throw new TypeError(`Invalid ${label} URI; pass a shorter string`);
49
+ let url;
50
+ try {
51
+ url = new URL(uri, base);
52
+ } catch {
53
+ throw new TypeError(`Invalid ${label} URI; pass a valid URL`);
54
+ }
55
+ if ((url.protocol === 'http:' || url.protocol === 'https:') && !hidesEscape(url.pathname)) {
56
+ for (const prefix of allowedURLs) if (underPrefix(url, prefix)) return url;
57
+ const root = base === undefined ? undefined : new URL('.', base);
58
+ if (root && url.origin === root.origin && url.pathname.startsWith(root.pathname)) return url;
59
+ }
60
+ throw new TypeError(
61
+ `${label} URI ${url.href} leaves the model's directory; add its prefix to allowedURLs to load it`,
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Check where a fetch of a model-file resource ended up: fetch follows redirects, so the final `response.url` passes
67
+ * the same assetURL policy (base and allowedURLs) as the URI did. On a violation the body is cancelled unread and a
68
+ * TypeError names the final URL. A response with no url (a custom fetch that builds its own Response) is taken as the
69
+ * URL it was asked for.
70
+ */
71
+ export function checkRedirect(response, base, allowedURLs = [], label = 'Asset') {
72
+ if (!response.url) return response;
73
+ try {
74
+ assetURL(response.url, base, allowedURLs, label);
75
+ } catch {
76
+ response.body?.cancel().catch(() => {});
77
+ throw new TypeError(
78
+ `${label} URI redirected to ${response.url}, which leaves the model's directory; add its prefix to allowedURLs to load it`,
79
+ );
80
+ }
81
+ return response;
82
+ }
@@ -0,0 +1,2 @@
1
+ /** CRC-32 of `bytes`, continuing from `crc` (the result of a previous call) when given. */
2
+ export function crc32(bytes: Uint8Array, crc?: number): number;
@@ -0,0 +1,47 @@
1
+ // CRC-32 (ISO 3309, reflected polynomial 0xEDB88320): the exporters ZIP, USDZ and PNG writers, the decoders PNG reader,
2
+ // the headless PNG reader, the loaders ZIP reader (its public crc32), and the voxel-pathtracer PNG writer.
3
+
4
+ /** Eight 256-entry tables: table k advances a byte through k further zero bytes ("slicing-by-8"). */
5
+ let tables;
6
+
7
+ function build() {
8
+ tables = new Int32Array(256 * 8);
9
+ for (let n = 0; n < 256; n++) {
10
+ let c = n;
11
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
12
+ tables[n] = c;
13
+ }
14
+ for (let n = 0; n < 256; n++)
15
+ for (let k = 1; k < 8; k++) {
16
+ const previous = tables[(k - 1) * 256 + n];
17
+ tables[k * 256 + n] = (previous >>> 8) ^ tables[previous & 255];
18
+ }
19
+ return tables;
20
+ }
21
+
22
+ /**
23
+ * CRC-32 of `bytes`, continuing from `crc` (the result of a previous call) when given. Eight bytes per step through
24
+ * the sliced tables (about 4x the byte-at-a-time loop: the USDZ writer spent 8 of its 20 ms here), the tail a byte at a
25
+ * time; the result is the same.
26
+ */
27
+ export function crc32(bytes, crc = 0) {
28
+ const t = tables ?? build(),
29
+ n = bytes.length,
30
+ end = n - (n & 7);
31
+ let c = ~crc,
32
+ i = 0;
33
+ for (; i < end; i += 8) {
34
+ c ^= bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);
35
+ c =
36
+ t[1792 + (c & 255)] ^
37
+ t[1536 + ((c >>> 8) & 255)] ^
38
+ t[1280 + ((c >>> 16) & 255)] ^
39
+ t[1024 + (c >>> 24)] ^
40
+ t[768 + bytes[i + 4]] ^
41
+ t[512 + bytes[i + 5]] ^
42
+ t[256 + bytes[i + 6]] ^
43
+ t[bytes[i + 7]];
44
+ }
45
+ for (; i < n; i++) c = t[(c ^ bytes[i]) & 255] ^ (c >>> 8);
46
+ return ~c >>> 0;
47
+ }
@@ -0,0 +1,36 @@
1
+ // The error convention (docs/conventions.md) for code in packages/shared, which is bundled into packages that may not depend
2
+ // on @margoengine/math (importing it here would make every such package build after math without declaring it).
3
+ // The result has MargoError's name and `code`, so `error instanceof MargoError` (it matches by name) and
4
+ // `error.code` behave exactly as for the class.
5
+ export const margoError = (code, message) => Object.assign(new Error(message), { name: 'MargoError', code });
6
+
7
+ // Core and the stage keep their messages short and link each one to its entry on the error help page
8
+ // (site/errors.html, generated from scripts/errors/entries.js; tests/errors-page.test.js keeps them in step).
9
+ const linked = (message, anchor) => `${message}; see https://margoengine.com/errors#${anchor}`;
10
+ /** `margoError` whose message links to `anchor` (default the code) on the error help page. */
11
+ export const fault = (code, message, anchor = code) => margoError(code, linked(message, anchor));
12
+ /** TypeError whose message links to `anchor` on the error help page. */
13
+ export const typeError = (message, anchor) => new TypeError(linked(message, anchor));
14
+ /** RangeError whose message links to `anchor` on the error help page. */
15
+ export const rangeError = (message, anchor) => new RangeError(linked(message, anchor));
16
+
17
+ /** Reject replacement of a retained transform vector, including from non-module callers. */
18
+ export const vectorAssignment = () => {
19
+ throw Object.assign(typeError('Retained vector: use a transform setter', 'transform'), { code: 'transform' });
20
+ };
21
+
22
+ /** Translate only policy-blocked Wasm initialization, including Emscripten's wrapped abort. Keep other failures intact. */
23
+ export function wasmError(error) {
24
+ if (
25
+ !/^(Compile|Eval|Runtime)Error$/.test(error?.name) ||
26
+ !/wasm-unsafe-eval|content security policy|\bCSP\b|disallowed by embedder/i.test(error.message)
27
+ )
28
+ return error;
29
+ return Object.assign(
30
+ margoError(
31
+ 'failed',
32
+ "Wasm compilation blocked by CSP; add 'wasm-unsafe-eval' to script-src; see https://margoengine.com/llms/docs/csp.md",
33
+ ),
34
+ { cause: error },
35
+ );
36
+ }