three-slicer-viewer 0.3.5 → 0.4.1

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.
@@ -1,72 +1,134 @@
1
- import { r as u, p } from "./parse_3mf-CpbA-6Iq.js";
1
+ import { c as M, s as w, r as k, i as I, a as g, p as P, b as S } from "./parse_3mf-6PLUgcZp.js";
2
2
  function b(r) {
3
3
  if (!r) return [];
4
- const t = [r.tris.buffer, ...r.modifiers.map((s) => s.tris.buffer)];
5
- return r.baked && t.push(r.baked.localPos.buffer, r.baked.normals.buffer), t;
4
+ const t = [r.tris.buffer, ...r.modifiers.map((a) => a.tris.buffer)];
5
+ return r.baked && t.push(r.baked.localPos.buffer), t;
6
6
  }
7
- const g = 8;
8
- let i = null, h = 0;
9
- const c = /* @__PURE__ */ new Map();
10
- function w() {
11
- if (i) return i;
12
- i = [];
13
- const r = Math.min(g, Math.max(1, (self.navigator?.hardwareConcurrency || 2) - 1));
7
+ const j = 8;
8
+ let c = null, x = 0;
9
+ const u = /* @__PURE__ */ new Map();
10
+ function h() {
11
+ if (c) return c;
12
+ c = [];
13
+ const r = Math.min(j, Math.max(1, (self.navigator?.hardwareConcurrency || 2) - 1));
14
14
  try {
15
15
  for (let t = 0; t < r; t++) {
16
- const s = new Worker(self.location.href, { type: "module" }), n = { worker: s, failed: !1 };
17
- s.onmessage = (o) => {
18
- const { id: e, result: f, error: a } = o.data || {}, l = c.get(e);
19
- l && (c.delete(e), a ? l.reject(new Error(a)) : l.resolve(f));
20
- }, s.onerror = () => {
16
+ const a = new Worker(self.location.href, { type: "module" }), n = { worker: a, failed: !1 };
17
+ a.onmessage = (i) => {
18
+ const { id: e, result: s, error: o, batch: f } = i.data || {}, l = u.get(e);
19
+ if (l) {
20
+ if (f) {
21
+ l.onBatch(f);
22
+ return;
23
+ }
24
+ u.delete(e), o ? l.reject(new Error(o)) : l.resolve(s);
25
+ }
26
+ }, a.onerror = () => {
21
27
  n.failed = !0;
22
- for (const [o, e] of c) e.helper === n && (c.delete(o), e.reject(new Error("3MF helper failed")));
23
- }, i.push(n);
28
+ for (const [i, e] of u) e.helper === n && (u.delete(i), e.reject(new Error("3MF helper failed")));
29
+ }, c.push(n);
24
30
  }
25
31
  } catch {
26
- for (const t of i) t.worker.terminate();
27
- i = [];
32
+ for (const t of c) t.worker.terminate();
33
+ c = [];
28
34
  }
29
- return i;
35
+ return c;
30
36
  }
31
- function M(r, t) {
32
- const s = ++h;
33
- return new Promise((n, o) => {
34
- c.set(s, { resolve: n, reject: o, helper: r }), r.worker.postMessage({ type: "item-job", id: s, job: t }, t.members.map((e) => e.data.buffer));
37
+ function B(r, t) {
38
+ return m(r, { type: "item-job", job: t }, t.members.map((a) => a.data.buffer));
39
+ }
40
+ function m(r, t, a, n = null) {
41
+ const i = ++x;
42
+ return new Promise((e, s) => {
43
+ u.set(i, { resolve: e, reject: s, helper: r, onBatch: n }), r.worker.postMessage({ ...t, id: i }, a);
35
44
  });
36
45
  }
37
- async function k(r) {
38
- const t = w().filter((e) => !e.failed);
39
- if (!t.length) return Promise.all(r.map(u));
40
- const s = new Array(r.length);
46
+ let E = 0;
47
+ function J() {
48
+ const r = h().filter((e) => !e.failed);
49
+ if (r.length < 2) return null;
50
+ const t = ++E, [a, ...n] = r, i = (e, s, o) => {
51
+ const f = S(s, o);
52
+ let l = e, d = [];
53
+ return e instanceof Blob || (l = e.slice(), d = [l.buffer]), m(a, { type: "inflate", data: l, entry: { method: s.method, size: s.size } }, d, (y) => f.push(y)).then(() => f.finish());
54
+ };
55
+ return n.length < 1 ? null : {
56
+ inflate: i,
57
+ size: n.length,
58
+ scan: (e, s, o) => m(n[e], { type: "scan", parseId: t, data: s, options: o }, [s.buffer]),
59
+ build: (e, s) => m(n[e], { type: "build", parseId: t, job: s }, s.members.map((o) => o.data.buffer)),
60
+ release: () => {
61
+ for (const e of n) e.worker.postMessage({ type: "release", parseId: t });
62
+ }
63
+ };
64
+ }
65
+ async function H(r) {
66
+ const t = h().filter((e) => !e.failed);
67
+ if (!t.length) return Promise.all(r.map(g));
68
+ const a = new Array(r.length);
41
69
  let n = 0;
42
- const o = async (e) => {
70
+ const i = async (e) => {
43
71
  for (; n < r.length; ) {
44
- const f = n++, a = r[f], l = a.members.map((m) => m.data.slice());
72
+ const s = n++, o = r[s], f = o.members.map((l) => l.data.slice());
45
73
  try {
46
- s[f] = await M(e, a);
74
+ a[s] = await B(e, o);
47
75
  } catch {
48
- s[f] = await u({ ...a, members: a.members.map((m, d) => ({ ...m, data: l[d] })) });
76
+ a[s] = await g({ ...o, members: o.members.map((l, d) => ({ ...l, data: f[d] })) });
49
77
  }
50
78
  }
51
79
  };
52
- return await Promise.all(t.slice(0, r.length).map(o)), s;
80
+ return await Promise.all(t.slice(0, r.length).map(i)), a;
53
81
  }
82
+ const p = /* @__PURE__ */ new Map();
54
83
  self.onmessage = async (r) => {
55
84
  const t = r.data || {};
85
+ if (t.type === "scan") {
86
+ try {
87
+ p.has(t.parseId) || p.set(t.parseId, M()), w(t.data, p.get(t.parseId), t.options), self.postMessage({ id: t.id, result: !0 });
88
+ } catch (e) {
89
+ self.postMessage({ id: t.id, error: e && e.message || String(e) });
90
+ }
91
+ return;
92
+ }
93
+ if (t.type === "build") {
94
+ try {
95
+ const e = await k(t.job, p.get(t.parseId));
96
+ self.postMessage({ id: t.id, result: e }, e.items.flatMap((s) => b(s.built)));
97
+ } catch (e) {
98
+ self.postMessage({ id: t.id, error: e && e.message || String(e) });
99
+ }
100
+ return;
101
+ }
102
+ if (t.type === "release") {
103
+ p.delete(t.parseId);
104
+ return;
105
+ }
106
+ if (t.type === "inflate") {
107
+ try {
108
+ await I(t.data, t.entry, (e) => self.postMessage({ id: t.id, batch: e }, [e.buffer])), self.postMessage({ id: t.id, result: !0 });
109
+ } catch (e) {
110
+ self.postMessage({ id: t.id, error: e && e.message || String(e) });
111
+ }
112
+ return;
113
+ }
56
114
  if (t.type === "item-job") {
57
115
  try {
58
- const e = await u(t.job);
59
- self.postMessage({ id: t.id, result: e }, e.items.flatMap((f) => b(f.built)));
116
+ const e = await g(t.job);
117
+ self.postMessage({ id: t.id, result: e }, e.items.flatMap((s) => b(s.built)));
60
118
  } catch (e) {
61
119
  self.postMessage({ id: t.id, error: e && e.message || String(e) });
62
120
  }
63
121
  return;
64
122
  }
65
- const { id: s, buffer: n, baseName: o } = t;
123
+ if (t.type === "warm") {
124
+ h();
125
+ return;
126
+ }
127
+ const { id: a, source: n, baseName: i } = t;
66
128
  try {
67
- const { objects: e, project: f } = await p(n, o, { runJobs: k, bake: !0 });
68
- self.postMessage({ id: s, objects: e, project: f }, e.flatMap((a) => [a.tris.buffer, a.baked.localPos.buffer, a.baked.normals.buffer]));
129
+ const { objects: e, project: s } = await P(n, i, { runJobs: H, bake: !0, pool: J() });
130
+ self.postMessage({ id: a, objects: e, project: s }, e.flatMap((o) => [o.tris.buffer, o.baked.localPos.buffer]));
69
131
  } catch (e) {
70
- self.postMessage({ id: s, error: e && e.message || String(e) });
132
+ self.postMessage({ id: a, error: e && e.message || String(e) });
71
133
  }
72
134
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "three-slicer-viewer",
3
- "version": "0.3.5",
3
+ "version": "0.4.1",
4
4
  "description": "The three-slicer viewer without the slicer — model loading, G-code parsing, GPU toolpath rendering and the settings transforms, under MIT. Plug a slicer in through the `slicer` prop.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,10 @@
22
22
  "types": "./types/loaders.d.ts",
23
23
  "default": "./dist/model_loaders.js"
24
24
  },
25
+ "./workers": {
26
+ "types": "./types/workers.d.ts",
27
+ "default": "./dist/make_worker.js"
28
+ },
25
29
  "./settings": {
26
30
  "types": "./types/settings.d.ts",
27
31
  "default": "./src/settings/index.js"
@@ -13,11 +13,20 @@ export function makeToggle(toggles = {}, schema = leanSchema) {
13
13
  // Settings value accessor (settings map first, schema default otherwise). Percentages ("15%") become numbers.
14
14
  function makeCfg(settings) {
15
15
  const val = k => {
16
- let v = settings ? settings[k] : undefined
17
- if (v === undefined || v === '') { const d = schema[k]?.default; v = Array.isArray(d) ? d[0] : d }
16
+ let v
17
+ if (settings) v = settings[k]
18
+ if (v === undefined || v === '') {
19
+ const d = schema[k]?.default
20
+ v = d
21
+ if (Array.isArray(d)) v = d[0]
22
+ }
18
23
  return v
19
24
  }
20
- const num = k => { const v = val(k); const n = parseFloat(v); return Number.isFinite(n) ? n : 0 }
25
+ const num = k => {
26
+ const n = parseFloat(val(k))
27
+ if (!Number.isFinite(n)) return 0
28
+ return n
29
+ }
21
30
  return {
22
31
  bool: k => { const v = val(k); return v === true || v === 1 || v === '1' || v === 'true' },
23
32
  int: k => Math.trunc(num(k)),
@@ -69,19 +78,116 @@ return { makeCfg, disabledKeys, evalEnableIf }
69
78
 
70
79
  // Evaluates enable_if (up to the first comma) to a boolean. Returns null (= stays enabled) when not fully translatable.
71
80
  export function evalEnableIf(expr, locals, cfg) {
81
+ const substituted = substituteEnableIf(expr, locals, cfg)
82
+ if (substituted === null) return null
83
+ return evaluateBooleanExpression(substituted)
84
+ }
85
+
86
+ // enable_if with every config read and local replaced by its value, or null when something is left that is not a
87
+ // boolean expression of values.
88
+ export function substituteEnableIf(expr, locals, cfg) {
72
89
  let s = String(expr).split(',')[0].trim()
73
90
  if (!s) return null
74
91
  // Direct config access pattern -> value substitution
75
- s = s.replace(/config->opt_bool\(\s*"([^"]+)"\s*\)/g, (_, k) => cfg.bool(k) ? 'true' : 'false')
92
+ s = s.replace(/config->opt_bool\(\s*"([^"]+)"\s*\)/g, (_, k) => String(cfg.bool(k)))
76
93
  s = s.replace(/config->opt_int\(\s*"([^"]+)"\s*\)/g, (_, k) => String(cfg.int(k)))
77
94
  s = s.replace(/config->opt_float\(\s*"([^"]+)"\s*\)/g, (_, k) => String(cfg.float(k)))
78
95
  // Substitute known locals (longest name first — prevents partial matches)
79
96
  for (const name of Object.keys(locals).sort((a, b) => b.length - a.length))
80
- s = s.replace(new RegExp('\\b' + name + '\\b', 'g'), locals[name] ? 'true' : 'false')
97
+ s = s.replace(new RegExp('\\b' + name + '\\b', 'g'), String(!!locals[name]))
81
98
  // Check the remaining string is a safe boolean expression (only true/false/numbers/operators/parens) — otherwise unknown -> null
82
99
  const stripped = s.replace(/\btrue\b|\bfalse\b/g, '1')
83
100
  if (!/^[\s()!<>=&|0-9.]*$/.test(stripped)) return null
84
- try { return !!Function('"use strict";return (' + s + ')')() } catch { return null }
101
+ return s
102
+ }
103
+
104
+ // After substitution an enable_if is a C++ boolean expression over true/false and numbers, which the check above
105
+ // narrows to ! && || == != < > <= >= and parentheses. It is parsed here rather than handed to Function(): a page whose
106
+ // CSP has no 'unsafe-eval' refuses Function, and the browser extension's does, so every option stayed enabled there
107
+ // (measured: 3 fields disabled on the site, 0 in the extension, 564 CSP violations). The operators keep JavaScript's
108
+ // semantics, loose == included, so the result is the one Function gave (test_toggle_parity.mjs, every upstream rule).
109
+ // Anything else the check lets through (a lone = & |, a malformed number) is not translatable: null, as before.
110
+ const EXPRESSION_TOKEN = /\s*(\d+\.?\d*|\.\d+|true|false|&&|\|\||==|!=|<=|>=|[()!<>])/y
111
+ const COMPARE = {
112
+ '==': (left, right) => left == right, // eslint-disable-line eqeqeq
113
+ '!=': (left, right) => left != right, // eslint-disable-line eqeqeq
114
+ '<': (left, right) => left < right,
115
+ '>': (left, right) => left > right,
116
+ '<=': (left, right) => left <= right,
117
+ '>=': (left, right) => left >= right,
118
+ }
119
+ const EQUALITY = ['==', '!=']
120
+ const RELATIONAL = ['<', '>', '<=', '>=']
121
+
122
+ function tokenize(source) {
123
+ const tokens = []
124
+ EXPRESSION_TOKEN.lastIndex = 0
125
+ while (EXPRESSION_TOKEN.lastIndex < source.length) {
126
+ if (!source.slice(EXPRESSION_TOKEN.lastIndex).trim()) break
127
+ const match = EXPRESSION_TOKEN.exec(source)
128
+ if (!match) return null
129
+ tokens.push(match[1])
130
+ }
131
+ return tokens
132
+ }
133
+
134
+ // Recursive descent in C++ precedence: || < && < == != < relational < unary !.
135
+ export function evaluateBooleanExpression(source) {
136
+ const tokens = tokenize(source)
137
+ if (!tokens?.length) return null
138
+ let position = 0
139
+ const peek = () => tokens[position]
140
+ const take = () => tokens[position++]
141
+ function primary() {
142
+ const token = take()
143
+ if (token === '(') {
144
+ const value = either()
145
+ if (take() !== ')') throw new SyntaxError('unclosed (')
146
+ return value
147
+ }
148
+ if (token === '!') return !primary()
149
+ if (token === 'true') return true
150
+ if (token === 'false') return false
151
+ if (token !== undefined && /^[\d.]/.test(token)) return Number(token)
152
+ throw new SyntaxError(`unexpected ${token}`)
153
+ }
154
+ function binary(operand, operators) {
155
+ return () => {
156
+ let left = operand()
157
+ while (operators.includes(peek())) {
158
+ const operator = take()
159
+ left = COMPARE[operator](left, operand())
160
+ }
161
+ return left
162
+ }
163
+ }
164
+ const relational = binary(primary, RELATIONAL)
165
+ const equality = binary(relational, EQUALITY)
166
+ function both() {
167
+ let left = equality()
168
+ while (peek() === '&&') {
169
+ take()
170
+ const right = equality()
171
+ left = left && right
172
+ }
173
+ return left
174
+ }
175
+ function either() {
176
+ let left = both()
177
+ while (peek() === '||') {
178
+ take()
179
+ const right = both()
180
+ left = left || right
181
+ }
182
+ return left
183
+ }
184
+ try {
185
+ const value = either()
186
+ if (position !== tokens.length) return null
187
+ return !!value
188
+ } catch {
189
+ return null
190
+ }
85
191
  }
86
192
 
87
193
  // The unbound default: nothing disables. `three-slicer/toggle` is the bound one.
@@ -1,12 +1,12 @@
1
- // three-slicer/components
1
+ // three-slicer-viewer/components
2
2
  import type * as React from 'react'
3
3
  import type { SlicerSettings } from './settings-keys.d.ts'
4
4
 
5
5
  export interface SettingsPanelProps {
6
6
  /**
7
7
  * The config schema to render from. Defaults to this package's reduced schema — types, defaults, enum values,
8
- * layout flags and units, but no label or tooltip, so a field is labelled by its key. `three-slicer/components`
9
- * passes the full schema; a host may pass its own (a translation, its own vocabulary).
8
+ * layout flags and units, but no label or tooltip, so a field is labelled by its key. Pass
9
+ * three-slicer/data's full schema for upstream's labels; a host may pass its own (a translation, its own vocabulary).
10
10
  */
11
11
  schema?: Record<string, Record<string, unknown>>
12
12
  /** The tab/page/group tree. Defaults to one flat page per builder over this package's ui-tree keys. */
package/types/gcode.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- // three-slicer/viewer/gcode — G-code text -> kernel-shaped layer stream (renderable without slicing).
2
- // Feed the returned layers straight into buildSegmentData (three-slicer/viewer/toolpath).
1
+ // three-slicer-viewer/gcode — G-code text -> kernel-shaped layer stream (renderable without slicing).
2
+ // Feed the returned layers straight into buildSegmentData (three-slicer-viewer/toolpath).
3
3
 
4
4
  export interface GcodeLayer {
5
5
  z: number
@@ -3,6 +3,15 @@
3
3
  /** The 5 built-ins plus any extension registered via `registerLoader()`, which pushes onto this array. */
4
4
  export const SUPPORTED_EXT: string[]
5
5
 
6
+ /** G-code extensions: print jobs, opened as a preview instead of a mesh. */
7
+ export const GCODE_EXTS: string[]
8
+
9
+ /** The resin archive extension (`sl1`). */
10
+ export const SL1_EXT: string
11
+
12
+ /** Every extension the viewport opens: `SUPPORTED_EXT`, `SL1_EXT` and `GCODE_EXTS`, read at call time. */
13
+ export function openableExtensions(): string[]
14
+
6
15
  /** Lowercased extension. Empty string when there is no dot. */
7
16
  export function fileExt(name: string): string
8
17
 
@@ -13,7 +22,20 @@ export interface LoadedObject {
13
22
  }
14
23
 
15
24
  /** A single file may contain several objects (3mf/amf/step) -> always an array. */
16
- export function loadModel(name: string, buffer: ArrayBuffer): Promise<LoadedObject[]>
25
+ /** Parses one model file. `source` may be the File (or Blob) itself; a 3mf is then read by its worker, not this thread. */
26
+ export function loadModel(name: string, source: ArrayBuffer | Blob): Promise<LoadedObject[]>
27
+
28
+ /** Starts the workers that will read a file of this name (a 3mf's parse worker and helpers) before it arrives. */
29
+ export function warmLoaderFor(name: string): void
30
+
31
+ /**
32
+ * Uses `worker` (from three-slicer-viewer/workers makeParse3mfWorker) as the 3mf parse worker, so a host can start it
33
+ * before this module has loaded. Ignored, and the worker terminated, when one is already in use.
34
+ */
35
+ export function adoptParseWorker(worker: Worker): void
36
+
37
+ /** Starts parsing `source` now; the viewport's own load of that same File then takes the result instead of parsing. */
38
+ export function preloadModel(name: string, source: ArrayBuffer | Blob): void
17
39
 
18
40
  /**
19
41
  * Registers an extra format. Formats needing heavy dependencies (STEP=OCCT WASM, etc.) are not bundled here,
package/types/toggle.d.ts CHANGED
@@ -19,6 +19,12 @@ export function makeCfg(settings: SlicerSettings | null | undefined): ToggleCfg
19
19
  */
20
20
  export function evalEnableIf(expr: string, locals: Record<string, unknown>, cfg: ToggleCfg): boolean | null
21
21
 
22
+ /** enable_if with config reads and locals replaced by values, or null when it is not a boolean expression of values. */
23
+ export function substituteEnableIf(expr: string, locals: Record<string, unknown>, cfg: ToggleCfg): string | null
24
+
25
+ /** Evaluates a substituted enable_if (true/false, numbers, ! && || == != < > <= >=, parentheses) without eval. null when malformed. */
26
+ export function evaluateBooleanExpression(source: string): boolean | null
27
+
22
28
  /** Keys that must be disabled under the current settings -> the enable_if expression that disabled them. Only rules that are unambiguously false. */
23
29
  export function disabledKeys(cfg: ToggleCfg): Record<string, string>
24
30
 
@@ -1,5 +1,4 @@
1
1
  // three-slicer-viewer — kernel layers -> GPU-instanced toolpath.
2
- // Also published as three-slicer/viewer/toolpath, which re-exports this package.
3
2
  // Does not import three: makeToolpath takes the THREE namespace as an argument (guaranteeing a single instance).
4
3
 
5
4
  /** The 24 triangle indices of the 8-vertex diamond cross-section (from SegmentTemplate.cpp:18) */
package/types/viewer.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- // three-slicer/viewer
1
+ // three-slicer-viewer
2
2
  import type * as React from 'react'
3
3
  import type { SlicerSettings } from './settings-keys.d.ts'
4
4
  import type { ProcessPresetsApi, FilamentPresetsApi } from './settings.d.ts'
@@ -114,8 +114,8 @@ export interface ViewportProps {
114
114
  */
115
115
  slicer?: (deps: Record<string, unknown>) => SlicerHandle
116
116
  /**
117
- * The vendor preset catalog. This package ships none — nothing passed means empty pickers. `three-slicer/viewer`
118
- * passes its bundled OrcaSlicer extraction; a host with its own fleet passes its own (a partial object is
117
+ * The vendor preset catalog. This package ships none — nothing passed means empty pickers. `three-slicer/settings`'
118
+ * `bundledCatalog` is the OrcaSlicer extraction; a host with its own fleet passes its own (a partial object is
119
119
  * merged over the empty catalog).
120
120
  */
121
121
  catalog?: Catalog | null
@@ -254,5 +254,5 @@ export function resolveCatalog(catalog?: Partial<Catalog> | null): Catalog
254
254
  export function useNoopSlicer(): SlicerHandle
255
255
 
256
256
  /** The slicing hook, unbound. `deps.makeWorker` must return a Worker speaking this package's slice protocol —
257
- * three-slicer/viewer supplies its WASM kernel worker and re-exports the bound hook. */
257
+ * three-slicer/client's makeSlicerWorker is the WASM kernel's. */
258
258
  export function useSlicer(deps: Record<string, unknown> & { makeWorker: () => Worker }): SlicerHandle
@@ -0,0 +1,10 @@
1
+ // three-slicer-viewer/workers — the factories of this package's own workers, for a host that starts one before the
2
+ // viewer bundle has loaded (hand the parse worker to adoptParseWorker in three-slicer-viewer/loaders).
3
+
4
+ /** The 3mf parse worker. */
5
+ export function makeParse3mfWorker(): Worker
6
+ /** The SL1 mesh-reconstruction workers. */
7
+ export function makeSlaReconstructWorker(): Worker
8
+ export function makeSlaSliceWorker(): Worker
9
+ /** The SL1 mask encoder. */
10
+ export function makeSl1EncodeWorker(): Worker
@@ -1,196 +0,0 @@
1
- import * as k from "three";
2
- import { OBJLoader as P } from "three/examples/jsm/loaders/OBJLoader.js";
3
- import { PLYLoader as x } from "three/examples/jsm/loaders/PLYLoader.js";
4
- import { AMFLoader as S } from "three/examples/jsm/loaders/AMFLoader.js";
5
- import { p as M } from "./parse_3mf-CpbA-6Iq.js";
6
- import { makeParse3mfWorker as v } from "./make_worker.js";
7
- const b = 80, y = 84, _ = 50, B = (t) => y + t * _;
8
- let p = null, h = !1, D = 0;
9
- const w = /* @__PURE__ */ new Map();
10
- function W() {
11
- if (h || typeof Worker > "u") return null;
12
- if (p) return p;
13
- try {
14
- p = v(), p.onmessage = (t) => {
15
- const { id: e, objects: s, project: r, error: n } = t.data || {}, c = w.get(e);
16
- c && (w.delete(e), n ? c.reject(new Error(n)) : c.resolve({ objects: s, project: r }));
17
- }, p.onerror = () => {
18
- h = !0;
19
- for (const [, t] of w) t.reject(new Error("3MF parse worker failed"));
20
- w.clear(), p = null;
21
- };
22
- } catch {
23
- h = !0, p = null;
24
- }
25
- return p;
26
- }
27
- async function $(t, e) {
28
- const s = W();
29
- if (!s) return M(t, e);
30
- try {
31
- const r = ++D, n = new Promise((c, i) => w.set(r, { resolve: c, reject: i }));
32
- return s.postMessage({ id: r, buffer: t, baseName: e }), await n;
33
- } catch {
34
- return M(t, e);
35
- }
36
- }
37
- const T = ["stl", "obj", "3mf", "amf", "ply"], X = ["gcode", "gco", "g"], A = /* @__PURE__ */ new Map();
38
- function H(t, e) {
39
- for (const s of (Array.isArray(t) ? t : String(t).split(",")).map((r) => r.trim().toLowerCase()))
40
- A.set(s, e), T.includes(s) || T.push(s);
41
- }
42
- function C(t) {
43
- const e = t.lastIndexOf(".");
44
- return e < 0 ? "" : t.slice(e + 1).toLowerCase();
45
- }
46
- function O(t) {
47
- const e = new DataView(t);
48
- if (t.byteLength >= y) {
49
- const i = e.getUint32(b, !0);
50
- if (t.byteLength === B(i)) {
51
- const l = new Float32Array(i * 9);
52
- let f = y, u = 0;
53
- for (let o = 0; o < i; o++) {
54
- f += 12;
55
- for (let a = 0; a < 3; a++)
56
- l[u++] = e.getFloat32(f, !0), l[u++] = e.getFloat32(f + 4, !0), l[u++] = e.getFloat32(f + 8, !0), f += 12;
57
- f += 2;
58
- }
59
- return l;
60
- }
61
- }
62
- const s = new TextDecoder().decode(t), r = /vertex\s+([-\d.eE+]+)\s+([-\d.eE+]+)\s+([-\d.eE+]+)/g, n = [];
63
- let c;
64
- for (; c = r.exec(s); ) n.push(+c[1], +c[2], +c[3]);
65
- return n.length < 9 ? null : new Float32Array(n);
66
- }
67
- function j(t, e) {
68
- const s = t?.attributes?.position;
69
- if (!s || s.count < 3) return null;
70
- const r = t.index, n = new k.Vector3(), c = Math.floor((r ? r.count : s.count) / 3), i = new Float32Array(c * 9);
71
- let l = 0;
72
- const f = (u) => {
73
- n.fromBufferAttribute(s, u), e && n.applyMatrix4(e), i[l++] = n.x, i[l++] = n.y, i[l++] = n.z;
74
- };
75
- if (r)
76
- for (let u = 0; u < c * 3; u++) f(r.getX(u));
77
- else
78
- for (let u = 0; u < c * 3; u++) f(u);
79
- return i;
80
- }
81
- function F(t) {
82
- t.updateMatrixWorld(!0);
83
- const e = [];
84
- return t.traverse((s) => {
85
- s.isMesh && s.geometry && e.push({ geometry: s.geometry, matrix: s.matrixWorld });
86
- }), e;
87
- }
88
- function L(t, e, s) {
89
- const r = e.map((l) => j(l.geometry, l.matrix)).filter(Boolean);
90
- if (!r.length) return [];
91
- if (s && r.length > 1)
92
- return r.map((l, f) => ({ name: `${t}#${f + 1}`, modelPos: l }));
93
- if (r.length === 1) return [{ name: t, modelPos: r[0] }];
94
- let n = 0;
95
- for (const l of r) n += l.length;
96
- const c = new Float32Array(n);
97
- let i = 0;
98
- for (const l of r)
99
- c.set(l, i), i += l.length;
100
- return [{ name: t, modelPos: c }];
101
- }
102
- async function V(t, e) {
103
- const s = C(t);
104
- switch (s) {
105
- case "stl": {
106
- const r = O(e);
107
- if (!r) throw new Error("Failed to parse STL");
108
- return [{ name: t, modelPos: r }];
109
- }
110
- case "obj": {
111
- const r = new P().parse(new TextDecoder().decode(e));
112
- return L(t, F(r), !1);
113
- }
114
- case "ply": {
115
- const r = new x().parse(e), n = j(r, null);
116
- if (!n) throw new Error("No PLY geometry");
117
- return [{ name: t, modelPos: n }];
118
- }
119
- case "3mf": {
120
- const { objects: r, project: n } = await $(e, t), c = r.map((i) => ({ name: i.name, modelPos: i.tris, baked: i.baked, objectid: i.objectid, paint: i.paint, bbox: i.bbox, project: n }));
121
- if (!c.length && n.gcodePlates) return [{ name: t, gcodePlates: n.gcodePlates, project: n }];
122
- if (!c.length) throw new Error("No mesh in 3MF");
123
- return c;
124
- }
125
- case "amf": {
126
- const r = new S().parse(e), n = L(t, F(r), !0);
127
- if (!n.length) throw new Error("No mesh in AMF");
128
- return n;
129
- }
130
- default: {
131
- const r = A.get(s);
132
- if (!r) throw new Error(`Unsupported format: .${s}`);
133
- const n = await r(e, t);
134
- if (!n?.length) throw new Error(`No mesh in .${s}`);
135
- return n;
136
- }
137
- }
138
- }
139
- function q(t) {
140
- return R(t)?.map((e) => I(t, e)) ?? null;
141
- }
142
- function I(t, e) {
143
- const s = new Float32Array(e.length * 9);
144
- let r = 0;
145
- for (const n of e) {
146
- const c = n * 9;
147
- for (let i = 0; i < 9; i++) s[r++] = t[c + i];
148
- }
149
- return s;
150
- }
151
- function R(t) {
152
- const e = Math.floor(t.length / 9);
153
- if (e < 2) return null;
154
- const s = 1e4, r = /* @__PURE__ */ new Map(), n = new Int32Array(e * 3);
155
- for (let o = 0; o < e; o++)
156
- for (let a = 0; a < 3; a++) {
157
- const d = o * 9 + a * 3, m = `${Math.round(t[d] * s)},${Math.round(t[d + 1] * s)},${Math.round(t[d + 2] * s)}`;
158
- let g = r.get(m);
159
- g === void 0 && (g = r.size, r.set(m, g)), n[o * 3 + a] = g;
160
- }
161
- const c = new Int32Array(e);
162
- for (let o = 0; o < e; o++) c[o] = o;
163
- const i = (o) => {
164
- for (; c[o] !== o; )
165
- c[o] = c[c[o]], o = c[o];
166
- return o;
167
- }, l = (o, a) => {
168
- o = i(o), a = i(a), o !== a && (c[a] = o);
169
- }, f = /* @__PURE__ */ new Map();
170
- for (let o = 0; o < e; o++)
171
- for (let a = 0; a < 3; a++) {
172
- const d = n[o * 3 + a], m = n[o * 3 + (a + 1) % 3], g = d < m ? d * 4294967296 + m : m * 4294967296 + d, E = f.get(g);
173
- E === void 0 ? f.set(g, o) : l(o, E);
174
- }
175
- const u = /* @__PURE__ */ new Map();
176
- for (let o = 0; o < e; o++) {
177
- const a = i(o);
178
- let d = u.get(a);
179
- d || (d = [], u.set(a, d)), d.push(o);
180
- }
181
- return u.size < 2 ? null : [...u.values()].sort((o, a) => a.length - o.length);
182
- }
183
- export {
184
- X as G,
185
- b as S,
186
- y as a,
187
- _ as b,
188
- T as c,
189
- R as d,
190
- I as e,
191
- C as f,
192
- q as g,
193
- V as l,
194
- H as r,
195
- B as s
196
- };