@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,514 @@
1
+ import { LoaderError } from './types.js';
2
+ import { limits, resolvePath, throwIfAborted } from './util.js';
3
+ import { read3MFMaterials } from './threemf-materials.js';
4
+ import { readXMLTree, decodeXML } from './xml.js';
5
+ const F = '3MF';
6
+ const attribute = (a, name) => a[name] ?? Object.entries(a).find(([key]) => key.endsWith(':' + name))?.[1];
7
+ function number(value, name, fallback) {
8
+ const n = value === undefined ? fallback : Number(value);
9
+ if (n === undefined || !Number.isFinite(n))
10
+ throw new LoaderError(F, 'syntax', `${name} must be a finite number`);
11
+ return n;
12
+ }
13
+ function index(value, name) {
14
+ const n = number(value, name);
15
+ if (!Number.isSafeInteger(n) || n < 0 || n >= 2147483648)
16
+ throw new LoaderError(F, 'range', `${name} must be a nonnegative 31-bit index`);
17
+ return n;
18
+ }
19
+ function positive(value, name, fallback) {
20
+ const n = number(value, name, fallback);
21
+ if (n <= 0)
22
+ throw new LoaderError(F, 'range', `${name} must be positive`);
23
+ return n;
24
+ }
25
+ function choice(value, values, fallback) {
26
+ if (value === undefined)
27
+ return fallback;
28
+ if (!values.includes(value))
29
+ throw new LoaderError(F, 'range', `expected ${values.join(', ')}; got ${value}`);
30
+ return value;
31
+ }
32
+ const cap = (value) => choice(value, ['sphere', 'hemisphere', 'butt'], 'sphere');
33
+ const own = (a) => Object.assign(Object.create(null), a);
34
+ const normalize = (path) => path.replaceAll('\\', '/').replace(/^\/+/, '').toLowerCase();
35
+ const list = (value, name) => {
36
+ if (!value?.trim())
37
+ throw new LoaderError(F, 'syntax', `${name} needs values`);
38
+ return value
39
+ .trim()
40
+ .split(/\s+/)
41
+ .map((v) => number(v, name));
42
+ };
43
+ /** Reads exact native beam/ball and slice resources alongside the existing textured/composite/multi material mesh. */
44
+ export async function parse3MFLattice(input, options = {}) {
45
+ const limit = limits(options, F), maxBeams = options.maxBeams ?? 1000000, maxSlices = options.maxSlices ?? 100000;
46
+ if (!Number.isSafeInteger(maxBeams) || maxBeams < 1 || !Number.isSafeInteger(maxSlices) || maxSlices < 1)
47
+ throw new LoaderError(F, 'limit', 'maxBeams and maxSlices must be positive safe integers');
48
+ throwIfAborted(options.signal, F);
49
+ const states = new Map(), instances = [], sliceInstances = [];
50
+ const ancestors = [];
51
+ let objectCount = 0, references = 0, expandedLayers = 0;
52
+ let beams = 0, balls = 0, slices = 0, vertices = 0, segments = 0;
53
+ const state = (m) => {
54
+ let s = states.get(m);
55
+ if (!s) {
56
+ s = { part: '', objects: new Map(), stacks: new Map(), properties: new Map(), xyz: [], xy: [] };
57
+ states.set(m, s);
58
+ }
59
+ return s;
60
+ };
61
+ const propertyRef = (a, pid, p) => ({
62
+ pid: a.pid ?? pid,
63
+ property: a.pindex === undefined ? p : index(a.pindex, 'pindex'),
64
+ });
65
+ const hooks = {
66
+ element(m, name, a) {
67
+ const s = state(m), obj = s.object;
68
+ if (name === 'model') {
69
+ const required = (a.requiredextensions ?? '').trim().split(/\s+/);
70
+ s.requiredSlice = Object.entries(a).some(([key, value]) => key.startsWith('xmlns:') &&
71
+ value === 'http://schemas.microsoft.com/3dmanufacturing/slice/2015/07' &&
72
+ required.includes(key.slice(6)));
73
+ }
74
+ else if (name === 'object') {
75
+ if (++objectCount > 100000)
76
+ throw new LoaderError(F, 'limit', 'native objects exceed 100000');
77
+ const id = a.id;
78
+ if (!id || s.objects.has(id))
79
+ throw new LoaderError(F, 'syntax', 'native object id is missing or duplicated');
80
+ s.object = {
81
+ part: '',
82
+ id,
83
+ type: a.type ?? 'model',
84
+ pid: a.pid,
85
+ property: a.pindex === undefined ? undefined : index(a.pindex, 'pindex'),
86
+ vertices: new Float64Array(),
87
+ triangles: new Uint32Array(),
88
+ };
89
+ s.objects.set(id, s.object);
90
+ s.xyz = [];
91
+ const stack = attribute(a, 'slicestackid');
92
+ if (stack)
93
+ s.object.slices = {
94
+ part: attribute(a, 'slicepath') ?? '',
95
+ id: stack,
96
+ resolution: choice(attribute(a, 'meshresolution'), ['fullres', 'lowres'], 'fullres'),
97
+ };
98
+ }
99
+ else if (name === 'vertex') {
100
+ if (++vertices > limit.maxVertices)
101
+ throw new LoaderError(F, 'limit', 'native/slice vertices exceed maxVertices');
102
+ if (s.slice) {
103
+ s.xy.push(number(a.x, 'slice x'), number(a.y, 'slice y'));
104
+ return true;
105
+ }
106
+ if (obj)
107
+ s.xyz.push(number(a.x, 'vertex x'), number(a.y, 'vertex y'), number(a.z, 'vertex z'));
108
+ }
109
+ else if (name === 'beamlattice') {
110
+ if (!obj || obj.lattice)
111
+ throw new LoaderError(F, 'syntax', 'beamlattice needs a distinct mesh object');
112
+ const r = propertyRef(a, m.objects.get(obj.id)?.pid, m.objects.get(obj.id)?.pindex);
113
+ const lattice = {
114
+ radius: positive(a.radius, 'radius'),
115
+ minLength: positive(a.minlength, 'minlength'),
116
+ cap: cap(a.cap),
117
+ ballMode: choice(attribute(a, 'ballmode'), ['none', 'mixed', 'all'], 'none'),
118
+ clippingMode: choice(a.clippingmode, ['none', 'inside', 'outside'], 'none'),
119
+ clippingMesh: a.clippingmesh,
120
+ representationMesh: a.representationmesh,
121
+ ...r,
122
+ beams: [],
123
+ balls: [],
124
+ sets: [],
125
+ activeBeams: new Uint32Array(),
126
+ effectiveBalls: [],
127
+ };
128
+ const br = attribute(a, 'ballradius');
129
+ if (br !== undefined)
130
+ lattice.ballRadius = positive(br, 'ballradius');
131
+ if (lattice.ballMode !== 'none' && lattice.ballRadius === undefined)
132
+ throw new LoaderError(F, 'syntax', 'ballmode needs ballradius');
133
+ obj.lattice = lattice;
134
+ s.lattice = lattice;
135
+ }
136
+ else if (name === 'beam') {
137
+ const l = s.lattice;
138
+ if (!l)
139
+ throw new LoaderError(F, 'syntax', 'beam outside beamlattice');
140
+ if (++beams > maxBeams)
141
+ throw new LoaderError(F, 'limit', 'beam count exceeds maxBeams');
142
+ if (a.r2 !== undefined && a.r1 === undefined)
143
+ throw new LoaderError(F, 'syntax', 'r2 requires r1');
144
+ const r1 = positive(a.r1, 'r1', l.radius), beam = {
145
+ v1: index(a.v1, 'v1'),
146
+ v2: index(a.v2, 'v2'),
147
+ r1,
148
+ r2: positive(a.r2, 'r2', r1),
149
+ cap1: a.cap1 === undefined ? l.cap : cap(a.cap1),
150
+ cap2: a.cap2 === undefined ? l.cap : cap(a.cap2),
151
+ pid: a.pid ?? l.pid,
152
+ p1: a.p1 === undefined ? l.property : index(a.p1, 'p1'),
153
+ p2: a.p2 === undefined ? l.property : index(a.p2, 'p2'),
154
+ };
155
+ l.beams.push(beam);
156
+ }
157
+ else if (name === 'ball') {
158
+ const l = s.lattice;
159
+ if (!l)
160
+ throw new LoaderError(F, 'syntax', 'ball outside beamlattice');
161
+ if (++balls > maxBeams)
162
+ throw new LoaderError(F, 'limit', 'ball count exceeds maxBeams');
163
+ l.balls.push({
164
+ vertex: index(a.vindex, 'vindex'),
165
+ radius: positive(a.r, 'ball radius', l.ballRadius),
166
+ pid: a.pid ?? l.pid,
167
+ property: a.p === undefined ? l.property : index(a.p, 'ball property'),
168
+ });
169
+ }
170
+ else if (name === 'beamset') {
171
+ if (!s.lattice || s.beamSet)
172
+ throw new LoaderError(F, 'syntax', 'invalid beamset nesting');
173
+ s.beamSet = { name: a.name, identifier: a.identifier, beams: [], balls: [] };
174
+ }
175
+ else if (name === 'ref' && s.beamSet) {
176
+ if (++references > maxBeams * 2)
177
+ throw new LoaderError(F, 'limit', 'beamset references exceed the native primitive budget');
178
+ s.beamSet.beams.push(index(a.index, 'beam ref'));
179
+ }
180
+ else if (name === 'ballref' && s.beamSet) {
181
+ if (++references > maxBeams * 2)
182
+ throw new LoaderError(F, 'limit', 'beamset references exceed the native primitive budget');
183
+ s.beamSet.balls.push(index(a.index, 'ball ref'));
184
+ }
185
+ else if (name === 'slicestack') {
186
+ if (s.stack || !a.id || s.stacks.has(a.id))
187
+ throw new LoaderError(F, 'syntax', 'invalid slicestack id or nesting');
188
+ s.stack = {
189
+ part: '',
190
+ id: a.id,
191
+ bottom: number(a.zbottom, 'zbottom', 0),
192
+ slices: [],
193
+ references: [],
194
+ layers: [],
195
+ };
196
+ s.stacks.set(a.id, s.stack);
197
+ }
198
+ else if (name === 'sliceref') {
199
+ if (!s.stack || !a.slicepath || !a.slicestackid)
200
+ throw new LoaderError(F, 'syntax', 'sliceref requires a stack, path and id');
201
+ if (++slices > maxSlices)
202
+ throw new LoaderError(F, 'limit', 'slice references exceed maxSlices');
203
+ s.stack.references.push({ part: a.slicepath, id: a.slicestackid });
204
+ }
205
+ else if (name === 'slice') {
206
+ if (!s.stack || s.slice)
207
+ throw new LoaderError(F, 'syntax', 'slice outside stack or nested');
208
+ if (++slices > maxSlices)
209
+ throw new LoaderError(F, 'limit', 'layers exceed maxSlices');
210
+ s.slice = { top: number(a.ztop, 'ztop'), vertices: new Float64Array(), polygons: [] };
211
+ s.stack.slices.push(s.slice);
212
+ s.xy = [];
213
+ }
214
+ else if (name === 'polygon' && s.slice) {
215
+ if (s.polygon)
216
+ throw new LoaderError(F, 'syntax', 'nested slice polygon');
217
+ s.polygon = { start: index(a.startv, 'startv'), segments: [] };
218
+ s.slice.polygons.push(s.polygon);
219
+ }
220
+ else if (name === 'segment' && s.polygon) {
221
+ if (++segments > limit.maxTriangles * 3)
222
+ throw new LoaderError(F, 'limit', 'slice segments exceed triangle-derived limit');
223
+ const p1 = a.p1 === undefined ? undefined : index(a.p1, 'p1');
224
+ s.polygon.segments.push({
225
+ vertex: index(a.v2, 'v2'),
226
+ pid: a.pid,
227
+ p1,
228
+ p2: a.p2 === undefined ? p1 : index(a.p2, 'p2'),
229
+ });
230
+ }
231
+ if (['basematerials', 'colorgroup', 'texture2dgroup', 'compositematerials', 'multiproperties'].includes(name)) {
232
+ if (!a.id || s.properties.has(a.id))
233
+ throw new LoaderError(F, 'syntax', 'missing or duplicate property resource id');
234
+ s.property = { part: '', id: a.id, kind: name, attributes: own(a), entries: [] };
235
+ s.properties.set(a.id, s.property);
236
+ }
237
+ else if (['base', 'color', 'tex2coord', 'composite', 'multi'].includes(name) && s.property)
238
+ s.property.entries.push(own(a));
239
+ },
240
+ close(m, name) {
241
+ const s = state(m);
242
+ if (name === 'object') {
243
+ if (s.object)
244
+ s.object.vertices = Float64Array.from(s.xyz);
245
+ s.object = undefined;
246
+ s.xyz = [];
247
+ }
248
+ else if (name === 'beamlattice')
249
+ s.lattice = undefined;
250
+ else if (name === 'beamset' && s.beamSet && s.lattice) {
251
+ s.lattice.sets.push({
252
+ ...s.beamSet,
253
+ beams: Uint32Array.from(s.beamSet.beams),
254
+ balls: Uint32Array.from(s.beamSet.balls),
255
+ });
256
+ s.beamSet = undefined;
257
+ }
258
+ else if (name === 'slice' && s.slice) {
259
+ s.slice.vertices = Float64Array.from(s.xy);
260
+ s.slice = undefined;
261
+ s.xy = [];
262
+ }
263
+ else if (name === 'polygon')
264
+ s.polygon = undefined;
265
+ else if (name === 'slicestack')
266
+ s.stack = undefined;
267
+ if (name === s.property?.kind)
268
+ s.property = undefined;
269
+ },
270
+ async ready(read, context) {
271
+ const relationships = new Map();
272
+ const related = async (part, path) => {
273
+ const target = normalize(resolvePath(part, path));
274
+ if (target === part)
275
+ return;
276
+ let targets = relationships.get(part);
277
+ if (!targets) {
278
+ const at = part.lastIndexOf('/'), name = part.slice(at + 1), folder = part.slice(0, at + 1);
279
+ const tree = readXMLTree(decodeXML(await read(folder + '_rels/' + name + '.rels')), F);
280
+ targets = new Set();
281
+ for (const root of tree.children)
282
+ for (const rel of root.children)
283
+ if (rel.name === 'Relationship' &&
284
+ rel.attributes.Type?.endsWith('/3dmodel') &&
285
+ rel.attributes.TargetMode !== 'External' &&
286
+ rel.attributes.Target)
287
+ targets.add(normalize(resolvePath(part, rel.attributes.Target)));
288
+ relationships.set(part, targets);
289
+ }
290
+ if (!targets.has(target))
291
+ throw new LoaderError(F, 'syntax', 'external slice model has no OPC model relationship');
292
+ };
293
+ // Model parts loaded here use the same reader and material hooks as the root, including 2D vertices.
294
+ for (const [part, m] of context.models) {
295
+ const s = state(m);
296
+ s.part = part;
297
+ const paths = [
298
+ ...[...s.objects.values()].flatMap((o) => (o.slices?.part ? [o.slices.part] : [])),
299
+ ...[...s.stacks.values()].flatMap((stack) => stack.references.map((r) => r.part)),
300
+ ];
301
+ for (const path of paths) {
302
+ await related(part, path);
303
+ await context.loadModelPart(resolvePath(part, path));
304
+ }
305
+ }
306
+ const checkProperty = (s, id, p) => {
307
+ if (p === undefined)
308
+ return;
309
+ const resource = id && s.properties.get(id);
310
+ if (!resource || p >= resource.entries.length)
311
+ throw new LoaderError(F, 'range', 'native property index is outside its resource');
312
+ };
313
+ for (const [m, s] of states) {
314
+ throwIfAborted(options.signal, F);
315
+ for (const resource of s.properties.values()) {
316
+ resource.part = s.part;
317
+ const colors = m.properties.get(resource.id);
318
+ if (colors)
319
+ resource.colors = Float64Array.from(colors.flat());
320
+ if (resource.kind === 'compositematerials') {
321
+ const indices = list(resource.attributes.matindices, 'matindices').map((n) => index(String(n), 'matindex')), base = s.properties.get(resource.attributes.matid);
322
+ if (!base || base.kind !== 'basematerials' || indices.some((n) => n >= base.entries.length))
323
+ throw new LoaderError(F, 'range', 'composite materials reference invalid base materials');
324
+ resource.materialId = base.id;
325
+ resource.materialIndices = Uint32Array.from(indices);
326
+ resource.weights = resource.entries.map((e) => {
327
+ const source = list(e.values, 'composite weights'), weights = indices.map((_, i) => source[i] ?? 0);
328
+ if (weights.some((w) => w < 0))
329
+ throw new LoaderError(F, 'range', 'invalid composite weight row');
330
+ const sum = weights.reduce((a, b) => a + b, 0);
331
+ return Float64Array.from(weights, (w) => (sum ? w / sum : 1 / indices.length));
332
+ });
333
+ }
334
+ else if (resource.kind === 'multiproperties') {
335
+ const pids = resource.attributes.pids?.trim().split(/\s+/);
336
+ if (!pids?.length ||
337
+ pids.some((id) => !s.properties.has(id) || s.properties.get(id).kind === 'multiproperties'))
338
+ throw new LoaderError(F, 'range', 'invalid multi-property resource references');
339
+ resource.propertyIds = pids;
340
+ const blends = resource.attributes.blendmethods?.trim().split(/\s+/) ?? [];
341
+ if (blends.length >= pids.length || blends.some((b) => b !== 'mix' && b !== 'multiply'))
342
+ throw new LoaderError(F, 'range', 'invalid multi-property blend methods');
343
+ resource.blendMethods = Array.from({ length: pids.length - 1 }, (_, i) => (blends[i] ?? 'mix'));
344
+ resource.rows = resource.entries.map((e) => {
345
+ const source = list(e.pindices, 'pindices');
346
+ const row = pids.map((_, i) => index(String(source[i] ?? 0), 'property index'));
347
+ row.forEach((n, i) => checkProperty(s, pids[i], n));
348
+ return Uint32Array.from(row);
349
+ });
350
+ }
351
+ }
352
+ for (const o of s.objects.values()) {
353
+ o.part = s.part;
354
+ o.triangles = m.objects.get(o.id)?.mesh?.triangles.result() ?? new Uint32Array();
355
+ if (o.slices)
356
+ o.slices.part = o.slices.part ? normalize(resolvePath(s.part, o.slices.part)) : s.part;
357
+ if (o.slices?.resolution === 'lowres' && !s.requiredSlice)
358
+ throw new LoaderError(F, 'syntax', 'lowres slice objects require the slice namespace in requiredextensions');
359
+ const l = o.lattice;
360
+ if (!l)
361
+ continue;
362
+ if (!l.beams.length)
363
+ throw new LoaderError(F, 'syntax', 'beamlattice requires at least one beam');
364
+ if (!m.objects.get(o.id)?.mesh || m.objects.get(o.id).components.length)
365
+ throw new LoaderError(F, 'syntax', 'lattice object requires a mesh');
366
+ const pointCount = o.vertices.length / 3, active = [], ends = new Set();
367
+ l.beams.forEach((beam, i) => {
368
+ if (beam.v1 === beam.v2 || beam.v1 >= pointCount || beam.v2 >= pointCount)
369
+ throw new LoaderError(F, 'range', 'invalid beam endpoints');
370
+ checkProperty(s, beam.pid, beam.p1);
371
+ checkProperty(s, beam.pid, beam.p2);
372
+ const a = beam.v1 * 3, b = beam.v2 * 3;
373
+ if (Math.hypot(o.vertices[a] - o.vertices[b], o.vertices[a + 1] - o.vertices[b + 1], o.vertices[a + 2] - o.vertices[b + 2]) >= l.minLength) {
374
+ active.push(i);
375
+ ends.add(beam.v1);
376
+ ends.add(beam.v2);
377
+ }
378
+ });
379
+ l.activeBeams = Uint32Array.from(active);
380
+ const explicit = new Map();
381
+ for (const ball of l.balls) {
382
+ if (ball.vertex >= pointCount || explicit.has(ball.vertex))
383
+ throw new LoaderError(F, 'range', 'invalid or repeated ball vertex');
384
+ checkProperty(s, ball.pid, ball.property);
385
+ explicit.set(ball.vertex, ball);
386
+ }
387
+ if (l.ballMode !== 'none')
388
+ for (const vertex of ends) {
389
+ const ball = explicit.get(vertex);
390
+ if (ball)
391
+ l.effectiveBalls.push({ ...ball });
392
+ else if (l.ballMode === 'all')
393
+ l.effectiveBalls.push({ vertex, radius: l.ballRadius, pid: l.pid, property: l.property });
394
+ }
395
+ for (const set of l.sets)
396
+ if (set.beams.some((i) => i >= l.beams.length) || set.balls.some((i) => i >= l.balls.length))
397
+ throw new LoaderError(F, 'range', 'beamset index outside source arrays');
398
+ for (const id of [l.clippingMesh, l.representationMesh])
399
+ if (id !== undefined) {
400
+ const target = s.objects.get(id);
401
+ const ids = [...s.objects.keys()];
402
+ if (!target ||
403
+ target === o ||
404
+ target.type !== 'model' ||
405
+ target.lattice ||
406
+ !target.triangles.length ||
407
+ ids.indexOf(id) >= ids.indexOf(o.id))
408
+ throw new LoaderError(F, 'range', 'clipping/representation mesh must be an earlier non-lattice model mesh');
409
+ }
410
+ if (l.clippingMode !== 'none' && !l.clippingMesh)
411
+ throw new LoaderError(F, 'syntax', 'clippingmode requires clippingmesh');
412
+ }
413
+ for (const stack of s.stacks.values()) {
414
+ stack.part = s.part;
415
+ if (stack.slices.length && stack.references.length)
416
+ throw new LoaderError(F, 'syntax', 'slice stack cannot mix inline slices and references');
417
+ let previous = stack.bottom;
418
+ for (const slice of stack.slices) {
419
+ if (slice.top <= previous)
420
+ throw new LoaderError(F, 'range', 'slice tops must strictly increase above zbottom');
421
+ previous = slice.top;
422
+ if ((slice.vertices.length && !slice.polygons.length) || (!slice.vertices.length && slice.polygons.length))
423
+ throw new LoaderError(F, 'syntax', 'nonvoid slice needs vertices and polygons');
424
+ for (const polygon of slice.polygons) {
425
+ if (polygon.start >= slice.vertices.length / 2 || !polygon.segments.length)
426
+ throw new LoaderError(F, 'range', 'invalid slice polygon start or empty segments');
427
+ let v = polygon.start;
428
+ for (const segment of polygon.segments) {
429
+ if (segment.vertex >= slice.vertices.length / 2 || segment.vertex === v)
430
+ throw new LoaderError(F, 'range', 'invalid slice segment vertex');
431
+ if (segment.pid !== undefined) {
432
+ checkProperty(s, segment.pid, segment.p1);
433
+ checkProperty(s, segment.pid, segment.p2);
434
+ if (s.properties.get(segment.pid)?.kind === 'texture2dgroup')
435
+ throw new LoaderError(F, 'range', 'slice segments cannot reference image properties');
436
+ }
437
+ v = segment.vertex;
438
+ }
439
+ }
440
+ }
441
+ }
442
+ }
443
+ const byPart = new Map([...states.values()].map((s) => [s.part, s]));
444
+ for (const s of states.values())
445
+ for (const stack of s.stacks.values()) {
446
+ stack.layers = [...stack.slices];
447
+ let previous = stack.bottom;
448
+ for (const ref of stack.references) {
449
+ ref.part = normalize(resolvePath(s.part, ref.part));
450
+ const target = byPart.get(ref.part)?.stacks.get(ref.id);
451
+ if (!target || target.part === stack.part || target.references.length)
452
+ throw new LoaderError(F, 'range', 'slice reference must target an external stack without references');
453
+ for (const layer of target.slices) {
454
+ if (++expandedLayers > maxSlices)
455
+ throw new LoaderError(F, 'limit', 'expanded slice references exceed maxSlices');
456
+ if (layer.top <= previous)
457
+ throw new LoaderError(F, 'range', 'referenced slice heights do not increase');
458
+ stack.layers.push(layer);
459
+ previous = layer.top;
460
+ }
461
+ }
462
+ }
463
+ for (const s of states.values())
464
+ for (const o of s.objects.values())
465
+ if (o.slices) {
466
+ const stack = byPart.get(o.slices.part)?.stacks.get(o.slices.id);
467
+ if (!stack)
468
+ throw new LoaderError(F, 'range', 'object references a missing slice stack');
469
+ for (const layer of stack.layers)
470
+ for (const polygon of layer.polygons) {
471
+ if ((o.type === 'model' || o.type === 'solidsupport') &&
472
+ polygon.segments.at(-1)?.vertex !== polygon.start)
473
+ throw new LoaderError(F, 'range', 'solid slice contour is not closed');
474
+ for (const segment of polygon.segments)
475
+ if (segment.pid === undefined) {
476
+ checkProperty(s, o.pid, segment.p1);
477
+ checkProperty(s, o.pid, segment.p2);
478
+ }
479
+ }
480
+ }
481
+ },
482
+ instance(m, obj, transform, unitScale, depth) {
483
+ const s = state(m), o = s.objects.get(obj.id);
484
+ const instance = { object: o, transform: new Float64Array(transform), unitScale };
485
+ instances.push(instance);
486
+ ancestors.length = depth;
487
+ const inherited = ancestors.some(Boolean);
488
+ ancestors[depth] = inherited || !!o.slices;
489
+ if (o.slices && !inherited) {
490
+ if (transform[2] !== 0 || transform[5] !== 0 || transform[6] !== 0 || transform[7] !== 0 || transform[8] !== 1)
491
+ throw new LoaderError(F, 'range', 'slice build transform must preserve the slicing plane');
492
+ const owner = [...states.values()].find((s) => s.part === o.slices.part);
493
+ sliceInstances.push({ ...instance, stack: owner.stacks.get(o.slices.id) });
494
+ }
495
+ },
496
+ hasGeometry() {
497
+ return instances.some((i) => i.object.lattice?.activeBeams.length);
498
+ },
499
+ bucket() {
500
+ return '';
501
+ },
502
+ corner() { },
503
+ group() { },
504
+ };
505
+ const mesh = await read3MFMaterials(input, options, hooks);
506
+ return {
507
+ ...mesh,
508
+ objects: [...states.values()].flatMap((s) => [...s.objects.values()]),
509
+ instances,
510
+ sliceStacks: [...states.values()].flatMap((s) => [...s.stacks.values()]),
511
+ sliceInstances,
512
+ propertyResources: [...states.values()].flatMap((s) => [...s.properties.values()]),
513
+ };
514
+ }
@@ -0,0 +1,75 @@
1
+ import { type LoadedGroup } from './types.js';
2
+ import type { BinaryInput } from './util.js';
3
+ import { type ThreeMFExtension, type ThreeMFOptions, type ThreeMFResult } from './threemf.js';
4
+ /** One `<texture2d>` of a package with the bytes of its image. */
5
+ export interface ThreeMFTexture {
6
+ /** The part's path in the package. */
7
+ path: string;
8
+ /** `image/png` or `image/jpeg`, as the file declares. */
9
+ contentType: string;
10
+ /** The image file, ready for `createImageBitmap`. */
11
+ data: Uint8Array;
12
+ /** How u and v repeat: `wrap` (the default), `mirror`, `clamp` or `none`. */
13
+ tileStyleU: string;
14
+ tileStyleV: string;
15
+ /** `auto` (the default), `linear` or `nearest`. */
16
+ filter: string;
17
+ }
18
+ /**
19
+ * One layer of a `multiproperties` stack, in the order its `pids` list them (bottom first). Its per-vertex values are in
20
+ * `attributes[attribute]`: four numbers per vertex for a colour layer (sRGB red, green, blue and linear alpha), two for a
21
+ * texture layer (u and v, v = 1 - the file's v as in `uvs`). Vertices outside the group hold zeros.
22
+ */
23
+ export interface ThreeMFLayer {
24
+ /** `'color'` for a base material, composite or colour group layer, `'texture'` for a texture group layer. */
25
+ kind: 'color' | 'texture';
26
+ /** A texture layer's index into `textures`. */
27
+ texture?: number;
28
+ /** `layerColor<k>` or `layerUV<k>`, k the layer's place in the stack. */
29
+ attribute: string;
30
+ /**
31
+ * How the layer goes over the result of the layers below (`blendmethods`): `'mix'` (the default) or `'multiply'`. The
32
+ * spec blends in linear light: mix is `rgb = new.rgb * new.a + below.rgb * (1 - new.a)`, `a = new.a + below.a * (1 -
33
+ * new.a)`; multiply is `rgb = new.rgb * below.rgb`, `a = new.a * below.a`. The first layer starts the stack, opaque.
34
+ */
35
+ blend: 'mix' | 'multiply';
36
+ }
37
+ /** A group of {@link ThreeMFMaterials}: {@link LoadedGroup} with the texture its triangles sample. */
38
+ export interface ThreeMFMaterialGroup extends LoadedGroup {
39
+ /** Index into `textures`: the group's only texture, or the first texture layer of its `layers`. */
40
+ texture?: number;
41
+ /** The whole layer stack, when the group's triangles use a `multiproperties`; `create3MFMesh` draws it. */
42
+ layers?: ThreeMFLayer[];
43
+ }
44
+ /** What {@link parse3MFMaterials} returns: {@link ThreeMFResult} with textures, and one vertex per triangle corner. */
45
+ export interface ThreeMFMaterials extends ThreeMFResult {
46
+ groups: ThreeMFMaterialGroup[];
47
+ /** Every texture the package declares. */
48
+ textures: ThreeMFTexture[];
49
+ }
50
+ /**
51
+ * Reads a 3MF package like `parse3MF` and adds the materials extension: `texture2d` images, `texture2dgroup`
52
+ * coordinates, `compositematerials` as mixed colours, and `multiproperties` layers. Every triangle corner gets its own
53
+ * vertex, so `uvs` and `colors` can differ across a seam; `uvs` use Margo's convention, v = 1 - the file's v. `colors` is
54
+ * present when corners of a triangle differ or a layer sets them. A group's `texture` indexes `textures`. In
55
+ * `multiproperties` colour layers mix by their alpha, and the first texture layer sets the group's texture: draw
56
+ * `colors` as a tint over it.
57
+ *
58
+ * @param input The package's bytes.
59
+ * @param options The same options as `parse3MF`.
60
+ * @returns The merged mesh with its coordinates, colours and images.
61
+ * @throws LoaderError with the codes of `parse3MF`, with `range` for a property index outside its group.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
66
+ *
67
+ * const bytes = await (await fetch('/prints/lithophane.3mf')).arrayBuffer();
68
+ * const { groups, textures, uvs } = await parse3MFMaterials(bytes);
69
+ * const image = await createImageBitmap(new Blob([textures[groups[0].texture ?? 0].data]));
70
+ * console.log(image.width, uvs?.length);
71
+ * ```
72
+ */
73
+ export declare function parse3MFMaterials(input: BinaryInput, options?: ThreeMFOptions): Promise<ThreeMFMaterials>;
74
+ /** Shared materials reader with optional additional format hooks, used by the lattice/slice entry. */
75
+ export declare function read3MFMaterials(input: BinaryInput, options: ThreeMFOptions, extra?: ThreeMFExtension): Promise<ThreeMFMaterials>;