Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.8

0.11.8 / src / edit_held.luc

## Edit nodes hold their result (docs/research/POLY-MODELING.md, "Edit nodes
## hold their result"; the owner's model, 2026-10-13): an Edit node is not a
## recipe replayed on each cook but the thing modeled in it. It holds an
## absolute result; every action (a move, a tool, a primitive, a deletion)
## replaces it at once, on the UI thread, and the node's cook returns it
## with no work. Undo keeps the node's earlier results in the undo history
## (each immutable, sharing storage); the history's memory is bounded
## (history.luc).
##
## Only the latest action stays adjustable (Blender's Adjust Last
## Operation): the node keeps the result before it (`base`) and the action
## as its one step (`Node.edits`), so the tool bar and a drag run it again
## from `base`. The next action bakes it: its result becomes the new
## `base`. There is no stack beyond that.
##
## A wired Edit node starts from its input's result when it is made (or with
## Reload Input); later changes upstream do not flow in: the node then says
## "Input changed" and Reload Input takes the new input (one undo step).
## Until its input can be cooked it passes the input through.
##
## The worker reads a held result by its content key from held_store.lucb.
## An Edit kind takes part when it `holds` (edit_types.EditKind).
##
## With the compute worker, an action the kind runs `in_background` (all
## but a gizmo's move, a sculpt stroke and a sketch's edit: a Boolean of
## large pieces or a fillet would hold the UI for many frames) runs there,
## not here: the node names the result it will hold (`held_key`, the
## content key of the base and the step) and the base it runs on
## (`held_base`); the worker runs the step on the base it reads from
## HeldStore, keeps the result there under that key and shows it like any
## cook. The node keeps showing what it held (the last good result) until
## then, and `adopt` takes the result when the worker's report comes. A
## drag adjusting such an action sends each frame's step; the worker cooks
## only the newest request, so frames coalesce and stale results are never
## shown (HeldStore lets go of the keys nothing names). The undo history is
## untouched: the action is one step, its result found again by its key.
from geometry_data import GeometryData
from luce_geocore.geocore import Verbs
from edit_operations import EditStep
from edit_types import EditKind, run_step
from held_store import HeldStore
from held import Held, held_as, meta_of, with_meta
from network import Network
from node import Node
from luce_cad.cad_geometry import CadGeometry
from luce_cad.model import CadTolerances, CadModel
from luce_cad.modeling import CadModeling
from node_evaluation import fixed_mm
from edit_cad_sketches import with_models

## Bring every holding Edit node's result up to date with its step:
## started from its input when it is acted on first, the steps before the
## last baked, the last run from the base. Called before each cook request
## (Workspace.rebuild) and by the local cook.
## `shown` holds, by node, the result a drag's last frame showed: a gizmo
## drag runs the gesture again from the state before it each frame, and its
## new result is made over that one (Mesh.rebased), so shading and GPU
## copies change only where points moved since the last frame.
pub func settle(graph: Network, shown: map[int, GeometryData] = {}) -> unit!:
    for node in graph.nodes:
        let kind = graph.kinds.of(node.kind) else continue
        if not kind.holds or not node.enabled:
            continue
        settle_node(graph, node, kind, shown[node.id])

