@rulecad/printcheck 0.3.3 → 0.4.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.
package/printcheck.mjs CHANGED
@@ -15,7 +15,8 @@ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a
15
15
  // Area-weighted normal of a planar polygon (its length is twice the area).
16
16
  function areaNormal(poly) {
17
17
  let n = [0, 0, 0];
18
- for (let i = 1; i < poly.length - 1; i++) n = n.map((c, k) => c + cross(sub(poly[i], poly[0]), sub(poly[i + 1], poly[0]))[k]);
18
+ for (let i = 1; i < poly.length - 1; i++)
19
+ n = n.map((c, k) => c + cross(sub(poly[i], poly[0]), sub(poly[i + 1], poly[0]))[k]);
19
20
  return n;
20
21
  }
21
22
 
@@ -38,8 +39,14 @@ const LEDGE_SLACK = (15 * Math.PI) / 180; // a point's supports all within a hal
38
39
  */
39
40
 
40
41
  export function bounds(polys) {
41
- const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; // a loop: spreading big models overflows the stack
42
- for (const p of polys) for (const v of p) for (let k = 0; k < 3; k++) { if (v[k] < lo[k]) lo[k] = v[k]; if (v[k] > hi[k]) hi[k] = v[k]; }
42
+ const lo = [Infinity, Infinity, Infinity],
43
+ hi = [-Infinity, -Infinity, -Infinity]; // a loop: spreading big models overflows the stack
44
+ for (const p of polys)
45
+ for (const v of p)
46
+ for (let k = 0; k < 3; k++) {
47
+ if (v[k] < lo[k]) lo[k] = v[k];
48
+ if (v[k] > hi[k]) hi[k] = v[k];
49
+ }
43
50
  return { lo, hi, size: hi.map((h, k) => h - lo[k]) };
44
51
  }
45
52
 
