@rulecad/cad 0.8.0 → 0.9.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 (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/mesh.mjs CHANGED
@@ -10,10 +10,13 @@ import fs from 'node:fs';
10
10
  import zlib from 'node:zlib';
11
11
 
12
12
  export const AXES = ['x', 'y', 'z'];
13
- export const axisOf = (a) => { const i = AXES.indexOf(String(a).toLowerCase()); if (i < 0) throw new Error(`axis is x, y or z, not "${a}"`); return i; };
13
+ export const axisOf = (a) => {
14
+ const i = AXES.indexOf(String(a).toLowerCase());
15
+ if (i < 0) throw new Error(`axis is x, y or z, not "${a}"`);
16
+ return i;
17
+ };
14
18
  // The two other axes of a cross-section, in order: across, then up (z when it can be)
15
19
  export const planeAxes = (axis) => (axis === 2 ? [0, 1] : axis === 1 ? [0, 2] : [1, 2]);
16
- const r2 = (n) => Math.round(n * 100) / 100;
17
20
 
18
21
  // ---- reading ----
19
22
 
@@ -24,117 +27,320 @@ export function readMesh(file) {
24
27
  throw new Error(`${file}: an STL or 3MF, please (export STEP files from a CAD program as STL first)`);
25
28
  }
26
29
 
27
- export function readStl(buf) {
30
+ // What cad reads from a file it did not make (an STL or 3MF from the internet): past these, the file is refused with
31
+ // the limit named, rather than left to fill memory. Two million triangles is about 660 MB as cad holds them, and more
32
+ // than a detailed print-ready model has; a 3MF that places its objects more than a hundred thousand times is made to
33
+ // hurt, not to print; 512 MB is what its zip may unpack to.
34
+ export const MESH_LIMITS = { triangles: 2_000_000, places: 100_000, unzipped: 512 * 1024 * 1024 };
35
+ const grouped = (n) => n.toLocaleString('en-GB');
36
+ const finite = (v) => v.length === 3 && v.every(Number.isFinite);
37
+
38
+ // readStl(buf, { triangles }) -> triangles; refuses a corner that is not three numbers, and a file past the limit
39
+ export function readStl(buf, { triangles: most = MESH_LIMITS.triangles } = {}) {
28
40
  const n = buf.length >= 84 ? buf.readUInt32LE(80) : -1;
29
- if (n >= 0 && 84 + n * 50 === buf.length) { // binary
41
+ if (n >= 0 && 84 + n * 50 === buf.length) {
42
+ // binary
43
+ if (n > most) throw new Error(`the STL has ${grouped(n)} triangles, more than the ${grouped(most)} cad reads`);
30
44
  const tris = [];
31
45
  for (let i = 0; i < n; i++) {
32
- const o = 84 + i * 50 + 12, v = (k) => [buf.readFloatLE(o + k * 12), buf.readFloatLE(o + k * 12 + 4), buf.readFloatLE(o + k * 12 + 8)];
33
- tris.push([v(0), v(1), v(2)]);
46
+ const o = 84 + i * 50 + 12,
47
+ v = (k) => [buf.readFloatLE(o + k * 12), buf.readFloatLE(o + k * 12 + 4), buf.readFloatLE(o + k * 12 + 8)];
48
+ const t = [v(0), v(1), v(2)],
49
+ bad = t.findIndex((c) => !finite(c));
50
+ if (bad >= 0) throw new Error(`not an STL: corner ${bad + 1} of triangle ${i + 1} is not three numbers`);
51
+ tris.push(t);
34
52
  }
35
53
  return tris;
36
54
  }
37
- const pts = [...buf.toString('utf8').matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)].map((m) => [+m[1], +m[2], +m[3]]);
55
+ const pts = [];
56
+ for (const m of buf.toString('utf8').matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)) {
57
+ const p = [+m[1], +m[2], +m[3]];
58
+ if (!finite(p)) {
59
+ const k = pts.length;
60
+ throw new Error(
61
+ `not an STL: corner ${(k % 3) + 1} (triangle ${Math.floor(k / 3) + 1}) is "${m.slice(1).join(' ')}", not three numbers`,
62
+ );
63
+ }
64
+ if (pts.push(p) > most * 3) throw new Error(`the STL has more than the ${grouped(most)} triangles cad reads`);
65
+ }
38
66
  if (!pts.length || pts.length % 3) throw new Error('not an STL: no triangles found');
39
67
  const tris = [];
40
68
  for (let i = 0; i < pts.length; i += 3) tris.push([pts[i], pts[i + 1], pts[i + 2]]);
41
69
  return tris;
42
70
  }
43
71
 
44
- // A zip's files by name (stored or deflated), from its central directory
45
- export function unzip(buf) {
72
+ // A zip's files by name (stored or deflated), from its central directory. What it unpacks, all entries together, may
73
+ // come to `max` bytes (512 MB): a zip made to unpack far past its size is refused, not unpacked into memory.
74
+ export function unzip(buf, { max = MESH_LIMITS.unzipped } = {}) {
46
75
  let e = buf.length - 22;
47
76
  while (e >= 0 && buf.readUInt32LE(e) !== 0x06054b50) e--;
48
77
  if (e < 0) throw new Error('not a zip file');
49
- let count = buf.readUInt16LE(e + 10), p = buf.readUInt32LE(e + 16);
50
- if (p === 0xffffffff && e >= 20 && buf.readUInt32LE(e - 20) === 0x07064b50) { // Zip64: the real numbers are in its own record
78
+ let count = buf.readUInt16LE(e + 10),
79
+ p = buf.readUInt32LE(e + 16);
80
+ if (p === 0xffffffff && e >= 20 && buf.readUInt32LE(e - 20) === 0x07064b50) {
81
+ // Zip64: the real numbers are in its own record
51
82
  const z = Number(buf.readBigUInt64LE(e - 12));
52
83
  count = Number(buf.readBigUInt64LE(z + 32));
53
84
  p = Number(buf.readBigUInt64LE(z + 48));
54
85
  }
55
- const files = {};
86
+ const files = {},
87
+ tooBig = () => new Error(`the zip unpacks to more than ${max / (1024 * 1024)} MB, the most cad reads`);
88
+ let left = max;
56
89
  for (let i = 0; i < count; i++) {
57
90
  if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error('a damaged zip file');
58
- const method = buf.readUInt16LE(p + 10), nameLen = buf.readUInt16LE(p + 28);
59
- const extraLen = buf.readUInt16LE(p + 30), noteLen = buf.readUInt16LE(p + 32);
60
- let local = buf.readUInt32LE(p + 42), csize = buf.readUInt32LE(p + 20);
91
+ const method = buf.readUInt16LE(p + 10),
92
+ nameLen = buf.readUInt16LE(p + 28);
93
+ const extraLen = buf.readUInt16LE(p + 30),
94
+ noteLen = buf.readUInt16LE(p + 32);
95
+ let local = buf.readUInt32LE(p + 42),
96
+ csize = buf.readUInt32LE(p + 20);
61
97
  const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
62
98
  // Zip64: sizes and offset in the extra field when the 32-bit ones are 0xffffffff
63
99
  const ext = buf.subarray(p + 46 + nameLen, p + 46 + nameLen + extraLen);
64
100
  for (let q = 0; q + 4 <= ext.length;) {
65
- const id = ext.readUInt16LE(q), len = ext.readUInt16LE(q + 2);
101
+ const id = ext.readUInt16LE(q),
102
+ len = ext.readUInt16LE(q + 2);
66
103
  if (id === 1) {
67
104
  let r = q + 4;
68
105
  if (buf.readUInt32LE(p + 24) === 0xffffffff) r += 8; // uncompressed size
69
- if (buf.readUInt32LE(p + 20) === 0xffffffff) { csize = Number(ext.readBigUInt64LE(r)); r += 8; }
106
+ if (buf.readUInt32LE(p + 20) === 0xffffffff) {
107
+ csize = Number(ext.readBigUInt64LE(r));
108
+ r += 8;
109
+ }
70
110
  if (local === 0xffffffff) local = Number(ext.readBigUInt64LE(r));
71
111
  }
72
112
  q += 4 + len;
73
113
  }
74
114
  const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
75
115
  const data = buf.subarray(start, start + csize);
76
- files[name] = method === 8 ? zlib.inflateRawSync(data) : method === 0 ? data : null;
116
+ let file = null;
117
+ if (method === 8)
118
+ try {
119
+ // (one byte more than is left, so that an entry that fills the rest exactly is told from one that runs over)
120
+ file = zlib.inflateRawSync(data, { maxOutputLength: left + 1 });
121
+ } catch (err) {
122
+ if (err.code === 'ERR_BUFFER_TOO_LARGE') throw tooBig();
123
+ throw err;
124
+ }
125
+ else if (method === 0) file = data;
126
+ if (file && (left -= file.length) < 0) throw tooBig();
127
+ files[name] = file;
77
128
  p += 46 + nameLen + extraLen + noteLen;
78
129
  }
79
130
  return files;
80
131
  }
81
132
 
82
- // A 3MF: every build item, with its transform, and the components it is made of (in this model file or another)
83
- export function read3mf(buf) {
84
- const files = unzip(buf);
85
- const models = Object.fromEntries(Object.entries(files).filter(([n, d]) => d && /\.model$/i.test(n)).map(([n, d]) => ['/' + n.replace(/^\//, ''), d.toString('utf8')]));
133
+ // A 3MF: every build item, with its transform, and the components it is made of (in this model file or another).
134
+ // limits: { triangles, places, max } (MESH_LIMITS): what it places is counted first, and a file past a limit is refused
135
+ // before anything is placed, as is a corner that is not three numbers or a triangle naming a corner its object hasn't.
136
+ export function read3mf(buf, limits = {}) {
137
+ const { triangles: most = MESH_LIMITS.triangles, places: follows = MESH_LIMITS.places } = limits;
138
+ const files = unzip(buf, limits);
139
+ const models = Object.fromEntries(
140
+ Object.entries(files)
141
+ .filter(([n, d]) => d && /\.model$/i.test(n))
142
+ .map(([n, d]) => ['/' + n.replace(/^\//, ''), d.toString('utf8')]),
143
+ );
86
144
  const root = Object.keys(models).find((n) => /^\/3D\/3dmodel\.model$/i.test(n)) || Object.keys(models)[0];
87
145
  if (!root) throw new Error('no 3D model in the 3MF');
88
- const attr = (s, k) => { const m = s.match(new RegExp(`(?:^|\\s)${k}="([^"]*)"`)); return m ? m[1] : undefined; };
89
- const objects = {}; // "<file>#<id>" -> { tris, components }
90
- for (const [file, xml] of Object.entries(models)) {
91
- for (const m of xml.matchAll(/<object\b([^>]*)>([\s\S]*?)<\/object>/g)) {
92
- const id = attr(m[1], 'id'), body = m[2];
93
- const verts = [...body.matchAll(/<vertex\b([^>]*)\/>/g)].map((v) => ['x', 'y', 'z'].map((k) => +attr(v[1], k)));
94
- const tris = [...body.matchAll(/<triangle\b([^>]*)\/>/g)].map((t) => ['v1', 'v2', 'v3'].map((k) => verts[+attr(t[1], k)]));
95
- const components = [...body.matchAll(/<component\b([^>]*)\/>/g)].map((c) => ({ ref: `${attr(c[1], 'p:path') || file}#${attr(c[1], 'objectid')}`, transform: attr(c[1], 'transform') }));
96
- objects[`${file}#${id}`] = { tris, components };
146
+ const objects = readObjects3mf(models, most, follows);
147
+ const items = [];
148
+ for (const it of models[root].matchAll(/<item\b([^>]*)\/>/g)) {
149
+ // (counted as they are read: a small file can name millions of build items, each one more placing)
150
+ if (items.length >= follows) throw tooManyPlaces(follows);
151
+ items.push({
152
+ ref: `${attr3mf(it[1], 'p:path') || root}#${attr3mf(it[1], 'objectid')}`,
153
+ transform: attr3mf(it[1], 'transform'),
154
+ });
155
+ }
156
+ const tops = items.length
157
+ ? items
158
+ : Object.keys(objects)
159
+ .filter((k) => k.startsWith(root))
160
+ .map((ref) => ({ ref }));
161
+ // How many triangles and placings each object brings, with all it holds (by depth, as placing stops at 16)
162
+ const memo = new Map();
163
+ const tally = (key, depth) => {
164
+ const o = objects[key];
165
+ if (!o || depth > 16) return [0, 0];
166
+ const k = `${key}@${depth}`;
167
+ if (!memo.has(k)) {
168
+ const sum = [o.tris.length, 1];
169
+ for (const c of o.components) {
170
+ const [t, n] = tally(c.ref, depth + 1);
171
+ sum[0] += t;
172
+ sum[1] += n;
173
+ }
174
+ memo.set(k, sum);
97
175
  }
176
+ return memo.get(k);
177
+ };
178
+ const total = [0, 0];
179
+ for (const it of tops) {
180
+ const [t, n] = tally(it.ref, 0);
181
+ total[0] += t;
182
+ total[1] += n;
98
183
  }
184
+ if (total[0] > most)
185
+ throw new Error(`the 3MF places ${grouped(total[0])} triangles, more than the ${grouped(most)} cad reads`);
186
+ if (total[1] > follows) throw tooManyPlaces(follows, total[1]);
99
187
  const out = [];
100
188
  const place = (key, M, depth = 0) => {
101
189
  const o = objects[key];
102
190
  if (!o || depth > 16) return;
103
- for (const t of o.tris) out.push(t.map((v) => apply3mf(M, v)));
191
+ for (const t of o.tris) {
192
+ const placed = t.map((v) => apply3mf(M, v));
193
+ // (finite corners and finite transforms can still multiply past what a number holds: 1e200 placed at 1e200)
194
+ if (!placed.every(finite))
195
+ throw new Error(`the 3MF places object ${key.split('#')[1]} so far out that its corners are not numbers`);
196
+ out.push(placed);
197
+ }
104
198
  for (const c of o.components) place(c.ref, mul3mf(parse3mf(c.transform), M), depth + 1);
105
199
  };
106
- const items = [...models[root].matchAll(/<item\b([^>]*)\/>/g)];
107
- if (items.length) for (const it of items) place(`${attr(it[1], 'p:path') || root}#${attr(it[1], 'objectid')}`, parse3mf(attr(it[1], 'transform')));
108
- else for (const k of Object.keys(objects)) if (k.startsWith(root)) place(k, parse3mf());
200
+ for (const it of tops) place(it.ref, parse3mf(it.transform));
109
201
  if (!out.length) throw new Error('the 3MF has no triangles');
110
202
  return out;
111
203
  }
204
+ const attr3mf = (s, k) => {
205
+ const m = s.match(new RegExp(`(?:^|\\s)${k}="([^"]*)"`));
206
+ return m ? m[1] : undefined;
207
+ };
208
+ // Every object in a 3MF's model files: "<file>#<id>" -> { tris, components }, its corners checked as it is read
209
+ // (Everything is counted as it is read, not after: a file that unpacks to 512 MB of corners, triangles or components
210
+ // would otherwise hold gigabytes before a limit was looked at. A part holds at most three corners for each triangle.)
211
+ function readObjects3mf(models, most, follows) {
212
+ const objects = {};
213
+ let held = 0,
214
+ corners = 0,
215
+ named = 0;
216
+ for (const [file, xml] of Object.entries(models)) {
217
+ for (const [attrs, body] of objects3mf(xml)) {
218
+ const id = attr3mf(attrs, 'id'),
219
+ where = `object ${id} (${file.slice(1)})`;
220
+ const verts = [];
221
+ for (const v of body.matchAll(/<vertex\b([^>]*)\/>/g)) {
222
+ if (++corners > most * 3) throw new Error(`the 3MF holds more than the ${grouped(most * 3)} corners cad reads`);
223
+ const p = ['x', 'y', 'z'].map((k) => Number(attr3mf(v[1], k) ?? NaN));
224
+ if (!finite(p)) throw new Error(`the 3MF's corner ${verts.length + 1} of ${where} is not three numbers`);
225
+ verts.push(p);
226
+ }
227
+ const tris = [];
228
+ for (const t of body.matchAll(/<triangle\b([^>]*)\/>/g)) {
229
+ if (++held > most) throw new Error(`the 3MF holds more than the ${grouped(most)} triangles cad reads`);
230
+ const ids = ['v1', 'v2', 'v3'].map((k) => Number(attr3mf(t[1], k)));
231
+ const bad = ids.find((i) => !(Number.isInteger(i) && i >= 0 && i < verts.length));
232
+ if (bad !== undefined)
233
+ throw new Error(
234
+ `the 3MF's triangle ${tris.length + 1} of ${where} names corner ${Number.isFinite(bad) ? bad + 1 : 'none'}, and the object has ${verts.length}`,
235
+ );
236
+ tris.push(ids.map((i) => verts[i]));
237
+ }
238
+ const components = [];
239
+ for (const c of body.matchAll(/<component\b([^>]*)\/>/g)) {
240
+ // (each component named is a placing, or names nothing: either way more than cad follows is refused)
241
+ if (++named > follows) throw tooManyPlaces(follows);
242
+ components.push({
243
+ ref: `${attr3mf(c[1], 'p:path') || file}#${attr3mf(c[1], 'objectid')}`,
244
+ transform: attr3mf(c[1], 'transform'),
245
+ });
246
+ }
247
+ objects[`${file}#${id}`] = { tris, components };
248
+ }
249
+ }
250
+ return objects;
251
+ }
252
+ const tooManyPlaces = (follows, n) =>
253
+ new Error(
254
+ n
255
+ ? `the 3MF places its objects ${grouped(n)} times, more than the ${grouped(follows)} cad follows`
256
+ : `the 3MF places its objects more than the ${grouped(follows)} times cad follows`,
257
+ );
258
+ // Each <object …>…</object> in a model file, as [its attributes, what it holds], read in one pass. (A pattern that
259
+ // looks for the closing tag from every opening one takes time by the square of the file: a few kilobytes of <object>
260
+ // with no </object> would hold cad for minutes.) An object never closed ends the reading, as nothing after it can be.
261
+ function* objects3mf(xml) {
262
+ for (let at = 0; ;) {
263
+ const s = xml.indexOf('<object', at);
264
+ if (s < 0) return;
265
+ if (/\w/.test(xml[s + 7] ?? '')) {
266
+ at = s + 7; // <objects…>, another tag
267
+ continue;
268
+ }
269
+ const open = xml.indexOf('>', s);
270
+ if (open < 0) return;
271
+ const close = xml.indexOf('</object>', open);
272
+ if (close < 0) return;
273
+ yield [xml.slice(s + 7, open), xml.slice(open + 1, close)];
274
+ at = close + 9;
275
+ }
276
+ }
112
277
  // 3MF transforms are 3 × 4, row vectors: p' = p · M (m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32)
113
- const parse3mf = (s) => (s ? s.trim().split(/\s+/).map(Number) : [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
114
- const apply3mf = (m, [x, y, z]) => [x * m[0] + y * m[3] + z * m[6] + m[9], x * m[1] + y * m[4] + z * m[7] + m[10], x * m[2] + y * m[5] + z * m[8] + m[11]];
115
- const mul3mf = (a, b) => { // a then b
278
+ const parse3mf = (s) => {
279
+ if (!s) return [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0];
280
+ const m = s.trim().split(/\s+/).map(Number);
281
+ if (m.length !== 12 || !m.every(Number.isFinite)) throw new Error(`the 3MF's transform "${s}" is not twelve numbers`);
282
+ return m;
283
+ };
284
+ const apply3mf = (m, [x, y, z]) => [
285
+ x * m[0] + y * m[3] + z * m[6] + m[9],
286
+ x * m[1] + y * m[4] + z * m[7] + m[10],
287
+ x * m[2] + y * m[5] + z * m[8] + m[11],
288
+ ];
289
+ const mul3mf = (a, b) => {
290
+ // a then b
116
291
  const r = [];
117
- for (let i = 0; i < 4; i++) for (let j = 0; j < 3; j++) r.push((i < 3 ? 0 : b[9 + j]) + a[i * 3] * b[j] + a[i * 3 + 1] * b[3 + j] + a[i * 3 + 2] * b[6 + j]);
292
+ for (let i = 0; i < 4; i++)
293
+ for (let j = 0; j < 3; j++)
294
+ r.push((i < 3 ? 0 : b[9 + j]) + a[i * 3] * b[j] + a[i * 3 + 1] * b[3 + j] + a[i * 3 + 2] * b[6 + j]);
118
295
  return r;
119
296
  };
120
297
 
121
298
  // ---- measuring ----
122
299
 
300
+ // An empty mesh has no size and no volume: both refuse it, rather than give Infinity and NaN to the sums after them
301
+ const someTriangles = (tris) => {
302
+ if (!tris?.length) throw new Error('no triangles: an empty mesh has no size or volume');
303
+ };
123
304
  export function bounds(tris) {
124
- const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
125
- for (const t of tris) for (const v of t) for (let a = 0; a < 3; a++) { if (v[a] < min[a]) min[a] = v[a]; if (v[a] > max[a]) max[a] = v[a]; }
305
+ someTriangles(tris);
306
+ const min = [Infinity, Infinity, Infinity],
307
+ max = [-Infinity, -Infinity, -Infinity];
308
+ for (const t of tris)
309
+ for (const v of t)
310
+ for (let a = 0; a < 3; a++) {
311
+ if (v[a] < min[a]) min[a] = v[a];
312
+ if (v[a] > max[a]) max[a] = v[a];
313
+ }
126
314
  return { min, max, size: max.map((m, a) => m - min[a]) };
127
315
  }
128
- export const volume = (tris) => Math.abs(tris.reduce((s, [a, b, c]) => s + (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6, 0));
316
+ export function volume(tris) {
317
+ someTriangles(tris);
318
+ return Math.abs(
319
+ tris.reduce(
320
+ (s, [a, b, c]) =>
321
+ s +
322
+ (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) /
323
+ 6,
324
+ 0,
325
+ ),
326
+ );
327
+ }
129
328
 
130
329
  // The cross-section at axis = v: segments in the plane's (across, up) coordinates
131
330
  export function section(tris, axis, v) {
132
- const [u, w] = planeAxes(axis), segs = [];
331
+ const [u, w] = planeAxes(axis),
332
+ segs = [];
133
333
  for (const t of tris) {
134
334
  const pts = [];
135
335
  for (let i = 0; i < 3; i++) {
136
- const a = t[i], b = t[(i + 1) % 3], da = a[axis] - v, db = b[axis] - v;
137
- if ((da < 0 && db >= 0) || (da >= 0 && db < 0)) { const f = da / (da - db); pts.push([a[u] + f * (b[u] - a[u]), a[w] + f * (b[w] - a[w])]); }
336
+ const a = t[i],
337
+ b = t[(i + 1) % 3],
338
+ da = a[axis] - v,
339
+ db = b[axis] - v;
340
+ if ((da < 0 && db >= 0) || (da >= 0 && db < 0)) {
341
+ const f = da / (da - db);
342
+ pts.push([a[u] + f * (b[u] - a[u]), a[w] + f * (b[w] - a[w])]);
343
+ }
138
344
  }
139
345
  if (pts.length === 2) segs.push(pts);
140
346
  }
@@ -149,25 +355,41 @@ export function section(tris, axis, v) {
149
355
  // more than half a step from one section to the next. A face lying flat moves no outline: the sections either side of
150
356
  // it hold what it covers.
151
357
  export function slabLevels(tris, lo, hi, step) {
152
- const eps = 1e-5, a = lo + eps, b = hi - eps, n0 = Math.max(1, Math.ceil((b - a) / (step / 2))), gap = (b - a) / n0, need = new Float64Array(n0);
358
+ const eps = 1e-5,
359
+ a = lo + eps,
360
+ b = hi - eps,
361
+ n0 = Math.max(1, Math.ceil((b - a) / (step / 2))),
362
+ gap = (b - a) / n0,
363
+ need = new Float64Array(n0);
153
364
  for (const [p, q, r] of tris) {
154
- const z0 = Math.max(a, Math.min(p[2], q[2], r[2])), z1 = Math.min(b, Math.max(p[2], q[2], r[2]));
365
+ const z0 = Math.max(a, Math.min(p[2], q[2], r[2])),
366
+ z1 = Math.min(b, Math.max(p[2], q[2], r[2]));
155
367
  if (!(z1 > z0)) continue;
156
- const u = [q[0] - p[0], q[1] - p[1], q[2] - p[2]], v = [r[0] - p[0], r[1] - p[1], r[2] - p[2]];
157
- const nx = u[1] * v[2] - u[2] * v[1], ny = u[2] * v[0] - u[0] * v[2], nz = u[0] * v[1] - u[1] * v[0], across = Math.hypot(nx, ny);
368
+ const u = [q[0] - p[0], q[1] - p[1], q[2] - p[2]],
369
+ v = [r[0] - p[0], r[1] - p[1], r[2] - p[2]];
370
+ const nx = u[1] * v[2] - u[2] * v[1],
371
+ ny = u[2] * v[0] - u[0] * v[2],
372
+ nz = u[0] * v[1] - u[1] * v[0],
373
+ across = Math.hypot(nx, ny);
158
374
  if (!(across > 1e-12)) continue;
159
375
  const lean = Math.abs(nz) / across;
160
- for (let i = Math.max(0, Math.floor((z0 - a) / gap)); i < n0 && a + i * gap < z1; i++) need[i] = Math.max(need[i], lean * (Math.min(z1, a + (i + 1) * gap) - Math.max(z0, a + i * gap)));
376
+ for (let i = Math.max(0, Math.floor((z0 - a) / gap)); i < n0 && a + i * gap < z1; i++)
377
+ need[i] = Math.max(need[i], lean * (Math.min(z1, a + (i + 1) * gap) - Math.max(z0, a + i * gap)));
161
378
  }
162
379
  const out = [a];
163
- for (let i = 0; i < n0; i++) { const m = Math.max(1, Math.ceil((2 * need[i]) / step)); for (let k = 1; k <= m; k++) out.push(a + gap * (i + k / m)); }
380
+ for (let i = 0; i < n0; i++) {
381
+ const m = Math.max(1, Math.ceil((2 * need[i]) / step));
382
+ for (let k = 1; k <= m; k++) out.push(a + gap * (i + k / m));
383
+ }
164
384
  return out;
165
385
  }
166
386
 
167
387
  // Where a line through a section, at height h, is inside: [[from, to], …] across
168
388
  export function crossings(segs, h) {
169
389
  const xs = [];
170
- for (const [a, b] of segs) if ((a[1] < h && b[1] >= h) || (a[1] >= h && b[1] < h)) xs.push(a[0] + ((h - a[1]) / (b[1] - a[1])) * (b[0] - a[0]));
390
+ for (const [a, b] of segs)
391
+ if ((a[1] < h && b[1] >= h) || (a[1] >= h && b[1] < h))
392
+ xs.push(a[0] + ((h - a[1]) / (b[1] - a[1])) * (b[0] - a[0]));
171
393
  xs.sort((p, q) => p - q);
172
394
  const out = [];
173
395
  for (let i = 0; i + 1 < xs.length; i += 2) out.push([xs[i], xs[i + 1]]);
@@ -176,13 +398,17 @@ export function crossings(segs, h) {
176
398
 
177
399
  // Where a line along an axis, through the point `at` (the other two coordinates), is inside the solid
178
400
  export function spans(tris, axis, at) {
179
- const [u, w] = planeAxes(axis), pu = at[0] + 1e-5, pw = at[1] + 1.3e-5; // off any edge
401
+ const [u, w] = planeAxes(axis),
402
+ pu = at[0] + 1e-5,
403
+ pw = at[1] + 1.3e-5; // off any edge
180
404
  const hits = [];
181
405
  for (const t of tris) {
182
406
  const [a, b, c] = t;
183
407
  const d = (b[u] - a[u]) * (c[w] - a[w]) - (c[u] - a[u]) * (b[w] - a[w]);
184
408
  if (!d) continue;
185
- const l1 = ((b[u] - pu) * (c[w] - pw) - (c[u] - pu) * (b[w] - pw)) / d, l2 = ((c[u] - pu) * (a[w] - pw) - (a[u] - pu) * (c[w] - pw)) / d, l3 = 1 - l1 - l2;
409
+ const l1 = ((b[u] - pu) * (c[w] - pw) - (c[u] - pu) * (b[w] - pw)) / d,
410
+ l2 = ((c[u] - pu) * (a[w] - pw) - (a[u] - pu) * (c[w] - pw)) / d,
411
+ l3 = 1 - l1 - l2;
186
412
  if (l1 >= 0 && l2 >= 0 && l3 >= 0) hits.push(l1 * a[axis] + l2 * b[axis] + l3 * c[axis]);
187
413
  }
188
414
  hits.sort((p, q) => p - q);
@@ -195,14 +421,22 @@ export function spans(tris, axis, at) {
195
421
  export function loops(segs, eps = 1e-4) {
196
422
  const key = (p) => `${Math.round(p[0] / eps)},${Math.round(p[1] / eps)}`;
197
423
  const from = new Map();
198
- segs.forEach((s, i) => { for (const p of s) { const k = key(p); if (!from.has(k)) from.set(k, []); from.get(k).push(i); } });
199
- const used = new Set(), out = [];
424
+ segs.forEach((s, i) => {
425
+ for (const p of s) {
426
+ const k = key(p);
427
+ if (!from.has(k)) from.set(k, []);
428
+ from.get(k).push(i);
429
+ }
430
+ });
431
+ const used = new Set(),
432
+ out = [];
200
433
  for (let i = 0; i < segs.length; i++) {
201
434
  if (used.has(i)) continue;
202
435
  used.add(i);
203
436
  const line = [segs[i][0], segs[i][1]];
204
437
  for (;;) {
205
- const end = line[line.length - 1], next = (from.get(key(end)) || []).find((j) => !used.has(j));
438
+ const end = line[line.length - 1],
439
+ next = (from.get(key(end)) || []).find((j) => !used.has(j));
206
440
  if (next === undefined) break;
207
441
  used.add(next);
208
442
  const [p, q] = segs[next];
@@ -221,17 +455,24 @@ export function loops(segs, eps = 1e-4) {
221
455
  export function profiles(tris, axis, { max = 4000, tol = 0.05 } = {}) {
222
456
  const { min, max: hi } = bounds(tris);
223
457
  let cuts = [...new Set(tris.flatMap((t) => t.map((v) => Math.round(v[axis] * 1000) / 1000)))].sort((a, b) => a - b);
224
- if (cuts.length > max) cuts = Array.from({ length: max + 1 }, (_, i) => min[axis] + ((hi[axis] - min[axis]) * i) / max);
458
+ if (cuts.length > max)
459
+ cuts = Array.from({ length: max + 1 }, (_, i) => min[axis] + ((hi[axis] - min[axis]) * i) / max);
225
460
  // A section's signature is its shape, not its triangulation: where lines across it, and up it, are inside
226
- const [u, w] = planeAxes(axis), grid = 48;
461
+ const [u, w] = planeAxes(axis),
462
+ grid = 48;
227
463
  const lines = (a) => Array.from({ length: grid }, (_, i) => min[a] + ((hi[a] - min[a]) * (i + 0.5)) / grid);
228
464
  const swap = (segs) => segs.map((sg) => sg.map(([x, y]) => [y, x]));
229
- const sig = (segs) => [...lines(w).map((h) => crossings(segs, h).flat()), ...lines(u).map((h) => crossings(swap(segs), h).flat())];
465
+ const sig = (segs) => [
466
+ ...lines(w).map((h) => crossings(segs, h).flat()),
467
+ ...lines(u).map((h) => crossings(swap(segs), h).flat()),
468
+ ];
230
469
  // The same shape: every line crosses it as often, at places within tol (a curve's facets move a crossing a little)
231
470
  const same = (a, b) => a.every((l, i) => l.length === b[i].length && l.every((x, j) => Math.abs(x - b[i][j]) <= tol));
232
471
  const runs = [];
233
472
  for (let i = 0; i + 1 < cuts.length; i++) {
234
- const at = (cuts[i] + cuts[i + 1]) / 2, segs = section(tris, axis, at), s = sig(segs);
473
+ const at = (cuts[i] + cuts[i + 1]) / 2,
474
+ segs = section(tris, axis, at),
475
+ s = sig(segs);
235
476
  const last = runs[runs.length - 1];
236
477
  if (last && same(last.sig, s)) last.to = cuts[i + 1];
237
478
  else runs.push({ from: cuts[i], to: cuts[i + 1], sig: s, at, segs });
@@ -239,17 +480,27 @@ export function profiles(tris, axis, { max = 4000, tol = 0.05 } = {}) {
239
480
  // Short runs that differ from each neighbour are a changing stretch (a taper or curve): merge them
240
481
  const out = [];
241
482
  for (const r of runs) {
242
- const last = out[out.length - 1], short = (x) => x.to - x.from < (hi[axis] - min[axis]) / 200;
243
- if (last && short(r) && (last.varies || short(last))) { last.to = r.to; last.varies = true; } else out.push({ ...r, varies: false });
483
+ const last = out[out.length - 1],
484
+ short = (x) => x.to - x.from < (hi[axis] - min[axis]) / 200;
485
+ if (last && short(r) && (last.varies || short(last))) {
486
+ last.to = r.to;
487
+ last.varies = true;
488
+ } else out.push({ ...r, varies: false });
244
489
  }
245
490
  // Number the distinct shapes: a stretch with the same section as an earlier one gets its number
246
491
  const distinct = [];
247
492
  for (const r of out) {
248
- if (!r.varies) { r.at = (r.from + r.to) / 2; r.segs = section(tris, axis, r.at); } // the middle: clear of any lead-in at its ends
493
+ if (!r.varies) {
494
+ r.at = (r.from + r.to) / 2;
495
+ r.segs = section(tris, axis, r.at);
496
+ } // the middle: clear of any lead-in at its ends
249
497
  Object.assign(r, profileOf(r.segs));
250
498
  if (r.varies || r.empty) continue;
251
499
  r.shape = distinct.findIndex((x) => same(x, r.sig));
252
- if (r.shape < 0) { distinct.push(r.sig); r.shape = distinct.length - 1; }
500
+ if (r.shape < 0) {
501
+ distinct.push(r.sig);
502
+ r.shape = distinct.length - 1;
503
+ }
253
504
  }
254
505
  for (const r of out) delete r.sig;
255
506
  return out;
@@ -260,24 +511,48 @@ export function profiles(tris, axis, { max = 4000, tol = 0.05 } = {}) {
260
511
  // bottom and top and at their widest; `straight` when the sides don't move within the band (no slope or curve).
261
512
  export function profileOf(segs) {
262
513
  if (!segs.length) return { empty: true, bands: [] };
263
- const pts = segs.flat(), us = pts.map((p) => p[0]), ws = pts.map((p) => p[1]);
514
+ const pts = segs.flat(),
515
+ us = pts.map((p) => p[0]),
516
+ ws = pts.map((p) => p[1]);
264
517
  const extent = { across: [Math.min(...us), Math.max(...us)], up: [Math.min(...ws), Math.max(...ws)] };
265
518
  const levels = [...new Set(ws.map((w) => Math.round(w * 1000) / 1000))].sort((a, b) => a - b);
266
519
  const raw = [];
267
520
  for (let i = 0; i + 1 < levels.length; i++) {
268
521
  const r = { from: levels[i], to: levels[i + 1], inside: crossings(segs, (levels[i] + levels[i + 1]) / 2) };
269
- if (r.to - r.from < 0.02 && raw.length) raw[raw.length - 1].to = r.to; else raw.push(r); // slivers between facets
522
+ if (r.to - r.from < 0.02 && raw.length) raw[raw.length - 1].to = r.to;
523
+ else raw.push(r); // slivers between facets
270
524
  }
271
525
  // Steps: flat stretches of outline (a ledge, a shoulder) start a new band even when the piece count doesn't change
272
- const steps = new Set(segs.filter(([a, b]) => Math.abs(a[1] - b[1]) < 1e-6 && Math.abs(a[0] - b[0]) > 0.05).map(([a]) => Math.round(a[1] * 1000) / 1000));
526
+ const steps = new Set(
527
+ segs
528
+ .filter(([a, b]) => Math.abs(a[1] - b[1]) < 1e-6 && Math.abs(a[0] - b[0]) > 0.05)
529
+ .map(([a]) => Math.round(a[1] * 1000) / 1000),
530
+ );
273
531
  const bands = [];
274
532
  for (const r of raw) {
275
533
  const last = bands[bands.length - 1];
276
- if (last && last.pieces === r.inside.length && ![...steps].some((h) => Math.abs(h - r.from) < 0.02)) { last.to = r.to; last.top = r.inside; last.n++; last.widest = last.widest.map(([a, b], j) => [Math.min(a, r.inside[j][0]), Math.max(b, r.inside[j][1])]); }
277
- else bands.push({ from: r.from, to: r.to, pieces: r.inside.length, bottom: r.inside, top: r.inside, widest: r.inside, n: 1 });
534
+ if (last && last.pieces === r.inside.length && ![...steps].some((h) => Math.abs(h - r.from) < 0.02)) {
535
+ last.to = r.to;
536
+ last.top = r.inside;
537
+ last.n++;
538
+ last.widest = last.widest.map(([a, b], j) => [Math.min(a, r.inside[j][0]), Math.max(b, r.inside[j][1])]);
539
+ } else
540
+ bands.push({
541
+ from: r.from,
542
+ to: r.to,
543
+ pieces: r.inside.length,
544
+ bottom: r.inside,
545
+ top: r.inside,
546
+ widest: r.inside,
547
+ n: 1,
548
+ });
278
549
  }
279
550
  const near = (x, y) => x.every(([a, b], j) => Math.abs(a - y[j][0]) < 0.01 && Math.abs(b - y[j][1]) < 0.01);
280
- for (const g of bands) { g.straight = near(g.bottom, g.top) && near(g.bottom, g.widest); g.inside = g.widest; delete g.n; }
551
+ for (const g of bands) {
552
+ g.straight = near(g.bottom, g.top) && near(g.bottom, g.widest);
553
+ g.inside = g.widest;
554
+ delete g.n;
555
+ }
281
556
  return { extent, bands, curved: bands.some((g) => !g.straight), loops: loops(segs) };
282
557
  }
283
558
 
@@ -285,25 +560,62 @@ export function profileOf(segs) {
285
560
 
286
561
  // The 24 ways to turn a part a quarter turn at a time, as 3 × 3 matrices (rows), with names like "rx90 rz180"
287
562
  export const turns = (() => {
288
- const rot = (a, q) => { const c = [1, 0, -1, 0][q], s = [0, 1, 0, -1][q], m = { 0: [[1, 0, 0], [0, c, -s], [0, s, c]], 1: [[c, 0, s], [0, 1, 0], [-s, 0, c]], 2: [[c, -s, 0], [s, c, 0], [0, 0, 1]] }; return m[a]; };
563
+ const rot = (a, q) => {
564
+ const c = [1, 0, -1, 0][q],
565
+ s = [0, 1, 0, -1][q],
566
+ m = {
567
+ 0: [
568
+ [1, 0, 0],
569
+ [0, c, -s],
570
+ [0, s, c],
571
+ ],
572
+ 1: [
573
+ [c, 0, s],
574
+ [0, 1, 0],
575
+ [-s, 0, c],
576
+ ],
577
+ 2: [
578
+ [c, -s, 0],
579
+ [s, c, 0],
580
+ [0, 0, 1],
581
+ ],
582
+ };
583
+ return m[a];
584
+ };
289
585
  const mul = (A, B) => A.map((r) => B[0].map((_, j) => r.reduce((s, x, k) => s + x * B[k][j], 0)));
290
586
  const seen = new Map();
291
- for (const [a0, q0] of [[0, 0], [0, 1], [0, 2], [0, 3], [1, 1], [1, 3]]) for (let q1 = 0; q1 < 4; q1++) {
292
- const M = mul(rot(2, q1), rot(a0, q0)), k = JSON.stringify(M);
293
- const name = [q0 ? `r${AXES[a0]}${q0 * 90}` : '', q1 ? `rz${q1 * 90}` : ''].filter(Boolean).join(' ') || 'none';
294
- if (!seen.has(k)) seen.set(k, { name, M });
295
- }
587
+ for (const [a0, q0] of [
588
+ [0, 0],
589
+ [0, 1],
590
+ [0, 2],
591
+ [0, 3],
592
+ [1, 1],
593
+ [1, 3],
594
+ ])
595
+ for (let q1 = 0; q1 < 4; q1++) {
596
+ const M = mul(rot(2, q1), rot(a0, q0)),
597
+ k = JSON.stringify(M);
598
+ const name = [q0 ? `r${AXES[a0]}${q0 * 90}` : '', q1 ? `rz${q1 * 90}` : ''].filter(Boolean).join(' ') || 'none';
599
+ if (!seen.has(k)) seen.set(k, { name, M });
600
+ }
296
601
  return [...seen.values()];
297
602
  })();
298
- export const turn = (tris, M, shift = [0, 0, 0]) => tris.map((t) => t.map((v) => M.map((r, i) => r[0] * v[0] + r[1] * v[1] + r[2] * v[2] + shift[i])));
603
+ export const turn = (tris, M, shift = [0, 0, 0]) =>
604
+ tris.map((t) => t.map((v) => M.map((r, i) => r[0] * v[0] + r[1] * v[1] + r[2] * v[2] + shift[i])));
299
605
 
300
606
  // "rz90 rx180 t1,2,3" -> { M, shift }: turns applied in order, then the shift
301
607
  export function parsePlacement(s) {
302
- let M = [[1, 0, 0], [0, 1, 0], [0, 0, 1]], shift = [0, 0, 0];
608
+ let M = [
609
+ [1, 0, 0],
610
+ [0, 1, 0],
611
+ [0, 0, 1],
612
+ ],
613
+ shift = [0, 0, 0];
303
614
  for (const w of String(s).trim().split(/\s+/).filter(Boolean)) {
304
- const r = w.match(/^r([xyz])(-?\d+)$/), t = w.match(/^t(-?[\d.]+),(-?[\d.]+),(-?[\d.]+)$/);
615
+ const r = w.match(/^r([xyz])(-?\d+)$/),
616
+ t = w.match(/^t(-?[\d.]+),(-?[\d.]+),(-?[\d.]+)$/);
305
617
  if (r) {
306
- const q = ((+r[2] / 90) % 4 + 4) % 4;
618
+ const q = (((+r[2] / 90) % 4) + 4) % 4;
307
619
  if (!Number.isInteger(q)) throw new Error(`${w}: quarter turns only (90, 180, 270)`);
308
620
  const one = turns.find((x) => x.name === (q ? `r${r[1]}${q * 90}` : 'none'))?.M || rotOne(axisOf(r[1]), q);
309
621
  M = one.map((row) => M[0].map((_, j) => row.reduce((s2, x, k) => s2 + x * M[k][j], 0)));
@@ -312,41 +624,89 @@ export function parsePlacement(s) {
312
624
  }
313
625
  return { M, shift };
314
626
  }
315
- const rotOne = (a, q) => { const c = [1, 0, -1, 0][q], s = [0, 1, 0, -1][q]; return { 0: [[1, 0, 0], [0, c, -s], [0, s, c]], 1: [[c, 0, s], [0, 1, 0], [-s, 0, c]], 2: [[c, -s, 0], [s, c, 0], [0, 0, 1]] }[a]; };
627
+ const rotOne = (a, q) => {
628
+ const c = [1, 0, -1, 0][q],
629
+ s = [0, 1, 0, -1][q];
630
+ return {
631
+ 0: [
632
+ [1, 0, 0],
633
+ [0, c, -s],
634
+ [0, s, c],
635
+ ],
636
+ 1: [
637
+ [c, 0, s],
638
+ [0, 1, 0],
639
+ [-s, 0, c],
640
+ ],
641
+ 2: [
642
+ [c, -s, 0],
643
+ [s, c, 0],
644
+ [0, 0, 1],
645
+ ],
646
+ }[a];
647
+ };
316
648
 
317
649
  // Nearest-point queries on a mesh, through a grid of its triangles
318
650
  export function surface(tris) {
319
651
  const { min, size } = bounds(tris);
320
- const h = Math.max(Math.cbrt((size[0] + 1) * (size[1] + 1) * (size[2] + 1) / Math.max(tris.length, 1)) * 1.5, 0.2);
652
+ const h = Math.max(Math.cbrt(((size[0] + 1) * (size[1] + 1) * (size[2] + 1)) / Math.max(tris.length, 1)) * 1.5, 0.2);
321
653
  const dims = size.map((s) => Math.max(1, Math.ceil((s + 1e-9) / h)));
322
654
  const cell = (v, a) => Math.min(dims[a] - 1, Math.max(0, Math.floor((v - min[a]) / h)));
323
- const grid = new Map(), id = (i, j, k) => (i * dims[1] + j) * dims[2] + k;
324
- const normals = tris.map(([a, b, c]) => { const u = sub(b, a), v = sub(c, a), n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]], l = Math.hypot(...n) || 1; return n.map((x) => x / l); });
655
+ const grid = new Map(),
656
+ id = (i, j, k) => (i * dims[1] + j) * dims[2] + k;
657
+ const normals = tris.map(([a, b, c]) => {
658
+ const u = sub(b, a),
659
+ v = sub(c, a),
660
+ n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]],
661
+ l = Math.hypot(...n) || 1;
662
+ return n.map((x) => x / l);
663
+ });
325
664
  tris.forEach((t, n) => {
326
- const lo = [0, 1, 2].map((a) => cell(Math.min(t[0][a], t[1][a], t[2][a]), a)), hi = [0, 1, 2].map((a) => cell(Math.max(t[0][a], t[1][a], t[2][a]), a));
327
- for (let i = lo[0]; i <= hi[0]; i++) for (let j = lo[1]; j <= hi[1]; j++) for (let k = lo[2]; k <= hi[2]; k++) { const c = id(i, j, k); if (!grid.has(c)) grid.set(c, []); grid.get(c).push(n); }
665
+ const lo = [0, 1, 2].map((a) => cell(Math.min(t[0][a], t[1][a], t[2][a]), a)),
666
+ hi = [0, 1, 2].map((a) => cell(Math.max(t[0][a], t[1][a], t[2][a]), a));
667
+ for (let i = lo[0]; i <= hi[0]; i++)
668
+ for (let j = lo[1]; j <= hi[1]; j++)
669
+ for (let k = lo[2]; k <= hi[2]; k++) {
670
+ const c = id(i, j, k);
671
+ if (!grid.has(c)) grid.set(c, []);
672
+ grid.get(c).push(n);
673
+ }
328
674
  });
329
675
  const far = Math.max(...dims);
330
676
  // nearest(p) -> { d (signed: + outside, - inside), q (the nearest point), n (its triangle) }
331
677
  const nearest = (p) => {
332
678
  const c = [0, 1, 2].map((a) => Math.floor((p[a] - min[a]) / h));
333
679
  let best = null;
334
- for (let r = 0; r <= far + Math.ceil(Math.max(...[0, 1, 2].map((a) => Math.max(-c[a], c[a] - dims[a] + 1, 0)))); r++) {
335
- for (let i = c[0] - r; i <= c[0] + r; i++) for (let j = c[1] - r; j <= c[1] + r; j++) for (let k = c[2] - r; k <= c[2] + r; k++) {
336
- if (Math.max(Math.abs(i - c[0]), Math.abs(j - c[1]), Math.abs(k - c[2])) !== r) continue; // this ring only
337
- if (i < 0 || j < 0 || k < 0 || i >= dims[0] || j >= dims[1] || k >= dims[2]) continue;
338
- for (const n of grid.get(id(i, j, k)) || []) {
339
- const q = closest(p, tris[n]), d = Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
340
- if (!best || d < best.dist - 1e-12) best = { dist: d, q, n };
341
- }
342
- }
680
+ for (
681
+ let r = 0;
682
+ r <= far + Math.ceil(Math.max(...[0, 1, 2].map((a) => Math.max(-c[a], c[a] - dims[a] + 1, 0))));
683
+ r++
684
+ ) {
685
+ for (let i = c[0] - r; i <= c[0] + r; i++)
686
+ for (let j = c[1] - r; j <= c[1] + r; j++)
687
+ for (let k = c[2] - r; k <= c[2] + r; k++) {
688
+ if (Math.max(Math.abs(i - c[0]), Math.abs(j - c[1]), Math.abs(k - c[2])) !== r) continue; // this ring only
689
+ if (i < 0 || j < 0 || k < 0 || i >= dims[0] || j >= dims[1] || k >= dims[2]) continue;
690
+ for (const n of grid.get(id(i, j, k)) || []) {
691
+ const q = closest(p, tris[n]),
692
+ d = Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
693
+ if (!best || d < best.dist - 1e-12) best = { dist: d, q, n };
694
+ }
695
+ }
343
696
  // Anything in a farther ring is at least r × h away (less the distance from p to its cell's edge)
344
697
  if (best && best.dist <= r * h) break;
345
698
  }
346
699
  if (!best) return null;
347
- const v = sub(p, best.q), nn = normals[best.n];
700
+ const v = sub(p, best.q),
701
+ nn = normals[best.n];
348
702
  let sign = Math.sign(v[0] * nn[0] + v[1] * nn[1] + v[2] * nn[2]);
349
- if (best.dist > 1e-9 && Math.abs(v[0] * nn[0] + v[1] * nn[1] + v[2] * nn[2]) < best.dist * 0.5) sign = pseudoSign(p, best, (grid.get(id(...[0, 1, 2].map((a) => cell(best.q[a], a)))) || []).map((n) => tris[n]), (grid.get(id(...[0, 1, 2].map((a) => cell(best.q[a], a)))) || []).map((n) => normals[n])); // near an edge: ask the neighbours
703
+ if (best.dist > 1e-9 && Math.abs(v[0] * nn[0] + v[1] * nn[1] + v[2] * nn[2]) < best.dist * 0.5)
704
+ sign = pseudoSign(
705
+ p,
706
+ best,
707
+ (grid.get(id(...[0, 1, 2].map((a) => cell(best.q[a], a)))) || []).map((n) => tris[n]),
708
+ (grid.get(id(...[0, 1, 2].map((a) => cell(best.q[a], a)))) || []).map((n) => normals[n]),
709
+ ); // near an edge: ask the neighbours
350
710
  return { d: (sign || 1) * best.dist, q: best.q, n: best.n };
351
711
  };
352
712
  return { nearest, normals };
@@ -354,47 +714,77 @@ export function surface(tris) {
354
714
  const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
355
715
  // At an edge or corner the nearest face's normal can point either way: average the normals of the faces that share the
356
716
  // nearest point
357
- function pseudoSign(p, best, tris, normals) { // tris and normals: the faces near the nearest point
358
- const q = best.q, v = sub(p, q), acc = [0, 0, 0];
359
- tris.forEach((t, n) => { if (Math.hypot(...sub(closest(q, t), q)) < 1e-6) for (let a = 0; a < 3; a++) acc[a] += normals[n][a]; });
717
+ function pseudoSign(p, best, tris, normals) {
718
+ // tris and normals: the faces near the nearest point
719
+ const q = best.q,
720
+ v = sub(p, q),
721
+ acc = [0, 0, 0];
722
+ tris.forEach((t, n) => {
723
+ if (Math.hypot(...sub(closest(q, t), q)) < 1e-6) for (let a = 0; a < 3; a++) acc[a] += normals[n][a];
724
+ });
360
725
  return Math.sign(v[0] * acc[0] + v[1] * acc[1] + v[2] * acc[2]);
361
726
  }
362
727
 
363
728
  // The point of triangle t nearest p (Ericson, Real-Time Collision Detection, 5.1.5)
364
729
  export function closest(p, [a, b, c]) {
365
- const ab = sub(b, a), ac = sub(c, a), ap = sub(p, a), dot = (x, y) => x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
730
+ const ab = sub(b, a),
731
+ ac = sub(c, a),
732
+ ap = sub(p, a),
733
+ dot = (x, y) => x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
366
734
  const at = (s, t) => [a[0] + ab[0] * s + ac[0] * t, a[1] + ab[1] * s + ac[1] * t, a[2] + ab[2] * s + ac[2] * t];
367
- const d1 = dot(ab, ap), d2 = dot(ac, ap);
735
+ const d1 = dot(ab, ap),
736
+ d2 = dot(ac, ap);
368
737
  if (d1 <= 0 && d2 <= 0) return a;
369
- const bp = sub(p, b), d3 = dot(ab, bp), d4 = dot(ac, bp);
738
+ const bp = sub(p, b),
739
+ d3 = dot(ab, bp),
740
+ d4 = dot(ac, bp);
370
741
  if (d3 >= 0 && d4 <= d3) return b;
371
742
  const vc = d1 * d4 - d3 * d2;
372
743
  if (vc <= 0 && d1 >= 0 && d3 <= 0) return at(d1 / (d1 - d3), 0);
373
- const cp = sub(p, c), d5 = dot(ab, cp), d6 = dot(ac, cp);
744
+ const cp = sub(p, c),
745
+ d5 = dot(ab, cp),
746
+ d6 = dot(ac, cp);
374
747
  if (d6 >= 0 && d5 <= d6) return c;
375
748
  const vb = d5 * d2 - d1 * d6;
376
749
  if (vb <= 0 && d2 >= 0 && d6 <= 0) return at(0, d2 / (d2 - d6));
377
750
  const va = d3 * d6 - d5 * d4;
378
- if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { const w = (d4 - d3) / (d4 - d3 + (d5 - d6)); return [b[0] + (c[0] - b[0]) * w, b[1] + (c[1] - b[1]) * w, b[2] + (c[2] - b[2]) * w]; }
751
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
752
+ const w = (d4 - d3) / (d4 - d3 + (d5 - d6));
753
+ return [b[0] + (c[0] - b[0]) * w, b[1] + (c[1] - b[1]) * w, b[2] + (c[2] - b[2]) * w];
754
+ }
379
755
  const den = 1 / (va + vb + vc);
380
756
  return at(vb * den, vc * den);
381
757
  }
382
758
 
383
759
  // Points spread evenly over a surface, by area; the same points every run (a fixed seed)
384
760
  export function sample(tris, n) {
385
- const areas = tris.map(([a, b, c]) => { const u = sub(b, a), v = sub(c, a); return Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) / 2; });
386
- const total = areas.reduce((s, x) => s + x, 0), cum = [];
761
+ const areas = tris.map(([a, b, c]) => {
762
+ const u = sub(b, a),
763
+ v = sub(c, a);
764
+ return Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) / 2;
765
+ });
766
+ const total = areas.reduce((s, x) => s + x, 0),
767
+ cum = [];
387
768
  areas.reduce((s, x, i) => (cum[i] = s + x), 0);
388
769
  let seed = 12345;
389
- const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
770
+ const rnd = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648;
390
771
  const out = [];
391
772
  for (let i = 0; i < n; i++) {
392
773
  const r = rnd() * total;
393
- let lo = 0, hi = cum.length - 1;
394
- while (lo < hi) { const m = (lo + hi) >> 1; if (cum[m] < r) lo = m + 1; else hi = m; }
774
+ let lo = 0,
775
+ hi = cum.length - 1;
776
+ while (lo < hi) {
777
+ const m = (lo + hi) >> 1;
778
+ if (cum[m] < r) lo = m + 1;
779
+ else hi = m;
780
+ }
395
781
  const [a, b, c] = tris[lo];
396
- let s = rnd(), t = rnd();
397
- if (s + t > 1) { s = 1 - s; t = 1 - t; }
782
+ let s = rnd(),
783
+ t = rnd();
784
+ if (s + t > 1) {
785
+ s = 1 - s;
786
+ t = 1 - t;
787
+ }
398
788
  out.push([0, 1, 2].map((k) => a[k] + (b[k] - a[k]) * s + (c[k] - a[k]) * t));
399
789
  }
400
790
  return out;
@@ -403,8 +793,13 @@ export function sample(tris, n) {
403
793
  // Lay `moving` over `fixed`: try the quarter turns whose bounding box matches best, centre them, then shift by the mean
404
794
  // offset to the nearest points a few times. Returns { name, M, shift, score (mean distance) }.
405
795
  export function align(moving, fixed, { samples = 1500 } = {}) {
406
- const F = bounds(fixed), S = surface(fixed), centre = (b) => b.min.map((m, a) => (m + b.max[a]) / 2);
407
- const tried = turns.map((t) => { const b = bounds(turn(moving, t.M)); return { ...t, b, fit: b.size.reduce((s, x, a) => s + Math.abs(x - F.size[a]), 0) }; });
796
+ const F = bounds(fixed),
797
+ S = surface(fixed),
798
+ centre = (b) => b.min.map((m, a) => (m + b.max[a]) / 2);
799
+ const tried = turns.map((t) => {
800
+ const b = bounds(turn(moving, t.M));
801
+ return { ...t, b, fit: b.size.reduce((s, x, a) => s + Math.abs(x - F.size[a]), 0) };
802
+ });
408
803
  const bestFit = Math.min(...tried.map((t) => t.fit));
409
804
  const results = [];
410
805
  for (const t of tried.filter((x) => x.fit <= bestFit + 0.5)) {
@@ -414,7 +809,12 @@ export function align(moving, fixed, { samples = 1500 } = {}) {
414
809
  for (let it = 0; it < 10; it++) {
415
810
  const off = [0, 0, 0];
416
811
  let sum = 0;
417
- for (const p of pts) { const q = [p[0] + shift[0], p[1] + shift[1], p[2] + shift[2]], n = S.nearest(q); sum += Math.abs(n.d); for (let a = 0; a < 3; a++) off[a] += n.q[a] - q[a]; }
812
+ for (const p of pts) {
813
+ const q = [p[0] + shift[0], p[1] + shift[1], p[2] + shift[2]],
814
+ n = S.nearest(q);
815
+ sum += Math.abs(n.d);
816
+ for (let a = 0; a < 3; a++) off[a] += n.q[a] - q[a];
817
+ }
418
818
  score = sum / pts.length;
419
819
  const step = off.map((x) => x / pts.length);
420
820
  shift = shift.map((x, a) => x + step[a]);
@@ -442,10 +842,17 @@ export function worst(points, { count = 5, apart = 3 } = {}) {
442
842
  }
443
843
 
444
844
  export function stats(points) {
445
- const a = points.map((x) => Math.abs(x.d)).sort((p, q) => p - q), n = a.length;
845
+ const a = points.map((x) => Math.abs(x.d)).sort((p, q) => p - q),
846
+ n = a.length;
446
847
  const pct = (f) => a[Math.min(n - 1, Math.floor(f * n))];
447
- return { max: a[n - 1], mean: a.reduce((s, x) => s + x, 0) / n, p95: pct(0.95), signed: points.reduce((s, x) => s + x.d, 0) / n };
848
+ return {
849
+ max: a[n - 1],
850
+ mean: a.reduce((s, x) => s + x, 0) / n,
851
+ p95: pct(0.95),
852
+ signed: points.reduce((s, x) => s + x.d, 0) / n,
853
+ };
448
854
  }
449
855
 
450
856
  // Licences that limit what can be made from a model (non-commercial, no derivatives, share-alike)
451
- export const limitingLicence = (s) => /\b(NC|ND|SA)\b|non-?commercial|no-?deriv|share-?alike|share alike/i.test(String(s || ''));
857
+ export const limitingLicence = (s) =>
858
+ /\b(NC|ND|SA)\b|non-?commercial|no-?deriv|share-?alike|share alike/i.test(String(s || ''));