dymokomi/luced-3d
Source of release 0.11.2
## 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 view (camera and
## display settings, view_state.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
from stamps import stamp_graph
from luce_geocore.geocore import Mesh, Selection, Domain
from luce_3d.graphics import Scene, Group, Vector3, Matrix4, AmbientLight, DirectionalLight, SurfaceHits, SurfaceHit
from place_prompt import PlacePrompt
from tool_prompt import ToolPrompt
from network import Network, Node
from tools import tool_run, transform_tools
from snapping import SnapSettings, SnapMark
from history import History, Snapshot
from scene_projection import append_bounds
from local_cook import cook_outputs
from compute_session import ComputeSession
from display_publisher import DisplayPublisher
from node_evaluation import SourceCache
from view_state import ViewState
from viewport_batches import ViewportBatches
from edit_kinds import is_edit, edit_kind
from geometry_data import GeometryData
from edit_types import EditKind, EditLevel, smart_level, face_level, soft_radius_slot, falloff_slot, symmetry_slot
import edit_mesh
import node_catalog
from luce_cad.cad_edits import CadEdits
from luce_std import math
pub class Workspace:
pub var network: Network
pub let history: History
pub let scene: Scene
let objects: Group
pub let view: ViewState
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
## 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
pub var last_sketch_tool: str = ""
## Edit kinds by node kind, made once each (they hold closures).
let edit_kinds: map[str, EditKind]
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"
## 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
pub var splat_footprint: float = 0.1
pub var splat_visible: 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
## 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
pub var revision: int = 0
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]
let sources: SourceCache
var pending_frame: bool = false
var project_epoch: int = 0
pub func init(self) -> unit!:
self.snaps = SnapSettings()
self.view = ViewState()
self.batches = ViewportBatches()
self.sources = SourceCache()
self.edit_kinds = {}
self.mesh_levels = edit_mesh.levels()
self.network = Network()
self.network.sources = self.sources
self.history = History()
self.scene = Scene()
self.objects = Group()
self.publisher = DisplayPublisher(self.objects)
self.local_nodes = []
self.local_meshes = []
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
self.pending_frame = false
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.network.background = self.compute != none
self.network.sources = self.sources
self.history.changes.clear()
self.history.cursor = 0
self.selection = none
self.prompt = none
self.component_mode = face_level
self.smart_pick = face_level
self.notice = ""
self.rebuild()
## Frame the selected components while editing, else every displayed mesh.
pub func frame_cube(self) -> unit!:
let points: list[Vector3] = []
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
if let session = self.compute:
if session.busy:
self.pending_frame = true
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)
var candidates = self.network.outputs(self.network.scope)
if let node = self.network.find(self.network.display):
if self.network.preview or node_catalog.places_children(node.kind):
candidates = [node]
if self.compute != none:
candidates = []
for node in candidates:
if not node.visible:
continue
let data = self.network.evaluate_data(node.id) catch failure:
continue
append_bounds(data, Matrix4(), points)
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.revision += 1
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.view.normals_visible = not self.view.normals_visible
self.revision += 1
if self.compute != none and self.view.normals_visible:
self.rebuild()
pub func toggle_hulls(self) -> unit!:
self.view.hulls_visible = not self.view.hulls_visible
self.revision += 1
## 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.revision += 1
## CAD bodies are meshed again at the new quality.
pub func set_cad_quality(self, divisions: int) -> unit!:
if divisions == self.view.cad_quality:
return
self.view.cad_quality = divisions
self.network.cad_quality = divisions
self.revision += 1
self.rebuild()
pub func set_display_mode(self, mode: int) -> unit!:
if self.view.set_display_mode(mode):
self.revision += 1
## The meshes on screen (world space) and the node each came from.
pub func on_screen(self) -> (list[int], list[Mesh]):
if self.compute != none:
return (self.publisher.nodes, self.publisher.meshes)
return (self.local_nodes, self.local_meshes)
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
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
## The Edit kind of node kind `name` (kept once made), or none.
pub func kind_of(self, name: str) -> EditKind?:
if let known = self.edit_kinds[name]:
return known
let made = edit_kind(name) else return none
self.edit_kinds[name] = made
return made
## 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)
## The selection levels: the selected Edit node's kind's, else Edit
## Mesh's (any displayed mesh selects on them).
pub func levels(self) -> list[EditLevel]:
if let kind = self.active_kind():
return kind.levels
return self.mesh_levels
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 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 levels Smart picks among (none: it is not offered).
pub func smart_levels(self) -> list[int]:
return self.strip_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
## 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.active_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!:
let kind = self.active_kind() else return tool_run(name) != none
if name in kind.primitives or name in kind.draw_tools:
return true
let tool = kind.tool(name) 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
for index in 0..<all.length:
if 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 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
return node.kind == sketch_node.kind_name and node.enabled and node.id == self.network.display and self.prompt == none
## 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
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"
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) 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 ["Transform", "Group", "CAD"] 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()
pub func snapshot(self) -> Snapshot!:
return Snapshot(self.network, self.selection, self.component_mode)
pub func begin(self, label: str) -> unit!:
if self.pending != none:
return
self.pending = self.snapshot()
self.pending_label = label
self.pending_changed = false
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.pending = none
self.pending_changed = false
self.revision += 1
# A drag's frames were previews: the released result is cooked in full.
if self.dragging:
self.dragging = false
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.network.frame = math.max(self.network.start, math.min(self.network.end, frame))
self.network.background = self.compute != none
self.selection = snapshot.selection
self.component_mode = snapshot.mode
self.rebuild()
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.revision += 1
return
self.pending_changed = true
self.revision += 1
if owns:
self.commit()
pub func rebuild(self) -> unit!:
if let session = self.compute:
self.network.level = self.component_mode
self.network.gesture = self.dragging
self.network.cad_quality = self.view.cad_quality
self.network.picking_cad = self.prompt != none
self.network.picking = self.picking()
session.submit(self.network, self.view.mesh_mode(), self.view.normals_visible)
self.revision += 1
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.notice = cooked.notice
self.local_nodes = cooked.nodes
self.local_meshes = cooked.meshes
self.geometry = none
if let node = cooked.node:
self.geometry = self.picked(node, cooked.data else trap("display"))
self.sync_selection()
self.revision += 1
## 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 node.enabled:
if let kind = self.kind_of(node.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.revision += 1
return true
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.revision += 1
return true
if self.publisher.adopt(session.service, self.network):
self.batches.adopt(session.service)
self.batches.volumes = self.publisher.volumes
self.batches.clouds = self.publisher.clouds
self.batches.cloud_nodes = self.publisher.cloud_nodes
self.geometry = self.publisher.geometry
self.sync_selection()
session.service.release_result(self.publisher.kept)
self.revision += 1
if self.pending_frame:
self.pending_frame = false
self.frame_cube()
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)
pub func cancel_placing(self) -> unit!:
if self.placing == none:
return
self.placing = none
self.notice = ""
self.revision += 1
## 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