@@ -55,279 +62,788 @@ export function bounds(polys) {
55
62
  */
56
63
  export function check(polys, printer, { eps = 1e-3, parts = null, slice = true } = {}) {
57
64
  // (a finding's at is a point, the middle of where it is; box is the box round it: one shape across the kit)
58
- const out = [], f = (level, text, code, values, box) => out.push({ level, text, code, ...(values && { values }), ...(box && Number.isFinite(box.lo?.[0]) ? { at: box.lo.map((x, k) => (x + box.hi[k]) / 2), box } : {}) });
65
+ const out = [],
66
+ f = (level, text, code, values, box) =>
67
+ out.push({
68
+ level,
69
+ text,
70
+ code,
71
+ ...(values && { values }),
72
+ ...(box && Number.isFinite(box.lo?.[0]) ? { at: box.lo.map((x, k) => (x + box.hi[k]) / 2), box } : {}),
73
+ });
59
74
  // What can't be checked is said at the door, not found out deep inside
60
- for (const k of ['bed', 'overhang']) if (!(Number(printer?.[k]) > 0)) throw new Error(`check(model, printer): the printer's "${k}" is needed, a number above 0 (got ${JSON.stringify(printer?.[k])}): { bed: 256, overhang: 45, layer: 0.2 }`);
61
- for (const k of ['layer', 'line', 'bridge', 'support_gap']) if (printer[k] != null && !(Number(printer[k]) > 0)) throw new Error(`check(model, printer): the printer's "${k}" must be a number above 0 (got ${JSON.stringify(printer[k])})`);
62
- polys = (Array.isArray(polys) ? polys : []).filter((p) => Array.isArray(p) && p.length >= 3 && p.every((v) => Array.isArray(v) && v.length >= 3 && v.every(Number.isFinite)));
63
- if (!polys.length) return [{ level: 'fail', text: 'nothing to check: the model has no faces (each face is three or more corners, each [x, y, z] in mm)', code: 'print.empty' }];
64
- const solids = (parts || []).filter((p) => p.role !== 'support').map((p) => ({ tris: p.triangles, box: bounds(p.triangles), grid: null }));
75
+ for (const k of ['bed', 'overhang'])
76
+ if (!(Number(printer?.[k]) > 0))
77
+ throw new Error(
78
+ `check(model, printer): the printer's "${k}" is needed, a number above 0 (got ${JSON.stringify(printer?.[k])}): { bed: 256, overhang: 45, layer: 0.2 }`,
79
+ );
80
+ for (const k of ['layer', 'line', 'bridge', 'support_gap'])
81
+ if (printer[k] != null && !(Number(printer[k]) > 0))
82
+ throw new Error(
83
+ `check(model, printer): the printer's "${k}" must be a number above 0 (got ${JSON.stringify(printer[k])})`,
84
+ );
85
+ polys = (Array.isArray(polys) ? polys : []).filter(
86
+ (p) =>
87
+ Array.isArray(p) &&
88
+ p.length >= 3 &&
89
+ p.every((v) => Array.isArray(v) && v.length >= 3 && v.every(Number.isFinite)),
90
+ );
91
+ if (!polys.length)
92
+ return [
93
+ {
94
+ level: 'fail',
95
+ text: 'nothing to check: the model has no faces (each face is three or more corners, each [x, y, z] in mm)',
96
+ code: 'print.empty',
97
+ },
98
+ ];
99
+ const solids = (parts || [])
100
+ .filter((p) => p.role !== 'support')
101
+ .map((p) => ({ tris: p.triangles, box: bounds(p.triangles), grid: null }));
65
102
  // Each part's faces filed by where they lie across the bed, on a grid, so a ray straight up meets only those near it
66
103
  // (a gearbox printed in place has hundreds of thousands of faces: every face against every other is hours)
67
- const CELL = 2, cellKey = (i, j) => `${i},${j}`;
104
+ const CELL = 2,
105
+ cellKey = (i, j) => `${i},${j}`;
68
106
  const gridOf = (s) => {
69
107
  if (s.grid) return s.grid;
70
108
  const g = new Map();
71
109
  for (const t of s.tris) {
72
- let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
73
- for (const v of t) { x0 = Math.min(x0, v[0]); x1 = Math.max(x1, v[0]); y0 = Math.min(y0, v[1]); y1 = Math.max(y1, v[1]); }
74
- for (let i = Math.floor(x0 / CELL); i <= Math.floor(x1 / CELL); i++) for (let j = Math.floor(y0 / CELL); j <= Math.floor(y1 / CELL); j++) { const k = cellKey(i, j); if (!g.has(k)) g.set(k, []); g.get(k).push(t); }
110
+ let x0 = Infinity,
111
+ x1 = -Infinity,
112
+ y0 = Infinity,
113
+ y1 = -Infinity;
114
+ for (const v of t) {
115
+ x0 = Math.min(x0, v[0]);
116
+ x1 = Math.max(x1, v[0]);
117
+ y0 = Math.min(y0, v[1]);
118
+ y1 = Math.max(y1, v[1]);
119
+ }
120
+ for (let i = Math.floor(x0 / CELL); i <= Math.floor(x1 / CELL); i++)
121
+ for (let j = Math.floor(y0 / CELL); j <= Math.floor(y1 / CELL); j++) {
122
+ const k = cellKey(i, j);
123
+ if (!g.has(k)) g.set(k, []);
124
+ g.get(k).push(t);
125
+ }
75
126
  }
76
127
  return (s.grid = g);
77
128
  };
78
129
  // Is the point inside one of the parts? A ray straight up crosses its surface an odd number of times
79
- const inPart = (pt) => solids.length > 1 && solids.some((s) => {
80
- const { box } = s;
81
- if (pt.some((c, k) => c < box.lo[k] - eps || c > box.hi[k] + eps)) return false;
82
- let n = 0;
83
- for (const t of gridOf(s).get(cellKey(Math.floor(pt[0] / CELL), Math.floor(pt[1] / CELL))) || []) for (let i = 1; i < t.length - 1; i++) {
84
- const [a, b, c] = [t[0], t[i], t[i + 1]], d = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
85
- if (Math.abs(d) < 1e-12) continue;
86
- const u = ((pt[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (pt[1] - a[1])) / d, v = ((b[0] - a[0]) * (pt[1] - a[1]) - (pt[0] - a[0]) * (b[1] - a[1])) / d;
87
- if (u < 0 || v < 0 || u + v > 1) continue;
88
- if (a[2] + u * (b[2] - a[2]) + v * (c[2] - a[2]) > pt[2]) n++;
89
- }
90
- return n % 2 === 1;
91
- });
92
- const rests = (p) => { const c = [0, 1, 2].map((k) => p.reduce((s, v) => s + v[k], 0) / p.length); return inPart([c[0] + 1e-4, c[1] + 2e-4, c[2] - printer.layer / 4]); };
130
+ const inPart = (pt) =>
131
+ solids.length > 1 &&
132
+ solids.some((s) => {
133
+ const { box } = s;
134
+ if (pt.some((c, k) => c < box.lo[k] - eps || c > box.hi[k] + eps)) return false;
135
+ let n = 0;
136
+ for (const t of gridOf(s).get(cellKey(Math.floor(pt[0] / CELL), Math.floor(pt[1] / CELL))) || [])
137
+ for (let i = 1; i < t.length - 1; i++) {
138
+ const [a, b, c] = [t[0], t[i], t[i + 1]],
139
+ d = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
140
+ if (Math.abs(d) < 1e-12) continue;
141
+ const u = ((pt[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (pt[1] - a[1])) / d,
142
+ v = ((b[0] - a[0]) * (pt[1] - a[1]) - (pt[0] - a[0]) * (b[1] - a[1])) / d;
143
+ if (u < 0 || v < 0 || u + v > 1) continue;
144
+ if (a[2] + u * (b[2] - a[2]) + v * (c[2] - a[2]) > pt[2]) n++;
145
+ }
146
+ return n % 2 === 1;
147
+ });
148
+ const rests = (p) => {
149
+ const c = [0, 1, 2].map((k) => p.reduce((s, v) => s + v[k], 0) / p.length);
150
+ return inPart([c[0] + 1e-4, c[1] + 2e-4, c[2] - printer.layer / 4]);
151
+ };
93
152
  const { lo, size } = bounds(polys);
94
153
  const mm = (n) => `${Number(n.toFixed(1))}`;
95
154
 
96
155
  const over = size.filter((s) => s > printer.bed);
97
- f(over.length ? 'fail' : 'pass', `${size.map(mm).join(' × ')} mm${over.length ? `: bigger than the ${printer.bed} mm bed` : ', fits the bed'}`, 'print.bed', { size, bed: printer.bed });
156
+ f(
157
+ over.length ? 'fail' : 'pass',
158
+ `${size.map(mm).join(' × ')} mm${over.length ? `: bigger than the ${printer.bed} mm bed` : ', fits the bed'}`,
159
+ 'print.bed',
160
+ { size, bed: printer.bed },
161
+ );
98
162
 
99
163
  // Faces the wrong way round: a closed solid's faces all point out, so the volume they enclose (signed, by the way
100
164
  // their corners run) is positive. Negative, every face points in, and nothing below reads right (the base faces up,
101
165
  // the top faces down): say that, not what follows from it
102
166
  let signed = 0;
103
- for (const p of polys) for (let i = 1; i < p.length - 1; i++) { const [a, b, c] = [p[0], p[i], p[i + 1]]; signed += (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; }
104
- if (signed < -eps) { f('fail', `the faces point inwards (their corners run clockwise seen from outside): the solid is inside out. Reverse every face's corners, or the exporter's winding`, 'print.inside-out', { volume: signed }); return out; }
167
+ for (const p of polys)
168
+ for (let i = 1; i < p.length - 1; i++) {
169
+ const [a, b, c] = [p[0], p[i], p[i + 1]];
170
+ signed +=
171
+ (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])) /
172
+ 6;
173
+ }
174
+ if (signed < -eps) {
175
+ f(
176
+ 'fail',
177
+ `the faces point inwards (their corners run clockwise seen from outside): the solid is inside out. Reverse every face's corners, or the exporter's winding`,
178
+ 'print.inside-out',
179
+ { volume: signed },
180
+ );
181
+ return out;
182
+ }
105
183
 
106
184
  // Flat on the bed: the lowest point is z = 0, and faces there point straight down.
107
- let base = 0, down = 0, support = 0, zs = [];
185
+ let base = 0,
186
+ support = 0,
187
+ zs = [];
108
188
  // Where a finding is: the box round the faces it's about, { lo, hi } (for a reader to point at)
109
189
  const overBox = { lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] };
110
- const grow = (box, p) => { for (const v of p) for (let k = 0; k < 3; k++) { box.lo[k] = Math.min(box.lo[k], v[k]); box.hi[k] = Math.max(box.hi[k], v[k]); } return box; };
111
- const boxOf = (faces) => faces.reduce((box, p) => grow(box, p), { lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] });
112
- const flatDown = [], flatUp = [];
190
+ const grow = (box, p) => {
191
+ for (const v of p)
192
+ for (let k = 0; k < 3; k++) {
193
+ box.lo[k] = Math.min(box.lo[k], v[k]);
194
+ box.hi[k] = Math.max(box.hi[k], v[k]);
195
+ }
196
+ return box;
197
+ };
198
+ const boxOf = (faces) =>
199
+ faces.reduce((box, p) => grow(box, p), {
200
+ lo: [Infinity, Infinity, Infinity],
201
+ hi: [-Infinity, -Infinity, -Infinity],
202
+ });
203
+ const flatDown = [],
204
+ flatUp = [];
113
205
  // A face overhanging past the limit (measured from vertical) points down by more than its sine; half a degree to
114
206
  // spare, since booleans tip a 45° chamfer by hundredths of a degree. (Cosine was used before: the same at 45° only.)
115
207
  const limit = Math.sin(((printer.overhang + OVERHANG_SLACK) * Math.PI) / 180);
116
208
  for (const p of polys) {
117
- const n = areaNormal(p), area = Math.hypot(...n) / 2, nz = n[2] / (2 * area || 1);
209
+ const n = areaNormal(p),
210
+ area = Math.hypot(...n) / 2,
211
+ nz = n[2] / (2 * area || 1);
118
212
  const longest = Math.max(...p.map((v, i) => Math.hypot(...sub(p[(i + 1) % p.length], v))));
119
- if (2 * area / (longest || 1) < HAIRLINE) continue; // a sliver thinner than a hairline (corners nearly in a line, left by a boolean) faces nowhere
120
- const zmin = Math.min(...p.map((v) => v[2])), zmax = Math.max(...p.map((v) => v[2]));
213
+ if ((2 * area) / (longest || 1) < HAIRLINE) continue; // a sliver thinner than a hairline (corners nearly in a line, left by a boolean) faces nowhere
214
+ const zmin = Math.min(...p.map((v) => v[2])),
215
+ zmax = Math.max(...p.map((v) => v[2]));
121
216
  if (nz < -eps && zmax - lo[2] > eps && rests(p)) continue; // on another part (a legend on its keycap)
122
217
  if (nz < -1 + eps && zmax - lo[2] < eps) base += area;
123
- else if (nz < -1 + eps) flatDown.push({ p, z: zmin, area }); // a flat underside above the bed
124
- else if (nz < -limit) { support += area; zs.push(zmin); grow(overBox, p); }
218
+ else if (nz < -1 + eps)
219
+ flatDown.push({ p, z: zmin, area }); // a flat underside above the bed
220
+ else if (nz < -limit) {
221
+ support += area;
222
+ zs.push(zmin);
223
+ grow(overBox, p);
224
+ }
125
225
  if (nz > 1 - eps) flatUp.push({ p, z: zmax });
126
- if (nz < 0) down += area;
127
226
  }
128
- if (Math.abs(lo[2]) > eps) f('fail', `lowest point is at z = ${mm(lo[2])} mm, not on the bed (z = 0)`, 'print.off-bed', { z: lo[2] });
227
+ if (Math.abs(lo[2]) > eps)
228
+ f('fail', `lowest point is at z = ${mm(lo[2])} mm, not on the bed (z = 0)`, 'print.off-bed', { z: lo[2] });
129
229
  if (base <= 0) f('fail', 'nothing sits flat on the bed', 'print.base', { area: base });
130
230
  else if (Math.abs(lo[2]) <= eps) f('pass', `${mm(base)} mm² flat on the bed`, 'print.base', { area: base }); // (off the bed, its flat underside isn't on it: the finding above says so)
131
- const overAt = support > 0.5 ? overBox : null, slicing = printer.layer != null; // sliced below, the layers are what count; the facets are then a note
132
- if (support > 0.5) f(slicing ? 'pass' : 'warn', slicing ? `${mm(support)} mm² of facets lean past ${printer.overhang}° (z ${mm(Math.min(...zs))} to ${mm(Math.max(...zs))} mm); sliced, the layers decide` : `${mm(support)} mm² overhangs past ${printer.overhang}° (z ${mm(Math.min(...zs))} to ${mm(Math.max(...zs))} mm): needs supports or another orientation`, 'print.overhang', { area: support, angle: printer.overhang, z: [Math.min(...zs), Math.max(...zs)] }, overAt);
133
- else f('pass', `no overhangs past ${printer.overhang}°`, 'print.overhang', { area: support, angle: printer.overhang });
231
+ const overAt = support > 0.5 ? overBox : null,
232
+ slicing = printer.layer != null; // sliced below, the layers are what count; the facets are then a note
233
+ // (flat undersides are not sloped overhangs: the bridge, ledge and mid-air checks below judge them, so the tick says
234
+ // only what it measured)
235
+ if (support > 0.5)
236
+ f(
237
+ slicing ? 'info' : 'warn',
238
+ slicing
239
+ ? `${mm(support)} mm² of facets lean past ${printer.overhang}° (z ${mm(Math.min(...zs))} to ${mm(Math.max(...zs))} mm); sliced, the layers decide`
240
+ : `${mm(support)} mm² overhangs past ${printer.overhang}° (z ${mm(Math.min(...zs))} to ${mm(Math.max(...zs))} mm): needs supports or another orientation`,
241
+ 'print.overhang',
242
+ { area: support, angle: printer.overhang, z: [Math.min(...zs), Math.max(...zs)] },
243
+ overAt,
244
+ );
245
+ else
246
+ f(
247
+ 'pass',
248
+ `no sloped overhangs past ${printer.overhang}°; flat undersides are checked on their own`,
249
+ 'print.overhang',
250
+ { area: support, angle: printer.overhang },
251
+ );
134
252
 
135
253
  // Flat undersides: on a breakaway support, or bridged
136
- const gap = printer.support_gap ?? 0.2, inside = (pt, poly) => { // point in the xy footprint of a convex face
137
- let sign = 0;
138
- for (let i = 0; i < poly.length; i++) {
139
- const a = poly[i], b = poly[(i + 1) % poly.length], c = (b[0] - a[0]) * (pt[1] - a[1]) - (b[1] - a[1]) * (pt[0] - a[0]);
140
- if (Math.abs(c) < 1e-9) continue; if (sign && Math.sign(c) !== sign) return false; sign = Math.sign(c);
141
- }
142
- return true;
143
- };
254
+ const gap = printer.support_gap ?? 0.2,
255
+ inside = (pt, poly) => {
256
+ // point in the xy footprint of a convex face
257
+ let sign = 0;
258
+ for (let i = 0; i < poly.length; i++) {
259
+ const a = poly[i],
260
+ b = poly[(i + 1) % poly.length],
261
+ c = (b[0] - a[0]) * (pt[1] - a[1]) - (b[1] - a[1]) * (pt[0] - a[0]);
262
+ if (Math.abs(c) < 1e-9) continue;
263
+ if (sign && Math.sign(c) !== sign) return false;
264
+ sign = Math.sign(c);
265
+ }
266
+ return true;
267
+ };
144
268
  const centroid = (p) => [0, 1].map((k) => p.reduce((s, v) => s + v[k], 0) / p.length);
145
269
  // (a breakaway gap, or two layers: a part printed in place rests on what is two layers under it as it does on the bed)
146
270
  const nearBed = Math.max(gap * 1.5, 2 * (printer.layer ?? 0.2));
147
- const held = flatDown.filter((d) => flatUp.some((u) => d.z - u.z > eps && d.z - u.z <= nearBed + eps && inside(centroid(d.p), u.p)));
148
- if (held.length) f('pass', `${mm(held.reduce((s, d) => s + d.area, 0))} mm² rests on a breakaway support (${mm(gap)} mm gap): snip it off after printing`, 'print.breakaway', { area: held.reduce((s, d) => s + d.area, 0), gap });
271
+ const held = flatDown.filter((d) =>
272
+ flatUp.some((u) => d.z - u.z > eps && d.z - u.z <= nearBed + eps && inside(centroid(d.p), u.p)),
273
+ );
274
+ if (held.length)
275
+ f(
276
+ 'pass',
277
+ `${mm(held.reduce((s, d) => s + d.area, 0))} mm² rests on a breakaway support (${mm(gap)} mm gap): snip it off after printing`,
278
+ 'print.breakaway',
279
+ { area: held.reduce((s, d) => s + d.area, 0), gap },
280
+ );
149
281
  // And the bed is a support too: an underside within a breakaway gap of it (a smoothed base's facets a hair up) is
150
282
  // squashed on to it with the first layer, not printed in the air
151
283
  const onBed = flatDown.filter((d) => !held.includes(d) && d.z - lo[2] <= nearBed + eps);
152
- if (onBed.length) f('pass', `${mm(onBed.reduce((s, d) => s + d.area, 0))} mm² lies within ${mm(nearBed)} mm of the bed: laid down with the first layers`, 'print.bed-near', { area: onBed.reduce((s, d) => s + d.area, 0) });
284
+ if (onBed.length)
285
+ f(
286
+ 'pass',
287
+ `${mm(onBed.reduce((s, d) => s + d.area, 0))} mm² lies within ${mm(nearBed)} mm of the bed: laid down with the first layers`,
288
+ 'print.bed-near',
289
+ { area: onBed.reduce((s, d) => s + d.area, 0) },
290
+ );
153
291
  const levels = new Map();
292
+ // The flat undersides some finding here judges (on a breakaway support, near the bed, or a bridge, ledge or mid-air
293
+ // start): the sliced overhang below leaves the layer just over each of them to that finding. A step of a slope
294
+ // narrower than a line is not among them: the slope it is part of is the sliced overhang's to judge.
295
+ const judged = [...held, ...onBed].map((d) => d.p);
154
296
  // (undersides within a layer of each other are one height: a smoothed surface's facets sit a hair apart)
155
297
  const layerH = printer.layer ?? 0.2;
156
- for (const d of flatDown) if (!held.includes(d) && !onBed.includes(d)) { const k = (Math.round(d.z / layerH) * layerH).toFixed(2); levels.set(k, [...(levels.get(k) || []), d.p]); }
298
+ for (const d of flatDown)
299
+ if (!held.includes(d) && !onBed.includes(d)) {
300
+ const k = (Math.round(d.z / layerH) * layerH).toFixed(2);
301
+ levels.set(k, [...(levels.get(k) || []), d.p]);
302
+ }
157
303
  // A point on a segment (in the plane), within eps; and a segment lying along another, overlapping it
158
- const onSeg = (pt, a, b) => { const dx = b[0] - a[0], dy = b[1] - a[1], l = dx * dx + dy * dy; if (l < eps * eps) return Math.hypot(pt[0] - a[0], pt[1] - a[1]) <= eps; const t = ((pt[0] - a[0]) * dx + (pt[1] - a[1]) * dy) / l; return t >= -eps && t <= 1 + eps && Math.hypot(pt[0] - a[0] - t * dx, pt[1] - a[1] - t * dy) <= eps; };
159
- const along = (a, b, c, d) => { // c–d lies on the line of a–b and overlaps it (an edge matched exactly, or by a part of it: a T-junction)
160
- const dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy); if (l < eps) return false;
161
- if (Math.abs((c[0] - a[0]) * dy - (c[1] - a[1]) * dx) / l > eps || Math.abs((d[0] - a[0]) * dy - (d[1] - a[1]) * dx) / l > eps) return false;
162
- const t0 = ((c[0] - a[0]) * dx + (c[1] - a[1]) * dy) / (l * l), t1 = ((d[0] - a[0]) * dx + (d[1] - a[1]) * dy) / (l * l);
304
+ const onSeg = (pt, a, b, tol = eps) => {
305
+ const dx = b[0] - a[0],
306
+ dy = b[1] - a[1],
307
+ l = dx * dx + dy * dy;
308
+ if (l < tol * tol) return Math.hypot(pt[0] - a[0], pt[1] - a[1]) <= tol;
309
+ const t = ((pt[0] - a[0]) * dx + (pt[1] - a[1]) * dy) / l;
310
+ return t >= -tol && t <= 1 + tol && Math.hypot(pt[0] - a[0] - t * dx, pt[1] - a[1] - t * dy) <= tol;
311
+ };
312
+ const along = (a, b, c, d) => {
313
+ // c–d lies on the line of a–b and overlaps it (an edge matched exactly, or by a part of it: a T-junction)
314
+ const dx = b[0] - a[0],
315
+ dy = b[1] - a[1],
316
+ l = Math.hypot(dx, dy);
317
+ if (l < eps) return false;
318
+ if (
319
+ Math.abs((c[0] - a[0]) * dy - (c[1] - a[1]) * dx) / l > eps ||
320
+ Math.abs((d[0] - a[0]) * dy - (d[1] - a[1]) * dx) / l > eps
321
+ )
322
+ return false;
323
+ const t0 = ((c[0] - a[0]) * dx + (c[1] - a[1]) * dy) / (l * l),
324
+ t1 = ((d[0] - a[0]) * dx + (d[1] - a[1]) * dy) / (l * l);
163
325
  return Math.min(t0, t1) < 1 - eps && Math.max(t0, t1) > eps;
164
326
  };
165
- const bridgeMax = printer.bridge ?? 5, line = printer.line ?? LINE;
327
+ const bridgeMax = printer.bridge ?? 5,
328
+ line = printer.line ?? LINE;
166
329
  // Each underside on its own: the faces at a level joined where they touch, edge to edge or a corner on another's
167
330
  // edge (a T-junction, which a boolean leaves plenty of). Two pockets' ceilings at one height are two bridges, each
168
- // measured to its own held edges, not to the other's across the part
331
+ // measured to its own held edges, not to the other's across the part. (Within a hairline: a sliver face between two
332
+ // faces is left out above, and they still touch across it)
169
333
  const regions = (group) => {
170
- const parent = group.map((_, i) => i), root = (i) => (parent[i] === i ? i : (parent[i] = root(parent[i]))), join = (i, j) => { parent[root(i)] = root(j); };
171
- const cell = 1, cellOf = (v) => `${Math.floor(v[0] / cell)},${Math.floor(v[1] / cell)}`, byCell = new Map();
172
- group.forEach((p, i) => { for (const v of p) { const k = cellOf(v); byCell.set(k, [...(byCell.get(k) || []), [v, i]]); } });
173
- group.forEach((p, i) => p.forEach((a, k) => { // every corner of another face on this edge joins the two
174
- const b = p[(k + 1) % p.length], n = Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / cell) * 2 + 1, seen = new Set();
175
- for (let t = 0; t <= n; t++) {
176
- const q = [a[0] + ((b[0] - a[0]) * t) / n, a[1] + ((b[1] - a[1]) * t) / n], ci = Math.floor(q[0] / cell), cj = Math.floor(q[1] / cell);
177
- for (let di = -1; di <= 1; di++) for (let dj = -1; dj <= 1; dj++) { const key = `${ci + di},${cj + dj}`; if (seen.has(key)) continue; seen.add(key); for (const [v, j] of byCell.get(key) || []) if (j !== i && onSeg(v, a, b)) join(i, j); }
334
+ const tol = Math.max(eps, HAIRLINE);
335
+ const parent = group.map((_, i) => i),
336
+ root = (i) => (parent[i] === i ? i : (parent[i] = root(parent[i]))),
337
+ join = (i, j) => {
338
+ parent[root(i)] = root(j);
339
+ };
340
+ const cell = 1,
341
+ cellOf = (v) => `${Math.floor(v[0] / cell)},${Math.floor(v[1] / cell)}`,
342
+ byCell = new Map();
343
+ group.forEach((p, i) => {
344
+ for (const v of p) {
345
+ const k = cellOf(v);
346
+ byCell.set(k, [...(byCell.get(k) || []), [v, i]]);
178
347
  }
179
- }));
348
+ });
349
+ group.forEach((p, i) =>
350
+ p.forEach((a, k) => {
351
+ // every corner of another face on this edge joins the two
352
+ const b = p[(k + 1) % p.length],
353
+ n = Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / cell) * 2 + 1,
354
+ seen = new Set();
355
+ for (let t = 0; t <= n; t++) {
356
+ const q = [a[0] + ((b[0] - a[0]) * t) / n, a[1] + ((b[1] - a[1]) * t) / n],
357
+ ci = Math.floor(q[0] / cell),
358
+ cj = Math.floor(q[1] / cell);
359
+ for (let di = -1; di <= 1; di++)
360
+ for (let dj = -1; dj <= 1; dj++) {
361
+ const key = `${ci + di},${cj + dj}`;
362
+ if (seen.has(key)) continue;
363
+ seen.add(key);
364
+ for (const [v, j] of byCell.get(key) || []) if (j !== i && onSeg(v, a, b, tol)) join(i, j);
365
+ }
366
+ }
367
+ }),
368
+ );
180
369
  const out = new Map();
181
- group.forEach((p, i) => { const r = root(i); out.set(r, [...(out.get(r) || []), p]); });
370
+ group.forEach((p, i) => {
371
+ const r = root(i);
372
+ out.set(r, [...(out.get(r) || []), p]);
373
+ });
182
374
  return [...out.values()];
183
375
  };
184
376
  // The top edges of walls that reach a level from below: an underside's edge lying along one is held up there
185
- const wallsAt = (z, tol = eps) => polys.filter((p) => Math.min(...p.map((v) => v[2])) < z - tol).flatMap((p) => p.flatMap((a, i) => { const b = p[(i + 1) % p.length]; return Math.abs(a[2] - z) <= tol && Math.abs(b[2] - z) <= tol ? [[a, b]] : []; }));
377
+ const wallsAt = (z, tol = eps) =>
378
+ polys
379
+ .filter((p) => Math.min(...p.map((v) => v[2])) < z - tol)
380
+ .flatMap((p) =>
381
+ p.flatMap((a, i) => {
382
+ const b = p[(i + 1) % p.length];
383
+ return Math.abs(a[2] - z) <= tol && Math.abs(b[2] - z) <= tol ? [[a, b]] : [];
384
+ }),
385
+ );
186
386
  // (a smoothed surface has many small undersides at a height: what starts in mid-air and what hangs as a ledge are
187
387
  // said once per height, with how many and the worst; each bridge on its own)
188
388
  for (const [z, level] of levels) {
189
- const walls = wallsAt(Number(z), layerH / 2 + eps), midAir = [], ledges = []; // (the level's faces lie within half a layer of it)
389
+ const walls = wallsAt(Number(z), layerH / 2 + eps),
390
+ midAir = [],
391
+ ledges = []; // (the level's faces lie within half a layer of it)
190
392
  for (const group of regions(level)) {
191
393
  const at = boxOf(group);
192
394
  if (Math.min(at.hi[0] - at.lo[0], at.hi[1] - at.lo[1]) < line - eps) continue; // a sliver narrower than a print line: the slicer lays nothing there
193
395
  if (widest(group) < line - eps) continue; // no wider than a line anywhere (a step of a slope cut in layers, a chamfer's tread): one layer's overhang, which the perimeter takes in its stride
396
+ judged.push(...group);
194
397
  const held = (a, b) => walls.some(([c, d]) => along(a, b, c, d));
195
398
  const under = flatUp.filter((u) => Number(z) - u.z > eps && Number(z) - u.z <= nearBed + eps).map((u) => u.p); // breakaway supports' tops, and what a part printed in place rests on
196
- const measured = spans(group, held, under), span = measured?.span ?? null, groupArea = group.reduce((s, p) => s + Math.hypot(...areaNormal(p)) / 2, 0);
399
+ const measured = spans(group, held, under, bridgeMax),
400
+ span = measured?.span ?? null,
401
+ groupArea = group.reduce((s, p) => s + Math.hypot(...areaNormal(p)) / 2, 0);
197
402
  if (span == null) midAir.push({ at, area: groupArea });
198
403
  else if (measured.reach > line + eps) ledges.push({ at, reach: measured.reach, where: measured.where });
199
- else if (span > bridgeMax + eps) f('warn', `${mm(span)} mm bridge at z ${mm(Number(z))}: wider than the ${bridgeMax} mm the printer can span, needs supports`, 'print.bridge', { span, max: bridgeMax, z: Number(z) }, at);
200
- else f('pass', `bridge ${mm(span)} mm at z ${mm(Number(z))} (up to ${bridgeMax} mm)`, 'print.bridge', { span, max: bridgeMax, z: Number(z) });
404
+ else if (span > bridgeMax + eps)
405
+ f(
406
+ 'warn',
407
+ `${mm(span)} mm bridge at z ${mm(Number(z))}: wider than the ${bridgeMax} mm the printer can span, needs supports`,
408
+ 'print.bridge',
409
+ { span, max: bridgeMax, z: Number(z) },
410
+ at,
411
+ );
412
+ else
413
+ f('pass', `bridge ${mm(span)} mm at z ${mm(Number(z))} (up to ${bridgeMax} mm)`, 'print.bridge', {
414
+ span,
415
+ max: bridgeMax,
416
+ z: Number(z),
417
+ });
201
418
  }
202
419
  if (midAir.length) {
203
- const biggest = midAir.reduce((m, x) => (x.area > m.area ? x : m)), total = midAir.reduce((s, x) => s + x.area, 0);
204
- f('warn', `${midAir.length === 1 ? 'an underside' : `${midAir.length} undersides (${mm(total)} mm²)`} at z ${mm(Number(z))} start${midAir.length === 1 ? 's' : ''} in mid-air: needs support (or a built-in breakaway support one ${mm(gap)} mm layer below)`, 'print.mid-air', { z: Number(z), count: midAir.length, area: total }, biggest.at);
420
+ const biggest = midAir.reduce((m, x) => (x.area > m.area ? x : m)),
421
+ total = midAir.reduce((s, x) => s + x.area, 0);
422
+ f(
423
+ 'warn',
424
+ `${midAir.length === 1 ? 'an underside' : `${midAir.length} undersides (${mm(total)} mm²)`} at z ${mm(Number(z))} start${midAir.length === 1 ? 's' : ''} in mid-air: needs support (or a built-in breakaway support one ${mm(gap)} mm layer below)`,
425
+ 'print.mid-air',
426
+ { z: Number(z), count: midAir.length, area: total },
427
+ biggest.at,
428
+ );
205
429
  }
206
430
  if (ledges.length) {
207
431
  const worst = ledges.reduce((m, x) => (x.reach > m.reach ? x : m));
208
- f('warn', `${ledges.length === 1 ? 'a ledge' : `${ledges.length} ledges`} at z ${mm(Number(z))} reach${ledges.length === 1 ? 'es' : ''} ${ledges.length === 1 ? '' : 'up to '}${mm(worst.reach)} mm out past what holds ${ledges.length === 1 ? 'it' : 'them'}, held on one side only: ${ledges.length === 1 ? 'it droops' : 'they droop'}. Slant the underside in at 45° to the wall, or support it`, 'print.ledge', { reach: worst.reach, z: Number(z), count: ledges.length, where: worst.where }, worst.at);
432
+ f(
433
+ 'warn',
434
+ `${ledges.length === 1 ? 'a ledge' : `${ledges.length} ledges`} at z ${mm(Number(z))} reach${ledges.length === 1 ? 'es' : ''} ${ledges.length === 1 ? '' : 'up to '}${mm(worst.reach)} mm out past what holds ${ledges.length === 1 ? 'it' : 'them'}, held on one side only: ${ledges.length === 1 ? 'it droops' : 'they droop'}. Slant the underside in at 45° to the wall, or support it`,
435
+ 'print.ledge',
436
+ { reach: worst.reach, z: Number(z), count: ledges.length, where: worst.where },
437
+ worst.at,
438
+ );
209
439
  }
210
440
  }
211
441
 
212
442
  // One piece, and nothing starting in mid-air, part by part (an assembly's parts are apart on purpose)
213
- for (const tris of parts && parts.length > 1 ? parts.filter((p) => p.role !== 'support').map((p) => p.triangles) : [polys]) {
443
+ for (const tris of parts && parts.length > 1
444
+ ? parts.filter((p) => p.role !== 'support').map((p) => p.triangles)
445
+ : [polys]) {
214
446
  const { pieces, tips } = shape(tris, eps, (printer.layer ?? 0.2) / 4);
215
447
  const loose = pieces.slice(1);
216
- if (loose.length) f('warn', `${pieces.length} pieces: ${loose.length} loose from the main one (${loose.length === 1 ? mm(loose[0].volume) : `${mm(Math.min(...loose.map((l) => l.volume)))} to ${mm(Math.max(...loose.map((l) => l.volume)))}`} mm³), which would print as stray bits or fall over`, 'print.pieces', { pieces: pieces.length, loose: loose.map((l) => l.volume) }, loose.reduce((b, l) => grow(grow(b, [l.box.lo]), [l.box.hi]), { lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] }));
448
+ if (loose.length)
449
+ f(
450
+ 'warn',
451
+ `${pieces.length} pieces: ${loose.length} loose from the main one (${loose.length === 1 ? mm(loose[0].volume) : `${mm(Math.min(...loose.map((l) => l.volume)))} to ${mm(Math.max(...loose.map((l) => l.volume)))}`} mm³), which would print as stray bits or fall over`,
452
+ 'print.pieces',
453
+ { pieces: pieces.length, loose: loose.map((l) => l.volume) },
454
+ loose.reduce((b, l) => grow(grow(b, [l.box.lo]), [l.box.hi]), {
455
+ lo: [Infinity, Infinity, Infinity],
456
+ hi: [-Infinity, -Infinity, -Infinity],
457
+ }),
458
+ );
217
459
  else if (pieces.length) f('pass', 'one piece', 'print.pieces', { pieces: 1 });
218
460
  const hanging = tips.filter((t) => t[2] - lo[2] > eps && !rests([t, t, t]));
219
- if (hanging.length) f('warn', `${hanging.length === 1 ? 'a point starts' : `${hanging.length} points start`} in mid-air (z ${mm(Math.min(...hanging.map((t) => t[2])))}${hanging.length > 1 ? ` to ${mm(Math.max(...hanging.map((t) => t[2])))}` : ''} mm): the lowest points of tips hanging down, with nothing below to print on`, 'print.island', { points: hanging }, hanging.reduce((b, t) => grow(b, [t]), { lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] }));
461
+ if (hanging.length)
462
+ f(
463
+ 'warn',
464
+ `${hanging.length === 1 ? 'a point starts' : `${hanging.length} points start`} in mid-air (z ${mm(Math.min(...hanging.map((t) => t[2])))}${hanging.length > 1 ? ` to ${mm(Math.max(...hanging.map((t) => t[2])))}` : ''} mm): the lowest points of tips hanging down, with nothing below to print on`,
465
+ 'print.island',
466
+ { points: hanging },
467
+ hanging.reduce((b, t) => grow(b, [t]), {
468
+ lo: [Infinity, Infinity, Infinity],
469
+ hi: [-Infinity, -Infinity, -Infinity],
470
+ }),
471
+ );
220
472
  else f('pass', 'nothing starts in mid-air', 'print.island', { points: [] });
221
473
  // And as the slicer sees it: every layer against the one below (slice: false leaves this out, the slow part: a page
222
474
  // can check a part at once, then slice it off its own thread)
223
- if (!slice) { f('info', 'not sliced: the layers are checked on their own (islands, the first layer, layer overhang)', 'print.unsliced'); continue; }
475
+ if (!slice) {
476
+ f(
477
+ 'info',
478
+ 'not sliced: the layers are checked on their own (islands, the first layer, layer overhang)',
479
+ 'print.unsliced',
480
+ );
481
+ continue;
482
+ }
224
483
  // (the first layer spreads `foot` each side as it is squashed on to the bed: two parts printed in place must stand
225
484
  // further apart there than the gap that prints apart higher up, or they print as one)
226
485
  const firstGap = printer.foot > 0 && printer.print_gap > 0 ? printer.print_gap + 2 * printer.foot : 0;
227
- const sliced = islands(tris, { layer: printer.layer ?? 0.2, overhang: printer.overhang, line: printer.line ?? LINE, firstGap }), isl = sliced.islands;
486
+ const sliced = islands(tris, {
487
+ layer: printer.layer ?? 0.2,
488
+ overhang: printer.overhang,
489
+ line: printer.line ?? LINE,
490
+ firstGap,
491
+ flats: judged,
492
+ }),
493
+ isl = sliced.islands;
228
494
  // A big part whose first layer is cut up (bars, spokes, a skeleton) has far more edge to lift than a plain footprint
229
495
  // of the same area. A small part (a gear) is allowed its small shapes.
230
- const { lo: lo0, hi: hi0 } = bounds(tris), across = Math.max(hi0[0] - lo0[0], hi0[1] - lo0[1]);
231
- if (across > FIRST_LARGE && sliced.firstSprawl > FIRST_SPRAWL) f('warn', `the first layer's outline is ${mm(sliced.firstSprawl)} times a plain shape's of the same area, on a part ${mm(across)} mm across: edges are where a first layer lifts and curls. Make the footprint smaller and solid, and take material out above the first layer`, 'print.first-layer.sprawl', { sprawl: sliced.firstSprawl });
232
- for (const x of sliced.fused) f('warn', `on the first layer, two parts are about ${mm(x.gap)} mm apart at (${mm(x.at[0])}, ${mm(x.at[1])}): the first layer spreads ${printer.foot} mm each side as it is squashed on, so under ${mm(firstGap)} mm they print as one. Keep them ${mm(firstGap)} mm apart on the bed, or lift one off it`, 'print.first-layer', { gap: x.gap, need: firstGap }, { lo: [x.at[0] - 1, x.at[1] - 1, 0], hi: [x.at[0] + 1, x.at[1] + 1, printer.layer ?? 0.2] });
233
- if (firstGap && !sliced.fused.length) f('pass', `on the first layer, nothing printed in place stands within ${mm(firstGap)} mm of another part (the first layer spreads ${printer.foot} mm each side)`, 'print.first-layer', { need: firstGap });
234
- // Overhang as the printer meets it: layers lying out past the one below, less the flat undersides the bridge check
235
- // judges on their own. The face-by-face measure above counts the surface's facets, which on a smoothed, cell-built
496
+ const { lo: lo0, hi: hi0 } = bounds(tris),
497
+ across = Math.max(hi0[0] - lo0[0], hi0[1] - lo0[1]);
498
+ if (across > FIRST_LARGE && sliced.firstSprawl > FIRST_SPRAWL)
499
+ f(
500
+ 'warn',
501
+ `the first layer's outline is ${mm(sliced.firstSprawl)} times a plain shape's of the same area, on a part ${mm(across)} mm across: edges are where a first layer lifts and curls. Make the footprint smaller and solid, and take material out above the first layer`,
502
+ 'print.first-layer.sprawl',
503
+ { sprawl: sliced.firstSprawl },
504
+ );
505
+ for (const x of sliced.fused)
506
+ f(
507
+ 'warn',
508
+ `on the first layer, two parts are about ${mm(x.gap)} mm apart at (${mm(x.at[0])}, ${mm(x.at[1])}): the first layer spreads ${printer.foot} mm each side as it is squashed on, so under ${mm(firstGap)} mm they print as one. Keep them ${mm(firstGap)} mm apart on the bed, or lift one off it`,
509
+ 'print.first-layer',
510
+ { gap: x.gap, need: firstGap },
511
+ { lo: [x.at[0] - 1, x.at[1] - 1, 0], hi: [x.at[0] + 1, x.at[1] + 1, printer.layer ?? 0.2] },
512
+ );
513
+ if (firstGap && !sliced.fused.length)
514
+ f(
515
+ 'pass',
516
+ `on the first layer, nothing printed in place stands within ${mm(firstGap)} mm of another part (the first layer spreads ${printer.foot} mm each side)`,
517
+ 'print.first-layer',
518
+ { need: firstGap },
519
+ );
520
+ // Overhang as the printer meets it: layers lying out past the one below, but for the pixels right over a flat
521
+ // underside judged above (each layer leaves out only what lies over one of them, so bridges in one place hide
522
+ // nothing elsewhere). The face-by-face measure above counts the surface's facets, which on a smoothed, cell-built
236
523
  // part are steeper than its layers are.
237
- const flatArea = flatDown.reduce((s, d) => s + d.area, 0), out = Math.max(0, sliced.overhang - flatArea);
238
- if (out > 2) f('warn', `${mm(out)} mm² of layers lie out past what the layer below holds at ${printer.overhang}° and a line (sliced at ${printer.layer ?? 0.2} mm): needs supports or another orientation`, 'print.overhang.sliced', { area: out, facets: support }); else f('pass', `every layer lies within ${printer.overhang}° and a line of the one below (sliced at ${printer.layer ?? 0.2} mm)`, 'print.overhang.sliced', { area: out, facets: support });
239
- if (isl.length) f('warn', `${isl.length === 1 ? 'an island' : `${isl.length} islands`} when sliced: ${isl.length === 1 ? `${mm(isl[0].area)} mm² at z ${mm(isl[0].z)}` : `${mm(Math.min(...isl.map((x) => x.area)))} to ${mm(Math.max(...isl.map((x) => x.area)))} mm², z ${mm(Math.min(...isl.map((x) => x.z)))} to ${mm(Math.max(...isl.map((x) => x.z)))}`}: a layer's region with nothing under it within the overhang reach, which the printer lays on air`, 'print.islands', { islands: isl }, isl.reduce((b, x) => grow(b, [x.at]), { lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] }));
240
- else f('pass', `no islands in ${sliced.layers} layers of ${printer.layer ?? 0.2} mm`, 'print.islands', { islands: [] });
524
+ const out = sliced.overhang;
525
+ if (out > 2)
526
+ f(
527
+ 'warn',
528
+ `${mm(out)} mm² of layers lie out past what the layer below holds at ${printer.overhang}° and a line (sliced at ${printer.layer ?? 0.2} mm): needs supports or another orientation`,
529
+ 'print.overhang.sliced',
530
+ { area: out, facets: support },
531
+ );
532
+ else
533
+ f(
534
+ 'pass',
535
+ `every layer lies within ${printer.overhang}° and a line of the one below (sliced at ${printer.layer ?? 0.2} mm; flat undersides are checked on their own)`,
536
+ 'print.overhang.sliced',
537
+ { area: out, facets: support },
538
+ );
539
+ if (isl.length)
540
+ f(
541
+ 'warn',
542
+ `${isl.length === 1 ? 'an island' : `${isl.length} islands`} when sliced: ${isl.length === 1 ? `${mm(isl[0].area)} mm² at z ${mm(isl[0].z)}` : `${mm(Math.min(...isl.map((x) => x.area)))} to ${mm(Math.max(...isl.map((x) => x.area)))} mm², z ${mm(Math.min(...isl.map((x) => x.z)))} to ${mm(Math.max(...isl.map((x) => x.z)))}`}: a layer's region with nothing under it within the overhang reach, which the printer lays on air`,
543
+ 'print.islands',
544
+ { islands: isl },
545
+ isl.reduce((b, x) => grow(b, [x.at]), {
546
+ lo: [Infinity, Infinity, Infinity],
547
+ hi: [-Infinity, -Infinity, -Infinity],
548
+ }),
549
+ );
550
+ else
551
+ f('pass', `no islands in ${sliced.layers} layers of ${printer.layer ?? 0.2} mm`, 'print.islands', {
552
+ islands: [],
553
+ });
241
554
  }
