stljoiner 0.2.1__py3-none-any.whl

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.
stljoiner/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """stljoiner: reassemble split STL parts by matching their mating faces."""
2
+ from stljoiner.version import __version__
3
+
4
+ __all__ = ["__version__"]
stljoiner/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from stljoiner.cli import main
2
+
3
+ raise SystemExit(main())
stljoiner/cli.py ADDED
@@ -0,0 +1,23 @@
1
+ """The `stljoiner` command.
2
+
3
+ stljoiner PART.stl PART.stl ... [-o joined.stl] join parts automatically
4
+ stljoiner web [--port 4300] start the web interface
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import sys
9
+
10
+
11
+ def main(argv: list[str] | None = None) -> int:
12
+ args = sys.argv[1:] if argv is None else list(argv)
13
+ if args and args[0] == "web":
14
+ from stljoiner import web # Flask is only loaded for the web interface
15
+
16
+ return web.main(args[1:])
17
+ from stljoiner import join
18
+
19
+ return join.main(args)
20
+
21
+
22
+ if __name__ == "__main__":
23
+ raise SystemExit(main())
stljoiner/join.py ADDED
@@ -0,0 +1,651 @@
1
+ """stljoiner - reassemble split STL parts by matching their mating faces.
2
+
3
+ Given several STL files that were cut from one part (e.g. split to fit a
4
+ print bed), stljoin finds the planar faces that mate with each other,
5
+ computes the rigid transform that puts each part back in place, and writes
6
+ a single combined mesh (boolean union by default).
7
+
8
+ Parts can be scattered, rotated or flipped; the alignment is found from the
9
+ shape of the cut faces alone. If the parts are already in place, that
10
+ placement is detected and kept.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import math
16
+ import sys
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import trimesh
22
+ from shapely import affinity
23
+ from shapely.geometry import Polygon
24
+ from shapely.ops import unary_union
25
+
26
+ from stljoiner.version import __version__
27
+
28
+ # --------------------------------------------------------------------------
29
+ # Data structures
30
+ # --------------------------------------------------------------------------
31
+
32
+ @dataclass
33
+ class Face:
34
+ """A planar region of a part that could be a mating (cut) face."""
35
+ part: int
36
+ index: int
37
+ normal: np.ndarray # outward unit normal
38
+ centroid: np.ndarray # area-weighted 3D centroid
39
+ area: float
40
+ perimeter: float
41
+ vertices3d: np.ndarray # vertices of the region's triangles (n,3)
42
+ triangles: np.ndarray # (m,3,3) triangle coordinates
43
+ basis: np.ndarray = field(default=None) # (2,3) in-plane axes
44
+ polygon: Polygon = field(default=None) # outline in (basis) coords, centered on centroid
45
+ tri_index: np.ndarray = field(default=None) # the mesh triangles this face is made of
46
+
47
+
48
+ @dataclass
49
+ class Match:
50
+ a: Face
51
+ b: Face
52
+ iou: float
53
+ transform: np.ndarray # 4x4: moves part b so face b sits on face a
54
+ ambiguous: bool # other rotations fit nearly as well (symmetric face)
55
+ in_place: bool # parts already touch at this face
56
+
57
+ @property
58
+ def score(self) -> float:
59
+ return self.iou * math.sqrt(min(self.a.area, self.b.area))
60
+
61
+
62
+ # --------------------------------------------------------------------------
63
+ # Geometry helpers
64
+ # --------------------------------------------------------------------------
65
+
66
+ def plane_basis(normal: np.ndarray) -> np.ndarray:
67
+ """Two orthonormal in-plane axes for a plane with the given normal."""
68
+ helper = np.array([1.0, 0, 0]) if abs(normal[0]) < 0.9 else np.array([0, 1.0, 0])
69
+ u = np.cross(normal, helper)
70
+ u /= np.linalg.norm(u)
71
+ v = np.cross(normal, u)
72
+ return np.vstack([u, v])
73
+
74
+
75
+ def rotation_between(a: np.ndarray, b: np.ndarray) -> np.ndarray:
76
+ """3x3 rotation taking unit vector a onto unit vector b."""
77
+ a = a / np.linalg.norm(a)
78
+ b = b / np.linalg.norm(b)
79
+ c = float(np.dot(a, b))
80
+ if c > 1 - 1e-12:
81
+ return np.eye(3)
82
+ if c < -1 + 1e-12:
83
+ # 180 degrees about any axis perpendicular to a
84
+ axis = plane_basis(a)[0]
85
+ return trimesh.transformations.rotation_matrix(math.pi, axis)[:3, :3]
86
+ axis = np.cross(a, b)
87
+ angle = math.atan2(np.linalg.norm(axis), c)
88
+ return trimesh.transformations.rotation_matrix(angle, axis)[:3, :3]
89
+
90
+
91
+ def project_polygon(triangles: np.ndarray, origin: np.ndarray, basis: np.ndarray) -> Polygon:
92
+ """Union of triangles projected into a 2D frame -> outline polygon (with holes)."""
93
+ pts = (triangles - origin) @ basis.T # (m,3,2)
94
+ polys = [Polygon(t) for t in pts]
95
+ polys = [p.buffer(0) for p in polys if p.area > 0]
96
+ if not polys:
97
+ return Polygon()
98
+ # A tiny dilate/erode closes slivers between triangles from float noise.
99
+ eps = 1e-6 * max(1.0, math.sqrt(sum(p.area for p in polys)))
100
+ return unary_union([p.buffer(eps) for p in polys]).buffer(-eps)
101
+
102
+
103
+ def iou(p: Polygon, q: Polygon) -> float:
104
+ if p.is_empty or q.is_empty:
105
+ return 0.0
106
+ inter = p.intersection(q).area
107
+ union = p.area + q.area - inter
108
+ return inter / union if union > 0 else 0.0
109
+
110
+
111
+ # --------------------------------------------------------------------------
112
+ # Face extraction
113
+ # --------------------------------------------------------------------------
114
+
115
+ def extract_faces(mesh: trimesh.Trimesh, part: int, max_faces: int, min_area_frac: float) -> list[Face]:
116
+ """Find the largest planar regions of a mesh: candidates for cut faces."""
117
+ groups = coplanar_groups(mesh)
118
+
119
+ areas = np.array([mesh.area_faces[g].sum() for g in groups])
120
+ order = np.argsort(-areas)
121
+ total = mesh.area
122
+ faces: list[Face] = []
123
+ for gi in order:
124
+ if len(faces) >= max_faces or areas[gi] < min_area_frac * total:
125
+ break
126
+ f = make_face(mesh, part, groups[gi], len(faces))
127
+ if f is not None:
128
+ faces.append(f)
129
+ return faces
130
+
131
+
132
+ def make_face(mesh: trimesh.Trimesh, part: int, tri_idx: np.ndarray, index: int = 0) -> Face | None:
133
+ """Build a Face from a set of (coplanar) triangle indices."""
134
+ g = np.asarray(tri_idx)
135
+ tri = mesh.triangles[g]
136
+ a = mesh.area_faces[g]
137
+ normal = (mesh.face_normals[g] * a[:, None]).sum(0)
138
+ normal /= np.linalg.norm(normal)
139
+ centroid = (mesh.triangles_center[g] * a[:, None]).sum(0) / a.sum()
140
+ basis = plane_basis(normal)
141
+ poly = project_polygon(tri, centroid, basis)
142
+ if poly.is_empty:
143
+ return None
144
+ return Face(part=part, index=index, normal=normal, centroid=centroid,
145
+ area=float(a.sum()), perimeter=float(poly.length),
146
+ vertices3d=tri.reshape(-1, 3), triangles=tri, basis=basis, polygon=poly, tri_index=g)
147
+
148
+
149
+ def coplanar_groups(mesh: trimesh.Trimesh) -> list[np.ndarray]:
150
+ """Triangle indices grouped by the plane they lie on.
151
+
152
+ Separate flat islands on the same plane form one group: a cut through a
153
+ hole or slot leaves several islands that together make one cut face.
154
+ """
155
+ if "coplanar_groups" in mesh._cache.cache:
156
+ return mesh._cache.cache["coplanar_groups"]
157
+ regions = [np.asarray(f) for f in mesh.facets]
158
+ in_facet = np.zeros(len(mesh.faces), dtype=bool)
159
+ for g in regions:
160
+ in_facet[g] = True
161
+ # Lone triangles count as planar regions too (e.g. a triangular cut face).
162
+ regions += [np.array([i]) for i in np.nonzero(~in_facet)[0]]
163
+
164
+ scale = max(float(mesh.scale), 1e-9)
165
+ buckets: dict[tuple, list[np.ndarray]] = {}
166
+ for g in regions:
167
+ a = mesh.area_faces[g]
168
+ n = (mesh.face_normals[g] * a[:, None]).sum(0)
169
+ norm = np.linalg.norm(n)
170
+ if norm == 0:
171
+ continue
172
+ n /= norm
173
+ d = float(np.dot(n, mesh.triangles_center[g[0]]))
174
+ key = (*np.round(n, 3).tolist(), round(d / (1e-4 * scale)))
175
+ buckets.setdefault(key, []).append(g)
176
+ groups = [np.concatenate(gs) for gs in buckets.values()]
177
+ mesh._cache.cache["coplanar_groups"] = groups
178
+ return groups
179
+
180
+
181
+ def planar_region(mesh: trimesh.Trimesh, triangle: int) -> np.ndarray:
182
+ """Indices of all triangles on the same plane as `triangle`."""
183
+ for g in coplanar_groups(mesh):
184
+ if triangle in g:
185
+ return g
186
+ return np.array([triangle])
187
+
188
+
189
+ # --------------------------------------------------------------------------
190
+ # Face matching
191
+ # --------------------------------------------------------------------------
192
+
193
+ def rotation_fits(fa: Face, fb: Face, coarse_step: float = 2.0) -> list[tuple[float, float]]:
194
+ """All distinct in-plane rotations (degrees) placing face b on face a.
195
+
196
+ Returns [(theta, iou), ...] sorted best first: one entry per local
197
+ optimum, so a symmetric face (e.g. a rectangle) yields several.
198
+ """
199
+ # R0 turns B so its face normal points opposite A's (faces touching).
200
+ r0 = rotation_between(fb.normal, -fa.normal)
201
+ tri_b = (fb.triangles - fb.centroid) @ r0.T # B's face, centered, in world orientation
202
+ poly_b = project_polygon(tri_b, np.zeros(3), fa.basis)
203
+ if poly_b.is_empty:
204
+ return []
205
+
206
+ def score_at(theta_deg: float) -> float:
207
+ return iou(fa.polygon, affinity.rotate(poly_b, theta_deg, origin=(0, 0)))
208
+
209
+ angles = np.arange(0, 360, coarse_step)
210
+ scores = np.array([score_at(t) for t in angles])
211
+ # Local maxima of the circular score curve are the candidate rotations.
212
+ peaks = [i for i in range(len(scores))
213
+ if scores[i] >= scores[i - 1] and scores[i] >= scores[(i + 1) % len(scores)] and scores[i] > 0]
214
+ peaks = sorted(peaks, key=lambda i: -scores[i])[:8]
215
+
216
+ fits: list[tuple[float, float]] = []
217
+ for idx in peaks:
218
+ lo, hi = angles[idx] - coarse_step, angles[idx] + coarse_step
219
+ best, best_theta = scores[idx], float(angles[idx])
220
+ for _ in range(3): # successive grid refinement
221
+ grid = np.linspace(lo, hi, 9)
222
+ s = [score_at(t) for t in grid]
223
+ k = int(np.argmax(s))
224
+ span = (hi - lo) / 8
225
+ lo, hi = grid[k] - span, grid[k] + span
226
+ if s[k] > best:
227
+ best, best_theta = s[k], float(grid[k])
228
+ theta = best_theta % 360
229
+ if all(abs(((theta - t + 180) % 360) - 180) > 2 * coarse_step for t, *_ in fits):
230
+ fits.append((theta, float(best)))
231
+ fits.sort(key=lambda f: -f[1])
232
+ # Snap each rotation exactly onto the outline vertices.
233
+ a_pts = outline_points(fa.polygon)
234
+ b_pts = outline_points(poly_b)
235
+ return [(theta, score, *refine_2d(a_pts, b_pts, theta)) for theta, score in fits]
236
+
237
+
238
+ def outline_points(poly) -> np.ndarray:
239
+ geoms = getattr(poly, "geoms", [poly])
240
+ pts = [np.asarray(r.coords) for g in geoms for r in [g.exterior, *g.interiors]]
241
+ return np.vstack(pts) if pts else np.zeros((0, 2))
242
+
243
+
244
+ def refine_2d(a_pts: np.ndarray, b_pts: np.ndarray, theta: float, iters: int = 30) -> tuple[float, float]:
245
+ """Snap outline b onto outline a with 2D ICP, starting from rotation `theta`.
246
+
247
+ Returns (rotation correction in degrees, in-plane offset of b's centroid)."""
248
+ from scipy.spatial import cKDTree
249
+ if len(a_pts) < 3 or len(b_pts) < 3:
250
+ return (0.0, np.zeros(2))
251
+ tree = cKDTree(a_pts)
252
+ t = math.radians(theta)
253
+ R = np.array([[math.cos(t), -math.sin(t)], [math.sin(t), math.cos(t)]])
254
+ off = np.zeros(2)
255
+ tol = 0.05 * math.sqrt(max(np.ptp(a_pts, axis=0).prod(), 1e-12))
256
+ for _ in range(iters):
257
+ moved = b_pts @ R.T + off
258
+ dist, idx = tree.query(moved)
259
+ keep = dist < tol
260
+ if keep.sum() < 3:
261
+ break
262
+ src, dst = b_pts[keep], a_pts[idx[keep]]
263
+ sc, dc = src.mean(0), dst.mean(0)
264
+ H = (src - sc).T @ (dst - dc)
265
+ U, _, Vt = np.linalg.svd(H)
266
+ Rn = Vt.T @ U.T
267
+ if np.linalg.det(Rn) < 0:
268
+ Vt[-1] *= -1
269
+ Rn = Vt.T @ U.T
270
+ off_n = dc - Rn @ sc
271
+ done = np.allclose(Rn, R, atol=1e-12) and np.allclose(off_n, off, atol=1e-12)
272
+ R, off = Rn, off_n
273
+ if done:
274
+ break
275
+ dtheta = math.degrees(math.atan2(R[1, 0], R[0, 0])) - theta
276
+ return (dtheta, off)
277
+
278
+
279
+ def placement(fa: Face, fb: Face, theta: float, dtheta: float = 0.0, offset=(0.0, 0.0)) -> np.ndarray:
280
+ """4x4 transform putting face b against face a, rotated theta degrees in-plane
281
+ (plus an optional exact correction dtheta and in-plane offset from refine_2d)."""
282
+ r0 = rotation_between(fb.normal, -fa.normal)
283
+ r_theta = trimesh.transformations.rotation_matrix(math.radians(theta + dtheta), fa.normal)[:3, :3]
284
+ rot = r_theta @ r0
285
+ T = np.eye(4)
286
+ T[:3, :3] = rot
287
+ T[:3, 3] = fa.centroid + np.asarray(offset) @ fa.basis - rot @ fb.centroid
288
+ return T
289
+
290
+
291
+ def match_faces(fa: Face, fb: Face, mesh_b: trimesh.Trimesh, tol: float, coarse_step: float = 2.0) -> list[Match]:
292
+ """All ways to place face b of part B onto face a of part A.
293
+
294
+ Returns one Match per rotation that fits (several for a symmetric face),
295
+ best first; empty if the outlines don't agree.
296
+ """
297
+ # Cheap rejections: area and perimeter must agree.
298
+ if abs(fa.area - fb.area) > tol * max(fa.area, fb.area):
299
+ return []
300
+ if abs(fa.perimeter - fb.perimeter) > 2 * tol * max(fa.perimeter, fb.perimeter):
301
+ return []
302
+
303
+ fits = [f for f in rotation_fits(fa, fb, coarse_step) if f[1] >= 1 - tol]
304
+ center_b = mesh_b.center_mass if mesh_b.is_volume else mesh_b.centroid
305
+ matches = []
306
+ for theta, score, dtheta, offset in fits:
307
+ T = placement(fa, fb, theta, dtheta, offset)
308
+ # B's body must end up on the far side of the face, not inside A.
309
+ if np.dot(trimesh.transform_points([center_b], T)[0] - fa.centroid, fa.normal) <= 0:
310
+ continue
311
+ in_place = bool(np.allclose(T, np.eye(4), atol=max(1e-3, 1e-4 * math.sqrt(fa.area))))
312
+ matches.append(Match(a=fa, b=fb, iou=score, transform=T, ambiguous=len(fits) > 1, in_place=in_place))
313
+ return matches
314
+
315
+
316
+ def already_in_place(fa: Face, fb: Face, tol: float) -> Match | None:
317
+ """Parts that already touch at coincident, opposed faces need no motion."""
318
+ if np.dot(fa.normal, fb.normal) > -0.999:
319
+ return None
320
+ gap = abs(np.dot(fb.centroid - fa.centroid, fa.normal))
321
+ scale = math.sqrt(max(fa.area, fb.area))
322
+ if gap > 1e-3 * scale + 1e-4:
323
+ return None
324
+ poly_b = project_polygon(fb.triangles, fa.centroid, fa.basis)
325
+ s = iou(fa.polygon, poly_b)
326
+ if s < 1 - tol:
327
+ return None
328
+ return Match(a=fa, b=fb, iou=s, transform=np.eye(4), ambiguous=False, in_place=True)
329
+
330
+
331
+ def overlap_volume(a: trimesh.Trimesh, b: trimesh.Trimesh) -> float:
332
+ """Volume shared by two meshes (0 when they only touch)."""
333
+ lo, hi = np.maximum(a.bounds[0], b.bounds[0]), np.minimum(a.bounds[1], b.bounds[1])
334
+ if np.any(hi - lo <= 1e-9):
335
+ return 0.0
336
+ try:
337
+ inter = trimesh.boolean.intersection([a, b], engine="manifold")
338
+ except Exception: # noqa: BLE001 - meshes manifold can't handle are treated as not overlapping
339
+ return 0.0
340
+ return float(abs(inter.volume)) if len(inter.faces) else 0.0
341
+
342
+
343
+ def same_transform(t1: np.ndarray, t2: np.ndarray, scale: float) -> bool:
344
+ return bool(np.allclose(t1[:3, :3], t2[:3, :3], atol=0.02) and
345
+ np.linalg.norm(t1[:3, 3] - t2[:3, 3]) < 0.01 * scale + 1e-3)
346
+
347
+
348
+ @dataclass
349
+ class Joint:
350
+ """One way to put part b against part a, backed by one or more face matches."""
351
+ matches: list[Match]
352
+ transform: np.ndarray
353
+ score: float = 0.0
354
+
355
+ @property
356
+ def a(self) -> int:
357
+ return self.matches[0].a.part
358
+
359
+ @property
360
+ def b(self) -> int:
361
+ return self.matches[0].b.part
362
+
363
+ @property
364
+ def in_place(self) -> bool:
365
+ return all(m.in_place for m in self.matches)
366
+
367
+
368
+ # --------------------------------------------------------------------------
369
+ # Assembly
370
+ # --------------------------------------------------------------------------
371
+
372
+ def find_joints(meshes: list[trimesh.Trimesh], faces: list[list[Face]], tol: float) -> list[Joint]:
373
+ """Every plausible way to join every pair of parts, scored.
374
+
375
+ Face matches that agree on the same placement are merged into one joint,
376
+ so a stepped or dovetailed cut (several flat faces) scores as one strong
377
+ joint. A face that fits many partners (a plain rectangle, say) is trusted
378
+ less than one that fits a single partner.
379
+ """
380
+ n = len(meshes)
381
+ matches: list[Match] = []
382
+ for i in range(n):
383
+ for j in range(i + 1, n):
384
+ for fa in faces[i]:
385
+ for fb in faces[j]:
386
+ m = already_in_place(fa, fb, tol)
387
+ matches.extend([m] if m else match_faces(fa, fb, meshes[j], tol))
388
+
389
+ # How many partners each face could mate with.
390
+ partners: dict[tuple[int, int], set[tuple[int, int]]] = {}
391
+ for m in matches:
392
+ ka, kb = (m.a.part, m.a.index), (m.b.part, m.b.index)
393
+ partners.setdefault(ka, set()).add(kb)
394
+ partners.setdefault(kb, set()).add(ka)
395
+
396
+ joints: list[Joint] = []
397
+ scale = max(float(m.scale) for m in meshes)
398
+ for m in matches:
399
+ for jt in joints:
400
+ if jt.a == m.a.part and jt.b == m.b.part and same_transform(jt.transform, m.transform, scale):
401
+ if all(x.a.index != m.a.index and x.b.index != m.b.index for x in jt.matches):
402
+ jt.matches.append(m)
403
+ break
404
+ else:
405
+ joints.append(Joint(matches=[m], transform=m.transform))
406
+ for jt in joints:
407
+ jt.score = sum(m.score / math.sqrt(len(partners[(m.a.part, m.a.index)]) * len(partners[(m.b.part, m.b.index)]))
408
+ for m in jt.matches)
409
+ # Several faces agreeing on one placement is strong evidence: that rarely
410
+ # happens by chance, while a single plain face often fits elsewhere too.
411
+ jt.score *= len(jt.matches) ** 2
412
+ # Several rotations of the same faces: each is less certain.
413
+ rivals = sum(1 for o in joints if o is not jt and {(x.a.index, x.b.index) for x in o.matches}
414
+ & {(x.a.index, x.b.index) for x in jt.matches} and o.a == jt.a and o.b == jt.b)
415
+ jt.score /= 1 + rivals
416
+ return joints
417
+
418
+
419
+ def assemble(meshes: list[trimesh.Trimesh], names: list[str], *, max_faces: int, min_area_frac: float,
420
+ tol: float, verbose: bool) -> tuple[list[np.ndarray], list[Match]]:
421
+ """Return one world transform per part plus the face matches used.
422
+
423
+ Joints are taken best first (parts already in place before anything
424
+ else). A joint is skipped if it reuses a face, links parts already
425
+ connected, or would push one part into another.
426
+ """
427
+ n = len(meshes)
428
+ faces = [extract_faces(m, i, max_faces, min_area_frac) for i, m in enumerate(meshes)]
429
+ if verbose:
430
+ for i, fs in enumerate(faces):
431
+ print(f" {names[i]}: {len(fs)} candidate faces "
432
+ f"(largest {fs[0].area:.1f} mm²)" if fs else f" {names[i]}: no planar faces", file=sys.stderr)
433
+
434
+ joints = find_joints(meshes, faces, tol)
435
+ joints.sort(key=lambda j: (j.in_place, j.score), reverse=True)
436
+
437
+ group = list(range(n)) # group id per part
438
+ pose = [np.eye(4) for _ in range(n)] # part -> its group's frame
439
+ used: set[tuple[int, int]] = set()
440
+ chosen: list[Match] = []
441
+ volumes = [abs(m.volume) if m.is_volume else 0.0 for m in meshes]
442
+ for jt in joints:
443
+ ga, gb = group[jt.a], group[jt.b]
444
+ keys = {(m.a.part, m.a.index) for m in jt.matches} | {(m.b.part, m.b.index) for m in jt.matches}
445
+ if ga == gb or keys & used:
446
+ continue
447
+ # Pose of every part of b's group in a's group frame.
448
+ to_a = pose[jt.a] @ jt.transform @ np.linalg.inv(pose[jt.b])
449
+ members_a = [k for k in range(n) if group[k] == ga]
450
+ members_b = [k for k in range(n) if group[k] == gb]
451
+ moved = {k: to_a @ pose[k] for k in members_b}
452
+ clash = False
453
+ for kb in members_b:
454
+ mb = meshes[kb].copy().apply_transform(moved[kb])
455
+ for ka in members_a:
456
+ ma = meshes[ka].copy().apply_transform(pose[ka])
457
+ limit = 0.005 * min(volumes[ka], volumes[kb]) if volumes[ka] and volumes[kb] else 0.0
458
+ if limit and overlap_volume(ma, mb) > limit:
459
+ clash = True
460
+ break
461
+ if clash:
462
+ break
463
+ if clash:
464
+ continue
465
+ for k in members_b:
466
+ pose[k] = moved[k]
467
+ group[k] = ga
468
+ used |= keys
469
+ best = max(jt.matches, key=lambda m: m.score)
470
+ # Another joint for either of these faces that scores about as well: the
471
+ # choice is a guess (a symmetric face, or another face of the same shape).
472
+ mine = {(m.a.part, m.a.index) for m in jt.matches} | {(m.b.part, m.b.index) for m in jt.matches}
473
+ rivals = [o for o in joints if o is not jt and abs(o.score - jt.score) < 0.05 * jt.score and
474
+ mine & ({(m.a.part, m.a.index) for m in o.matches} | {(m.b.part, m.b.index) for m in o.matches})]
475
+ chosen.append(Match(a=best.a, b=best.b, iou=min(m.iou for m in jt.matches), transform=jt.transform,
476
+ ambiguous=bool(rivals), in_place=jt.in_place))
477
+
478
+ # Express everything relative to the largest part, which stays put.
479
+ root = int(np.argmax([m.volume if m.is_volume else m.area for m in meshes]))
480
+ base = np.linalg.inv(pose[root])
481
+ world = [base @ pose[k] if group[k] == group[root] else pose[k] for k in range(n)]
482
+ missing = [names[k] for k in range(n) if group[k] != group[root]]
483
+ if missing:
484
+ print(f"warning: no mating face found for: {', '.join(missing)} — left where they are",
485
+ file=sys.stderr)
486
+ return world, chosen
487
+
488
+
489
+ def snap_seams(meshes: list[trimesh.Trimesh], eps: float = 1e-3) -> list[trimesh.Trimesh]:
490
+ """Weld vertices that sit within eps (mm) of a vertex on another part.
491
+
492
+ Aligned parts meet at faces that are coincident only to float precision;
493
+ left as-is, the boolean union turns the tiny offsets into sliver triangles.
494
+ """
495
+ from scipy.spatial import cKDTree
496
+ out = [m.copy() for m in meshes]
497
+ for i in range(1, len(out)):
498
+ ref = np.vstack([m.vertices for m in out[:i]])
499
+ dist, idx = cKDTree(ref).query(out[i].vertices, distance_upper_bound=eps)
500
+ hit = np.isfinite(dist)
501
+ if hit.any():
502
+ v = out[i].vertices.copy()
503
+ v[hit] = ref[idx[hit]]
504
+ out[i].vertices = v
505
+ return out
506
+
507
+
508
+ def combine(meshes: list[trimesh.Trimesh], union: bool) -> trimesh.Trimesh:
509
+ if union and len(meshes) > 1:
510
+ meshes = snap_seams(meshes)
511
+ try:
512
+ return trimesh.boolean.union(meshes, engine="manifold")
513
+ except Exception as exc: # noqa: BLE001 - any union failure falls back to concatenation
514
+ print(f"warning: boolean union failed ({exc}); writing parts concatenated instead",
515
+ file=sys.stderr)
516
+ return trimesh.util.concatenate(meshes)
517
+
518
+
519
+ # --------------------------------------------------------------------------
520
+ # Files
521
+ # --------------------------------------------------------------------------
522
+
523
+ INPUT_FORMATS = ("stl", "3mf", "obj", "ply", "off", "glb", "gltf")
524
+ OUTPUT_FORMATS = ("stl", "3mf", "obj", "ply", "off", "glb")
525
+
526
+
527
+ def load_parts(source, name: str) -> list[tuple[str, trimesh.Trimesh]]:
528
+ """Read a mesh file (path or file-like) into named parts.
529
+
530
+ A file holding several objects (3MF, GLB) gives one part per object, named
531
+ "file.3mf: object"; anything else gives a single part.
532
+ """
533
+ ext = Path(name).suffix.lower().lstrip(".")
534
+ if ext not in INPUT_FORMATS:
535
+ raise ValueError(f"unsupported file type '.{ext}' (use {', '.join('.' + e for e in INPUT_FORMATS)})")
536
+ loaded = trimesh.load(source, file_type=ext)
537
+ if isinstance(loaded, trimesh.Scene):
538
+ meshes = []
539
+ for node in sorted(loaded.graph.nodes_geometry):
540
+ transform, geom_name = loaded.graph[node]
541
+ geom = loaded.geometry[geom_name]
542
+ if isinstance(geom, trimesh.Trimesh) and len(geom.faces):
543
+ meshes.append((f"{name}: {node}", geom.copy().apply_transform(transform)))
544
+ if len(meshes) == 1:
545
+ meshes = [(name, meshes[0][1])]
546
+ else:
547
+ meshes = [(name, loaded)]
548
+ if not meshes:
549
+ raise ValueError(f"{name} holds no triangle meshes")
550
+ for _, m in meshes:
551
+ m.merge_vertices()
552
+ return meshes
553
+
554
+
555
+ def export_result(parts: list[trimesh.Trimesh], names: list[str], fmt: str, union: bool) -> bytes:
556
+ """Placed parts -> file bytes.
557
+
558
+ With union, one merged solid. Without, 3MF and GLB keep each part as its
559
+ own object (handy for multi-colour printing); other formats hold all the
560
+ parts in one mesh.
561
+ """
562
+ fmt = fmt.lower().lstrip(".")
563
+ if fmt not in OUTPUT_FORMATS:
564
+ raise ValueError(f"unsupported output type '.{fmt}' (use {', '.join('.' + e for e in OUTPUT_FORMATS)})")
565
+ if not union and fmt in ("3mf", "glb"):
566
+ scene = trimesh.Scene()
567
+ for mesh, name in zip(parts, names, strict=True):
568
+ scene.add_geometry(mesh, geom_name=Path(name).stem or name, node_name=Path(name).stem or name)
569
+ data = scene.export(file_type=fmt)
570
+ else:
571
+ data = combine(parts, union=union).export(file_type=fmt)
572
+ return data.encode() if isinstance(data, str) else data
573
+
574
+
575
+ # --------------------------------------------------------------------------
576
+ # CLI
577
+ # --------------------------------------------------------------------------
578
+
579
+ def main(argv: list[str] | None = None) -> int:
580
+ ap = argparse.ArgumentParser(prog="stljoiner", description=__doc__,
581
+ epilog="Run 'stljoiner web' for the browser interface.",
582
+ formatter_class=argparse.RawDescriptionHelpFormatter)
583
+ ap.add_argument("inputs", nargs="+", type=Path,
584
+ help="mesh files to join: .stl, .3mf, .obj, .ply, .off, .glb (a 3MF or GLB with several "
585
+ "objects counts as several parts)")
586
+ ap.add_argument("--version", action="version", version=f"stljoiner {__version__}")
587
+ ap.add_argument("-o", "--output", type=Path, default=Path("joined.stl"),
588
+ help="output file; its extension picks the format: .stl, .3mf, .obj, .ply, .off, .glb "
589
+ "(default: joined.stl)")
590
+ ap.add_argument("--no-union", action="store_true",
591
+ help="place the parts without merging them (3MF/GLB keep each part as its own object)")
592
+ ap.add_argument("--tolerance", type=float, default=0.05,
593
+ help="allowed mismatch between mating faces, as a fraction (default 0.05)")
594
+ ap.add_argument("--max-faces", type=int, default=12,
595
+ help="planar faces per part considered as cut faces (default 12)")
596
+ ap.add_argument("--min-area", type=float, default=0.005,
597
+ help="ignore planar faces smaller than this fraction of the part's surface (default 0.005)")
598
+ ap.add_argument("--export-parts", type=Path, metavar="DIR",
599
+ help="also write each repositioned part to DIR")
600
+ ap.add_argument("-q", "--quiet", action="store_true")
601
+ args = ap.parse_args(argv)
602
+
603
+ verbose = not args.quiet
604
+
605
+ meshes, names = [], []
606
+ for p in args.inputs:
607
+ try:
608
+ parts = load_parts(p, p.name)
609
+ except (ValueError, OSError) as exc:
610
+ ap.error(str(exc))
611
+ for name, m in parts:
612
+ if verbose and not m.is_watertight:
613
+ print(f"warning: {name} is not watertight; union may fail", file=sys.stderr)
614
+ meshes.append(m)
615
+ names.append(name)
616
+ if len(meshes) < 2:
617
+ ap.error("need at least two parts to join")
618
+ out_fmt = args.output.suffix.lower().lstrip(".") or "stl"
619
+ if out_fmt not in OUTPUT_FORMATS:
620
+ ap.error(f"can't write '.{out_fmt}' files (use {', '.join('.' + e for e in OUTPUT_FORMATS)})")
621
+
622
+ if verbose:
623
+ print(f"Finding mating faces among {len(meshes)} parts...", file=sys.stderr)
624
+ world, chosen = assemble(meshes, names, max_faces=args.max_faces, min_area_frac=args.min_area,
625
+ tol=args.tolerance, verbose=verbose)
626
+
627
+ if verbose:
628
+ for m in chosen:
629
+ note = " (already in place)" if m.in_place else ""
630
+ if m.ambiguous:
631
+ note += " ⚠ other faces or rotations fit just as well: check this joint"
632
+ print(f" joined {names[m.b.part]} → {names[m.a.part]}: face area {m.a.area:.1f} mm², "
633
+ f"fit {m.iou * 100:.1f}%{note}", file=sys.stderr)
634
+
635
+ placed = [m.copy().apply_transform(T) for m, T in zip(meshes, world, strict=True)]
636
+ if args.export_parts:
637
+ args.export_parts.mkdir(parents=True, exist_ok=True)
638
+ for m, name in zip(placed, names, strict=True):
639
+ safe = "".join(c if c.isalnum() or c in "-_." else "_" for c in Path(name.replace(": ", "_")).stem)
640
+ m.export(args.export_parts / f"{safe}.stl")
641
+
642
+ args.output.write_bytes(export_result(placed, names, out_fmt, union=not args.no_union))
643
+ if verbose:
644
+ out = trimesh.util.concatenate(placed) if args.no_union else load_parts(args.output, args.output.name)[0][1]
645
+ ext = out.extents
646
+ print(f"Wrote {args.output} — {ext[0]:.1f} × {ext[1]:.1f} × {ext[2]:.1f} mm"
647
+ + ("" if args.no_union else f", watertight={out.is_watertight}"), file=sys.stderr)
648
+ return 0
649
+
650
+ if __name__ == "__main__":
651
+ sys.exit(main())