Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.3

0.11.3 / src / code_node.luc

## The Code node (Houdini's Attribute Wrangle, in Luce Base): its body runs
## for one element at a time (a point, primitive or vertex, or the detail
## once, or n numbers) and luce-kernel runs it for every element in
## parallel (luce-geocore's Code). Texts: 0 the group, 1 the body, 2 the
## header (helper functions above the generated entry), 3 the spare
## parameters' slots. Values: 0 Run Over, 1 Numbers' count, the group type
## at node_catalog.group_type_slot, the spare parameters from
## first_spare_slot on.
##
## A spare parameter is a literal `k.f32("amount", 0.2)` (or f64, i32,
## vec3...) in the code: each name gets a value row, its slots kept by name
## while the code changes, so a tuned value survives edits. The Script node
## (script_node.luc) places its rows, ramps and failures with the same calls.
from luce_geocore.geocore import Code
from network import Node
from code_cook import Spare, spares_of, spares_text, value_count, first_spare_slot, first_text_slot, text_slots, run_over_slot, body_slot, header_slot, spares_slot, Ramp, ramps_of, ramps_text, ramps_slot, default_ramp
from workspace import Workspace
from parameter_rows import Parameter, number, whole, vector, toggle, menu, entry

## Put `text` in slot `slot` (the body or the header) as one undo step;
## the parameters the code names become rows, and the node follows the
## timeline when the code reads it.
pub func set_code(w: Workspace, id: int, slot: int, text: str) -> unit!:
    let node = w.network.find(id) else return
    if node.texts[slot] == text:
        return
    w.perform("Edit code", func () -> unit!:
        node.texts[slot] = text
        refresh(node)
        w.network.invalidate(node.id)
        w.rebuild())

## Read the code's parameters and time use again (a code that does not
## check keeps its rows, so typing does not lose them).
pub func refresh(node: Node) -> unit!:
    let check = Code.check(int(node.values[run_over_slot]), node.texts[header_slot], node.texts[body_slot])
    if not check.ok():
        return
    node.time_dependent = check.reads_time()
    let wanted: list[Wanted] = []
    for i in 0..<check.parameter_count():
        let row = Wanted(check.parameter_name(i), check.parameter_components(i), check.parameter_integer(i))
        row.ramp = check.parameter_ramp(i)
        for c in 0..<row.components:
            row.defaults.append(check.parameter_default(i, c))
        wanted.append(row)
    place(node, wanted)

## A spare parameter a node's code names (Code and Script nodes): its
## name, components and row kind, defaults, a text default and a menu's
## choices; `ramp` its channels when it is a ramp (1 float, 3 color).
pub class Wanted:
    pub let name: str
    pub let components: int
    pub let integer: bool
    pub var kind: str = ""
    pub var defaults: list[float]
    pub var text: str = ""
    pub var choices: str = ""
    pub var ramp: int = 0

    pub func init(self, name: str, components: int, integer: bool):
        self.name = name
        self.components = components
        self.integer = integer
        self.defaults = []

## Give `node` rows for the `wanted` parameters: a name the node already
## has keeps its slot (and value) when its shape is the same; a new one
## takes free slots at its defaults. Ramps keep their data by name and kind.
pub func place(node: Node, wanted: list[Wanted]) -> unit!:
    let old_ramps = ramps_of(node.texts[ramps_slot])
    let ramps: list[Ramp] = []
    for w in wanted:
        if w.ramp == 0:
            continue
        var data = default_ramp(w.ramp)
        for r in old_ramps:
            if r.name == w.name and r.channels == w.ramp:
                data = r.data
        ramps.append(Ramp(w.name, w.ramp, data))
    node.texts[ramps_slot] = ramps_text(ramps)
    let old = spares_of(node.texts[spares_slot])
    let placed: list[Spare] = []
    let fresh: list[Wanted] = []
    for w in wanted:
        if w.ramp != 0:
            continue
        var slot = -1
        for s in old:
            if s.name == w.name and s.components == w.components and s.textual() == (w.kind in ["text", "file"]):
                slot = s.slot
        if slot >= 0:
            placed.append(Spare(w.name, slot, w.components, w.integer, w.kind, w.choices))
        else:
            fresh.append(w)
    # New names take free slots, at their defaults.
    for w in fresh:
        let textual = w.kind in ["text", "file"]
        let slot = free_text_slot(placed) if textual else free_slot(placed, w.components)
        if slot < 0:
            continue
        placed.append(Spare(w.name, slot, w.components, w.integer, w.kind, w.choices))
        if textual:
            node.texts[slot] = w.text
        for c in 0..<w.components:
            node.values[slot + c] = w.defaults[c] if c < w.defaults.length else 0.0
    node.texts[spares_slot] = spares_text(placed)