242
555
 
243
556
  // Closed: every edge is matched by an edge running the other way. An edge that meets the middle of a longer edge
244
557
  // (a T-junction, left by booleans) is still closed if the edges along the other side cover it exactly.
245
- const { gaps, tjunctions, hairlines } = parts && parts.length > 1
246
- ? parts.map((p) => seams(p.triangles, eps)).reduce((s, x) => ({ gaps: s.gaps + x.gaps, tjunctions: s.tjunctions + x.tjunctions, hairlines: s.hairlines + x.hairlines }), { gaps: 0, tjunctions: 0, hairlines: 0 })
247
- : seams(polys, eps);
248
- if (gaps) f('warn', `${gaps === 1 ? '1 edge' : `${gaps} edges`} with nothing on the other side: ${gaps === 1 ? 'a hole' : 'holes'} in the surface (slicers may repair ${gaps === 1 ? 'it' : 'them'})`, 'print.closed', { gaps });
249
- else f('pass', `closed solid${tjunctions || hairlines ? ` (${[tjunctions && `${tjunctions} T-junction edges`, hairlines && `${hairlines} hairline seams under ${HAIRLINE} mm`].filter(Boolean).join(', ')}: watertight for printing)` : ''}`, 'print.closed', { gaps, tjunctions, hairlines });
558
+ const { gaps, tjunctions, hairlines } =
559
+ parts && parts.length > 1
560
+ ? parts
561
+ .map((p) => seams(p.triangles, eps))
562
+ .reduce(
563
+ (s, x) => ({
564
+ gaps: s.gaps + x.gaps,
565
+ tjunctions: s.tjunctions + x.tjunctions,
566
+ hairlines: s.hairlines + x.hairlines,
567
+ }),
568
+ { gaps: 0, tjunctions: 0, hairlines: 0 },
569
+ )
570
+ : seams(polys, eps);
571
+ if (gaps)
572
+ f(
573
+ 'warn',
574
+ `${gaps === 1 ? '1 edge' : `${gaps} edges`} with nothing on the other side: ${gaps === 1 ? 'a hole' : 'holes'} in the surface (slicers may repair ${gaps === 1 ? 'it' : 'them'})`,
575
+ 'print.closed',
576
+ { gaps },
577
+ );
578
+ else
579
+ f(
580
+ 'pass',
581
+ `closed solid${tjunctions || hairlines ? ` (${[tjunctions && `${tjunctions} T-junction edges`, hairlines && `${hairlines} hairline seams under ${HAIRLINE} mm`].filter(Boolean).join(', ')}: watertight for printing)` : ''}`,
582
+ 'print.closed',
583
+ { gaps, tjunctions, hairlines },
584
+ );
585
+ // No tick for a measure a finding here contradicts: "no overhangs" above a ledge that droops, or an underside that
586
+ // starts in mid-air, reads as a pass to someone scanning for crosses. Those ticks become notes.
587
+ // (and the faces' "no sloped overhangs" beside layers that lie out past the limit: a staircase of treads each
588
+ // narrower than a line has no sloped face, yet leans as a slope does)
589
+ const needs = out.filter((x) => x.level !== 'pass' && x.level !== 'info' && SUPPORT_NEEDED.has(x.code)),
590
+ leans = out.some((x) => x.code === 'print.overhang.sliced' && x.level === 'warn');
591
+ if (needs.length || leans)
592
+ for (const x of out)
593
+ if (x.level === 'pass' && (x.code === 'print.overhang' || (needs.length && x.code === 'print.overhang.sliced'))) {
594
+ x.level = 'info';
595
+ x.text = `${x.text.replace(/;? ?flat undersides are checked on their own/, '')}, but another finding here says part of it needs support`;
596
+ }
250
597
  return out;
