Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.5

0.11.5 / src / edit_cad.luc

## Edit CAD: the Edit framework's kind for analytic models. Its levels are
## Object (a whole model), CVs (control vertices), Edges (a B-rep edge) and
## Faces (a B-rep face); Smart picks edges and faces. Object, Faces and
## Edges pick on the models' display tessellations tagged with their
## models, faces and edges (luce-cad's CadEdits.pick_mesh); CVs on the
## control-vertex cloud. Whole models move, rotate, scale and go; faces go
## (a model losing every face goes); edges are filleted and chamfered by the
## CAD nodes' own code; CVs move by the point verbs that keep topology, and
## moved boundary CVs re-project their trims (luce-cad). Primitives are
## luce-cad's analytic solids, named, created as recipe steps.
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
import cad_nodes
from geometry_data import GeometryData
from edit_operations import EditStep
from edit_types import EditKind, EditLevel, EditTool, object_level, point_level, edge_level, face_level
from tools import tool_run
from luce_ui import ui

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:
    return EditKind(kind_name, levels(), tool_list(), primitive_names(), start, pick, run, create, smart = [edge_level, face_level])

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)]

## Delete models or faces; noise, flatten and snap CVs; Fillet and
## Chamfer picked edges (the CAD nodes, run on the model the edges are on).
## The gizmo moves, rotates and scales models and CVs.
func tool_list() -> list[EditTool]:
    let result: list[EditTool] = []
    for (name, offered) in [("Delete", [object_level, face_level]), ("Noise", [cv_level]), ("Flatten", [cv_level]), ("Snap", [cv_level])]:
        let made = tool_run(name) else continue
        result.append(EditTool(name, made.verb, offered, made.numbers))
    for feature in edge_features():
        result.append(EditTool(feature, feature, [edge_level]))
    return result

## The CAD nodes that are Edit CAD tools on picked edges.
pub func edge_features() -> list[str]:
    return ["Fillet", "Chamfer"]

## 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))
    return f"@cad_edge={owner}" if owner >= 0 else "!*"

## The input's CAD models; other components pass through (with a warning
## when there are no models yet: create one, or connect CAD).
func start(data: GeometryData) -> GeometryData!:
    if data.has_cad() or (data.instance_count() == 0 and data.mesh == none):
        return 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) -> Mesh?!:
    if not data.has_cad():
        return Mesh.empty()
    if level == cv_level:
        return CadGeometry.cv_cloud(data.geometry)
    return pick_mesh(data)

## The tagged tessellations the Object, Faces and Edges levels pick on,
## made once per result, with what the last step created as `.selection`
## (a group may name it, so steps read their groups on this same mesh).
func pick_mesh(data: GeometryData) -> Mesh!:
    if let known = data.pick_cache:
        return known
    var made = CadEdits.pick_mesh(data.geometry)
    if data.created != "":
        made = Groups.with_group(made, ".selection", 2, data.created)
    data.pick_cache = made
    return made

func run(step: EditStep, data: GeometryData) -> GeometryData!:
    if step.verb.starts_with("Create "):
        return created(step, data)
    if not data.has_cad():
        error(ui.invalid, "Edit CAD has no models to edit yet: create one, or connect CAD")
    if step.group_type == 1:
        return moved_cvs(step, data)
    if step.verb in edge_features():
        return featured(step, data)
    if step.group_type == 2:
        error(ui.invalid, f"{step.verb} does not apply to CAD edges")
    let shown = pick_mesh(data)
    if step.topology != 0 and step.topology != shown.topology_hash():
        error(ui.invalid, "The CAD input changed. Undo the upstream change or clear this node's edits.")
    if step.verb == "Transform Components":
        return GeometryData(geometry = CadEdits.transformed_parts(data.geometry, shown, step.group, step.numbers))
    if step.verb == "Delete":
        return GeometryData(geometry = CadEdits.without_parts(data.geometry, shown, step.group))
    error(ui.invalid, f"{step.verb} does not apply to CAD models or faces")

## A feature on picked edges, as its node makes it: each model with picked
## edges replaced by the feature on them (its new faces named for the step).
func featured(step: EditStep, data: GeometryData) -> GeometryData!:
    let shown = pick_mesh(data)
    if step.topology != 0 and step.topology != shown.topology_hash():
        error(ui.invalid, "The CAD input changed. Undo the upstream change or clear this node's edits.")
    var geometry = data.geometry
    var any = false
    for index in 0..<CadGeometry.model_count(data.geometry):
        let edges = CadEdits.model_edges(shown, step.group, index)
        if edges == "":
            continue
        let body = GeometryData(geometry = CadGeometry.of_model(CadGeometry.model(data.geometry, index)))
        let made = cad_nodes.evaluate_cad(step.verb, step.numbers, body, f"#e{step.topology}.{index}", texts = [edges, "", ""])
        geometry = CadEdits.replaced(geometry, index, CadGeometry.model(made.geometry, 0))
        any = true
    if not any:
        error(ui.invalid, f"{step.verb} needs edges of a model: pick them at the Edges level")
    return GeometryData(geometry = geometry)

## 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 CAD input's control vertices changed. Undo the upstream change or clear this node's edits.")
    let result = Verbs.run(step.verb, before, step.group, step.group_type, step.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` added as a model of its own, named as
## what was created.
func created(step: EditStep, data: GeometryData) -> GeometryData!:
    let name = step.verb[7..]
    let v = step.numbers
    if v.length < 6:
        error(ui.invalid, f"{step.verb} needs six numbers")
    # Named, so features (Fillet) can find its edges again.
    let index = CadGeometry.model_count(data.geometry)
    let solid = CadModeling.tagged(solid_of(name, v), f"#c{index}")
    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]) -> CadModel!:
    if name == "Box":
        return CadSolids.box(v[0], v[1], v[2])
    if name == "Cylinder":
        return CadSolids.cylinder(v[0], v[1])
    if name == "Cone":
        return CadSolids.cone(v[0], v[1], v[2])
    if name == "Sphere":
        return CadSolids.sphere(v[0])
    if name == "Torus":
        return CadSolids.torus(v[0], v[1])
    error(ui.invalid, f"Edit CAD cannot create {name}")