## The first run of `components` value slots no spare holds, or -1.
func free_slot(spares: list[Spare], components: int) -> int:
    var slot = first_spare_slot
    while slot + components <= value_count:
        var clear = true
        for s in spares:
            if not s.textual() and slot < s.slot + s.components and s.slot < slot + components:
                clear = false
        if clear:
            return slot
        slot += 1
    return -1

## The first text slot no text or file parameter holds, or -1.
func free_text_slot(spares: list[Spare]) -> int:
    for slot in first_text_slot..<first_text_slot + text_slots:
        var clear = true
        for s in spares:
            if s.textual() and s.slot == slot:
                clear = false
        if clear:
            return slot
    return -1

## The rows the inspector shows for the spares, then the ramps (a ramp
## row's slot is its index among the ramps).
pub func spare_rows(node: Node) -> list[Parameter]:
    let rows: list[Parameter] = []
    let ramps = ramps_of(node.texts[ramps_slot])
    for at in 0..<ramps.length:
        let row = Parameter(ramps[at].name, at, 0.0, 0.0, 1.0)
        row.kind = "color_ramp" if ramps[at].channels == 3 else "ramp"
        row.doc = f"A ramp of the code: k.{"ramp_color" if ramps[at].channels == 3 else "ramp"}(\"{ramps[at].name}\", t)."
        rows.append(row)
    for s in spares_of(node.texts[spares_slot]):
        let call = s.kind if s.kind != "" else ("i32" if s.integer else ("vec3" if s.components > 1 else "f32"))
        let doc = f"A parameter of the code: k.{call}(\"{s.name}\", …)."
        if s.textual():
            rows.append(entry(s.name, s.slot, doc, "path" if s.kind == "file" else "text"))
        elif s.kind == "toggle":
            rows.append(toggle(s.name, s.slot, node.values[s.slot], doc))
        elif s.kind == "menu":
            rows.append(menu(s.name, s.slot, s.choices, node.values[s.slot], doc))
        elif s.components > 1:
            let defaults: list[float] = []
            for c in 0..<s.components:
                defaults.append(node.values[s.slot + c])
            let row = vector(s.name, s.slot, defaults, doc)
            if s.kind == "color":
                row.kind = "color"
            rows.append(row)
        elif s.integer:
            rows.append(whole(s.name, s.slot, node.values[s.slot], -1000000.0, 1000000.0, doc))
        else:
            rows.append(number(s.name, s.slot, node.values[s.slot], -1000000.0, 1000000.0, 0.01, doc, soft = 10.0))
    return rows

## What the inspector's ramp rows depend on: the ramps' names and kinds.
pub func ramp_key(node: Node) -> str:
    let parts: list[str] = []
    for r in ramps_of(node.texts[ramps_slot]):
        parts.append(f"{r.name}:{r.channels}")
    return parts.join(",")

## Ramp `index` of Code node `id` now holds `data` (a ramp row's edit, in
## the undo step the panel's begin/commit bracket).
pub func set_ramp(w: Workspace, id: int, index: int, data: list[float]) -> unit!:
    let node = w.network.find(id) else return
    let ramps = ramps_of(node.texts[ramps_slot])
    if index < 0 or index >= ramps.length:
        return
    ramps[index] = Ramp(ramps[index].name, ramps[index].channels, data)
    node.texts[ramps_slot] = ramps_text(ramps)
    w.network.invalidate(node.id)
    w.rebuild()

## Where a cook failure points: [part (0 body, 1 header), line, column], or
## [] when it names no line ("line 7, column 3: …", "header line 2, …").
pub func failure_place(message: str) -> list[int]:
    # Cook failures carry the node's name first ("Code 3: line 2, …").
    var part = 0
    var text = message
    if let at = message.index_of("header line "):
        part = 1
        text = message[at + 7..]
    elif let at = message.index_of("line "):
        text = message[at..]
    else:
        return []
    let comma = text.index_of(", column ") else return []
    let line = int(text[5..<comma]) catch failure:
        recover 0
    let rest = text[comma + 9..]
    let colon = rest.index_of(":") else return []
    let column = int(rest[..<colon]) catch failure:
        recover 0
    if line <= 0 or column <= 0:
        return []
    return [part, line, column]