251
598
  }
599
+ // The findings that say part of a print hangs on nothing: an overhang tick beside one of them is no tick
600
+ const SUPPORT_NEEDED = new Set(['print.ledge', 'print.mid-air', 'print.bridge', 'print.islands', 'print.island']);
252
601
 
253
602
  // The widest circle that fits in a flat region made of faces, measured to the outline edges that are held up
254
603
  // (held(a, b) -> true), or to the tops of breakaway supports one layer below (under: faces): its diameter in mm, the
255
604
  // gap a bridge has to span. null if nothing holds it up.
256
605
  // Sampled: points spread over each face, each measured to the held edges of the region's outline and to the supports.
257
606
  // A point with support on one side only (nothing held beyond it, away from its nearest held edge) is on a ledge, not
258
- // a bridge: `ledges(polys, held, under)` gives how far the longest reaches.
607
+ // a bridge: `ledges(polys, held, under)` gives how far the longest reaches. The edge of a hole in it that nothing
608
+ // holds is a ledge too, unless the underside taken whole, the hole filled in, is a bridge within `bridge` mm.
259
609
  /**
260
610
  * The widest circle that fits in an underside, measured to its held-up edges (the bridge it makes).
261
611
  * @param {Face[]} polys @param {(edge: [Point, Point]) => boolean} [held] @param {Face[]} [under]
612
+ * @param {number} [bridge] the longest bridge the printer spans, mm (5): an underside with a hole in it that is no wider, hole and all, is a bridge
262
613
  * @returns {number} mm
263
614
  */
