Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.9

0.11.9 / src / sketch_editor.luc

## Editing a Sketch node in the viewport, Fusion 360's way
## (docs/research/FUSION-SKETCH-STUDY.md): while a Sketch node is selected
## and displayed, the viewport draws its entities on its plane (fully
## constrained ones white, free ones blue, construction orange), and the
## marking menus (hold A, S or D: CREATE, MODIFY, CONSTRAINTS) pick a tool.
##
## A tool is used once, then Select again (Line chains from its last end
## until Esc). Drawing tools are click by click; the cursor snaps through
## the snapping layer (snapping.luc: points, middles, crossings, curves,
## the grid; a snapped point is the same point, or held on its curve), and
## a line drawn near level or upright becomes horizontal or vertical.
## Holding Cmd (Ctrl elsewhere) places freely. Constraint tools take their
## entities in order, the first the reference (sketch_constrain.luc);
## Sketch Dimension takes one entity or two, then a click in empty space.
## Select picks entities (Shift adds, Ctrl or Cmd takes away) and drags
## points, which snap and are held where they are let go; a drag from
## empty space draws a box selecting at the level what lies wholly inside it
## dragged left to right, what it touches dragged right to left (Fusion's
## window and crossing; at Shapes, whole chains), the same
## modifiers, a plain box over nothing selecting nothing. A click on a
## constraint's glyph or a dimension selects that constraint
## (sketch_glyphs.luc, sketch_dimensions.luc; they win over geometry under
## the pointer); a click on a selected dimension opens its value box on its
## label, and a dimension dragged moves its label (one undo step). While a
## drawing tool's shape is begun, value boxes follow the cursor
## (sketch_typing.luc): typing, Tab and Enter size it. Delete
## removes the selection, constraints and entities in one undo step (the
## viewport's right-click menu too); X makes it construction, Q is Select.
##
## The editor works on a live CadSketch read from the node; each finished
## action writes it back as one undo step (commit), and an undo or a change
## from elsewhere reads the node again (sync).
##
## This class holds the sketch, the tool, what is drawn and selected, and
## the edits on them; the viewport's pointer and keys come through
## sketch_input.luc. What the editor leans on: where the cursor lands
## (sketch_inference.luc),
## selections and boxes (sketch_selecting.luc), Project
## (sketch_projecting.luc), the frame and Look At (sketch_frames.luc), the
## glyphs (sketch_glyphs.luc), the dimensions (sketch_dimensions.luc), the
## value boxes (sketch_typing.luc) and the profiles (sketch_profiles.luc).
from edit_types import point_level, edge_level, face_level
from sketch_profiles import SketchProfiles
from luce_cad.sketch import CadSketch, CadShadows
from workspace import Workspace
from sketch_node import SketchFrame, node_frame
from sketch_frames import FrameCache, look_at
from sketch_projecting import SketchProjecting
from sketch_source import ModelSketches
import sketch_source
import sketch_tools
import sketch_kinds
from sketch_kinds import on_curve, midpoint, point_kind, line_kind
import sketch_selecting
import marquee
from sketch_dimensions import SketchDimensions, LabelDrag
from sketch_glyphs import SketchGlyphs, Glyph
from sketch_typing import SketchTyping
import sketch_origin

## How near the cursor snaps, in points on screen.
pub let snap_reach = 9.0

