dymokomi/luced-3d
Source of release 0.11.8
## The editor's state: the node network and its undo history, the
## displayed geometry and its component selection, the selection level, and
## the transactions every change goes through (perform, begin/commit,
## undo/redo). It cooks the graph (rebuild), synchronously or on the worker
## (poll_compute), and publishes the scene. It holds the viewport's panes
## (view_panes.luc: each pane's camera and shading), the display settings
## they share (display_settings.luc) and the viewport's line batches
## (viewport_batches.luc). Commands on it live beside it: node_commands,
## selection_commands, modeling_commands and placing_commands.
import sketch_node
import edit_cad_sketches
from stamps import stamp_graph
import edit_held
from held_store import HeldStore
from luce_geocore.geocore import Mesh, Selection, Domain
from luce_3d.graphics import WireBatch, Scene, Group, Vector3, AmbientLight, DirectionalLight, SurfaceHits, SurfaceHit, ObjectNode
from place_prompt import PlacePrompt
from tool_prompt import ToolPrompt
from tool_prompt import domain as tool_prompt_domain
from network import Network
from node import Node
from tools import transform_tools
import tool_registry
from select_run import SelectRun
from drag_session import DragSession
from snapping import SnapSettings, SnapMark
from history import History, Snapshot
from scene_projection import append_bounds, display_mesh
from local_cook import cook_outputs
from context_view import view_items, is_outside
import context_display
from compute_session import ComputeSession
from display_publisher import DisplayPublisher
from node_evaluation import SourceCache
from view_state import ViewState
from view_panes import ViewPanes
from display_settings import DisplaySettings
from viewport_batches import ViewportBatches
from edit_kinds import is_edit, context_kind, EditKinds
from geometry_data import GeometryData
from edit_types import EditKind, EditLevel, smart_level, face_level, object_level, point_level, curve_level, soft_radius_slot, falloff_slot, symmetry_slot
import edit_mesh
import node_catalog
from luce_cad.cad_edits import CadEdits
from slice_view import Slicer
from luce_std import math
pub class Workspace:
pub var network: Network
pub let history: History
pub let scene: Scene
let objects: Group
## The viewport's panes, and the view of the one acted on: the active
## pane's, or while the viewport draws or handles a pane, that pane's
## (everything drawing, picking or moving the camera reads this one).
pub let panes: ViewPanes
pub var view: ViewState
## What every pane shows alike.
pub let display: DisplaySettings
pub let batches: ViewportBatches
pub var geometry: Mesh? = none
## Components of `geometry` (a luce-geocore Selection), on any displayed
## node; none when nothing is selected.
pub var selection: Selection? = none
## Faces of `geometry` hidden from the viewport (Hide): not drawn, not
## picked, never selected; none when nothing is hidden.
pub var hidden: Selection? = none
## The pick geometry the selection was last checked on.
var selected_on: Mesh? = none
## The selection level (edit_types: Object, Point, Edge, Face, Smart),
## an index into levels() but for Smart. Node selection and display are
## independent.
pub var component_mode: int = face_level
## Under Smart, the level its last pick was on (the selection's).
pub var smart_pick: int = face_level
## What a sketch's Select picks, on the same buttons: Point (points),
## Edge (lines and curves), Face (shapes: curves joined end to end) or
## Smart (whatever is nearest).
pub var sketch_level: int = smart_level
## The sketch editor's tool, and the last one before Select (the tool
## column's bottom slot shows it).
pub var sketch_tool: str = "Select"
## What positions snap to, and what the pointer last snapped to
## (snapping.luc).
pub let snaps: SnapSettings
pub var snap_mark: SnapMark? = none
## The object placing lands on alone (a retopology's scan: -1 none),
## picked with Snap Target (retopology.luc); an Edit Mesh edited then
## reads it as its Reference input.
pub var snap_target: int = -1
## Whether the next viewport click picks the snap target.
pub var picking_target: bool = false
pub var last_sketch_tool: str = ""
## The registry tool run last (its label) and its numbers, which Repeat
## runs again on a new selection; a node it made, whose values then win
## (-1: it was a step, whose tool bar keeps the numbers here).
pub var last_tool: str = ""
## The Select tool run last, while its rows stay on the tool bar.
pub var last_select: SelectRun? = none
pub var last_tool_numbers: list[float]
pub var last_tool_node: int = -1
## The edited sketch's picked profiles (their keys, sketch_profiles.luc),
## what Extrude takes.
pub var sketch_profiles: list[str]
## A shown sketch's curves picked outside its editor (sketch_shown.luc),
## and the Sketch node its picks (and sketch_profiles there) are on.
pub var sketch_picks: list[int]
pub var sketch_picked_on: int = -1
## While a Sketch is edited, the node displayed before it was (-1:
## none): Finish Sketch shows it again, as Fusion rolls forward.
pub var sketch_return: int = -1
## While a sketch is edited, the view its pane had before, and which
## pane (sketch_camera.luc); empty when none is kept.
pub var sketch_view: list[float]
pub var sketch_pane: int = 0
## The sketch of an Edit CAD node edited in the viewport (its name, ""
## none) and that node: Fusion's sketches in direct modeling, objects of
## the model (edit_cad_sketches.luc), edited by the same editor.
pub var edit_sketch: str = ""
pub var edit_sketch_node: int = -1
## The Edit CAD model's shown sketch under the pointer ("" none).
pub var hovered_sketch: str = ""
## Whether the viewport has the keyboard (its arrow keys then nudge
## picked CVs rather than step the timeline: component_moves.nudges).
pub var viewport_focus: bool = false
## The Project tool's cast of the edited sketch's input body
## (sketch_node.shadows_text), made by the cook (off the UI thread with
## the worker), and the Sketch stamp it is for.
pub var shadows: str = ""
pub var shadows_stamp: int = 0
## Slice: while a sketch is edited, the body in front of its plane is
## cut away in the viewport (display only), its cap (slice_view.luc)
## made by the cook, and the Sketch stamp it is for; `slicer` makes them
## without the worker.
pub var slice: bool = false
pub var section: str = ""
pub var section_stamp: int = 0
pub let slicer: Slicer
## A feature just made from the viewport wants its value typed: the
## panels open the value box by its first handle (feature_handles.luc)
## once its cook has placed it.
pub var ask_value: bool = false
## Edit kinds by node kind, made once each (they hold closures).
let edit_kinds: EditKinds
let mesh_levels: list[EditLevel]
## A tool waiting for its components (Houdini's tool → select), or
## Reselect of a node's group.
pub var prompt: ToolPrompt? = none
## A face or corners being placed in the viewport (place_prompt.luc).
pub var placing: PlacePrompt? = none
## What the next result of the displayed node selects (sync_selection):
## the displayed verb's output selection (Extrude's front faces), at
## level `pending_level` for a create step's piece (-1: the output's
## own); or group `pending_group` of Group Type `pending_type` (Reselect).
pub var adopt_output: bool = false
pub var pending_level: int = -1
pub var pending_group: str = ""
pub var pending_type: int = 0
pub var edit_tool: str = "Select"
## The tool just run whose row a drag in the viewport sets (tool_drag.luc).
pub var drag_session: DragSession? = none
## How Edit GSplats selects (splat_select.luc): the shape a drag makes
## (0 box, 1 lasso, 2 brush), the brush's radius in points, the
## footprint alpha a splat is picked at, and whether only the splats
## seen are picked (V), not every one through the depth.
pub var splat_shape: int = 0
pub var splat_brush: float = 24.0
## What the undo history may keep of Edit nodes' held results beyond
## the graph's own, in bytes (bound_history): 2 GiB.
pub var held_budget: int = 2147483648
## What a drag's last frame showed of each Edit node holding its result
## (edit_held.settle makes the next frame over it); empty between drags.
pub var drag_shown: map[int, GeometryData] = {}
## What keep_held last walked for (its key), and how many times the
## graph was replaced (undo, a project opened).
var kept_key: int = 0
var graph_swaps: int = 0
## The held keys the undo history reaches, as of its version.
var history_keys: list[int] = []
var history_keys_version: int = -1
## The sculpt brush's radius on screen, in points (sculpt_gesture.luc).
pub var sculpt_radius: float = 50.0
pub var splat_footprint: float = 0.1
pub var splat_visible: bool = false
## Boxes at component levels select through the depth (V): hidden and
## back-facing points, edges and faces too, not only what shows.
pub var through_depth: bool = false
## A gizmo drag's frames are being previewed (preview_move and
## preview_parameters); commit cooks the released result in full.
pub var dragging: bool = false
## A CV drag's frame (Edit CAD's CV move modes), fixed when it starts,
## and the control hulls as they were then, drawn as a ghost (Alias's
## Proxy Display).
pub var cv_frame: list[Vector3]? = none
pub var ghost_hulls: list[WireBatch] = []
## Shift or Cmd is held during a tool prompt: its input shows instead of
## the tool's result, to see what is picked (as Fusion 360 does).
pub var peeking: bool = false
## Moves on with each change the panels show (`touch`).
pub var revision: int = 0
## Told of each change (`touch`): the editor wakes its loop once for
## however many come in a turn, and the panels catch up then.
pub var on_change: (func() -> unit)? = none
pub var notice: str = ""
## The open transaction: the state before it, its label, and whether it
## changed anything (only then does it become an undo step).
pub var pending: Snapshot? = none
var pending_label: str = ""
pub var pending_changed: bool = false
pub var compute: ComputeSession? = none
pub let publisher: DisplayPublisher
## Without the worker: the meshes on screen and their nodes.
var local_nodes: list[int]
var local_meshes: list[Mesh]
var local_around: list[Mesh]
var local_outside: list[Mesh]
var local_outside_nodes: list[int]
## The scope the worker's lines were split for (context_view.luc).
var batches_scope: int = -2
let sources: SourceCache
var project_epoch: int = 0
pub func init(self) -> unit!:
self.slicer = Slicer()
self.snaps = SnapSettings()
self.sketch_profiles = []
self.sketch_picks = []
self.sketch_view = []
self.last_tool_numbers = []
self.panes = ViewPanes()
self.view = self.panes.view()
self.display = DisplaySettings()
self.batches = ViewportBatches()
self.sources = SourceCache()
self.edit_kinds = EditKinds()
self.mesh_levels = edit_mesh.levels()
self.network = Network()
self.network.sources = self.sources
self.history = History()
self.local_outside = []
self.local_outside_nodes = []
self.scene = Scene()
self.objects = Group()
self.publisher = DisplayPublisher(self.objects)
self.local_nodes = []
self.local_meshes = []
self.local_around = []
self.scene.add(self.objects)
self.scene.add(AmbientLight(intensity = 0.35))
self.scene.add(DirectionalLight(direction = Vector3(3.0, 5.0, 2.0), intensity = 0.85))
self.rebuild()
## Install a validated document. Old worker generations cannot overwrite it;
## the source epoch also prevents reusing stale imports with recycled IDs.
pub func replace_network(self, graph: Network) -> unit!:
self.pending = none
self.pending_changed = false
for view in self.panes.views:
view.pending_frame = 0
for node in self.network.nodes:
if node.source_revision > self.project_epoch: self.project_epoch = node.source_revision
self.project_epoch += 1
for node in graph.nodes:
node.source_revision = self.project_epoch
self.network = graph
self.graph_swaps += 1
self.network.background = self.compute != none
self.network.sources = self.sources
self.history.changes.clear()
self.history.version += 1
self.history.cursor = 0
self.selection = none
self.prompt = none
self.component_mode = face_level
self.smart_pick = face_level
self.notice = ""
self.rebuild()
## F: frame selected components while editing, else the displayed
## scene, including Camera/Light glyphs so their gizmos can be reached.
pub func frame_cube(self) -> unit!:
if self.selected_count() > 0:
let mesh = self.geometry else return
let chosen = self.selection else return
# The selection's box, in Base.
let box = chosen.bounds(mesh)
let bounds = mesh.bounds()
self.frame_points([box.minimum, box.maximum], bounds.maximum.subtract(bounds.minimum).length() * 0.01)
return
self.frame_scene(true)
## Frame the displayed model alone, centered and whole: the orthographic
## panes as the four show and as a project opens (Camera and Light
## glyphs count only when nothing else is shown).
pub func frame_model(self) -> unit!:
self.frame_scene(false)
## Frame every pane as F frames the one under the pointer.
pub func frame_every_pane(self) -> unit!:
let acting = self.view
for view in self.panes.views:
self.view = view
self.frame_cube()
self.view = acting
## Frame the displayed scene, its Camera/Light glyphs too when
## `glyphs`; while the worker cooks, once it is done (the view's
## pending_frame).
func frame_scene(self, glyphs: bool) -> unit!:
let points: list[Vector3] = []
if let session = self.compute:
if session.busy:
self.view.ask_frame(1 if glyphs else 2)
return
for point in self.publisher.bounds:
points.append(point)
# Fog volumes and point clouds frame by their boxes, with the worker
# or without.
for volume in self.batches.volumes:
let box = volume.bounds()
points.append(box.minimum)
points.append(box.maximum)
for cloud in self.batches.clouds:
let box = cloud.bounds()
points.append(box.minimum)
points.append(box.maximum)
# Curves frame by their drawn lines, with the worker or without.
for batch in self.batches.curve_batches:
if batch.count() > 0:
let box = batch.bounds()
points.append(box.minimum)
points.append(box.maximum)
# The context frames; the rest of the scene only when there is none.
let items = view_items(self.network)
var context = false
for item in items:
context = context or not item.outside
for item in items:
if self.compute != none or (item.outside and context):
continue
let data = self.network.evaluate_data(item.node.id) catch failure:
continue
append_bounds(data, item.matrix, points)
if glyphs or points.length == 0:
for at in 0..<self.batches.scenes.length:
for helper in self.batches.helpers(at):
if self.display.hulls_visible and helper.count() > 0:
let box = helper.bounds()
points.append(box.minimum)
points.append(box.maximum)
# Even with helpers hidden, a selected Camera/Light has a movable origin.
if let node = self.selected():
if node.kind in ["Camera", "Light"]:
points.append(Vector3(node.values[1], node.values[2], node.values[3]))
self.frame_points(points)
## Frame `points`, from at least `least` away.
func frame_points(self, points: list[Vector3], least: float = 0.001) -> unit!:
self.view.frame(points, least)
self.touch()
## F: frame, or with Space held over the viewport, make the viewport
## fill the window (or give the panels back).
pub func frame_or_fill(self) -> unit!:
if self.panes.space.held:
self.panes.space.other()
self.toggle_full_screen()
return
self.frame_cube()
## The viewport filling the window, or the panels back (the panels apply
## it).
pub func toggle_full_screen(self) -> unit!:
self.panes.full_screen = not self.panes.full_screen
self.touch()
## The active pane alone, or the four panes.
pub func toggle_four(self) -> unit!:
self.toggle_pane(self.panes.active)
## Pane `index` alone, or the four again: their orthographic views
## framed on the model as they appear.
pub func toggle_pane(self, index: int) -> unit!:
self.panes.toggle(index)
if self.panes.four:
self.panes.fit_orthographic()
self.touch()
## The docked Grid button among four panes: every pane's grid on, or off
## when one shows.
pub func toggle_every_grid(self) -> unit!:
var shown = false
for view in self.panes.views:
shown = shown or view.grid_visible
for view in self.panes.views:
view.grid_visible = not shown
self.touch()
pub func reset_view(self) -> unit!:
self.view.yaw = 0.7
self.view.pitch = 0.5
self.frame_cube()
## Normal guides are made on the worker only while they are shown.
pub func toggle_normals(self) -> unit!:
self.display.normals_visible = not self.display.normals_visible
self.touch()
if self.compute != none and self.display.normals_visible:
self.rebuild()
pub func toggle_hulls(self) -> unit!:
self.display.hulls_visible = not self.display.hulls_visible
self.touch()
## Show lengths in `name` ("mm" or "in"): the document's unit, kept with
## it and undone like any change; lengths themselves stay as they are.
pub func set_units(self, name: str) -> unit!:
if self.network.units == name or not (name in ["mm", "in"]):
return
self.perform("Units", func () -> unit!:
self.network.units = name)
pub func toggle_grid(self) -> unit!:
self.view.grid_visible = not self.view.grid_visible
self.touch()
## CAD bodies are meshed again at the new quality.
pub func set_cad_quality(self, divisions: int) -> unit!:
if divisions == self.display.cad_quality:
return
self.display.cad_quality = divisions
self.network.cad_quality = divisions
self.touch()
self.rebuild()
pub func set_display_mode(self, mode: int) -> unit!:
if self.view.set_display_mode(mode):
self.touch()
## The meshes on screen (world space) and the node each came from.
## The meshes on screen the viewport picks on, and the node each came
## from: the context's, never the rest of the scene around it.
pub func on_screen(self) -> (list[int], list[Mesh]):
if self.compute == none:
return (self.local_nodes, self.local_meshes)
let nodes: list[int] = []
let meshes: list[Mesh] = []
for at in 0..<self.publisher.nodes.length:
if not is_outside(self.network, self.publisher.nodes[at]):
nodes.append(self.publisher.nodes[at])
meshes.append(self.publisher.meshes[at])
return (nodes, meshes)
## The nodes drawn as the rest of the scene around the context.
func outside_nodes(self) -> list[int]:
let result: list[int] = []
for node in self.network.nodes:
if is_outside(self.network, node.id):
result.append(node.id)
return result
## Draw the rest of the scene around a context as `mode` says (all,
## greyed, hidden: context_display.luc). A view setting: nothing recooks.
pub func set_context_mode(self, mode: int) -> unit!:
if mode < context_display.all or mode > context_display.hidden or mode == self.display.context_mode:
return
self.display.context_mode = mode
if self.compute != none:
self.publisher.restyle(self.network, mode)
else:
self.rebuild()
self.touch()
## Every mesh drawn solid, the context's and the rest of the scene's:
## what hides what lies behind it (Visible only).
pub func drawn(self) -> list[Mesh]:
let (_, meshes) = self.on_screen()
let result = meshes.copy()
if self.compute == none:
for mesh in self.local_around: result.append(mesh)
return result
# Greyed or hidden, the rest of the scene hides nothing.
if self.display.context_mode != context_display.all:
return result
for at in 0..<self.publisher.nodes.length:
if is_outside(self.network, self.publisher.nodes[at]):
result.append(self.publisher.meshes[at])
return result
pub func selected(self) -> Node?:
return self.network.find(self.network.selected)
## At the Object level, unless an Edit node is displayed (its Object
## level picks pieces) or a tool waits for components, the viewport picks
## objects: the displayed nodes.
pub func picking_objects(self) -> bool:
if self.component_mode != 0 or self.prompt != none or self.placing != none:
return false
if self.selection_kind() == none: return true
let node = self.network.find(self.network.display) else return true
return not (node.enabled and is_edit(node.kind))
## Components can be picked whenever the viewport shows a node's mesh.
pub func selecting(self) -> bool:
return self.geometry != none and self.selection_kind() != none and not self.picking_objects()
## The Edit kind of node kind `name` (kept once made), or none.
pub func kind_of(self, name: str) -> EditKind?:
return self.edit_kinds.of(name)
## The selected node's Edit kind, when it is an enabled Edit node.
pub func active_kind(self) -> EditKind?:
let node = self.selected() else return none
if not node.enabled:
return none
return self.kind_of(node.kind)
## Selection is defined by the authoring context, even without an Edit node.
pub func selection_kind(self) -> EditKind?:
return self.kind_of(context_kind(self.network.context()))
## Scene, volume and material contexts expose only object selection.
pub func levels(self) -> list[EditLevel]:
if let kind = self.selection_kind():
return kind.levels
return [self.mesh_levels[0]]
pub func level(self) -> EditLevel:
return self.levels()[self.level_index()]
## The level picked on: the chosen one, or under Smart its last pick's.
pub func level_index(self) -> int:
let forced = self.prompt_level()
if forced >= 0:
return forced
let at = self.smart_pick if self.component_mode == smart_level else self.component_mode
let all = self.levels()
return at if at < all.length and all[at].available else 0
## The level a waiting prompt picks on, whatever level is chosen (its
## selection filter: tool_prompt.domain); -1 without one.
pub func prompt_level(self) -> int:
let prompt = self.prompt else return -1
let domain = tool_prompt_domain(prompt)
if domain == -2:
return object_level
return self.level_of(domain) if domain >= 0 else -1
## Whether picks go by Smart's rules: Smart chosen, and no prompt
## filtering what is picked.
pub func picking_smart(self) -> bool:
return self.component_mode == smart_level and self.prompt_level() < 0
## The levels Smart picks among (none: it is not offered).
pub func smart_levels(self) -> list[int]:
let kind = self.selection_kind() else return []
return kind.smart
## Whether level `index` (Smart too) can be chosen.
pub func level_available(self, index: int) -> bool:
if index == smart_level:
return self.smart_levels().length > 0
let all = self.levels()
return index >= 0 and index < all.length and all[index].available
## The compact switcher order, retaining stable numeric shortcuts.
pub func shown_levels(self) -> list[int]:
if self.sketching(): return [1, 2, 3, 4]
let result: list[int] = []
for index in [0, 1, 2, 3, 5, 6, 4]:
if self.level_available(index): result.append(index)
return result
## Make level `index` the one picked on, staying in Smart when it is one
## of Smart's levels (a tool's output, a reselection's type).
pub func adopt_level(self, index: int):
if self.component_mode == smart_level and index in self.smart_levels():
self.smart_pick = index
else:
self.component_mode = index
## The kind whose tools the viewport offers: the active Edit node's,
## else Edit Mesh's (tools on any displayed mesh make verb nodes).
pub func strip_kind(self) -> EditKind:
return self.selection_kind() else (self.kind_of(edit_mesh.kind_name) else trap("Edit Mesh"))
## Whether viewport tool `name` applies at the current level: the Edit
## node's kind offers it there (Edit Mesh's tools on another node's mesh).
pub func tool_available(self, name: str) -> bool!:
if self.selection_kind() == none: return false
let kind = self.active_kind() else return self.network.context() == "geometry" and tool_registry.find(name) != none or self.network.context() == "cad" and cad_node_named(name)
if name in kind.primitives or name in kind.draw_tools:
return true
let tool = kind.tool_at(name, self.level_index()) else return false
return tool.offered(self.level_index())
## The level that selects single elements of `domain` (Polygons rather
## than Object), or the first level.
pub func level_of(self, domain: int) -> int:
let all = self.levels()
for index in 0..<all.length:
if all[index].available and all[index].domain_number() == domain and all[index].piece == none:
return index
# A component level before Object, whose faces stand for whole models.
for index in 0..<all.length:
if index != object_level and all[index].available and all[index].domain_number() == domain:
return index
return 0
## The Edit overlay's mode for the level's domain (0 points, 1 edges,
## 2 faces, 3 corners).
pub func overlay_mode(self) -> int:
let domain = self.domain()
return 1 if domain == 4 else (3 if domain == 1 else domain)
## The selection's domain on the pick geometry (0 points, 4 edges,
## 2 faces, 1 corners) and the Group Type steps and verb nodes read.
pub func domain(self) -> int:
return self.level().domain_number()
## Whether the selection level picks on domain `domain`.
pub func on_domain(self, domain: Domain) -> bool:
return self.level().domain == domain
pub func group_type(self) -> int:
return self.level().group_number()
## The soft selection the viewport tints: the selected Edit node's soft
## radius, falloff and symmetry, where its moves honor them (Edit Mesh,
## and Edit CAD's control vertices, both through Transform Components);
## a radius of 0 elsewhere.
pub func soft_selection(self) -> list[float]:
let node = self.selected() else return [0.0, 0.0, 0.0]
let honored = node.kind == "Edit Mesh" or (node.kind == "Edit CAD" and self.group_type() == 1)
if not honored or not self.editing() or node.values.length < 4:
return [0.0, 0.0, 0.0]
return [node.values[soft_radius_slot], node.values[falloff_slot], node.values[symmetry_slot]]
## The hidden faces, when they fit the displayed mesh.
pub func hidden_faces(self) -> Selection?!:
let mesh = self.geometry else return none
let faces = self.hidden else return none
return faces if faces.fits(mesh) else none
## What a selection change from `before` to `chosen` keeps: in an Edit
## Mesh with a Symmetry axis, the change mirrored across it (what was
## taken away, its mirror too; then the mirror of the rest added:
## Maya's symmetric selection), less the components hidden with the
## faces (an edge or a point is hidden when every face using it is).
pub func kept(self, chosen: Selection, before: Selection? = none) -> Selection!:
let mesh = self.geometry else return chosen
if not chosen.fits(mesh):
return chosen
var result = chosen
let axis = self.symmetry_axis()
if axis > 0:
if let previous = before:
if previous.domain() == chosen.domain() and previous.fits(mesh):
let removed = previous.joined(chosen, 1)
if removed.count() > 0:
result = chosen.joined(removed.ruled(mesh, "Select Mirror", [float(axis - 1), 0.0]), 1)
if result.count() > 0:
result = result.ruled(mesh, "Select Mirror", [float(axis - 1), 1.0])
let faces = self.hidden_faces() else return result
return result.joined(faces.on_domain(mesh, chosen.domain(), true), 1)
## The Symmetry axis of the edited Edit Mesh (1 X, 2 Y, 3 Z; 0 none).
pub func symmetry_axis(self) -> int:
let node = self.selected() else return 0
if not self.editing() or node.kind != edit_mesh.kind_name:
return 0
return int(node.values[symmetry_slot])
## The selection on the displayed mesh (empty when there is none).
pub func current_selection(self) -> Selection?!:
let mesh = self.geometry else return none
if let chosen = self.selection:
if chosen.domain() == self.domain() and chosen.fits(mesh): return chosen
return Selection.empty(mesh, self.domain())
## The selected components' ids, ascending (tests and small selections).
pub func selected_ids(self) -> list[int]:
let result: list[int] = []
let chosen = self.selection else return result
var at = chosen.next(-1)
while at >= 0:
result.append(at)
at = chosen.next(at)
return result
## Whether a Sketch node is being edited in the viewport: selected,
## displayed, enabled, and no tool prompt open (sketch_editor.luc).
pub func sketching(self) -> bool:
let node = self.selected() else return false
if node.id != self.network.display or not node.enabled or self.prompt != none:
return false
return node.kind == sketch_node.kind_name or self.sketching_model(node)
## Whether Edit CAD node `node` has a sketch of its own being edited:
## the one named edit_sketch, which it holds (or its steps make).
pub func sketching_model(self, node: Node) -> bool:
if self.edit_sketch == "" or node.id != self.edit_sketch_node or not is_edit(node.kind):
return false
if node.held != none:
let held = edit_cad_sketches.named(edit_cad_sketches.parse_objects(node.sketch_state), self.edit_sketch) catch failure:
recover none
if held != none:
return true
for step in node.edits:
if step.verb == edit_cad_sketches.sketch_verb and step.text(edit_cad_sketches.name_slot) == self.edit_sketch:
return true
return false
## The Sketch the Project tool works in (-1: none): its body's edges are
## cast by the cook.
pub func projecting(self) -> int:
if not self.sketching() or self.sketch_tool != "Project":
return -1
return self.network.display
## Without the worker, the Project cast made here, as the worker would.
func local_cast(self) -> unit!:
self.shadows = ""
self.shadows_stamp = 0
let node = self.network.find(self.network.projecting) else return
let made = self.network.evaluate_data(node.id) catch failure:
recover GeometryData()
# An Edit CAD sketch casts its own model's edges; a Sketch node its
# input body's.
var body = made
if self.network.sketch_object == "":
let input = self.network.find(node.inputs[0]) else return
body = self.network.evaluate_data(input.id) catch failure:
recover GeometryData()
let plane = edit_cad_sketches.edited_plane(made, self.network.sketch_object) else return
self.shadows = sketch_node.shadows_text(body, plane)
self.shadows_stamp = node.stamp
## Whether the viewport picks on a CAD body (its B-rep edges show, not
## a tessellation's polygons).
pub func picking_brep(self) -> bool:
let mesh = self.geometry else return false
return mesh.find_attribute("cad_edge", 4) >= 0
## The UI reports CAD entities, never the proxy's polygon/segment count.
pub func selected_entities(self) -> int!:
let mesh = self.geometry else return 0
let chosen = self.current_selection() else return 0
# Curves: each picked curve once (its segments are the elements).
if self.level_index() == curve_level:
let owners = mesh.find_attribute("cad_curve", 4)
let seen: list[int] = []
var at = chosen.next(-1)
while at >= 0:
let owner = int(mesh.attribute_value(owners, at)) if owners >= 0 else -1
if not (owner in seen):
seen.append(owner)
at = chosen.next(at)
return seen.length
if self.network.context() == "cad":
return CadEdits.selected_entities(mesh, chosen, self.level_index())
return chosen.count()
pub func selected_count(self) -> int:
let chosen = self.selection else return 0
return chosen.count()
## A modal tool (the Knife) ends with the selection or node it was for;
## the transform tools (Q, W, E, R, T) stay.
pub func end_modal_tool(self):
if not (self.edit_tool in transform_tools()):
self.edit_tool = "Select"
## Whether the transform tools (Move, Rotate, Scale, Manipulator) have
## something to act on: selected components at a component level, else a
## selected object; a node the gizmo moves itself (Transform, Group, a
## Cube's handles, a Camera) at any level. Without one they hide.
pub func transform_target(self) -> bool:
if self.selecting() and self.selected_count() > 0:
return true
let node = self.selected() else return false
return not self.selecting() or node_catalog.moves_itself(node.kind)
## The tool in use: the one chosen, but Select while a transform tool has
## nothing to act on. The chosen one stays chosen and is back with the
## next selection (Maya's tools stay too).
pub func tool_in_use(self) -> str:
if self.edit_tool != "Select" and self.edit_tool in transform_tools() and not self.transform_target():
return "Select"
return self.edit_tool
## Whether the shown, selected Edit node is being edited: also while an
## action of its runs on the worker (it shows what it held till then),
## so menus and tools do not change and change back around each action.
pub func editing(self) -> bool:
let node = self.selected() else return false
return is_edit(node.kind) and node.enabled and (not node.dirty or self.pending != none or edit_held.waiting(node)) and node.id == self.network.display and self.geometry != none
pub func transforming(self) -> bool:
let node = self.selected() else return false
return node.kind in node_catalog.transforming_kinds() and node.enabled
## Parameter gizmos submit absolute gesture values; no mesh work on UI thread.
pub func preview_parameters(self, values: list[float]) -> unit!:
let before = self.pending else return
self.dragging = true
let original = before.graph.require(self.network.selected)
let node = self.selected() else return
node.values = values.copy()
self.pending_changed = values != original.values
self.network.invalidate(node.id)
self.rebuild()
## Camera node `id` moved with a pane looking through it
## (camera_views.luc) to `values`: live inside a gesture begun with
## begin() (committed as one undo step), else an undo step of its own.
pub func move_camera_node(self, id: int, values: list[float]) -> unit!:
let node = self.network.find(id) else return
if node.values == values:
return
if self.pending != none:
node.values = values.copy()
self.pending_changed = true
self.network.invalidate(id)
self.rebuild()
return
self.perform("Move " + node.name, func () -> unit!:
node.values = values.copy()
self.network.invalidate(id)
self.rebuild())
## An Edit node's last step's numbers dragged (a handle in the
## viewport): live, one undo step with the drag that began it.
pub func preview_step(self, numbers: list[float]) -> unit!:
let before = self.pending else return
let node = self.selected() else return
if node.edits.length == 0:
return
self.dragging = true
let original = before.graph.require(node.id)
node.edits[-1] = node.edits[-1].with_numbers(numbers)
self.pending_changed = original.action_count() != node.action_count() or original.edits.length == 0 or original.edits[-1].numbers != numbers
self.network.invalidate(node.id)
self.rebuild()
pub func snapshot(self) -> Snapshot!:
return Snapshot(self.network, self.selection, self.component_mode, self.hidden)
pub func begin(self, label: str) -> unit!:
if self.pending != none:
return
self.pending = self.snapshot()
self.pending_label = label
self.pending_changed = false
## A transaction whose changes are previews, as a viewport drag's are
## (a parameter scrubbed in the inspector or the tool bar): shown at
## preview quality while it lasts, cooked in full by commit.
pub func begin_preview(self, label: str) -> unit!:
self.begin(label)
if self.pending != none:
self.dragging = true
pub func commit(self) -> unit!:
let before = self.pending else return
let changed = self.pending_changed
if changed:
self.history.push(self.pending_label, before, self.snapshot())
self.bound_history()
self.pending = none
self.pending_changed = false
self.touch()
# A drag's frames were previews: the released result is cooked in full
# (an Edit node's again: its last step failing is a warning now).
if self.dragging:
self.dragging = false
if let node = self.selected():
if is_edit(node.kind):
self.network.invalidate(node.id)
self.rebuild()
pub func cancel(self) -> unit!:
let before = self.pending else return
self.pending = none
self.pending_changed = false
self.dragging = false
self.restore(before)
pub func in_transaction(self) -> bool:
return self.pending != none
pub func restore(self, snapshot: Snapshot) -> unit!:
# The frame is where the user is looking, not an edit: it stays.
let frame = self.network.frame
self.network = snapshot.graph.copy()
self.graph_swaps += 1
self.network.frame = math.max(self.network.start, math.min(self.network.end, frame))
self.network.background = self.compute != none
self.selection = snapshot.selection
self.hidden = snapshot.hidden
self.component_mode = snapshot.mode
self.rebuild()
## Whether nodes of kind `name` hold their result (edit_held.luc).
pub func holds(self, name: str) -> bool:
let kind = self.network.kinds.of(name) else return false
return kind.holds
## The undo history's memory bound: the held results it keeps (each
## shared array counted once, from the newest change back) take at most
## `held_budget` bytes beyond the graph's own; older changes go, the
## newest always stays. With its 64 changes this bounds what undo keeps
## of Edit nodes' results.
func bound_history(self) -> unit!:
let changes = self.history.changes
if changes.length < 2:
return
# The newest change always stays (the last action's undo).
let keys: list[int] = []
edit_held.held_keys(self.network, keys)
let own = HeldStore.footprint(keys)
edit_held.held_keys(changes[changes.length - 1].before.graph, keys)
var at = changes.length - 2
while at >= 0:
edit_held.held_keys(changes[at].before.graph, keys)
if HeldStore.footprint(keys) - own > self.held_budget:
self.history.drop_before(at + 1)
return
at -= 1
## While a drag changes what the shown Edit node holds, draw that in
## place of the mesh shown for it (its GPU copies update only where
## points moved), and pick on it; false when the node is not shown on
## its own or holds no mesh, and the cook draws it instead.
func show_held(self) -> bool!:
let node = self.selected() else return false
if node.id != self.network.display or not self.holds(node.kind) or not node.enabled or node.hidden.length > 0 or edit_held.waiting(node):
return false
let held = node.held else return false
let mesh = held.result.mesh else return false
let shown = self.geometry else return false
# Shown where it is, not placed by a container's transform.
var placed = false
for item in view_items(self.network):
if item.node.id == node.id and item.matrix.is_identity():
placed = true
if not placed:
return false
if not swap_shown(self.objects.node(), shown.points_id(), mesh, 0):
return false
self.drag_shown[node.id] = held.result
self.geometry = self.picked(node, held.result)
self.sync_selection()
return true
## Release the held results nothing can reach any more: not the graph,
## the gesture's starting state or the undo history.
func keep_held(self) -> unit!:
# Something can have become unreachable only if a result was added,
# the undo history changed, a transaction began or ended, or the
# graph was replaced.
let key = (HeldStore.generation(), self.history.version, self.pending != none, self.graph_swaps).hash()
if key == self.kept_key:
return
self.kept_key = key
# The history's keys, gathered again only when it changed: a drag's
# frames walk no history.
if self.history_keys_version != self.history.version:
self.history_keys_version = self.history.version
self.history_keys = []
for change in self.history.changes:
edit_held.held_keys(change.before.graph, self.history_keys)
edit_held.held_keys(change.after.graph, self.history_keys)
let alive: list[int] = self.history_keys.copy()
edit_held.held_keys(self.network, alive)
if let before = self.pending:
edit_held.held_keys(before.graph, alive)
HeldStore.keep(alive)
pub func undo(self) -> unit!:
if self.placing != none:
self.cancel_placing()
return
if self.pending != none:
self.cancel_prompt()
return
if self.history.can_undo():
self.history.cursor -= 1
self.restore(self.history.changes[self.history.cursor].before)
pub func redo(self) -> unit!:
if self.pending != none:
self.cancel_prompt()
if self.history.can_redo():
let snapshot = self.history.changes[self.history.cursor].after
self.history.cursor += 1
self.restore(snapshot)
## Every mutation enters this command transaction path, including scripts
## and UI gestures. Invalid topology/links roll back without losing history.
pub func perform(self, label: str, action: func() -> unit!) -> unit!:
let owns = self.pending == none
if owns:
self.begin(label)
action() catch failure:
self.cancel()
self.notice = failure.message
self.touch()
return
self.pending_changed = true
self.touch()
if owns:
self.commit()
## Something the panels show changed: the revision moves on and
## `on_change` hears it.
pub func touch(self):
self.revision += 1
if let changed = self.on_change:
changed()
pub func rebuild(self) -> unit!:
# Normalize before cooking, including empty contexts and the worker.
if not self.level_available(self.component_mode):
self.component_mode = 0
self.selection = none
# Edit nodes that hold their result bring it up to date here, on
# this thread (edit_held.luc); the cook only reads it.
stamp_graph(self.network)
if not self.dragging:
self.drag_shown = {}
self.network.gesture = self.dragging
edit_held.settle(self.network, self.drag_shown)
self.keep_held()
# A drag on the shown Edit node that holds its result draws it as it
# now is: no cook here or on the worker until the drag ends.
if self.dragging and self.show_held():
self.touch()
return
self.network.projecting = self.projecting()
self.network.slicing = self.network.display if self.slice and self.sketching() else -1
self.network.sketch_object = ""
if let shown = self.selected():
if self.sketching_model(shown):
self.network.sketch_object = self.edit_sketch
self.network.gesture = self.dragging
self.network.quiet = self.dragging or self.in_transaction()
self.network.cv_nets = self.network.display if self.editing() and self.component_mode == point_level and (self.selected() else trap("selected")).kind == "Edit CAD" else -1
if let session = self.compute:
self.network.level = self.component_mode
self.network.cad_quality = self.display.cad_quality
self.network.picking_cad = self.prompt != none
self.network.picking = self.picking()
session.submit(self.network, self.view.mesh_mode(), self.display.normals_visible)
self.touch()
return
self.network.picking_cad = self.prompt != none
self.network.picking = self.picking()
stamp_graph(self.network)
let cooked = cook_outputs(self.network, self.objects, self.batches, self.view.mesh_mode(), self.slicer, self.display.context_mode, self.dragging)
self.notice = cooked.notice
self.local_cast()
self.section = self.slicer.section
self.section_stamp = self.slicer.section_stamp
self.local_nodes = cooked.nodes
self.local_meshes = cooked.meshes
self.local_around = cooked.around
self.local_outside = cooked.outside
self.local_outside_nodes = cooked.outside_nodes
self.geometry = none
if let node = cooked.node:
self.geometry = self.picked(node, cooked.data else trap("display"))
self.sync_selection()
self.touch()
## The node a tool prompt picks on (its input, while the tool's result
## is shown); -1 without a prompt.
func picking(self) -> int:
let prompt = self.prompt else return -1
return prompt.input
## What the viewport picks on for displayed `node`: its Edit kind's
## geometry for the level, else its mesh.
func picked(self, node: Node, data: GeometryData) -> Mesh?!:
if let kind = self.selection_kind():
return kind.pick(data, self.level_index()) catch failure:
recover none
if data.mesh == none and self.network.picking_cad and data.has_cad():
# A CAD body picks on its tagged tessellation (B-rep faces and edges).
return CadEdits.pick_mesh(data.geometry)
return data.mesh
## Runtime UI uses a persistent worker; deterministic tests/scripts may cook
## synchronously. Published scenes remain visible while replacements compute.
pub func enable_compute(self) -> unit!:
if self.compute == none:
self.compute = ComputeSession()
self.network.background = true
self.rebuild()
pub func poll_compute(self) -> bool!:
let session = self.compute else return false
let progress = session.poll_progress(self.network)
let completed = session.service.completed()
if completed == 0:
return progress
if completed != session.generation:
session.service.release_result(self.publisher.kept)
return progress
self.notice = session.read_report(self.network) catch failure:
session.service.release_result(self.publisher.kept)
session.busy = false
self.notice = failure.message
self.touch()
return true
# Actions the worker ran: their nodes hold the results now.
_ = edit_held.adopt(self.network)
self.shadows = session.shadows
self.shadows_stamp = session.shadows_stamp
self.section = session.section
self.section_stamp = session.section_stamp
if session.service.failed() or session.resync:
session.service.release_result(self.publisher.kept)
# The worker lost its mirror: send the whole graph once.
if session.resync:
self.rebuild()
self.touch()
return true
# Lines split by the scope the result was styled for: a new scope
# with the same products splits them again.
if self.publisher.adopt(session.service, self.network, self.display.context_mode) or self.batches_scope != self.network.scope:
self.batches.adopt(session.service, self.outside_nodes())
self.batches_scope = self.network.scope
self.batches.volumes = self.publisher.volumes
self.batches.volume_nodes = self.publisher.volume_nodes
self.batches.clouds = self.publisher.clouds
self.batches.cloud_nodes = self.publisher.cloud_nodes
self.batches.scenes = self.publisher.scenes
self.batches.scene_keys = self.publisher.scene_keys
self.batches.scene_nodes = self.publisher.scene_nodes
self.geometry = self.publisher.geometry
self.sync_selection()
session.service.release_result(self.publisher.kept)
self.touch()
# The frames put off till now, each in the pane that asked, if
# nobody moved its view since.
let acting = self.view
for view in self.panes.views:
let kind = view.take_frame()
if kind != 0:
self.view = view
self.frame_scene(kind == 1)
self.view = acting
return true
## The nearest visible surface along a view ray (the displayed scene).
pub func surface_at(self, origin: Vector3, direction: Vector3) -> SurfaceHit!:
return SurfaceHits.cast(self.objects, origin, direction)
## Where placing lands along a view ray: on the snap target alone when
## one is picked, else on the nearest visible surface.
pub func landing_at(self, origin: Vector3, direction: Vector3) -> SurfaceHit!:
if self.snap_target < 0:
return self.surface_at(origin, direction)
var best = SurfaceHit(false, Vector3(), Vector3(0.0, 1.0, 0.0), -1.0)
for mesh in self.meshes_of(self.snap_target):
let face = mesh.ray_face(origin, direction)
if face < 0:
continue
let distance = mesh.ray_distance(origin, direction)
if not best.found or distance < best.distance:
var normal = mesh.face_normal(face)
# Two-sided: the side the ray comes from.
if normal.dot(direction) > 0.0:
normal = normal.multiply_scalar(-1.0)
best = SurfaceHit(true, origin.add(direction.multiply_scalar(distance)), normal, distance)
return best
## The meshes drawn for node `id`, in the context or around it.
pub func meshes_of(self, id: int) -> list[Mesh]:
let result: list[Mesh] = []
if self.compute == none:
for at in 0..<self.local_nodes.length:
if self.local_nodes[at] == id: result.append(self.local_meshes[at])
for at in 0..<self.local_outside_nodes.length:
if self.local_outside_nodes[at] == id: result.append(self.local_outside[at])
return result
for at in 0..<self.publisher.nodes.length:
if self.publisher.nodes[at] == id: result.append(self.publisher.meshes[at])
return result
pub func cancel_placing(self) -> unit!:
if self.placing == none:
return
self.placing = none
self.notice = ""
self.touch()
## Esc: drop the prompted node (or the reselection) with the transaction.
pub func cancel_prompt(self) -> unit!:
self.prompt = none
self.peeking = false
self.pending_group = ""
self.notice = ""
self.cancel()
## The components' center; the bounds center without a selection.
pub func selection_center(self) -> Vector3!:
let mesh = self.geometry else return Vector3()
let chosen = self.current_selection() else return mesh.bounds().minimum.add(mesh.bounds().maximum).multiply_scalar(0.5)
return chosen.center(mesh)
## A new result of the displayed node: adopt a tool's output selection
## (switching the component type, as Houdini does), a reselection's
## group, or drop a selection that no longer fits.
func sync_selection(self) -> unit!:
let mesh = self.geometry else return
if not self.level_available(self.component_mode):
self.component_mode = 0
self.selection = none
# A create step's piece: selected at its level (Object).
if self.adopt_output and self.pending_level >= 0:
self.adopt_output = false
self.adopt_level(self.pending_level)
self.pending_level = -1
if mesh.group_size(".selection", self.domain()) >= 0:
self.selection = Selection.of(mesh, ".selection", self.domain())
return
if self.pending_group != "":
let domain = [0, 0, 4, 2, 1][self.pending_type] if self.pending_type > 0 else self.domain()
self.adopt_level(self.level_of(domain))
self.selection = Selection.of(mesh, self.pending_group, domain)
self.pending_group = ""
return
if self.adopt_output:
self.adopt_output = false
for domain in [2, 4, 0, 1]:
if mesh.group_size(".selection", domain) >= 0:
self.adopt_level(self.level_of(domain))
self.selection = Selection.of(mesh, ".selection", domain)
return
if let chosen = self.selection:
if chosen.domain() != self.domain() or not chosen.fits(mesh):
self.selection = none
# B-rep faces or edges meshed again (a face moved, a value
# changed): the same faces or edges stay selected.
if let before = self.selected_on:
if chosen.domain() == self.domain() and self.picking_brep():
let carried = CadEdits.carried(before, chosen, mesh)
if carried != "":
self.selection = Selection.of(mesh, carried, chosen.domain())
self.selected_on = mesh
## Whether a CAD tool labeled `name` is a node in a CAD network.
func cad_node_named(name: str) -> bool:
for entry in tool_registry.cad_nodes():
if entry.label == name:
return true
return false
## Under scene node `parent`, the object drawing the mesh whose points are
## `points` replaced by one drawing `mesh` (the cook nests a context's
## objects in groups); whether one was.
func swap_shown(parent: ObjectNode, points: int, mesh: Mesh, depth: int) -> bool!:
if depth > 4:
return false
for index in 0..<parent.child_count():
let child = parent.child(index)
if let polygon = child.polygon():
if polygon.points_id() == points:
_ = parent.remove(child)
parent.add(display_mesh(mesh))
return true
continue
if swap_shown(child.node(), points, mesh, depth + 1):
return true
return false