cadskill 0.1.0__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.
- cadskill-0.1.0.dist-info/METADATA +48 -0
- cadskill-0.1.0.dist-info/RECORD +13 -0
- cadskill-0.1.0.dist-info/WHEEL +4 -0
- cadskill-0.1.0.dist-info/entry_points.txt +3 -0
- cadskill_mcp/__init__.py +0 -0
- cadskill_mcp/cli.py +474 -0
- cadskill_mcp/daemon.py +131 -0
- cadskill_mcp/runner.py +149 -0
- cadskill_mcp/server.py +485 -0
- cadskill_mcp/skill/SKILL.md +168 -0
- cadskill_mcp/static/viewer.html +4506 -0
- cadskill_mcp/store.py +101 -0
- cadskill_mcp/worker.py +643 -0
cadskill_mcp/worker.py
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
"""The CadQuery side: runs model scripts and answers questions about the result.
|
|
2
|
+
|
|
3
|
+
This module runs in a child process (see runner.py) so a script that hangs or
|
|
4
|
+
crashes the kernel cannot take the MCP server down. Every request names the
|
|
5
|
+
script it is about; results are cached by the script's hash, so the worker can
|
|
6
|
+
be killed and restarted at any time without the server tracking its state.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import hashlib
|
|
12
|
+
import io
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
import traceback
|
|
16
|
+
from collections import OrderedDict
|
|
17
|
+
|
|
18
|
+
SCRIPT_NAME = "<model>"
|
|
19
|
+
CACHE_SIZE = 4
|
|
20
|
+
MAX_OUTPUT = 4000
|
|
21
|
+
MAX_ROWS = 200
|
|
22
|
+
MESH_TOLERANCE = 0.03
|
|
23
|
+
MESH_ANGLE = 0.3
|
|
24
|
+
|
|
25
|
+
_cache: "OrderedDict[str, list[dict]]" = OrderedDict() # script hash -> parts
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ModelError(Exception):
|
|
29
|
+
"""A problem to report to the caller as-is (bad selector, unknown part...)."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ---------------------------------------------------------------- running a script
|
|
33
|
+
|
|
34
|
+
def _shapes_of(obj):
|
|
35
|
+
"""Turn anything a script may show into a list of (shape, name, color) tuples."""
|
|
36
|
+
import cadquery as cq
|
|
37
|
+
|
|
38
|
+
if isinstance(obj, cq.Assembly):
|
|
39
|
+
out = []
|
|
40
|
+
for name, node in obj.traverse():
|
|
41
|
+
shapes = _shapes_of(node.obj) if node.obj is not None else []
|
|
42
|
+
if not shapes:
|
|
43
|
+
continue
|
|
44
|
+
loc, parent = node.loc, node.parent
|
|
45
|
+
while parent is not None: # world placement = every ancestor's location, outermost first
|
|
46
|
+
loc = parent.loc * loc
|
|
47
|
+
parent = parent.parent
|
|
48
|
+
color = node.color.toTuple()[:3] if node.color is not None else None
|
|
49
|
+
for shape, _, _ in shapes:
|
|
50
|
+
out.append((shape.moved(loc), name.split("/")[-1], color))
|
|
51
|
+
return out
|
|
52
|
+
if isinstance(obj, cq.Workplane):
|
|
53
|
+
shapes = [v for v in obj.vals() if isinstance(v, cq.Shape)]
|
|
54
|
+
if not shapes:
|
|
55
|
+
return []
|
|
56
|
+
return [(shapes[0] if len(shapes) == 1 else cq.Compound.makeCompound(shapes), None, None)]
|
|
57
|
+
if isinstance(obj, cq.Sketch):
|
|
58
|
+
faces = [f for f in obj.faces().vals() if isinstance(f, cq.Shape)]
|
|
59
|
+
return [(cq.Compound.makeCompound(faces), None, None)] if faces else []
|
|
60
|
+
if isinstance(obj, cq.Shape):
|
|
61
|
+
return [(obj, None, None)]
|
|
62
|
+
if isinstance(obj, (list, tuple)):
|
|
63
|
+
return [s for item in obj for s in _shapes_of(item)]
|
|
64
|
+
raise ModelError(f"show_object() cannot display a {type(obj).__name__}. Pass a Workplane, a Shape or an Assembly.")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _color(options):
|
|
68
|
+
if not options or "color" not in options:
|
|
69
|
+
return None
|
|
70
|
+
import cadquery as cq
|
|
71
|
+
|
|
72
|
+
c = options["color"]
|
|
73
|
+
if isinstance(c, str):
|
|
74
|
+
return cq.Color(c).toTuple()[:3]
|
|
75
|
+
c = tuple(float(x) for x in c)[:3]
|
|
76
|
+
return tuple(x / 255 for x in c) if max(c) > 1 else c
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _error_report(exc: BaseException, code: str) -> dict:
|
|
80
|
+
"""Where in the script it went wrong, in the script's own line numbers."""
|
|
81
|
+
line = None
|
|
82
|
+
if isinstance(exc, SyntaxError) and exc.filename == SCRIPT_NAME:
|
|
83
|
+
line = exc.lineno
|
|
84
|
+
else:
|
|
85
|
+
for frame in traceback.extract_tb(exc.__traceback__):
|
|
86
|
+
if frame.filename == SCRIPT_NAME:
|
|
87
|
+
line = frame.lineno # the last script frame is the line that failed
|
|
88
|
+
lines = code.splitlines()
|
|
89
|
+
message = str(exc) or type(exc).__name__
|
|
90
|
+
if isinstance(exc, SyntaxError):
|
|
91
|
+
message = exc.msg
|
|
92
|
+
return {
|
|
93
|
+
"type": type(exc).__name__,
|
|
94
|
+
"message": message,
|
|
95
|
+
"line": line,
|
|
96
|
+
"source": lines[line - 1].strip() if line and 0 < line <= len(lines) else None,
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _execute(code: str, model_dir: str) -> dict:
|
|
101
|
+
"""Run the script. Returns {'parts': [...], 'stdout': str} or {'error': {...}, 'stdout': str}."""
|
|
102
|
+
import cadquery as cq
|
|
103
|
+
|
|
104
|
+
shown: list[tuple] = []
|
|
105
|
+
|
|
106
|
+
def show_object(obj, name=None, options=None, **_):
|
|
107
|
+
for shape, own_name, own_color in _shapes_of(obj):
|
|
108
|
+
shown.append((shape, name or own_name, _color(options) or own_color))
|
|
109
|
+
|
|
110
|
+
def asset(filename: str) -> str:
|
|
111
|
+
path = os.path.join(model_dir, "assets", filename)
|
|
112
|
+
if not os.path.exists(path):
|
|
113
|
+
raise ModelError(f"No imported file named '{filename}'. Use the import_file tool first.")
|
|
114
|
+
return path
|
|
115
|
+
|
|
116
|
+
env = {"__name__": "__cadskill__", "cq": cq, "cadquery": cq, "show_object": show_object,
|
|
117
|
+
"debug": lambda *a, **k: None, "asset": asset, "math": math}
|
|
118
|
+
out = io.StringIO()
|
|
119
|
+
old_cwd = os.getcwd()
|
|
120
|
+
try:
|
|
121
|
+
os.makedirs(model_dir, exist_ok=True)
|
|
122
|
+
os.chdir(model_dir)
|
|
123
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
|
|
124
|
+
exec(compile(code, SCRIPT_NAME, "exec"), env)
|
|
125
|
+
if not shown and "result" in env:
|
|
126
|
+
show_object(env["result"])
|
|
127
|
+
if not shown:
|
|
128
|
+
raise ModelError("The script ran but showed nothing. Call show_object(part, name='...') for each part.")
|
|
129
|
+
except BaseException as exc: # noqa: BLE001 - a script may raise anything, including SystemExit
|
|
130
|
+
return {"error": _error_report(exc, code), "stdout": out.getvalue()[-MAX_OUTPUT:]}
|
|
131
|
+
finally:
|
|
132
|
+
os.chdir(old_cwd)
|
|
133
|
+
|
|
134
|
+
parts, used = [], set()
|
|
135
|
+
for i, (shape, name, color) in enumerate(shown):
|
|
136
|
+
base = name or (f"part{i + 1}" if len(shown) > 1 else "part")
|
|
137
|
+
name, n = base, 2
|
|
138
|
+
while name in used: # names are how tools refer to parts, so they must be unique
|
|
139
|
+
name, n = f"{base}-{n}", n + 1
|
|
140
|
+
used.add(name)
|
|
141
|
+
parts.append({"name": name, "shape": shape, "color": color})
|
|
142
|
+
return {"parts": parts, "stdout": out.getvalue()[-MAX_OUTPUT:]}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _load(code: str, model_dir: str) -> list[dict]:
|
|
146
|
+
"""Parts for a script, from the cache or by running it. Raises ModelError if the script fails."""
|
|
147
|
+
key = hashlib.sha256(code.encode()).hexdigest()
|
|
148
|
+
if key in _cache:
|
|
149
|
+
_cache.move_to_end(key)
|
|
150
|
+
return _cache[key]
|
|
151
|
+
result = _execute(code, model_dir)
|
|
152
|
+
if "error" in result:
|
|
153
|
+
e = result["error"]
|
|
154
|
+
raise ModelError(f"The current script no longer runs: {e['message']}" + (f" (line {e['line']})" if e["line"] else ""))
|
|
155
|
+
_remember(key, result["parts"])
|
|
156
|
+
return result["parts"]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _remember(key: str, parts: list[dict]) -> None:
|
|
160
|
+
_cache[key] = parts
|
|
161
|
+
_cache.move_to_end(key)
|
|
162
|
+
while len(_cache) > CACHE_SIZE:
|
|
163
|
+
_cache.popitem(last=False)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# ---------------------------------------------------------------- describing parts
|
|
167
|
+
|
|
168
|
+
def _r(v: float, digits: int = 3) -> float:
|
|
169
|
+
return round(float(v), digits) + 0.0 # + 0.0 turns -0.0 into 0.0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _vec(v) -> list[float]:
|
|
173
|
+
return [_r(v.x), _r(v.y), _r(v.z)]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _summary(part: dict) -> dict:
|
|
177
|
+
"""Size, topology and mass properties. Kept on the part: on big imports this takes seconds."""
|
|
178
|
+
if "summary" not in part:
|
|
179
|
+
part["summary"] = _measure_part(part)
|
|
180
|
+
return part["summary"]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _measure_part(part: dict) -> dict:
|
|
184
|
+
shape = part["shape"]
|
|
185
|
+
bb = shape.BoundingBox()
|
|
186
|
+
info = {
|
|
187
|
+
"name": part["name"],
|
|
188
|
+
"size": [_r(bb.xlen), _r(bb.ylen), _r(bb.zlen)],
|
|
189
|
+
"min": [_r(bb.xmin), _r(bb.ymin), _r(bb.zmin)],
|
|
190
|
+
"max": [_r(bb.xmax), _r(bb.ymax), _r(bb.zmax)],
|
|
191
|
+
"solids": len(shape.Solids()),
|
|
192
|
+
"faces": len(shape.Faces()),
|
|
193
|
+
"edges": len(shape.Edges()),
|
|
194
|
+
"valid": bool(shape.isValid()),
|
|
195
|
+
}
|
|
196
|
+
try:
|
|
197
|
+
info["volume"] = _r(shape.Volume())
|
|
198
|
+
info["area"] = _r(shape.Area())
|
|
199
|
+
info["center_of_mass"] = _vec(shape.Center())
|
|
200
|
+
except Exception: # noqa: BLE001 - wires and empty compounds have no mass properties
|
|
201
|
+
pass
|
|
202
|
+
if part["color"]:
|
|
203
|
+
info["color"] = [_r(c) for c in part["color"]]
|
|
204
|
+
return info
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def op_run(code: str, model_dir: str) -> dict:
|
|
208
|
+
result = _execute(code, model_dir)
|
|
209
|
+
if "error" in result:
|
|
210
|
+
return result
|
|
211
|
+
_remember(hashlib.sha256(code.encode()).hexdigest(), result["parts"])
|
|
212
|
+
return {"parts": [_summary(p) for p in result["parts"]], "stdout": result["stdout"]}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _part(parts: list[dict], name: str | None) -> dict:
|
|
216
|
+
if name is None:
|
|
217
|
+
if len(parts) == 1:
|
|
218
|
+
return parts[0]
|
|
219
|
+
raise ModelError("This model has several parts; name one of: " + ", ".join(p["name"] for p in parts))
|
|
220
|
+
for p in parts:
|
|
221
|
+
if p["name"] == name:
|
|
222
|
+
return p
|
|
223
|
+
raise ModelError(f"No part named '{name}'. Parts: " + ", ".join(p["name"] for p in parts))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
KINDS = {"faces": "Faces", "edges": "Edges", "vertices": "Vertices"}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _select(parts: list[dict], sel: dict) -> tuple[list, list[int], str]:
|
|
230
|
+
"""Resolve {'part', 'kind', 'selector', 'index'} to (shapes, their indices, kind).
|
|
231
|
+
|
|
232
|
+
With no kind the whole part is selected. Indices are positions in the
|
|
233
|
+
part's own face/edge/vertex list, which is what `inspect` prints.
|
|
234
|
+
"""
|
|
235
|
+
import cadquery as cq
|
|
236
|
+
|
|
237
|
+
part = _part(parts, sel.get("part"))
|
|
238
|
+
kind = sel.get("kind")
|
|
239
|
+
if not kind:
|
|
240
|
+
return [part["shape"]], [], "part"
|
|
241
|
+
if kind not in KINDS:
|
|
242
|
+
raise ModelError("kind must be one of: faces, edges, vertices.")
|
|
243
|
+
everything = getattr(part["shape"], KINDS[kind])()
|
|
244
|
+
chosen = list(range(len(everything)))
|
|
245
|
+
if sel.get("selector"):
|
|
246
|
+
try:
|
|
247
|
+
picked = getattr(cq.Workplane("XY").newObject([part["shape"]]), kind)(sel["selector"]).vals()
|
|
248
|
+
except Exception as exc: # noqa: BLE001
|
|
249
|
+
raise ModelError(f"Selector '{sel['selector']}' is not valid: {exc}") from exc
|
|
250
|
+
chosen = [i for i, s in enumerate(everything) if any(s.isSame(p) for p in picked)]
|
|
251
|
+
if sel.get("index") is not None:
|
|
252
|
+
wanted = sel["index"] if isinstance(sel["index"], list) else [sel["index"]]
|
|
253
|
+
bad = [i for i in wanted if not 0 <= i < len(everything)]
|
|
254
|
+
if bad:
|
|
255
|
+
raise ModelError(f"{part['name']} has {len(everything)} {kind}; no index {bad[0]}.")
|
|
256
|
+
chosen = [i for i in chosen if i in wanted]
|
|
257
|
+
return [everything[i] for i in chosen], chosen, kind
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _radius(shape) -> float | None:
|
|
261
|
+
from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface
|
|
262
|
+
from OCP.GeomAbs import GeomAbs_Circle, GeomAbs_Cone, GeomAbs_Cylinder, GeomAbs_Sphere, GeomAbs_Torus
|
|
263
|
+
|
|
264
|
+
try:
|
|
265
|
+
if shape.ShapeType() == "Edge":
|
|
266
|
+
c = BRepAdaptor_Curve(shape.wrapped)
|
|
267
|
+
return _r(c.Circle().Radius()) if c.GetType() == GeomAbs_Circle else None
|
|
268
|
+
s = BRepAdaptor_Surface(shape.wrapped)
|
|
269
|
+
t = s.GetType()
|
|
270
|
+
if t == GeomAbs_Cylinder:
|
|
271
|
+
return _r(s.Cylinder().Radius())
|
|
272
|
+
if t == GeomAbs_Sphere:
|
|
273
|
+
return _r(s.Sphere().Radius())
|
|
274
|
+
if t == GeomAbs_Torus:
|
|
275
|
+
return _r(s.Torus().MinorRadius())
|
|
276
|
+
if t == GeomAbs_Cone:
|
|
277
|
+
return _r(s.Cone().RefRadius())
|
|
278
|
+
except Exception: # noqa: BLE001
|
|
279
|
+
pass
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def op_inspect(code: str, model_dir: str, sel: dict) -> dict:
|
|
284
|
+
parts = _load(code, model_dir)
|
|
285
|
+
sel = {**sel, "kind": sel.get("kind") or "faces"}
|
|
286
|
+
shapes, indices, kind = _select(parts, sel)
|
|
287
|
+
rows = []
|
|
288
|
+
for i, s in list(zip(indices, shapes))[:MAX_ROWS]:
|
|
289
|
+
row = {"index": i}
|
|
290
|
+
if kind == "vertices":
|
|
291
|
+
row["at"] = _vec(s.Center())
|
|
292
|
+
else:
|
|
293
|
+
row["type"] = s.geomType()
|
|
294
|
+
row["center"] = _vec(s.Center())
|
|
295
|
+
radius = _radius(s)
|
|
296
|
+
if radius is not None:
|
|
297
|
+
row["radius"] = radius
|
|
298
|
+
if kind == "faces":
|
|
299
|
+
row["area"] = _r(s.Area())
|
|
300
|
+
if s.geomType() == "PLANE":
|
|
301
|
+
row["normal"] = _vec(s.normalAt())
|
|
302
|
+
else:
|
|
303
|
+
row["length"] = _r(s.Length())
|
|
304
|
+
if s.geomType() == "LINE":
|
|
305
|
+
row["from"], row["to"] = _vec(s.startPoint()), _vec(s.endPoint())
|
|
306
|
+
rows.append(row)
|
|
307
|
+
return {"part": _part(parts, sel.get("part"))["name"], "kind": kind, "matched": len(shapes),
|
|
308
|
+
"shown": len(rows), "rows": rows}
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def op_measure(code: str, model_dir: str, a: dict, b: dict) -> dict:
|
|
312
|
+
import cadquery as cq
|
|
313
|
+
from OCP.BRepExtrema import BRepExtrema_DistShapeShape
|
|
314
|
+
|
|
315
|
+
parts = _load(code, model_dir)
|
|
316
|
+
sa, _, ka = _select(parts, a)
|
|
317
|
+
sb, _, kb = _select(parts, b)
|
|
318
|
+
if not sa or not sb:
|
|
319
|
+
raise ModelError("One of the selections matched nothing.")
|
|
320
|
+
one = lambda shapes: shapes[0] if len(shapes) == 1 else cq.Compound.makeCompound(shapes) # noqa: E731
|
|
321
|
+
dist = BRepExtrema_DistShapeShape(one(sa).wrapped, one(sb).wrapped)
|
|
322
|
+
if not dist.IsDone():
|
|
323
|
+
raise ModelError("The kernel could not measure between these selections.")
|
|
324
|
+
p1, p2 = dist.PointOnShape1(1), dist.PointOnShape2(1)
|
|
325
|
+
out = {"distance": _r(dist.Value()), "from": [_r(p1.X()), _r(p1.Y()), _r(p1.Z())], "to": [_r(p2.X()), _r(p2.Y()), _r(p2.Z())]}
|
|
326
|
+
|
|
327
|
+
def direction(shapes, kind):
|
|
328
|
+
if len(shapes) != 1:
|
|
329
|
+
return None
|
|
330
|
+
s = shapes[0]
|
|
331
|
+
if kind == "faces" and s.geomType() == "PLANE":
|
|
332
|
+
return s.normalAt()
|
|
333
|
+
if kind == "edges" and s.geomType() == "LINE":
|
|
334
|
+
return s.endPoint() - s.startPoint()
|
|
335
|
+
return None
|
|
336
|
+
|
|
337
|
+
da, db = direction(sa, ka), direction(sb, kb)
|
|
338
|
+
if da is not None and db is not None:
|
|
339
|
+
out["angle_degrees"] = _r(math.degrees(da.getAngle(db)), 2)
|
|
340
|
+
return out
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# ---------------------------------------------------------------- meshes for the viewer
|
|
344
|
+
|
|
345
|
+
def _triangulate(shape, tolerance):
|
|
346
|
+
"""Mesh the shape and read the triangulation into numpy arrays.
|
|
347
|
+
|
|
348
|
+
Does what cq.Shape.tessellate does, but much faster on big parts: OCCT meshes
|
|
349
|
+
the faces in parallel, and triangles are read with Triangle(i) rather than by
|
|
350
|
+
iterating Triangles(), which in OCP costs ~60 µs per triangle (9 s for a
|
|
351
|
+
150k-triangle STEP import).
|
|
352
|
+
"""
|
|
353
|
+
import numpy as np
|
|
354
|
+
from OCP.BRep import BRep_Tool
|
|
355
|
+
from OCP.BRepMesh import BRepMesh_IncrementalMesh
|
|
356
|
+
from OCP.TopAbs import TopAbs_FACE, TopAbs_REVERSED
|
|
357
|
+
from OCP.TopExp import TopExp_Explorer
|
|
358
|
+
from OCP.TopLoc import TopLoc_Location
|
|
359
|
+
from OCP.TopoDS import TopoDS
|
|
360
|
+
|
|
361
|
+
BRepMesh_IncrementalMesh(shape.wrapped, tolerance, False, MESH_ANGLE, True)
|
|
362
|
+
verts, tris, offset = [], [], 0
|
|
363
|
+
explorer = TopExp_Explorer(shape.wrapped, TopAbs_FACE)
|
|
364
|
+
while explorer.More():
|
|
365
|
+
face = TopoDS.Face_s(explorer.Current())
|
|
366
|
+
explorer.Next()
|
|
367
|
+
loc = TopLoc_Location()
|
|
368
|
+
poly = BRep_Tool.Triangulation_s(face, loc)
|
|
369
|
+
if poly is None:
|
|
370
|
+
continue
|
|
371
|
+
v = np.array([poly.Node(i).Coord() for i in range(1, poly.NbNodes() + 1)], dtype=np.float64)
|
|
372
|
+
t = np.array([poly.Triangle(i).Get() for i in range(1, poly.NbTriangles() + 1)], dtype=np.int64) - 1
|
|
373
|
+
if not loc.IsIdentity():
|
|
374
|
+
trsf = loc.Transformation()
|
|
375
|
+
m = np.array([[trsf.Value(r, c) for c in range(1, 5)] for r in range(1, 4)])
|
|
376
|
+
v = v @ m[:, :3].T + m[:, 3]
|
|
377
|
+
if face.Orientation() == TopAbs_REVERSED:
|
|
378
|
+
t = t[:, [0, 2, 1]]
|
|
379
|
+
verts.append(v)
|
|
380
|
+
tris.append(t + offset)
|
|
381
|
+
offset += len(v)
|
|
382
|
+
if not verts:
|
|
383
|
+
return np.zeros((0, 3)), np.zeros((0, 3), dtype=np.uint32)
|
|
384
|
+
return np.concatenate(verts), np.concatenate(tris).astype(np.uint32)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _mesh(shape, tolerance=MESH_TOLERANCE):
|
|
388
|
+
"""Triangles with per-vertex normals. Vertices are not shared between faces, so creases stay sharp."""
|
|
389
|
+
import numpy as np
|
|
390
|
+
|
|
391
|
+
v, t = _triangulate(shape, tolerance)
|
|
392
|
+
n = np.zeros_like(v)
|
|
393
|
+
if len(t):
|
|
394
|
+
face_n = np.cross(v[t[:, 1]] - v[t[:, 0]], v[t[:, 2]] - v[t[:, 0]])
|
|
395
|
+
for k in range(3):
|
|
396
|
+
np.add.at(n, t[:, k], face_n)
|
|
397
|
+
length = np.linalg.norm(n, axis=1, keepdims=True)
|
|
398
|
+
n = np.divide(n, length, out=np.zeros_like(n), where=length > 0)
|
|
399
|
+
return v.astype(np.float32), n.astype(np.float32), t
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def op_mesh(code: str, model_dir: str) -> dict:
|
|
403
|
+
import base64
|
|
404
|
+
|
|
405
|
+
key = hashlib.sha256(code.encode()).hexdigest()[:12]
|
|
406
|
+
out = []
|
|
407
|
+
for i, p in enumerate(_load(code, model_dir)):
|
|
408
|
+
v, n, t = _mesh(p["shape"])
|
|
409
|
+
info = _summary(p)
|
|
410
|
+
b64 = lambda a: base64.b64encode(a.tobytes()).decode() # noqa: E731
|
|
411
|
+
out.append({"id": p["name"], "key": f"{key}-{i}", "name": p["name"], "color": info.get("color"),
|
|
412
|
+
"size": info["size"], "volume": info.get("volume"), "triangles": int(len(t)),
|
|
413
|
+
"positions": b64(v), "normals": b64(n), "indices": b64(t)})
|
|
414
|
+
return {"parts": out}
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
# ---------------------------------------------------------------- pictures
|
|
418
|
+
|
|
419
|
+
VIEWS = { # name -> (where the camera sits relative to the model, which way is up)
|
|
420
|
+
"iso": ((1, -1, 0.8), (0, 0, 1)),
|
|
421
|
+
"front": ((0, -1, 0), (0, 0, 1)),
|
|
422
|
+
"back": ((0, 1, 0), (0, 0, 1)),
|
|
423
|
+
"right": ((1, 0, 0), (0, 0, 1)),
|
|
424
|
+
"left": ((-1, 0, 0), (0, 0, 1)),
|
|
425
|
+
"top": ((0, 0, 1), (0, 1, 0)),
|
|
426
|
+
"bottom": ((0, 0, -1), (0, 1, 0)),
|
|
427
|
+
}
|
|
428
|
+
FOUR = ["iso", "top", "front", "right"]
|
|
429
|
+
PART_COLOR = (0.62, 0.68, 0.74)
|
|
430
|
+
HIGHLIGHT = (0.92, 0.26, 0.21)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _polydata(shape, tolerance):
|
|
434
|
+
import numpy as np
|
|
435
|
+
import vtk
|
|
436
|
+
from vtk.util import numpy_support
|
|
437
|
+
|
|
438
|
+
v, n, t = _mesh(shape, tolerance)
|
|
439
|
+
pd = vtk.vtkPolyData()
|
|
440
|
+
pts = vtk.vtkPoints()
|
|
441
|
+
pts.SetData(numpy_support.numpy_to_vtk(v, deep=True))
|
|
442
|
+
pd.SetPoints(pts)
|
|
443
|
+
cells = vtk.vtkCellArray()
|
|
444
|
+
offsets = numpy_support.numpy_to_vtkIdTypeArray(np.arange(0, 3 * len(t) + 1, 3, dtype=np.int64), deep=True)
|
|
445
|
+
conn = numpy_support.numpy_to_vtkIdTypeArray(t.astype(np.int64).ravel(), deep=True)
|
|
446
|
+
cells.SetData(offsets, conn)
|
|
447
|
+
pd.SetPolys(cells)
|
|
448
|
+
pd.GetPointData().SetNormals(numpy_support.numpy_to_vtk(n, deep=True))
|
|
449
|
+
return pd
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _edge_polydata(shape, tolerance):
|
|
453
|
+
"""The part's real edges as polylines, so pictures show the same outlines a drawing would."""
|
|
454
|
+
import vtk
|
|
455
|
+
from OCP.BRepAdaptor import BRepAdaptor_Curve
|
|
456
|
+
from OCP.GCPnts import GCPnts_QuasiUniformDeflection
|
|
457
|
+
|
|
458
|
+
pts, lines = vtk.vtkPoints(), vtk.vtkCellArray()
|
|
459
|
+
for e in shape.Edges():
|
|
460
|
+
try:
|
|
461
|
+
curve = BRepAdaptor_Curve(e.wrapped)
|
|
462
|
+
disc = GCPnts_QuasiUniformDeflection(curve, tolerance)
|
|
463
|
+
if not disc.IsDone() or disc.NbPoints() < 2:
|
|
464
|
+
continue
|
|
465
|
+
ids = []
|
|
466
|
+
for i in range(1, disc.NbPoints() + 1):
|
|
467
|
+
p = disc.Value(i)
|
|
468
|
+
ids.append(pts.InsertNextPoint(p.X(), p.Y(), p.Z()))
|
|
469
|
+
lines.InsertNextCell(len(ids), ids)
|
|
470
|
+
except Exception: # noqa: BLE001 - degenerate edges (sphere poles) have no curve
|
|
471
|
+
continue
|
|
472
|
+
pd = vtk.vtkPolyData()
|
|
473
|
+
pd.SetPoints(pts)
|
|
474
|
+
pd.SetLines(lines)
|
|
475
|
+
return pd
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _section(shape, plane: dict):
|
|
479
|
+
"""Cut the part with a plane and keep the side behind it, so the inside is visible."""
|
|
480
|
+
import cadquery as cq
|
|
481
|
+
|
|
482
|
+
origin = cq.Vector(*plane.get("origin", (0, 0, 0)))
|
|
483
|
+
normal = cq.Vector(*plane["normal"]).normalized()
|
|
484
|
+
reach = shape.BoundingBox().DiagonalLength * 4 + 10
|
|
485
|
+
block = cq.Workplane(cq.Plane(origin=origin.toTuple(), normal=normal.toTuple())).rect(reach, reach).extrude(reach).val()
|
|
486
|
+
return shape.cut(block)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def op_render(code: str, model_dir: str, spec: dict) -> dict:
|
|
490
|
+
import vtk
|
|
491
|
+
|
|
492
|
+
everything = _load(code, model_dir)
|
|
493
|
+
parts = [_part(everything, name) for name in spec["parts"]] if spec.get("parts") else everything
|
|
494
|
+
view = spec.get("view") or "four"
|
|
495
|
+
names = FOUR if view == "four" else [view]
|
|
496
|
+
custom = spec.get("direction") if view != "four" else None
|
|
497
|
+
if not custom and any(n not in VIEWS for n in names):
|
|
498
|
+
raise ModelError("view must be one of: four, " + ", ".join(VIEWS) + " (or pass a direction).")
|
|
499
|
+
width, height = int(spec.get("width") or 1000), int(spec.get("height") or 760)
|
|
500
|
+
|
|
501
|
+
highlight = _select(everything, spec["highlight"])[0] if spec.get("highlight") else []
|
|
502
|
+
|
|
503
|
+
shapes = []
|
|
504
|
+
for p in parts:
|
|
505
|
+
shape = p["shape"]
|
|
506
|
+
if spec.get("section"):
|
|
507
|
+
try:
|
|
508
|
+
shape = _section(shape, spec["section"])
|
|
509
|
+
except Exception as exc: # noqa: BLE001
|
|
510
|
+
raise ModelError(f"Could not section '{p['name']}': {exc}") from exc
|
|
511
|
+
shapes.append((shape, p["color"]))
|
|
512
|
+
diag = max((s.BoundingBox().DiagonalLength for s, _ in shapes), default=1.0) or 1.0
|
|
513
|
+
tolerance = max(diag / 2000, 0.005)
|
|
514
|
+
|
|
515
|
+
actors = []
|
|
516
|
+
for shape, color in shapes:
|
|
517
|
+
mapper = vtk.vtkPolyDataMapper()
|
|
518
|
+
mapper.SetInputData(_polydata(shape, tolerance))
|
|
519
|
+
mapper.SetResolveCoincidentTopologyToPolygonOffset()
|
|
520
|
+
actor = vtk.vtkActor()
|
|
521
|
+
actor.SetMapper(mapper)
|
|
522
|
+
prop = actor.GetProperty()
|
|
523
|
+
prop.SetColor(*(color or PART_COLOR))
|
|
524
|
+
prop.SetAmbient(0.35)
|
|
525
|
+
prop.SetDiffuse(0.7)
|
|
526
|
+
prop.SetSpecular(0.05)
|
|
527
|
+
if highlight:
|
|
528
|
+
prop.SetOpacity(0.35)
|
|
529
|
+
actors.append(actor)
|
|
530
|
+
em = vtk.vtkPolyDataMapper()
|
|
531
|
+
em.SetInputData(_edge_polydata(shape, tolerance))
|
|
532
|
+
ea = vtk.vtkActor()
|
|
533
|
+
ea.SetMapper(em)
|
|
534
|
+
ea.GetProperty().SetColor(0.08, 0.1, 0.13)
|
|
535
|
+
ea.GetProperty().SetLineWidth(1.6)
|
|
536
|
+
ea.GetProperty().LightingOff()
|
|
537
|
+
actors.append(ea)
|
|
538
|
+
for h in highlight:
|
|
539
|
+
mapper = vtk.vtkPolyDataMapper()
|
|
540
|
+
mapper.SetInputData(_edge_polydata(h, tolerance) if h.ShapeType() == "Edge" else _polydata(h, tolerance))
|
|
541
|
+
actor = vtk.vtkActor()
|
|
542
|
+
actor.SetMapper(mapper)
|
|
543
|
+
actor.GetProperty().SetColor(*HIGHLIGHT)
|
|
544
|
+
actor.GetProperty().SetLineWidth(5)
|
|
545
|
+
actor.GetProperty().LightingOff()
|
|
546
|
+
actors.append(actor)
|
|
547
|
+
|
|
548
|
+
win = vtk.vtkRenderWindow()
|
|
549
|
+
win.SetOffScreenRendering(1)
|
|
550
|
+
win.SetSize(width, height)
|
|
551
|
+
win.SetMultiSamples(8)
|
|
552
|
+
cols = 2 if len(names) > 1 else 1
|
|
553
|
+
rows = math.ceil(len(names) / cols)
|
|
554
|
+
for i, name in enumerate(names):
|
|
555
|
+
ren = vtk.vtkRenderer()
|
|
556
|
+
ren.SetBackground(0.96, 0.97, 0.98)
|
|
557
|
+
col, row = i % cols, i // cols
|
|
558
|
+
ren.SetViewport(col / cols, 1 - (row + 1) / rows, (col + 1) / cols, 1 - row / rows)
|
|
559
|
+
for a in actors:
|
|
560
|
+
ren.AddActor(a)
|
|
561
|
+
direction, up = VIEWS.get(name, VIEWS["iso"])
|
|
562
|
+
if custom:
|
|
563
|
+
direction = tuple(float(d) for d in custom)
|
|
564
|
+
steep = abs(direction[2]) > 0.99 * math.sqrt(sum(d * d for d in direction))
|
|
565
|
+
up = (0, 1, 0) if steep else (0, 0, 1)
|
|
566
|
+
cam = ren.GetActiveCamera()
|
|
567
|
+
cam.ParallelProjectionOn() # no perspective: lengths can be compared by eye
|
|
568
|
+
cam.SetFocalPoint(0, 0, 0)
|
|
569
|
+
cam.SetPosition(*direction)
|
|
570
|
+
cam.SetViewUp(*up)
|
|
571
|
+
ren.ResetCamera()
|
|
572
|
+
cam.Zoom(1.25)
|
|
573
|
+
ren.ResetCameraClippingRange()
|
|
574
|
+
label = vtk.vtkTextActor()
|
|
575
|
+
label.SetInput("CUSTOM" if custom else name.upper())
|
|
576
|
+
label.GetTextProperty().SetColor(0.3, 0.36, 0.42)
|
|
577
|
+
label.GetTextProperty().SetFontSize(15)
|
|
578
|
+
label.SetPosition(10, 8)
|
|
579
|
+
ren.AddViewProp(label)
|
|
580
|
+
win.AddRenderer(ren)
|
|
581
|
+
win.Render()
|
|
582
|
+
grab = vtk.vtkWindowToImageFilter()
|
|
583
|
+
grab.SetInput(win)
|
|
584
|
+
grab.ReadFrontBufferOff()
|
|
585
|
+
grab.Update()
|
|
586
|
+
writer = vtk.vtkPNGWriter()
|
|
587
|
+
writer.WriteToMemoryOn()
|
|
588
|
+
writer.SetInputConnection(grab.GetOutputPort())
|
|
589
|
+
writer.Write()
|
|
590
|
+
data = bytes(memoryview(writer.GetResult()))
|
|
591
|
+
win.Finalize()
|
|
592
|
+
return {"png": data, "views": ["custom"] if custom else names}
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
# ---------------------------------------------------------------- files out
|
|
596
|
+
|
|
597
|
+
FORMATS = ("step", "stl", "3mf", "brep", "glb", "svg")
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def op_export(code: str, model_dir: str, fmt: str, path: str, names: list[str] | None) -> dict:
|
|
601
|
+
import cadquery as cq
|
|
602
|
+
|
|
603
|
+
parts = _load(code, model_dir)
|
|
604
|
+
if names:
|
|
605
|
+
parts = [_part(parts, n) for n in names]
|
|
606
|
+
if fmt not in FORMATS:
|
|
607
|
+
raise ModelError("format must be one of: " + ", ".join(FORMATS))
|
|
608
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
609
|
+
if fmt in ("step", "glb"): # these formats keep part names and colours
|
|
610
|
+
assy = cq.Assembly()
|
|
611
|
+
for p in parts:
|
|
612
|
+
assy.add(p["shape"], name=p["name"], color=cq.Color(*p["color"]) if p["color"] else None)
|
|
613
|
+
assy.export(path)
|
|
614
|
+
else:
|
|
615
|
+
shape = parts[0]["shape"] if len(parts) == 1 else cq.Compound.makeCompound([p["shape"] for p in parts])
|
|
616
|
+
if fmt == "svg":
|
|
617
|
+
cq.exporters.export(cq.Workplane("XY").newObject([shape]), path, opt={"showAxes": False, "projectionDir": (1, -1, 0.8)})
|
|
618
|
+
else:
|
|
619
|
+
cq.exporters.export(shape, path, tolerance=0.01, angularTolerance=0.1)
|
|
620
|
+
return {"path": path, "bytes": os.path.getsize(path), "parts": [p["name"] for p in parts]}
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
# ---------------------------------------------------------------- request loop
|
|
624
|
+
|
|
625
|
+
OPS = {"run": op_run, "inspect": op_inspect, "measure": op_measure, "mesh": op_mesh, "render": op_render, "export": op_export}
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def serve(conn) -> None:
|
|
629
|
+
"""Answer requests from the parent until the pipe closes."""
|
|
630
|
+
import cadquery # noqa: F401 - pay the import cost once, before the first request
|
|
631
|
+
|
|
632
|
+
conn.send({"ready": True})
|
|
633
|
+
while True:
|
|
634
|
+
try:
|
|
635
|
+
op, kwargs = conn.recv()
|
|
636
|
+
except (EOFError, KeyboardInterrupt):
|
|
637
|
+
return
|
|
638
|
+
try:
|
|
639
|
+
conn.send({"ok": OPS[op](**kwargs)})
|
|
640
|
+
except ModelError as exc:
|
|
641
|
+
conn.send({"problem": str(exc)})
|
|
642
|
+
except BaseException as exc: # noqa: BLE001
|
|
643
|
+
conn.send({"problem": f"{type(exc).__name__}: {exc}"})
|