264
- export function widest(polys, held = () => true, under = []) { return spans(polys, held, under)?.span ?? null; }
615
+ export function widest(polys, held = () => true, under = [], bridge = 5) {
616
+ return spans(polys, held, under, bridge)?.span ?? null;
617
+ }
265
618
  /**
266
619
  * How far an underside reaches out past its last support, held on one side only (a ledge in the air): mm, 0 if it is
267
620
  * held on both sides everywhere (a bridge), null if nothing holds it.
268
621
  * @param {Face[]} polys @param {(edge: [Point, Point]) => boolean} [held] @param {Face[]} [under]
622
+ * @param {number} [bridge] the longest bridge the printer spans, mm (5): an underside with a hole in it that is no wider, hole and all, is a bridge
269
623
  * @returns {number | null} mm
270
624
  */
271
- export function ledges(polys, held = () => true, under = []) { return spans(polys, held, under)?.reach ?? null; }
625
+ export function ledges(polys, held = () => true, under = [], bridge = 5) {
626
+ return spans(polys, held, under, bridge)?.reach ?? null;
627
+ }
272
628
 
273
- function spans(polys, held, under) {
274
- const key = (v) => `${v[0].toFixed(3)},${v[1].toFixed(3)}`, count = new Map(), edges = [];
275
- for (const p of polys) p.forEach((a, i) => { const b = p[(i + 1) % p.length], k = [key(a), key(b)].sort().join('|'); count.set(k, (count.get(k) || 0) + 1); edges.push([k, a, b]); });
276
- const outline = edges.filter(([k]) => count.get(k) === 1).map(([, a, b]) => [a, b]).filter(([a, b]) => held(a, b));
629
+ function spans(polys, held, under, bridge = 5) {
630
+ const key = (v) => `${v[0].toFixed(3)},${v[1].toFixed(3)}`,
631
+ count = new Map(),
632
+ edges = [];
633
+ for (const p of polys)
634
+ p.forEach((a, i) => {
635
+ const b = p[(i + 1) % p.length],
636
+ k = [key(a), key(b)].sort().join('|');
637
+ count.set(k, (count.get(k) || 0) + 1);
638
+ edges.push([k, a, b]);
639
+ });
640
+ const outline = edges
641
+ .filter(([k]) => count.get(k) === 1)
642
+ .map(([, a, b]) => [a, b])
643
+ .filter(([a, b]) => held(a, b));
277
644
  const tops = under.flatMap((p) => p.map((a, i) => [a, p[(i + 1) % p.length]]));
278
645
  if (!outline.length && !tops.length) return null;
279
- const onTop = (pt) => under.some((p) => { let sign = 0; for (let i = 0; i < p.length; i++) { const a = p[i], b = p[(i + 1) % p.length], c = (b[0] - a[0]) * (pt[1] - a[1]) - (b[1] - a[1]) * (pt[0] - a[0]); if (Math.abs(c) < 1e-9) continue; if (sign && Math.sign(c) !== sign) return false; sign = Math.sign(c); } return true; });
280
- const nearest = (pt, [a, b]) => { // the segment's closest point to pt, and how far
281
- const dx = b[0] - a[0], dy = b[1] - a[1], l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((pt[0] - a[0]) * dx + (pt[1] - a[1]) * dy) / l)) : 0, c = [a[0] + t * dx, a[1] + t * dy];
646
+ const onTop = (pt) =>
647
+ under.some((p) => {
648
+ let sign = 0;
649
+ for (let i = 0; i < p.length; i++) {
650
+ const a = p[i],
651
+ b = p[(i + 1) % p.length],
652
+ c = (b[0] - a[0]) * (pt[1] - a[1]) - (b[1] - a[1]) * (pt[0] - a[0]);
653
+ if (Math.abs(c) < 1e-9) continue;
654
+ if (sign && Math.sign(c) !== sign) return false;
655
+ sign = Math.sign(c);
656
+ }
657
+ return true;
658
+ });
659
+ const nearest = (pt, [a, b]) => {
660
+ // the segment's closest point to pt, and how far
661
+ const dx = b[0] - a[0],
662
+ dy = b[1] - a[1],
663
+ l = dx * dx + dy * dy,
664
+ t = l ? Math.max(0, Math.min(1, ((pt[0] - a[0]) * dx + (pt[1] - a[1]) * dy) / l)) : 0,
665
+ c = [a[0] + t * dx, a[1] + t * dy];
282
666
  return { c, d: Math.hypot(pt[0] - c[0], pt[1] - c[1]) };
283
667
  };
284
668
  const supports = [...outline, ...tops];
285
- let best = 0, reach = 0, where = null;
669
+ let best = 0,
670
+ reach = 0,
671
+ where = null;
286
672
  const N = 6;
287
- for (const p of polys) for (let i = 1; i < p.length - 1; i++) {
288
- const [a, b, c] = [p[0], p[i], p[i + 1]];
289
- for (let u = 0; u <= N; u++) for (let v = 0; u + v <= N; v++) {
290
- const w = N - u - v, pt = [0, 1].map((k) => (a[k] * u + b[k] * v + c[k] * w) / N);
291
- if (onTop(pt)) continue; // right over a support
292
- const near = supports.map((s) => nearest(pt, s)), first = near.reduce((m, x) => (x.d < m.d ? x : m));
293
- best = Math.max(best, first.d);
294
- // Held round it, or on one side only? The directions to its supports: all within one half-plane (a gap of more
295
- // than a half turn between them) and it hangs out past the last of them, a ledge reaching first.d; supports
296
- // on opposing sides, and a line between two of them crosses it: a bridge
297
- if (first.d > 1e-9) {
298
- const angles = near.filter((x) => x.d > 1e-9).map((x) => Math.atan2(x.c[1] - pt[1], x.c[0] - pt[0])).sort((a, b) => a - b);
299
- let gap = angles.length ? angles[0] + 2 * Math.PI - angles.at(-1) : 2 * Math.PI;
300
- for (let k = 1; k < angles.length; k++) gap = Math.max(gap, angles[k] - angles[k - 1]);
301
- // (a bridge between two supports nearly opposite each other, a strap from a wall to a post, leaves a gap a few
302
- // degrees over a half turn where the post's nearest point is off its line: some slack, LEDGE_SLACK, before it
303
- // counts as a ledge)
304
- if (gap > Math.PI + LEDGE_SLACK && first.d > reach) { reach = first.d; where = pt; }
305
- }
673
+ for (const p of polys)
674
+ for (let i = 1; i < p.length - 1; i++) {
675
+ const [a, b, c] = [p[0], p[i], p[i + 1]];
676
+ for (let u = 0; u <= N; u++)
677
+ for (let v = 0; u + v <= N; v++) {
678
+ const w = N - u - v,
679
+ pt = [0, 1].map((k) => (a[k] * u + b[k] * v + c[k] * w) / N);
680
+ if (onTop(pt)) continue; // right over a support
681
+ const near = supports.map((s) => nearest(pt, s)),
682
+ first = near.reduce((m, x) => (x.d < m.d ? x : m));
683
+ best = Math.max(best, first.d);
684
+ // Held round it, or on one side only? The directions to its supports: all within one half-plane (a gap of more
685
+ // than a half turn between them) and it hangs out past the last of them, a ledge reaching first.d; supports
686
+ // on opposing sides, and a line between two of them crosses it: a bridge
687
+ if (first.d > 1e-9) {
688
+ const angles = near
689
+ .filter((x) => x.d > 1e-9)
690
+ .map((x) => Math.atan2(x.c[1] - pt[1], x.c[0] - pt[0]))
691
+ .sort((a, b) => a - b);
692
+ let gap = angles.length ? angles[0] + 2 * Math.PI - angles.at(-1) : 2 * Math.PI;
693
+ for (let k = 1; k < angles.length; k++) gap = Math.max(gap, angles[k] - angles[k - 1]);
694
+ // (a bridge between two supports nearly opposite each other, a strap from a wall to a post, leaves a gap a few
695
+ // degrees over a half turn where the post's nearest point is off its line: some slack, LEDGE_SLACK, before it
696
+ // counts as a ledge)
697
+ if (gap > Math.PI + LEDGE_SLACK && first.d > reach) {
698
+ reach = first.d;
699
+ where = pt;
700
+ }
701
+ }
702
+ }
306
703
  }
704
+ // A hole in the underside whose edge nothing holds (a counterbore opening on the bed: the ring round the screw's hole
705
+ // is held at its outside only). From a point on that edge the held edges lie all round, so it passes the test above
706
+ // as a bridge, measured across the hole; but no line is laid across a hole. Taken whole, hole and all, the seat is
707
+ // either a bridge (a nut slot's roof with the screw's hole up through it: lines run wall to wall across it, past the
708
+ // hole), measured by its own width, or it is not, and then the line round the hole hangs out from the nearest
709
+ // support: a ledge reaching as far (as wide as the ring, round a counterbore).
710
+ const holes = freeHoles(polys, edges, count, held);
711
+ if (holes.length) {
712
+ const reachOf = (pt) => (onTop(pt) ? 0 : Math.min(...supports.map((s) => nearest(pt, s).d)));
713
+ // The widest circle in the seat with its holes filled in: measured at the middle of the hole straight across from
714
+ // each edge, and half-way to it (each edge on its own, so a hole whose outline a boolean left in pieces is still
715
+ // measured across its middle)
716
+ let whole = best;
717
+ for (const { m, across } of holes)
718
+ whole = Math.max(whole, reachOf(across), reachOf([(m[0] + across[0]) / 2, (m[1] + across[1]) / 2]));
719
+ if (2 * whole <= bridge + 1e-3) best = whole;
720
+ else
721
+ for (const { a, b } of holes) {
722
+ const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 0.5));
723
+ for (let t = 0; t <= n; t++) {
724
+ const pt = [a[0] + ((b[0] - a[0]) * t) / n, a[1] + ((b[1] - a[1]) * t) / n],
725
+ d = reachOf(pt);
726
+ if (d > reach) {
727
+ reach = d;
728
+ where = pt;
729
+ }
730
+ }
731
+ }
307
732
  }
308
733
  return { span: 2 * best, reach, where };
309
734
  }
310
735
 
736
+ // The edges of holes in an underside that nothing holds: each { a, b, m, across }, its ends, its middle, and the middle
737
+ // of the hole straight across from it. An edge with the underside on one side of it only is on the outline (one with it
738
+ // on both is a T-junction inside it, which booleans leave); the other side is in a hole when every way out from there
739
+ // runs into the underside again (eight ways, an eighth of a turn apart), and outside it when one gets away. A gap
740
+ // narrower than a print line across is one the slicer closes over (a crack), not a hole.
741
+ function freeHoles(polys, edges, count, held) {
742
+ const candidates = edges.filter(([k]) => count.get(k) === 1).map(([, a, b]) => [a, b]);
743
+ if (candidates.length < 3 || candidates.every(([a, b]) => held(a, b))) return [];
744
+ const inFace = (pt) =>
745
+ polys.some((p) => {
746
+ // within a face of the underside, seen from above
747
+ let sign = 0;
748
+ for (let i = 0; i < p.length; i++) {
749
+ const a = p[i],
750
+ b = p[(i + 1) % p.length],
751
+ c = (b[0] - a[0]) * (pt[1] - a[1]) - (b[1] - a[1]) * (pt[0] - a[0]);
752
+ if (Math.abs(c) < 1e-12) continue;
753
+ if (sign && Math.sign(c) !== sign) return false;
754
+ sign = Math.sign(c);
755
+ }
756
+ return true;
757
+ });
758
+ const d = 2e-3,
759
+ outline = [];
760
+ for (const [a, b] of candidates) {
761
+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]);
762
+ if (len < 1e-6) continue;
763
+ const m = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2],
764
+ n = [-(b[1] - a[1]) / len, (b[0] - a[0]) / len];
765
+ const left = inFace([m[0] + n[0] * d, m[1] + n[1] * d]),
766
+ right = inFace([m[0] - n[0] * d, m[1] - n[1] * d]);
767
+ if (left === right) continue; // inside the underside (a T-junction), or a sliver
768
+ outline.push({ a, b, m, out: left ? [-n[0], -n[1]] : n, held: held(a, b), len });
769
+ }
770
+ const hit = (q, [dx, dy]) => {
771
+ // how far a ray from q runs before it meets the outline (Infinity: it gets away)
772
+ let best = Infinity;
773
+ for (const { a, b } of outline) {
774
+ const ex = b[0] - a[0],
775
+ ey = b[1] - a[1],
776
+ den = dx * ey - dy * ex;
777
+ if (Math.abs(den) < 1e-12) continue;
778
+ const wx = a[0] - q[0],
779
+ wy = a[1] - q[1],
780
+ t = (wx * ey - wy * ex) / den,
781
+ u = (wx * dy - wy * dx) / den;
782
+ if (t > 1e-9 && u >= -1e-9 && u <= 1 + 1e-9 && t < best) best = t;
783
+ }
784
+ return best;
785
+ };
786
+ const free = [];
787
+ for (const e of outline) {
788
+ if (e.held) continue;
789
+ const o = e.out,
790
+ q = [e.m[0] + o[0] * d, e.m[1] + o[1] * d],
791
+ across = hit(q, o);
792
+ if (across < LINE) continue; // a crack, not a hole
793
+ let enclosed = across < Infinity;
794
+ for (let k = 1; k < 8 && enclosed; k++) {
795
+ const t = (k * Math.PI) / 4,
796
+ c = Math.cos(t),
797
+ s = Math.sin(t);
798
+ if (hit(q, [o[0] * c - o[1] * s, o[0] * s + o[1] * c]) === Infinity) enclosed = false;
799
+ }
800
+ if (enclosed)
801
+ free.push({ a: e.a, b: e.b, m: e.m, across: [q[0] + (o[0] * across) / 2, q[1] + (o[1] * across) / 2] });
802
+ }
803
+ return free;
804
+ }
805
+
311
806
  // seams(polys) -> { gaps, tjunctions, hairlines }: edges not matched by a reverse edge, split into T-junctions (covered
