Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.8

0.11.8 / src / view.luc

## The 3D viewport: the scene drawn by luce-3d's renderer (faces, wires,
## curves, hulls, normals, the ground grid, point clouds as Gaussian splats
## or dots, fog volumes ray-marched over them), or in Render mode by
## luce-render (render_mode.luc) with the same overlays over its image, the
## node tools over it (viewport_tools.luc), the sketch editor's
## and profile picker's drawings, the marking menus (hold A, S or D) and the
## shading button, the selected CAD feature's handles (feature_handles.luc),
## Pick axis's sketch lines and the right-click menu. Its events go to the
## marking menu, the chrome, the sketch editor, the pickers, the handles
## and the tools before the camera's navigation.
##
## It shows one pane or four (view_panes.luc), each drawn through its own
## view, with its camera menu (camera_menu.luc) and navigation gizmo
## (view_cube.luc) at the top right; among four, each pane keeps only those
## and its shading button, and the rest of the chrome (the levels, the
## tools, snapping, the view buttons) is docked once over the viewport
## (viewport_chrome.luc), its events taken before any pane's. The
## workspace's `view` is the pane being drawn or handled: every tool reads
## it. Events go to the pane under the pointer (a drag stays with the pane
## it began in), which becomes the active one; the active pane is drawn
## last, so what the tools keep from a draw (dimension labels, glyphs) is
## the active pane's. Space tapped shows
## the pane alone or the four again (space_tap.luc); held with F the
## viewport fills the window.
from luce_ui.ui import Widget, Layout, Constraints, Size, Event, Painter
from luce_3d.graphics import GroundGrid, Vector3, Renderer, SplatScene, FogScene, GaussianSplats, FogVolume
from luce_3d import graphics as three
from luce_gpu.gpu import RenderTarget, Rect
from luce_window.input import EventKind, Key, ScrollUnit
from luce_std.wake import Waker
from workspace import Workspace
from viewport_tools import ViewportTools
from splat_select import is_edited_cloud
from viewport_chrome import shading_button, on_shading_button, snap_row_end, outline
from snapping import grid_step
from sketch_view import SketchView
from model_sketch_view import ModelSketchView
from knot_place import KnotPlacer
from trim_regions import TrimMarkers
from align_view import AlignLines
from build_labels import BuildLabels
from stretch_handles import StretchHandles
import sketch_input
from combine_target import CombineTarget
from profile_pick import ProfilePick
from feature_handles import FeatureHandles
from axis_pick import AxisPick
from sketch_shown import SketchShown
from actions import Actions
from marking_menu import MarkingMenu, MarkItem
from render_mode import RenderMode
from camera_menu import CameraMenu
from view_cube import ViewCube, Place
from view_state import front_view, back_view, left_view, right_view, scene_camera
import camera_views
import sketch_camera
import marking_items
import theme
import check_labels
from view_projection import project
import units
import time
from shading_menu import mode_icon
from context_view import is_outside
from viewport_objects import authored_node
import context_display
import modeling_commands
import tool_drag
import component_moves
import placing_commands
import knife_placing
from luce_geocore.geocore import Domain, Mesh, Selection
import tool_prompts
from luce_std import math

