@rulecad/printcheck 0.1.4 → 0.2.2
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/README.md +23 -4
- package/package.json +1 -1
- package/printcheck.d.mts +38 -20
- package/printcheck.mjs +286 -31
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ words. No dependencies; browsers and Node 20+.
|
|
|
6
6
|
```js
|
|
7
7
|
import { check } from '@rulecad/printcheck';
|
|
8
8
|
|
|
9
|
-
const printer = { bed: 256, overhang: 45, layer: 0.2, support_gap: 0.2, bridge: 5 };
|
|
9
|
+
const printer = { bed: 256, overhang: 45, layer: 0.2, support_gap: 0.2, bridge: 5, line: 0.42, print_gap: 0.3, foot: 0.15 };
|
|
10
10
|
const findings = check(triangles, printer);
|
|
11
11
|
// [{ level: 'pass', text: '20 × 4 × 12 mm, fits the bed' },
|
|
12
12
|
// { level: 'warn', text: 'an underside at z 10 starts in mid-air: needs support …' }, …]
|
|
@@ -19,11 +19,29 @@ triangulated.
|
|
|
19
19
|
What it checks:
|
|
20
20
|
|
|
21
21
|
- **Fits the bed** (`bed`, mm) and **sits on it**: lowest point at z = 0, with faces flat on the bed.
|
|
22
|
-
- **Overhangs** steeper than `overhang` degrees from vertical
|
|
22
|
+
- **Overhangs** steeper than `overhang` degrees from vertical (with half a degree to spare: a boolean tips a 45°
|
|
23
|
+
chamfer by hundredths of a degree).
|
|
24
|
+
- **Inside out**: a mesh whose faces all point inwards (corners running clockwise seen from outside) fails as that,
|
|
25
|
+
before anything else is read from it.
|
|
23
26
|
- **Flat undersides above the bed**: each must start on something. Either it rests on a built-in **breakaway support**
|
|
24
27
|
(one `support_gap` below a surface), or it **bridges** no wider than `bridge` mm. The bridge is the widest circle that
|
|
25
28
|
fits in the underside, measured to the edges held up by material below. An underside held by nothing starts in
|
|
26
|
-
mid-air.
|
|
29
|
+
mid-air. One held on one side only (its supports all within a half turn of it, and a little), further out than a
|
|
30
|
+
print line, is a **ledge**: nothing bridges it, each line is laid past the last in the air, and it droops (slant its
|
|
31
|
+
underside in at 45° to the wall instead). What lies within a breakaway gap or two layers of the bed, or of a
|
|
32
|
+
surface below it, rests on it. Undersides within a layer of each other are one height; what starts in mid-air
|
|
33
|
+
and what hangs as a ledge is said once per height, with how many and the worst, and where.
|
|
34
|
+
Each underside is taken on its own (the faces at a height joined where they touch), and an edge is held wherever
|
|
35
|
+
it lies along the top edge of a wall below (booleans leave T-junctions; they don't matter). An underside no wider
|
|
36
|
+
than a print line (`line`, 0.42 mm unless given) anywhere is a step of a slope printed in layers, or a sliver the
|
|
37
|
+
slicer lays nothing on, and is not counted.
|
|
38
|
+
- **The first layer**: two parts printed in place must stand `print_gap` plus twice `foot` apart on the bed (`foot`
|
|
39
|
+
is how far the first layer spreads each side as it is squashed on: elephant's foot); nearer, they print as one.
|
|
40
|
+
Checked when the printer gives both; lifting one part a layer off the bed takes it out of the check.
|
|
41
|
+
- **Islands, as the slicer sees them**: the mesh cut at every layer (`layer`), each layer's regions against the one
|
|
42
|
+
below within the overhang reach; a region with nothing under it is an island the printer would lay on air. Drawn
|
|
43
|
+
on a grid of the print line (`line`), so slivers narrower than a line don't count. Also exported as `islands()`,
|
|
44
|
+
with each island's pixels for whatever fixes it.
|
|
27
45
|
- **Closed solid**: every edge is matched by a face on the other side. T-junctions count as closed, and so do hairline
|
|
28
46
|
seams narrower than `HAIRLINE` (0.01 mm), which booleans leave and no printer can resolve. Wider gaps are holes.
|
|
29
47
|
- **One piece**: a loose piece would print as a stray bit or fall over. A cavity inside a part (its surface faces in)
|
|
@@ -38,4 +56,5 @@ Several parts printed together (a keycap with an inlaid legend in another colour
|
|
|
38
56
|
its own. A part with `role: 'support'` is printed and then removed.
|
|
39
57
|
|
|
40
58
|
Also exported: `bounds(triangles)` (`{ lo, hi, size }`), `seams(triangles)` (`{ gaps, tjunctions, hairlines }`),
|
|
41
|
-
`shape(triangles)` (`{ pieces, tips }`)
|
|
59
|
+
`shape(triangles)` (`{ pieces, tips }`), `widest(polys, held, under)` (the bridge measurement) and
|
|
60
|
+
`ledges(polys, held, under)` (how far an underside reaches past its last support).
|
package/package.json
CHANGED
package/printcheck.d.mts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
/** @typedef {[number, number, number]} Point a corner in mm, Z up */
|
|
7
7
|
/** @typedef {Point[]} Face a polygon: three or more corners, counter-clockwise seen from outside */
|
|
8
|
-
/** @typedef {{ bed: number, overhang: number, layer?: number, support_gap?: number, bridge?: number }} Printer mm and degrees */
|
|
8
|
+
/** @typedef {{ bed: number, overhang: number, layer?: number, support_gap?: number, bridge?: number, line?: number, print_gap?: number, foot?: number }} Printer mm and degrees; layer and line drive the sliced-layer island check; print_gap and foot (how far the first layer spreads each side) the first-layer check */
|
|
9
9
|
/**
|
|
10
10
|
* A finding: its level and words, and for programs a code (print.bridge, fit.gap, …), the numbers behind it, and where
|
|
11
11
|
* it is when that's known (the box round the faces it's about, in mm).
|
|
@@ -36,6 +36,13 @@ export function check(polys: Face[], printer: Printer, { eps, parts }?: {
|
|
|
36
36
|
* @returns {number} mm
|
|
37
37
|
*/
|
|
38
38
|
export function widest(polys: Face[], held?: (edge: [Point, Point]) => boolean, under?: Face[]): number;
|
|
39
|
+
/**
|
|
40
|
+
* 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
|
|
41
|
+
* held on both sides everywhere (a bridge), null if nothing holds it.
|
|
42
|
+
* @param {Face[]} polys @param {(edge: [Point, Point]) => boolean} [held] @param {Face[]} [under]
|
|
43
|
+
* @returns {number | null} mm
|
|
44
|
+
*/
|
|
45
|
+
export function ledges(polys: Face[], held?: (edge: [Point, Point]) => boolean, under?: Face[]): number | null;
|
|
39
46
|
/**
|
|
40
47
|
* Open edges, sorted: real gaps, T-junctions (closed) and hairline seams (closed).
|
|
41
48
|
* @param {Face[]} polys @param {number} [eps]
|
|
@@ -46,25 +53,33 @@ export function seams(polys: Face[], eps?: number): {
|
|
|
46
53
|
tjunctions: number;
|
|
47
54
|
hairlines: number;
|
|
48
55
|
};
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
};
|
|
56
|
+
export function islands(polys: any, { layer, overhang, line, firstGap, onLayer }?: {
|
|
57
|
+
layer?: number;
|
|
58
|
+
overhang?: number;
|
|
59
|
+
line?: number;
|
|
60
|
+
firstGap?: number;
|
|
61
|
+
}): {
|
|
62
|
+
islands: any[];
|
|
63
|
+
layers: number;
|
|
64
|
+
overhang: number;
|
|
65
|
+
fused?: undefined;
|
|
66
|
+
} | {
|
|
67
|
+
islands: {
|
|
68
|
+
z: number;
|
|
69
|
+
area: number;
|
|
70
|
+
at: number[];
|
|
71
|
+
cells: number[][];
|
|
66
72
|
}[];
|
|
67
|
-
|
|
73
|
+
layers: number;
|
|
74
|
+
overhang: number;
|
|
75
|
+
fused: {
|
|
76
|
+
region: number;
|
|
77
|
+
at: number[];
|
|
78
|
+
}[];
|
|
79
|
+
};
|
|
80
|
+
export function shape(polys: any, eps?: number, drop?: number, hang?: number): {
|
|
81
|
+
pieces: any[];
|
|
82
|
+
tips: any[];
|
|
68
83
|
};
|
|
69
84
|
export const HAIRLINE: 0.01;
|
|
70
85
|
/**
|
|
@@ -76,7 +91,7 @@ export type Point = [number, number, number];
|
|
|
76
91
|
*/
|
|
77
92
|
export type Face = Point[];
|
|
78
93
|
/**
|
|
79
|
-
* mm and degrees
|
|
94
|
+
* mm and degrees; layer and line drive the sliced-layer island check; print_gap and foot (how far the first layer spreads each side) the first-layer check
|
|
80
95
|
*/
|
|
81
96
|
export type Printer = {
|
|
82
97
|
bed: number;
|
|
@@ -84,6 +99,9 @@ export type Printer = {
|
|
|
84
99
|
layer?: number;
|
|
85
100
|
support_gap?: number;
|
|
86
101
|
bridge?: number;
|
|
102
|
+
line?: number;
|
|
103
|
+
print_gap?: number;
|
|
104
|
+
foot?: number;
|
|
87
105
|
};
|
|
88
106
|
/**
|
|
89
107
|
* A finding: its level and words, and for programs a code (print.bridge, fit.gap, …), the numbers behind it, and where
|
package/printcheck.mjs
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
// · tips hanging down that start in mid-air
|
|
4
4
|
// flat undersides above the bed: on a built-in breakaway support (one support gap above a surface), or bridges no
|
|
5
5
|
// wider than the printer can span: the widest circle that fits in the underside, measured to the edges that are
|
|
6
|
-
// held up by material below. An underside with no such edge starts in mid-air: it needs support
|
|
6
|
+
// held up by material below. An underside with no such edge starts in mid-air: it needs support; one held on one
|
|
7
|
+
// side only past a print line is a ledge, which droops. Each underside
|
|
8
|
+
// is taken on its own (the faces at a height joined edge to edge), and one no wider than a print line anywhere is
|
|
9
|
+
// a step of a slope printed in layers, not a bridge.
|
|
7
10
|
// Z is up and the bed is z = 0: a design is checked as it will print, so print orientation is part of the design.
|
|
8
11
|
|
|
9
12
|
const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
|
@@ -17,6 +20,8 @@ function areaNormal(poly) {
|
|
|
17
20
|
}
|
|
18
21
|
|
|
19
22
|
const OVERHANG_SLACK = 0.5; // degrees
|
|
23
|
+
const LINE = 0.42; // mm: the line width when the printer gives none (a 0.4 mm nozzle's usual line)
|
|
24
|
+
const LEDGE_SLACK = (15 * Math.PI) / 180; // a point's supports all within a half turn and this: a ledge
|
|
20
25
|
|
|
21
26
|
/**
|
|
22
27
|
* The box around faces.
|
|
@@ -25,7 +30,7 @@ const OVERHANG_SLACK = 0.5; // degrees
|
|
|
25
30
|
*/
|
|
26
31
|
/** @typedef {[number, number, number]} Point a corner in mm, Z up */
|
|
27
32
|
/** @typedef {Point[]} Face a polygon: three or more corners, counter-clockwise seen from outside */
|
|
28
|
-
/** @typedef {{ bed: number, overhang: number, layer?: number, support_gap?: number, bridge?: number }} Printer mm and degrees */
|
|
33
|
+
/** @typedef {{ bed: number, overhang: number, layer?: number, support_gap?: number, bridge?: number, line?: number, print_gap?: number, foot?: number }} Printer mm and degrees; layer and line drive the sliced-layer island check; print_gap and foot (how far the first layer spreads each side) the first-layer check */
|
|
29
34
|
/**
|
|
30
35
|
* A finding: its level and words, and for programs a code (print.bridge, fit.gap, …), the numbers behind it, and where
|
|
31
36
|
* it is when that's known (the box round the faces it's about, in mm).
|
|
@@ -40,7 +45,7 @@ export function bounds(polys) {
|
|
|
40
45
|
|
|
41
46
|
// parts ([{ triangles, role }]): when parts print together (a keycap and its inlaid legend), an underside resting on
|
|
42
47
|
// another part isn't an overhang, and each part must be closed on its own (their shared faces are inside the print).
|
|
43
|
-
// printer: the printer's rules, any printer: { bed, overhang (degrees), layer, support_gap?, bridge? } in mm.
|
|
48
|
+
// printer: the printer's rules, any printer: { bed, overhang (degrees), layer, support_gap?, bridge?, line? } in mm.
|
|
44
49
|
/**
|
|
45
50
|
* Is it printable? Findings in plain words, each pass, warn or fail.
|
|
46
51
|
* @param {Face[]} polys the model as faces (triangles are fine), Z up, the bed at z = 0
|
|
@@ -50,6 +55,11 @@ export function bounds(polys) {
|
|
|
50
55
|
*/
|
|
51
56
|
export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
|
|
52
57
|
const out = [], f = (level, text, code, values, at) => out.push({ level, text, code, ...(values && { values }), ...(at && { at }) });
|
|
58
|
+
// What can't be checked is said at the door, not found out deep inside
|
|
59
|
+
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 }`);
|
|
60
|
+
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])})`);
|
|
61
|
+
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)));
|
|
62
|
+
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' }];
|
|
53
63
|
const solids = (parts || []).filter((p) => p.role !== 'support').map((p) => ({ tris: p.triangles, box: bounds(p.triangles) }));
|
|
54
64
|
// Is the point inside one of the parts? A ray straight up crosses its surface an odd number of times
|
|
55
65
|
const inPart = (pt) => solids.length > 1 && solids.some(({ tris, box }) => {
|
|
@@ -71,6 +81,13 @@ export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
|
|
|
71
81
|
const over = size.filter((s) => s > printer.bed);
|
|
72
82
|
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 });
|
|
73
83
|
|
|
84
|
+
// Faces the wrong way round: a closed solid's faces all point out, so the volume they enclose (signed, by the way
|
|
85
|
+
// their corners run) is positive. Negative, every face points in, and nothing below reads right (the base faces up,
|
|
86
|
+
// the top faces down): say that, not what follows from it
|
|
87
|
+
let signed = 0;
|
|
88
|
+
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; }
|
|
89
|
+
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; }
|
|
90
|
+
|
|
74
91
|
// Flat on the bed: the lowest point is z = 0, and faces there point straight down.
|
|
75
92
|
let base = 0, down = 0, support = 0, zs = [];
|
|
76
93
|
// Where a finding is: the box round the faces it's about, { lo, hi } (for a reader to point at)
|
|
@@ -94,9 +111,10 @@ export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
|
|
|
94
111
|
if (nz < 0) down += area;
|
|
95
112
|
}
|
|
96
113
|
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] });
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
114
|
+
if (base <= 0) f('fail', 'nothing sits flat on the bed', 'print.base', { area: base });
|
|
115
|
+
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)
|
|
116
|
+
const overAt = support > 0.5 ? overBox : null, slicing = printer.layer != null; // sliced below, the layers are what count; the facets are then a note
|
|
117
|
+
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);
|
|
100
118
|
else f('pass', `no overhangs past ${printer.overhang}°`, 'print.overhang', { area: support, angle: printer.overhang });
|
|
101
119
|
|
|
102
120
|
// Flat undersides: on a breakaway support, or bridged
|
|
@@ -109,22 +127,71 @@ export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
|
|
|
109
127
|
return true;
|
|
110
128
|
};
|
|
111
129
|
const centroid = (p) => [0, 1].map((k) => p.reduce((s, v) => s + v[k], 0) / p.length);
|
|
112
|
-
|
|
130
|
+
// (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)
|
|
131
|
+
const nearBed = Math.max(gap * 1.5, 2 * (printer.layer ?? 0.2));
|
|
132
|
+
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)));
|
|
113
133
|
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 });
|
|
134
|
+
// And the bed is a support too: an underside within a breakaway gap of it (a smoothed base's facets a hair up) is
|
|
135
|
+
// squashed on to it with the first layer, not printed in the air
|
|
136
|
+
const onBed = flatDown.filter((d) => !held.includes(d) && d.z - lo[2] <= nearBed + eps);
|
|
137
|
+
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) });
|
|
114
138
|
const levels = new Map();
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
139
|
+
// (undersides within a layer of each other are one height: a smoothed surface's facets sit a hair apart)
|
|
140
|
+
const layerH = printer.layer ?? 0.2;
|
|
141
|
+
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]); }
|
|
142
|
+
// A point on a segment (in the plane), within eps; and a segment lying along another, overlapping it
|
|
143
|
+
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; };
|
|
144
|
+
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)
|
|
145
|
+
const dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy); if (l < eps) return false;
|
|
146
|
+
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;
|
|
147
|
+
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);
|
|
148
|
+
return Math.min(t0, t1) < 1 - eps && Math.max(t0, t1) > eps;
|
|
149
|
+
};
|
|
150
|
+
const bridgeMax = printer.bridge ?? 5, line = printer.line ?? LINE;
|
|
151
|
+
// Each underside on its own: the faces at a level joined where they touch, edge to edge or a corner on another's
|
|
152
|
+
// edge (a T-junction, which a boolean leaves plenty of). Two pockets' ceilings at one height are two bridges, each
|
|
153
|
+
// measured to its own held edges, not to the other's across the part
|
|
154
|
+
const regions = (group) => {
|
|
155
|
+
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); };
|
|
156
|
+
const cell = 1, cellOf = (v) => `${Math.floor(v[0] / cell)},${Math.floor(v[1] / cell)}`, byCell = new Map();
|
|
157
|
+
group.forEach((p, i) => { for (const v of p) { const k = cellOf(v); byCell.set(k, [...(byCell.get(k) || []), [v, i]]); } });
|
|
158
|
+
group.forEach((p, i) => p.forEach((a, k) => { // every corner of another face on this edge joins the two
|
|
159
|
+
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();
|
|
160
|
+
for (let t = 0; t <= n; t++) {
|
|
161
|
+
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);
|
|
162
|
+
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); }
|
|
163
|
+
}
|
|
164
|
+
}));
|
|
165
|
+
const out = new Map();
|
|
166
|
+
group.forEach((p, i) => { const r = root(i); out.set(r, [...(out.get(r) || []), p]); });
|
|
167
|
+
return [...out.values()];
|
|
168
|
+
};
|
|
169
|
+
// The top edges of walls that reach a level from below: an underside's edge lying along one is held up there
|
|
170
|
+
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]] : []; }));
|
|
171
|
+
// (a smoothed surface has many small undersides at a height: what starts in mid-air and what hangs as a ledge are
|
|
172
|
+
// said once per height, with how many and the worst; each bridge on its own)
|
|
173
|
+
for (const [z, level] of levels) {
|
|
174
|
+
const walls = wallsAt(Number(z), layerH / 2 + eps), midAir = [], ledges = []; // (the level's faces lie within half a layer of it)
|
|
175
|
+
for (const group of regions(level)) {
|
|
176
|
+
const at = boxOf(group);
|
|
177
|
+
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
|
|
178
|
+
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
|
|
179
|
+
const held = (a, b) => walls.some(([c, d]) => along(a, b, c, d));
|
|
180
|
+
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
|
|
181
|
+
const measured = spans(group, held, under), span = measured?.span ?? null, groupArea = group.reduce((s, p) => s + Math.hypot(...areaNormal(p)) / 2, 0);
|
|
182
|
+
if (span == null) midAir.push({ at, area: groupArea });
|
|
183
|
+
else if (measured.reach > line + eps) ledges.push({ at, reach: measured.reach, where: measured.where });
|
|
184
|
+
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);
|
|
185
|
+
else f('pass', `bridge ${mm(span)} mm at z ${mm(Number(z))} (up to ${bridgeMax} mm)`, 'print.bridge', { span, max: bridgeMax, z: Number(z) });
|
|
186
|
+
}
|
|
187
|
+
if (midAir.length) {
|
|
188
|
+
const biggest = midAir.reduce((m, x) => (x.area > m.area ? x : m)), total = midAir.reduce((s, x) => s + x.area, 0);
|
|
189
|
+
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);
|
|
190
|
+
}
|
|
191
|
+
if (ledges.length) {
|
|
192
|
+
const worst = ledges.reduce((m, x) => (x.reach > m.reach ? x : m));
|
|
193
|
+
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);
|
|
194
|
+
}
|
|
128
195
|
}
|
|
129
196
|
|
|
130
197
|
// One piece, and nothing starting in mid-air, part by part (an assembly's parts are apart on purpose)
|
|
@@ -136,6 +203,20 @@ export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
|
|
|
136
203
|
const hanging = tips.filter((t) => t[2] - lo[2] > eps && !rests([t, t, t]));
|
|
137
204
|
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] }));
|
|
138
205
|
else f('pass', 'nothing starts in mid-air', 'print.island', { points: [] });
|
|
206
|
+
// And as the slicer sees it: every layer against the one below
|
|
207
|
+
// (the first layer spreads `foot` each side as it is squashed on to the bed: two parts printed in place must stand
|
|
208
|
+
// further apart there than the gap that prints apart higher up, or they print as one)
|
|
209
|
+
const firstGap = printer.foot > 0 && printer.print_gap > 0 ? printer.print_gap + 2 * printer.foot : 0;
|
|
210
|
+
const sliced = islands(tris, { layer: printer.layer ?? 0.2, overhang: printer.overhang, line: printer.line ?? LINE, firstGap }), isl = sliced.islands;
|
|
211
|
+
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] });
|
|
212
|
+
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 });
|
|
213
|
+
// Overhang as the printer meets it: layers lying out past the one below, less the flat undersides the bridge check
|
|
214
|
+
// judges on their own. The face-by-face measure above counts the surface's facets, which on a smoothed, cell-built
|
|
215
|
+
// part are steeper than its layers are.
|
|
216
|
+
const flatArea = flatDown.reduce((s, d) => s + d.area, 0), out = Math.max(0, sliced.overhang - flatArea);
|
|
217
|
+
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 });
|
|
218
|
+
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] }));
|
|
219
|
+
else f('pass', `no islands in ${sliced.layers} layers of ${printer.layer ?? 0.2} mm`, 'print.islands', { islands: [] });
|
|
139
220
|
}
|
|
140
221
|
|
|
141
222
|
// Closed: every edge is matched by an edge running the other way. An edge that meets the middle of a longer edge
|
|
@@ -143,7 +224,7 @@ export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
|
|
|
143
224
|
const { gaps, tjunctions, hairlines } = parts && parts.length > 1
|
|
144
225
|
? 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 })
|
|
145
226
|
: seams(polys, eps);
|
|
146
|
-
if (gaps) f('warn', `${gaps} edges with nothing on the other side: holes in the surface (slicers may repair them)`, 'print.closed', { gaps });
|
|
227
|
+
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 });
|
|
147
228
|
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 });
|
|
148
229
|
return out;
|
|
149
230
|
}
|
|
@@ -152,36 +233,58 @@ export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
|
|
|
152
233
|
// (held(a, b) -> true), or to the tops of breakaway supports one layer below (under: faces): its diameter in mm, the
|
|
153
234
|
// gap a bridge has to span. null if nothing holds it up.
|
|
154
235
|
// Sampled: points spread over each face, each measured to the held edges of the region's outline and to the supports.
|
|
236
|
+
// A point with support on one side only (nothing held beyond it, away from its nearest held edge) is on a ledge, not
|
|
237
|
+
// a bridge: `ledges(polys, held, under)` gives how far the longest reaches.
|
|
155
238
|
/**
|
|
156
239
|
* The widest circle that fits in an underside, measured to its held-up edges (the bridge it makes).
|
|
157
240
|
* @param {Face[]} polys @param {(edge: [Point, Point]) => boolean} [held] @param {Face[]} [under]
|
|
158
241
|
* @returns {number} mm
|
|
159
242
|
*/
|
|
160
|
-
export function widest(polys, held = () => true, under = []) {
|
|
243
|
+
export function widest(polys, held = () => true, under = []) { return spans(polys, held, under)?.span ?? null; }
|
|
244
|
+
/**
|
|
245
|
+
* 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
|
|
246
|
+
* held on both sides everywhere (a bridge), null if nothing holds it.
|
|
247
|
+
* @param {Face[]} polys @param {(edge: [Point, Point]) => boolean} [held] @param {Face[]} [under]
|
|
248
|
+
* @returns {number | null} mm
|
|
249
|
+
*/
|
|
250
|
+
export function ledges(polys, held = () => true, under = []) { return spans(polys, held, under)?.reach ?? null; }
|
|
251
|
+
|
|
252
|
+
function spans(polys, held, under) {
|
|
161
253
|
const key = (v) => `${v[0].toFixed(3)},${v[1].toFixed(3)}`, count = new Map(), edges = [];
|
|
162
254
|
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]); });
|
|
163
255
|
const outline = edges.filter(([k]) => count.get(k) === 1).map(([, a, b]) => [a, b]).filter(([a, b]) => held(a, b));
|
|
164
256
|
const tops = under.flatMap((p) => p.map((a, i) => [a, p[(i + 1) % p.length]]));
|
|
165
257
|
if (!outline.length && !tops.length) return null;
|
|
166
258
|
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; });
|
|
167
|
-
const
|
|
168
|
-
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;
|
|
169
|
-
return Math.hypot(pt[0] -
|
|
259
|
+
const nearest = (pt, [a, b]) => { // the segment's closest point to pt, and how far
|
|
260
|
+
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];
|
|
261
|
+
return { c, d: Math.hypot(pt[0] - c[0], pt[1] - c[1]) };
|
|
170
262
|
};
|
|
171
|
-
|
|
263
|
+
const supports = [...outline, ...tops];
|
|
264
|
+
let best = 0, reach = 0, where = null;
|
|
172
265
|
const N = 6;
|
|
173
266
|
for (const p of polys) for (let i = 1; i < p.length - 1; i++) {
|
|
174
267
|
const [a, b, c] = [p[0], p[i], p[i + 1]];
|
|
175
268
|
for (let u = 0; u <= N; u++) for (let v = 0; u + v <= N; v++) {
|
|
176
269
|
const w = N - u - v, pt = [0, 1].map((k) => (a[k] * u + b[k] * v + c[k] * w) / N);
|
|
177
270
|
if (onTop(pt)) continue; // right over a support
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
271
|
+
const near = supports.map((s) => nearest(pt, s)), first = near.reduce((m, x) => (x.d < m.d ? x : m));
|
|
272
|
+
best = Math.max(best, first.d);
|
|
273
|
+
// Held round it, or on one side only? The directions to its supports: all within one half-plane (a gap of more
|
|
274
|
+
// than a half turn between them) and it hangs out past the last of them, a ledge reaching first.d; supports
|
|
275
|
+
// on opposing sides, and a line between two of them crosses it: a bridge
|
|
276
|
+
if (first.d > 1e-9) {
|
|
277
|
+
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);
|
|
278
|
+
let gap = angles.length ? angles[0] + 2 * Math.PI - angles.at(-1) : 2 * Math.PI;
|
|
279
|
+
for (let k = 1; k < angles.length; k++) gap = Math.max(gap, angles[k] - angles[k - 1]);
|
|
280
|
+
// (a bridge between two supports nearly opposite each other, a strap from a wall to a post, leaves a gap a few
|
|
281
|
+
// degrees over a half turn where the post's nearest point is off its line: some slack, LEDGE_SLACK, before it
|
|
282
|
+
// counts as a ledge)
|
|
283
|
+
if (gap > Math.PI + LEDGE_SLACK && first.d > reach) { reach = first.d; where = pt; }
|
|
284
|
+
}
|
|
182
285
|
}
|
|
183
286
|
}
|
|
184
|
-
return 2 * best;
|
|
287
|
+
return { span: 2 * best, reach, where };
|
|
185
288
|
}
|
|
186
289
|
|
|
187
290
|
// seams(polys) -> { gaps, tjunctions, hairlines }: edges not matched by a reverse edge, split into T-junctions (covered
|
|
@@ -250,6 +353,158 @@ export function seams(polys, eps = 1e-3) {
|
|
|
250
353
|
* @param {Face[]} polys @param {number} [eps] @param {number} [drop] @param {number} [hang] how far a tip must hang, mm
|
|
251
354
|
* @returns {{ pieces: { volume: number, box: { lo: number[], hi: number[] } }[], tips: number[][] }}
|
|
252
355
|
*/
|
|
356
|
+
/**
|
|
357
|
+
* The slicer's view: the mesh cut at every layer, each layer's regions checked against the one below. A region that
|
|
358
|
+
* overlaps nothing in the layer below, within the overhang reach (a layer's height over the tangent of the limit, so a
|
|
359
|
+
* 45° wall counts as held), starts in mid-air: an island, which a printer lays on nothing. Each layer is drawn on a
|
|
360
|
+
* grid of a quarter of the print line and opened by half a line, so anything narrower than a line (which the slicer
|
|
361
|
+
* never extrudes) is not a region, and the rest is compared by pixels.
|
|
362
|
+
* @param {Face[]} polys the closed mesh
|
|
363
|
+
* @param {{ layer?: number, overhang?: number, line?: number, onLayer?: (layer: number, layers: number) => void }} printer
|
|
364
|
+
* layer height, overhang limit (degrees from vertical), the line width; onLayer: called as each layer is cut (progress)
|
|
365
|
+
* @returns {{ islands: { z: number, area: number, at: number[], cells: number[][] }[], layers: number, overhang: number }}
|
|
366
|
+
* each island's layer (its z), its area (mm²), its centre, and its pixels' centres ([x, y], for whatever fixes it); how
|
|
367
|
+
* many layers were cut; and overhang: the area (mm²) of layers lying further out than the one below can hold, flat
|
|
368
|
+
* undersides included (the bridge check judges those separately)
|
|
369
|
+
*/
|
|
370
|
+
const SPANS = [5, 20]; // layers: the spans a lean is held over (see islands)
|
|
371
|
+
export function islands(polys, { layer = 0.2, overhang = 45, line = LINE, firstGap = 0, onLayer } = {}) {
|
|
372
|
+
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})`);
|
|
373
|
+
if (!polys.length) return { islands: [], layers: 0, overhang: 0 };
|
|
374
|
+
// The pixel: a quarter of a line, or coarser on a big part so a layer stays under about a million pixels
|
|
375
|
+
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;
|
|
376
|
+
const r2 = Math.max(1, Math.round(line / 2 / pitch)); // half a line, in pixels
|
|
377
|
+
// Pixels a layer may step out past the one below: its height times the tangent of the limit (measured from upright,
|
|
378
|
+
// so a wall leaning 45° steps out one layer's height each layer), and a line beyond that: a line hanging out is held
|
|
379
|
+
// by the one beside it
|
|
380
|
+
const step = layer * Math.tan((overhang * Math.PI) / 180), reach = Math.ceil(step / pitch) + 2 * r2;
|
|
381
|
+
// That line's grace is for a ledge, once. A wall that leans on, layer after layer, would take it every layer (at
|
|
382
|
+
// 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
|
|
383
|
+
// layers down, with the same single line's grace over the whole span: the longer a lean goes on, the nearer to the
|
|
384
|
+
// limit it is held.
|
|
385
|
+
const reachOver = SPANS.map((n) => Math.ceil((n * step) / pitch) + 2 * r2), history = [];
|
|
386
|
+
const tris = [];
|
|
387
|
+
for (const p of polys) for (let i = 1; i < p.length - 1; i++) tris.push([p[0], p[i], p[i + 1]]);
|
|
388
|
+
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]));
|
|
389
|
+
const count = Math.max(1, Math.round((hi[2] - lo[2]) / layer)), out = [];
|
|
390
|
+
// Each triangle filed under the layers whose middle it spans, so a layer looks only at its own
|
|
391
|
+
const byLayer = Array.from({ length: count }, () => []);
|
|
392
|
+
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);
|
|
393
|
+
let below = null, held = null, prev = null, counted = null, overhangArea = 0;
|
|
394
|
+
const fused = []; // on the first layer, regions nearer each other than firstGap: { at, gap } (the first layer spreads, and they print as one)
|
|
395
|
+
const px = (x) => Math.floor((x - lo[0]) / pitch) + 3;
|
|
396
|
+
// Only what the printer can lay counts: each layer is opened by half a line (eroded, then grown back), so anything
|
|
397
|
+
// narrower than a line, which the slicer drops, is not a region at all
|
|
398
|
+
// Square windows, by running sums along each row and then each column: any (grow) or all (shrink) within r pixels
|
|
399
|
+
const sweep = (f, r, all) => {
|
|
400
|
+
const tmp = new Uint8Array(nx * ny), out = new Uint8Array(nx * ny), w = 2 * r + 1, sum = new Int32Array(Math.max(nx, ny) + 1);
|
|
401
|
+
for (let j = 0; j < ny; j++) { // along x
|
|
402
|
+
const row = j * nx; sum[0] = 0;
|
|
403
|
+
for (let i = 0; i < nx; i++) sum[i + 1] = sum[i] + f[row + i];
|
|
404
|
+
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; }
|
|
405
|
+
}
|
|
406
|
+
for (let i = 0; i < nx; i++) { // then along y
|
|
407
|
+
sum[0] = 0;
|
|
408
|
+
for (let j = 0; j < ny; j++) sum[j + 1] = sum[j] + tmp[j * nx + i];
|
|
409
|
+
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; }
|
|
410
|
+
}
|
|
411
|
+
return out;
|
|
412
|
+
};
|
|
413
|
+
const erode = (f) => sweep(f, r2, true), dilate = (f, r) => sweep(f, r, false);
|
|
414
|
+
const opened = (f) => dilate(erode(f), r2);
|
|
415
|
+
for (let L = 0; L < count; L++) {
|
|
416
|
+
onLayer?.(L, count);
|
|
417
|
+
const z = lo[2] + (L + 0.5) * layer, segs = [];
|
|
418
|
+
for (const t of byLayer[L]) {
|
|
419
|
+
if (zmin[t] > z || zmax[t] < z) continue;
|
|
420
|
+
const pts = [];
|
|
421
|
+
for (let i = 0; i < 3; i++) {
|
|
422
|
+
const a = tris[t][i], b = tris[t][(i + 1) % 3];
|
|
423
|
+
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])]); }
|
|
424
|
+
}
|
|
425
|
+
if (pts.length === 2) segs.push(pts);
|
|
426
|
+
}
|
|
427
|
+
// Scanline fill, even-odd, a pixel row at a time
|
|
428
|
+
const raw = new Uint8Array(nx * ny);
|
|
429
|
+
for (let j = 0; j < ny; j++) {
|
|
430
|
+
const y = lo[1] + (j - 2.5) * pitch, xs = [];
|
|
431
|
+
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]));
|
|
432
|
+
xs.sort((p, q) => p - q);
|
|
433
|
+
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;
|
|
434
|
+
}
|
|
435
|
+
// A layer drawn the same as the one below (an upright wall, most of most parts) lies wholly on it: nothing to measure
|
|
436
|
+
let same = !!prev;
|
|
437
|
+
for (let n = 0; same && n < nx * ny; n++) if (raw[n] !== prev[n]) same = false;
|
|
438
|
+
prev = raw;
|
|
439
|
+
history.push(same ? below : null); // (filled in below, once this layer is drawn)
|
|
440
|
+
if (history.length > SPANS.at(-1) + 1) history[history.length - SPANS.at(-1) - 2] = null; // older layers are let go
|
|
441
|
+
if (same) continue;
|
|
442
|
+
const filled = opened(raw);
|
|
443
|
+
history[L] = filled;
|
|
444
|
+
if (L === 0 && firstGap > 0) {
|
|
445
|
+
// Each region labelled; grown by half the gap, two that meet were nearer than it. Where they meet is the spot
|
|
446
|
+
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 }; };
|
|
447
|
+
const own = label(filled), r = Math.max(1, Math.round(firstGap / 2 / pitch)), grown = label(dilate(filled, r));
|
|
448
|
+
if (own.n > 1) {
|
|
449
|
+
const seen = new Map(); // a grown region → the first own label in it, and the first pixel of a second
|
|
450
|
+
for (let e = 0; e < nx * ny; e++) {
|
|
451
|
+
if (!own.lab[e]) continue;
|
|
452
|
+
const g = grown.lab[e], first = seen.get(g);
|
|
453
|
+
if (first == null) seen.set(g, own.lab[e]);
|
|
454
|
+
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] });
|
|
455
|
+
}
|
|
456
|
+
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
|
|
457
|
+
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)];
|
|
458
|
+
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; }
|
|
459
|
+
x.gap = +(Math.max(0, d - 1) * pitch).toFixed(2); delete x.region;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (below) {
|
|
464
|
+
held = dilate(below, reach); // where this layer may lie: on the one below, or a step out from it
|
|
465
|
+
let unheld = 0;
|
|
466
|
+
for (let n = 0; n < nx * ny; n++) if (filled[n] && !held[n]) unheld++;
|
|
467
|
+
// A lean kept up over a span: what isn't straight above the layer below, and lies out past what the layer a
|
|
468
|
+
// span down allows. (What is straight above the layer below rests on it: the layers over a bridge, say.)
|
|
469
|
+
let leant = 0;
|
|
470
|
+
for (let k = 0; k < SPANS.length; k++) {
|
|
471
|
+
const far = L >= SPANS[k] ? history[L - SPANS[k]] : null;
|
|
472
|
+
if (!far || far === below) continue;
|
|
473
|
+
const heldOver = dilate(far, reachOver[k]);
|
|
474
|
+
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; }
|
|
475
|
+
}
|
|
476
|
+
counted = null;
|
|
477
|
+
overhangArea += (unheld + leant) * pitch * pitch;
|
|
478
|
+
// Regions of this layer that lie on nothing: an island is a region with no pixel within reach of the layer
|
|
479
|
+
// below, so only a region holding an unheld pixel can be one. Most layers have none, and are done here.
|
|
480
|
+
if (unheld) {
|
|
481
|
+
const seen = new Uint8Array(nx * ny), stack = new Int32Array(nx * ny);
|
|
482
|
+
for (let start = 0; start < nx * ny; start++) {
|
|
483
|
+
if (!filled[start] || held[start] || seen[start]) continue;
|
|
484
|
+
let top = 0, onSomething = false;
|
|
485
|
+
const cells = [];
|
|
486
|
+
stack[top++] = start; seen[start] = 1;
|
|
487
|
+
while (top) {
|
|
488
|
+
const e = stack[--top], i = e % nx;
|
|
489
|
+
cells.push(e);
|
|
490
|
+
if (held[e]) onSomething = true;
|
|
491
|
+
if (i + 1 < nx && filled[e + 1] && !seen[e + 1]) { seen[e + 1] = 1; stack[top++] = e + 1; }
|
|
492
|
+
if (i > 0 && filled[e - 1] && !seen[e - 1]) { seen[e - 1] = 1; stack[top++] = e - 1; }
|
|
493
|
+
if (e + nx < nx * ny && filled[e + nx] && !seen[e + nx]) { seen[e + nx] = 1; stack[top++] = e + nx; }
|
|
494
|
+
if (e >= nx && filled[e - nx] && !seen[e - nx]) { seen[e - nx] = 1; stack[top++] = e - nx; }
|
|
495
|
+
}
|
|
496
|
+
if (!onSomething) {
|
|
497
|
+
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;
|
|
498
|
+
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]) });
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
below = filled;
|
|
504
|
+
}
|
|
505
|
+
return { islands: out, layers: count, overhang: overhangArea, fused };
|
|
506
|
+
}
|
|
507
|
+
|
|
253
508
|
export function shape(polys, eps = 1e-3, drop = 0.05, hang = 1) {
|
|
254
509
|
const ids = new Map(), at = [], key = (v) => v.map((c) => Math.round(c / eps)).join(',');
|
|
255
510
|
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); }));
|