Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.8

0.11.8 / src / sketch_view.luc

## What the Sketch editor draws (sketch_editor.luc): Slice's cap
## (sketch_section.luc), its profiles shaded
## (sketch_profiles.luc), its curves as line batches on the plane (made
## again only when the sketch changes), what is
## hovered, selected or picked and what is being drawn on top; then, flat
## on the screen, its points, dimensions (sketch_dimensions.luc), constraint
## glyphs, Select's box and the value boxes of a shape being drawn
## (sketch_typing.luc). Its tools are on the marking menus (A, S, D:
## marking_items.luc), its Points / Lines / Shapes levels on the viewport's
## level buttons.
from luce_gpu.gpu import RenderTarget, Rect, Color
from luce_ui.ui import Painter
from overlay_lines import OverlayLines
from view_grid import GridLines
from workspace import Workspace
from sketch_editor import SketchEditor
from sketch_node import SketchFrame
import sketch_modify
import sketch_create
import sketch_picking
from view_projection import project
import sketch_kinds as names
import sketch_tools
import sketch_typing
import sketch_origin
from sketch_section import SketchSection
import units
from snapping import grid_step
from marquee import draw_box, dragged, crosses
import theme
from luce_std import math

pub class SketchView:
    let w: Workspace
    pub let editor: SketchEditor
    ## The curve batches as of editor revision and lifted plane `drawn`.
    var drawn: str = ""
    var batches: list[OverlayLines]
    ## The points of projected curves, as of `drawn` (purple, as their
    ## curves).
    var projected_points: list[int]
    ## Slice's cap, under the sketch.
    let section: SketchSection
    ## The plane's grid, and the lit lines (selected and picked, hovered,
    ## conflicting) as of their keys: made again only when what they show
    ## changes, and drawn from the GPU in between.
    let grid_lines: GridLines
    var chosen: OverlayLines? = none
    var chosen_key: str = ""
    var hovered: OverlayLines? = none
    var hovered_key: str = ""
    var conflicting: OverlayLines? = none
    var conflicting_key: str = ""

    pub func init(self, w: Workspace) -> unit!:
        self.w = w
        self.editor = SketchEditor(w)
        self.editor.on_modify = self.modify
        self.editor.on_finish = self.finish
        self.editor.on_pick = self.pick
        self.editor.on_constrain = self.constrain
        self.batches = []
        self.projected_points = []
        self.section = SketchSection()
        self.grid_lines = GridLines()

    ## A drawing tool's clicks are in.
    func finish(self) -> unit!:
        sketch_create.finish(self.editor)

    ## A constraint or dimension tool's click.
    func pick(self) -> unit!:
        sketch_picking.pick_click(self.editor)

    ## A constraint tool chosen with a selection: applied to it.
    func constrain(self) -> bool!:
        return sketch_picking.constrain_picks(self.editor)

    ## A MODIFY tool's click on the editor (Shift held: `shift`).
    func modify(self, shift: bool) -> unit!:
        sketch_modify.modify_click(self.editor, shift)

    ## The curves, in the 3D pass: free, fully constrained and construction
    ## ones, projected ones and lost ones, then the highlighted and what is
    ## being drawn. They are lifted a hair toward the camera off the plane,
    ## so a sketch on a face (its projected loop on the face's edges) is not
    ## hidden by the face it lies on.
    pub func draw_lines(self, target: RenderTarget) -> unit!:
        let e = self.editor
        if not e.active():
            return
        e.sync()
        let sketch = e.sketch else return
        let n = e.frame.normal()
        let eye = self.w.view.camera.projection(1.0).position
        let toward = 1.0 if eye.subtract(e.frame.origin).dot(n) >= 0.0 else -1.0
        let f = SketchFrame(e.frame.origin.add(n.multiply_scalar(toward * self.w.view.distance * 0.0006)), e.frame.u, e.frame.v)
        let drawn = f"{e.revision}|{f.key()}"
        if self.drawn != drawn:
            self.batches = []
            for which in 0..<3:
                let lines = OverlayLines.make()
                lines.add_sketch(sketch, f.origin, f.u, f.v, which, unlinked = true)
                self.batches.append(lines)
            # Projected curves over them (Fusion's purple), those whose
            # edge was lost upstream apart.
            let linked = OverlayLines.make()
            let lost = OverlayLines.make()
            self.projected_points = []
            for at in 0..<sketch.entity_count():
                if at in e.lost:
                    lost.add_sketch(sketch, f.origin, f.u, f.v, 3, at)
                elif sketch.linked(at):
                    linked.add_sketch(sketch, f.origin, f.u, f.v, 3, at)
                    if sketch.kind(at) == names.point_kind:
                        self.projected_points.append(at)
                    for part in 0..<sketch.part_count(at):
                        self.projected_points.append(sketch.part(at, part))
            self.batches.append(linked)
            self.batches.append(lost)
            self.drawn = drawn
        let camera = self.w.view.camera
        self.grid(target)
        # The origin's axes across the view, as in every Fusion sketch.
        sketch_origin.draw_axes(self.w, target, camera, f, e.hover_origin)
        # Project: the input body's edges cast on the plane, the one under
        # the cursor brighter.
        if e.tool == "Project":
            if let cast = e.projection():
                let all = OverlayLines.make()
                all.add_shadows(cast, f.origin, f.u, f.v)
                if all.count() > 0:
                    all.batch().draw(camera, target, theme.grey(110.0), 1.0)
                let under = e.projected_edge()
                if under >= 0:
                    let one = OverlayLines.make()
                    one.add_shadows(cast, f.origin, f.u, f.v, under)
                    one.batch().draw(camera, target, theme.accent(), 2.0)
                # Off the edges, inside a face: its loops, all they bring.
                let face = e.projected_face()
                if face >= 0:
                    let loops = OverlayLines.make()
                    for at in 0..<cast.face_edge_count(face):
                        loops.add_shadows(cast, f.origin, f.u, f.v, cast.face_edge(face, at))
                    if loops.count() > 0:
                        loops.batch().draw(camera, target, theme.accent(), 2.0)
        # Slice's cap (hatched), then its profiles shaded under the curves,
        # picked and hovered ones lit.
        let size = target.size()
        if let node = self.w.network.find(e.node):
            self.section.draw(self.w, target, camera, node.id, node.stamp, e.frame, f, size.width, size.height)
        e.profiles.draw(target, camera, sketch, e.frame, self.w.sketch_profiles, size.width, size.height, f.origin.subtract(e.frame.origin))
        let colors = [theme.sketch_free(), theme.sketch_fixed(), theme.sketch_construction(), theme.sketch_projected(), theme.warning()]
        # Projected curves only in Fusion's purple (left out of the others),
        # lost ones last, over the edge projected again in their place.
        for which in [0, 1, 2, 3, 4]:
            if self.batches[which].count() > 0:
                self.batches[which].batch().draw(camera, target, colors[which], 1.5)
        let chosen_key = f"{drawn}|{e.selection}|{e.picks}"
        if chosen_key != self.chosen_key or self.chosen == none:
            let chosen = OverlayLines.make()
            for at in e.selection + e.picks:
                chosen.add_sketch(sketch, f.origin, f.u, f.v, 3, at)
            self.chosen = chosen
            self.chosen_key = chosen_key
        if let chosen = self.chosen:
            chosen.draw_lit_kept(camera, target, theme.accent(), 2.5)
        self.modify_preview(target)
        # What a selected or hovered glyph holds, lit.
        let glyphed = e.constraint_selection.copy()
        if e.hover_glyph >= 0:
            glyphed.append(e.hover_glyph)
        # A drawing tool's rubber band follows the cursor: made each frame.
        let banding = sketch_tools.draws(e.tool)
        let hovered_key = f"{drawn}|{e.tool}|{e.hover}|{glyphed}"
        if banding or hovered_key != self.hovered_key or self.hovered == none:
            let hovered = OverlayLines.make()
            if e.hover >= 0 and e.tool != "Trim":
                hovered.add_sketch(sketch, f.origin, f.u, f.v, 3, e.hover)
            for c in glyphed:
                if c >= sketch.constraint_count():
                    continue
                for which in 0..<3:
                    let held = sketch.constraint_entity(c, which)
                    if held >= 0 and held < sketch.entity_count():
                        hovered.add_sketch(sketch, f.origin, f.u, f.v, 3, held)
            self.rubber_band(hovered)
            self.hovered = hovered
            self.hovered_key = "" if banding else hovered_key
        if let hovered = self.hovered:
            if banding: hovered.draw_lit(camera, target, theme.grey(245.0), 2.0)
            else: hovered.draw_lit_kept(camera, target, theme.grey(245.0), 2.0)
        # What the constraints an over-constraint runs through hold.
        let conflicting_key = f"{drawn}|{e.conflicts}"
        if conflicting_key != self.conflicting_key or self.conflicting == none:
            let conflicting = OverlayLines.make()
            for c in e.conflicts:
                if c >= sketch.constraint_count():
                    continue
                for which in 0..<3:
                    let held = sketch.constraint_entity(c, which)
                    if held >= 0 and held < sketch.entity_count():
                        conflicting.add_sketch(sketch, f.origin, f.u, f.v, 3, held)
            self.conflicting = conflicting
            self.conflicting_key = conflicting_key
        if let conflicting = self.conflicting:
            conflicting.draw_lit_kept(camera, target, theme.warning(), 2.0)

    ## The sketch plane's grid around where the camera looks: a line every
    ## 1, 2 or 5 × 10ⁿ mm, about a tenth of the view's distance apart, a
    ## brighter one every fifth.
    func grid(self, target: RenderTarget) -> unit!:
        let f = self.editor.frame
        let view = self.w.view
        # The snapping grid's step (snapping.luc).
        let step = grid_step(view.distance)
        let at = f.coordinates(view.target)
        let major = step * 5.0
        let center = f.at(math.round(at[0] / major) * major, math.round(at[1] / major) * major)
        self.grid_lines.draw(view.camera, target, center, f.u, f.v, step, theme.grey(48.0), theme.grey(70.0))

    ## What a drawing tool would make with the cursor where it is.
    func rubber_band(self, lines: OverlayLines) -> unit!:
        if sketch_tools.draws(self.editor.tool):
            sketch_create.preview(self.editor, lines)

    ## What Trim would take, or Offset make, with the cursor where it is.
    func modify_preview(self, target: RenderTarget) -> unit!:
        let e = self.editor
        let sketch = e.sketch else return
        let f = e.frame
        let lines = OverlayLines.make()
        if e.tool == "Trim" and e.hover >= 0 and sketch.kind(e.hover) in [names.line_kind, names.circle_kind, names.arc_kind]:
            lines.add_trim_piece(sketch, e.hover, e.cursor[0], e.cursor[1], f.origin, f.u, f.v) catch failure:
                return
            if lines.count() > 0:
                lines.batch().draw(self.w.view.camera, target, theme.warning(), 3.0)
        elif e.tool == "Offset" and e.picks.length > 0:
            let distance = sketch_modify.offset_distance(e)
            if distance > 0.0:
                lines.add_offset_preview(sketch, e.picks, distance, e.cursor[0], e.cursor[1], f.origin, f.u, f.v) catch failure:
                    return
                if lines.count() > 0:
                    lines.batch().draw(self.w.view.camera, target, theme.grey(200.0), 1.5)

    ## The flat layer: points, constraint glyphs and dimensions; in the
    ## `active` pane (the pointer's) also Select's box and the value boxes.
    pub func draw(self, p: Painter, width: float, height: float, active: bool = true) -> unit!:
        let e = self.editor
        if not e.active():
            return
        e.sync()
        let sketch = e.sketch else return
        let f = e.frame
        sketch_origin.draw_point(self.w, p, f, e.hover_origin == sketch_origin.origin_point or e.snap == sketch_origin.snap_mark(sketch_origin.origin_point), width, height)
        for at in 0..<sketch.entity_count():
            # (The origin's point is drawn above, its axes' ends not at all.)
            if sketch.kind(at) != names.point_kind or sketch.origin_part(at) >= 0:
                continue
            let s = project(self.w, f.at(sketch.x(at), sketch.y(at)), width, height)
            if s[2] < 0.0:
                continue
            let chosen = at in e.selection or at in e.picks
            let color = theme.accent() if chosen else (theme.sketch_projected() if at in self.projected_points else (theme.sketch_fixed() if sketch.fixed(at) else theme.sketch_free()))
            let size = 7.0 if at == e.hover or chosen else 5.0
            p.rectangle(Rect(s[0] - size * 0.5, s[1] - size * 0.5, size, size), color)
        if e.snap >= 0 and sketch.kind(e.snap) == names.point_kind:
            let s = project(self.w, f.at(e.cursor[0], e.cursor[1]), width, height)
            outline(p, Rect(s[0] - 7.0, s[1] - 7.0, 14.0, 14.0), theme.accent())
        _ = e.dimensions.placed(self.w, sketch, f, e.revision, width, height)
        e.dimensions.draw(p, e.constraint_selection, e.hover_glyph, e.conflicts)
        self.glyphs(p, width, height)
        # Select's box while it is dragged.
        if not active:
            return
        if e.boxing and dragged(e.box):
            draw_box(p, e.box, crossing = crosses(e.box))
        self.value_boxes(p, width, height)

    ## Each constraint's glyph beside what it holds, where sketch_glyphs
    ## places them: the selected ones in the accent, those an
    ## over-constraint runs through in the warning color, the one under the
    ## pointer lit.
    func glyphs(self, p: Painter, width: float, height: float) -> unit!:
        let e = self.editor
        let sketch = e.sketch else return
        for g in e.placed_glyphs(width, height):
            let chosen = g.constraint in e.constraint_selection
            let conflicting = g.constraint in e.conflicts
            let lit = g.constraint == e.hover_glyph
            let b = g.box
            p.rounded_rectangle(b, theme.warning() if conflicting else (theme.accent() if chosen else (theme.grey(95.0) if lit else theme.grey(60.0))), 3.0)
            p.text(g.label, b.x + 3.0, b.y + 1.0, theme.text() if chosen or lit or conflicting else theme.text_muted())

    ## The value boxes of a shape being drawn, beside what each measures:
    ## the focused one outlined in the accent (its text lit while the next
    ## key replaces it), locked ones tinted, one that does not read red.
    func value_boxes(self, p: Painter, width: float, height: float) -> unit!:
        let e = self.editor
        let t = e.typing
        if not t.active():
            return
        let shown_unit = units.document_unit(self.w)
        for at in 0..<t.boxes.length:
            let b = t.boxes[at]
            let s = project(self.w, e.frame.at(b.x, b.y), width, height)
            if s[2] < 0.0:
                continue
            let text = sketch_typing.shown(b, shown_unit)
            let box_width = math.max(58.0, float(text.length) * 7.5 + 14.0)
            let r = Rect(s[0] - box_width * 0.5, s[1] - 11.0, box_width, 22.0)
            let focused = at == t.focus
            p.rounded_rectangle(r, theme.surface_raised() if b.locked else theme.surface(), 3.0)
            if b.locked:
                p.rounded_rectangle(r, theme.accent(), 3.0, opacity = 0.22)
            if focused and t.fresh:
                p.rectangle(Rect(r.x + 5.0, r.y + 4.0, float(text.length) * 7.5 + 2.0, 14.0), theme.accent(), opacity = 0.35)
            outline(p, r, theme.warning() if not b.valid else (theme.accent() if focused else theme.border()))
            p.text(text, r.x + 6.0, r.y + 3.0, theme.text() if focused or b.locked else theme.text_muted())

## A rectangle's outline.
func outline(p: Painter, r: Rect, color: Color) -> unit!:
    p.rectangle(Rect(r.x, r.y, r.width, 1.5), color)
    p.rectangle(Rect(r.x, r.y + r.height - 1.5, r.width, 1.5), color)
    p.rectangle(Rect(r.x, r.y, 1.5, r.height), color)
    p.rectangle(Rect(r.x + r.width - 1.5, r.y, 1.5, r.height), color)