Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.7

0.11.7 / src / edit_types.luc

## What an Edit node kind plugs into the Edit framework (edit_kinds.luc):
## its selection levels, its tools and primitives, the geometry each level
## picks on, and the step executor that gives its recipe's verbs meaning.
## The framework owns everything else: the recipe (undo is a shorter
## recipe), checkpoints, move coalescing, symmetry, soft selection and Keep
## selection, the selection and its hand-off, Tool → Select, the inspector
## rows, the level buttons, the marking menus and the tool bar (the last
## step's parameters).
from luce_geocore.geocore import Verbs
from luce_geocore.geocore import Mesh, Domain, GroupType, Vector3
from geometry_data import GeometryData
from edit_operations import EditStep
from parameter_rows import Parameter
from tool_record import Tool
from luce_ui import ui
from luce_cad.model import CadTolerances

## The viewport's selection levels, the same in every context (keys 1-7):
## Object, Point (vertices, CVs), Edge (edges, isoparms), Face, and Smart,
## which picks whichever of the kind's `smart` levels is under the pointer;
## Edit CAD adds Patch (a whole surface) and Curves.
pub let object_level = 0
pub let point_level = 1
pub let edge_level = 2
pub let face_level = 3
pub let smart_level = 4
pub let patch_level = 5
## Edit CAD's Curves: its curve objects (luce-cad's cad_curves), whole.
pub let curve_level = 6

## The levels' switcher names, icons and keys.
pub func level_names() -> list[str]:
    return ["Object", "Point", "Edge", "Face", "Smart", "Patch", "Curves"]

## A sketch's names for them (it has no Object level).
pub func sketch_level_names() -> list[str]:
    return ["Object", "Points", "Lines", "Shapes", "Smart"]

pub func level_icons() -> list[str]:
    return ["cube", "vertex-select", "edge-select", "face-select", "smart-select", "patch-select", "curve-select"]

## A selection level: what one pick selects, on which domain of the level's
## pick geometry, and the group type its steps receive. A kind without a
## level (Edit SDF has only Object) leaves its slot `missing`.
pub class EditLevel:
    ## The switcher's label and icon ("Polygons", "face-select").
    pub let name: str
    pub let icon: str
    pub let domain: Domain
    pub let group_type: GroupType
    ## With a piece function, a pick selects the whole piece around the
    ## picked element: the group expression naming it on `domain` (Object
    ## levels); without one, the element alone.
    pub let piece: func(Mesh, int) -> str!?
    pub let available: bool

    pub func init(self, name: str, icon: str, domain: Domain, group_type: GroupType, piece: func(Mesh, int) -> str!? = none, available: bool = true):
        self.name = name
        self.icon = icon
        self.domain = domain
        self.group_type = group_type
        self.piece = piece
        self.available = available

    ## The group expression of what picking `element` of `mesh` selects: its
    ## piece, or "" for the element alone.
    pub func whole(self, mesh: Mesh, element: int) -> str!:
        let expand = self.piece else return ""
        return expand(mesh, element)

    ## The domain and group type as geocore's i64 parameters take them.
    pub func domain_number(self) -> int:
        return domain_number(self.domain)

    pub func group_number(self) -> int:
        return group_number(self.group_type)

## A level slot a kind does not have (`name` as level_names has it).
pub func missing(name: str) -> EditLevel:
    return EditLevel(name, "", Domain.face, GroupType.faces, available = false)

## A tool: its label, the verb its step runs, the levels it is offered on
## ([] every level), the step's starting numbers and the tool bar's rows
## over them. The verb is a node kind (a mesh verb, Fillet) whenever the
## tool is that node inside the Edit node: `numbers` none then starts from
## the node's starting values, and `rows` none shows the node's own rows but its
## selection (Group, Group Type, Edges). A kind's own verb (Edit SDF's
## Blend) gives both. A registry tool (tool_registry.luc: Edit Mesh's) is
## made from its Tool, which `tool` keeps for the menus. `icon` is what the
## kind's menus draw for it: a registry tool's own, else the kind names it
## (Edit SDF's Intersect is a boolean where Edit CAD's intersects surfaces).
pub class EditTool:
    pub let name: str
    pub let verb: str
    pub let levels: list[int]
    pub let numbers: list[float]?
    pub let rows: list[Parameter]?
    pub let tool: Tool?
    pub let icon: str

    pub func init(self, name: str, verb: str, levels: list[int], numbers: list[float]? = none, rows: list[Parameter]? = none, tool: Tool? = none, icon: str = ""):
        self.name = name
        self.verb = verb
        self.levels = levels
        self.numbers = numbers
        self.rows = rows
        self.tool = tool
        var shown = icon
        if let registered = tool:
            if shown == "": shown = registered.icon
        self.icon = shown

    pub func offered(self, level: int) -> bool:
        return self.levels.length == 0 or level in self.levels

