bambu-printer-mcp 1.1.88 → 1.1.90

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.
@@ -1,10 +1,11 @@
1
- """Independent geometry checks, six orthographic views and triangle-exact surface separation."""
1
+ """Independent geometry checks, six orthographic views, a perspective view and triangle-exact surface separation."""
2
2
  from pathlib import Path
3
+ import json
3
4
  import math
4
5
  import numpy as np
5
6
  import trimesh
6
7
  import manifold3d as mf
7
- from PIL import Image, ImageDraw
8
+ from PIL import Image, ImageDraw, ImageFont
8
9
 
9
10
 
10
11
  def mesh(file):
@@ -30,14 +31,220 @@ def inspect(request):
30
31
  step_bounds = [list(sb.min), list(sb.max)] if sb is not None else None
31
32
  checks = {'watertight': bool(m.is_watertight), 'winding_consistent': bool(m.is_winding_consistent), 'positive_volume': bool(m.is_volume),
32
33
  'manifold': mm.status() == mf.Error.NoError, 'step_valid': bool(step.is_valid) if step is not None else None,
34
+ # A solid design whose STEP holds only shells (seen after rounding a sketch by offsetting it out and
35
+ # back) is not the B-rep it claims to be, however good its mesh looks.
36
+ 'step_solids': bool(len(step.solids()) >= 1) if step is not None else None,
33
37
  'stl_step_bounds_agree': bool(np.max(np.abs(m.bounds - np.array(step_bounds))) <= 0.2) if step_bounds is not None else None}
38
+ try:
39
+ assembly = bodies(step, request) if step is not None else None
40
+ except Exception as e: # a failed measurement must not cost the person the export; it is reported, not passed
41
+ assembly = {'error': f'{type(e).__name__}: {e}'[:300]}
34
42
  return {'valid': all(v for v in checks.values() if v is not None), 'units': 'mm', 'bounds_mm': bounds,
35
43
  'size_mm': m.extents.tolist(), 'volume_mm3': float(m.volume) if m.is_volume else None,
36
44
  'step_volume_mm3': float(step.volume) if step is not None else None, 'solid_count': len(step.solids()) if step is not None else len(m.split(only_watertight=True)),
37
45
  'mesh_components': len(m.split(only_watertight=False)), 'checks': checks,
46
+ **evidence(assembly),
38
47
  'renders': render(m, base.parent / (base.name + '.renders'))}
39
48
 
40
49
 
