Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.3

0.11.3 / src / inspector.luc

## The Parameters pane: a compact node header (name, type and flags, what it
## does), then the node's parameters as one ParameterPanel built from the
## catalog, one line each after Houdini's parameter pane. The catalog's rows
## name the value or text slot each edits; an Edit node adds its component
## edit rows. A drag is live and one undo step on release.
from luce_ui.ui import VStack, HStack, Text, TextField, Font, Button, ParameterPanel, ParameterSpec, ParameterKind, Rect, Size, TextEditor
from code_editor import CodeEditor
from script_check import ScriptChecker
import code_node
import code_cook
import script_cook
import script_node
from interop import Connection
from workspace import Workspace
from actions import Actions
from parameter_rows import Parameter
from shader_nodes import is_shader
from network import Node
from shader_nodes import inputs as shader_inputs
import node_catalog
from edit_kinds import is_edit
from usd_nodes import Composition, compose_usd
import node_commands
import cad_nodes
import sketch_node
import sketch_commands
from sketch_commands import SketchDimension
import units
from angles import radians, degrees
import tool_prompts

pub class Inspector:
    ## A path row's Browse: pick a file for text slot `slot`.
    pub var on_browse: func(int) -> unit!? = none
    ## The Render node's Render button.
    pub var on_render: func() -> unit!? = none
    pub let body: VStack
    ## The selected node's parameters.
    pub let parameters: ParameterPanel
    let workspace: Workspace
    let actions: Actions
    let name: TextField
    let kind: Text
    let stats: Text
    let description: Text
    let state_rows: VStack
    let delete_button: Button
    let generic_rows: VStack
    let connections: list[Connection]
    ## The catalog rows the panel shows, and what each row is to the inspector:
    ## "value", "text", "info", "reload", "clear", "edits",
    ## "operation", or a blend's "edges", "pick_edges" and "all_edges".
    var rows: list[Parameter]
    var roles: list[str]
    ## What the panel was built for: node kind, file format and edit count.
    var built: str = ""
    ## A USD File node's composed stage, and the file, texts and revision
    ## it was composed for.
    var stage: Composition? = none
    var stage_key: str = ""
    var showing: int = -2
    ## A Sketch node's dimensions, read once per text it has.
    var dimensions_text: str = ""
    var dimensions: list[SketchDimension]
    ## A Code node's body and header editors, shown for Code nodes; a Script
    ## node's code in the body editor, without a header.
    let code_box: VStack
    ## The Code or Script node's code (public for captures).
    pub let code_body: CodeEditor
    let code_header: CodeEditor
    let code_title: Text
    let header_title: Text
    ## What the code's k.printf calls said in the last cook (many lines).
    let console: TextEditor
    ## A Script node's check while typing, and the error of the text it held
    ## back ("" none), which the editor marks in place of the cook's.
    let checker: ScriptChecker
    var check_failure: str = ""

    pub func init(self, workspace: Workspace, actions: Actions, font: Font) -> unit!:
        self.dimensions = []
        self.workspace = workspace
        self.actions = actions
        self.connections = []
        self.rows = []
        self.roles = []
        self.name = TextField("", font = font, placeholder = "Node name", cells = 18.0)
        self.connections.append(self.name.on_commit(func (name: str) -> unit!: node_commands.rename(workspace, name)))
        self.kind = Text("", font = font, muted = true)
        self.stats = Text("", font = font, muted = true)
        self.description = Text("", font = font, muted = true)
        self.parameters = ParameterPanel([], font = font)
        self.connections.append(self.parameters.on_begin(func (index: int) -> unit!:
            if self.roles[index] in ["value", "dimension", "angle_dimension", "ramp"]:
                workspace.begin("Change " + self.rows[index].name)))
        self.connections.append(self.parameters.on_change(self.changed))
        self.connections.append(self.parameters.on_commit(func (index: int) -> unit!:
            workspace.commit()))
        self.connections.append(self.parameters.on_action(self.acted))
        self.state_rows = VStack([
            HStack([Button(action = actions.output, font = font), Button(action = actions.auto_output, font = font), Button(action = actions.visibility, font = font)], spacing = 4.0),
            HStack([Button(action = actions.display, font = font), Button(action = actions.enabled, font = font)], spacing = 4.0)], spacing = 4.0)
        self.delete_button = Button(action = actions.delete, font = font)
        let header = VStack([self.name, self.kind, self.state_rows, self.description], spacing = 4.0, padding = 6.0)
        let footer = VStack([self.stats, self.delete_button], spacing = 4.0, padding = 6.0)
        self.code_body = CodeEditor(font)
        self.code_header = CodeEditor(font)
        self.code_body.editor.layout().set_limits(Size(240.0, 240.0), Size(16384.0, 420.0))
        self.code_header.editor.layout().set_limits(Size(240.0, 90.0), Size(16384.0, 300.0))
        self.code_body.on_commit = func (text: str) -> unit!: self.code_committed(code_cook.body_slot, text)
        self.checker = ScriptChecker()
        self.code_header.on_commit = func (text: str) -> unit!: self.code_committed(code_cook.header_slot, text)
        self.code_header.part = 1
        self.code_body.partner = self.code_header
        self.code_header.partner = self.code_body
        self.console = TextEditor("", read_only = true, line_numbers = false, font = font)
        self.console.layout().set_limits(Size(240.0, 40.0), Size(16384.0, 200.0))
        self.code_title = Text("Code (one element; it runs for all in parallel)", font = font, muted = true)
        self.header_title = Text("Header (helper functions)", font = font, muted = true)
        self.code_box = VStack([self.code_title, self.code_body.editor, self.console, self.header_title, self.code_header.editor], spacing = 4.0, padding = 6.0)
        self.generic_rows = VStack([header, self.parameters, self.code_box, footer], spacing = 0.0)
        self.body = VStack([self.generic_rows], spacing = 0.0)
        self.refresh()

    ## A parameter changed in the panel: its slots take the values (a vector
    ## its components), a text row its text.
    func changed(self, index: int) -> unit!:
        let role = self.roles[index]
        let row = self.rows[index]
        if role == "value":
            for component in 0..<row.components:
                node_commands.set_parameter(self.workspace, row.slot + component, self.parameters.component(index, component))
        elif role == "text":
            let node = self.workspace.selected() else return
            if node.kind == script_cook.kind_name and row.slot == script_cook.packages_slot:
                script_node.set_packages(self.workspace, node.id, self.parameters.text(index))
            else:
                node_commands.set_text(self.workspace, row.slot, self.parameters.text(index))
        elif role == "ramp":
            let node = self.workspace.selected() else return
            if node.kind in [code_cook.kind_name, script_cook.kind_name]:
                code_node.set_ramp(self.workspace, node.id, row.slot, self.parameters.ramp(index))
            else:
                node_commands.set_ramp_text(self.workspace, node.id, row.slot, self.parameters.ramp(index))
        elif role == "dimension" or role == "angle_dimension":
            let node = self.workspace.selected() else return
            let value = self.parameters.value(index)
            sketch_commands.set_dimension(self.workspace, node.id, row.slot, radians(value) if role == "angle_dimension" else value)

    func acted(self, index: int) -> unit!:
        let role = self.roles[index]
        if role == "text":
            if let callback = self.on_browse:
                callback(self.rows[index].slot)
        elif role == "reload":
            node_commands.reload_file(self.workspace)
        elif role == "render":
            if let callback = self.on_render:
                callback()
        elif role == "clear":
            self.actions.clear_edits.trigger()
        elif role == "pick_edges":
            if let node = self.workspace.selected(): tool_prompts.pick_edges(self.workspace, node.id)
        elif role == "all_edges" or role == "all_profiles":
            node_commands.set_text(self.workspace, 0, "")
        elif role == "pick_face":
            if let node = self.workspace.selected(): tool_prompts.pick_face(self.workspace, node.id)
        elif role == "pick_profiles":
            if let node = self.workspace.selected(): tool_prompts.pick_profiles(self.workspace, node.id)
        elif role == "reselect":
            if let node = self.workspace.selected(): tool_prompts.reselect(self.workspace, node.id)
        elif role == "keep_ids":
            if let node = self.workspace.selected(): node_commands.keep_ids(self.workspace, node.id)

    ## The field showing value slot `slot`, in window points; empty when none shows it.
    pub func field_bounds(self, slot: int) -> Rect!:
        let origin = self.parameters.layout().bounds()
        for index in 0..<self.rows.length:
            let row = self.rows[index]
            if self.roles[index] == "value" and slot >= row.slot and slot < row.slot + row.components:
                let field = self.parameters.field_bounds(index, slot - row.slot)
                return Rect(origin.x + field.x, origin.y + field.y, field.width, field.height)
        return Rect()

    ## The value the panel shows for slot `slot`.
    pub func shown_value(self, slot: int) -> float!:
        for index in 0..<self.rows.length:
            let row = self.rows[index]
            if self.roles[index] == "value" and slot >= row.slot and slot < row.slot + row.components:
                return self.parameters.component(index, slot - row.slot)
        return 0.0

    ## Rebuild the panel's rows for `node`: the catalog's, and an Edit node's edits.
    func build(self, kind: str, path: str) -> unit!:
        self.rows = []
        self.roles = []
        var specs: list[ParameterSpec] = []
        let shown = units.document_unit(self.workspace)
        var fields = node_catalog.fields(kind, path, self.stage)
        # A Code or Script node's spare parameters, from its code.
        if kind == code_cook.kind_name or kind == script_cook.kind_name:
            if let node = self.workspace.selected():
                fields = fields + code_node.spare_rows(node)
        for row in fields:
            specs.append(row.spec(shown))
            self.rows.append(row)
            self.roles.append("ramp" if row.kind in ["ramp", "color_ramp"] else "text" if row.kind in ["text", "path"] else (("render" if row.name == "Render" else "reload") if row.kind == "button" else ("info" if row.kind == "info" else "value")))
        if is_edit(kind):
            self.add(specs, "edits", ParameterSpec(name = "edits", label = "Edits", kind = ParameterKind.info))
            self.add(specs, "clear", ParameterSpec(name = "clear", label = "Clear edits", kind = ParameterKind.button,
                                                    doc = "Remove every component edit of this node."))
        # A verb node made from a selection: pick its components again, or keep
        # its numbers on a changed topology (Houdini's behaviour).
        # A blend's edges: references to them by their faces (luce-cad's
        # names), which survive changes upstream; shown as a count.
        if kind == sketch_node.kind_name:
            self.add(specs, "face", ParameterSpec(name = "face", label = "Face", kind = ParameterKind.info,
                                                  doc = "The input body's face the sketch is on (Plane: Face), kept by its name so it stays that face as the body changes."))
            self.add(specs, "pick_face", ParameterSpec(name = "pick_face", label = "Pick face", kind = ParameterKind.button,
                                                       doc = "Show the input body and click the flat face to sketch on."))
        if kind in ["Extrude", "Revolve"]:
            self.add(specs, "profiles", ParameterSpec(name = "profiles", label = "Profiles", kind = ParameterKind.info,
                                                      doc = "The sketch's regions to take, remembered by the curves round them so they hold as dimensions change. None picked: its closed shapes, holes left empty."))
            self.add(specs, "pick_profiles", ParameterSpec(name = "pick_profiles", label = "Pick profiles", kind = ParameterKind.button, join = true,
                                                           doc = "Click the sketch's regions to take (again to leave one out); Enter finishes."))
            self.add(specs, "all_profiles", ParameterSpec(name = "all_profiles", label = "Closed shapes", kind = ParameterKind.button,
                                                          doc = "Forget the picked profiles: take the sketch's closed shapes."))
        if kind in ["Fillet", "Chamfer"]:
            self.add(specs, "edges", ParameterSpec(name = "edges", label = "Edges", kind = ParameterKind.info,
                                                   doc = "The edges to blend, remembered by the faces they lie between, so they stay the same edges when anything upstream changes. None picked: every straight convex edge between flat faces."))
            self.add(specs, "pick_edges", ParameterSpec(name = "pick_edges", label = "Pick edges", kind = ParameterKind.button, join = true,
                                                        doc = "Show the input body and pick the edges to blend (Enter accepts). Hole rims can be picked too."))
            self.add(specs, "all_edges", ParameterSpec(name = "all_edges", label = "All edges", kind = ParameterKind.button,
                                                       doc = "Forget the picked edges: blend every straight convex edge between flat faces."))
        # A sketch's dimensions, each a row in the document's unit (an
        # angle in degrees); its constraint is the row's slot.
        if kind == sketch_node.kind_name:
            for d in self.sketch_dimensions(path):
                let label = d.name + (" (driven)" if d.driven else "")
                if d.angle:
                    self.add(specs, "angle_dimension", ParameterSpec(name = d.name, label = label, value = degrees(d.value), minimum = -360.0, maximum = 360.0, step = 1.0, decimals = 2, suffix = "°",
                                                                    doc = "An angle the sketch holds; change it and the sketch follows."), d.constraint)
                else:
                    self.add(specs, "dimension", ParameterSpec(name = d.name, label = label, value = d.value, minimum = 0.0, maximum = 1000000.0, step = 1.0, decimals = 2, units = shown,
                                                              doc = "A length the sketch holds; change it and the sketch follows. Type any unit: 10 mm, 0.5 in."), d.constraint)
        if node_catalog.is_mesh_verb(kind):
            self.add(specs, "reselect", ParameterSpec(name = "reselect", label = "Reselect", kind = ParameterKind.button, join = true,
                                                      doc = "Show the input and pick the group's components again (Enter accepts)."))
            self.add(specs, "keep_ids", ParameterSpec(name = "keep_ids", label = "Keep IDs", kind = ParameterKind.button,
                                                      doc = "Use the group's numbers on the input's current topology."))
        self.parameters.set_specs(specs)
        self.show_ramps()

    ## An inspector row of the Edit node; `slot` is an operation's index.
    func add(self, specs: list[ParameterSpec], role: str, spec: ParameterSpec, slot: int = -1):
        specs.append(spec)
        self.rows.append(Parameter(spec.label, slot, 0.0))
        self.roles.append(role)

    pub func refresh(self) -> unit!:
        self.generic_rows.layout().set_visible(self.workspace.selected() != none)
        let node = self.workspace.selected() else return
        let changed = node.id != self.showing
        let file = node.kind == "File"
        let format = node_catalog.file_format(node.texts[0]) if file else ""
        let key = f"{node.kind}|{format}|{self.compose(node.texts, node.source_revision) if format == "usd" else ""}|{self.sketch_key(node.kind, node.texts[0])}|{node.texts[code_cook.spares_slot] + code_node.ramp_key(node) if node.kind in [code_cook.kind_name, script_cook.kind_name] else ""}|{self.workspace.network.units}"
        if key != self.built:
            self.build(node.kind, node.texts[0])
            self.built = key
        if changed:
            self.checker.stop()
            self.check_failure = ""
        self.showing = node.id
        self.state_rows.layout().set_visible(not file)
        let scripting = node.kind == script_cook.kind_name
        let coding = node.kind == code_cook.kind_name or scripting
        self.code_box.layout().set_visible(coding)
        # Ramp rows follow the node (an undo) unless one is being dragged.
        if coding and not self.workspace.in_transaction():
            self.show_ramps()
        if coding:
            if self.console.text() != node.console:
                self.console.set_text(node.console)
            self.console.layout().set_visible(node.console != "")
            self.header_title.layout().set_visible(not scripting)
            self.code_header.editor.layout().set_visible(not scripting)
            self.code_title.set_text("Script (runs once per cook, natively; imports any package)" if scripting else "Code (one element; it runs for all in parallel)")
            # Completion and hover read the Code node's API, or a script's
            # check package (its imports, checked in process).
            self.code_body.script_file = self.checker.prepare(node.texts[script_cook.packages_slot], node.texts[script_cook.lock_slot], self.workspace.network.folder) if scripting else ""
            # A Script's text is checked at a pause before it goes to the node.
            self.code_body.on_pause = (func (text: str) -> unit!: self.check_script(text)) if scripting else none
            if scripting:
                self.code_body.show(node.texts[script_cook.code_slot])
            else:
                let run_over = int(node.values[code_cook.run_over_slot])
                self.code_body.run_over = run_over
                self.code_header.run_over = run_over
                self.code_body.show(node.texts[code_cook.body_slot])
                self.code_header.show(node.texts[code_cook.header_slot])
            let message = self.check_failure if scripting and self.check_failure != "" else node.failure
            let place = code_node.failure_place(message)
            self.code_body.show_error(place[1] if place.length == 3 and place[0] == 0 else 0, place[2] if place.length == 3 else 0, (place[2] if place.length == 3 else 0) + 1, message)
            self.code_header.show_error(place[1] if place.length == 3 and place[0] == 1 else 0, place[2] if place.length == 3 else 0, (place[2] if place.length == 3 else 0) + 1, message)
        self.delete_button.layout().set_visible(not file)
        if changed or not self.name.layout().is_focused():
            self.name.set_text(node.name)
        let network = self.workspace.network
        self.kind.set_text(node.kind + (" · Out" if network.is_output(node.id) else " · internal") + (" · Auto" if node.output == 0 else "") + (" · preview" if network.preview and node.id == network.display else "") + ("" if node.enabled else " · bypassed") + (" · frozen" if node.frozen != "" else ""))
        # One line: a message from code may hold line breaks or tabs.
        self.description.set_text(one_line(node.failure if node.failure != "" else ("Warning: " + node.warning if node.warning != "" else node_catalog.description(node.kind))))
        self.description.layout().set_visible(not file or node.failure != "" or node.warning != "")
        self.parameters.layout().set_enabled(node.enabled or file)
        for index in 0..<self.rows.length:
            let role = self.roles[index]
            let row = self.rows[index]
            if role == "value":
                for component in 0..<row.components:
                    self.parameters.set_component(index, component, node.values[row.slot + component])
                # A shader node's linked input takes its link: its value waits.
                if is_shader(node.kind):
                    self.parameters.set_enabled(index, not linked_slot(node, row.slot))
            elif role == "text":
                # A selection too large to read as text shows as a summary
                # (the group itself stays exact); Reselect changes it.
                let text = node.texts[row.slot]
                let baked = row.name == "Group" and text.byte_count > 16384
                self.parameters.set_text(index, f"‹selection of {text.byte_count // 1024} KB›" if baked else text)
                self.parameters.set_enabled(index, not baked)
            elif role == "info":
                self.parameters.set_text(index, row.text)
            elif role == "edits":
                self.parameters.set_text(index, f"{node.edits.length} edits / {self.workspace.selected_count()} selected")
            elif role == "edges":
                self.parameters.set_text(index, cad_nodes.edges_summary(node.texts[0]))
            elif role == "all_edges" or role == "all_profiles":
                self.parameters.set_enabled(index, node.texts[0] != "")
            elif role == "face":
                self.parameters.set_text(index, node.texts[1] if node.texts[1] != "" else "None picked")
            elif role == "profiles":
                self.parameters.set_text(index, cad_nodes.profiles_summary(node.texts[0]))
            elif role == "clear":
                self.parameters.set_enabled(index, node.edits.length > 0)
            elif role == "keep_ids":
                self.parameters.set_enabled(index, node.guard != 0)
            elif role == "dimension" or role == "angle_dimension":
                for d in self.sketch_dimensions(node.texts[0]):
                    if d.constraint == row.slot:
                        self.parameters.set_value(index, degrees(d.value) if d.angle else d.value)
                        self.parameters.set_enabled(index, not d.driven)
        if node_catalog.places_children(node.kind):
            self.stats.set_text(f"{network.outputs(node.id).length} exposed children")
        elif self.workspace.compute != none:
            self.stats.set_text(node.phase if node.computing else node.summary)
        elif let data = node.cache:
            self.stats.set_text(data.description())
        else:
            self.stats.set_text("No evaluated geometry")

    ## Compose a USD File node's stage when its file, texts or revision
    ## changed (a failure shows as the node's cook error); the key composed.
    func compose(self, texts: list[str], revision: int) -> str:
        let key = f"{texts[0].trim()}|{texts[1]}|{texts[2]}|{revision}"
        if key != self.stage_key:
            self.stage_key = key
            self.stage = none
            let composed = compose_usd(texts[0].trim(), texts) catch failure:
                return key
            self.stage = composed
        return key

    ## Sketch text `text`'s dimensions (none when it does not read).
    func sketch_dimensions(self, text: str) -> list[SketchDimension]:
        if text != self.dimensions_text:
            self.dimensions_text = text
            self.dimensions = sketch_commands.dimensions(text) catch failure:
                recover []
        return self.dimensions

    ## What a Sketch node's dimension rows depend on: which constraints are
    ## dimensions (their values refresh in place).
    func sketch_key(self, kind: str, text: str) -> str:
        if kind != sketch_node.kind_name:
            return ""
        let parts: list[str] = []
        for d in self.sketch_dimensions(text):
            parts.append(f"{d.constraint}{"a" if d.angle else ""}{"d" if d.driven else ""}")
        return parts.join(",")

    ## The ramp rows show their data: a Code or Script node's ramps, a verb
    ## node's ramp texts (Volume Visualization's emission color ramp).
    func show_ramps(self) -> unit!:
        let node = self.workspace.selected() else return
        let coded = node.kind in [code_cook.kind_name, script_cook.kind_name]
        let ramps = code_cook.ramps_of(node.texts[code_cook.ramps_slot]) if coded else []
        for index in 0..<self.rows.length:
            if self.roles[index] != "ramp":
                continue
            let slot = self.rows[index].slot
            if coded and slot >= ramps.length:
                continue
            let data = ramps[slot].data if coded else node_catalog.verb_ramp(node.kind, slot, node.texts[slot])
            if self.parameters.ramp(index) != data:
                self.parameters.set_ramp(index, data)

    ## A Code editor's text, to the selected Code node.
    func code_committed(self, slot: int, text: str) -> unit!:
        let node = self.workspace.selected() else return
        self.check_failure = ""
        if node.kind == code_cook.kind_name:
            code_node.set_code(self.workspace, node.id, slot, text)
        elif node.kind == script_cook.kind_name and slot == code_cook.body_slot:
            script_node.set_code(self.workspace, node.id, text)

    ## Each frame: the code editors commit when typing pauses, and a Script's
    ## check reports.
    pub func poll(self) -> unit!:
        self.code_body.poll()
        self.code_header.poll()
        if self.checker.poll():
            # Only an error in the code holds the text back; anything else (a
            # package that cannot be found) is the build's to report.
            let place = code_node.failure_place(self.checker.failure)
            self.check_failure = self.checker.failure if place.length == 3 else ""
            if self.check_failure == "":
                self.code_body.checked(self.checker.text)
            else:
                self.code_body.show_error(place[1], place[2], place[2] + 1, self.check_failure)

    ## Check the selected Script node's `text` with its packages.
    func check_script(self, text: str) -> unit!:
        let node = self.workspace.selected() else return
        self.checker.start(text, node.texts[script_cook.packages_slot], node.texts[script_cook.lock_slot], self.workspace.network.folder)

    pub func close(self):
        self.checker.stop()
        self.code_body.close()
        self.code_header.close()
        self.on_browse = none
        self.on_render = none
        for connection in self.connections:
            connection.disconnect()
        self.connections.clear()

## Whether the shader input kept in value slot `slot` is linked.
func linked_slot(node: Node, slot: int) -> bool:
    let sockets = shader_inputs(node.kind)
    for port in 0..<sockets.length:
        if sockets[port].slot == slot and port < node.inputs.length and node.inputs[port] >= 0:
            return true
    return false

## `text` on one line: line breaks and tabs as spaces (a Text holds one).
func one_line(text: str) -> str:
    return text.replace("\r", " ").replace("\n", " ").replace("\t", " ")