"""Whitelisted geometry tools exposed to the LLM (JSON-schema function calling)."""
from __future__ import annotations
import math
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
import numpy as np
from .. import _core as nf
from . import constraints, verify
Vec = list[float]
[docs]
@dataclass
class Workspace:
"""Named object store the LLM operates on."""
objects: dict[str, Any] = field(default_factory=dict)
[docs]
def put(self, name: str, obj: Any) -> str:
self.objects[name] = obj
return f"stored {name}: {obj!r}"
[docs]
def get(self, name: str) -> Any:
if name not in self.objects:
raise KeyError(f"unknown object '{name}'. Known: {sorted(self.objects)}")
return self.objects[name]
_VEC = {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}
_NAME = {"type": "string", "description": "name of the object in the workspace"}
def _obj(props: dict[str, Any], required: list[str]) -> dict[str, Any]:
return {"type": "object", "properties": props, "required": required}
def _deg(a: float) -> float:
return math.radians(a)
def _build_tools() -> list[Tool]:
T: list[Tool] = []
def add(name, desc, props, req):
def deco(f):
T.append(Tool(name, desc, _obj(props, req), f))
return f
return deco
@add("make_line", "Create a straight line segment.",
{"name": _NAME, "p0": _VEC, "p1": _VEC}, ["name", "p0", "p1"])
def _(ws, name, p0, p1):
return ws.put(name, nf.make_line(p0, p1))
@add("make_circle", "Create a full circle (exact NURBS).",
{"name": _NAME, "center": _VEC, "normal": _VEC, "radius": {"type": "number"}},
["name", "center", "normal", "radius"])
def _(ws, name, center, normal, radius):
return ws.put(name, nf.make_circle(center, normal, radius))
@add("make_arc", "Create a circular arc. Angles in degrees, measured from x_axis to y_axis.",
{"name": _NAME, "center": _VEC, "x_axis": _VEC, "y_axis": _VEC,
"radius": {"type": "number"}, "start_deg": {"type": "number"}, "end_deg": {"type": "number"}},
["name", "center", "x_axis", "y_axis", "radius", "start_deg", "end_deg"])
def _(ws, name, center, x_axis, y_axis, radius, start_deg, end_deg):
return ws.put(name, nf.make_arc(center, x_axis, y_axis, radius, _deg(start_deg), _deg(end_deg)))
@add("make_polygon", "Create a closed regular polygon (n vertices on a circle of the given "
"radius about center, in the plane with the given normal).",
{"name": _NAME, "center": _VEC, "normal": _VEC, "radius": {"type": "number"},
"n": {"type": "integer", "minimum": 3}}, ["name", "center", "normal", "radius", "n"])
def _(ws, name, center, normal, radius, n):
return ws.put(name, nf.make_polygon(center, normal, radius, n))
@add("make_helix", "Create a helix about an axis starting at a point (its distance from the "
"axis is the radius): pitch = rise per turn (0: planar spiral), turns > 0, optional "
"end_radius for a conical helix or spiral, left_handed to wind clockwise.",
{"name": _NAME, "axis_point": _VEC, "axis_dir": _VEC, "start": _VEC,
"pitch": {"type": "number"}, "turns": {"type": "number"},
"end_radius": {"type": "number"}, "left_handed": {"type": "boolean"}},
["name", "axis_point", "axis_dir", "start", "pitch", "turns"])
def _(ws, name, axis_point, axis_dir, start, pitch, turns, end_radius=-1.0,
left_handed=False):
return ws.put(name, nf.make_helix(axis_point, axis_dir, start, pitch, turns, end_radius,
left_handed))
@add("round_corners", "Round all corners of a planar curve (polyline, polygon, rectangle "
"outline) with circular arcs of the given radius; one smooth curve.",
{"name": _NAME, "source": _NAME, "radius": {"type": "number"}},
["name", "source", "radius"])
def _(ws, name, source, radius):
return ws.put(name, nf.fillet_corners(ws.get(source), radius))
@add("chamfer_corners", "Chamfer all corners of a curve (polyline, polygon, rectangle "
"outline) with straight cuts at the given distance from each corner; one curve.",
{"name": _NAME, "source": _NAME, "distance": {"type": "number"}},
["name", "source", "distance"])
def _(ws, name, source, distance):
return ws.put(name, nf.chamfer_corners(ws.get(source), distance))
@add("make_rectangle", "Create a planar rectangular surface.",
{"name": _NAME, "origin": _VEC, "edge_u": _VEC, "edge_v": _VEC},
["name", "origin", "edge_u", "edge_v"])
def _(ws, name, origin, edge_u, edge_v):
return ws.put(name, nf.make_rectangle(origin, edge_u, edge_v))
@add("revolve", "Revolve a curve about an axis to create a surface. Angle in degrees.",
{"name": _NAME, "profile": _NAME, "axis_point": _VEC, "axis_dir": _VEC,
"angle_deg": {"type": "number"}},
["name", "profile", "axis_point", "axis_dir", "angle_deg"])
def _(ws, name, profile, axis_point, axis_dir, angle_deg):
return ws.put(name, nf.revolve(ws.get(profile), axis_point, axis_dir, _deg(angle_deg)))
@add("extrude", "Extrude a curve along a direction vector to create a surface.",
{"name": _NAME, "profile": _NAME, "direction": _VEC}, ["name", "profile", "direction"])
def _(ws, name, profile, direction):
return ws.put(name, nf.extrude(ws.get(profile), direction))
@add("ruled", "Create a ruled surface between two curves.",
{"name": _NAME, "curve0": _NAME, "curve1": _NAME}, ["name", "curve0", "curve1"])
def _(ws, name, curve0, curve1):
return ws.put(name, nf.ruled(ws.get(curve0), ws.get(curve1)))
@add("translate", "Copy an object translated by a vector.",
{"name": _NAME, "source": _NAME, "vector": _VEC}, ["name", "source", "vector"])
def _(ws, name, source, vector):
return ws.put(name, ws.get(source).transformed(nf.Transform.translation(vector)))
@add("rotate", "Copy an object rotated about an axis. Angle in degrees.",
{"name": _NAME, "source": _NAME, "axis_point": _VEC, "axis_dir": _VEC,
"angle_deg": {"type": "number"}}, ["name", "source", "axis_point", "axis_dir", "angle_deg"])
def _(ws, name, source, axis_point, axis_dir, angle_deg):
t = nf.Transform.rotation(axis_point, axis_dir, _deg(angle_deg))
return ws.put(name, ws.get(source).transformed(t))
@add("mirror", "Copy an object mirrored at a plane (point + normal).",
{"name": _NAME, "source": _NAME, "plane_point": _VEC, "plane_normal": _VEC},
["name", "source", "plane_point", "plane_normal"])
def _(ws, name, source, plane_point, plane_normal):
return ws.put(name, ws.get(source).transformed(nf.Transform.mirror(plane_point, plane_normal)))
@add("polar_array", "Create count rotated copies about an axis; stored as name_0..name_{count-1}.",
{"name": _NAME, "source": _NAME, "axis_point": _VEC, "axis_dir": _VEC,
"count": {"type": "integer"}, "total_angle_deg": {"type": "number"}},
["name", "source", "axis_point", "axis_dir", "count", "total_angle_deg"])
def _(ws, name, source, axis_point, axis_dir, count, total_angle_deg):
ts = nf.polar_pattern(axis_point, axis_dir, int(count), _deg(total_angle_deg))
src = ws.get(source)
return "; ".join(ws.put(f"{name}_{i}", src.transformed(t)) for i, t in enumerate(ts))
@add("linear_array", "Create count translated copies; stored as name_0..name_{count-1}.",
{"name": _NAME, "source": _NAME, "step": _VEC, "count": {"type": "integer"}},
["name", "source", "step", "count"])
def _(ws, name, source, step, count):
src = ws.get(source)
return "; ".join(ws.put(f"{name}_{i}", src.transformed(t))
for i, t in enumerate(nf.linear_pattern(step, int(count))))
@add("list_objects", "List all objects in the workspace.", {}, [])
def _(ws):
return "\n".join(f"{k}: {v!r}" for k, v in ws.objects.items()) or "(empty)"
@add("closest_point", "Closest point of an object to a given point, with its parameters "
"and the distance.", {"name": _NAME, "point": _VEC}, ["name", "point"])
def _(ws, name, point):
r = nf.closest_point(ws.get(name), point)
params = f"u={r.u:.6g}" if isinstance(r, nf.CurvePoint) else f"u={r.u:.6g}, v={r.v:.6g}"
p = r.point
return f"{params}, point=({p.x:.6g}, {p.y:.6g}, {p.z:.6g}), distance={r.distance:.6g}"
@add("interpolate_points", "Create a smooth curve through the given points (in order).",
{"name": _NAME, "points": {"type": "array", "items": _VEC, "minItems": 2},
"degree": {"type": "integer", "description": "default 3"}}, ["name", "points"])
def _(ws, name, points, degree=3):
pts = np.asarray(points, dtype=float)
return ws.put(name, nf.interpolate_curve(pts, min(int(degree), len(pts) - 1)))
@add("fit_surface", "Fit a smooth surface to unordered measured points (e.g. a height "
"map). smoothing: 0.001 follows the points closely, 0.1-1 smooths noisy data. Reports "
"the max and rms deviation.",
{"name": _NAME, "points": {"type": "array", "items": _VEC, "minItems": 3},
"smoothing": {"type": "number"},
"num_ctrl": {"type": "integer", "description": "control points per direction, "
"0 = automatic"}},
["name", "points"])
def _(ws, name, points, smoothing=1e-3, num_ctrl=0):
f = nf.fit_surface(np.asarray(points, dtype=float), num_u=int(num_ctrl),
num_v=int(num_ctrl), smoothing=smoothing)
ws.put(name, f.surface)
return (f"stored {name}: max deviation {f.max_error:.3g}, rms {f.rms_error:.3g}, "
f"{f.surface.num_u} x {f.surface.num_v} control points")
@add("loft", "Create a smooth surface through several section curves (in the given order).",
{"name": _NAME, "sections": {"type": "array", "items": _NAME, "minItems": 2},
"degree": {"type": "integer", "description": "degree across the sections, default 3"}},
["name", "sections"])
def _(ws, name, sections, degree=3):
return ws.put(name, nf.loft([ws.get(s) for s in sections], int(degree)))
@add("sweep", "Sweep a profile curve along a path curve. The profile must be drawn at the "
"start of the path (typically in the plane normal to the path). Optional twist in "
"degrees over the whole path. With 'profiles' (several curves drawn where they cross "
"the path, e.g. a circle at the start and a larger one at the end) the cross-section "
"blends between them.",
{"name": _NAME, "profile": _NAME, "path": _NAME, "twist_deg": {"type": "number"},
"profiles": {"type": "array", "items": _NAME}},
["name", "path"])
def _(ws, name, path, profile=None, twist_deg=0.0, profiles=None):
opt = nf.SweepOptions(twist=_deg(twist_deg))
if profiles:
return ws.put(name, nf.sweep([ws.get(p) for p in profiles], ws.get(path),
options=opt))
if profile is None:
raise ValueError("give 'profile' or 'profiles'")
return ws.put(name, nf.sweep(ws.get(profile), ws.get(path), opt))
@add("rail_revolve", "Revolve a profile curve about an axis while its outer end follows a "
"rail curve (e.g. a reflector with an elliptic or square-ish rim): the profile is scaled "
"radially so its end stays on the rail; scale_height also scales heights.",
{"name": _NAME, "profile": _NAME, "rail": _NAME, "axis_point": _VEC, "axis_dir": _VEC,
"scale_height": {"type": "boolean"}},
["name", "profile", "rail", "axis_point", "axis_dir"])
def _(ws, name, profile, rail, axis_point, axis_dir, scale_height=False):
return ws.put(name, nf.rail_revolve(ws.get(profile), ws.get(rail), axis_point, axis_dir,
scale_height))
def _pieces(ws, name, surfaces):
if len(surfaces) == 1:
return ws.put(name, surfaces[0])
return ws.put(name, nf.Shell.sew([nf.TrimmedSurface(s) for s in surfaces]))
@add("extrude_tapered", "Tapered (draft-angle) extrusion of a planar profile along a "
"direction normal to its plane (the vector length is the height). angle_deg > 0 widens "
"the section towards the top, < 0 narrows it. Corners are mitred; a profile with "
"corners gives an open shell of faces (use 'cap' to close it).",
{"name": _NAME, "profile": _NAME, "direction": _VEC, "angle_deg": {"type": "number"}},
["name", "profile", "direction", "angle_deg"])
def _(ws, name, profile, direction, angle_deg):
return _pieces(ws, name, nf.extrude_tapered(ws.get(profile), direction,
_deg(angle_deg)))
@add("ribbon", "Planar strip of the given width along a curve (to the left seen from the "
"plane normal's tip; negative width: right). Corners are mitred.",
{"name": _NAME, "curve": _NAME, "width": {"type": "number"}, "plane_normal": _VEC},
["name", "curve", "width"])
def _(ws, name, curve, width, plane_normal=(0, 0, 1)):
return _pieces(ws, name, nf.ribbon(ws.get(curve), width, plane_normal))
@add("extrude_to_point", "Cone-like surface from a curve to an apex point (exact for "
"circles and arcs).",
{"name": _NAME, "curve": _NAME, "apex": _VEC}, ["name", "curve", "apex"])
def _(ws, name, curve, apex):
return ws.put(name, nf.extrude_to_point(ws.get(curve), apex))
@add("triangle_patch", "Three-sided surface filling three boundary curves that form a "
"closed loop (any orientation).",
{"name": _NAME, "c0": _NAME, "c1": _NAME, "c2": _NAME}, ["name", "c0", "c1", "c2"])
def _(ws, name, c0, c1, c2):
return ws.put(name, nf.triangle_patch(ws.get(c0), ws.get(c1), ws.get(c2)))
@add("rebuild", "Rebuild a curve or surface with a given number of control points "
"(uniform cubic B-spline by default), e.g. to simplify or unify it; reports the "
"maximum deviation.",
{"name": _NAME, "source": _NAME, "num_u": {"type": "integer", "minimum": 2},
"num_v": {"type": "integer", "minimum": 2,
"description": "surfaces only (default num_u)"},
"degree": {"type": "integer", "minimum": 1, "maximum": 7}},
["name", "source", "num_u"])
def _(ws, name, source, num_u, num_v=None, degree=3):
o = ws.get(source)
if isinstance(o, nf.NurbsCurve):
r = nf.rebuild_curve(o, num_u, degree)
out = ws.put(name, r.curve)
elif isinstance(o, nf.NurbsSurface):
r = nf.rebuild_surface(o, num_u, num_v or num_u, degree, degree)
out = ws.put(name, r.surface)
else:
raise TypeError(f"'{source}' is not a curve or surface")
return f"{out}; max deviation {r.max_error:.3g}"
@add("coons", "Create a surface filling four boundary curves that form a closed loop "
"(any orientation).",
{"name": _NAME, "c0": _NAME, "c1": _NAME, "d0": _NAME, "d1": _NAME},
["name", "c0", "c1", "d0", "d1"])
def _(ws, name, c0, c1, d0, d1):
return ws.put(name, nf.coons(ws.get(c0), ws.get(c1), ws.get(d0), ws.get(d1)))
@add("asphere", "Create an optical lens surface (sag along +z, vertex at the origin): "
"radius of curvature R (0 = flat; positive: centre at +z), conic constant k and optional "
"even aspheric coefficients A4, A6, ... over the clear radius.",
{"name": _NAME, "radius": {"type": "number"}, "conic": {"type": "number"},
"coefficients": {"type": "array", "items": {"type": "number"}},
"clear_radius": {"type": "number"}},
["name", "radius", "clear_radius"])
def _(ws, name, radius, clear_radius, conic=0.0, coefficients=None):
a = nf.Asphere(curvature=0.0 if radius == 0 else 1.0 / radius, conic=conic,
even=list(coefficients or []))
return ws.put(name, nf.asphere_surface(a, clear_radius))
@add("extend", "Extend a curve at its start or end (or a surface across a side umin/umax/"
"vmin/vmax) by a length. mode 'natural' continues the shape smoothly, 'linear' "
"continues straight along the tangent.",
{"name": _NAME, "source": _NAME,
"where": {"type": "string", "enum": ["start", "end", "umin", "umax", "vmin", "vmax"]},
"length": {"type": "number"},
"mode": {"type": "string", "enum": ["natural", "linear"]}},
["name", "source", "where", "length"])
def _(ws, name, source, where, length, mode="natural"):
o = ws.get(source)
kind = nf.Extension.Linear if mode == "linear" else nf.Extension.Natural
if isinstance(o, nf.NurbsCurve):
end = {"start": nf.CurveEnd.Start, "end": nf.CurveEnd.End}[where]
return ws.put(name, nf.extend(o, end, length, kind))
side = {"umin": nf.SurfaceSide.UMin, "umax": nf.SurfaceSide.UMax,
"vmin": nf.SurfaceSide.VMin, "vmax": nf.SurfaceSide.VMax}[where]
return ws.put(name, nf.extend(o, side, length, kind))
@add("offset", "Offset a curve or surface by a signed distance. Surfaces move along their "
"normal. Curves must be planar and move within their plane, to the left of the "
"direction of travel seen from plane_normal (default [0, 0, 1]; e.g. inwards for a "
"counter-clockwise circle). Fails if the distance reaches a radius of curvature.",
{"name": _NAME, "source": _NAME, "distance": {"type": "number"},
"plane_normal": {**_VEC, "description": "curves only, default [0, 0, 1]"}},
["name", "source", "distance"])
def _(ws, name, source, distance, plane_normal=None):
o = ws.get(source)
if isinstance(o, nf.NurbsCurve):
return ws.put(name, nf.offset_curve(o, distance, plane_normal or [0.0, 0.0, 1.0]))
return ws.put(name, nf.offset_surface(o, distance))
@add("fillet", "Round the corner between two objects with a constant radius. Two planar "
"intersecting curves: circular arc tangent to both, stored as name, with the trimmed "
"curves stored as name_a and name_b (a, arc, b form a smooth chain); the corner is "
"chosen automatically unless side_a/side_b are given (+1 left / -1 right of the curve "
"direction seen from plane_normal). Two surfaces: rolling-ball fillet surface stored as "
"name, contact curves as name_contact1/name_contact2; side_a/side_b = +1 (default) put "
"the ball on the normal side of a/b, -1 on the other side.",
{"name": _NAME, "a": _NAME, "b": _NAME, "radius": {"type": "number"},
"side_a": {"type": "integer", "enum": [-1, 0, 1]},
"side_b": {"type": "integer", "enum": [-1, 0, 1]},
"plane_normal": {**_VEC, "description": "curves only, default [0, 0, 1]"}},
["name", "a", "b", "radius"])
def _(ws, name, a, b, radius, side_a=None, side_b=None, plane_normal=None):
oa, ob = ws.get(a), ws.get(b)
if isinstance(oa, nf.NurbsCurve) and isinstance(ob, nf.NurbsCurve):
f = nf.fillet_curves(oa, ob, radius, plane_normal or [0.0, 0.0, 1.0],
side_a=side_a or 0, side_b=side_b or 0)
ws.put(f"{name}_a", f.trimmed_a)
ws.put(f"{name}_b", f.trimmed_b)
return (ws.put(name, f.arc) + f"; trimmed curves {name}_a, {name}_b; centre "
f"({f.center.x:.6g}, {f.center.y:.6g}, {f.center.z:.6g})")
if isinstance(oa, nf.NurbsSurface) and isinstance(ob, nf.NurbsSurface):
f = nf.fillet_surfaces(oa, ob, radius, side1=side_a or 1, side2=side_b or 1)
ws.put(f"{name}_contact1", f.contact1)
ws.put(f"{name}_contact2", f.contact2)
return ws.put(name, f.surface) + f"; contact curves {name}_contact1, {name}_contact2"
raise ValueError("fillet needs two curves or two surfaces")
@add("chamfer", "Straight cut between two intersecting curves: from the point of a at "
"distance_a from their intersection to the point of b at distance_b (default "
"distance_a). The cut is stored as name, the trimmed curves as name_a and name_b "
"(a, cut, b form a chain).",
{"name": _NAME, "a": _NAME, "b": _NAME, "distance_a": {"type": "number"},
"distance_b": {"type": "number"}}, ["name", "a", "b", "distance_a"])
def _(ws, name, a, b, distance_a, distance_b=None):
c = nf.chamfer_curves(ws.get(a), ws.get(b), distance_a, distance_b)
ws.put(f"{name}_a", c.trimmed_a)
ws.put(f"{name}_b", c.trimmed_b)
return ws.put(name, c.line) + f"; trimmed curves {name}_a, {name}_b"
@add("intersect", "Intersection of two objects: points for curve/curve and curve/surface; "
"for surface/surface the intersection curves are stored as name_1, name_2, ...",
{"a": _NAME, "b": _NAME, "name": {"type": "string", "description":
"base name for surface/surface curves (default 'cut')"}},
["a", "b"])
def _(ws, a, b, name="cut"):
oa, ob = ws.get(a), ws.get(b)
if isinstance(oa, nf.NurbsSurface) and isinstance(ob, nf.NurbsSurface):
res = nf.intersect(oa, ob)
out = []
for i, c in enumerate(res.curves, 1):
ws.put(f"{name}_{i}", c.curve)
out.append(f"{name}_{i}: {'closed' if c.closed else 'open'}, length "
f"{nf.length(c.curve):.6g}")
out += [f"touching point ({p.point.x:.6g}, {p.point.y:.6g}, {p.point.z:.6g})"
for p in res.points]
return "; ".join(out) if out else "no intersection"
if isinstance(oa, nf.NurbsSurface):
oa, ob = ob, oa
hits = nf.intersect(oa, ob)
if not hits:
return "no intersection"
return "; ".join(f"({h.point.x:.6g}, {h.point.y:.6g}, {h.point.z:.6g})" for h in hits)
@add("trim_circle", "Restrict a surface to a circular region of its parameter domain "
"(e.g. a circular aperture of an optical surface: for sag/graph surfaces u = x, v = y).",
{"name": _NAME, "source": _NAME, "center_u": {"type": "number"},
"center_v": {"type": "number"}, "radius": {"type": "number"}},
["name", "source", "center_u", "center_v", "radius"])
def _(ws, name, source, center_u, center_v, radius):
s = ws.get(source)
return ws.put(name, nf.TrimmedSurface(s, nf.circle_loop(center_u, center_v, radius)))
@add("split", "Split a surface along its intersection with another surface; the pieces "
"are stored as name_1, name_2, ...",
{"name": {"type": "string"}, "surface": _NAME, "cutter": _NAME},
["name", "surface", "cutter"])
def _(ws, name, surface, cutter):
parts = nf.split(ws.get(surface), ws.get(cutter))
out = []
for i, p in enumerate(parts, 1):
ws.put(f"{name}_{i}", p)
out.append(f"{name}_{i}: area {p.area(1e-7):.6g}")
return "; ".join(out)
@add("section", "Cut a surface with a plane (point and normal); the section curves are "
"stored as name_1, name_2, ...",
{"name": {"type": "string"}, "surface": _NAME, "point": _VEC, "normal": _VEC},
["name", "surface", "point", "normal"])
def _(ws, name, surface, point, normal):
res = nf.planar_section(ws.get(surface), nf.Plane(point, normal))
out = []
for i, c in enumerate(res.curves, 1):
ws.put(f"{name}_{i}", c.curve)
out.append(f"{name}_{i}: {'closed' if c.closed else 'open'}, length {nf.length(c.curve):.6g}")
return "; ".join(out) if out else "no section"
@add("sew", "Sew surfaces (and trimmed surfaces) along shared edges into a shell; reports "
"whether it is closed and, if so, the enclosed volume.",
{"name": _NAME, "faces": {"type": "array", "items": _NAME, "minItems": 1}},
["name", "faces"])
def _(ws, name, faces):
objs = [ws.get(f) for f in faces]
trimmed = [o if isinstance(o, nf.TrimmedSurface) else nf.TrimmedSurface(o) for o in objs]
shell = nf.Shell.sew(trimmed).oriented()
ws.put(name, shell)
if shell.is_closed:
return f"stored {name}: closed shell, volume {shell.volume(1e-7):.6g}"
return f"stored {name}: open shell with {len(shell.free_edges())} free edges"
@add("solid", "Create a closed solid (shell with outward normals): kind 'box' (corner = "
"'point', edge lengths = 'size'), 'sphere' (center, radius), 'cylinder' (base center, "
"axis, radius, height), 'cone' (base, axis, radius = base radius, radius2 = top radius, "
"0 for an apex, height) or 'torus' (center, axis, radius = major, radius2 = tube).",
{"name": _NAME, "kind": {"type": "string",
"enum": ["box", "sphere", "cylinder", "cone", "torus"]},
"point": _VEC, "axis": _VEC, "size": _VEC, "radius": {"type": "number"},
"radius2": {"type": "number"}, "height": {"type": "number"}},
["name", "kind", "point"])
def _(ws, name, kind, point, axis=(0, 0, 1), size=None, radius=None, radius2=None,
height=None):
def need(**kw):
missing = [k for k, v in kw.items() if v is None]
if missing:
raise ValueError(f"solid '{kind}' needs {', '.join(missing)}")
if kind == "box":
need(size=size)
shell = nf.make_box(point, size)
elif kind == "sphere":
need(radius=radius)
shell = nf.make_sphere(point, radius)
elif kind == "cylinder":
need(radius=radius, height=height)
shell = nf.make_cylinder(point, axis, radius, height)
elif kind == "cone":
need(radius=radius, radius2=radius2, height=height)
shell = nf.make_cone(point, axis, radius, radius2, height)
else:
need(radius=radius, radius2=radius2)
shell = nf.make_torus(point, axis, radius, radius2)
ws.put(name, shell)
return f"stored {name}: closed shell, volume {shell.volume(1e-7):.6g}"
@add("mass_properties", "Volume, centroid and inertia tensor (about the centroid, unit "
"density; principal moments and axes) of a closed shell.",
{"name": _NAME}, ["name"])
def _(ws, name):
mp = ws.get(name).mass_properties()
c = mp.centroid
size = mp.volume ** (1 / 3)
imax = max(abs(x) for row in mp.inertia for x in row)
def g(x, scale, digits=6): # rounding noise far below the scale shows as 0
return f"{0.0 if abs(x) < 1e-7 * scale else x:.{digits}g}"
rows = "; ".join(" ".join(g(x, imax) for x in row) for row in mp.inertia)
moments = ", ".join(g(x, imax) for x in mp.principal_moments)
axes = "; ".join(" ".join(g(x, 1.0, 4) for x in a) for a in mp.principal_axes)
return (f"{name}: volume {mp.volume:.6g}, centroid ({g(c.x, size)}, {g(c.y, size)}, "
f"{g(c.z, size)}), inertia [{rows}], principal moments {moments}, axes [{axes}]")
@add("boolean", "Boolean operation of two closed shells (from 'sew'): union, intersection or "
"difference (a minus b). Reports the volume of the result.",
{"name": _NAME, "a": _NAME, "b": _NAME,
"op": {"type": "string", "enum": ["union", "intersection", "difference"]}},
["name", "a", "b", "op"])
def _(ws, name, a, b, op):
kind = {"union": nf.BooleanOp.Union, "intersection": nf.BooleanOp.Intersection,
"difference": nf.BooleanOp.Difference}[op]
res = nf.boolean(ws.get(a), ws.get(b), kind)
ws.put(name, res)
if res.is_closed:
return f"stored {name}: closed shell, volume {res.volume(1e-7):.6g}"
return f"stored {name}: shell with {len(res.free_edges())} free edges"
def _as_shell(o):
if isinstance(o, nf.Shell):
return o
if isinstance(o, nf.NurbsSurface):
o = nf.TrimmedSurface(o)
if isinstance(o, nf.TrimmedSurface):
return nf.Shell.sew([o])
raise ValueError("expected a shell or a surface")
def _report(ws, name, res):
ws.put(name, res)
if res.is_closed:
return (f"stored {name}: closed shell, {len(res.faces)} faces, volume "
f"{res.volume(1e-7):.6g}, labels {sorted(set(res.face_labels))}")
return f"stored {name}: shell with {len(res.free_edges())} free edges"
@add("blend", "Smooth transition curve from an end of curve a to an end of curve b (G1 or G2 "
"continuity). Ends are 'start' or 'end'.",
{"name": _NAME, "a": _NAME, "end_a": {"type": "string", "enum": ["start", "end"]},
"b": _NAME, "end_b": {"type": "string", "enum": ["start", "end"]},
"continuity": {"type": "integer", "enum": [1, 2]}},
["name", "a", "end_a", "b", "end_b"])
def _(ws, name, a, end_a, b, end_b, continuity=2):
e = {"start": nf.CurveEnd.Start, "end": nf.CurveEnd.End}
return ws.put(name, nf.blend_curves(ws.get(a), e[end_a], ws.get(b), e[end_b], continuity))
_SIDE = {"type": "string", "enum": ["umin", "umax", "vmin", "vmax"]}
_SIDES = {"umin": nf.SurfaceSide.UMin, "umax": nf.SurfaceSide.UMax,
"vmin": nf.SurfaceSide.VMin, "vmax": nf.SurfaceSide.VMax}
def _surface(o):
return o.surface if isinstance(o, nf.TrimmedSurface) else o
@add("blend_surfaces", "Smooth transition surface between a side of surface a and a side of "
"surface b (sides umin/umax/vmin/vmax): continuity 0 (ruled), 1 (tangent planes match) "
"or 2 (also curvature). tension scales how far the blend bulges.",
{"name": _NAME, "a": _NAME, "side_a": _SIDE, "b": _NAME, "side_b": _SIDE,
"continuity": {"type": "integer", "enum": [0, 1, 2]}, "tension": {"type": "number"}},
["name", "a", "side_a", "b", "side_b"])
def _(ws, name, a, side_a, b, side_b, continuity=2, tension=1.0):
return ws.put(name, nf.blend_surfaces(_surface(ws.get(a)), _SIDES[side_a],
_surface(ws.get(b)), _SIDES[side_b], continuity,
tension))
@add("match_surface", "Modify a surface near one of its sides so that it joins a side of a "
"target surface smoothly (continuity 0: edges meet, 1: tangent, 2: curvature). The "
"opposite side stays unchanged. Stored under name.",
{"name": _NAME, "surface": _NAME, "side": _SIDE, "target": _NAME, "target_side": _SIDE,
"continuity": {"type": "integer", "enum": [0, 1, 2]}},
["name", "surface", "side", "target", "target_side"])
def _(ws, name, surface, side, target, target_side, continuity=2):
return ws.put(name, nf.match_surface(_surface(ws.get(surface)), _SIDES[side],
_surface(ws.get(target)), _SIDES[target_side],
continuity))
@add("project", "Project a curve onto a surface, along the surface normal or along a "
"direction. Stores the 3D curve as name and its parameter-space curve as name + '_uv'.",
{"name": _NAME, "curve": _NAME, "surface": _NAME, "direction": _VEC},
["name", "curve", "surface"])
def _(ws, name, curve, surface, direction=(0, 0, 0)):
s = ws.get(surface)
if isinstance(s, nf.TrimmedSurface):
s = s.surface
pr = nf.project_curve(ws.get(curve), s, direction)
ws.put(name + "_uv", pr.pcurve)
return ws.put(name, pr.curve)
@add("project_to_plane", "Flatten a curve or surface onto a plane (through point, with "
"normal) by parallel projection along direction (default: the plane normal). Exact.",
{"name": _NAME, "source": _NAME, "point": _VEC, "normal": _VEC, "direction": _VEC},
["name", "source", "point", "normal"])
def _(ws, name, source, point, normal, direction=(0, 0, 0)):
return ws.put(name, nf.project_to_plane(ws.get(source), nf.Plane(point, normal),
direction))
@add("offset_on_surface", "Offset a curve lying on a surface within the surface (geodesic "
"distance; positive = left of the curve seen from the surface normal). The curve is "
"given by its parameter-space curve (e.g. the name + '_uv' stored by project). Stores "
"the 3D curve as name and its parameter-space curve as name + '_uv'.",
{"name": _NAME, "curve_uv": _NAME, "surface": _NAME, "distance": {"type": "number"}},
["name", "curve_uv", "surface", "distance"])
def _(ws, name, curve_uv, surface, distance):
s = ws.get(surface)
if isinstance(s, nf.TrimmedSurface):
s = s.surface
pr = nf.offset_on_surface(s, ws.get(curve_uv), distance)
ws.put(name + "_uv", pr.pcurve)
return ws.put(name, pr.curve)
@add("tween", "Intermediate curves between two curves a and b (running in the same "
"direction), stored as name_1 .. name_count.",
{"name": _NAME, "a": _NAME, "b": _NAME, "count": {"type": "integer", "minimum": 1}},
["name", "a", "b", "count"])
def _(ws, name, a, b, count):
return "\n".join(ws.put(f"{name}_{k}", c)
for k, c in enumerate(nf.tween_curves(ws.get(a), ws.get(b), count), 1))
@add("split_solid", "Split a closed solid by a plane into the part below (opposite to the "
"normal, stored as name + '_below') and above (name + '_above'). The new faces in the "
"plane get the label cut_label (default 'cut'), e.g. for a symmetry condition.",
{"name": _NAME, "solid": _NAME, "point": _VEC, "normal": _VEC,
"cut_label": {"type": "string"}}, ["name", "solid", "point", "normal"])
def _(ws, name, solid, point, normal, cut_label="cut"):
below, above = nf.split(ws.get(solid), nf.Plane(point, normal), cut_label=cut_label)
return "\n".join([_report(ws, name + "_below", below),
_report(ws, name + "_above", above)])
@add("cap", "Close the planar openings of an open shell with planar faces (label 'cap').",
{"name": _NAME, "shell": _NAME}, ["name", "shell"])
def _(ws, name, shell):
return _report(ws, name, nf.cap(_as_shell(ws.get(shell))))
@add("thicken", "Give an open smooth shell or a surface a wall thickness along its normal "
"(negative: other side; symmetric: half on each side). Side walls get label 'wall'.",
{"name": _NAME, "shell": _NAME, "thickness": {"type": "number"},
"symmetric": {"type": "boolean"}}, ["name", "shell", "thickness"])
def _(ws, name, shell, thickness, symmetric=False):
return _report(ws, name, nf.thicken(_as_shell(ws.get(shell)), thickness, symmetric))
@add("hollow", "Hollow a smooth closed solid to a wall of the given thickness: an inner "
"void, or open at the faces whose labels are listed in open_labels.",
{"name": _NAME, "solid": _NAME, "thickness": {"type": "number"},
"open_labels": {"type": "array", "items": {"type": "string"}}},
["name", "solid", "thickness"])
def _(ws, name, solid, thickness, open_labels=()):
return _report(ws, name, nf.hollow(ws.get(solid), thickness, list(open_labels)))
@add("pipe", "Solid pipe along a path curve with a circular cross-section of the given "
"radius (end_radius: linear taper). Faces labelled 'wall', 'inlet', 'outlet'.",
{"name": _NAME, "path": _NAME, "radius": {"type": "number"},
"end_radius": {"type": "number"}}, ["name", "path", "radius"])
def _(ws, name, path, radius, end_radius=-1.0):
return _report(ws, name, nf.make_pipe(ws.get(path), radius, end_radius))
@add("merge_faces", "Defeaturing: merge adjacent faces of a solid that lie on the same "
"surface and carry the same label (e.g. coplanar pieces left by a union).",
{"name": _NAME, "solid": _NAME}, ["name", "solid"])
def _(ws, name, solid):
return _report(ws, name, nf.merge_faces(ws.get(solid)))
@add("round_edges", "Fillet (round) or chamfer the edges of a solid between the faces "
"labelled label_a and label_b (e.g. 'top' and 'side' for the rim of a cylinder, 'top' "
"and 'front' for a box edge); '*' matches any label ('top', '*': all edges of the top "
"face; '*', '*': every edge). Convex edges lose material, concave edges gain it. "
"Where selected edges meet at a corner they are mitred, continue tangentially, or (all "
"three edges of a corner) get a spherical / triangular corner patch. Optional variable "
"size: radius / distance at points on the edges. New faces are labelled 'fillet' or "
"'chamfer'.",
{"name": _NAME, "solid": _NAME, "label_a": {"type": "string"},
"label_b": {"type": "string"}, "size": {"type": "number",
"description": "radius or chamfer distance"},
"kind": {"type": "string", "enum": ["fillet", "chamfer"]},
"sizes": {"type": "array", "description": "variable size: size at points on the "
"edges, smooth in between",
"items": {"type": "object",
"properties": {"point": _VEC, "size": {"type": "number"}},
"required": ["point", "size"]}}},
["name", "solid", "label_a", "label_b", "size"])
def _(ws, name, solid, label_a, label_b, size, kind="fillet", sizes=()):
s = ws.get(solid)
edges = []
for i, e in enumerate(s.edges):
if len(e.uses) != 2:
continue
la, lb = (s.faces[u.face].label for u in e.uses)
if any((a == "*" or a == x) and (b == "*" or b == y)
for a, b in ((label_a, label_b),) for x, y in ((la, lb), (lb, la))):
edges.append(i)
if not edges:
raise ValueError(f"no edge between faces labelled '{label_a}' and '{label_b}'")
op = nf.fillet_edges if kind == "fillet" else nf.chamfer_edges
pts = [(tuple(p["point"]), p["size"]) for p in sizes]
return _report(ws, name, op(s, edges, size, sizes=pts))
@add("remove_holes", "Defeaturing: fill the through and blind holes of a closed solid that "
"are smaller than max_size across.",
{"name": _NAME, "solid": _NAME, "max_size": {"type": "number"}},
["name", "solid", "max_size"])
def _(ws, name, solid, max_size):
return _report(ws, name, nf.remove_holes(ws.get(solid), max_size))
@add("export_step", "Write shells (from 'sew' or 'boolean'; surfaces are sewn into a shell "
"each) to a STEP file with the native writer. Closed shells become solids.",
{"objects": {"type": "array", "items": _NAME, "minItems": 1},
"path": {"type": "string", "description": "output file, e.g. part.step"},
"unit": {"type": "string", "enum": ["mm", "cm", "m", "inch"]}},
["objects", "path"])
def _(ws, objects, path, unit="mm"):
shells = []
for n in objects:
o = ws.get(n)
if isinstance(o, nf.NurbsSurface):
o = nf.TrimmedSurface(o)
if isinstance(o, nf.TrimmedSurface):
o = nf.Shell.sew([o])
if not isinstance(o, nf.Shell):
raise TypeError(f"'{n}' is not a shell or surface")
shells.append(o)
nf.write_step(path, shells, unit=unit)
closed = sum(1 for s in shells if s.is_closed)
return f"wrote {path}: {len(shells)} shell(s), {closed} closed"
@add("import_step", "Read the solids and surface models of a STEP file with the native "
"reader. The shells are stored as name, name_1, name_2, ... (one per solid / shell).",
{"name": _NAME,
"path": {"type": "string", "description": "input file, e.g. part.step"},
"unit": {"type": "string", "enum": ["mm", "cm", "m", "inch"],
"description": "unit to convert to (default mm)"}},
["name", "path"])
def _(ws, name, path, unit="mm"):
shells = nf.read_step(path, unit=unit)
if not shells:
return f"no solids or surface models in {path}"
out = []
for i, s in enumerate(shells):
key = name if i == 0 else f"{name}_{i}"
ws.put(key, s)
desc = (f"closed, volume {s.volume(1e-7):.6g}" if s.is_closed
else f"open, {len(s.free_edges())} free edges")
out.append(f"{key}: {len(s.faces)} faces, {desc}")
return f"read {path}: " + "; ".join(out)
@add("solve", "Find unknown dimensions from measured targets. 'recipe' is a list of tool "
"calls {tool, args} whose numeric arguments may be \"$name\" or \"${expression}\" "
"(+ - * / **, pi, sqrt, sin/cos/tan in degrees); 'unknowns' maps each name to "
"{start, min, max}; 'targets' are {name, property, value} on measured properties "
"(as in 'check': volume, area, length, bbox.max, ...). The recipe is re-run until the "
"targets are met, then executed for real.",
{"recipe": {"type": "array", "items": {"type": "object"}},
"unknowns": {"type": "object"},
"targets": {"type": "array", "items": {"type": "object"}}},
["recipe", "unknowns", "targets"])
def _(ws, recipe, unknowns, targets):
res = constraints.solve(ws, recipe, unknowns, targets, call_tool)
vals = ", ".join(f"{k}={v:.10g}" for k, v in res["values"].items())
worst = max(abs(e) for e in res["residuals"])
if res["converged"]:
return (f"solved in {res['iterations']} iterations: {vals} (max relative target "
f"error {worst:.2e}); recipe executed")
return (f"NOT solved after {res['iterations']} iterations: {vals} (max relative target "
f"error {worst:.2e}); nothing was created – check the recipe, bounds or targets")
@add("inspect", "Measured properties of an object (type, bounding box, length / area / "
"volume, closed, free edges, ...) and detected issues. Use it to verify results.",
{"name": _NAME}, ["name"])
def _(ws, name):
return verify.describe(name, ws.get(name))
@add("check", "Verify a measured property of an object against an expected value, e.g. "
"property 'volume', 'area', 'length', 'closed', 'bbox.min', 'bbox.max', 'faces'. "
"Returns PASS or FAIL with the measured value.",
{"name": _NAME, "property": {"type": "string"},
"expected": {"description": "number, list of numbers, boolean or string"},
"tolerance": {"type": "number", "description": "absolute; default 1e-6 relative"}},
["name", "property", "expected"])
def _(ws, name, property, expected, tolerance=None):
return verify.check(ws.get(name), property, expected, tolerance)
@add("measure", "Length of a curve or area of a surface.", {"name": _NAME}, ["name"])
def _(ws, name):
o = ws.get(name)
if isinstance(o, nf.NurbsCurve):
return f"length={nf.length(o):.10g}"
if isinstance(o, nf.TrimmedSurface):
return f"area={o.area(1e-8):.10g}"
if isinstance(o, nf.Shell):
v = f", volume={o.volume(1e-8):.10g}" if o.is_closed else ""
return f"area={o.area(1e-8):.10g}{v}"
return f"area={nf.area(o):.10g}"
@add("evaluate", "Evaluate a curve at u or a surface at (u, v).",
{"name": _NAME, "u": {"type": "number"}, "v": {"type": "number"}}, ["name", "u"])
def _(ws, name, u, v=None):
o = ws.get(name)
return repr(o(u) if v is None else o(u, v))
return T
TOOLS: list[Tool] = _build_tools()
TOOL_MAP: dict[str, Tool] = {t.name: t for t in TOOLS}