pub class SketchEditor:
    pub let w: Workspace
    ## The node edited, the Edit CAD sketch's name ("" a Sketch node's),
    ## both as one key, and the text the live sketch was read from.
    pub var node: int = -1
    pub var name: str = ""
    var edited: str = ""
    var text: str = ""
    ## An Edit CAD node's sketches as its cook reported them.
    pub let models: ModelSketches
    pub var sketch: CadSketch? = none
    pub var frame: SketchFrame
    pub let frames: FrameCache
    ## The curves whose links the last cook lost (drawn apart).
    pub var lost: list[int]
    ## Project's casts of the input body's edges.
    pub let projecting: SketchProjecting
    ## The tool in use (set_tool keeps the workspace's sketch_tool the same).
    pub var tool: str = "Select"
    var tool_was: str = "Select"
    ## A drawing tool's placed points: plane coordinates, and the point
    ## entity each is (-1: not made yet).
    pub var clicks: list[list[float]]
    pub var click_snaps: list[int]
    ## What each click snapped to: its kind (snapping.luc's, CadSketch.snap:
    ## 1 point, 2 middle, 4 crossing, 8 curve; 0 none or the grid) and a
    ## crossing's second curve.
    pub var click_kinds: list[int]
    pub var click_others: list[int]
    ## Each click's point once made (made_point), else -1.
    pub var made: list[int]
    ## The cursor on the plane, snapped, and what it snapped to (-1: none).
    pub var cursor: list[float]
    pub var snap: int = -1
    pub var snap_kind: int = 0
    pub var snap_other: int = -1
    pub var free_placing: bool = false
    pub var hover: int = -1
    ## The part of the sketch origin under the pointer when no entity is
    ## (sketch_origin.luc: 0 its point, 1 its x axis, 2 its y axis; -1 none).
    pub var hover_origin: int = -1
    pub var selection: list[int]
    ## Constraints selected by their glyphs, and the one whose glyph is
    ## under the pointer (-1: none).
    pub var constraint_selection: list[int]
    pub var hover_glyph: int = -1
    ## The dimensions and constraints the last over-constraining one
    ## conflicted with, lit until the next change (sketch_picking.luc).
    pub var conflicts: list[int]
    ## The sketch's profiles: shaded, hovered and picked at Shapes and Smart
    ## (the picked keys are the workspace's sketch_profiles).
    pub let profiles: SketchProfiles
    ## The profile under a press that may turn into a box ("": none).
    pub var box_profile: str = ""
    ## A constraint or dimension tool's picks so far.
    pub var picks: list[int]
    ## A point being dragged by Select.
    pub var dragging: int = -1
    pub var drag_moved: bool = false
    ## Select pressed on nothing: a box from (box[0], box[1]) to the pointer
    ## at (box[2], box[3]) while `boxing`, and what it does (0 replaces, 1
    ## adds, 2 takes away).
    pub var boxing: bool = false
    pub var box: list[float]
    pub var box_operation: int = 0
    ## Counts changes to the live sketch, so drawings are made again.
    pub var revision: int = 0
    ## A dimension's value is typed here: called with its constraint, where
    ## (the viewport's points: the click placing it, or its label's corner)
    ## and whether the box sits on the label.
    pub var on_value: func(int, float, float, bool) -> unit!? = none
    ## A drawing tool's clicks are in (sketch_create.luc finishes it), set
    ## by the view.
    pub var on_finish: func() -> unit!? = none
    ## Ask for a number (a tool's value typed): its label, the value to
    ## start from, and what takes the answer.
    pub var on_ask: func(str, float, func(float) -> unit!) -> unit!? = none
    ## The distance the last Offset was.
    pub var last_offset: float = 5.0
    ## The Text tool's clicks are in: ask what it says (place_text).
    pub var on_text: func() -> unit!? = none
    ## Where that text goes: its anchor (x, y), height and the point its
    ## anchor snapped to (-1: none).
    pub var text_at: list[float]
    ## A MODIFY tool's click (sketch_modify.luc; Shift held), set by the
    ## view so this module need not know it.
    pub var on_modify: func(bool) -> unit!? = none
    ## A constraint or dimension tool's click (sketch_picking.luc), and a
    ## constraint tool applied to its picks, whether they were enough
    ## (set by the view).
    pub var on_pick: func() -> unit!? = none
    pub var on_constrain: func() -> bool!? = none
    ## The dimensions and the constraint glyphs as placed on the screen.
    pub let dimensions: SketchDimensions
    pub let glyphs: SketchGlyphs
    ## A dimension pressed, its label to drag.
    pub let label_drag: LabelDrag
    ## The value boxes while drawing, the clicks placed so far by the tool
    ## (they follow it), and the cursor as it landed before they steered it.
    pub let typing: SketchTyping
    pub var placed_clicks: int = 0
    pub var landed: list[float]
    ## A click in the viewport (an open value box closes).
    pub var on_click: func() -> unit!? = none
    var edited_was: str = ""
    pub var pointer_x: float = 0.0
    pub var pointer_y: float = 0.0
    ## Screen size of the last event, and the reach of a snap in sketch units.
    pub var width: float = 1.0
    pub var height: float = 1.0
    pub var reach: float = 1.0

    pub func init(self, w: Workspace) -> unit!:
        self.text_at = []
        self.lost = []
        self.w = w
        self.models = ModelSketches()
        self.frame = node_frame([1.0, 0.0])
        self.frames = FrameCache()
        self.projecting = SketchProjecting()
        self.clicks = []
        self.click_snaps = []
        self.click_kinds = []
        self.click_others = []
        self.made = []
        self.cursor = [0.0, 0.0]
        self.selection = []
        self.constraint_selection = []
        self.conflicts = []
        self.profiles = SketchProfiles()
        self.picks = []
        self.box = []
        self.dimensions = SketchDimensions()
        self.glyphs = SketchGlyphs()
        self.label_drag = LabelDrag()
        self.typing = SketchTyping()
        self.landed = [0.0, 0.0]

    ## Whether a Sketch node is being edited: selected, displayed, enabled,
    ## and no tool prompt open.
    pub func active(self) -> bool:
        return self.w.sketching()

    ## Read the sketch again when it is another sketch, or its text or plane
    ## changed (an undo, the parameter panel, a cook casting it again).
    pub func sync(self) -> unit!:
        let node = self.w.selected() else return
        let source = sketch_source.source_of(self.w, self.frames, self.models, node)
        let which = f"{node.id}/{source.name}"
        # The plane follows its face as the body upstream changes.
        if not source.plane.equals(self.frame):
            let moved = self.sketch != none and which == self.edited
            self.frame = source.plane
            self.revision += 1
            # A new plane (a face picked): look straight at it.
            if moved:
                self.look_at()
        self.lost = source.lost
        if which == self.edited and source.text == self.text and self.sketch != none:
            return
        # Another sketch than the one edited: its tool and selection go.
        if which != self.edited and self.edited != "":
            self.reset_tool()
            self.selection = []
            self.constraint_selection = []
            self.w.sketch_profiles = []
            self.set_tool("Select")
        # What the pointer was over, and a tool's clicks and picks, belong to
        # the sketch read before (an undo, another node).
        self.hover = -1
        self.hover_glyph = -1
        self.hover_origin = -1
        self.conflicts = []
        self.snap = -1
        self.reset_tool()
        self.node = node.id
        self.name = source.name
        self.text = source.text
        let sketch = CadSketch.parse(self.text)
        _ = sketch.solve()
        sketch.analyze()
        let entering = self.sketch == none or self.edited_was != which
        self.edited_was = which
        self.edited = which
        self.sketch = sketch
        if entering:
            self.look_at()
        let kept: list[int] = []
        for at in self.selection:
            if at < sketch.entity_count():
                kept.append(at)
        self.selection = kept
        let constraints: list[int] = []
        for at in self.constraint_selection:
            if at < sketch.constraint_count():
                constraints.append(at)
        self.constraint_selection = constraints
        self.w.sketch_profiles = self.profiles.still_there(sketch, self.frame, self.w.sketch_profiles)
        self.revision += 1

    ## The constraint glyphs on a viewport `width` by `height`, placed clear
    ## of the dimensions' labels (each made again only when the sketch or
    ## the view changed).
    pub func placed_glyphs(self, width: float, height: float) -> list[Glyph]!:
        let sketch = self.sketch else return []
        let labels = self.dimensions.placed(self.w, sketch, self.frame, self.revision, width, height)
        return self.glyphs.placed(self.w, sketch, self.frame, self.dimensions.made_from, width, height, labels)

    ## Look straight at the sketch plane, as Fusion's Look At does.
    pub func look_at(self) -> unit!:
        let sketch = self.sketch else return
        look_at(self.w, sketch, self.frame)

    ## Light the constraints an over-constraint of `sketch` runs through,
    ## but `added` (the one that over-constrained it; -1 none), as they
    ## will be numbered once it is taken away (`removing`).
    pub func light_conflicts(self, sketch: CadSketch, added: int, removing: bool) -> unit!:
        let found: list[int] = []
        for at in 0..<sketch.find_dependent():
            let c = sketch.dependent(at)
            if c != added:
                found.append(c - 1 if removing and c > added else c)
        self.conflicts = found
        self.revision += 1

    ## Say `text` in the status line.
    pub func say(self, text: str):
        self.w.notice = text
        self.w.touch()

    ## Write the live sketch back as one undo step (the Sketch node's text,
    ## or the Edit CAD sketch's step: sketch_source.write).
    pub func commit(self, label: str) -> unit!:
        let sketch = self.sketch else return
        let node = self.w.network.find(self.node) else return
        let text = sketch.text()
        self.conflicts = []
        if not sketch_source.write(self.w, node, self.name, text, label):
            return
        self.text = text
        sketch.analyze()
        self.revision += 1
        # A tool is used once: what it made is in, so back to Select (Line
        # goes on from its end until Esc).
        if not (self.tool in ["Select", "Line"]):
            self.reset_tool()
            self.set_tool("Select")
            self.w.notice = self.hint()

    ## Pick tool `name` (Select, a drawing tool, a constraint tool or Sketch
    ## Dimension). A constraint tool with enough already selected applies
    ## to the selection at once.
    pub func choose(self, name: str) -> unit!:
        self.sync()
        self.reset_tool()
        self.set_tool(name)
        if name != "Select":
            self.w.last_sketch_tool = name
        if sketch_tools.constrains(name) and self.selection.length > 0:
            self.picks = self.selection.copy()
            if let constrain = self.on_constrain:
                if constrain():
                    self.set_tool("Select")
        self.w.notice = self.hint()
        self.w.touch()

    ## The tool in use, here and on the workspace (the viewport's tool
    ## column shows it).
    pub func set_tool(self, name: str) -> unit!:
        let casting = name == "Project" or self.tool == "Project"
        self.tool = name
        self.w.sketch_tool = name
        # The cook casts the body's edges while Project is the tool.
        if casting and name != self.tool_was:
            self.w.rebuild()
        self.tool_was = name
        if name != "Project":
            self.projecting.relinking = []

    pub func reset_tool(self):
        self.clicks = []
        self.click_snaps = []
        self.click_kinds = []
        self.click_others = []
        self.made = []
        self.picks = []
        self.dragging = -1
        self.boxing = false
        _ = self.label_drag.finish()
        self.typing.clear()

    ## The status line's hint for the current tool.
    pub func hint(self) -> str:
        return sketch_tools.hint(self.tool)

    ## A point at the cursor: the snapped point itself, else a new point (on
    ## the snapped curve, constrained there).
    pub func cursor_point(self) -> int!:
        return self.snapped_point(self.cursor, self.snap, self.snap_kind, self.snap_other)

    ## The input body's edges cast onto the plane while Project is the
    ## tool; none without a body.
    pub func projection(self) -> CadShadows?!:
        return self.projecting.projection(self.w, self.node)

    ## The edge whose shadow is under the cursor, or -1.
    pub func projected_edge(self) -> int!:
        let cast = self.projection() else return -1
        return cast.nearest(self.cursor[0], self.cursor[1], self.reach)

    ## The face Project would bring with the cursor where it is (off every
    ## edge, inside a face's shadow, the nearest the camera), or -1.
    pub func projected_face(self) -> int!:
        let cast = self.projection() else return -1
        if cast.nearest(self.cursor[0], self.cursor[1], self.reach) >= 0:
            return -1
        return cast.face_at(self.cursor[0], self.cursor[1], self.camera_side())

    ## +1 when the camera is on the sketch plane's normal side, else -1.
    pub func camera_side(self) -> float!:
        let eye = self.w.view.camera.projection(1.0).position
        return 1.0 if eye.subtract(self.frame.origin).dot(self.frame.normal()) >= 0.0 else -1.0

    ## Project body (the right-click menu while Project is the tool): the
    ## input body's outline as seen from the camera, as one undo step.
    pub func project_body(self) -> unit!:
        let sketch = self.sketch else return
        let (made, problem) = self.projecting.project_body(self.w, self.node, sketch, self.camera_side())
        if problem != "":
            self.say(problem)
        if made:
            self.commit("Project body")

    ## The Text tool's words: the text where its clicks put it, as one undo.
    pub func place_text(self, content: str) -> unit!:
        let sketch = self.sketch else return
        if self.text_at.length < 4 or content.trim() == "":
            return
        let snapped = int(self.text_at[3])
        let anchor = snapped if snapped >= 0 and sketch.kind(snapped) == point_kind else sketch.add_point(self.text_at[0], self.text_at[1])
        _ = sketch.add_text(anchor, self.text_at[2], content)
        self.text_at = []
        self.commit("Text")

    ## Click `at`'s point, made once: the point it snapped to, else a new
    ## one there (on the curve it snapped to).
    pub func made_point(self, at: int) -> int!:
        let sketch = self.sketch else return -1
        if self.made[at] >= 0:
            return self.made[at]
        let point = self.snapped_point(self.clicks[at], self.click_snaps[at], self.click_kinds[at], self.click_others[at])
        self.made[at] = point
        return point

    ## A point at `place` as what it snapped to holds it: that point itself;
    ## a new one at a line's middle, on two crossing curves or on a curve
    ## (held there by its constraints); else a free new one.
    pub func snapped_point(self, place: list[float], caught: int, kind: int, other: int) -> int!:
        let sketch = self.sketch else return -1
        let snapped = self.resolved(caught)
        if snapped >= 0 and sketch.kind(snapped) == point_kind:
            return snapped
        let point = sketch.add_point(place[0], place[1])
        if snapped < 0:
            return point
        if kind == 2 and sketch.kind(snapped) == line_kind:
            _ = sketch.constrain(midpoint, point, snapped)
            return point
        for curve in [snapped, other if kind == 4 else -1]:
            if curve >= 0 and sketch_kinds.holds_points(sketch.kind(curve)):
                _ = sketch.constrain(on_curve, point, curve)
        return point

    ## Snapped-to entity `snapped` as an entity: the origin's part for its
    ## mark (sketch_origin.snap_mark), made in the sketch when first used.
    pub func resolved(self, snapped: int) -> int!:
        let part = sketch_origin.marked_part(snapped)
        if part < 0:
            return snapped
        return self.origin_entity(part)

    ## The sketch origin's part `part` (0 point, 1 x axis, 2 y axis) as an
    ## entity of the live sketch, made when first held to (Fusion's
    ## origin, projected into the sketch when referenced).
    pub func origin_entity(self, part: int) -> int!:
        let sketch = self.sketch else return -1
        let before = sketch.entity_count()
        let at = sketch.origin(part)
        if sketch.entity_count() != before:
            self.revision += 1
        return at

    ## What Select hovers at the selection level (Points: points, Lines and
    ## Shapes: curves); other tools pick either (CadSketch.pick's `only`).
    pub func pick_filter(self) -> int:
        # Tools that work on curves pick only curves (not a crossing's or
        # an end's point under the cursor).
        if sketch_tools.picks_curves(self.tool):
            return 2
        if self.tool != "Select":
            return 0
        if self.w.sketch_level == point_level:
            return 1
        return 2 if self.w.sketch_level in [edge_level, face_level] else 0

    ## Profile `key` (a click in its region) alone (`operation` 0, the
    ## entities and constraints let go), added or taken away again (1,
    ## Shift) or taken away (2, Ctrl or Cmd).
    pub func select_profile(self, key: str, operation: int):
        if operation == 0:
            self.selection = []
            self.constraint_selection = []
        self.w.sketch_profiles = sketch_selecting.toggled_key(self.w.sketch_profiles, key, operation)
        self.revision += 1
        self.w.touch()

    ## Constraint `constraint` (its glyph clicked) alone (`operation` 0,
    ## the entities let go), added or taken away again (1, Shift) or taken
    ## away (2, Ctrl or Cmd).
    pub func select_constraint(self, constraint: int, operation: int):
        if operation == 0:
            self.selection = []
            self.w.sketch_profiles = []
        self.constraint_selection = sketch_selecting.toggled(self.constraint_selection, constraint, operation)
        self.revision += 1

    ## The selection with `picked` alone (`operation` 0; selected
    ## constraints and profiles let go), added (1) or taken away (2).
    pub func change_selection(self, picked: list[int], operation: int):
        if operation == 0:
            self.constraint_selection = []
            self.w.sketch_profiles = []
        self.selection = sketch_selecting.changed(self.selection, picked, operation)
        self.revision += 1

    ## Select's box let go: a click on nothing picks the profile pressed in
    ## (Shapes and Smart), else selects nothing (Shift or Ctrl: changes
    ## nothing); a drag selects at the level what lies wholly inside the
    ## box, or what it touches when dragged right to left
    ## (sketch_selecting.boxed).
    pub func finish_box(self) -> unit!:
        let sketch = self.sketch else return
        let operation = self.box_operation
        if not marquee.dragged(self.box):
            if self.box_profile != "":
                self.select_profile(self.box_profile, operation)
            elif operation == 0:
                self.change_selection([], 0)
            return
        self.change_selection(sketch_selecting.boxed(self.w, sketch, self.frame, self.box, self.pick_filter(), self.w.sketch_level == face_level, self.width, self.height), operation)

    ## Open dimension `constraint`'s value box on its label (a driven one
    ## is measured, not set: said instead).
    pub func edit_dimension(self, constraint: int) -> unit!:
        let sketch = self.sketch else return
        if constraint < 0 or constraint >= sketch.constraint_count():
            return
        if sketch.driven(constraint):
            self.say("A driven dimension measures the sketch: make it driving (right-click) to set it")
            return
        let shown = self.dimensions.find(constraint) else return
        if let open = self.on_value:
            open(constraint, shown.box.x, shown.box.y, true)

    ## The selected projected curves (those linked to the body's edges).
    pub func linked_selection(self) -> list[int]:
        let sketch = self.sketch else return []
        let found: list[int] = []
        for at in self.selection:
            if at < sketch.entity_count() and sketch.linked(at):
                found.append(at)
        return found

    ## Break Link: the selected projected curves become plain curves, where
    ## they are, as one undo step.
    pub func break_links(self) -> unit!:
        let sketch = self.sketch else return
        for at in self.linked_selection():
            sketch.break_link(at)
        self.lost = []
        self.commit("Break link")

    ## Re-link: the selected projected curves follow the edge clicked next
    ## (Project is the tool until then).
    pub func relink_selection(self) -> unit!:
        let chosen = self.linked_selection()
        if chosen.length == 0:
            return
        self.choose("Project")
        self.projecting.relinking = chosen
        self.say("Re-link: click the body's edge the curves should follow")

    ## Delete: the selected constraints, then the selected entities (and
    ## what is drawn on them), as one undo step.
    pub func remove_selection(self) -> unit!:
        let sketch = self.sketch else return
        if self.selection.length == 0 and self.constraint_selection.length == 0:
            return
        let label = "Delete sketch entities" if self.selection.length > 0 else ("Delete constraint" if self.constraint_selection.length == 1 else "Delete constraints")
        # Highest first, as removing renumbers what follows.
        let constraints = self.constraint_selection.copy()
        constraints.sort()
        var at = constraints.length
        while at > 0:
            at -= 1
            if constraints[at] < sketch.constraint_count():
                sketch.unconstrain(constraints[at])
        # The origin is the sketch's frame: never deleted.
        let chosen: list[int] = []
        for entity in self.selection:
            if entity < sketch.entity_count() and sketch.origin_part(entity) < 0:
                chosen.append(entity)
        chosen.sort()
        at = chosen.length
        while at > 0:
            at -= 1
            if chosen[at] < sketch.entity_count():
                sketch.remove(chosen[at])
        self.selection = []
        self.constraint_selection = []
        self.hover_glyph = -1
        self.commit(label)