Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.1

0.11.1 / src / edit_cad.luc

## Edit CAD: the Edit framework's kind for analytic models. Its levels are
## Object (a whole model), Faces (a B-rep face), Edges (a B-rep edge) and
## CVs (control vertices). 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); 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, 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 geometry_data import GeometryData
from edit_operations import EditStep
from edit_types import EditKind, EditLevel, EditTool
from tools import tool_run
from luce_ui import ui

pub let kind_name = "Edit CAD"

## Level indices.
let object_level = 0
let cv_level = 3

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

func levels() -> list[EditLevel]:
    return [EditLevel("Object", "cube", Domain.face, GroupType.faces, model_piece),
            EditLevel("Faces", "face-select", Domain.face, GroupType.faces, face_piece),
            EditLevel("Edges", "edge-select", Domain.edge, GroupType.edges, edge_piece),
            EditLevel("CVs", "vertex-select", Domain.point, GroupType.points)]

## Rotate and scale whole models or CVs, Delete models or faces; noise,
## flatten and snap CVs.
func tool_list() -> list[EditTool]:
    let result: list[EditTool] = []
    for (name, offered) in [("Rotate", [object_level, cv_level]), ("Scale", [object_level, cv_level]), ("Delete", [object_level, 1]),
                            ("Noise", [cv_level]), ("Flatten", [cv_level]), ("Snap", [cv_level])]:
        let tool = name
        let made = tool_run(tool, 0.5) else continue
        result.append(EditTool(tool, made.verb, offered, func (amount: float) -> list[float]:
            if let current = tool_run(tool, amount):
                return current.numbers
            return []))
    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))
    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.group_type == 2:
        error(ui.invalid, "CAD edges have no tools yet")
    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 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")
    let solid = solid_of(name, v)
    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 index = CadGeometry.model_count(data.geometry)
    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}")