312
807
  // all along by reverse edges on the same line, or lying along a longer reverse edge), hairlines (within HAIRLINE of
313
808
  // another face) and real gaps.
314
- const FIRST_LARGE = 80, FIRST_SPRAWL = 8; // mm, and times a circle's outline: a part over 80 mm across whose first layer has eight times the edge a plain shape would
809
+ const FIRST_LARGE = 80,
810
+ FIRST_SPRAWL = 8; // mm, and times a circle's outline: a part over 80 mm across whose first layer has eight times the edge a plain shape would
315
811
  export const HAIRLINE = 0.01; // mm: a fortieth of a print line
316
- const vsub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], vdot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
317
- function pointToTriangle(p, a, b, c) { // Ericson, Real-Time Collision Detection 5.1.5
318
- const ab = vsub(b, a), ac = vsub(c, a), ap = vsub(p, a), d1 = vdot(ab, ap), d2 = vdot(ac, ap);
319
- const at = (q) => Math.hypot(...vsub(p, q)), mix = (u, v, w) => [0, 1, 2].map((k) => a[k] * u + b[k] * v + c[k] * w);
812
+ const vsub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
813
+ vdot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
814
+ function pointToTriangle(p, a, b, c) {
815
+ // Ericson, Real-Time Collision Detection 5.1.5
816
+ const ab = vsub(b, a),
817
+ ac = vsub(c, a),
818
+ ap = vsub(p, a),
819
+ d1 = vdot(ab, ap),
820
+ d2 = vdot(ac, ap);
821
+ const at = (q) => Math.hypot(...vsub(p, q)),
822
+ mix = (u, v, w) => [0, 1, 2].map((k) => a[k] * u + b[k] * v + c[k] * w);
320
823
  if (d1 <= 0 && d2 <= 0) return at(a);
321
- const bp = vsub(p, b), d3 = vdot(ab, bp), d4 = vdot(ac, bp);
824
+ const bp = vsub(p, b),
825
+ d3 = vdot(ab, bp),
826
+ d4 = vdot(ac, bp);
322
827
  if (d3 >= 0 && d4 <= d3) return at(b);
323
828
  const vc = d1 * d4 - d3 * d2;
324
- if (vc <= 0 && d1 >= 0 && d3 <= 0) { const v = d1 / (d1 - d3); return at(mix(1 - v, v, 0)); }
325
- const cp = vsub(p, c), d5 = vdot(ab, cp), d6 = vdot(ac, cp);
829
+ if (vc <= 0 && d1 >= 0 && d3 <= 0) {
830
+ const v = d1 / (d1 - d3);
831
+ return at(mix(1 - v, v, 0));
832
+ }
833
+ const cp = vsub(p, c),
834
+ d5 = vdot(ab, cp),
835
+ d6 = vdot(ac, cp);
326
836
  if (d6 >= 0 && d5 <= d6) return at(c);
327
837
  const vb = d5 * d2 - d1 * d6;
328
- if (vb <= 0 && d2 >= 0 && d6 <= 0) { const w = d2 / (d2 - d6); return at(mix(1 - w, 0, w)); }
838
+ if (vb <= 0 && d2 >= 0 && d6 <= 0) {
839
+ const w = d2 / (d2 - d6);
840
+ return at(mix(1 - w, 0, w));
841
+ }
329
842
  const va = d3 * d6 - d5 * d4;
330
- if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { const w = (d4 - d3) / (d4 - d3 + (d5 - d6)); return at(mix(0, 1 - w, w)); }
843
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
844
+ const w = (d4 - d3) / (d4 - d3 + (d5 - d6));
845
+ return at(mix(0, 1 - w, w));
846
+ }
331
847
  const den = 1 / (va + vb + vc);
332
848
  return at(mix(1 - vb * den - vc * den, vb * den, vc * den));
333
849
  }
@@ -337,26 +853,46 @@ function pointToTriangle(p, a, b, c) { // Ericson, Real-Time Collision Detection
337
853
  * @returns {{ gaps: number, tjunctions: number, hairlines: number }}
338
854
  */
339
855
  export function seams(polys, eps = 1e-3) {
340
- const key = (v) => v.map((c) => Math.round(c / eps)).join(','), segs = [], count = new Map();
341
- for (const p of polys) p.forEach((a, i) => { const b = p[(i + 1) % p.length]; if (key(a) !== key(b)) { segs.push([a, b]); const k = `${key(a)}|${key(b)}`; count.set(k, (count.get(k) || 0) + 1); } });
856
+ const key = (v) => v.map((c) => Math.round(c / eps)).join(','),
857
+ segs = [],
858
+ count = new Map();
859
+ for (const p of polys)
860
+ p.forEach((a, i) => {
861
+ const b = p[(i + 1) % p.length];
862
+ if (key(a) !== key(b)) {
863
+ segs.push([a, b]);
864
+ const k = `${key(a)}|${key(b)}`;
865
+ count.set(k, (count.get(k) || 0) + 1);
866
+ }
867
+ });
342
868
  const d = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
343
869
  const on = (p, a, b) => Math.abs(d(a, p) + d(p, b) - d(a, b)) < eps;
344
870
  // A seam whose middle lies within HAIRLINE of another face (not one of its own) is a hairline left by booleans, far
345
871
  // narrower than anything the printer can make: closed, for printing
346
872
  const tris = polys.flatMap((t) => t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]]));
347
873
  const hairline = (a, b) => {
348
- const mid = [0, 1, 2].map((k) => (a[k] + b[k]) / 2), own = (t) => t.some((v) => key(v) === key(a)) && t.some((v) => key(v) === key(b));
874
+ const mid = [0, 1, 2].map((k) => (a[k] + b[k]) / 2),
875
+ own = (t) => t.some((v) => key(v) === key(a)) && t.some((v) => key(v) === key(b));
349
876
  return tris.some((t) => !own(t) && pointToTriangle(mid, ...t) < HAIRLINE);
350
877
  };