func settle_node(graph: Network, node: Node, kind: EditKind, shown: GeometryData?) -> unit!:
    var held = node.held
    if held == none:
        # A new node starts from its input's result; an input that cannot
        # be cooked yet leaves it passing its input through until it can.
        held = start(graph, node, kind) catch failure:
            if node.edits.length > 0:
                error(failure.code, failure.message)
            return
    var current = held else trap("held")
    node.held_base = 0
    # Steps before the last are baked: their result is the new base (the
    # worker's, when it ran there; one still running is run here).
    while node.edits.length > 1:
        let step = node.edits[0]
        node.edits = node.edits[1..]
        if current.made_for == step.key:
            current = Held(current.result, current.key, current.result, current.key, "", 0, current.input_stamp, current.actions + 1)
            continue
        let key = (current.base_key, step.key).hash()
        var made = current.base
        if HeldStore.holds(key):
            made = stored(key)
        else:
            let (ran, _) = run_step(kind, step, current.actions, current.base, tag_of(node), graph.tolerances, false, reference_of(graph, node, step))
            made = ran
        current = Held(made, key, made, key, "", 0, current.input_stamp, current.actions + 1)
    if node.edits.length == 0:
        # The last action was taken back (Clear): the base stands.
        if current.made_for != 0:
            current = held_as(current.base, current.base_key, current.input_stamp, current.actions)
    else:
        let step = node.edits[0]
        let wanted = (current.base_key, step.key).hash()
        if current.made_for != step.key and HeldStore.holds(wanted) and graph.background and kind.in_background(step):
            # The worker ran it already (an undo or a redo back to it).
            let made = stored(wanted)
            node.held_failure = ""
            current = Held(current.base, current.base_key, made, wanted, made.warning, step.key, current.input_stamp, current.actions)
        elif current.made_for != step.key and graph.background and kind.in_background(step):
            # The worker runs it: the node names the result it will hold
            # and keeps showing what it held.
            node.held = current
            node.held_key = wanted
            node.held_base = current.base_key
            node.held_actions = current.actions
            node.held_failure = ""
            HeldStore.put(current.base_key, current.base.geometry, meta_of(current.base))
            return
        if current.made_for != step.key:
            # The same action adjusted again (a drag): its new result is made
            # over its last one where only positions differ, so shading and
            # GPU copies update only where points moved.
            var last: GeometryData? = shown
            if last == none and current.made_for != 0:
                last = current.result
            var made = current.base
            var ran = false
            let reference = reference_of(graph, node, step)
            if let previous = last:
                if let again = kind.run_over:
                    # A failure is reported by the plain run below.
                    let tried: GeometryData? = again(step, current.base, reference, previous) catch failure:
                        recover none
                    if let result = tried:
                        made = result
                        ran = true
            if not ran:
                # While a drag sets its values the action's failure fails the
                # node instead: the viewport keeps the drag's last good
                # result, as a feature node's does; let go, it says why.
                let attempt: (GeometryData, bool)? = run_step(kind, step, current.actions, current.base, tag_of(node), graph.tolerances, graph.gesture, reference) catch failure:
                    if not graph.gesture:
                        error(failure.code, failure.message)
                    node.held_failure = failure.message
                    recover none
                let (plain, _) = attempt else return
                made = plain
            node.held_failure = ""
            current = Held(current.base, current.base_key, made, (current.base_key, step.key).hash(), made.warning, step.key, current.input_stamp, current.actions)
    keep(node, current)

## `held` as what `node` holds, put where the worker reads it.
func keep(node: Node, held: Held) -> unit!:
    node.held = held
    node.held_key = held.key
    node.held_note = held.warning
    # What the result tells the editor (sketches, handles, the last
    # action's aids) is the UI's own: the worker reads only the geometry.
    node.sketch_state = held.result.sketch_state
    node.handles = held.result.handles
    # CAD models go to the worker as a crate: their codecs first.
    _ = CadGeometry.register_codec()
    HeldStore.put(held.key, held.result.geometry, meta_of(held.result))

## The node's start: its input's result (cooked here, on the UI thread, once)
## made the kind's own, or nothing for an unwired node.
func start(graph: Network, node: Node, kind: EditKind) -> Held!:
    var input = GeometryData()
    var stamp = 0
    if node.inputs.length > 0 and node.inputs[0] >= 0:
        let upstream = graph.require(node.inputs[0])
        stamp = upstream.stamp
        input = local_cook(graph).evaluate_data(upstream.id)
    let started = kind.start(input, tag_of(node))
    return held_as(started, ("start", node.id, stamp).hash(), stamp)

## Take the input's current result again (Reload Input): the node starts
## over from it.
pub func reload(graph: Network, node: Node) -> unit!:
    let kind = graph.kinds.of(node.kind) else return
    node.edits = []
    keep(node, start(graph, node, kind))

## Whether the node's input has changed since it started from it.
pub func input_changed(graph: Network, node: Node) -> bool:
    let held = node.held else return false
    if held.input_stamp == 0 or node.inputs.length == 0 or node.inputs[0] < 0:
        return false
    let upstream = graph.find(node.inputs[0]) else return false
    return upstream.stamp != held.input_stamp

## The project's tolerances changed: held CAD bodies do not cook again, so
## each is checked against the new ones instead (luce-cad's rechecked): an
## edge lying off its faces by more than the new positional tolerance is
## made tolerant there, and the node says how many. The base and the
## result alike, so the last action stays adjustable.
pub func recheck(graph: Network) -> unit!:
    for node in graph.nodes:
        let held = node.held else continue
        if not held.result.has_cad():
            continue
        let (base, _) = rechecked(held.base, graph.tolerances)
        let (result, note) = rechecked(held.result, graph.tolerances)
        let stamp = graph.tolerances.positional
        let base_key = (held.base_key, "tolerances", stamp).hash()
        let key = (held.key, "tolerances", stamp).hash()
        let warning = note if note != "" else held.warning
        keep(node, Held(base, base_key, result, key, warning, held.made_for, held.input_stamp, held.actions))