## The EditTool of registry tool `tool`: its label, verb, first pick's
## levels and starting numbers.
pub func from_tool(tool: Tool) -> EditTool:
    return EditTool(tool.label, tool.name, tool.offered_levels(), tool.starting(), tool = tool)

## An Edit node kind.
pub class EditKind:
    ## The node kind ("Edit Mesh").
    pub let name: str
    ## Object, Point, Edge and Face, in that order (missing ones too).
    pub let levels: list[EditLevel]
    pub let tools: list[EditTool]
    ## Create entries ("Box", "Sphere", …).
    pub let primitives: list[str]
    ## The geometry the recipe starts from, made from the node's input (an
    ## empty GeometryData when unconnected) and the node's tag (cad_nodes'
    ## tag_of, which names what it makes); fails on input it cannot edit.
    pub let start: func(GeometryData, str) -> GeometryData!
    ## The geometry level `level` of `data` picks on (the worker publishes
    ## it for the viewport); none when there is nothing to pick.
    pub let pick: func(GeometryData, int) -> Mesh?!
    ## Recipe step number `at` on `data`, in the node tagged `tag` (the tag
    ## and number name what the step makes, so later steps can refer to it,
    ## and two Edit nodes in one chain never make the same names).
    ## `reference`: the node's second input (Edit Mesh's Reference), if wired;
    ## the project's CAD tolerances, for what a step makes.
    pub let run: func(EditStep, int, GeometryData, str, GeometryData?, CadTolerances) -> GeometryData!
    ## The step creating primitive `name`, with its default numbers.
    pub let create: func(str) -> EditStep?!
    ## Whether the selection also shows through surfaces: for pick geometry
    ## the viewport does not draw (Edit SDF's proxies inside the surface).
    pub let see_through: bool
    ## Tools that, with nothing selected, draw instead: clicks place corners
    ## (on points, surfaces or the ground), Enter or the first corner again
    ## finishes, and `drawn` makes the one step (Edit Mesh's PolyDraw).
    pub let draw_tools: list[str]
    pub let drawn: func(str, list[Vector3]) -> EditStep?!?
    ## The levels Smart picks among (all on the same pick geometry): the
    ## nearest point, else edge, else face under the pointer (none: all
    ## three).
    pub let smart: list[int]
    ## Whether the pick geometry is a splat cloud the viewport tints where
    ## selected (Edit GSplats): no point markers, and a drag selects by the
    ## splats' footprints with a box, a lasso or a brush.
    pub let tints: bool
    ## Steps the kind runs that no tool makes: commands make them (Edit
    ## CAD's sketches, and the Extrude and Revolve of their profiles).
    pub let steps: list[str]
    ## A holding kind's step run again with the result of its last run
    ## (`over`, a drag's last frame) to build over where only positions
    ## change; none: `run` alone.
    pub let run_over: func(EditStep, GeometryData, GeometryData?, GeometryData) -> GeometryData!?
    ## Whether its nodes hold their result (edit_held.luc): each action
    ## replaces it at once and only the last stays adjustable; otherwise
    ## its recipe is replayed.
    pub let holds: bool
    ## Whether a holding kind's action runs on the compute worker rather
    ## than the UI thread (edit_held.luc): all but what must follow the
    ## pointer at once and costs only what moved (a gizmo's move, a sculpt
    ## stroke; a sketch's edit). None: every action runs on the UI thread.
    pub let background: func(EditStep) -> bool!?

    pub func init(self, name: str, levels: list[EditLevel], tools: list[EditTool], primitives: list[str], start: func(GeometryData, str) -> GeometryData!,
                  pick: func(GeometryData, int) -> Mesh?!, run: func(EditStep, int, GeometryData, str, GeometryData?, CadTolerances) -> GeometryData!, create: func(str) -> EditStep?!,
                  see_through: bool = false, draw_tools: list[str] = [], drawn: func(str, list[Vector3]) -> EditStep?!? = none, smart: list[int]? = none,
                  tints: bool = false, steps: list[str] = [], holds: bool = false, run_over: func(EditStep, GeometryData, GeometryData?, GeometryData) -> GeometryData!? = none,
                  background: func(EditStep) -> bool!? = none):
        self.name = name
        self.levels = levels
        self.tools = tools
        self.primitives = primitives
        self.start = start
        self.pick = pick
        self.run = run
        self.create = create
        self.see_through = see_through
        self.draw_tools = draw_tools
        self.drawn = drawn
        self.smart = smart else [point_level, edge_level, face_level]
        self.tints = tints
        self.steps = steps
        self.holds = holds
        self.run_over = run_over
        self.background = background

    ## Whether a recipe step of `verb` is one this kind makes: a geometry
    ## verb (luce-geocore's), a primitive's (its create's), a tool's or a
    ## draw tool's step, or a move (Transform Components).
    pub func knows(self, verb: str) -> bool:
        if Verbs.index_of(verb) >= 0 or verb == "Transform Components" or verb in self.draw_tools or verb in self.steps:
            return true
        # A primitive's step is named by its create ("Box" makes Create
        # Box).
        for name in self.primitives:
            let step = self.create(name) catch failure:
                continue
            if let made = step:
                if made.verb == verb:
                    return true
        for tool in self.tools:
            if tool.verb == verb:
                return true
        return false

    ## Whether `step` runs on the compute worker (see `background`).
    pub func in_background(self, step: EditStep) -> bool:
        let decide = self.background else return false
        return decide(step) catch failure:
            return false

    ## Tool `name`, when this kind has it.
    pub func tool(self, name: str) -> EditTool?:
        for tool in self.tools:
            if tool.name == name:
                return tool
        return none

    ## Tool `name` as offered at level `level`: of two tools of one name
    ## (Edit CAD's Blend Curve of curves and of edges), the one the level
    ## takes, else the first.
    pub func tool_at(self, name: str, level: int) -> EditTool?:
        for tool in self.tools:
            if tool.name == name and tool.offered(level):
                return tool
        return self.tool(name)