50
+ # Starting print-in-place gap between separate bodies: Prusa's first value for movable parts is "at least 0.3 mm"
51
+ # (design guidance, fdm_fit [F3]). A script sets its own with a literal P["print_in_place_clearance_mm"], and says
52
+ # its bodies are shown assembled (not printed in place) with P["print_in_place"] = False.
53
+ PIP_CLEARANCE_MM = 0.3
54
+ BED_TOLERANCE_MM = 0.05
55
+ SCREEN_ANGLE = 0.1 # tessellation angular deflection (radians) for the gap screen
56
+ EXACT_CAP = 32 # exact B-rep distance calls per result
57
+
58
+
59
+ def clearance_setting(request):
60
+ try:
61
+ params = json.loads(Path(request['parameters']).read_text()) if request.get('parameters') else {}
62
+ except (OSError, ValueError):
63
+ params = {}
64
+ params = params if isinstance(params, dict) else {}
65
+ value = params.get('print_in_place_clearance_mm')
66
+ in_place = params.get('print_in_place', True) is not False
67
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and 0 <= value <= 10:
68
+ return float(value), 'P["print_in_place_clearance_mm"]', in_place
69
+ return PIP_CLEARANCE_MM, 'default: Prusa\'s "at least 0.3 mm" for movable parts (fdm_fit)', in_place
70
+
71
+
72
+ def bodies(step, request, budget_s=20.0):
73
+ """Every pair of solids in the exported STEP: closest approach (screened on tessellations, measured exactly on the
74
+ B-rep for every pair the screen cannot clear), overlap, whether each labelled body the script returned is still one
75
+ solid, and whether each solid stands on the print plate (Z = 0) or on a solid that does. Council 2026-11-11
76
+ (scan-to-make #734): chainmail links fused at 48 interfaces, a pawl grazing its wheel while a severed bar kept the
77
+ solid count right, discs starting in mid-air, all with valid: true."""
78
+ import time
79
+ from build123d import Compound
80
+ clearance, source, in_place = clearance_setting(request)
81
+ started = time.monotonic()
82
+ over = lambda: time.monotonic() - started > budget_s
83
+ # Declared bodies: the top-level children of a returned Compound, named by their labels.
84
+ declared, names = [], []
85
+ children = list(step.children) if isinstance(step, Compound) else []
86
+ # STEP import names an unlabelled shape after its type ("SOLID", "COMPOUND"): only the script's own labels declare
87
+ labelled = lambda c: bool(c.label) and c.label != type(c).__name__.upper() and c.label.upper() not in ('SOLID', 'COMPOUND', 'COMPSOLID', 'SHELL')
88
+ if children and all(labelled(c) for c in children):
89
+ for child in children:
90
+ pieces = child.solids()
91
+ declared.append({'body': child.label, 'solids': len(pieces)})
92
+ names += [child.label if len(pieces) == 1 else f'{child.label} piece {k + 1}' for k in range(len(pieces))]
93
+ solids = [s for c in children for s in c.solids()]
94
+ else:
95
+ solids = list(step.solids())
96
+ names = [f'solid {k + 1}' for k in range(len(solids))]
97
+ boxes = [s.bounding_box() for s in solids]
98
+ r3 = lambda v: [round(v[0], 3), round(v[1], 3), round(v[2], 3)]
99
+ mid = lambda pa, pb: r3(((pa.X + pb.X) / 2, (pa.Y + pb.Y) / 2, (pa.Z + pb.Z) / 2))
100
+ # The screen's error on a curved face is its chord sag, at most R a^2 / 8 per surface for angular deflection a; R is
101
+ # bounded by half the pair's larger box diagonal. Every pair the screen reads within the clearance + 0.2 mm + that
102
+ # sag is measured exactly on the B-rep.
103
+ sag = lambda i: (boxes[i].diagonal / 2) * SCREEN_ANGLE ** 2 / 8
104
+ window = lambda i, j: clearance + 0.2 + sag(i) + sag(j)
105
+ def solid_manifold(s):
106
+ v, f = s.tessellate(0.01, SCREEN_ANGLE)
107
+ t = trimesh.Trimesh(np.array([[p.X, p.Y, p.Z] for p in v], dtype=float), np.array(f, dtype=np.int64), process=True)
108
+ t.merge_vertices()
109
+ return manifold(t)
110
+ meshes = [None] * len(solids)
111
+ rows, unmeasured, errors, exact_calls, screened_only = [], [], [], 0, 0
112
+ near_pairs = [] # (i, j, gap) for every pair within its window: what rests on what
113
+ for i in range(len(solids)):
114
+ for j in range(i + 1, len(solids)):
115
+ a, b = boxes[i], boxes[j]
116
+ gap = math.sqrt(sum(max(0.0, lo2 - hi1, lo1 - hi2) ** 2 for lo1, hi1, lo2, hi2 in
117
+ ((a.min.X, a.max.X, b.min.X, b.max.X), (a.min.Y, a.max.Y, b.min.Y, b.max.Y), (a.min.Z, a.max.Z, b.min.Z, b.max.Z))))
118
+ w = window(i, j)
119
+ if gap >= w: continue
120
+ if over():
121
+ unmeasured.append((names[i], names[j], 'time budget'))
122
+ continue
123
+ try:
124
+ for k in (i, j):
125
+ if meshes[k] is None: meshes[k] = solid_manifold(solids[k])
126
+ if meshes[i].status() == mf.Error.NoError and meshes[j].status() == mf.Error.NoError:
127
+ d = meshes[i].min_gap(meshes[j], w)
128
+ else: # a tessellation that does not close: only the exact measurement can say
129
+ d = 0.0
130
+ if d >= w: continue
131
+ exact = exact_calls < EXACT_CAP and not over()
132
+ if exact:
133
+ exact_calls += 1
134
+ d, pa, pb = solids[i].distance_to_with_closest_points(solids[j])
135
+ at = mid(pa, pb)
136
+ holds = lambda x, y: all(getattr(x.min, c) <= getattr(y.min, c) and getattr(y.max, c) <= getattr(x.max, c) for c in 'XYZ')
137
+ if d > 1e-6 and (holds(a, b) or holds(b, a)) and not over() and getattr(solids[i] & solids[j], 'volume', 0.0) > 1e-6:
138
+ d = 0.0 # one wholly inside the other: the surfaces never meet
139
+ else: # past the exact cap or the time budget: the screened gap, marked as such
140
+ screened_only += 1
141
+ at = r3([(max(getattr(a.min, c), getattr(b.min, c)) + min(getattr(a.max, c), getattr(b.max, c))) / 2 for c in 'XYZ'])
142
+ rows.append({'a': names[i], 'b': names[j], 'gap_mm': round(d, 4), 'at': at, 'exact': exact})
143
+ near_pairs.append((i, j, d))
144
+ except Exception as e: # one pair that cannot be measured does not cost the others
145
+ errors.append(f'{names[i]} / {names[j]}: {type(e).__name__}: {e}'[:200])
146
+ unmeasured.append((names[i], names[j], 'error'))
147
+ fused = [r for r in rows if r['gap_mm'] <= 1e-6]
148
+ under = [r for r in rows if 1e-6 < r['gap_mm'] < clearance - 1e-9]
149
+ # a screened-only row read at or past the clearance is still within the screen's error of it: not cleared
150
+ unsure = [r for r in rows if not r['exact'] and r['gap_mm'] >= clearance - 1e-9]
151
+ closest = min(rows, key=lambda r: r['gap_mm']) if rows else None
152
+ # The print plate is Z = 0 of the exported frame. A solid below it is cut off by the plate; one above it prints on
153
+ # air unless it rests on a solid that reaches the plate: material directly under its first layer, within the pair's
154
+ # window (print-in-place stacks).
155
+ below = [{'solid': names[k], 'lowest_z_mm': round(boxes[k].min.Z, 3)} for k in range(len(solids)) if boxes[k].min.Z < -BED_TOLERANCE_MM]
156
+ grounded = {k for k in range(len(solids)) if abs(boxes[k].min.Z) <= BED_TOLERANCE_MM}
157
+ rests, support_unknown, supports = {}, set(), {}
158
+ def held_up(up, low):
159
+ # Support is material of low directly under up's first layer: the footprint of up's lowest 0.2 mm overlaps
160
+ # the footprint of low within the pair's window below it. A neighbour beside the solid is not under it
161
+ # (Codex review, 2026-11-11: a box 10 mm up, 0.4 mm beside a taller grounded box, read as resting on it).
162
+ if (up, low) not in supports:
163
+ z, w = boxes[up].min.Z, window(up, low)
164
+ if meshes[up] is None or meshes[low] is None or meshes[up].status() != mf.Error.NoError or meshes[low].status() != mf.Error.NoError:
165
+ supports[(up, low)] = None
166
+ else:
167
+ lo = [min(boxes[up].min.X, boxes[low].min.X) - 1, min(boxes[up].min.Y, boxes[low].min.Y) - 1]
168
+ size = [max(boxes[up].max.X, boxes[low].max.X) + 1 - lo[0], max(boxes[up].max.Y, boxes[low].max.Y) + 1 - lo[1]]
169
+ band = lambda m, z0, z1: (m ^ mf.Manifold.cube((size[0], size[1], z1 - z0)).translate((lo[0], lo[1], z0))).project()
170
+ supports[(up, low)] = (band(meshes[up], z, z + 0.2) ^ band(meshes[low], z - w, z + BED_TOLERANCE_MM)).area() > 1e-3
171
+ return supports[(up, low)]
172
+ changed = True
173
+ while changed:
174
+ changed = False
175
+ for i, j, d in near_pairs:
176
+ for up, low in ((i, j), (j, i)):
177
+ if up not in grounded and low in grounded and boxes[low].min.Z < boxes[up].min.Z - BED_TOLERANCE_MM:
178
+ try:
179
+ held = held_up(up, low)
180
+ except Exception as e:
181
+ held = None
182
+ errors.append(f'support of {names[up]} on {names[low]}: {type(e).__name__}: {e}'[:200])
183
+ if held is None: support_unknown.add(up)
184
+ elif held: grounded.add(up); rests[up] = (low, d); changed = True
185
+ above = []
186
+ for k in range(len(solids)):
187
+ z = boxes[k].min.Z
188
+ if z <= BED_TOLERANCE_MM: continue
189
+ row = {'solid': names[k], 'starts_mm_above_bed': round(z, 3), 'at': r3(((boxes[k].min.X + boxes[k].max.X) / 2, (boxes[k].min.Y + boxes[k].max.Y) / 2, z))}
190
+ if k in rests: row.update(rests_on=names[rests[k][0]], gap_below_mm=round(rests[k][1], 4))
191
+ elif k in support_unknown: row['support_not_measured'] = True
192
+ above.append(row)
193
+ floating = [r for r in above if 'rests_on' not in r]
194
+ severed = [d for d in declared if d['solids'] != 1]
195
+ def capped(items, say, kind):
196
+ out = [say(x) for x in items[:8]]
197
+ if len(items) > 8: out.append(f'... and {len(items) - 8} more {kind} (see bodies)')
198
+ return out
199
+ weld = 'they weld when printed' if in_place else 'a fit, not checked against print-in-place (P["print_in_place"] is False)'
200
+ problems = (capped(fused, lambda r: f'{r["a"]} and {r["b"]} touch or overlap at {r["at"]}: they print as one piece', 'touching or overlapping pairs') +
201
+ (capped(under, lambda r: f'{r["a"]} and {r["b"]} are {r["gap_mm"]} mm apart at {r["at"]}{"" if r["exact"] else " (screened, not measured exactly)"}, under the {clearance} mm print-in-place clearance: {weld}; if these bodies are shown assembled rather than printed in place, set P["print_in_place"] = False', 'pairs under the clearance') if in_place else []) +
202
+ capped(unsure, lambda r: f'{r["a"]} and {r["b"]} screen at {r["gap_mm"]} mm, within the screen error of the {clearance} mm clearance, and were not measured exactly (exact cap or time budget)', 'unconfirmed pairs') +
203
+ [f'body "{d["body"]}" is {d["solids"]} separate solids: something cuts it apart' if d['solids'] > 1 else f'body "{d["body"]}" has no solid' for d in severed] +
204
+ capped(below, lambda r: f'{r["solid"]} reaches {r["lowest_z_mm"]} mm, below the print plate (Z = 0): the plate cuts it off', 'solids below the plate') +
205
+ capped(floating, lambda r: f'{r["solid"]} starts {r["starts_mm_above_bed"]} mm above the print plate (Z = 0) and whether a solid under it reaches the plate could not be measured (a tessellation that does not close)' if r.get('support_not_measured') else f'{r["solid"]} starts {r["starts_mm_above_bed"]} mm above the print plate (Z = 0) with no solid under it that reaches the plate: its first layer is printed on air', 'floating solids'))
206
+ if unmeasured:
207
+ problems.append(f'{len(unmeasured)} near pair(s) were not measured ({", ".join(sorted({u[2] for u in unmeasured}))}); see bodies.pairs_not_measured')
208
+ return {'solids': len(solids), 'clearance_mm': clearance, 'clearance_source': source, 'print_in_place': in_place,
209
+ 'declared_bodies': declared or None, 'pairs_measured': len(rows), 'exact_measurements': exact_calls, 'screened_only': screened_only,
210
+ 'pairs_not_measured': [{'a': u[0], 'b': u[1], 'why': u[2]} for u in unmeasured], 'errors': errors,
211
+ 'fused': fused, 'too_close': under, 'unconfirmed': unsure, 'closest': closest,
212
+ 'above_bed': above, 'below_bed': below, 'severed': severed, 'problems': problems,
213
+ 'seconds': round(time.monotonic() - started, 3)}
214
+
215
+
216
+ def evidence(assembly):
217
+ """What this result does and does not establish, so valid geometry is never read as a working part."""
218
+ checked = ['the exported mesh is closed, manifold and consistently wound, and the STEP agrees with it (valid, checks)',
219
+ 'bounds, size, volumes and solid count of the exported files']
220
+ not_checked = ['fit to the real object or a mating part (use cad_check_fit per state)',
221
+ 'strength, stiffness or how it holds under load',
222
+ 'motion, articulated poses and snap or flex behaviour',
223
+ 'printing: supports, bridges and bed adhesion are the slicer\'s answer']
224
+ if assembly is None:
225
+ not_checked.append('gaps between separate bodies and contact with the print plate (mesh mode has no solids)')
226
+ return {'checked': checked, 'not_checked': not_checked, 'problems': []}
227
+ if 'error' in assembly:
228
+ not_checked.append('gaps between separate bodies: the measurement failed (' + assembly['error'] + ')')
229
+ return {'bodies': assembly, 'checked': checked, 'not_checked': not_checked, 'problems': ['bodies could not be measured: ' + assembly['error']]}
230
+ checked.append('whether each solid stands on the print plate (Z = 0 of the exported frame) or rests on a solid that does, and whether any reaches below it (bodies; failures are in problems)')
231
+ if assembly['solids'] > 1:
232
+ pairs = f'the closest approach of each near pair of the {assembly["solids"]} solids'
233
+ rule = (f'against a {assembly["clearance_mm"]} mm print-in-place clearance ({assembly["clearance_source"]})' if assembly['print_in_place']
234
+ else 'for touching or overlap only: the script says its bodies are shown assembled (P["print_in_place"] is False)')
235
+ if assembly['pairs_not_measured'] or assembly['unconfirmed']:
236
+ not_checked.append(f'{pairs} {rule}: {len(assembly["pairs_not_measured"])} pair(s) were not measured and {len(assembly["unconfirmed"])} only screened (bodies)')
237
+ else:
238
+ checked.append(f'{pairs} {rule}, screened on tessellations and measured exactly where the screen could not clear them (bodies; failures are in problems)')
239
+ if not assembly['print_in_place']:
240
+ not_checked.append('print-in-place clearance: the bodies are declared as shown assembled')
241
+ if assembly['declared_bodies']:
242
+ checked.append('whether each labelled body is exactly one solid (bodies.declared_bodies; failures are in problems)')
243
+ elif assembly['solids'] > 1:
244
+ not_checked.append('which solids are meant to be separate bodies: return Compound(children=[...]) with a label on each body so a severed piece cannot pass for one')
245
+ return {'bodies': assembly, 'problems': assembly['problems'], 'checked': checked, 'not_checked': not_checked}
246
+
247
+
41
248
  def render(m, folder):