## `data`'s models checked against `tolerances`, its sketches and Aligns
## kept, and what it says when edges were made tolerant ("" when none).
func rechecked(data: GeometryData, tolerances: CadTolerances) -> (GeometryData, str)!:
    if not data.has_cad():
        return (data, "")
    let models: list[CadModel] = []
    var edges = 0
    var worst = 0.0
    for model in data.models():
        let checked = CadModeling.rechecked(model, tolerances)
        let report = CadModeling.tolerance_report(checked)
        edges += report.tolerant_edges
        if report.worst > worst: worst = report.worst
        models.append(checked)
    let made = with_models(data, models)
    made.aligns = data.aligns
    made.sketch_state = data.sketch_state
    made.handles = data.handles
    if edges == 0:
        return (made, "")
    return (made, f"{edges} edge{"" if edges == 1 else "s"} lie up to {fixed_mm(worst)} mm off their faces, looser than the project's {fixed_mm(tolerances.positional)} mm: made tolerant there")

## The result held under `key` (HeldStore), saying what it said.
pub func stored(key: int) -> GeometryData!:
    _ = CadGeometry.register_codec()
    return with_meta(GeometryData(geometry = HeldStore.get(key)), HeldStore.meta(key))

## Take the results the worker made for actions it ran (see the top):
## whether any node's result changed.
pub func adopt(graph: Network) -> bool!:
    # A drag's frames stay on the worker; its last is taken once it ends.
    if graph.gesture:
        return false
    var adopted = false
    for node in graph.nodes:
        if node.held_base == 0 or not HeldStore.holds(node.held_key):
            continue
        let held = node.held else continue
        if node.edits.length == 0:
            continue
        let made = stored(node.held_key)
        node.held_base = 0
        keep(node, Held(held.base, held.base_key, made, node.held_key, made.warning, node.edits[0].key, held.input_stamp, held.actions))
        adopted = true
    return adopted

## Whether `node` waits for the worker to run its last action.
pub func waiting(node: Node) -> bool:
    return node.held_base != 0

## Run every action still waiting for the worker here (a project being
## saved needs the results).
pub func finish(graph: Network) -> unit!:
    var waits = false
    for node in graph.nodes:
        if node.held_base != 0: waits = true
    if not waits:
        return
    let background = graph.background
    graph.background = false
    settle(graph) catch failure:
        graph.background = background
        error(failure.code, failure.message)
    graph.background = background

## The keys of every result held in `graph` (live, for HeldStore.keep): the
## results, the bases the last actions run on, and a result the worker is
## making.
pub func held_keys(graph: Network, into: list[int]):
    for node in graph.nodes:
        if let held = node.held:
            into.append(held.key)
            into.append(held.base_key)
        if node.held_base != 0:
            into.append(node.held_key)
            into.append(node.held_base)

## A copy of `graph` that cooks here, on this thread: with the worker, the
## UI's nodes hold no results.
func local_cook(graph: Network) -> Network!:
    let local = graph.copy()
    if graph.background:
        local.background = false
        for node in local.nodes:
            node.dirty = true
            node.cache = none
    return local

## What names the node's creations (cad_nodes.tag_of's form).
func tag_of(node: Node) -> str:
    return f"#{node.id}"

## The node's second input's result (Edit Mesh's Reference) for `step`
## run on the UI thread: none unless its verb reads a reference surface
## (Shrinkwrap, Relax, Corrective Smooth: luce-geocore verbs of two inputs),
## which with the worker run there, not here; a gizmo's move or a sculpt
## stroke never cooks it. Without the worker the graph cooks it here once
## and keeps it (its nodes' caches).
func reference_of(graph: Network, node: Node, step: EditStep) -> GeometryData?!:
    if node.inputs.length < 2 or node.inputs[1] < 0:
        return none
    let verb = Verbs.index_of(step.verb)
    if verb < 0 or Verbs.inputs(verb) < 2:
        return none
    let cooking = local_cook(graph) if graph.background else graph
    return cooking.evaluate_data(node.inputs[1]) catch failure:
        recover none