Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.8

0.11.8 / src / compute_worker.luc

## Worker-local DAG mirror, result store (one current result per node:
## result_store.luc) and publishing. No UI objects are created here. Cooking
## resolves each node by stamp: its stored result is reused while the stamp
## stands, and a recipe Edit node applies only the steps after its longest
## stored checkpoint.
from compute_bridge import ComputeChannel, ComputeHandler
import compute_bridge
from compute_request import read_request, write_report, Outcome
from network import Network, warned
from node import Node
from context_view import view_items
from node_evaluation import SourceCache
from result_store import ResultStore
from stamps import prefix_stamp, edit_base
from cache_node import reads_file
from geometry_data import GeometryData, key_light
import cad_nodes
from scene_projection import append_overlays, append_patch_boundaries, append_cad_hulls
from luce_geocore.geocore import Mesh, Subdivision
from overlay_lines import OverlayLines
from luce_3d.graphics import Matrix4, FogVolume, GaussianSplats
import node_catalog
import script_cook
import import_node
from luce_ui import ui
from edit_kinds import is_edit, context_kind
from edit_types import run_step, EditKind
from shader_nodes import is_shader
from luce_cad.cad_edits import CadEdits
from render_geometry import render_geometry
import sketch_node
import edit_cad_sketches
import slice_view
from slice_view import Slicer
from held_store import HeldStore
import edit_held
from held import meta_of