pub func domain_number(domain: Domain) -> int:
    if domain == Domain.corner: return 1
    if domain == Domain.face: return 2
    if domain == Domain.edge: return 4
    return 0

pub func group_number(group_type: GroupType) -> int:
    if group_type == GroupType.points: return 1
    if group_type == GroupType.edges: return 2
    if group_type == GroupType.faces: return 3
    if group_type == GroupType.corners: return 4
    return 0

# -- The Edit node's own value slots (its parameter pane).

pub let soft_radius_slot = 0
pub let falloff_slot = 1
pub let symmetry_slot = 2
pub let keep_slot = 3

# -- Running a recipe.

## Action `step` (number `at`, which names what it makes) run by `kind` on
## `data`: its result, and true. An action that cannot be built leaves
## `data` as it was, with a warning saying which action failed and why
## (a step_failure), and false: the viewport keeps what the node held (a
## cancelled computation still stops the cook). While a drag sets the step's values
## (`dragged`), its failure fails the node instead, so the viewport keeps
## the drag's last good result, as a feature node's does; let go, the
## warning stands.
pub func run_step(kind: EditKind, step: EditStep, at: int, data: GeometryData, tag: str, tolerances: CadTolerances, dragged: bool = false, reference: GeometryData? = none) -> (GeometryData, bool)!:
    var failed = ""
    var made: GeometryData? = none
    made = kind.run(step, at, data, tag, reference, tolerances) catch failure:
        if failure.message == "Computation superseded":
            error(failure.code, failure.message)
        failed = failure.message
        recover none
    if let result = made:
        return (result, true)
    if dragged:
        error(ui.invalid, f"{step.verb} could not be built: {failed}")
    # A step waiting for a pick (Replace Face's target, Revolve's axis)
    # says what it waits for.
    if failed.starts_with("Pick "):
        return (data.passed(f"{step.verb} waits: {failed}."), false)
    return (data.passed(f"{step.verb} could not be built: {failed}. Undo it, or change its values."), false)

## Whether `warning` is run_step's for an action that was not built.
pub func step_failure(warning: str) -> bool:
    return warning.contains(" could not be built: ") or warning.contains(" waits: ")

## Why a step's warning (run_step's) says it was not built: the reason
## alone, for the step's own tool bar.
pub func step_reason(warning: str) -> str:
    var text = warning
    for marker in [" could not be built: ", " waits: "]:
        if let at = text.index_of(marker):
            text = text[at + marker.length..]
    if let end = text.index_of(". Undo it, or change its values"):
        text = text[..<end]
    return text

# -- Helpers kinds share.

## The input in a wrapper of the Edit node's own (its warning kept), so the
## pick geometry a kind caches on it is that kind's: a `start` for kinds
## that edit a component and pass the others through.
pub func own_data(data: GeometryData, tag: str = "") -> GeometryData!:
    let result = GeometryData(geometry = data.geometry)
    result.warning = data.warning
    return result