pub class SceneViewport: Widget:
    let box: Layout
    let workspace: Workspace
    ## Draws every pane's scene (each through its own camera).
    pub let renderer: Renderer
    pub let tools: ViewportTools
    ## A Sketch node's editor, while one is selected and displayed.
    pub let sketch: SketchView
    ## An Edit CAD model's sketches, shown.
    pub let model_sketches: ModelSketchView
    ## Insert and Remove Knot's isoparm under the pointer, and its click.
    pub let knots: KnotPlacer
    ## Trim's region markers (trim_regions.luc).
    pub let regions: TrimMarkers
    ## Align's rows and isoparm (align_view.luc).
    pub let align_lines: AlignLines
    ## The builders' Boundary Labels (build_labels.luc).
    pub let build_labels: BuildLabels
    ## Stretch's handles on the curve (stretch_handles.luc).
    pub let stretch: StretchHandles
    ## Pick profiles, while an Extrude or Revolve takes them.
    pub let profiles: ProfilePick
    ## Combine's target lit while its tools are picked.
    let combine_target: CombineTarget
    ## The selected CAD feature's handles (arrows, taper and angle rings).
    pub let arrow: FeatureHandles
    ## Pick axis's sketch lines, while a Revolve waits for its axis.
    pub let axes: AxisPick
    ## A shown sketch's profiles and curves picked among the body's faces.
    pub let shown: SketchShown
    ## Hold A (create), S (modify) or D (a sketch's constraints).
    pub let marking: MarkingMenu
    ## Every displayed point cloud, sorted together each view (interleaved
    ## clouds and instances blend in depth order).
    pub let splats: SplatScene
    ## Every displayed fog drawing, marched together each view.
    pub let fog: FogScene
    ## Each pane's Render shading mode's progressive render.
    pub let renders: list[RenderMode]
    ## Each pane's camera menu and navigation gizmo (one open or pressed at
    ## a time).
    pub let cameras: CameraMenu
    pub let cube: ViewCube
    let actions: Actions
    ## A marking menu's node entry: add that node after the selected one.
    pub var on_add: func(str) -> unit!? = none
    var dragging: bool = false
    var navigation_button: int = 0
    var pending_right: bool = false
    var last_x: float = 0.0
    var last_y: float = 0.0
    var mode_press: int = -1
    pub var on_shading: func(bool) -> unit!? = none
    ## The context display button (context_display.luc): when its press
    ## began (-1: none), and what opens its menu (held or not).
    var context_press: int = -1
    pub var on_context_menu: func(bool) -> unit!? = none
    ## A right click: the viewport's menu (viewport_menu.luc) at (x, y) of
    ## the viewport.
    pub var on_menu: func(float, float) -> unit!? = none
    ## Tab: the node menu, at the pointer.
    pub var on_search: func() -> unit!? = none
    ## A press the viewport times began (`waits` says when `due` is to run).
    pub var on_wait: func() -> unit!? = none
    ## Each input the viewport took.
    pub var on_input: func() -> unit!? = none
    ## The viewport drew at a new size (docked elsewhere, the window resized).
    pub var on_resized: func() -> unit!? = none
    var drawn_size: list[float] = []
    ## Draws so far (tests, and the idle probe: none while idle).
    pub var draws: int = 0
    ## The pointer in the pane under it (what the tools and menus place by),
    ## and in the whole viewport.
    pub var pointer_x: float = 100.0
    pub var pointer_y: float = 100.0
    var viewport_x: float = 100.0
    var viewport_y: float = 100.0
    ## The pane a press began in, which keeps its drag (-1: none).
    var captured: int = -1
    ## A camera drag through a scene camera: one undo step for the gesture.
    var moving_camera: bool = false
    ## Whether the viewport takes typed text now (take_text).
    var typing: bool = false
    ## What of the docked chrome is under the pointer: on_dock_eye, a
    ## chrome button (viewport_chrome.luc's) or -1.
    var dock_hover: int = -1

    ## Nanoseconds from `now` until a press the viewport times is due (a
    ## marking menu's family, the shading or context button held), or -1.
    pub func waits(self, now: int) -> int:
        var soon = self.marking.waits(now)
        for pressed in [self.mode_press, self.context_press]:
            if pressed >= 0:
                var left = 350000000 - (now - pressed)
                if left < 0: left = 0
                if soon < 0 or left < soon: soon = left
        return soon

    ## A pane looking through a camera follows its node; a sketch left gives
    ## its pane's view back (as the network changes, and each frame played).
    pub func follow_cameras(self) -> unit!:
        if camera_views.sync(self.workspace) or sketch_camera.follow(self.workspace):
            self.layout().invalidate()

    ## When a press the viewport times is due (`waits`): a marking menu's
    ## family opens, a held shading or context button opens its menu.
    pub func due(self) -> unit!:
        if self.marking.poll(time.now()):
            self.layout().invalidate()
        if self.mode_press >= 0 and time.now() - self.mode_press >= 350000000:
            self.mode_press = -1
            if let open = self.on_shading:
                open(true)
        if self.context_press >= 0 and time.now() - self.context_press >= 350000000:
            self.context_press = -1
            if let open = self.on_context_menu:
                open(true)

    pub func init(self, workspace: Workspace, actions: Actions) -> unit!:
        self.workspace = workspace
        self.tools = ViewportTools(workspace, actions)
        self.sketch = SketchView(workspace)
        self.model_sketches = ModelSketchView(workspace)
        self.knots = KnotPlacer(workspace)
        self.regions = TrimMarkers(workspace)
        self.align_lines = AlignLines(workspace)
        self.build_labels = BuildLabels(workspace)
        self.stretch = StretchHandles(workspace)
        self.profiles = ProfilePick(workspace)
        self.combine_target = CombineTarget(workspace)
        self.arrow = FeatureHandles(workspace)
        self.axes = AxisPick(workspace)
        self.shown = SketchShown(workspace)
        self.marking = MarkingMenu()
        self.splats = SplatScene()
        self.fog = FogScene()
        self.renders = [RenderMode(), RenderMode(), RenderMode(), RenderMode()]
        self.cameras = CameraMenu(workspace)
        self.cube = ViewCube()
        self.actions = actions
        self.tools.chrome.on_reuse = self.reuse_tool
        self.tools.chrome.sketch_selected = self.sketch_selected
        self.renderer = Renderer(true)
        self.tools.picker.renderer = self.renderer
        self.tools.objects.renderer = self.renderer
        self.box = Layout()
        self.box.set_flex()
        self.box.set_interactive(true)
        self.box.set_focusable(true)
        self.box.set_accepts_tab(true)

    pub func layout(self) -> Layout:
        return self.box

    pub func measure(self, available: Constraints) -> Size!:
        return Size(320.0, 240.0)

    ## The active pane's Render mode.
    pub func render_mode(self) -> RenderMode:
        return self.renders[self.workspace.panes.active]

    ## Whether a pane's Render mode is rendering.
    pub func rendering(self) -> bool:
        for render in self.renders:
            if render.running():
                return true
        return false

    ## Wake `waker` when a pane's Render mode has compiled a scene.
    pub func wake_renders_with(self, waker: Waker):
        for render in self.renders:
            render.wake_with(waker)

    ## Stop every pane's Render mode.
    pub func stop_rendering(self):
        for render in self.renders:
            render.stop()

    ## The context display button, in the window: left of the active
    ## pane's shading button, or docked among four panes.
    pub func context_button(self) -> Rect:
        let bounds = self.layout().bounds()
        if self.workspace.panes.four:
            let eye = self.tools.chrome.dock_eye()
            return Rect(bounds.x + eye.x, bounds.y + eye.y, eye.width, eye.height)
        let pane = self.pane_bounds()
        let r = context_display.button(shading_button(pane.width))
        return Rect(pane.x + r.x, pane.y + r.y, r.width, r.height)

    ## The active pane's rectangle, in the window.
    pub func pane_bounds(self) -> Rect:
        let bounds = self.layout().bounds()
        let r = self.workspace.panes.rect_of(self.workspace.panes.active, bounds.width, bounds.height)
        return Rect(bounds.x + r.x, bounds.y + r.y, r.width, r.height)

    ## Every pane shown, each into its own region through its own view, the
    ## active one last; between four, a gap, the active one outlined.
    pub func draw(self, target: RenderTarget) -> unit!:
        self.draws += 1
        let size = target.size()
        if self.drawn_size != [size.width, size.height]:
            self.drawn_size = [size.width, size.height]
            if let resized = self.on_resized:
                resized()
        let painter = Painter(target)
        painter.rectangle(Rect(0.0, 0.0, size.width, size.height), theme.grey(30.0) if self.workspace.panes.four else theme.backdrop())
        painter.close()
        let w = self.workspace
        _ = camera_views.sync(w)
        for (index, r) in w.panes.shown(size.width, size.height):
            if r.width < 8.0 or r.height < 8.0:
                continue
            w.view = w.panes.views[index]
            w.view.aspect = r.width / r.height
            if w.view.fit_model:
                w.view.fit_model = false
                w.frame_model()
            self.draw_pane(target.region(r), index, index == w.panes.active)
        w.view = w.panes.view()
        if w.panes.four:
            let r = w.panes.rect_of(w.panes.active, size.width, size.height)
            let edge = Painter(target)
            outline(edge, r, theme.accent())
            # The docked chrome over the panes, and the context display
            # button with its view buttons.
            self.tools.chrome.draw(edge, size.width, size.height)
            let eye = self.tools.chrome.dock_eye()
            context_display.draw_at(edge, eye, w.display.context_mode, w.network.scope >= 0, self.dock_hover == on_dock_eye)
            edge.close()

    ## Pane `index` into `target`, through the workspace's view (the pane's);
    ## the `active` pane draws what the pointer is doing (boxes, strokes,
    ## the marking menu, value boxes).
    func draw_pane(self, target: RenderTarget, index: int, active: bool) -> unit!:
        let size = target.size()
        let painter = Painter(target)
        painter.rectangle(Rect(0.0, 0.0, size.width, size.height), theme.backdrop())
        painter.close()
        let w = self.workspace
        let renderer = self.renderer
        let render = self.renders[index]
        # Components are shown while editing, prompting, or with a selection.
        let editing = w.editing() or w.prompt != none or w.selected_count() > 0
        let wired = w.view.display_mode in [0, 1, 4]
        renderer.set_flat(w.view.display_mode in [1, 2])
        # Draft (mode 10) measures against its pull direction where zebra's
        # stripes take their axis.
        let draft = w.view.display_mode == 10
        renderer.set_shading(2 if w.view.display_mode == 7 else (3 if w.view.display_mode == 8 else (6 if w.view.display_mode == 9 else (7 if draft else 0))), float(w.display.zebra_stripes), w.display.zebra_duty,
                             self.pull() if draft else self.zebra_axis(), w.display.zebra_planar, w.display.zebra_stripes_only)
        renderer.set_curvature(w.display.curvature_kind, w.display.curvature_range, w.display.curvature_band_low, w.display.curvature_band_high)
        renderer.set_draft(w.display.draft_angle)
        # Selected faces are tinted in the surface pass: one bit per face.
        let accent = theme.accent()
        let tinted = w.selecting() and not w.picking_brep() and w.selection != none and w.on_domain(Domain.face)
        if tinted:
            renderer.set_selected_faces(w.geometry else trap("geometry"), w.selection else trap("selection"), three.Color(accent.red, accent.green, accent.blue), 0.45)
        else:
            renderer.clear_face_selection()
        # Hidden faces (Hide) are left out of the surface, its wires and
        # the pick pass.
        let hidden = w.hidden_faces() if w.selecting() and not w.picking_brep() else none
        if let mesh = w.geometry:
            renderer.set_hidden_faces(mesh, hidden)
        else:
            renderer.clear_hidden_faces()
        # Polygon wires come from each mesh's GPU arrays; Edit mode keeps them
        # on, but for a CAD body, whose B-rep edges are what is picked.
        let polygons = editing and not w.picking_brep()
        let wire_color = theme.grey(90.0) if polygons else (theme.grey(175.0) if w.view.display_mode == 0 else theme.grey(55.0))
        renderer.set_edges(1.0 if wired or polygons else 0.0, wire_color, w.view.display_mode != 0)
        renderer.set_wire_overlay(1.0 if wired or polygons or w.batches.patch_batches.length > 0 else 0.0)
        # Render mode shows luce-render's image once it suits the viewport
        # (render_mode.luc); until then the scene draws as Shaded draws it.
        let rendering = w.view.display_mode == 5
        let rendered = rendering and render.advance(w, target, size.width, size.height)
        if not rendering:
            render.stop()
        if rendered:
            # The rasterized scene lays down the depth the overlays test
            # against; luce-render's image then covers its colors, and the
            # editing wires draw again over the image, alone.
            renderer.set_edges(0.0, wire_color, true)
            renderer.set_wire_overlay(0.0)
            renderer.render(w.scene, w.view.camera, target, fit_aspect = true)
            render.show(target, size.width, size.height)
            if polygons:
                renderer.set_edges(1.0, wire_color, false)
                renderer.render(w.scene, w.view.camera, target, fit_aspect = true)
        else:
            renderer.render(w.scene, w.view.camera, target, fit_aspect = true)
        if wired:
            for batch in w.batches.wire_batches:
                batch.draw(w.view.camera, target, theme.grey(175.0) if w.view.display_mode == 0 else theme.grey(55.0))
        else:
            for batch in w.batches.patch_batches:
                batch.draw(w.view.camera, target, theme.grey(55.0))
        # Curves draw in every mode, over their dimmer control hulls. A sketch
        # being edited draws its own curves (live as they move), no hulls.
        let sketching = self.sketch.editor.active()
        if w.display.hulls_visible and not sketching:
            # A CV drag's hulls as they were, a ghost under the moving ones.
            if w.dragging:
                for batch in w.ghost_hulls:
                    batch.draw(w.view.camera, target, theme.ghost(), 1.0)
            for batch in w.batches.hull_batches:
                batch.draw(w.view.camera, target, theme.grey(110.0))
            self.draw_glyphs(target)
        if not sketching:
            for batch in w.batches.curve_batches:
                batch.draw(w.view.camera, target, theme.grey(225.0), 1.5)
        # Check nodes' lines over the body: edges by how they did, then the
        # combs and the cross quills (cad_check.luc).
        if not sketching:
            for at in 0..<w.batches.check_batches.length:
                let group = at % 5
                w.batches.check_batches[at].draw(w.view.camera, target, theme.check_group(group), 2.5 if group < 3 else 1.25)
        # The rest of the scene's lines around a context: as they are, dim,
        # or not at all.
        if w.display.context_mode != context_display.hidden and not sketching:
            for batch in w.batches.around:
                batch.draw(w.view.camera, target, theme.grey(120.0) if w.display.context_mode == context_display.all else theme.grey(68.0))
        self.sketch.draw_lines(target)
        self.model_sketches.draw(target)
        self.profiles.draw_lines(target)
        self.combine_target.draw(target)
        self.shown.draw_lines(target, size.width, size.height)
        if w.display.normals_visible:
            for batch in w.batches.normal_batches:
                batch.draw(w.view.camera, target, theme.accent())
        if self.workspace.view.grid_visible and not sketching:
            # The ground grid to the horizon (luce-3d's GroundGrid), its
            # lines at the snapping step and every fifth level of it, finer
            # ones fading in as the camera nears; its axes in the accent.
            # An orthographic view of the six shows the grid it looks
            # square at, through the origin, as Maya's do.
            let facing = grid_facing(w.view.looking) if w.view.orthographic else 1
            GroundGrid.draw(w.view.camera, target, -0.008 if facing == 1 else 0.0, grid_step(w.view.distance), theme.grey(58.0), theme.grey(84.0), theme.accent(), w.view.distance * 18.0, facing = facing)
        # Point clouds after the opaque scene, all sorted together back to
        # front: they veil what lies behind them and hide behind what is in
        # front. Fog last of the 3D, every grid in one march: it veils the
        # meshes, lines and grid behind it and ends at those in front. The
        # render draws splats itself, and has no fog.
        if not rendered:
            self.mark_selection()
            self.splats.set_look(w.display.splat_look(w.view.display_mode))
            let (clouds, volumes) = self.styled_around()
            self.splats.draw(clouds, w.view.camera, target)
            self.fog.draw(volumes, w.view.camera, target)
        let overlay = Painter(target)
        # Where we are, centered along the top: the network's path; along
        # the bottom in a pane too narrow for it between the top's buttons.
        # Among four, the docked chrome shows the path once.
        let four = w.panes.four
        if not four:
            let where = self.workspace.network.path()
            let roomy = size.width - float(where.length) * 7.5 > 2.0 * 420.0
            overlay.text(where, (size.width - float(where.length) * 7.5) * 0.5, 14.0 if roomy else size.height - 32.0, theme.text_muted())
        # The grid's step, right of the snapping button (among four, of the
        # docked tools along the left panes).
        let footer = snap_row_end() + 10.0 if not four or index % 2 == 0 else 16.0
        overlay.text(f"Y up  /  grid: {units.length_text(grid_step(w.view.distance), units.document_unit(w))}", footer, size.height - 32.0, theme.text_muted())
        if rendering:
            # What the render is at, in the bottom-right corner.
            let label = render.label()
            overlay.text(label, size.width - float(label.length) * 7.5 - 16.0, size.height - 32.0, theme.text_muted())
        self.tools.draw(overlay, size.width, size.height, active)
        self.knots.draw(overlay)
        self.regions.draw(overlay, size.width, size.height)
        self.align_lines.draw(overlay, size.width, size.height)
        self.build_labels.draw(overlay, size.width, size.height)
        self.stretch.draw(overlay, size.width, size.height)
        self.arrow.draw(overlay, size.width, size.height)
        self.axes.draw(overlay, size.width, size.height)
        self.sketch.draw(overlay, size.width, size.height, active)
        self.shown.draw(overlay, size.width, size.height)
        # Check nodes' edge labels, over the model.
        if not self.sketch.editor.active():
            check_labels.draw(overlay, w.batches.check_labels, func (at: Vector3) -> list[float]!:
                return project(w, at, size.width, size.height))
        if active:
            self.marking.draw(overlay, size.width, size.height)
        # The shading button, left of the view buttons (among four, alone
        # in the corner).
        let shading = shading_button(size.width, four)
        overlay.rounded_rectangle(shading, theme.surface(), 4.0)
        mode_icon(overlay, w.view.display_mode, shading.x + 4.0, 11.0)
        overlay.rectangle(Rect(shading.x + 28.0, 34.0, 3.0, 3.0), theme.accent())
        # The context display button, left of it (docked among four).
        if not four:
            context_display.draw_button(overlay, shading, w.display.context_mode, w.network.scope >= 0, active and context_display.on_button(self.pointer_x, self.pointer_y, shading))
        # Under them (among four, beside the shading button), the camera
        # menu, the navigation gizmo under it; the menu's list over
        # everything.
        self.cameras.draw(overlay, index, w.view, size.width)
        self.cube.draw(overlay, w.view, Place(size.width, size.height, four), active)
        self.cameras.draw_list(overlay, index, w.view, size.width)
        overlay.close()

    ## The scene's Camera and Light glyphs, the rest of the scene's around a
    ## context greyed or left out as its lines are; not the camera the pane
    ## looks through, as Maya hides it there.
    func draw_glyphs(self, target: RenderTarget) -> unit!:
        let w = self.workspace
        let mode = w.display.context_mode
        for at in 0..<w.batches.scenes.length:
            let node = w.batches.scene_nodes[at]
            let around = is_outside(w.network, node)
            if around and mode == context_display.hidden:
                continue
            let scene = w.batches.scenes[at].scene()
            let glyphs = w.batches.glyph_batches(at)
            for index in 0..<glyphs.length:
                if w.view.looking == scene_camera and scene.is_camera(index) and authored_node(w, scene.path(index), "Camera", node) == w.view.camera_node:
                    continue
                let ink = (theme.grey(120.0) if mode == context_display.all else theme.grey(68.0)) if around else theme.grey(110.0)
                glyphs[index].draw(w.view.camera, target, ink)

    ## The point clouds and fog volumes to draw: the rest of the scene's
    ## faded (Greyed) or left out (Hidden) around a context.
    func styled_around(self) -> (list[GaussianSplats], list[FogVolume]):
        let w = self.workspace
        let mode = w.display.context_mode
        let clouds: list[GaussianSplats] = []
        for at in 0..<w.batches.clouds.length:
            let around = at < w.batches.cloud_nodes.length and is_outside(w.network, w.batches.cloud_nodes[at])
            w.batches.clouds[at].set_faded(around and mode == context_display.greyed)
            if not around or mode != context_display.hidden:
                clouds.append(w.batches.clouds[at])
        let volumes: list[FogVolume] = []
        for at in 0..<w.batches.volumes.length:
            let around = at < w.batches.volume_nodes.length and is_outside(w.network, w.batches.volume_nodes[at])
            if not around or mode != context_display.hidden:
                volumes.append(w.batches.volumes[at])
        return (clouds, volumes)

    ## While Edit GSplats is edited, its cloud shows the selected splats
    ## tinted; others show none. Its cloud is the one the edited (displayed)
    ## node drew from the very points the pick mesh shares: same node, same
    ## positions id. Another cloud of the same size, even an earlier version
    ## of this one shown by another node, is left alone.
    pub func mark_selection(self) -> unit!:
        let w = self.workspace
        var mesh: Mesh? = none
        if let kind = w.selection_kind():
            if kind.tints and w.selecting():
                mesh = w.geometry
        for at in 0..<w.batches.clouds.length:
            let cloud = w.batches.clouds[at]
            var marks: Selection? = none
            if let picked = mesh:
                if is_edited_cloud(cloud, w.batches.cloud_nodes, at, w.network.display, picked):
                    if let chosen = w.selection:
                        if chosen.domain() == 0 and chosen.fits(picked):
                            marks = chosen
            cloud.set_marks(marks)

    ## Whether the sketch edited has entities selected (the chrome asks).
    func sketch_selected(self) -> bool:
        return self.sketch.editor.selection.length > 0

    ## The tool column's pick: in a sketch the editor's tool, else the
    ## workspace's.
    func reuse_tool(self, name: str) -> unit!:
        if self.workspace.sketching():
            self.sketch.editor.choose(name)
        elif name != "":
            modeling_commands.choose_tool(self.workspace, name)
        self.layout().invalidate()

    ## A held A, S or D opens its marking menu at the pointer (Create,
    ## Modify; D is a sketch's Constraints, else Select); a tap leaves it
    ## open to click.
    func open_marking(self, event: Event) -> bool!:
        if event.kind != EventKind.key_down or event.repeated or event.meta or event.control or event.alt:
            return false
        if not (event.key in [Key.a, Key.s, Key.d]):
            return false
        let w = self.workspace
        let add = self.on_add else return false
        let editor = self.sketch.editor
        # Entries follow what is selected now.
        self.actions.refresh()
        # A tool's drag keeps its value as a menu opens.
        tool_drag.settle(w)
        var items: list[MarkItem] = []
        var title = "Create"
        if event.key == Key.a:
            items = marking_items.create_items(w, self.actions, add, editor)
        elif event.key == Key.s:
            title = "Modify"
            items = marking_items.modify_items(w, self.actions, add, editor)
        elif w.sketching():
            title = "Constraints"
            items = marking_items.constraint_items(editor)
        else:
            title = "Select"
            items = marking_items.select_items(w, self.actions)
        self.marking.show(title, items, event.key, self.pointer_x, self.pointer_y)
        return true

    ## Esc closes the tool shelf (tool_shelf.luc) when the viewport has
    ## nothing of its own to cancel: no tool placing, prompting or dragging,
    ## no sketch tool under way or sketch selection (Esc clears that
    ## first). Whether it did.
    func shelf_escape(self, event: Event) -> bool!:
        let chrome = self.tools.chrome
        if event.kind != EventKind.key_down or event.key != Key.escape or not chrome.shelf.open or not chrome.shelved():
            return false
        let w = self.workspace
        if w.placing != none or w.prompt != none or self.tools.drag.live() or self.knots.active() or self.regions.active():
            return false
        if w.sketching():
            let e = self.sketch.editor
            if e.tool != "Select" or e.clicks.length > 0 or e.picks.length > 0 or e.boxing or e.selection.length > 0:
                return false
        chrome.toggle_shelf()
        return true

    ## Whether the Knife's stroke is being drawn (its keys come here).
    func knife_drawing(self) -> bool:
        let placing = self.workspace.placing else return false
        return placing.gesture == "knife"

    ## Whether the viewport takes typed text (a shape's value boxes show, a
    ## tool's drag is live, or the Knife draws), changed only when it
    ## changes; Tab stays the viewport's either way.
    func take_text(self, typing: bool):
        if typing == self.typing:
            return
        self.typing = typing
        self.layout().set_text_input(typing, tabs = true)
        self.layout().set_accepts_tab(true)

    ## Draft's pull direction: +X, +Y, +Z, -X, -Y or -Z.
    func pull(self) -> Vector3:
        let axis = self.workspace.display.draft_axis
        let sign = 1.0 if axis < 3 else -1.0
        let at = axis % 3
        return Vector3(sign if at == 0 else 0.0, sign if at == 1 else 0.0, sign if at == 2 else 0.0)

    ## The world axis zebra and isophote stripes run around: X, Y, Z or the view's up.
    func zebra_axis(self) -> Vector3!:
        let axis = self.workspace.display.zebra_axis
        if axis == 3:
            return self.workspace.view.camera.projection(1.0).up
        return Vector3(1.0 if axis == 0 else 0.0, 1.0 if axis == 1 else 0.0, 1.0 if axis == 2 else 0.0)

    ## An event for the pane under the pointer (or the one a drag began in),
    ## in its coordinates and through its view; that pane becomes the active
    ## one, but while a marking menu, the camera menu or a value box holds
    ## the active pane.
    ## An input: routed to the chrome, the panes and their tools; then a
    ## press it began that is timed asks for its turn (`on_wait`), and
    ## `on_input` hears it (the editor's settings follow views and panes).
    pub func event(self, event: Event) -> unit!:
        self.route(event)
        if self.waits(time.now()) >= 0:
            if let asked = self.on_wait:
                asked()
        if let heard = self.on_input:
            heard()

    func route(self, event: Event) -> unit!:
        let bounds = self.layout().bounds()
        let w = self.workspace
        let pointer = event.kind in [EventKind.pointer_moved, EventKind.pointer_down, EventKind.pointer_up, EventKind.scroll, EventKind.magnify]
        if pointer:
            self.viewport_x = event.x
            self.viewport_y = event.y
        # The docked chrome takes its events before the panes, leaving the
        # active pane as it is.
        if self.dock_event(event, bounds.width, bounds.height):
            return
        var index = w.panes.pane_at(self.viewport_x, self.viewport_y, bounds.width, bounds.height)
        if self.captured >= 0:
            index = self.captured
        let held = self.marking.is_open() or self.cameras.open_pane >= 0 or self.sketch.editor.typing.active()
        if index != w.panes.active and not held:
            w.panes.active = index
            self.layout().invalidate()
        index = w.panes.active
        if event.kind == EventKind.pointer_down:
            self.captured = index
        let r = w.panes.rect_of(index, bounds.width, bounds.height)
        var local = event
        local.x = event.x - r.x
        local.y = event.y - r.y
        w.view = w.panes.views[index]
        self.pane_event(local, index, r.width, r.height)
        w.view = w.panes.view()
        if event.kind == EventKind.pointer_up or event.cancelled or event.kind == EventKind.focus_lost:
            self.captured = -1
            if self.moving_camera:
                self.moving_camera = false
                w.commit()

    ## The docked chrome's pointer events over a viewport `width` by
    ## `height` (four panes; none while a press in a pane drags or a menu
    ## is open): hover, a button pressed, the context display button
    ## clicked (the next mode) or held or right-clicked (its menu, as
    ## `due` opens it). Whether the event was the dock's.
    func dock_event(self, event: Event, width: float, height: float) -> bool!:
        let chrome = self.tools.chrome
        if not chrome.docked() or self.captured >= 0 or self.marking.is_open() or self.cameras.open_pane >= 0:
            return false
        if not (event.kind in [EventKind.pointer_moved, EventKind.pointer_down, EventKind.pointer_up]):
            return false
        if event.kind == EventKind.pointer_up and self.context_press >= 0:
            self.context_press = -1
            self.workspace.set_context_mode((self.workspace.display.context_mode + 1) % context_display.names().length)
            self.layout().invalidate()
            return true
        let eye = chrome.dock_eye()
        let on_eye = event.inside and not event.alt and event.x >= eye.x and event.x <= eye.x + eye.width and event.y >= eye.y and event.y <= eye.y + eye.height
        let button = chrome.button_at(event.x, event.y, width, height, dock = true) if event.inside and not event.alt else -1
        if event.kind == EventKind.pointer_moved:
            let hover = on_dock_eye if on_eye else button
            if hover != self.dock_hover or button != chrome.hover_tool:
                self.layout().invalidate()
            self.dock_hover = hover
            chrome.hover_tool = button
            return hover >= 0
        if event.kind == EventKind.pointer_up:
            return on_eye or button >= 0
        if on_eye:
            if event.button == 1:
                if let open = self.on_context_menu:
                    open(false)
            else:
                self.context_press = time.now()
            return true
        # A click away from the snapping options closes them.
        if chrome.snaps_open and button < 400:
            chrome.snaps_open = false
            self.layout().invalidate()
        if button >= 0 and event.button == 0:
            chrome.press(button)
            self.layout().invalidate()
            return true
        return false

    ## Space: tapped over a pane, that pane alone or the four again; the
    ## press is spent by any other key or button (Space with F fills the
    ## window: Workspace.frame_or_fill). Whether the event was Space's.
    func space(self, event: Event, index: int) -> bool!:
        let tap = self.workspace.panes.space
        if event.kind == EventKind.key_down and event.key == Key.space:
            tap.press(time.now())
            return true
        if event.kind == EventKind.key_up and event.key == Key.space:
            if tap.release(time.now()):
                self.workspace.toggle_pane(index)
                self.layout().invalidate()
            return true
        if event.kind == EventKind.key_down or event.kind == EventKind.pointer_down:
            tap.other()
        if event.kind == EventKind.focus_lost:
            tap.cancel()
        return false

    ## The view moved by navigation (`how`: 0 orbit, 1 zoom, 2 pan) by
    ## (`dx`, `dy`) in a pane `height` tall; a camera looked through moves
    ## with it.
    func navigate(self, how: int, dx: float, dy: float, height: float) -> unit!:
        let view = self.workspace.view
        # Through a camera, a drag moves it as one undo step (event ends it).
        if view.looking == scene_camera and self.captured >= 0 and not self.moving_camera:
            self.workspace.begin("Move camera")
            self.moving_camera = true
        if how == 0:
            view.orbit(dx, dy)
        elif how == 1:
            view.zoom(dx)
        else:
            view.pan(dx, dy, height)
        camera_views.follow_view(self.workspace, view)

    ## Pane `index`'s event, (x, y) in it, the pane `width` by `height`.
    func pane_event(self, event: Event, index: int, width: float, height: float) -> unit!:
        let bounds = Rect(0.0, 0.0, width, height)
        self.workspace.viewport_focus = self.layout().is_focused()
        # The arrows nudge picked CVs by the step size (Alias's), only while
        # a CV move is on and the viewport has the keyboard: left and right
        # along the gizmo's first axis, up and down its second, with Shift
        # its third.
        if event.kind == EventKind.key_down and event.key in [Key.left, Key.right, Key.up, Key.down] and component_moves.nudges(self.workspace) and self.workspace.viewport_focus:
            let sign = 1.0 if event.key in [Key.right, Key.up] else -1.0
            let axis = 0 if event.key in [Key.left, Key.right] else (2 if event.shift else 1)
            component_moves.nudge(self.workspace, axis, sign)
            self.layout().invalidate()
            return
        if event.kind == EventKind.pointer_moved or event.kind == EventKind.pointer_down:
            self.pointer_x = event.x
            self.pointer_y = event.y
            # A tool that snaps marks where this move landed afresh.
            self.workspace.snap_mark = none
        # A shape's value boxes take typing, Tab included, before the menus
        # and tools; the viewport takes text while they show.
        if event.kind in [EventKind.key_down, EventKind.text_input] and (sketch_input.typing_event(self.sketch.editor, event) or self.tools.drag.typing(event) or self.tools.creating.typing(event) or self.tools.pen.key(event) or self.tools.sculpt.key(event) or knife_placing.key(self.workspace, event)):
            self.layout().invalidate()
            return
        # So does a tool's live drag (its value box, its axis keys), and the
        # Knife's stroke (its C, Z and Backspace).
        self.take_text(self.sketch.editor.typing.active() or self.tools.drag.live() or self.tools.creating.live() or self.tools.pen.active() or self.knife_drawing())
        if self.space(event, index):
            return
        if event.kind == EventKind.key_down and event.key == Key.tab:
            if let search = self.on_search:
                search()
            return
        if self.marking.event(event, bounds.width, bounds.height):
            self.layout().invalidate()
            return
        if self.open_marking(event):
            self.layout().invalidate()
            return
        if self.shelf_escape(event):
            self.layout().invalidate()
            return
        # The camera menu and the navigation gizmo keep their pointer events.
        if not event.alt and self.cameras.event(index, self.workspace.view, event, width):
            self.layout().invalidate()
            return
        let four = self.workspace.panes.four
        if not event.alt and self.cube.event(self.workspace.view, event, Place(width, height, four), func (dx: float, dy: float) -> unit!: self.navigate(0, dx, dy, height)):
            self.layout().invalidate()
            return
        if event.cancelled or event.kind == EventKind.focus_lost:
            self.mode_press = -1
            self.context_press = -1
        # Shift or Cmd held during a tool prompt peeks at its input.
        if event.kind in [EventKind.modifiers_changed, EventKind.key_down, EventKind.key_up, EventKind.pointer_moved, EventKind.pointer_down]:
            tool_prompts.set_peek(self.workspace, event.shift or event.meta)
        elif event.kind == EventKind.focus_lost:
            tool_prompts.set_peek(self.workspace, false)
        if event.kind == EventKind.pointer_down and event.inside and not event.alt and on_shading_button(event.x, event.y, bounds.width, four):
            if event.button == 1:
                if let open = self.on_shading:
                    open(false)
            else:
                self.mode_press = time.now()
            return
        if event.kind == EventKind.pointer_up and self.mode_press >= 0:
            self.mode_press = -1
            if let open = self.on_shading:
                open(false)
            return
        # The context display button: a click steps the mode, a held press
        # or a right click opens its menu.
        if event.kind == EventKind.pointer_down and event.inside and not event.alt and not four and context_display.on_button(event.x, event.y, shading_button(bounds.width)):
            if event.button == 1:
                if let open = self.on_context_menu:
                    open(false)
            else:
                self.context_press = time.now()
            return
        if event.kind == EventKind.pointer_up and self.context_press >= 0:
            self.context_press = -1
            self.workspace.set_context_mode((self.workspace.display.context_mode + 1) % context_display.names().length)
            self.layout().invalidate()
            return
        if event.cancelled:
            self.dragging = false
            self.pending_right = false
        # A click away from the snapping options closes them.
        if event.kind == EventKind.pointer_down and self.tools.chrome.snaps_open and self.tools.chrome.button_at(event.x, event.y, bounds.width, bounds.height) < 400:
            self.tools.chrome.snaps_open = false
            self.layout().invalidate()
        # The viewport's buttons keep their clicks from every tool.
        if event.kind in [EventKind.pointer_down, EventKind.pointer_moved] and event.inside and not event.alt and self.tools.chrome.button_at(event.x, event.y, bounds.width, bounds.height) >= 0:
            _ = self.tools.event(event, bounds.width, bounds.height)
            self.layout().invalidate()
            return
        # An Edit CAD model's sketch under the pointer is lit (the
        # right-click menu offers to edit it).
        if event.kind == EventKind.pointer_moved and event.inside:
            if self.model_sketches.hover(event.x, event.y, bounds.width, bounds.height):
                self.layout().invalidate()
        # Insert and Remove Knot: the isoparm under the pointer, placed by a
        # click (Alias's); Esc lets the clicks select again.
        if self.knots.active():
            if event.kind == EventKind.pointer_moved and event.inside and self.knots.hover(event.x, event.y, bounds.width, bounds.height):
                self.layout().invalidate()
            if event.kind == EventKind.pointer_down and event.inside and event.button == 0 and not event.alt and self.knots.click(event.x, event.y, bounds.width, bounds.height):
                self.layout().invalidate()
                return
            if event.kind == EventKind.key_down and event.key == Key.escape and self.knots.dismiss():
                self.layout().invalidate()
                return
        # Stretch's handles: dragged, or added and taken away by Shift-click.
        if self.stretch.active() and self.stretch.event(event, bounds.width, bounds.height):
            self.layout().invalidate()
            if event.kind != EventKind.pointer_moved or self.stretch.dragging:
                return
        # Trim's region markers: a click picks a region or lets it go
        # (Alias's); Esc lets the clicks select again.
        if self.regions.active():
            if event.kind == EventKind.pointer_moved and event.inside and self.regions.hover(event.x, event.y, bounds.width, bounds.height):
                self.layout().invalidate()
            if event.kind == EventKind.pointer_down and event.inside and event.button == 0 and not event.alt and self.regions.click(event.x, event.y, bounds.width, bounds.height):
                self.layout().invalidate()
                return
            if event.kind == EventKind.key_down and event.key == Key.escape and self.regions.dismiss():
                self.layout().invalidate()
                return
        # The builders' Boundary Labels: a click cycles one's continuity.
        if self.build_labels.active():
            if event.kind == EventKind.pointer_moved and event.inside and self.build_labels.hover(event.x, event.y, bounds.width, bounds.height):
                self.layout().invalidate()
            if event.kind == EventKind.pointer_down and event.inside and event.button == 0 and not event.alt and self.build_labels.click(event.x, event.y, bounds.width, bounds.height):
                self.layout().invalidate()
                return
        # The sketch editor, then Pick profiles, Pick axis's lines, the
        # feature's handles and the shown sketch's profiles, before other
        # tools.
        if sketch_input.handle(self.sketch.editor, event, bounds.width, bounds.height) or self.profiles.event(event, bounds.width, bounds.height) or self.axes.event(event, bounds.width, bounds.height) or self.arrow.event(event, bounds.width, bounds.height) or self.shown.event(event, bounds.width, bounds.height):
            self.layout().invalidate()
            return
        if self.tools.event(event, bounds.width, bounds.height):
            self.layout().invalidate()
            return
        # luce-ui currently drops modifiers on its special right-press route.
        # Arm only; the first move must confirm Alt before any camera change.
        if event.kind == EventKind.pointer_down and event.inside and event.button == 1:
            self.pending_right = true
            self.last_x = event.x
            self.last_y = event.y
        # A right click let go where it was pressed opens the viewport's menu
        # (on_menu); a press moved with Alt zooms instead.
        if event.kind == EventKind.pointer_moved and self.pending_right:
            if event.alt:
                self.pending_right = false
                self.dragging = true
                self.navigation_button = 1
            elif math.hypot(event.x - self.last_x, event.y - self.last_y) > 4.0:
                self.pending_right = false
        if event.kind == EventKind.pointer_up and event.button == 1 and self.pending_right and not self.dragging:
            self.pending_right = false
            if let open = self.on_menu:
                open(event.x, event.y)
            self.layout().invalidate()
            return
        if event.kind == EventKind.pointer_down and event.inside and event.alt and (event.button == 0 or event.button == 1 or event.button == 2):
            self.dragging = true
            self.navigation_button = event.button
            self.last_x = event.x
            self.last_y = event.y
        elif event.kind == EventKind.pointer_moved and self.dragging:
            let dx = event.x - self.last_x
            let dy = event.y - self.last_y
            if self.navigation_button == 2:
                self.navigate(2, dx, dy, height)
            elif self.navigation_button == 1:
                self.navigate(1, (dx - dy) * 0.1, 0.0, height)
            else:
                self.navigate(0, dx, dy, height)
            self.last_x = event.x
            self.last_y = event.y
        elif event.kind == EventKind.pointer_up or event.kind == EventKind.focus_lost or event.kind == EventKind.overflow:
            self.dragging = false
            self.pending_right = false
        elif event.kind == EventKind.scroll and event.scroll_unit == ScrollUnit.points:
            # A touchpad's two fingers: orbit, or pan with Shift; a pinch zooms.
            if event.shift:
                self.navigate(2, event.scroll_x, event.scroll_y, height)
            else:
                self.navigate(0, event.scroll_x, event.scroll_y, height)
        elif event.kind == EventKind.scroll:
            # A mouse wheel's lines zoom.
            self.navigate(1, event.scroll_y, 0.0, height)
        elif event.kind == EventKind.magnify:
            self.navigate(1, event.scroll_y * 12.0, 0.0, height)
        elif event.kind == EventKind.key_down:
            if event.key == Key.escape:
                self.dragging = false
                if self.workspace.placing != none: self.workspace.cancel_placing()
                elif self.workspace.prompt != none: self.workspace.cancel_prompt()
            elif event.key == Key.enter and self.workspace.placing != none:
                placing_commands.finish_placing(self.workspace)
            elif event.key == Key.enter and self.workspace.prompt != none:
                tool_prompts.accept_prompt(self.workspace)
        # Hover over the same component changes nothing on screen.
        if event.kind == EventKind.pointer_moved and not self.dragging and not self.tools.hover_changed:
            return
        self.layout().invalidate()

## The world axis the grid of orthographic view `looking` faces: Front and
## Back see the XY plane, Left and Right the YZ plane, the rest the ground.
func grid_facing(looking: int) -> int:
    if looking == front_view or looking == back_view:
        return 2
    if looking == left_view or looking == right_view:
        return 0
    return 1

## dock_hover's answer for the docked context display button.
let on_dock_eye = 1000