Files
qlcplus/scripts/make_chataigne.py
T
2026-10-22 11:44:19 +13:00

326 lines
14 KiB
Python

#!/usr/bin/env python3
"""Write a Chataigne project from a show spec.
python3 scripts/make_chataigne.py shows/test.show.json chataigne/test
Writes <out>/<name>.noisette and <out>/<name>.js. The script holds the scenes and
the pad and slider mapping, and sends DMX through the project's DMX module, named Lights, and a copy to Preview. Solo
frames and scene fades follow what QLC+ does with the same spec.
"""
from __future__ import annotations
import argparse
import json
import struct
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TEMPLATE = ROOT / "chataigne" / "show.template.js"
def absolute_levels(show: dict, stage: dict, values: dict[str, dict[str, int]]) -> dict[int, int]:
"""Map a scene's fixture channels to 1-based DMX channels in the output universe."""
levels: dict[int, int] = {}
for key, channels in values.items():
fixture = stage["fixtures"][key]
for offset, level in channels.items():
levels[int(fixture["address"]) + int(offset) + 1] = int(level)
return levels
SCALE = 1.25
MARGIN = 10
BUTTON = 28
def clear_png() -> bytes:
"""A 4x4 fully transparent PNG, for a trigger that should show what is behind it."""
def chunk(kind: bytes, data: bytes) -> bytes:
body = kind + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
rows = b"".join(b"\x00" + b"\x00" * 16 for _ in range(4))
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows))
+ chunk(b"IEND", b"")
)
def script_path(name: str) -> str:
"""Chataigne names the script after its file and the module after its title."""
return f"/modules/pad/scripts/{name}/params/"
def ident(prefix: str, number: int, name: str) -> str:
"""A control name Chataigne keeps as written: letters and digits, lower-case first."""
return f"{prefix}{number}" + "".join(c for c in name if c.isalnum())
def collect(show: dict, stage: dict) -> dict:
functions = {f["key"]: f for f in show["functions"]}
groups: dict[str, dict] = {}
for number, frame in enumerate(show["vc"], 1):
pads, sliders = [], []
for widget in frame.get("children", []):
kind = widget["type"]
function = functions[widget["function"]]
binding = widget.get("input") or {}
levels = absolute_levels(show, stage, function["values"])
if kind == "button" and "note" in binding:
pads.append({
"id": ident("c", number, widget["caption"]),
"box": box(frame, widget),
"bg": widget.get("bg", [60, 60, 60]),
"fg": widget.get("fg", [255, 255, 255]),
"note": binding["note"][1],
"name": widget["caption"],
"fade": [function.get("fade_in") or 0, function.get("fade_out") or 0],
"levels": levels,
})
elif kind == "slider" and "cc" in binding:
sliders.append({
"id": ident("s", number, widget["caption"]),
"box": box(frame, widget),
"fg": widget.get("fg", [255, 255, 255]),
"cc": binding["cc"][1],
"name": widget["caption"],
"levels": levels,
})
if pads or sliders:
groups[frame["caption"]] = {
"name": frame["caption"],
"now": f"now{number}",
"box": box(frame, {"x": 0, "y": -30, "w": frame["w"], "h": 26}),
"pads": pads,
"sliders": sliders,
}
return groups
def box(frame: dict, widget: dict) -> list[int]:
"""x, y, w, h of a widget on the dashboard. Frames sit side by side, as on the virtual console."""
return [round((frame["x"] + widget["x"]) * SCALE), round((frame["y"] + widget["y"]) * SCALE + 40),
round(widget["w"] * SCALE), round(widget["h"] * SCALE)]
def colour(rgb: list[int]) -> int:
"""A Chataigne colour value: ARGB as a signed 32-bit int."""
argb = (255 << 24) | (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]
return argb - (1 << 32) if argb >= 1 << 31 else argb
def js_levels(levels: dict[int, int]) -> str:
return "[" + ",".join(f"{ch},{level}" for ch, level in sorted(levels.items())) + "]"
def render_data(groups: dict) -> str:
lines = ["var GROUPS = ["]
for caption, group in groups.items():
lines.append(" {")
lines.append(f" name: {json.dumps(caption)},")
lines.append(f" now: {json.dumps(group['now'])},")
lines.append(" pads: [")
for pad in group["pads"]:
lines.append(
f" {{id: {json.dumps(pad['id'])}, rgb: {json.dumps([round(c / 255, 3) for c in pad['bg']])}, note: {pad['note']}, name: {json.dumps(pad['name'])}, "
f"fadeIn: {pad['fade'][0]}, fadeOut: {pad['fade'][1]}, levels: {js_levels(pad['levels'])}}},"
)
lines.append(" ],")
lines.append(" sliders: [")
for slider in group["sliders"]:
lines.append(
f" {{id: {json.dumps(slider['id'])}, cc: {slider['cc']}, name: {json.dumps(slider['name'])}, levels: {js_levels(slider['levels'])}}},"
)
lines.append(" ]")
lines.append(" },")
lines.append("];")
return "\n".join(lines)
def dashboard_item(index: int, kind: str, target: str, box: list[int], label: str, colours: dict[str, list[int]]) -> dict:
parameters = [
{"value": [float(box[0]), float(box[1])], "controlAddress": "/viewUIPosition"},
{"value": [float(box[2]), float(box[3])], "controlAddress": "/viewUISize"},
{"value": target, "controlAddress": "/target"},
{"value": label, "controlAddress": "/customText", "enabled": True},
]
for address, rgb in colours.items():
parameters.append({"value": colour(rgb), "controlAddress": address, "enabled": True})
return {
"parameters": parameters,
"niceName": f"Item {index}",
"type": kind,
"ghostAddress": target,
"controllable": target,
}
def dashboard(groups: dict, name: str, view: tuple[int, int], overlay: str | None) -> dict:
"""A dashboard with a tile and button per pad, a slider per knob, and what each group is showing."""
items = []
for group in groups.values():
items.append(dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + group["now"],
group["box"], group["name"], {},
))
for pad in group["pads"]:
x, y, w, h = pad["box"]
# Triggers draw grey whatever colour they are given, but a colour control always paints.
# The tile carries the colour and name; the trigger on it is a transparent image that takes the press.
small = overlay is None
tile = dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + pad["id"] + "Lamp",
[x, y, w, h - BUTTON - 2 if small else h], pad["name"], {"/textColor": [255, 255, 255]},
)
tile["parameters"] += [
{"value": True, "controlAddress": "/readOnly"},
{"value": False, "controlAddress": "/showValue"},
]
items.append(tile)
press = dashboard_item(
len(items) + 1, "DashboardTriggerItem", script_path(name) + pad["id"],
[x, y + h - BUTTON, w, BUTTON] if small else [x, y, w, h], "Select" if small else "",
{"/backgroundColor": pad["bg"], "/textColor": pad["fg"]},
)
if overlay:
# A custom label that is a single space: with none, the trigger draws its own name.
press["parameters"][3].update({"value": " ", "enabled": True})
press["parameters"].append({"value": False, "controlAddress": "/showLabel"})
press["parameters"].append({"value": overlay, "controlAddress": "/customImage", "enabled": True})
items.append(press)
for slider in group["sliders"]:
items.append(dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + slider["id"], slider["box"], slider["name"],
{"/foregroundColor": slider["fg"]},
))
# Dashboard coordinates start at the middle of the view, so move the board to its top left.
left = min(i["parameters"][0]["value"][0] for i in items)
top = min(i["parameters"][0]["value"][1] for i in items)
for i in items:
position = i["parameters"][0]["value"]
position[0] += MARGIN - view[0] / 2 - left
position[1] += MARGIN - view[1] / 2 - top
return {
"parameters": [{"value": False, "controlAddress": "/editMode"}],
"items": [
{
"niceName": "Board",
"type": "BaseItem",
"itemManager": {
# The web page puts the middle of the canvas at 0, 0, so the canvas has to be the view's size
# for the board to start at its top left.
"parameters": [{"value": [float(view[0]), float(view[1])], "controlAddress": "/canvasSize", "enabled": True}],
"items": items,
"viewOffset": [0, 0],
"viewZoom": 1.0,
},
}
],
"viewOffset": [0, 0],
"viewZoom": 1.0,
}
def dmx_module(name: str, host: str, universe: int, interface: str | None) -> dict:
device: dict = {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}}
if interface:
device["parameters"] = [{"value": interface, "controlAddress": "/networkInterface"}]
return {
"niceName": name,
"type": "DMX",
"params": {
"parameters": [
{"value": "Art-Net", "controlAddress": "/dmxType"},
{"value": 40, "controlAddress": "/sendRate"},
],
"containers": {
"artNet": {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}},
"outputUniverses": {
"items": [
{
"niceName": "Universe",
"parameters": [
{"value": 0, "controlAddress": "/net"},
{"value": 0, "controlAddress": "/subnet"},
{"value": universe, "controlAddress": "/universe"},
],
}
]
}
},
},
"device": device,
}
def project(
script: str, host: str, universe: int, interface: str, groups: dict, preview: str | None, pad: str, view: tuple[int, int], overlay: str | None
) -> dict:
"""A Chataigne project: a DMX module on Art-Net and a MIDI module that runs the show script."""
dmx = [dmx_module("Lights", host, universe, interface)]
if preview:
dmx.append(dmx_module("Preview", preview, universe, None))
midi = {
"niceName": "Pad",
"type": "MIDI",
"params": {"parameters": [{"value": [pad, ""], "inputName": pad, "controlAddress": "/devices"}]},
"scripts": {
"items": [{"niceName": "Show", "parameters": [{"value": script, "controlAddress": "/filePath"}]}]
},
}
return {
"metaData": {"version": "1.10.4"},
"projectSettings": {
"containers": {
"dashboardSettings": {
"parameters": [
{"value": True, "controlAddress": "/enableDashboardServer"},
{"value": 9999, "hexMode": False, "controlAddress": "/serverPort"},
]
}
}
},
"dashboardManager": dashboard(groups, Path(script).stem, view, overlay),
"modules": {"viewOffset": [0, 0], "viewZoom": 1.0, "items": [*dmx, midi]},
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("show", type=Path)
parser.add_argument("out", type=Path, help="directory to write into")
parser.add_argument("--host", help="Art-Net destination (default: from the show's output universe)")
parser.add_argument("--pad", default="SINCO SMC-PAD-Master", help="MIDI input the pad arrives on (Bluetooth: SMC-PAD Bluetooth)")
parser.add_argument("--view", default="1574x953", help="dashboard panel size in pixels, for the top-left placement")
parser.add_argument("--small-buttons", action="store_true", help="a grey Select button under each tile, instead of the whole tile pressing")
parser.add_argument("--preview", default="127.0.0.1", help="second Art-Net destination for the simulator; empty for none")
args = parser.parse_args()
show = json.loads(args.show.read_text())
stage = json.loads((ROOT / show["stage"]).read_text())
output = next(u["output"] for u in show["universes"] if u.get("output", {}).get("plugin") == "ArtNet")
name = args.show.name.removesuffix(".show.json")
groups = collect(show, stage)
source = TEMPLATE.read_text().replace("/*__DATA__*/", render_data(groups))
args.out.mkdir(parents=True, exist_ok=True)
(args.out / f"{name}.js").write_text(source)
overlay = None if args.small_buttons else str((args.out / "clear.png").resolve())
if overlay:
(args.out / "clear.png").write_bytes(clear_png())
doc = project(f"{name}.js", args.host or output["ip"], int(output["universe"]), output["uid"], groups, args.preview or None, args.pad, tuple(int(n) for n in args.view.split("x")), overlay)
(args.out / f"{name}.noisette").write_text(json.dumps(doc, indent=2) + "\n")
print(f"{args.out / (name + '.noisette')}: {len(groups)} groups, {sum(len(g['pads']) for g in groups.values())} pads")
if __name__ == "__main__":
main()