class Computation:
    let channel: ComputeChannel
    var graph: Network
    let store: ResultStore
    let sources: SourceCache
    ## Cooks per node ID, reported as the node's evaluation count.
    let cooks: map[int, int]
    ## Failures met while cooking this request, with node names.
    let failures: map[int, str]
    var preview_warning: str = ""
    ## What showing each node's CAD left out (faces its tessellation could
    ## not mesh, named): on the node, beside its own warning.
    let display_warnings: map[int, str]
    var recipes: int = 0
    ## Meshes published under keys the UI may hold, kept alive so an identity
    ## match never sees a recycled object. A mesh reaching several nodes (an
    ## Edit without recipes, a Null, a bypass) keeps one key, so the UI keeps
    ## its copy, scene object and renderer data.
    var meshes: list[Mesh]
    var keys: list[int]
    ## Slice's last cut, kept while the body and plane stay.
    let slicer: Slicer
    ## Results of Edit actions run here (held_action), by key, while a node
    ## names them: a drag's frames stay here (a result holding CAD models
    ## would cross to the UI as a file); the last, once let go, goes to
    ## HeldStore for the node to take.
    let made: map[int, GeometryData]

    pub func init(self, channel: ComputeChannel) -> unit!:
        self.slicer = Slicer()
        self.made = {}
        self.channel = channel
        self.graph = Network(false)
        self.store = ResultStore()
        self.sources = SourceCache()
        # A cook waiting on a Script build or child also wakes for a newer request.
        channel.wake_on_requests(self.sources.scripts.news)
        self.cooks = {}
        self.failures = {}
        self.display_warnings = {}
        self.meshes = []
        self.keys = []

    pub func compute(self, message: str) -> unit!:
        self.graph = read_request(message, self.graph) catch failure:
            # The mirror is unusable: ask the UI for a full request.
            self.graph = Network(false)
            self.channel.report(write_report(failure.message, true, []))
            return
        # A newer delta is queued: apply this one, cook only the newest.
        if self.channel.superseded():
            return
        let graph = self.graph
        self.sources.folder = graph.folder
        self.preview_warning = ""
        self.recipes = 0
        self.failures.clear()
        self.display_warnings.clear()
        var notice = ""
        let meshes: list[Mesh] = []
        let keys: list[int] = []
        for at in 0..<self.keys.length:
            if self.channel.holds(self.keys[at]):
                meshes.append(self.meshes[at])
                keys.append(self.keys[at])
        self.meshes = meshes
        self.keys = keys
        # The root's objects, whole, for the viewport's render mode.
        for node in graph.outputs(-1):
            let data = self.evaluate(node) catch failure:
                if failure.message == "Computation superseded":
                    error(failure.code, failure.message)
                notice = failure.message
                continue
            self.publish_scene(node, data)
        # What the viewport draws: the context, then the rest of the root.
        for item in view_items(graph):
            let data = self.evaluate(item.node) catch failure:
                if failure.message == "Computation superseded":
                    error(failure.code, failure.message)
                if not item.outside:
                    notice = failure.message
                    let shown = self.publish_fallback(item.node, item.matrix)
                    if shown != "":
                        notice = f"{failure.message} (the viewport {shown})"
                continue
            self.store.remember_good(item.node.id)
            self.channel.progress(item.node.id, 0.95, "Preparing viewport")
            self.publish(item.node, self.slicer.shown(graph, item.node, data), item.matrix, slice_view.salt(graph, item.node))
        if let node = graph.find(graph.selected):
            let data = self.evaluate(node) catch failure:
                if failure.message == "Computation superseded":
                    error(failure.code, failure.message)
                recover GeometryData()
            # The authoring context also owns selection on plain feature nodes.
            let kind = graph.kinds.of(context_kind(graph.context()))
            if let editor = kind:
                let picked = editor.pick(data, graph.level) catch failure:
                    recover none
                if let mesh = picked:
                    self.inspect(node, mesh, graph.level)
            elif let mesh = data.mesh:
                self.inspect(node, mesh)
            elif graph.picking_cad and data.has_cad():
                # A CAD body picks on its tagged tessellation.
                self.inspect(node, CadEdits.pick_mesh(data.geometry))
        if notice == "":
            notice = self.preview_warning
        let (shadows, shadows_stamp) = self.shadows()
        let live = self.node_ids()
        self.store.prune(live, self.wanted_checkpoints())
        self.prune_made()
        # Cook counts of nodes gone go too.
        let gone: list[int] = []
        for id in self.cooks.keys():
            if not (id in live): gone.append(id)
        for id in gone:
            _ = self.cooks.remove(id)
        self.channel.report(write_report(notice, false, self.outcomes(), self.recipes, shadows, shadows_stamp, self.slicer.section, self.slicer.section_stamp, self.store.count(), self.store.bytes()))

    ## The Project tool's cast: the projecting Sketch's input body's edges
    ## on its plane, and that Sketch's stamp; none when nothing projects or
    ## either fails (the tool then says there is no body).
    func shadows(self) -> (str, int)!:
        let node = self.graph.find(self.graph.projecting) else return ("", 0)
        let made = self.evaluate(node) catch failure:
            if failure.message == "Computation superseded":
                error(failure.code, failure.message)
            return ("", 0)
        # An Edit CAD sketch casts its own model's edges; a Sketch node its
        # input body's.
        var body = made
        if self.graph.sketch_object == "":
            let input = self.graph.find(node.inputs[0]) else return ("", 0)
            body = self.evaluate(input) catch failure:
                if failure.message == "Computation superseded":
                    error(failure.code, failure.message)
                return ("", 0)
        let plane = edit_cad_sketches.edited_plane(made, self.graph.sketch_object) else return ("", 0)
        return (sketch_node.shadows_text(body, plane), node.stamp)

    ## Stored result for the node's stamp, or cook it. Failures from inputs
    ## propagate without being stored under this node's stamp.
    func evaluate(self, node: Node, depth: int = 0) -> GeometryData!:
        if depth > 64:
            error(ui.invalid, "Cycle detected during evaluation")
        if let entry = self.store.get(node.id, node.stamp):
            if entry.failure != "":
                error(ui.invalid, self.failed(node, entry.failure))
            return entry.data else GeometryData()
        self.channel.begin(node.stamp)
        let result = self.cook(node, depth) catch failure:
            self.channel.end()
            error(failure.code, failure.message)
        self.channel.end()
        return result

    func cook(self, node: Node, depth: int) -> GeometryData!:
        let graph = self.graph
        # Shader nodes make no geometry; a Material reads them.
        if is_shader(node.kind):
            return GeometryData()
        if node.kind == "Material":
            graph.resolve_material(node)
        var input = GeometryData()
        var second: GeometryData? = none
        if node.frozen != "":
            input = GeometryData()
        elif node.kind == "Input":
            let source = graph.context_input(node)
            if source >= 0: input = self.upstream(node, graph.require(source), depth)
        elif node_catalog.collects_children(node.kind):
            input = GeometryData()
            if node.enabled:
                let children: list[GeometryData] = []
                for child in graph.outputs(node.id):
                    let data = self.upstream(node, child, depth)
                    if graph.direct_children(node):
                        input = input.merged(data)
                    else:
                        children.append(data)
                input = input.with_instances(children)
        elif node.kind == "Render":
            # Render renders the root: every flagged object there.
            input = GeometryData()
            for child in graph.outputs(-1):
                input = input.merged(self.upstream(node, child, depth))
        elif node.kind == import_node.kind_name:
            # Other nodes' results, by path, placed by the Transform menu
            # and merged in authoring order.
            if node.enabled:
                let sources = graph.import_read(node) catch failure:
                    return self.own(node, failure.code, failure.message)
                for at in 0..<sources.length:
                    let steps = graph.import_steps(node, sources[at]) catch failure:
                        return self.own(node, failure.code, failure.message)
                    let data = import_node.placed(self.upstream(node, sources[at], depth), steps)
                    input = data if at == 0 else input.merged(data)
        elif not (node.kind in node_catalog.sources()) and node.inputs.length > 0 and not reads_file(node.kind, node.enabled, node.values):
            let port = int(node.values[0]) if node.kind == "Switch" and node.enabled else 0
            # An Edit node starts from nothing when unconnected (it can create).
            let unconnected = node_catalog.optional_input(node.kind) and node.inputs[0] < 0
            if not unconnected and (port < 0 or port >= node.inputs.length or node.inputs[port] < 0):
                return self.own(node, ui.invalid, "Connect a geometry input")
            if not unconnected:
                input = self.upstream(node, graph.require(node.inputs[port]), depth)
            # An Edit node's Reference is read though nothing is wired first.
            if (not unconnected or is_edit(node.kind)) and node.enabled and node.inputs.length == 2 and not (node.kind in ["Switch", "Null"]):
                if node.inputs[1] >= 0:
                    second = self.upstream(node, graph.require(node.inputs[1]), depth)
                elif node_catalog.requires_second(node.kind):
                    return self.own(node, ui.invalid, "Connect the second geometry input")
        # A Cache or Export writes its file once the gesture ends: its input
        # passes through while it lasts, not kept as its result, so the
        # release cooks it again and writes what was let go.
        if self.graph.gesture and node.enabled and node.frozen == "" and (node.kind == "Export" or (node.kind == "Cache" and not reads_file(node.kind, node.enabled, node.values))):
            return input
        self.channel.progress(node.id, 0.0, "Computing")
        self.cooks[node.id] = (self.cooks[node.id] else 0) + 1
        var result = GeometryData()
        if is_edit(node.kind) and node.enabled and node.frozen == "":
            result = self.edit(node, input, second) catch failure:
                return self.own(node, failure.code, failure.message)
        else:
            let progress = func (fraction: float) -> unit!:
                self.channel.progress(node.id, fraction, "Tessellating" if node.kind == "Tessellate" else (script_cook.phase(fraction) if node.kind == script_cook.kind_name else "Computing"))
            result = node.compute(input, second, progress, self.sources, [graph.frame, graph.time(), graph.fps], input_keys(graph, node), graph.direct_children(node), graph.sketch_text(node), tolerances = graph.tolerances) catch failure:
                return self.own(node, failure.code, failure.message)
            if node.kind == "Render":
                result = graph.render_result(node, result) catch failure:
                    return self.own(node, failure.code, failure.message)
            if node_catalog.collects_children(node.kind):
                result = warned(result, graph.output_warning(node.id))
        result = node.shown(result) catch failure:
            return self.own(node, failure.code, failure.message)
        _ = self.store.put(node.id, node.stamp, result)
        self.channel.progress(node.id, 1.0, "Complete")
        return result

    ## Apply only the recipes after the longest stored prefix. Prefixes at the
    ## checkpoints (the last eight, every sixteenth) are stored as they are
    ## made: undo inside that window, a gizmo drag and the next recipe start
    ## from a stored result. The node's Edit kind runs each step.
    func edit(self, node: Node, input: GeometryData, reference: GeometryData?) -> GeometryData!:
        let kind = self.graph.kinds.of(node.kind) else error(ui.invalid, f"{node.kind} is not an Edit node")
        var base = 0
        if let upstream = self.graph.find(node.inputs[0]):
            base = upstream.stamp
        base = edit_base(self.graph, base)
        let tag = cad_nodes.tag_of(node.id)
        # A holding kind's result is held: read by its key (the UI made it);
        # untouched, its input passes through.
        if kind.holds:
            if node.held_failure != "":
                error(ui.invalid, node.held_failure)
            # The last action runs here (edit_held.luc: a heavy one), on the
            # base the UI holds; its result goes where the UI takes it.
            if node.held_base != 0 and not HeldStore.holds(node.held_key):
                return self.held_action(node, kind, tag, reference)
            if node.held_key != 0:
                return self.held_data(node.held_key)
            return kind.start(input, tag)
        var result = kind.start(input, tag)
        var start = 0
        var count = node.edits.length - 1
        while count > 0 and start == 0:
            if let data = self.store.checkpoint(node.id, prefix_stamp(node, base, count)):
                result = data
                start = count
            count -= 1
        for at in start..<node.edits.length:
            let (next, built) = run_step(kind, node.edits[at], at, result, tag, self.graph.tolerances, self.graph.gesture and at == node.edits.length - 1, reference)
            result = next
            self.recipes += 1
            self.channel.check()
            if not built:
                break
            if at + 1 < node.edits.length and checkpoint(at + 1, node.edits.length):
                self.store.put_checkpoint(node.id, prefix_stamp(node, base, at + 1), result)
        return result

    ## A holding Edit node's last action run on its base (`held_base`), the
    ## result kept in HeldStore under the key the node names (`held_key`).
    ## While a drag sets its values, a failure fails the node (the viewport
    ## keeps the last good result); else the base passes with a warning.
    func held_action(self, node: Node, kind: EditKind, tag: str, reference: GeometryData?) -> GeometryData!:
        if node.edits.length == 0:
            error(ui.invalid, f"{node.name}'s action is missing")
        var made = GeometryData()
        if let ran = self.made[node.held_key]:
            made = ran
        else:
            let step = node.edits[node.edits.length - 1]
            self.channel.progress(node.id, 0.05, step.verb)
            let base = self.held_data(node.held_base)
            let (result, _) = run_step(kind, step, node.held_actions, base, tag, self.graph.tolerances, self.graph.gesture, reference)
            self.recipes += 1
            self.channel.check()
            self.made[node.held_key] = result
            made = result
        if not self.graph.gesture:
            HeldStore.put(node.held_key, made.geometry, meta_of(made))
        return made

    ## The held result under `key`: one made here, else HeldStore's.
    func held_data(self, key: int) -> GeometryData!:
        if let made = self.made[key]:
            return made
        return edit_held.stored(key)

    ## Let go of results made here that no node names.
    func prune_made(self) -> unit:
        if self.made.length == 0:
            return
        let named: set[int] = {}
        for node in self.graph.nodes:
            named.insert(node.held_key)
            named.insert(node.held_base)
        let gone: list[int] = []
        for key in self.made.keys():
            if not (key in named): gone.append(key)
        for key in gone:
            _ = self.made.remove(key)

    func upstream(self, node: Node, input: Node, depth: int) -> GeometryData!:
        let data = self.evaluate(input, depth + 1) catch failure:
            if failure.message == "Computation superseded":
                error(failure.code, failure.message)
            error(failure.code, self.failed(node, failure.message))
        return data

    ## A failure of this node's own recipe, stored under its stamp.
    func own(self, node: Node, code: ErrorCode, message: str) -> GeometryData!:
        if message == "Computation superseded":
            error(code, message)
        _ = self.store.fail(node.id, node.stamp, message)
        error(code, self.failed(node, message))

    func failed(self, node: Node, message: str) -> str:
        let text = f"{node.name}: {message}"
        self.failures[node.id] = text
        return text

    ## The ids of the graph's nodes (their slots stay in the store).
    func node_ids(self) -> set[int]:
        let result: set[int] = {}
        for node in self.graph.nodes:
            result.insert(node.id)
        return result

    ## Each recipe Edit node's checkpoints its current recipe uses.
    func wanted_checkpoints(self) -> map[int, set[int]]!:
        let result: map[int, set[int]] = {}
        for node in self.graph.nodes:
            if not is_edit(node.kind) or node.edits.length == 0 or holds(self.graph, node):
                continue
            var base = 0
            if let upstream = self.graph.find(node.inputs[0]):
                base = upstream.stamp
            base = edit_base(self.graph, base)
            let stamps: set[int] = {}
            for count in 1..<node.edits.length:
                if checkpoint(count, node.edits.length):
                    stamps.insert(prefix_stamp(node, base, count))
            result[node.id] = stamps
        return result

    func outcomes(self) -> list[Outcome]:
        let result: list[Outcome] = []
        for node in self.graph.nodes:
            var cooked = 0
            var summary = ""
            var paths: list[str] = []
            var failure = self.failures[node.id] else ""
            var warning = ""
            var console = ""
            var sketch_state = ""
            var automatic = ""
            var handles = ""
            var curves: list[str] = []
            if let entry = self.store.peek(node.id, node.stamp):
                cooked = node.stamp
                summary = entry.summary
                paths = entry.paths
                warning = entry.warning
                console = entry.console
                sketch_state = entry.sketch_state
                automatic = entry.automatic
                handles = entry.handles
                curves = entry.curves
                if entry.failure != "":
                    failure = f"{node.name}: {entry.failure}"
            elif failure != "":
                cooked = node.stamp
            if let shown = self.display_warnings[node.id]:
                warning = shown if warning == "" else f"{warning}; {shown}"
            let outcome = Outcome(node.id, cooked, failure, summary, self.cooks[node.id] else 0, paths)
            outcome.warning = warning
            outcome.console = console
            outcome.sketch_state = sketch_state
            outcome.automatic = automatic
            outcome.handles = handles
            outcome.curves = curves
            result.append(outcome)
        return result

    ## A root object's whole set, for the viewport's render mode: shared, not
    ## copied.
    func publish_scene(self, node: Node, data: GeometryData) -> unit!:
        let scene_key = (node.stamp, "scene", self.graph.gesture, self.graph.cad_quality).hash()
        let scene = data.geometry if self.channel.holds(scene_key) else render_geometry(data, self.graph.gesture, self.graph.cad_quality)
        self.channel.scene(scene_key, node.id, scene)

    ## Publish a drawn node's meshes and overlays, placed by `matrix`, by
    ## content key; keys the UI still holds cost nothing. CAD previews build
    ## under the node's stamp, so a newer request that still wants it lets
    ## the preview finish.
    ## `salt` keys apart what a node shows that is not its result as stored
    ## (a sliced sketch's clipped body).
    func publish(self, node: Node, data: GeometryData, matrix: Matrix4, salt: int = 0) -> unit!:
        self.channel.begin(node.stamp)
        self.prepare(data, node) catch failure:
            self.channel.end()
            error(failure.code, failure.message)
        self.channel.end()
        # A placed copy (the rest of the scene around a context) keys by its
        # placement too.
        let placement = salt if salt != 0 else (0 if matrix.is_identity() else matrix_key(matrix))
        _ = self.display(data, matrix, node, 0, placement)
        # CAD edges are keyed by what they are drawn from (the models' edges
        # as the viewport's quality samples them), so a CV drag keeps them
        # held; normal guides follow the result.
        let edges = data.edges_key()
        if edges != 0:
            self.publish_lines((edges, "cad-edges", placement, self.graph.cad_quality).hash(), node, data, matrix, true, false)
            if self.graph.show_normals:
                self.publish_lines((node.stamp, "guides", placement).hash(), node, data, matrix, false, true)
        else:
            self.publish_lines((node.stamp, "overlays", self.graph.show_normals, placement).hash(), node, data, matrix, true, self.graph.show_normals)
        self.publish_curves(node, data, matrix, placement)
        self.publish_cad_hulls(node, data, matrix, placement)
        self.publish_checks(node, data, matrix, placement)

    ## A failed node's place in the viewport, so the view never goes blank:
    ## while a drag makes it fail, its last good cook (kept); else the
    ## nearest node upstream that cooked (what the failing feature started
    ## from), published as that node's. What the viewport shows ("keeps its
    ## last good result", "shows its input"), "" nothing.
    func publish_fallback(self, node: Node, matrix: Matrix4) -> str!:
        if self.graph.gesture:
            if let data = self.store.good(node.id):
                self.publish(node, data, matrix)
                return "keeps its last good result"
        for id in self.graph.upstream_chain(node.id):
            let upstream = self.graph.find(id) else return ""
            let data = self.evaluate(upstream) catch failure:
                if failure.message == "Computation superseded":
                    error(failure.code, failure.message)
                continue
            self.publish(upstream, data, matrix)
            return "shows its input"
        return ""

    ## Overlay lines under `key`: the CAD edges (as wires and patch borders)
    ## with `edges`, the normal guides with `normals`.
    func publish_lines(self, key: int, node: Node, data: GeometryData, matrix: Matrix4, edges: bool, normals: bool) -> unit!:
        if self.channel.holds(key):
            self.channel.reuse(key, node.id, false, false)
            return
        let wires = OverlayLines.make()
        let guides = OverlayLines.make()
        let patches = OverlayLines.make()
        # Display only: lines that cannot be drawn are left out, the result
        # stands.
        append_overlays(data, matrix, wires if edges else OverlayLines.make(), guides if normals else OverlayLines.make(), polygons = false) catch failure:
            _ = failure
        if edges:
            append_patch_boundaries(data, matrix, patches) catch failure:
                _ = failure
        if wires.count() + guides.count() + patches.count() > 0:
            self.channel.overlay(key, node.id, wires, guides, patches)

    ## CAD control nets go to the shared hull product, under their own key
    ## (camera and light glyphs are drawn from the displayed scenes, each on
    ## its own: view.luc's draw_glyphs).
    func publish_cad_hulls(self, node: Node, data: GeometryData, matrix: Matrix4, placement: int) -> unit!:
        let modeled = node.id == self.graph.cv_nets
        let key = (node.stamp, "cad-hull", placement, modeled).hash()
        if self.channel.holds(key):
            self.channel.reuse(key, node.id, false, false)
            return
        let lines = OverlayLines.make()
        append_cad_hulls(data, matrix, lines, modeled = modeled)
        if lines.count() > 0:
            self.channel.hull(key, node.id, lines)

    ## A Check node's lines (cad_check.luc), under their own content key.
    func publish_checks(self, node: Node, data: GeometryData, matrix: Matrix4, placement: int) -> unit!:
        let check = data.check else return
        let key = (node.stamp, "checks", placement).hash()
        if self.channel.holds(key):
            self.channel.reuse(key, node.id, false, false)
            return
        self.channel.checks(key, node.id, check, matrix)

    ## Curves are drawn as lines, published under their own content key.
    func publish_curves(self, node: Node, data: GeometryData, matrix: Matrix4, placement: int) -> unit!:
        let key = (node.stamp, "curves", placement).hash()
        if self.channel.holds(key):
            self.channel.reuse(key, node.id, false, false)
            return
        self.channel.curves(key, node.id, data.geometry, matrix, with_hulls = cad_nodes.shows_curve_hulls(node.kind))

    func prepare(self, data: GeometryData, node: Node) -> unit!:
        if data.has_cad():
            # A drag's frames show moved control vertices' quick previews.
            let report = func (fraction: float) -> unit!:
                self.channel.progress(node.id, fraction * 0.9, "Tessellating CAD")
            let preview = data.preview(report, self.graph.gesture, self.graph.cad_quality)
            if preview.failed_faces > 0:
                self.preview_warning = f"{preview.failed_faces} CAD preview patches failed: {preview.first_error}"
                self.channel.progress(node.id, 0.9, f"{preview.failed_faces} preview failures")
                self.display_warnings[node.id] = self.preview_warning
            elif preview.cv_warning != "":
                self.preview_warning = preview.cv_warning
                self.display_warnings[node.id] = preview.cv_warning
        for index in 0..<data.instance_count():
            if data.instance_visible(index):
                self.prepare(data.instance(index), node)

    ## Deterministic traversal: a stamp always yields the same ordinals.
    func display(self, data: GeometryData, matrix: Matrix4, node: Node, ordinal: int, placement: int) -> int!:
        self.channel.check()
        var next = ordinal
        # A tint (a Check's deviation colors) shades in place of the bodies.
        if let tint = data.tint:
            self.show(tint, matrix, node, next, false, placement)
            return next + 1
        if let mesh = data.mesh:
            self.show(mesh, matrix, node, next, true, placement)
            next += 1
        # A drag's frames show a coarse SDF surface; the release, the full one.
        if let preview = data.field_preview(self.graph.gesture):
            self.show(preview, matrix, node, next, false, placement)
            next += 1
        # Fog grids are ray-marched: their texels are made here, once per
        # content key (a new look keeps it).
        for index in 0..<FogVolume.count(data.geometry):
            let key = FogVolume.key(data.geometry, index, matrix, key_light())
            self.channel.volume(key, node.id, data.geometry, index, matrix, key_light())
        # A point cloud draws as Gaussian splats (or dots): packed here, once
        # per content key.
        if GaussianSplats.count(data.geometry) > 0:
            self.channel.cloud(GaussianSplats.key(data.geometry, matrix), node.id, data.geometry, matrix)
        if data.has_cad():
            for mesh in data.preview().meshes:
                self.show(mesh, matrix, node, next, false, placement)
                next += 1
        for index in 0..<data.instance_count():
            if data.instance_visible(index):
                next = self.display(data.instance(index), matrix.multiply(data.instance_matrix(index)), node, next, placement)
        return next

    func show(self, mesh: Mesh, matrix: Matrix4, node: Node, ordinal: int, overlays: bool, placement: int) -> unit!:
        let identity = matrix.is_identity()
        let key = self.key_of(mesh, (node.stamp, ordinal).hash()) if identity and placement == 0 else (node.stamp, ordinal, placement).hash()
        # Picking runs on the GPU; a query index is built by its first query.
        var shown: Mesh? = none
        if self.channel.holds(key):
            self.channel.reuse(key, node.id, true, false)
        else:
            let placed = mesh if identity else mesh.placed(matrix)
            shown = placed
            # A subdivided mesh's display is made here, off the UI thread: the
            # renderer then finds it cached (by connectivity and positions).
            _ = Subdivision.display(placed)
            self.channel.mesh(placed, key, node.id, true, false)
            if identity and placement == 0:
                self.meshes.append(mesh)
                self.keys.append(key)
        if overlays and self.graph.show_normals:
            let guides = (key, "guides").hash()
            if self.channel.holds(guides):
                self.channel.reuse(guides, node.id, false, false)
            else:
                self.channel.guides(guides, node.id, shown else (mesh if identity else mesh.placed(matrix)))

    ## The selected node's mesh for the spreadsheet and component picking. A
    ## mesh already published (displayed, or held from before) doubles as it.
    ## `level`: the Edit node's level whose pick geometry `mesh` is (-1 a
    ## node's own mesh), part of the key since levels pick on other meshes.
    func inspect(self, node: Node, mesh: Mesh, level: int = -1) -> unit!:
        let key = self.key_of(mesh, (node.stamp, "inspect", level).hash())
        if self.channel.holds(key) or self.listed(key):
            self.channel.reuse(key, node.id, false, true)
            return
        self.channel.mesh(mesh, key, node.id, false, true)
        self.meshes.append(mesh)
        self.keys.append(key)

    func key_of(self, mesh: Mesh, fallback: int) -> int:
        for at in 0..<self.meshes.length:
            if self.meshes[at] is mesh:
                return self.keys[at]
        return fallback

    func listed(self, key: int) -> bool:
        return key in self.keys

## A key of `matrix`'s values (a placed copy's products key by it).
func matrix_key(matrix: Matrix4) -> int:
    let columns = [matrix.x, matrix.y, matrix.z, matrix.translation]
    var key = 7
    for column in columns:
        key = (key, column.x, column.y, column.z).hash()
    return key if key != 0 else 1

## The content keys of `node`'s inputs: their nodes' stamps, the keys their
## results are stored under (0 for an unwired input).
func input_keys(graph: Network, node: Node) -> list[int]:
    let keys: list[int] = []
    for id in node.inputs:
        if let input = graph.find(id):
            keys.append(input.stamp)
        else:
            keys.append(0)
    return keys

## Whether the result after `count` of `total` steps is kept: the last eight
## (instant undo and redo) and every sixteenth (a replay from any point costs
## at most fifteen steps), per D18.
pub func checkpoint(count: int, total: int) -> bool:
    return count >= total - 8 or count % 16 == 0

pub func compute_factory(token: int) -> ComputeHandler!:
    let computation = Computation(compute_bridge.channel(token))
    return computation.compute

## Whether `node`'s Edit kind holds its result (edit_held.luc).
func holds(graph: Network, node: Node) -> bool:
    let kind = graph.kinds.of(node.kind) else return false
    return kind.holds