351
- let gaps = 0, tjunctions = 0, hairlines = 0;
878
+ let gaps = 0,
879
+ tjunctions = 0,
880
+ hairlines = 0;
352
881
  for (const [a, b] of segs) {
353
882
  if ((count.get(`${key(b)}|${key(a)}`) || 0) > 0) continue;
354
883
  // Reverse pieces on this edge, as stretches of it from b (0) to a (1): together they must cover all of it. They may
355
884
  // overlap (booleans can cut the faces on the other side in more than one way), so it's their union that counts.
356
- const len = d(a, b), along = segs.filter(([x, y]) => on(x, b, a) && on(y, b, a) && d(b, x) < d(b, y)).map(([x, y]) => [d(b, x) / len, d(b, y) / len]).sort((p, q) => p[0] - q[0]);
885
+ const len = d(a, b),
886
+ along = segs
887
+ .filter(([x, y]) => on(x, b, a) && on(y, b, a) && d(b, x) < d(b, y))
888
+ .map(([x, y]) => [d(b, x) / len, d(b, y) / len])
889
+ .sort((p, q) => p[0] - q[0]);
357
890
  let reach = 0;
358
- for (const [from, to] of along) { if (from > reach + eps / len * 10) break; reach = Math.max(reach, to); }
359
- const covered = along.length > 0 && reach >= 1 - eps / len * 10;
891
+ for (const [from, to] of along) {
892
+ if (from > reach + (eps / len) * 10) break;
893
+ reach = Math.max(reach, to);
894
+ }
895
+ const covered = along.length > 0 && reach >= 1 - (eps / len) * 10;
360
896
  const within = segs.some(([x, y]) => on(a, y, x) && on(b, y, x) && d(y, a) < d(y, b) && d(x, y) > d(a, b) + eps); // part of a longer reverse edge
361
897
  if (covered || within) tjunctions++;
362
898
  else if (hairline(a, b)) hairlines++;
@@ -382,37 +918,74 @@ export function seams(polys, eps = 1e-3) {
382
918
  * grid of a quarter of the print line and opened by half a line, so anything narrower than a line (which the slicer
383
919
  * never extrudes) is not a region, and the rest is compared by pixels.
384
920
  * @param {Face[]} polys the closed mesh
385
- * @param {{ layer?: number, overhang?: number, line?: number, onLayer?: (layer: number, layers: number) => void }} printer
386
- * layer height, overhang limit (degrees from vertical), the line width; onLayer: called as each layer is cut (progress)
921
+ * @param {{ layer?: number, overhang?: number, line?: number, firstGap?: number, flats?: Face[], onLayer?: (layer: number, layers: number) => void }} printer
922
+ * layer height, overhang limit (degrees from vertical), the line width; firstGap: how far apart two parts must stand
923
+ * on the first layer; flats: flat undersides judged on their own (bridges, ledges), whose first layer is left out of
924
+ * the overhang, just over each face and nowhere else; onLayer: called as each layer is cut (progress)
387
925
  * @returns {{ islands: { z: number, area: number, at: number[], cells: number[][] }[], layers: number, overhang: number }}
388
926
  * each island's layer (its z), its area (mm²), its centre, and its pixels' centres ([x, y], for whatever fixes it); how
389
- * many layers were cut; and overhang: the area (mm²) of layers lying further out than the one below can hold, flat
390
- * undersides included (the bridge check judges those separately)
927
+ * many layers were cut; and overhang: the area (mm²) of layers lying further out than the one below can hold, but
928
+ * for what lies right over one of the flats
391
929
  */
392
930
  const SPANS = [5, 20]; // layers: the spans a lean is held over (see islands)
393
- export function islands(polys, { layer = 0.2, overhang = 45, line = LINE, firstGap = 0, onLayer } = {}) {
394
- if (!(layer > 0) || !(line > 0) || !(overhang > 0 && overhang < 90)) throw new Error(`islands: layer and line are lengths above 0 and overhang an angle between 0 and 90 (got layer ${layer}, line ${line}, overhang ${overhang})`);
931
+ export function islands(polys, { layer = 0.2, overhang = 45, line = LINE, firstGap = 0, flats = [], onLayer } = {}) {
932
+ if (!(layer > 0) || !(line > 0) || !(overhang > 0 && overhang < 90))
933
+ throw new Error(
934
+ `islands: layer and line are lengths above 0 and overhang an angle between 0 and 90 (got layer ${layer}, line ${line}, overhang ${overhang})`,
935
+ );
395
936
  if (!polys.length) return { islands: [], layers: 0, overhang: 0 };
396
937
  // The pixel: a quarter of a line, or coarser on a big part so a layer stays under about a million pixels
397
- const { lo, hi } = bounds(polys), pitch = Math.max(line / 4, Math.max(hi[0] - lo[0], hi[1] - lo[1]) / 1000), nx = Math.ceil((hi[0] - lo[0]) / pitch) + 6, ny = Math.ceil((hi[1] - lo[1]) / pitch) + 6;
938
+ const { lo, hi } = bounds(polys),
939
+ pitch = Math.max(line / 4, Math.max(hi[0] - lo[0], hi[1] - lo[1]) / 1000),
940
+ nx = Math.ceil((hi[0] - lo[0]) / pitch) + 6,
941
+ ny = Math.ceil((hi[1] - lo[1]) / pitch) + 6;
398
942
  const r2 = Math.max(1, Math.round(line / 2 / pitch)); // half a line, in pixels
399
943
  // Pixels a layer may step out past the one below: its height times the tangent of the limit (measured from upright,
400
944
  // so a wall leaning 45° steps out one layer's height each layer), and a line beyond that: a line hanging out is held
401
945
  // by the one beside it
402
- const step = layer * Math.tan((overhang * Math.PI) / 180), reach = Math.ceil(step / pitch) + 2 * r2;
946
+ const step = layer * Math.tan((overhang * Math.PI) / 180),
947
+ reach = Math.ceil(step / pitch) + 2 * r2;
403
948
  // That line's grace is for a ledge, once. A wall that leans on, layer after layer, would take it every layer (at
404
949
  // 0.2 mm layers and a 0.42 mm line, a 72° lean would pass), so each layer is also held against the ones SPANS
405
950
  // layers down, with the same single line's grace over the whole span: the longer a lean goes on, the nearer to the
406
951
  // limit it is held.
407
- const reachOver = SPANS.map((n) => Math.ceil((n * step) / pitch) + 2 * r2), history = [];
952
+ const reachOver = SPANS.map((n) => Math.ceil((n * step) / pitch) + 2 * r2),
953
+ history = [];
408
954
  const tris = [];
409
955
  for (const p of polys) for (let i = 1; i < p.length - 1; i++) tris.push([p[0], p[i], p[i + 1]]);
410
- const zmin = tris.map((t) => Math.min(t[0][2], t[1][2], t[2][2])), zmax = tris.map((t) => Math.max(t[0][2], t[1][2], t[2][2]));
411
- const count = Math.max(1, Math.round((hi[2] - lo[2]) / layer)), out = [];
412
- // Each triangle filed under the layers whose middle it spans, so a layer looks only at its own
956
+ const zmin = tris.map((t) => Math.min(t[0][2], t[1][2], t[2][2])),
957
+ zmax = tris.map((t) => Math.max(t[0][2], t[1][2], t[2][2]));
958
+ const count = Math.max(1, Math.round((hi[2] - lo[2]) / layer)),
959
+ out = [];
960
+ // Each triangle filed under the layers whose middle it spans, so a layer looks only at its own. (A face that ends right
961
+ // at a layer's middle is filed under it too: 9.1 / 0.2 - 0.5 comes out a hair under 45, and a hole ending there
962
+ // was in no layer's list, so the layer was drawn with the hole filled in)
413
963
  const byLayer = Array.from({ length: count }, () => []);
414
- for (let t = 0; t < tris.length; t++) for (let L = Math.max(0, Math.ceil((zmin[t] - lo[2]) / layer - 0.5)); L <= Math.min(count - 1, Math.floor((zmax[t] - lo[2]) / layer - 0.5)); L++) byLayer[L].push(t);
415
- let below = null, held = null, prev = null, counted = null, overhangArea = 0;
964
+ for (let t = 0; t < tris.length; t++)
965
+ for (
966
+ let L = Math.max(0, Math.ceil((zmin[t] - lo[2]) / layer - 0.5 - 1e-6));
967
+ L <= Math.min(count - 1, Math.floor((zmax[t] - lo[2]) / layer - 0.5 + 1e-6));
968
+ L++
969
+ )
970
+ byLayer[L].push(t);
971
+ // Each flat underside filed under the first layer over it: the one whose middle lies within a layer above it, and the
972
+ // one cut right at its height too, when a layer's middle falls on it (which side of the cut it lies is then a toss)
973
+ const flatsBy = new Map();
974
+ for (const p of flats || []) {
975
+ const z0 = Math.min(...p.map((v) => v[2])),
976
+ z1 = Math.max(...p.map((v) => v[2]));
977
+ for (
978
+ let L = Math.max(0, Math.floor((z0 - lo[2]) / layer));
979
+ L < count && lo[2] + (L + 0.5) * layer <= z1 + layer + 1e-9;
980
+ L++
981
+ )
982
+ if (lo[2] + (L + 0.5) * layer > z0 - layer / 2) flatsBy.set(L, [...(flatsBy.get(L) || []), p]);
983
+ }
984
+ let below = null,
985
+ held = null,
986
+ prev = null,
987
+ counted = null,
988
+ overhangArea = 0;
416
989
  let firstSprawl = 0; // the first layer's outline against a circle's of the same area
417
990
  const fused = []; // on the first layer, regions nearer each other than firstGap: { at, gap } (the first layer spreads, and they print as one)
418
991
  const px = (x) => Math.floor((x - lo[0]) / pitch) + 3;
@@ -420,41 +993,69 @@ export function islands(polys, { layer = 0.2, overhang = 45, line = LINE, firstG
420
993
  // narrower than a line, which the slicer drops, is not a region at all
421
994
  // Square windows, by running sums along each row and then each column: any (grow) or all (shrink) within r pixels
422
995
  const sweep = (f, r, all) => {
423
- const tmp = new Uint8Array(nx * ny), out = new Uint8Array(nx * ny), w = 2 * r + 1, sum = new Int32Array(Math.max(nx, ny) + 1);
424
- for (let j = 0; j < ny; j++) { // along x
425
- const row = j * nx; sum[0] = 0;
996
+ const tmp = new Uint8Array(nx * ny),
997
+ out = new Uint8Array(nx * ny),
998
+ w = 2 * r + 1,
999
+ sum = new Int32Array(Math.max(nx, ny) + 1);
1000
+ for (let j = 0; j < ny; j++) {
1001
+ // along x
1002
+ const row = j * nx;
1003
+ sum[0] = 0;
426
1004
  for (let i = 0; i < nx; i++) sum[i + 1] = sum[i] + f[row + i];
427
- for (let i = 0; i < nx; i++) { const a = Math.max(0, i - r), b = Math.min(nx, i + r + 1), n = sum[b] - sum[a]; tmp[row + i] = all ? (b - a === w && n === w ? 1 : 0) : n > 0 ? 1 : 0; }
1005
+ for (let i = 0; i < nx; i++) {
1006
+ const a = Math.max(0, i - r),
1007
+ b = Math.min(nx, i + r + 1),
1008
+ n = sum[b] - sum[a];
1009
+ tmp[row + i] = all ? (b - a === w && n === w ? 1 : 0) : n > 0 ? 1 : 0;
1010
+ }
428
1011
  }
429
- for (let i = 0; i < nx; i++) { // then along y
1012
+ for (let i = 0; i < nx; i++) {
1013
+ // then along y
430
1014
  sum[0] = 0;
431
1015
  for (let j = 0; j < ny; j++) sum[j + 1] = sum[j] + tmp[j * nx + i];
432
- for (let j = 0; j < ny; j++) { const a = Math.max(0, j - r), b = Math.min(ny, j + r + 1), n = sum[b] - sum[a]; out[j * nx + i] = all ? (b - a === w && n === w ? 1 : 0) : n > 0 ? 1 : 0; }
1016
+ for (let j = 0; j < ny; j++) {
1017
+ const a = Math.max(0, j - r),
1018
+ b = Math.min(ny, j + r + 1),
1019
+ n = sum[b] - sum[a];
1020
+ out[j * nx + i] = all ? (b - a === w && n === w ? 1 : 0) : n > 0 ? 1 : 0;
1021
+ }
433
1022
  }
434
1023
  return out;
435
1024
  };
436
- const erode = (f) => sweep(f, r2, true), dilate = (f, r) => sweep(f, r, false);
1025
+ const erode = (f) => sweep(f, r2, true),
1026
+ dilate = (f, r) => sweep(f, r, false);
1027
+ // Scanline fill of outlines (segments [[x, y], [x, y]]), even-odd, a pixel row at a time
1028
+ const fill = (segs, into = new Uint8Array(nx * ny)) => {
1029
+ for (let j = 0; j < ny; j++) {
1030
+ const y = lo[1] + (j - 2.5) * pitch,
1031
+ xs = [];
1032
+ for (const [a, b] of segs)
1033
+ if (a[1] <= y !== b[1] <= y) xs.push(a[0] + ((y - a[1]) / (b[1] - a[1])) * (b[0] - a[0]));
1034
+ xs.sort((p, q) => p - q);
1035
+ for (let k = 0; k + 1 < xs.length; k += 2)
1036
+ for (let i = Math.max(0, px(xs[k])); i <= Math.min(nx - 1, px(xs[k + 1]) - 1); i++) into[j * nx + i] = 1;
1037
+ }
1038
+ return into;
1039
+ };
437
1040
  const opened = (f) => dilate(erode(f), r2);
438
1041
  for (let L = 0; L < count; L++) {
439
1042
  onLayer?.(L, count);
440
- const z = lo[2] + (L + 0.5) * layer, segs = [];
1043
+ const z = lo[2] + (L + 0.5) * layer,
1044
+ segs = [];
441
1045
  for (const t of byLayer[L]) {
442
1046
  if (zmin[t] > z || zmax[t] < z) continue;
443
1047
  const pts = [];
444
1048
  for (let i = 0; i < 3; i++) {
445
- const a = tris[t][i], b = tris[t][(i + 1) % 3];
446
- if ((a[2] < z) !== (b[2] < z)) { const u = (z - a[2]) / (b[2] - a[2]); pts.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]); }
1049
+ const a = tris[t][i],
1050
+ b = tris[t][(i + 1) % 3];
1051
+ if (a[2] < z !== b[2] < z) {
1052
+ const u = (z - a[2]) / (b[2] - a[2]);
1053
+ pts.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]);
1054
+ }
447
1055
  }
448
1056
  if (pts.length === 2) segs.push(pts);
449
1057
  }
450
- // Scanline fill, even-odd, a pixel row at a time
451
- const raw = new Uint8Array(nx * ny);
452
- for (let j = 0; j < ny; j++) {
453
- const y = lo[1] + (j - 2.5) * pitch, xs = [];
454
- for (const [a, b] of segs) if ((a[1] <= y) !== (b[1] <= y)) xs.push(a[0] + ((y - a[1]) / (b[1] - a[1])) * (b[0] - a[0]));
455
- xs.sort((p, q) => p - q);
456
- for (let k = 0; k + 1 < xs.length; k += 2) for (let i = Math.max(0, px(xs[k])); i <= Math.min(nx - 1, px(xs[k + 1]) - 1); i++) raw[j * nx + i] = 1;
457
- }
1058
+ const raw = fill(segs);
458
1059
  // A layer drawn the same as the one below (an upright wall, most of most parts) lies wholly on it: nothing to measure
459
1060
  let same = !!prev;
460
1061
  for (let n = 0; same && n < nx * ny; n++) if (raw[n] !== prev[n]) same = false;
@@ -464,34 +1065,109 @@ export function islands(polys, { layer = 0.2, overhang = 45, line = LINE, firstG
464
1065
  if (same) continue;
465
1066
  const filled = opened(raw);
466
1067
  history[L] = filled;
467
- if (L === 0) { // how long the first layer's outline is, against a circle's of the same area: 1 for a disc, more the more it's cut up
468
- let area = 0, edges = 0;
469
- for (let n = 0; n < nx * ny; n++) if (filled[n]) { area++; if (!filled[n - 1]) edges++; if (!filled[n + 1]) edges++; if (!filled[n - nx]) edges++; if (!filled[n + nx]) edges++; }
1068
+ if (L === 0) {
1069
+ // how long the first layer's outline is, against a circle's of the same area: 1 for a disc, more the more it's cut up
1070
+ let area = 0,
1071
+ edges = 0;
1072
+ for (let n = 0; n < nx * ny; n++)
1073
+ if (filled[n]) {
1074
+ area++;
1075
+ if (!filled[n - 1]) edges++;
1076
+ if (!filled[n + 1]) edges++;
1077
+ if (!filled[n - nx]) edges++;
1078
+ if (!filled[n + nx]) edges++;
1079
+ }
470
1080
  firstSprawl = area ? (edges * pitch) / (2 * Math.sqrt(Math.PI * area * pitch * pitch)) : 0;
471
1081
  }
472
1082
  if (L === 0 && firstGap > 0) {
473
1083
  // Each region labelled; grown by half the gap, two that meet were nearer than it. Where they meet is the spot
474
- const label = (mask) => { const lab = new Int32Array(nx * ny), stack = new Int32Array(nx * ny); let n = 0; for (let st = 0; st < nx * ny; st++) { if (!mask[st] || lab[st]) continue; n++; let top = 0; stack[top++] = st; lab[st] = n; while (top) { const e = stack[--top], i = e % nx; for (const d of [i + 1 < nx ? e + 1 : -1, i > 0 ? e - 1 : -1, e + nx < nx * ny ? e + nx : -1, e >= nx ? e - nx : -1]) if (d >= 0 && mask[d] && !lab[d]) { lab[d] = n; stack[top++] = d; } } } return { lab, n }; };
475
- const own = label(filled), r = Math.max(1, Math.round(firstGap / 2 / pitch)), grown = label(dilate(filled, r));
1084
+ const label = (mask) => {
1085
+ const lab = new Int32Array(nx * ny),
1086
+ stack = new Int32Array(nx * ny);
1087
+ let n = 0;
1088
+ for (let st = 0; st < nx * ny; st++) {
1089
+ if (!mask[st] || lab[st]) continue;
1090
+ n++;
1091
+ let top = 0;
1092
+ stack[top++] = st;
1093
+ lab[st] = n;
1094
+ while (top) {
1095
+ const e = stack[--top],
1096
+ i = e % nx;
1097
+ for (const d of [
1098
+ i + 1 < nx ? e + 1 : -1,
1099
+ i > 0 ? e - 1 : -1,
1100
+ e + nx < nx * ny ? e + nx : -1,
1101
+ e >= nx ? e - nx : -1,
1102
+ ])
1103
+ if (d >= 0 && mask[d] && !lab[d]) {
1104
+ lab[d] = n;
1105
+ stack[top++] = d;
1106
+ }
1107
+ }
1108
+ }
1109
+ return { lab, n };
1110
+ };
1111
+ const own = label(filled),
1112
+ r = Math.max(1, Math.round(firstGap / 2 / pitch)),
1113
+ grown = label(dilate(filled, r));
476
1114
  if (own.n > 1) {
477
1115
  const seen = new Map(); // a grown region → the first own label in it, and the first pixel of a second
478
1116
  for (let e = 0; e < nx * ny; e++) {
479
1117
  if (!own.lab[e]) continue;
480
- const g = grown.lab[e], first = seen.get(g);
1118
+ const g = grown.lab[e],
1119
+ first = seen.get(g);
481
1120
  if (first == null) seen.set(g, own.lab[e]);
482
- else if (first !== own.lab[e] && !fused.some((x) => x.region === g)) fused.push({ region: g, at: [lo[0] + ((e % nx) - 2.5) * pitch, lo[1] + (Math.floor(e / nx) - 2.5) * pitch, z] });
1121
+ else if (first !== own.lab[e] && !fused.some((x) => x.region === g))
1122
+ fused.push({
1123
+ region: g,
1124
+ at: [lo[0] + ((e % nx) - 2.5) * pitch, lo[1] + (Math.floor(e / nx) - 2.5) * pitch, z],
1125
+ });
483
1126
  }
484
- for (const x of fused) { // the gap itself: how far this pixel is from the other region, in pixels, by growing it until they meet
485
- let d = 1; const mine = own.lab[Math.round((x.at[1] - lo[1]) / pitch + 2.5) * nx + Math.round((x.at[0] - lo[0]) / pitch + 2.5)];
486
- for (; d <= 2 * r + 1; d++) { const i0 = Math.round((x.at[0] - lo[0]) / pitch + 2.5), j0 = Math.round((x.at[1] - lo[1]) / pitch + 2.5); let met = false; for (let dj = -d; dj <= d && !met; dj++) for (let di = -d; di <= d && !met; di++) { const i = i0 + di, j = j0 + dj; if (i >= 0 && j >= 0 && i < nx && j < ny && own.lab[j * nx + i] && own.lab[j * nx + i] !== mine) met = true; } if (met) break; }
487
- x.gap = +(Math.max(0, d - 1) * pitch).toFixed(2); delete x.region;
1127
+ for (const x of fused) {
1128
+ // the gap itself: how far this pixel is from the other region, in pixels, by growing it until they meet
1129
+ let d = 1;
1130
+ const mine =
1131
+ own.lab[Math.round((x.at[1] - lo[1]) / pitch + 2.5) * nx + Math.round((x.at[0] - lo[0]) / pitch + 2.5)];
1132
+ for (; d <= 2 * r + 1; d++) {
1133
+ const i0 = Math.round((x.at[0] - lo[0]) / pitch + 2.5),
1134
+ j0 = Math.round((x.at[1] - lo[1]) / pitch + 2.5);
1135
+ let met = false;
1136
+ for (let dj = -d; dj <= d && !met; dj++)
1137
+ for (let di = -d; di <= d && !met; di++) {
1138
+ const i = i0 + di,
1139
+ j = j0 + dj;
1140
+ if (i >= 0 && j >= 0 && i < nx && j < ny && own.lab[j * nx + i] && own.lab[j * nx + i] !== mine)
1141
+ met = true;
1142
+ }
1143
+ if (met) break;
1144
+ }
1145
+ x.gap = +(Math.max(0, d - 1) * pitch).toFixed(2);
1146
+ delete x.region;
488
1147
  }
489
1148
  }
490
1149
  }
491
1150
  if (below) {
492
1151
  held = dilate(below, reach); // where this layer may lie: on the one below, or a step out from it
493
- let unheld = 0;
494
- for (let n = 0; n < nx * ny; n++) if (filled[n] && !held[n]) unheld++;
1152
+ // What lies right over a flat underside judged on its own (a bridge, a ledge) is that finding's, not an overhang
1153
+ // here: each face drawn, and grown a pixel for the drawing's rounding
1154
+ let mask = null;
1155
+ if (flatsBy.has(L)) {
1156
+ mask = new Uint8Array(nx * ny);
1157
+ for (const p of flatsBy.get(L))
1158
+ fill(
1159
+ p.map((a, i) => [a, p[(i + 1) % p.length]]),
1160
+ mask,
1161
+ );
1162
+ mask = dilate(mask, 1);
1163
+ }
1164
+ let unheld = 0,
1165
+ unheldOut = 0;
1166
+ for (let n = 0; n < nx * ny; n++)
1167
+ if (filled[n] && !held[n]) {
1168
+ unheld++;
1169
+ if (!mask || !mask[n]) unheldOut++;
1170
+ }
495
1171
  // A lean kept up over a span: what isn't straight above the layer below, and lies out past what the layer a
496
1172
  // span down allows. (What is straight above the layer below rests on it: the layers over a bridge, say.)
497
1173
  let leant = 0;
@@ -499,31 +1175,57 @@ export function islands(polys, { layer = 0.2, overhang = 45, line = LINE, firstG
499
1175
  const far = L >= SPANS[k] ? history[L - SPANS[k]] : null;
500
1176
  if (!far || far === below) continue;
501
1177
  const heldOver = dilate(far, reachOver[k]);
502
- for (let n = 0; n < nx * ny; n++) if (filled[n] && held[n] && !below[n] && !heldOver[n] && !(counted && counted[n])) { leant++; (counted ||= new Uint8Array(nx * ny))[n] = 1; }
1178
+ for (let n = 0; n < nx * ny; n++)
1179
+ if (filled[n] && held[n] && !below[n] && !heldOver[n] && !(counted && counted[n]) && !(mask && mask[n])) {
1180
+ leant++;
1181
+ (counted ||= new Uint8Array(nx * ny))[n] = 1;
1182
+ }
503
1183
  }
504
1184
  counted = null;
505
- overhangArea += (unheld + leant) * pitch * pitch;
1185
+ overhangArea += (unheldOut + leant) * pitch * pitch;
506
1186
  // Regions of this layer that lie on nothing: an island is a region with no pixel within reach of the layer
507
1187
  // below, so only a region holding an unheld pixel can be one. Most layers have none, and are done here.
508
1188
  if (unheld) {
509
- const seen = new Uint8Array(nx * ny), stack = new Int32Array(nx * ny);
1189
+ const seen = new Uint8Array(nx * ny),
1190
+ stack = new Int32Array(nx * ny);
510
1191
  for (let start = 0; start < nx * ny; start++) {
511
1192
  if (!filled[start] || held[start] || seen[start]) continue;
512
- let top = 0, onSomething = false;
1193
+ let top = 0,
1194
+ onSomething = false;
513
1195
  const cells = [];
514
- stack[top++] = start; seen[start] = 1;
1196
+ stack[top++] = start;
1197
+ seen[start] = 1;
515
1198
  while (top) {
516
- const e = stack[--top], i = e % nx;
1199
+ const e = stack[--top],
1200
+ i = e % nx;
517
1201
  cells.push(e);
518
1202
  if (held[e]) onSomething = true;
519
- if (i + 1 < nx && filled[e + 1] && !seen[e + 1]) { seen[e + 1] = 1; stack[top++] = e + 1; }
520
- if (i > 0 && filled[e - 1] && !seen[e - 1]) { seen[e - 1] = 1; stack[top++] = e - 1; }
521
- if (e + nx < nx * ny && filled[e + nx] && !seen[e + nx]) { seen[e + nx] = 1; stack[top++] = e + nx; }
522
- if (e >= nx && filled[e - nx] && !seen[e - nx]) { seen[e - nx] = 1; stack[top++] = e - nx; }
1203
+ if (i + 1 < nx && filled[e + 1] && !seen[e + 1]) {
1204
+ seen[e + 1] = 1;
1205
+ stack[top++] = e + 1;
1206
+ }
1207
+ if (i > 0 && filled[e - 1] && !seen[e - 1]) {
1208
+ seen[e - 1] = 1;
1209
+ stack[top++] = e - 1;
1210
+ }
1211
+ if (e + nx < nx * ny && filled[e + nx] && !seen[e + nx]) {
1212
+ seen[e + nx] = 1;
1213
+ stack[top++] = e + nx;
1214
+ }
1215
+ if (e >= nx && filled[e - nx] && !seen[e - nx]) {
1216
+ seen[e - nx] = 1;
1217
+ stack[top++] = e - nx;
1218
+ }
523
1219
  }
524
1220
  if (!onSomething) {
525
- const cx = cells.reduce((s, e) => s + (e % nx), 0) / cells.length, cy = cells.reduce((s, e) => s + Math.floor(e / nx), 0) / cells.length;
526
- out.push({ z: +z.toFixed(3), area: cells.length * pitch * pitch, at: [lo[0] + (cx - 2.5) * pitch, lo[1] + (cy - 2.5) * pitch, z], cells: cells.map((e) => [lo[0] + ((e % nx) - 2.5) * pitch, lo[1] + (Math.floor(e / nx) - 2.5) * pitch]) });
1221
+ const cx = cells.reduce((s, e) => s + (e % nx), 0) / cells.length,
1222
+ cy = cells.reduce((s, e) => s + Math.floor(e / nx), 0) / cells.length;
1223
+ out.push({
1224
+ z: +z.toFixed(3),
1225
+ area: cells.length * pitch * pitch,
1226
+ at: [lo[0] + (cx - 2.5) * pitch, lo[1] + (cy - 2.5) * pitch, z],
1227
+ cells: cells.map((e) => [lo[0] + ((e % nx) - 2.5) * pitch, lo[1] + (Math.floor(e / nx) - 2.5) * pitch]),
1228
+ });
527
1229
  }
528
1230
  }
529
1231
  }
@@ -534,17 +1236,54 @@ export function islands(polys, { layer = 0.2, overhang = 45, line = LINE, firstG
534
1236
  }
535
1237
 
536
1238
  export function shape(polys, eps = 1e-3, drop = 0.05, hang = 1) {
537
- const ids = new Map(), at = [], key = (v) => v.map((c) => Math.round(c / eps)).join(',');
538
- const faces = polys.map((p) => p.map((v) => { const k = key(v); if (!ids.has(k)) { ids.set(k, at.length); at.push(v); } return ids.get(k); }));
539
- const up = at.map((_, i) => i), find = (i) => { while (up[i] !== i) i = up[i] = up[up[i]]; return i; };
540
- const near = at.map(() => new Set()), facing = at.map(() => 0);
541
- faces.forEach((f, n) => { const z = areaNormal(polys[n])[2]; for (const v of f) facing[v] += z; });
542
- for (const f of faces) for (let i = 0; i < f.length; i++) { const a = f[i], b = f[(i + 1) % f.length]; up[find(a)] = find(b); near[a].add(b); near[b].add(a); }
1239
+ const ids = new Map(),
1240
+ at = [],
1241
+ key = (v) => v.map((c) => Math.round(c / eps)).join(',');
1242
+ const faces = polys.map((p) =>
1243
+ p.map((v) => {
1244
+ const k = key(v);
1245
+ if (!ids.has(k)) {
1246
+ ids.set(k, at.length);
1247
+ at.push(v);
1248
+ }
1249
+ return ids.get(k);
1250
+ }),
1251
+ );
1252
+ const up = at.map((_, i) => i),
1253
+ find = (i) => {
1254
+ while (up[i] !== i) i = up[i] = up[up[i]];
1255
+ return i;
1256
+ };
1257
+ const near = at.map(() => new Set()),
1258
+ facing = at.map(() => 0);
1259
+ faces.forEach((f, n) => {
1260
+ const z = areaNormal(polys[n])[2];
1261
+ for (const v of f) facing[v] += z;
1262
+ });
1263
+ for (const f of faces)
1264
+ for (let i = 0; i < f.length; i++) {
1265
+ const a = f[i],
1266
+ b = f[(i + 1) % f.length];
1267
+ up[find(a)] = find(b);
1268
+ near[a].add(b);
1269
+ near[b].add(a);
1270
+ }
543
1271
  const by = new Map();
544
1272
  for (const f of faces) {
545
- const r = find(f[0]), piece = by.get(r) ?? { volume: 0, box: { lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] } };
546
- for (let i = 1; i < f.length - 1; i++) { const [a, b, c] = [at[f[0]], at[f[i]], at[f[i + 1]]]; piece.volume += vdot(a, cross(b, c)) / 6; }
547
- for (const v of f) for (let k = 0; k < 3; k++) { piece.box.lo[k] = Math.min(piece.box.lo[k], at[v][k]); piece.box.hi[k] = Math.max(piece.box.hi[k], at[v][k]); }
1273
+ const r = find(f[0]),
1274
+ piece = by.get(r) ?? {
1275
+ volume: 0,
1276
+ box: { lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] },
1277
+ };
1278
+ for (let i = 1; i < f.length - 1; i++) {
1279
+ const [a, b, c] = [at[f[0]], at[f[i]], at[f[i + 1]]];
1280
+ piece.volume += vdot(a, cross(b, c)) / 6;
1281
+ }
1282
+ for (const v of f)
1283
+ for (let k = 0; k < 3; k++) {
1284
+ piece.box.lo[k] = Math.min(piece.box.lo[k], at[v][k]);
1285
+ piece.box.hi[k] = Math.max(piece.box.hi[k], at[v][k]);
1286
+ }
548
1287
  by.set(r, piece);
549
1288
  }
550
1289
  const pieces = [...by.values()].filter((p) => p.volume > eps).sort((a, b) => b.volume - a.volume);
@@ -552,12 +1291,15 @@ export function shape(polys, eps = 1e-3, drop = 0.05, hang = 1) {
552
1291
  // A tip hangs: within hang of its point the surface stays narrow (a cone at 45° is as wide as it is tall). A dip in a
553
1292
  // smoothed underside is shallow: within hang of it, the surface spreads wide, as far as the underside does.
554
1293
  const narrow = (i) => {
555
- const seen = new Set([i]), todo = [i], v = at[i];
1294
+ const seen = new Set([i]),
1295
+ todo = [i],
1296
+ v = at[i];
556
1297
  while (todo.length) {
557
1298
  for (const j of near[todo.pop()]) {
558
1299
  if (seen.has(j) || at[j][2] > v[2] + hang) continue;
559
1300
  if (Math.hypot(at[j][0] - v[0], at[j][1] - v[1]) > 2 * hang) return false;
560
- seen.add(j); todo.push(j);
1301
+ seen.add(j);
1302
+ todo.push(j);
561
1303
  }
562
1304
  }
563
1305
  return true;