42
249
  folder.mkdir(exist_ok=True)
43
250
  tri, centres, normals = m.triangles, m.triangles.mean(axis=1), m.face_normals
@@ -83,12 +290,127 @@ def render(m, folder):
83
290
  draw.line([tuple(xy[i, j]), tuple(xy[i, (j + 1) % 3])], fill=(27, 62, 70), width=2)
84
291
  draw.text((24, 22), name + ' | ' + ', '.join(f'{x:.2f}' for x in m.extents) + ' mm', fill='black')
85
292
  file = folder / (name + '.png'); im.save(file); paths[name] = str(file); images.append(im)
86
- sheet = Image.new('RGB', (1600, 2400), 'white')
87
- for i, im in enumerate(images): sheet.paste(im, ((i % 2) * 800, (i // 2) * 800))
293
+ # The view a person judges a shape from: three-quarter, in perspective, large on the sheet beside the six.
294
+ big = perspective(m, 1600)
295
+ label = 'perspective, from the front right and above | ' + ' x '.join(f'{x:.1f}' for x in m.extents) + ' mm'
296
+ ImageDraw.Draw(big).text((28, 24), label, fill='black', font=ImageFont.load_default(size=30))
297
+ file = folder / 'perspective.png'; big.resize((800, 800), Image.LANCZOS).save(file); paths['perspective'] = str(file)
298
+ sheet = Image.new('RGB', (1600 + 2 * 534, 1602), 'white')
299
+ sheet.paste(big, (0, 0))
300
+ for i, im in enumerate(images): sheet.paste(im.resize((534, 534), Image.LANCZOS), (1600 + (i % 2) * 534, (i // 2) * 534))
88
301
  sheet.save(folder / 'contact.png'); paths['contact'] = str(folder / 'contact.png')
89
302
  return paths
90
303
 
91
304
 
305
+ def perspective(m, size=1600, azimuth=35.0, elevation=26.0):
306
+ """A three-quarter view in true perspective with a depth buffer (large flat faces defeat depth sorting at an
307
+ angle). Seen from the front (-Y) turned `azimuth` degrees towards +X and raised `elevation` degrees, through a
308
+ 28 degree lens, framed to fill the picture. Smooth shading across facets that meet within 40 degrees, so a
309
+ lofted or filleted surface reads as one surface and a real edge stays an edge; outlines where the surface steps
310
+ in depth or creases by more than 35 degrees. Every array operation is over all triangles at once."""
311
+ V, F, N = np.asarray(m.vertices, float), np.asarray(m.faces), np.asarray(m.face_normals, float)
312
+ centre, radius = m.bounds.mean(axis=0), max(float(np.linalg.norm(m.extents)) / 2, 1e-9)
313
+ az, el = math.radians(azimuth), math.radians(elevation)
314
+ to_eye = np.array([math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)])
315
+ d = -to_eye
316
+ r = np.cross(d, [0, 0, 1.0]); r /= np.linalg.norm(r)
317
+ u = np.cross(r, d)
318
+ eye = centre + to_eye * radius / math.sin(math.radians(14)) * 1.06
319
+ q = V - eye
320
+ zc = q @ d
321
+ tx, ty = (q @ r) / zc, (q @ u) / zc
322
+ zoom = 0.86 * size / max(float(np.ptp(tx)), float(np.ptp(ty)), 1e-12)
323
+ X = size / 2 + zoom * (tx - (tx.min() + tx.max()) / 2)
324
+ Y = size / 2 - zoom * (ty - (ty.min() + ty.max()) / 2)
325
+ W = 1.0 / zc # inverse depth is affine across a triangle on screen
326
+ # light: key from the upper left of the viewer, a weaker fill from the right
327
+ key = -0.55 * r + 0.75 * u - 0.45 * d; key /= np.linalg.norm(key)
328
+ fill = 0.8 * r + 0.15 * u - 0.6 * d; fill /= np.linalg.norm(fill)
329
+ lum = lambda n: 0.26 + 0.58 * np.clip(n @ key, 0, None) + 0.2 * np.clip(n @ fill, 0, None)
330
+ vn = np.asarray(m.vertex_normals, float)
331
+ corner = vn[F] # (T, 3, 3): use the vertex normal only where it is this face's
332
+ smooth = np.einsum('tkj,tj->tk', corner, N) > 0.766
333
+ L = np.where(smooth, lum(corner.reshape(-1, 3)).reshape(-1, 3), lum(N)[:, None])
334
+ facing = np.einsum('ij,ij->i', N, V[F].mean(axis=1) - eye) < 0
335
+ if m.is_watertight:
336
+ front = facing # a closed solid: its back faces are never seen
337
+ else: # an open scan is seen from both sides: light the side that faces the eye
338
+ front = np.ones(len(F), bool)
339
+ L = np.where(facing[:, None], L, np.where(smooth, lum(-corner.reshape(-1, 3)).reshape(-1, 3), lum(-N)[:, None]))
340
+ N = np.where(facing[:, None], N, -N)
341
+ x, y, w, L = X[F][front], Y[F][front], W[F][front], L[front]
342
+ Nf = N[front]
343
+ det = (x[:, 1] - x[:, 0]) * (y[:, 2] - y[:, 0]) - (x[:, 2] - x[:, 0]) * (y[:, 1] - y[:, 0])
344
+ ok = np.abs(det) > 1e-12
345
+ x, y, w, L, Nf, det = x[ok], y[ok], w[ok], L[ok], Nf[ok], det[ok]
346
+ if not len(x): # nothing faces the eye (a mesh seen exactly edge-on)
347
+ return Image.new('RGB', (size, size), '#f5f5f2')
348
+ def plane(a): # a(px, py) = a0 + gx (px - x0) + gy (py - y0)
349
+ gx = ((a[:, 1] - a[:, 0]) * (y[:, 2] - y[:, 0]) - (a[:, 2] - a[:, 0]) * (y[:, 1] - y[:, 0])) / det
350
+ gy = ((a[:, 2] - a[:, 0]) * (x[:, 1] - x[:, 0]) - (a[:, 1] - a[:, 0]) * (x[:, 2] - x[:, 0])) / det
351
+ return a[:, 0], gx, gy
352
+ w0, wx, wy = plane(w)
353
+ l0, lx, ly = plane(L)
354
+ # rows each triangle covers (pixel centres at +0.5), then the columns of each row
355
+ r0 = np.clip(np.ceil(y.min(axis=1) - 0.5), 0, size - 1).astype(np.int64)
356
+ r1 = np.clip(np.floor(y.max(axis=1) - 0.5), 0, size - 1).astype(np.int64)
357
+ rows = np.maximum(r1 - r0 + 1, 0)
358
+ t = np.repeat(np.arange(len(x)), rows)
359
+ row = r0[t] + (np.arange(len(t)) - np.repeat(np.cumsum(rows) - rows, rows))
360
+ yc = row + 0.5
361
+ lo, hi = np.full(len(t), np.inf), np.full(len(t), -np.inf)
362
+ for a, b in ((0, 1), (1, 2), (2, 0)):
363
+ ya, yb, xa, xb = y[t, a], y[t, b], x[t, a], x[t, b]
364
+ crosses = ((ya <= yc) & (yc < yb)) | ((yb <= yc) & (yc < ya))
365
+ xi = xa + (yc - ya) * (xb - xa) / np.where(crosses, yb - ya, 1.0)
366
+ lo, hi = np.where(crosses, np.minimum(lo, xi), lo), np.where(crosses, np.maximum(hi, xi), hi)
367
+ c0 = np.clip(np.ceil(np.where(np.isfinite(lo), lo, 0) - 0.5), 0, size - 1).astype(np.int64)
368
+ c1 = np.clip(np.floor(np.where(np.isfinite(hi), hi, -1) - 0.5), -1, size - 1).astype(np.int64)
369
+ cols = np.maximum(c1 - c0 + 1, 0)
370
+ cols[~np.isfinite(lo)] = 0
371
+ k = np.repeat(np.arange(len(t), dtype=np.int32), cols)
372
+ px = (c0[k] + (np.arange(len(k)) - np.repeat(np.cumsum(cols) - cols, cols))).astype(np.int32)
373
+ tri, py = t[k].astype(np.int32), row[k].astype(np.int32)
374
+ del k
375
+ dx, dy = (px + 0.5 - x[tri, 0]).astype(np.float32), (py + 0.5 - y[tri, 0]).astype(np.float32)
376
+ wv = w0[tri] + wx[tri] * dx + wy[tri] * dy
377
+ pix = py.astype(np.int64) * size + px
378
+ del px, py
379
+ zbuf = np.zeros(size * size)
380
+ np.maximum.at(zbuf, pix, wv)
381
+ win = wv >= zbuf[pix]
382
+ tid = np.full(size * size, -1, dtype=np.int32)
383
+ tid[pix[win]] = tri[win]
384
+ shade = np.zeros(size * size, dtype=np.float32)
385
+ shade[pix[win]] = np.clip(l0[tri[win]] + lx[tri[win]] * dx[win] + ly[tri[win]] * dy[win], 0, 1)
386
+ del tri, dx, dy, wv, pix, win
387
+ tid, zbuf, shade = tid.reshape(size, size), zbuf.reshape(size, size), shade.reshape(size, size)
388
+ solid = tid >= 0
389
+ ti = np.where(solid, tid, 0)
390
+ gx, gy, nrm = wx[ti], wy[ti], Nf[ti].astype(np.float32)
391
+ edge = np.zeros((size, size), bool)
392
+ for sy, sx in ((0, 1), (1, 0), (0, -1), (-1, 0)):
393
+ other = np.roll(solid, (-sy, -sx), axis=(0, 1))
394
+ wj = np.roll(zbuf, (-sy, -sx), axis=(0, 1))
395
+ nj = np.roll(nrm, (-sy, -sx), axis=(0, 1))
396
+ inside = np.ones((size, size), bool)
397
+ if sx == 1: inside[:, -1] = False
398
+ if sx == -1: inside[:, 0] = False
399
+ if sy == 1: inside[-1, :] = False
400
+ if sy == -1: inside[0, :] = False
401
+ step = np.abs(wj - (zbuf + gx * sx + gy * sy)) > 1.6 * zbuf / zoom
402
+ crease = np.einsum('ijk,ijk->ij', nrm, nj) < math.cos(math.radians(35))
403
+ edge |= solid & inside & ((~other) | (other & (wj < zbuf) & step) | (other & crease & (sx + sy > 0)))
404
+ edge |= np.roll(edge, 1, axis=0) & solid | np.roll(edge, 1, axis=1) & solid # two pixels wide before scaling down
405
+ del gx, gy, nrm, ti
406
+ rgb = np.empty((size, size, 3), dtype=np.float32)
407
+ ramp = np.linspace(0, 1, size)[:, None]
408
+ for c, (base, dark, top, bottom) in enumerate(((79, 22, 247, 240), (166, 46, 247, 240), (186, 52, 244, 238))):
409
+ rgb[:, :, c] = np.where(solid, base * shade + dark * (1 - shade), top + (bottom - top) * ramp)
410
+ rgb[edge] = (27, 62, 70)
411
+ return Image.fromarray(rgb.clip(0, 255).astype(np.uint8), 'RGB')
412
+
413
+
92
414
  def triangle_distance(a, b):
93
415
  """Distance for one A triangle against N B triangles: vertex/face and all 9 edge pairs."""
94
416
  n = len(b)
@@ -207,6 +207,9 @@ ${r.readonly
207
207
  (file) => !(r.inputs ?? []).includes(file),
208
208
  ))
209
209
  args.push("--ro-bind", file, file);
210
+ // bubblewrap makes the folders above each bind on its own root tmpfs; left writable (bubblewrap 0.11), a script
211
+ // could create files beside the job folder (never on the host) and setup's forbidden-write proof fails
212
+ args.push("--remount-ro", "/");
210
213
  args.push("--chdir", r.job);
211
214
  return { command: "bwrap", args };
212
215
  }