dymokomi/luced-3d
Source of release 0.11.9
## Edit CAD: the Edit framework's kind for analytic models, Fusion 360's
## direct modeling ("Do not capture design history") in one node, with
## Alias's curves and surfaces. Its levels are Object (a whole model), CVs
## (control vertices of surfaces and curves), Edges (a B-rep edge), Faces
## (a B-rep face), Patch and Curves (a whole curve); Smart picks edges and
## faces. Object, Faces and Edges pick on the models' display tessellations
## at the project's display quality, tagged with their models, faces and
## edges (luce-cad's CadEdits.pick_mesh); CVs on the control-vertex cloud;
## Curves on the curves' segments (CadCurves.pick_mesh). A step keeps the
## bodies, faces and edges it picked as B-rep entities, by name
## (cad_picks.luc), so no tessellation changes what it picked.
##
## Every tool is a step on the model the steps before it made, and nothing
## earlier changes when something later does:
## sketches and the Extrude and Revolve of their profiles
## (edit_cad_sketches.luc: a sketch is an object of the model);
## the gizmo's moves (whole models placed, faces moved and turned with
## their neighbors following), Create copy, Offset Face, Delete (faces
## healed), Remove Faces, Replace Face, Shell, Combine and Split Body
## (edit_cad_faces.luc);
## Fillet and Chamfer of picked edges, by the CAD nodes' own code;
## CVs moved by the point verbs that keep topology, a moved boundary CV
## re-projecting its trims (luce-cad), and the CV moves and structure
## steps of edit_cad_nets.luc;
## curves drawn, duplicated, blended and edited (edit_cad_curves.luc);
## curves projected onto faces and faces intersected, trimmed, untrimmed,
## converted and shrunk, bodies stitched and unstitched
## (edit_cad_surfaces.luc), aligned (edit_cad_align.luc);
## surfaces built from curves and edges extended (edit_cad_build.luc);
## luce-cad's analytic solids, created named.
## The faces a step makes are named for the node and the step's place in
## the recipe (`#<node>s<n>`), so later steps find them by name and two Edit
## CAD nodes in one chain never make the same names; a model whose faces
## have no names (a STEP import) gets them when the recipe starts
## (`#<node>m<i>`).
from luce_geocore.geocore import Mesh, Verbs, Groups, Domain, GroupType, Vector3, Matrix4
from luce_cad.cad_geometry import CadGeometry
from luce_cad.cad_edits import CadEdits
from luce_cad.solids import CadSolids
from luce_cad.model import CadModel
from luce_cad.modeling import CadModeling
from geometry_data import GeometryData
from edit_operations import EditStep
from edit_types import EditKind, EditLevel, EditTool, point_level, edge_level, face_level, curve_level, missing, own_data
import cad_moves
import tool_registry
import cad_cook
import edit_cad_sketches
import edit_cad_nets
import edit_cad_curves
import edit_cad_align
import cad_picks
from luce_cad.cad_curves import CadCurves
from luce_ui import ui
from luce_cad.model import CadTolerances, MeshQuality
pub let kind_name = "Edit CAD"
## CVs are the Point level.
let cv_level = point_level
## The verbs that move control vertices.
pub func cv_verbs() -> list[str]:
return ["Transform Components", "Mountain", "Flatten", "Snap"]
pub func primitive_names() -> list[str]:
return ["Box", "Cylinder", "Cone", "Sphere", "Torus"]
pub func kind() -> EditKind:
let steps = [edit_cad_sketches.sketch_verb, edit_cad_sketches.edit_sketch_verb, edit_cad_sketches.visibility_verb, edit_cad_sketches.plane_verb, edit_cad_nets.move_verb]
return EditKind(kind_name, levels(), tool_list(), primitive_names(), start, pick, run, create, smart = [edge_level, face_level], steps = steps,
draw_tools = placing(), drawn = edit_cad_curves.drawn, holds = true, background = background, kept = cad_picks.kept)
## Whether `step` runs on the compute worker: every action. A face moved
## takes ~17 ms, a fillet or a shell far more; and a result holding CAD
## models made here would have to cross to the worker as a file (HeldStore),
## where one the worker makes stays its own until the node takes it.
func background(step: EditStep) -> bool!:
return true
## The tools whose clicks place points (the curves' drawing tools).
func placing() -> list[str]:
let result: list[str] = []
for tool in tool_registry.of_kind(kind_name):
if tool.gesture == "place":
result.append(tool.label)
return result
func levels() -> list[EditLevel]:
return [EditLevel("Object", "cube", Domain.face, GroupType.faces, model_piece),
EditLevel("CVs", "vertex-select", Domain.point, GroupType.points),
EditLevel("Edges", "edge-select", Domain.edge, GroupType.edges, edge_piece),
EditLevel("Faces", "face-select", Domain.face, GroupType.faces, face_piece), missing("Smart"),
EditLevel("Patch", "patch-select", Domain.face, GroupType.faces, patch_piece),
EditLevel("Curves", "curve-select", Domain.edge, GroupType.edges, edit_cad_curves.curve_piece)]
## The tools on picked components: Move/Copy (the gizmo's step, its tool
## bar Fusion's dialog: cad_moves.luc), Delete (models go, faces heal),
## Remove (bodies, as a step of its own), Remove Faces, Offset Face,
## Replace Face, Split Face, Shell, Combine and Split Body; Reblend (the
## picked blends' radius changed); Fillet and
## Chamfer of edges; Noise, Flatten and Snap of CVs; Insert Knot, Remove
## Knot, Raise Degree, Rebuild and Convert to B-spline of a CV's or a
## face's surface; the curves' drawing tools, Duplicate Curve, Blend Curve,
## Attach, Detach, Close, Stretch, Reverse and Delete (edit_cad_curves).
func tool_list() -> list[EditTool]:
let result: list[EditTool] = []
# The CAD tools' declarations (cad_tools.luc).
for tool in tool_registry.of_kind(kind_name):
result.append(EditTool(tool.label, tool.verb, tool.first_pick().levels, tool.starting(), tool.bar_rows(), tool = tool))
for (name, offered) in [("Noise", [cv_level]), ("Flatten", [cv_level]), ("Snap", [cv_level])]:
let made = tool_registry.find(name) else continue
result.append(EditTool(name, made.name, offered, made.starting(), tool = made))
return result
## The whole model under a picked polygon.
func model_piece(mesh: Mesh, face: int) -> str!:
return f"@cad_model={int(mesh.attribute_value(mesh.find_attribute("cad_model", 2), face))}"
## The whole B-rep face under a picked polygon.
func face_piece(mesh: Mesh, face: int) -> str!:
let model = int(mesh.attribute_value(mesh.find_attribute("cad_model", 2), face))
let owner = int(mesh.attribute_value(mesh.find_attribute("cad_face", 2), face))
return f"@cad_model={model} &@cad_face={owner}"
## The whole B-rep edge under a picked mesh edge (nothing inside a face).
func edge_piece(mesh: Mesh, edge: int) -> str!:
let owner = int(mesh.attribute_value(mesh.find_attribute("cad_edge", 4), edge))
let model = int(mesh.attribute_value(mesh.find_attribute("cad_edge_model", 4), edge))
return f"@cad_edge_model={model} &@cad_edge={owner}" if owner >= 0 else "!*"
## Every trimmed region on the picked underlying surface of this model.
func patch_piece(mesh: Mesh, face: int) -> str!:
let model = int(mesh.attribute_value(mesh.find_attribute("cad_model", 2), face))
let surface = int(mesh.attribute_value(mesh.find_attribute("cad_surface", 2), face))
return f"@cad_model={model} &@cad_surface={surface}"
## A separate gesture expands an edge along its unambiguous tangent chain.
pub func edge_chain(mesh: Mesh, edge: int) -> str!:
let chain = int(mesh.attribute_value(mesh.find_attribute("cad_edge_chain", 4), edge))
let model = int(mesh.attribute_value(mesh.find_attribute("cad_edge_model", 4), edge))
return f"@cad_edge_model={model} &@cad_edge_chain={chain}" if chain >= 0 else "!*"
## The input's CAD models, their faces named where they had none (a STEP
## import's), and its sketches; other components pass through (with a
## warning when there are no models yet: create one, sketch, or connect
## CAD).
func start(data: GeometryData, tag: str) -> GeometryData!:
if data.has_cad():
return stated(GeometryData(geometry = CadEdits.named_models(data.geometry, f"{tag}m")))
if data.has_curves():
return stated(own_data(data))
if data.instance_count() == 0 and data.mesh == none:
return stated(data)
return data.passed("The input has no CAD models; it passes through (create a solid, or connect CAD)")
func pick(data: GeometryData, level: int, quality: MeshQuality) -> Mesh?!:
if level == curve_level:
if not data.has_curves():
return Mesh.empty()
# A curve the last step made (an isoparm picked) is selected.
let made = CadCurves.pick_mesh(data.geometry)
return Groups.with_group(made, ".selection", 4, data.created) if data.created.starts_with("@cad_curve") else made
if level == cv_level and (data.has_cad() or data.has_curves()):
return CadGeometry.cv_cloud(data.geometry)
if not data.has_cad():
return Mesh.empty()
return cad_cook.pick_mesh(data, quality)
## Step number `at` of a recipe on `data`, with the model's sketches told
## to the editor (Node.sketch_state); after Insert Knot or Remove Knot, the
## surface it works on too (edit_cad_nets.probe_line: the viewport draws
## the isoparm under the pointer from it, knot_place.luc), and after Trim
## its region markers (surface_ops: trim_regions.luc draws them). What the
## step picked by name is found on `data`'s pick mesh at the display
## quality `quality` first (cad_cook.resolved), as its tools take groups.
func run(step: EditStep, at: int, data: GeometryData, tag: str, reference: GeometryData?, tolerances: CadTolerances, quality: MeshQuality) -> GeometryData!:
var made = ran(cad_cook.resolved(step, data, quality), f"{tag}s{at}", data, tolerances, quality)
# Aligned rows stay aligned: a CV drag on them runs their Align again;
# the Aligns so far carry on to later steps.
if step.verb == edit_cad_nets.move_verb or (step.group_type == 1 and step.verb in cv_verbs()):
made = edit_cad_align.realigned(data, made)
elif not (step.verb in edit_cad_align.verbs()):
made.aligns = data.aligns
let kept: list[str] = []
for line in made.sketch_state.split("\n"):
if line.starts_with(edit_cad_nets.probe_head) or line.starts_with("trim_") or line.starts_with("stretch_") or line.starts_with("align_") or line.starts_with("build_"):
kept.append(line)
let result = stated(made)
if kept.length > 0:
result.sketch_state = result.sketch_state + "\n" + kept.join("\n") if result.sketch_state != "" else kept.join("\n")
return result
## `data` with its sketches as the editor reads them.
func stated(data: GeometryData) -> GeometryData!:
data.sketch_state = edit_cad_sketches.state_of(data)
return data
## `name` names what the step makes (`#<node>s<n>`).
func ran(step: EditStep, name: str, data: GeometryData, tolerances: CadTolerances, quality: MeshQuality) -> GeometryData!:
if step.verb.starts_with("Create "):
return created(step, name, data, tolerances)
if edit_cad_sketches.is_sketch_step(step.verb):
return edit_cad_sketches.sketched(step, data)
# CVs moved by the gizmo or a point verb go back to their surfaces and
# curves.
if step.group_type == 1 and step.verb in cv_verbs():
if not data.has_cad() and not data.has_curves():
cad_cook.needs_models(data)
return moved_cvs(step, data)
# A CAD tool's step: its declaration's cook (cad_tools.luc).
if let tool = tool_registry.cad_step(step.verb):
return tool.cook(step.invocation(tolerances = tolerances, quality = quality), data, name)
# The gizmo's CV moves in a frame of their own (Move CVs).
if step.verb == edit_cad_nets.move_verb:
cad_cook.needs_models(data)
return edit_cad_nets.run_move(step, data)
if step.group_type == 1:
error(ui.invalid, f"{step.verb} does not apply to control vertices")
error(ui.invalid, f"{step.verb} does not apply to CAD models or faces")
## A point verb on the control vertices: the moved points go back.
func moved_cvs(step: EditStep, data: GeometryData) -> GeometryData!:
if not (step.verb in cv_verbs()):
error(ui.invalid, f"{step.verb} does not apply to control vertices")
let before = CadGeometry.cv_cloud(data.geometry)
if step.topology != 0 and step.topology != before.topology_hash():
error(ui.invalid, "The control vertices picked are gone: pick them again")
let numbers = step.numbers[..<cad_moves.transform_count] if step.numbers.length > cad_moves.transform_count else step.numbers
let result = Verbs.run(step.verb, before, step.group, step.group_type, numbers, step.symmetry, step.keep)
let made = GeometryData(geometry = CadGeometry.with_cv_cloud(data.geometry, before, result.mesh()))
made.warning = result.warning()
return made
## The step adding solid `name` at the origin. Its numbers: three sizes
## (box width, height, depth; cylinder and cone radius, height, top radius;
## sphere radius; torus ring and tube radii), then the position.
func create(name: str) -> EditStep?!:
if not (name in primitive_names()):
return none
var sizes = [2.0, 2.0, 2.0]
if name == "Cylinder" or name == "Cone":
sizes = [1.0, 2.0, 0.0]
elif name == "Sphere":
sizes = [1.0, 0.0, 0.0]
elif name == "Torus":
sizes = [1.0, 0.3, 0.0]
return EditStep("Create " + name, "", 0, sizes + [0.0, 0.0, 0.0], 0)
## `data` with the solid of step `name` added as a model of its own,
## named for the step and selected as what was created.
func created(step: EditStep, tag: str, data: GeometryData, tolerances: CadTolerances) -> GeometryData!:
let name = step.verb[7..]
let v = step.numbers
if v.length < 6:
error(ui.invalid, f"{step.verb} needs six numbers")
let index = CadGeometry.model_count(data.geometry)
let solid = CadModeling.tagged(solid_of(name, v, tolerances), tag)
let position = Vector3(v[3], v[4], v[5])
let placed = solid if position.length() == 0.0 else solid.placed(Matrix4.compose(position, Vector3(), Vector3(1.0, 1.0, 1.0)))
let result = GeometryData(geometry = CadEdits.with_model(data.geometry, placed))
result.created = f"@cad_model={index}"
return result
func solid_of(name: str, v: list[float], tolerances: CadTolerances) -> CadModel!:
if name == "Box":
return CadSolids.box(v[0], v[1], v[2], tolerances = tolerances)
if name == "Cylinder":
return CadSolids.cylinder(v[0], v[1], tolerances = tolerances)
if name == "Cone":
return CadSolids.cone(v[0], v[1], v[2], tolerances = tolerances)
if name == "Sphere":
return CadSolids.sphere(v[0], tolerances = tolerances)
if name == "Torus":
return CadSolids.torus(v[0], v[1], tolerances = tolerances)
error(ui.invalid, f"Edit CAD cannot create {name}")