@margoengine/cad 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.
@@ -0,0 +1,589 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const u=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { a as e, i as t, n, o as r, r as i, s as a, t as o } from "./cad-async-kUFSo7gb.js";
5
+ import { t as s } from "./closed-Db7gO_Gy.js";
6
+ import { Geometry as c, PbrMaterial as l, engineRuntime as __margoRuntime, meshRuntime as d } from "@margoengine/core/extension";
7
+ import { MargoError as f } from "@margoengine/math/errors";
8
+ import { invertMatrixStable as p, multiplyMatrices as m } from "@margoengine/math/mat4";
9
+ //#region ../shared/errors.js
10
+ var h = (e, t) => Object.assign(Error(t), {
11
+ name: "MargoError",
12
+ code: e
13
+ }), g = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, _ = (e, t, n = e) => h(e, g(t, n)), v = (e, t) => TypeError(g(e, t)), y = class {
14
+ constructor(...e) {
15
+ this.failed = e.length > 0, this.error = e[0];
16
+ }
17
+ run(e) {
18
+ try {
19
+ e();
20
+ } catch (e) {
21
+ this.failed || (this.error = e), this.failed = !0;
22
+ }
23
+ return this;
24
+ }
25
+ finish() {
26
+ if (this.failed) throw this.error;
27
+ }
28
+ };
29
+ //#endregion
30
+ //#region ../shared/loading.js
31
+ async function b(e, { maxBytes: t, signal: n, label: r = "Asset", output: i = null, expected: a = 0 }) {
32
+ if (!Number.isSafeInteger(t) || t < 0 || i !== null && (!(i instanceof Uint8Array) || i.length !== t)) throw RangeError("Invalid asset byte budget; pass maxBytes as an integer");
33
+ if (n?.throwIfAborted(), !e) throw TypeError(`Empty ${r} response; check the URL`);
34
+ let o = e.getReader(), s = [], c = 0, l = i, u = new y(), d = (e) => {
35
+ try {
36
+ Promise.resolve(o.cancel(e)).catch(() => {});
37
+ } catch {}
38
+ }, f = () => d(n.reason);
39
+ n?.addEventListener("abort", f, { once: !0 });
40
+ try {
41
+ for (!i && Number.isSafeInteger(a) && a > 0 && a <= t && (l = new Uint8Array(a));;) {
42
+ n?.throwIfAborted();
43
+ let { done: e, value: i } = await o.read();
44
+ if (n?.throwIfAborted(), e) break;
45
+ if (!(i instanceof Uint8Array)) throw TypeError(`${r} stream requires byte chunks`);
46
+ if (i.byteLength > t - c) throw RangeError(`${r} byte budget exceeded; raise maxBytes`);
47
+ l && i.length <= l.length - c ? l.set(i, c) : (l && s.push(l.subarray(0, c)), l = null, s.push(i.length < i.buffer.byteLength || !(i.buffer instanceof ArrayBuffer) ? i.slice() : i)), c += i.byteLength;
48
+ }
49
+ } catch (e) {
50
+ d(e), u = new y(e);
51
+ }
52
+ if (u.run(() => n?.removeEventListener("abort", f)).run(() => o.releaseLock()).finish(), i) return i.subarray(0, c);
53
+ if (l) return c < l.length ? l.slice(0, c) : l;
54
+ let p = new Uint8Array(c), m = 0;
55
+ for (let e of s) p.set(e, m), m += e.length;
56
+ return p;
57
+ }
58
+ async function x(e, t) {
59
+ try {
60
+ if (t.signal?.throwIfAborted(), !e.ok) throw h("failed", `${t.label ?? "Asset"} request failed: HTTP ${e.status}; check the URL and that the server serves it`);
61
+ let n = Number(e.headers.get("content-length"));
62
+ if (Number.isFinite(n) && n > t.maxBytes) throw RangeError(`${t.label ?? "Asset"} byte budget exceeded; raise maxBytes`);
63
+ let r = e.headers.get("content-encoding");
64
+ (!r || r === "identity") && (t = {
65
+ ...t,
66
+ expected: n
67
+ });
68
+ } catch (t) {
69
+ try {
70
+ Promise.resolve(e.body?.cancel(t)).catch(() => {});
71
+ } catch {}
72
+ throw t;
73
+ }
74
+ return b(e.body, t);
75
+ }
76
+ //#endregion
77
+ //#region ../shared/require-webgpu.js
78
+ function S(e, t) {
79
+ if (e.backend === "webgl2" || !e.gpu) throw new f("unsupported", `${t} needs WebGPU; see https://margoengine.com/errors#webgpu`);
80
+ }
81
+ //#endregion
82
+ //#region ../shared/mesh-source.js
83
+ var C = Symbol.for("margoengine.mesh-sources.v1"), w = globalThis[C] ?? /* @__PURE__ */ new WeakMap();
84
+ globalThis[C] || Object.defineProperty(globalThis, C, { value: w });
85
+ var T = Symbol.for("margoengine.geometry-surfaces.v1"), E = globalThis[T] ?? /* @__PURE__ */ new WeakMap();
86
+ globalThis[T] || Object.defineProperty(globalThis, T, { value: E });
87
+ function D(e) {
88
+ if (e?.geometry) return {
89
+ kind: "core",
90
+ geometry: e.geometry
91
+ };
92
+ let t = e && w.get(e);
93
+ if (!t || t.model.disposed) return null;
94
+ try {
95
+ e.check?.();
96
+ } catch {
97
+ return null;
98
+ }
99
+ return {
100
+ kind: "pbr",
101
+ source: t
102
+ };
103
+ }
104
+ function O(e, t = !1, n) {
105
+ let r = 0, i = 0;
106
+ for (let t of e) {
107
+ if (t.vertices.length % 20) throw RangeError("PBR vertex array length is not a multiple of its stride; pass gltf/pbr primitives with 20-float vertices");
108
+ r += t.vertices.length / 20, i += t.indices.length;
109
+ }
110
+ n?.(r, i);
111
+ let a = t ? 6 : 3, o = new Float32Array(r * a), s = new Uint32Array(i), c = 0, l = 0;
112
+ for (let n of e) {
113
+ let e = n.vertices.length / 20;
114
+ for (let r = 0; r < e; r++) o.set(n.vertices.subarray(r * 20, r * 20 + 3), (c + r) * a), t && o.set(n.vertices.subarray(r * 20 + 4, r * 20 + 7), (c + r) * a + 3);
115
+ for (let e of n.indices) s[l++] = c + e;
116
+ c += e;
117
+ }
118
+ return {
119
+ vertices: o,
120
+ indices: s,
121
+ stride: a
122
+ };
123
+ }
124
+ //#endregion
125
+ //#region src/internal/format.ts
126
+ var k = {
127
+ stl: "stl",
128
+ obj: "obj",
129
+ step: "step",
130
+ stp: "step",
131
+ iges: "iges",
132
+ igs: "iges",
133
+ sat: "sat",
134
+ xt: "xt",
135
+ x_t: "xt",
136
+ x_b: "xt",
137
+ xmt_txt: "xt",
138
+ xmt_bin: "xt",
139
+ jt: "jt"
140
+ };
141
+ function A(e, t) {
142
+ let n = t ?? e.toLowerCase().split(".").at(-1) ?? "";
143
+ return t === void 0 ? Object.hasOwn(k, n) ? k[n] : void 0 : Object.values(k).find((e) => e === n);
144
+ }
145
+ //#endregion
146
+ //#region ../shared/visibility.js
147
+ function j(e, t) {
148
+ for (let n = t; n >= 0; n = e.parents?.[n] ?? -1) if (e.hidden[n]) return !0;
149
+ return !1;
150
+ }
151
+ Array.from({ length: 6 }, (e, t) => ({
152
+ shaderLocation: t + 2,
153
+ offset: t * 16,
154
+ format: "float32x4"
155
+ }));
156
+ function M(e, t, n, r, i) {
157
+ let a = e.get(n);
158
+ return (!a || a.bindings.length !== i.length || i.some((e, t) => {
159
+ let n = a.bindings[t], r = e.resource, i = n.resource;
160
+ return e.binding !== n.binding || (r.buffer ? r.buffer !== i.buffer || r.offset !== i.offset || r.size !== i.size : r !== i);
161
+ })) && (a = {
162
+ bindings: i.map(({ binding: e, resource: t }) => ({
163
+ binding: e,
164
+ resource: t.buffer ? { ...t } : t
165
+ })),
166
+ group: t.createBindGroup({
167
+ layout: n.getBindGroupLayout(0),
168
+ entries: [r, ...i]
169
+ })
170
+ }, e.set(n, a)), a.group;
171
+ }
172
+ //#endregion
173
+ //#region ../shared/unit-light.js
174
+ function N(e, t, n) {
175
+ let r = Math.hypot(n[0], n[1], n[2]);
176
+ e[t] = n[0] / r, e[t + 1] = n[1] / r, e[t + 2] = n[2] / r, e[t + 3] = n[3];
177
+ }
178
+ //#endregion
179
+ //#region src/pack.ts
180
+ var P = 11, F = class {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
181
+ constructor(e, t) {
182
+ this.partVertices = e, this.packVertices = t, this.stats = {
183
+ packs: 0,
184
+ packed: 0
185
+ }, this.shadowPrimitives = [], this.packs = [], this.built = !1, this.frameData = /* @__PURE__ */ new Float32Array(32), this.closed = /* @__PURE__ */ new WeakMap(), this.variants = [], this.groups = /* @__PURE__ */ new WeakMap(), this.colors = [], this.depth = { view: void 0 }, this.pass = {
186
+ colorAttachments: this.colors,
187
+ depthStencilAttachment: this.depth
188
+ }, this.inverse = /* @__PURE__ */ new Float32Array(16), this.relative = /* @__PURE__ */ new Float32Array(16), this.partInverse = /* @__PURE__ */ new Float32Array(16), this.workspace = /* @__PURE__ */ new Float64Array(52);
189
+ }
190
+ setup(e) {
191
+ this.engine = e;
192
+ }
193
+ refresh() {
194
+ this.release();
195
+ }
196
+ execute(e, t) {
197
+ let n = this.engine;
198
+ if (!n) return;
199
+ if (!t) {
200
+ this.built && this.release();
201
+ return;
202
+ }
203
+ if (this.built || this.build(n, e), this.validate(n) && !this.packs.length) return;
204
+ let r = this.frame ??= e.device.createBuffer({
205
+ size: 128,
206
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
207
+ }), i = this.frameData, a = n.lighting;
208
+ i.set(e.camera.matrix), i.set(e.camera.position, 16), N(i, 20, a.direction), i.set(a.radiance, 24), i.fill(1, 28, 31), a.ambient && i.set(a.ambient, 28), e.device.queue.writeBuffer(r, 0, i);
209
+ for (let t of this.packs) this.instances(e.device, t);
210
+ let o = e.draw;
211
+ e.draw = (t = {}) => {
212
+ o(t), this.draw(e, t);
213
+ };
214
+ }
215
+ release() {
216
+ for (let e of this.packs) this.drop(e);
217
+ this.packs = [], this.shadowPrimitives = [], this.built = !1, this.stats.packs = this.stats.packed = 0, this.invalidateShadows();
218
+ }
219
+ dispose() {
220
+ this.release(), this.frame?.destroy(), this.frame = void 0, this.variants.length = 0;
221
+ }
222
+ onDeviceRestored() {
223
+ this.release(), this.frame = void 0, this.variants.length = 0;
224
+ }
225
+ build(e, t) {
226
+ this.built = !0;
227
+ let n = e.store, r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map();
228
+ for (let e of t.batches ?? []) i.set(e.geometry, e);
229
+ for (let t of e.meshes.values()) t.geometry && r.set(t.geometry, (r.get(t.geometry) ?? 0) + 1);
230
+ for (let t of e.meshes.values()) {
231
+ let o = t.geometry;
232
+ if (!o || r.get(o) !== 1 || o.vertices.length / 6 > this.partVertices || !i.has(o) || n.constrained[t.id] || n.parents[t.id] === -1) continue;
233
+ let s = t.id, c = !1;
234
+ for (; n.parents[s] !== -1;) c ||= !!n.hidden[s], s = n.parents[s];
235
+ if (c || !this.isClosed(o)) continue;
236
+ let l = e.meshes.get(s), u = a.get(l) ?? /* @__PURE__ */ new Map(), d = t.material.data.subarray(0, 7).join();
237
+ a.set(l, u);
238
+ let f = u.get(d);
239
+ f ? f.push(t) : u.set(d, [t]);
240
+ }
241
+ for (let [e, n] of a) if (p(e.matrix, this.inverse, this.workspace)) for (let r of n.values()) {
242
+ let n = 0;
243
+ for (; n < r.length;) {
244
+ let a = n, o = 0;
245
+ for (; a < r.length && o + r[a].geometry.vertices.length / 6 <= this.packVertices;) o += r[a++].geometry.vertices.length / 6;
246
+ a - n > 1 && this.bake(t.device, e, r.slice(n, a), i), n = a;
247
+ }
248
+ }
249
+ this.shadowPrimitives = this.packs.map((e) => e.shadow), this.stats.packs = this.packs.length, this.stats.packed = this.packs.reduce((e, t) => e + t.live, 0), this.packs.length && this.invalidateShadows();
250
+ }
251
+ isClosed(e) {
252
+ let t = this.closed.get(e);
253
+ return t === void 0 && this.closed.set(e, t = s(e)), t;
254
+ }
255
+ bake(e, t, n, r) {
256
+ let i = this.engine.store, a = i.transforms, o = this.relative, s = this.partInverse, c = 0, l = 0;
257
+ for (let e of n) c += e.geometry.vertices.length / 6, l += e.geometry.indices.length;
258
+ let u = new Float32Array(c * 6), d = new Uint32Array(l), f = [], h = 0, g = 0;
259
+ for (let e of n) {
260
+ let n = e.geometry, c = n.vertices, l = n.indices;
261
+ if (m(this.inverse, e.matrix, o), !p(o, s, this.workspace)) continue;
262
+ let _ = o, v = _[0] * (_[5] * _[10] - _[6] * _[9]) - _[4] * (_[1] * _[10] - _[2] * _[9]) + _[8] * (_[1] * _[6] - _[2] * _[5]) < 0;
263
+ for (let e = 0; e < c.length; e += 6) {
264
+ let t = c[e], n = c[e + 1], r = c[e + 2], i = c[e + 3], a = c[e + 4], o = c[e + 5], l = h * 6 + e;
265
+ u[l] = _[0] * t + _[4] * n + _[8] * r + _[12], u[l + 1] = _[1] * t + _[5] * n + _[9] * r + _[13], u[l + 2] = _[2] * t + _[6] * n + _[10] * r + _[14], u[l + 3] = s[0] * i + s[1] * a + s[2] * o, u[l + 4] = s[4] * i + s[5] * a + s[6] * o, u[l + 5] = s[8] * i + s[9] * a + s[10] * o;
266
+ }
267
+ for (let e = 0; e < l.length; e += 3) d[g + e] = h + l[e], d[g + e + 1] = h + l[v ? e + 2 : e + 1], d[g + e + 2] = h + l[v ? e + 1 : e + 2];
268
+ let y = [];
269
+ for (let n = e.id; n !== t.id; n = i.parents[n]) y.push(n);
270
+ let b = new Float32Array(y.length * P);
271
+ y.forEach((e, t) => {
272
+ let n = t * P;
273
+ b[n] = a.x[e], b[n + 1] = a.y[e], b[n + 2] = a.z[e], b[n + 3] = a.qx[e], b[n + 4] = a.qy[e], b[n + 5] = a.qz[e], b[n + 6] = a.qw[e], b[n + 7] = a.sx[e], b[n + 8] = a.sy[e], b[n + 9] = a.sz[e], b[n + 10] = i.parents[e];
274
+ }), f.push({
275
+ mesh: e,
276
+ geometry: n,
277
+ batch: r.get(n),
278
+ first: g,
279
+ count: l.length,
280
+ base: h,
281
+ chain: y,
282
+ stamp: b,
283
+ live: !0
284
+ }), h += c.length / 6, g += l.length;
285
+ }
286
+ if (f.length < 2) return;
287
+ let _ = e.limits.maxBufferSize;
288
+ if (u.byteLength > _ || d.byteLength > _ || f.length * 96 > _) return;
289
+ let v = (t, n) => {
290
+ let r = e.createBuffer({
291
+ size: t.byteLength,
292
+ usage: n | GPUBufferUsage.COPY_DST
293
+ });
294
+ return e.queue.writeBuffer(r, 0, t), r;
295
+ }, y = v(u, GPUBufferUsage.VERTEX), b = v(d.subarray(0, g), GPUBufferUsage.INDEX), x = new Float32Array(f.length * 24), S = e.createBuffer({
296
+ size: x.byteLength,
297
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
298
+ });
299
+ f.forEach((e, t) => x[t * 24 + 23] = e.mesh.id), x[0] = NaN;
300
+ for (let e of f) e.batch.claimed = !0;
301
+ this.packs.push({
302
+ root: t,
303
+ material: n[0].material.data.slice(0, 7),
304
+ parts: f,
305
+ live: f.length,
306
+ vertex: y,
307
+ index: b,
308
+ instance: S,
309
+ count: g,
310
+ instances: x,
311
+ shadow: {
312
+ node: t,
313
+ vertex: y,
314
+ index: b,
315
+ count: g,
316
+ stride: 24
317
+ }
318
+ });
319
+ }
320
+ validate(e) {
321
+ let t = e.store, n = t.transforms, r = !0;
322
+ for (let i = this.packs.length - 1; i >= 0; i--) {
323
+ let a = this.packs[i];
324
+ if (e.meshes.get(a.root.id) !== a.root) this.drop(a), this.packs.splice(i, 1), r = !1;
325
+ else {
326
+ for (let i of a.parts) {
327
+ if (!i.live) continue;
328
+ let o = i.mesh, s = e.meshes.get(o.id) === o && o.geometry === i.geometry && this.sameMaterial(o, a.material) && !t.constrained[o.id] && i.batch.count <= 1;
329
+ for (let e = 0; s && e < i.chain.length; e++) {
330
+ let r = i.chain[e], a = i.stamp, o = e * P;
331
+ s = !t.hidden[r] && n.x[r] === a[o] && n.y[r] === a[o + 1] && n.z[r] === a[o + 2] && n.qx[r] === a[o + 3] && n.qy[r] === a[o + 4] && n.qz[r] === a[o + 5] && n.qw[r] === a[o + 6] && n.sx[r] === a[o + 7] && n.sy[r] === a[o + 8] && n.sz[r] === a[o + 9] && t.parents[r] === a[o + 10];
332
+ }
333
+ s || (r = !1, this.unpack(a, i));
334
+ }
335
+ a.live || (this.drop(a), this.packs.splice(i, 1));
336
+ }
337
+ }
338
+ return r || (this.shadowPrimitives = this.packs.map((e) => e.shadow), this.stats.packs = this.packs.length, this.stats.packed = this.packs.reduce((e, t) => e + t.live, 0), this.invalidateShadows()), r;
339
+ }
340
+ unpack(e, t) {
341
+ t.live = !1, t.batch.claimed = !1, e.live--, e.live && this.engine.gpu?.queue.writeBuffer(e.index, t.first * 4, new Uint32Array(t.count).fill(t.base));
342
+ }
343
+ drop(e) {
344
+ for (let t of e.parts) t.live && (t.batch.claimed = !1);
345
+ e.live = 0, e.vertex.destroy(), e.index.destroy(), e.instance.destroy();
346
+ }
347
+ instances(e, t) {
348
+ let n = t.instances, r = t.root.matrix, i = !0;
349
+ for (let e = 0; i && e < 16; e++) i = n[e] === r[e];
350
+ if (!i) {
351
+ for (let e = 0; e < t.parts.length; e++) n.set(r, e * 24), n.set(t.material, e * 24 + 16);
352
+ e.queue.writeBuffer(t.instance, 0, n);
353
+ }
354
+ }
355
+ draw(e, t) {
356
+ let n = this.engine.store, r = !1;
357
+ for (let e of this.packs) r ||= !j(n, e.root.id);
358
+ if (!r) return;
359
+ let i = t.pipeline ?? this.variant(e), a = this.group(e.device, i, t.bindings ?? e.bindings), o = this.colors, s = this.depth, c = e.descriptor.depthStencil.format.includes("stencil");
360
+ o.length = 0, o.push({
361
+ view: e.color,
362
+ loadOp: "load",
363
+ storeOp: "store"
364
+ });
365
+ for (let e of t.colorAttachments ?? []) o.push({
366
+ view: e.view,
367
+ resolveTarget: e.resolveTarget,
368
+ loadOp: "load",
369
+ storeOp: e.storeOp
370
+ });
371
+ s.view = e.depth, s.depthLoadOp = "load", s.depthStoreOp = "store", s.stencilLoadOp = c ? "load" : void 0, s.stencilStoreOp = c ? "store" : void 0;
372
+ let l = e.view?.viewport, u = t.viewport === void 0 ? l : t.viewport, d = t.scissor === void 0 ? t.viewport === void 0 ? e.view?.scissor ?? l : void 0 : t.scissor, f = e.encoder.beginRenderPass(this.pass);
373
+ u && f.setViewport(...u, 0, 1), d && f.setScissorRect(...d), f.setPipeline(i), f.setBindGroup(0, a);
374
+ for (let e of this.packs) if (!j(n, e.root.id)) {
375
+ if (f.setVertexBuffer(0, e.vertex), f.setVertexBuffer(1, e.instance), f.setIndexBuffer(e.index, "uint32"), t.partIds) for (let t = 0; t < e.parts.length; t++) {
376
+ let n = e.parts[t];
377
+ n.live && f.drawIndexed(n.count, 1, n.first, 0, t);
378
+ }
379
+ else f.drawIndexed(e.count, 1, 0, 0, 0);
380
+ }
381
+ f.end();
382
+ }
383
+ sameMaterial(e, t) {
384
+ let n = e.material.data;
385
+ for (let e = 0; e < 7; e++) if (n[e] !== t[e]) return !1;
386
+ return !0;
387
+ }
388
+ variant(e) {
389
+ let t = e.descriptor.multisample?.count + e.format + e.descriptor.depthStencil?.format;
390
+ for (let n of this.variants) if (n[0] === e.shader && n[1] === t) return n[2];
391
+ let n = e.device.createShaderModule({ code: e.shader }), r = e.device.createRenderPipeline({
392
+ ...e.descriptor,
393
+ vertex: {
394
+ ...e.descriptor.vertex,
395
+ module: n
396
+ },
397
+ fragment: {
398
+ ...e.descriptor.fragment,
399
+ module: n,
400
+ targets: [{ format: e.format }]
401
+ }
402
+ });
403
+ return this.variants.length >= 64 && this.variants.shift(), this.variants.push([
404
+ e.shader,
405
+ t,
406
+ r
407
+ ]), r;
408
+ }
409
+ group(e, t, n) {
410
+ return M(this.groups, e, t, {
411
+ binding: 0,
412
+ resource: { buffer: this.frame }
413
+ }, n);
414
+ }
415
+ invalidateShadows() {
416
+ (this.engine?.plugins.get("shadows"))?.invalidate?.();
417
+ }
418
+ };
419
+ //#endregion
420
+ //#region src/cad.ts
421
+ function I(e) {
422
+ let t = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Set(), c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Set(), u = (e) => {
423
+ let r = n(e), a = `${r.length}:${i(r)}`, o = t.get(a) ?? [], s = o.find((e) => e.data.length === r.length && e.data.every((e, t) => e === r[t]));
424
+ return s || (o.push({
425
+ data: r,
426
+ geometry: e
427
+ }), t.set(a, o)), s?.geometry;
428
+ }, f = 0, p = 0;
429
+ for (let t of e) {
430
+ let e = d(t);
431
+ e.check();
432
+ let n = D(e);
433
+ if (!n) continue;
434
+ if (n.kind === "pbr") {
435
+ let { source: t } = n, { primitives: r } = t;
436
+ if (!r.length) continue;
437
+ f++;
438
+ let c = R(r);
439
+ if (t.skinned || t.morphed) {
440
+ s.has(e) || (s.add(e), p++);
441
+ continue;
442
+ }
443
+ L(t.model, r, o);
444
+ let l = `${c.length}:${i(c)}`, u = a.get(l) ?? [];
445
+ u.some((e) => e.length === c.length && e.every((e, t) => e === c[t])) || (u.push(c), a.set(l, u), p++);
446
+ continue;
447
+ }
448
+ f++;
449
+ let { geometry: m } = n, h = r.get(m);
450
+ if (!h) {
451
+ let e = m.indices.length, t = c.get(e);
452
+ if (!t && !l.has(e)) c.set(e, m), h = m, p++;
453
+ else {
454
+ t && (c.delete(e), l.add(e), u(t));
455
+ let n = u(m);
456
+ h = n ?? m, n || p++;
457
+ }
458
+ r.set(m, h);
459
+ }
460
+ m !== h && e.setGeometry(h);
461
+ }
462
+ if (!f) throw TypeError("CAD grouping found no supported geometry; pass meshes that have geometry or PBR primitives.");
463
+ return {
464
+ parts: f,
465
+ unique: p
466
+ };
467
+ }
468
+ function L(e, t, n) {
469
+ if (typeof e.shareBuffers != "function") return;
470
+ let r = n.get(e);
471
+ r || n.set(e, r = /* @__PURE__ */ new Map());
472
+ for (let n of t) {
473
+ if (n.deformed || n.definition.targets?.length || n.definition.attributes?.JOINTS_0 !== void 0) continue;
474
+ let t = n.vertices, a = n.indices, o = `${t.length}:${a.length}:${i(t)}:${i(new Float32Array(a.buffer, a.byteOffset, a.length))}`, s = r.get(o) ?? [], c = s.find((e) => e.vertices.every((e, n) => e === t[n]) && e.indices.every((e, t) => e === a[t]));
475
+ c ? e.shareBuffers(n, c) : (s.push(n), r.set(o, s));
476
+ }
477
+ }
478
+ function R(t) {
479
+ let { vertices: r, indices: i } = O(t, !0, (t, n) => {
480
+ if (!t || !n || n % 3) throw RangeError("PBR geometry needs whole triangles");
481
+ if (n > 3e6) throw RangeError(`Deduplication supports at most ${e / 3} triangles per part; split the part or skip deduplication.`);
482
+ });
483
+ return n({
484
+ vertices: r,
485
+ indices: i
486
+ });
487
+ }
488
+ function z(e, t, n, { maxParts: i } = {}) {
489
+ let a = u(e), o = r(t, n, (e, t, n) => new c(e, t, n), void 0, i), s = [];
490
+ try {
491
+ let e = a.createMesh();
492
+ s.push(e);
493
+ let t = o.map((t) => {
494
+ let n = a.createMesh(e);
495
+ return s.push(n), n.name = t.name, n.setGeometry(t.geometry).setMaterial(new l({
496
+ color: "#a6b9c8",
497
+ roughness: .4,
498
+ metalness: .3
499
+ }));
500
+ });
501
+ return I(t), {
502
+ root: e,
503
+ meshes: t,
504
+ dispose() {
505
+ for (let e = s.length - 1; e >= 0; e--) s[e].dispose();
506
+ }
507
+ };
508
+ } catch (e) {
509
+ for (let e = s.length - 1; e >= 0; e--) s[e].dispose();
510
+ throw e;
511
+ }
512
+ }
513
+ async function B(e, n, { format: r, signal: i, fetch: s = globalThis.fetch, ...c } = {}) {
514
+ let l = new URL(n, globalThis.location?.href);
515
+ if (!["http:", "https:"].includes(l.protocol)) throw TypeError("CAD URL must use HTTP(S)");
516
+ i?.throwIfAborted();
517
+ let d = a(u(e)), p = await x(await s(l, { signal: i }), {
518
+ maxBytes: t,
519
+ signal: i,
520
+ label: "CAD download"
521
+ }), m = A(l.pathname, r);
522
+ if (!m) throw TypeError("Cannot tell the CAD format from the URL; pass the format option: stl, obj, step, iges, sat, xt or jt.");
523
+ i?.throwIfAborted();
524
+ let h = m !== "stl" && m !== "obj";
525
+ if (typeof Worker > "u" && !(h && c.importer)) {
526
+ if (h) throw new f("unsupported", "B-rep import (STEP, IGES, SAT, XT, JT) requires Web Workers; pass an importer option to read them without one.");
527
+ return d.run(() => z(e, p, m, c));
528
+ }
529
+ let g = p.byteOffset === 0 && p.byteLength === p.buffer.byteLength ? p.buffer : p.buffer.slice(p.byteOffset, p.byteOffset + p.byteLength);
530
+ return d.run(() => o(e, g, m, {
531
+ signal: i,
532
+ ...c
533
+ }));
534
+ }
535
+ var V = class e {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
536
+ static attach(t, n = {}) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
537
+ let r = new e(n);
538
+ return u(t).use(r), r;
539
+ }
540
+ constructor(e = {}) {
541
+ this.name = "part-instancer", this.removed = !1;
542
+ let t = e.partVertices ?? 4096, n = e.packVertices ?? Math.max(262144, t);
543
+ if (!Number.isSafeInteger(t) || t < 3) throw RangeError("partVertices must be an integer of at least 3");
544
+ if (!Number.isSafeInteger(n) || n < t) throw RangeError("packVertices must be an integer no smaller than partVertices");
545
+ if (e.pack !== void 0 && typeof e.pack != "boolean") throw TypeError("pack must be a boolean");
546
+ this.pack = e.pack ?? !0, this.packs = new F(t, n), this.stats = Object.assign(this.packs.stats, {
547
+ parts: 0,
548
+ unique: 0
549
+ });
550
+ }
551
+ get shadowPrimitives() {
552
+ return this.packs.shadowPrimitives;
553
+ }
554
+ get disposed() {
555
+ return this.removed;
556
+ }
557
+ setup(e) {
558
+ this.engine = e, S(e, "PartInstancer"), Object.assign(this.stats, I(e.meshes.values())), this.packs.setup(e);
559
+ }
560
+ refresh() {
561
+ this.packs.refresh();
562
+ }
563
+ registerPasses(e) {
564
+ e.add({
565
+ name: "parts:indirect",
566
+ order: -45,
567
+ execute: (e) => {
568
+ e.backend === "webgpu" && (e.indirect = !0);
569
+ }
570
+ }), e.add({
571
+ name: "parts:pack",
572
+ order: -1e3,
573
+ execute: (e) => {
574
+ e.backend === "webgpu" && this.packs.execute(e, this.pack);
575
+ }
576
+ });
577
+ }
578
+ onDeviceRestored() {
579
+ this.packs.onDeviceRestored();
580
+ }
581
+ dispose() {
582
+ this.removed || (this.removed = !0, this.packs.dispose(), this.engine?.sceneOf(this)?.removePlugin(this.name));
583
+ }
584
+ [Symbol.dispose ?? Symbol()]() {
585
+ this.dispose();
586
+ }
587
+ };
588
+ //#endregion
589
+ export { A as a, v as c, z as i, I as n, D as o, B as r, _ as s, V as t };