dymokomi/luced-3d
Source of release 0.11.7
0.11.7 / src / sketch_node.luc
## The Sketch node: a 2D sketch on a plane inside a CAD node, Fusion 360's
## way. Its entities and constraints are luce-cad's (CadSketch), kept as
## text in the node's first text and solved on every evaluation, so a
## dimension typed in the parameter panel moves the geometry. Its result is
## the sketch's curves on its plane, what Extrude and Revolve read, with the
## input's bodies. The
## plane is one of the origin planes (XY, the XZ ground, YZ) or a flat face
## of the body connected to its input (Face: kept by the face's name, so
## the sketch stays on it as features upstream change the body), moved
## along its normal by Offset; drawing and constraining happen in the
## viewport (sketch_editor.luc). The input's bodies pass through beside the
## curves, so a chain Box → Sketch → Extrude is one wire and displaying the
## sketch shows the body as it was there. Curves projected from the input body's
## edges are cast again on every evaluation, so they follow it. A sketch on
## a face has that face's loops projected (linked) the first time it is
## evaluated on it, as Fusion projects a sketch's face, so an Offset of a
## loop follows the face. Each evaluation reports the sketch's state for
## the editor (SketchState): its plane and its text as evaluated, so the
## editor never cooks the body on the UI thread. Lengths are millimeters.
from luce_cad.sketch import CadSketch, CadProjection, CadShadows
from luce_cad.cad_geometry import CadGeometry
from luce_cad.modeling import CadModeling
from luce_3d.graphics import Vector3
from geometry_data import GeometryData
from luce_ui import ui
from luce_geocore.geocore import GeometrySet, Sketches
pub let kind_name = "Sketch"
## A sketch plane: its origin and the directions of the sketch's x and y
## (the normal is x × y). Seen from the normal's side, x runs right and y
## up: on XY as from the front (+Z), on the ground XZ as from above (+Y,
## with -Z up the screen), on YZ as from the right (+X, with -Z right).
pub class SketchFrame:
pub let origin: Vector3
pub let u: Vector3
pub let v: Vector3
pub func init(self, origin: Vector3, u: Vector3, v: Vector3):
self.origin = origin
self.u = u
self.v = v
pub func normal(self) -> Vector3:
return self.u.cross(self.v)
## Whether `other` is the same plane with the same axes.
pub func equals(self, other: SketchFrame) -> bool:
return self.origin.subtract(other.origin).length() == 0.0 and self.u.subtract(other.u).length() == 0.0 and self.v.subtract(other.v).length() == 0.0
## The frame as text, for keys of what is cached on it.
pub func key(self) -> str:
return f"{self.origin.x}|{self.origin.y}|{self.origin.z}|{self.u.x}|{self.u.y}|{self.u.z}|{self.v.x}|{self.v.y}|{self.v.z}"
## Sketch coordinates (`x`, `y`) as a world point.
pub func at(self, x: float, y: float) -> Vector3:
return self.origin.add(self.u.multiply_scalar(x)).add(self.v.multiply_scalar(y))
## World point `p`'s sketch coordinates (it projected onto the plane).
pub func coordinates(self, p: Vector3) -> list[float]:
let d = p.subtract(self.origin)
return [d.dot(self.u), d.dot(self.v)]
pub func plane_names() -> str:
return "XY|XZ|YZ|Face"
## The Plane menu's Face entry.
pub let face_plane = 3
## The frame of plane `plane` (plane_names' order) moved `offset` along
## its normal.
pub func frame(plane: int, offset: float) -> SketchFrame:
var u = Vector3(1.0, 0.0, 0.0)
var v = Vector3(0.0, 1.0, 0.0)
if plane == 1:
v = Vector3(0.0, 0.0, -1.0)
elif plane == 2:
u = Vector3(0.0, 0.0, -1.0)
v = Vector3(0.0, 1.0, 0.0)
return SketchFrame(u.cross(v).multiply_scalar(offset), u, v)
## The frame of a Sketch node with values `v` (plane, offset).
pub func node_frame(v: list[float]) -> SketchFrame:
return frame(int(v[0]), v[1])
## What a Sketch's evaluation tells its editor: the plane, the text as
## evaluated when casting changed it (projections cast again, a face's
## loops projected; "": the node's text stands), and the curves whose links
## were lost. As text (it crosses from the compute
## worker): a frame line, a lost line, then the sketch's text.
pub class SketchState:
pub let plane: SketchFrame
pub let text: str
pub let lost: list[int]
pub func init(self, plane: SketchFrame, text: str, lost: list[int]):
self.plane = plane
self.text = text
self.lost = lost
pub func encode(self) -> str:
let f = self.plane
let lost: list[str] = []
for at in self.lost:
lost.append(f"{at}")
return f"frame {f.origin.x} {f.origin.y} {f.origin.z} {f.u.x} {f.u.y} {f.u.z} {f.v.x} {f.v.y} {f.v.z}\nlost {lost.join(" ")}\n{self.text}"
## The state `text` encodes, or none (no state, or not one).
pub func parse_state(text: str) -> SketchState?!:
if not text.starts_with("frame "):
return none
let first = text.index_of("\n") else return none
let rest = text[first + 1..<text.length]
let second = rest.index_of("\n") else return none
let numbers: list[float] = []
for word in text[6..<first].split(" "):
numbers.append(float(word))
if numbers.length != 9:
return none
let lost: list[int] = []
for word in rest[5..<second].split(" "):
if word != "":
lost.append(int(word))
let f = SketchFrame(Vector3(numbers[0], numbers[1], numbers[2]), Vector3(numbers[3], numbers[4], numbers[5]), Vector3(numbers[6], numbers[7], numbers[8]))
return SketchState(f, rest[second + 1..<rest.length], lost)
## A Sketch node's result: its text solved, as curves on its plane (on a
## face of `data`'s body for the Face plane), with its state for the editor.
pub func evaluate_sketch(v: list[float], texts: list[str], data: GeometryData) -> GeometryData!:
let sketch = CadSketch.parse(texts[0])
let read = sketch.text()
let on_face = int(v[0]) == face_plane
let f = face_frame(v, texts, data) if on_face else node_frame(v)
# A face's loops projected and linked, once (what is drawn on them
# names them by index).
if on_face and not sketch.projects_face(texts[1].trim()):
_ = sketch.project_face(CadGeometry.model(data.geometry, 0), texts[1].trim(), f.origin, f.u, f.v)
# Projected curves cast again from the body as it is now.
var lost = 0
let lost_curves: list[int] = []
if sketch.link_count() > 0:
if CadGeometry.model_count(data.geometry) == 0:
error(ui.invalid, "The sketch's projected curves follow its input body: connect the body")
lost = sketch.relink(CadGeometry.model(data.geometry, 0), f.origin, f.u, f.v)
for at in 0..<sketch.entity_count():
if sketch.lost_link(at):
lost_curves.append(at)
let cast = sketch.text() != read
if sketch.entity_count() > 0 and not sketch.solve():
error(ui.invalid, "The sketch's constraints cannot all hold: remove one that conflicts")
# The input's bodies pass on beside the curves: one body flows down the
# chain, as Fusion's design does along its timeline (an earlier
# sketch's curves do not: the curves in a set are its nearest sketch's).
var result = GeometryData(geometry = sketch.curves(f.origin, f.u, f.v))
if CadGeometry.model_count(data.geometry) > 0:
result = result.merged(GeometryData(geometry = data.geometry.without("curves")))
if lost > 0:
result.warning = f"{lost} projected curve(s) lost their edge upstream: they stay where they were (right-click them in the sketch: Re-link, Break link)"
result.sketch_state = SketchState(f, sketch.text() if cast else "", lost_curves).encode()
return result
## The edges of body `data` (its first model) cast onto plane `f`, as
## shadows' text (luce-cad's CadShadows) for the editor's Project tool;
## empty without a body.
## (An Edit CAD model's several bodies are cast as one: their union, or
## the first when they cannot be joined.)
pub func shadows_text(data: GeometryData, f: SketchFrame) -> str!:
let count = CadGeometry.model_count(data.geometry)
if count == 0:
return ""
var body = CadGeometry.model(data.geometry, 0)
for at in 1..<count:
body = CadModeling.combined(body, CadGeometry.model(data.geometry, at), 0) catch failure:
recover body
return CadShadows.text_of(CadProjection.of(body, f.origin, f.u, f.v))
## The sketch plane a set of a sketch's curves carries (luce-geocore's
## detail attributes), its axes as Extrude and Revolve read them.
pub func plane_of(geometry: GeometrySet) -> SketchFrame!:
return SketchFrame(Sketches.plane_origin(geometry), Sketches.plane_u(geometry), Sketches.plane_v(geometry))
## The plane of the face named `texts[1]` of `data`'s body, moved Offset
## along its normal.
pub func face_frame(v: list[float], texts: list[str], data: GeometryData) -> SketchFrame!:
if texts[1].trim() == "":
error(ui.invalid, "Pick the face the sketch is on (Pick face)")
if CadGeometry.model_count(data.geometry) == 0:
error(ui.invalid, "The sketch's face is on its input body: connect the body")
let found = CadModeling.face_frame(CadGeometry.model(data.geometry, 0), texts[1])
if not found.found:
error(ui.invalid, "The sketch's face is not on the body, or not flat: pick a flat face (Pick face)")
let f = SketchFrame(found.origin, found.u, found.v)
return SketchFrame(f.origin.add(f.normal().multiply_scalar(v[1])), f.u, f.v)