@rulecad/printcheck 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JoniBach and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # @rulecad/printcheck
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Is this mesh printable on an FDM printer? Hand it triangles and your printer's limits; get back findings in plain
4
+ words. No dependencies; browsers and Node 18+.
5
+
6
+ ```js
7
+ import { check } from '@rulecad/printcheck';
8
+
9
+ const printer = { bed: 256, overhang: 45, layer: 0.2, support_gap: 0.2, bridge: 5 };
10
+ const findings = check(triangles, printer);
11
+ // [{ level: 'pass', text: '20 × 4 × 12 mm, fits the bed' },
12
+ // { level: 'warn', text: 'an underside at z 10 starts in mid-air: needs support …' }, …]
13
+ ```
14
+
15
+ `triangles` is `[[[x, y, z], [x, y, z], [x, y, z]], …]` in millimetres, **Z up, the bed at z = 0**: the model is
16
+ checked as it will print, so its orientation is part of the design. Any CAD library's output works once
17
+ triangulated.
18
+
19
+ What it checks:
20
+
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.
23
+ - **Flat undersides above the bed**: each must start on something. Either it rests on a built-in **breakaway support**
24
+ (one `support_gap` below a surface), or it **bridges** no wider than `bridge` mm. The bridge is the widest circle that
25
+ fits in the underside, measured to the edges held up by material below. An underside held by nothing starts in
26
+ mid-air.
27
+ - **Closed solid**: every edge is matched by a face on the other side. T-junctions count as closed, and so do hairline
28
+ seams narrower than `HAIRLINE` (0.01 mm), which booleans leave and no printer can resolve. Wider gaps are holes.
29
+
30
+ Several parts printed together (a keycap with an inlaid legend in another colour): pass
31
+ `{ parts: [{ triangles, role }] }`. Then one part resting on another isn't an overhang, and each part must be closed on
32
+ its own. A part with `role: 'support'` is printed and then removed.
33
+
34
+ Also exported: `bounds(triangles)` (`{ lo, hi, size }`), `seams(triangles)` (`{ gaps, tjunctions, hairlines }`) and
35
+ `widest(polys, held, under)` (the bridge measurement).
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@rulecad/printcheck",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Is this mesh printable? Bed fit, flat base, overhangs, bridges, breakaway supports and watertightness, for any FDM printer.",
5
+ "type": "module",
6
+ "exports": {
7
+ "types": "./printcheck.d.mts",
8
+ "default": "./printcheck.mjs"
9
+ },
10
+ "files": [
11
+ "printcheck.mjs",
12
+ "printcheck.d.mts",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "license": "MIT",
17
+ "keywords": [
18
+ "3d-printing",
19
+ "fdm",
20
+ "mesh",
21
+ "printability",
22
+ "stl"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "sideEffects": false,
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/JoniBach/rulecad.git",
31
+ "directory": "packages/printcheck"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test"
35
+ },
36
+ "types": "./printcheck.d.mts"
37
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The box around faces.
3
+ * @param {Face[]} polys
4
+ * @returns {{ lo: Point, hi: Point, size: Point }}
5
+ */
6
+ /** @typedef {[number, number, number]} Point a corner in mm, Z up */
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 */
9
+ /** @typedef {{ level: 'pass' | 'warn' | 'fail', text: string }} Finding */
10
+ export function bounds(polys: any): {
11
+ lo: number[];
12
+ hi: number[];
13
+ size: number[];
14
+ };
15
+ /**
16
+ * Is it printable? Findings in plain words, each pass, warn or fail.
17
+ * @param {Face[]} polys the model as faces (triangles are fine), Z up, the bed at z = 0
18
+ * @param {Printer} printer the printer's limits
19
+ * @param {{ eps?: number, parts?: { triangles: Face[], role?: 'part' | 'support' }[] }} [options]
20
+ * @returns {Finding[]}
21
+ */
22
+ export function check(polys: Face[], printer: Printer, { eps, parts }?: {
23
+ eps?: number;
24
+ parts?: {
25
+ triangles: Face[];
26
+ role?: "part" | "support";
27
+ }[];
28
+ }): Finding[];
29
+ /**
30
+ * The widest circle that fits in an underside, measured to its held-up edges (the bridge it makes).
31
+ * @param {Face[]} polys @param {(edge: [Point, Point]) => boolean} [held] @param {Face[]} [under]
32
+ * @returns {number} mm
33
+ */
34
+ export function widest(polys: Face[], held?: (edge: [Point, Point]) => boolean, under?: Face[]): number;
35
+ /**
36
+ * Open edges, sorted: real gaps, T-junctions (closed) and hairline seams (closed).
37
+ * @param {Face[]} polys @param {number} [eps]
38
+ * @returns {{ gaps: number, tjunctions: number, hairlines: number }}
39
+ */
40
+ export function seams(polys: Face[], eps?: number): {
41
+ gaps: number;
42
+ tjunctions: number;
43
+ hairlines: number;
44
+ };
45
+ export const HAIRLINE: 0.01;
46
+ /**
47
+ * a corner in mm, Z up
48
+ */
49
+ export type Point = [number, number, number];
50
+ /**
51
+ * a polygon: three or more corners, counter-clockwise seen from outside
52
+ */
53
+ export type Face = Point[];
54
+ /**
55
+ * mm and degrees
56
+ */
57
+ export type Printer = {
58
+ bed: number;
59
+ overhang: number;
60
+ layer?: number;
61
+ support_gap?: number;
62
+ bridge?: number;
63
+ };
64
+ export type Finding = {
65
+ level: "pass" | "warn" | "fail";
66
+ text: string;
67
+ };
package/printcheck.mjs ADDED
@@ -0,0 +1,220 @@
1
+ // Printability, from the faces and the printer's rules. Each finding is { level: 'fail' | 'warn' | 'pass', text }.
2
+ // fits the bed · sits flat on it · a closed solid (slicers need one) · overhangs past the printer's limit
3
+ // flat undersides above the bed: on a built-in breakaway support (one support gap above a surface), or bridges no
4
+ // wider than the printer can span: the widest circle that fits in the underside, measured to the edges that are
5
+ // held up by material below. An underside with no such edge starts in mid-air: it needs support.
6
+ // 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.
7
+
8
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
9
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
10
+
11
+ // Area-weighted normal of a planar polygon (its length is twice the area).
12
+ function areaNormal(poly) {
13
+ let n = [0, 0, 0];
14
+ 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]);
15
+ return n;
16
+ }
17
+
18
+ const OVERHANG_SLACK = 0.5; // degrees
19
+
20
+ /**
21
+ * The box around faces.
22
+ * @param {Face[]} polys
23
+ * @returns {{ lo: Point, hi: Point, size: Point }}
24
+ */
25
+ /** @typedef {[number, number, number]} Point a corner in mm, Z up */
26
+ /** @typedef {Point[]} Face a polygon: three or more corners, counter-clockwise seen from outside */
27
+ /** @typedef {{ bed: number, overhang: number, layer?: number, support_gap?: number, bridge?: number }} Printer mm and degrees */
28
+ /** @typedef {{ level: 'pass' | 'warn' | 'fail', text: string }} Finding */
29
+
30
+ export function bounds(polys) {
31
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; // a loop: spreading big models overflows the stack
32
+ 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]; }
33
+ return { lo, hi, size: hi.map((h, k) => h - lo[k]) };
34
+ }
35
+
36
+ // parts ([{ triangles, role }]): when parts print together (a keycap and its inlaid legend), an underside resting on
37
+ // another part isn't an overhang, and each part must be closed on its own (their shared faces are inside the print).
38
+ // printer: the printer's rules, any printer: { bed, overhang (degrees), layer, support_gap?, bridge? } in mm.
39
+ /**
40
+ * Is it printable? Findings in plain words, each pass, warn or fail.
41
+ * @param {Face[]} polys the model as faces (triangles are fine), Z up, the bed at z = 0
42
+ * @param {Printer} printer the printer's limits
43
+ * @param {{ eps?: number, parts?: { triangles: Face[], role?: 'part' | 'support' }[] }} [options]
44
+ * @returns {Finding[]}
45
+ */
46
+ export function check(polys, printer, { eps = 1e-3, parts = null } = {}) {
47
+ const out = [], f = (level, text) => out.push({ level, text });
48
+ const solids = (parts || []).filter((p) => p.role !== 'support').map((p) => ({ tris: p.triangles, box: bounds(p.triangles) }));
49
+ // Is the point inside one of the parts? A ray straight up crosses its surface an odd number of times
50
+ const inPart = (pt) => solids.length > 1 && solids.some(({ tris, box }) => {
51
+ if (pt.some((c, k) => c < box.lo[k] - eps || c > box.hi[k] + eps)) return false;
52
+ let n = 0;
53
+ for (const t of tris) for (let i = 1; i < t.length - 1; i++) {
54
+ 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]);
55
+ if (Math.abs(d) < 1e-12) continue;
56
+ 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;
57
+ if (u < 0 || v < 0 || u + v > 1) continue;
58
+ if (a[2] + u * (b[2] - a[2]) + v * (c[2] - a[2]) > pt[2]) n++;
59
+ }
60
+ return n % 2 === 1;
61
+ });
62
+ 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]); };
63
+ const { lo, size } = bounds(polys);
64
+ const mm = (n) => `${Number(n.toFixed(1))}`;
65
+
66
+ const over = size.filter((s) => s > printer.bed);
67
+ f(over.length ? 'fail' : 'pass', `${size.map(mm).join(' × ')} mm${over.length ? `: bigger than the ${printer.bed} mm bed` : ', fits the bed'}`);
68
+
69
+ // Flat on the bed: the lowest point is z = 0, and faces there point straight down.
70
+ let base = 0, down = 0, support = 0, zs = [];
71
+ const flatDown = [], flatUp = [];
72
+ // A face overhanging past the limit (measured from vertical) points down by more than its sine; half a degree to
73
+ // spare, since booleans tip a 45° chamfer by hundredths of a degree. (Cosine was used before: the same at 45° only.)
74
+ const limit = Math.sin(((printer.overhang + OVERHANG_SLACK) * Math.PI) / 180);
75
+ for (const p of polys) {
76
+ const n = areaNormal(p), area = Math.hypot(...n) / 2, nz = n[2] / (2 * area || 1);
77
+ const longest = Math.max(...p.map((v, i) => Math.hypot(...sub(p[(i + 1) % p.length], v))));
78
+ if (2 * area / (longest || 1) < HAIRLINE) continue; // a sliver thinner than a hairline (corners nearly in a line, left by a boolean) faces nowhere
79
+ const zmin = Math.min(...p.map((v) => v[2])), zmax = Math.max(...p.map((v) => v[2]));
80
+ if (nz < -eps && zmax - lo[2] > eps && rests(p)) continue; // on another part (a legend on its keycap)
81
+ if (nz < -1 + eps && zmax - lo[2] < eps) base += area;
82
+ else if (nz < -1 + eps) flatDown.push({ p, z: zmin, area }); // a flat underside above the bed
83
+ else if (nz < -limit) { support += area; zs.push(zmin); }
84
+ if (nz > 1 - eps) flatUp.push({ p, z: zmax });
85
+ if (nz < 0) down += area;
86
+ }
87
+ if (Math.abs(lo[2]) > eps) f('fail', `lowest point is at z = ${mm(lo[2])} mm, not on the bed (z = 0)`);
88
+ f(base > 0 ? 'pass' : 'fail', base > 0 ? `${mm(base)} mm² flat on the bed` : 'nothing sits flat on the bed');
89
+ if (support > 0.5) f('warn', `${mm(support)} mm² overhangs past ${printer.overhang}° (z ${mm(Math.min(...zs))} to ${mm(Math.max(...zs))} mm): needs supports or another orientation`);
90
+ else f('pass', `no overhangs past ${printer.overhang}°`);
91
+
92
+ // Flat undersides: on a breakaway support, or bridged
93
+ const gap = printer.support_gap ?? 0.2, inside = (pt, poly) => { // point in the xy footprint of a convex face
94
+ let sign = 0;
95
+ for (let i = 0; i < poly.length; i++) {
96
+ 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]);
97
+ if (Math.abs(c) < 1e-9) continue; if (sign && Math.sign(c) !== sign) return false; sign = Math.sign(c);
98
+ }
99
+ return true;
100
+ };
101
+ const centroid = (p) => [0, 1].map((k) => p.reduce((s, v) => s + v[k], 0) / p.length);
102
+ const held = flatDown.filter((d) => flatUp.some((u) => d.z - u.z > eps && d.z - u.z <= gap * 1.5 + eps && inside(centroid(d.p), u.p)));
103
+ 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`);
104
+ const levels = new Map();
105
+ for (const d of flatDown) if (!held.includes(d)) { const k = d.z.toFixed(2); levels.set(k, [...(levels.get(k) || []), d.p]); }
106
+ // Which faces meet at each edge, so an underside's edges can be checked for material below them
107
+ const vkey = (v) => v.map((c) => Math.round(c / eps)).join(','), byEdge = new Map();
108
+ for (const p of polys) p.forEach((a, i) => { const k = [vkey(a), vkey(p[(i + 1) % p.length])].sort().join('|'); byEdge.set(k, [...(byEdge.get(k) || []), p]); });
109
+ const bridgeMax = printer.bridge ?? 5;
110
+ for (const [z, group] of levels) {
111
+ const mine = new Set(group);
112
+ const held = (a, b) => (byEdge.get([vkey(a), vkey(b)].sort().join('|')) || []).some((p) => !mine.has(p) && Math.min(...p.map((v) => v[2])) < Number(z) - eps);
113
+ const under = flatUp.filter((u) => Number(z) - u.z > eps && Number(z) - u.z <= gap * 1.5 + eps).map((u) => u.p); // breakaway supports' tops
114
+ const span = widest(group, held, under);
115
+ if (span == null) f('warn', `an underside at z ${mm(Number(z))} starts in mid-air: needs support (or a built-in breakaway support one ${mm(gap)} mm layer below)`);
116
+ 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`);
117
+ else f('pass', `bridge ${mm(span)} mm at z ${mm(Number(z))} (up to ${bridgeMax} mm)`);
118
+ }
119
+
120
+ // Closed: every edge is matched by an edge running the other way. An edge that meets the middle of a longer edge
121
+ // (a T-junction, left by booleans) is still closed if the edges along the other side cover it exactly.
122
+ const { gaps, tjunctions, hairlines } = parts && parts.length > 1
123
+ ? 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 })
124
+ : seams(polys, eps);
125
+ if (gaps) f('warn', `${gaps} edges with nothing on the other side: holes in the surface (slicers may repair them)`);
126
+ 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)` : ''}`);
127
+ return out;
128
+ }
129
+
130
+ // The widest circle that fits in a flat region made of faces, measured to the outline edges that are held up
131
+ // (held(a, b) -> true), or to the tops of breakaway supports one layer below (under: faces): its diameter in mm, the
132
+ // gap a bridge has to span. null if nothing holds it up.
133
+ // Sampled: points spread over each face, each measured to the held edges of the region's outline and to the supports.
134
+ /**
135
+ * The widest circle that fits in an underside, measured to its held-up edges (the bridge it makes).
136
+ * @param {Face[]} polys @param {(edge: [Point, Point]) => boolean} [held] @param {Face[]} [under]
137
+ * @returns {number} mm
138
+ */
139
+ export function widest(polys, held = () => true, under = []) {
140
+ const key = (v) => `${v[0].toFixed(3)},${v[1].toFixed(3)}`, count = new Map(), edges = [];
141
+ 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]); });
142
+ const outline = edges.filter(([k]) => count.get(k) === 1).map(([, a, b]) => [a, b]).filter(([a, b]) => held(a, b));
143
+ const tops = under.flatMap((p) => p.map((a, i) => [a, p[(i + 1) % p.length]]));
144
+ if (!outline.length && !tops.length) return null;
145
+ 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; });
146
+ const toSeg = (pt, [a, b]) => {
147
+ 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;
148
+ return Math.hypot(pt[0] - a[0] - t * dx, pt[1] - a[1] - t * dy);
149
+ };
150
+ let best = 0;
151
+ const N = 6;
152
+ for (const p of polys) for (let i = 1; i < p.length - 1; i++) {
153
+ const [a, b, c] = [p[0], p[i], p[i + 1]];
154
+ for (let u = 0; u <= N; u++) for (let v = 0; u + v <= N; v++) {
155
+ const w = N - u - v, pt = [0, 1].map((k) => (a[k] * u + b[k] * v + c[k] * w) / N);
156
+ if (onTop(pt)) continue; // right over a support
157
+ let d = Infinity;
158
+ for (const s of outline) d = Math.min(d, toSeg(pt, s));
159
+ for (const s of tops) d = Math.min(d, toSeg(pt, s));
160
+ best = Math.max(best, d);
161
+ }
162
+ }
163
+ return 2 * best;
164
+ }
165
+
166
+ // seams(polys) -> { gaps, tjunctions, hairlines }: edges not matched by a reverse edge, split into T-junctions (covered
167
+ // all along by reverse edges on the same line, or lying along a longer reverse edge), hairlines (within HAIRLINE of
168
+ // another face) and real gaps.
169
+ export const HAIRLINE = 0.01; // mm: a fortieth of a print line
170
+ 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];
171
+ function pointToTriangle(p, a, b, c) { // Ericson, Real-Time Collision Detection 5.1.5
172
+ const ab = vsub(b, a), ac = vsub(c, a), ap = vsub(p, a), d1 = vdot(ab, ap), d2 = vdot(ac, ap);
173
+ 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);
174
+ if (d1 <= 0 && d2 <= 0) return at(a);
175
+ const bp = vsub(p, b), d3 = vdot(ab, bp), d4 = vdot(ac, bp);
176
+ if (d3 >= 0 && d4 <= d3) return at(b);
177
+ const vc = d1 * d4 - d3 * d2;
178
+ if (vc <= 0 && d1 >= 0 && d3 <= 0) { const v = d1 / (d1 - d3); return at(mix(1 - v, v, 0)); }
179
+ const cp = vsub(p, c), d5 = vdot(ab, cp), d6 = vdot(ac, cp);
180
+ if (d6 >= 0 && d5 <= d6) return at(c);
181
+ const vb = d5 * d2 - d1 * d6;
182
+ if (vb <= 0 && d2 >= 0 && d6 <= 0) { const w = d2 / (d2 - d6); return at(mix(1 - w, 0, w)); }
183
+ const va = d3 * d6 - d5 * d4;
184
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { const w = (d4 - d3) / (d4 - d3 + (d5 - d6)); return at(mix(0, 1 - w, w)); }
185
+ const den = 1 / (va + vb + vc);
186
+ return at(mix(1 - vb * den - vc * den, vb * den, vc * den));
187
+ }
188
+ /**
189
+ * Open edges, sorted: real gaps, T-junctions (closed) and hairline seams (closed).
190
+ * @param {Face[]} polys @param {number} [eps]
191
+ * @returns {{ gaps: number, tjunctions: number, hairlines: number }}
192
+ */
193
+ export function seams(polys, eps = 1e-3) {
194
+ const key = (v) => v.map((c) => Math.round(c / eps)).join(','), segs = [], count = new Map();
195
+ 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); } });
196
+ const d = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
197
+ const on = (p, a, b) => Math.abs(d(a, p) + d(p, b) - d(a, b)) < eps;
198
+ // A seam whose middle lies within HAIRLINE of another face (not one of its own) is a hairline left by booleans, far
199
+ // narrower than anything the printer can make: closed, for printing
200
+ const tris = polys.flatMap((t) => t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]]));
201
+ const hairline = (a, b) => {
202
+ 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));
203
+ return tris.some((t) => !own(t) && pointToTriangle(mid, ...t) < HAIRLINE);
204
+ };
205
+ let gaps = 0, tjunctions = 0, hairlines = 0;
206
+ for (const [a, b] of segs) {
207
+ if ((count.get(`${key(b)}|${key(a)}`) || 0) > 0) continue;
208
+ // Reverse pieces on this edge, as stretches of it from b (0) to a (1): together they must cover all of it. They may
209
+ // overlap (booleans can cut the faces on the other side in more than one way), so it's their union that counts.
210
+ 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]);
211
+ let reach = 0;
212
+ for (const [from, to] of along) { if (from > reach + eps / len * 10) break; reach = Math.max(reach, to); }
213
+ const covered = along.length > 0 && reach >= 1 - eps / len * 10;
214
+ 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
215
+ if (covered || within) tjunctions++;
216
+ else if (hairline(a, b)) hairlines++;
217
+ else gaps++;
218
+ }
219
+ return { gaps, tjunctions, hairlines };
220
+ }