Add Pattern Studio, SMC-PAD MIDI helpers, and the current venue workspaces.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jimmyandCursor committed 2026-10-20 15:05:04 +13:00
1 parent 55a38478db
commit 12420bec93
19 files changed
+8954

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
"""Mover Pattern Studio — design pan/tilt patterns and write them into QLC+ workspaces.
Run with: python3 -m patternstudio
"""
__version__ = "0.1.0"
+41
View File
@@ -0,0 +1,41 @@
"""python3 -m patternstudio [--port 8765] [--root .] [--no-browser]"""
from __future__ import annotations
import argparse
import sys
import threading
import webbrowser
from pathlib import Path
from .server import make_server
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="patternstudio", description="Mover Pattern Studio for QLC+ workspaces")
p.add_argument("--root", default=str(Path(__file__).resolve().parents[1]), help="Project root (contains shows/, fixtures/)")
p.add_argument("--host", default="127.0.0.1")
p.add_argument("--port", type=int, default=8765)
p.add_argument("--no-browser", action="store_true", help="Do not open the browser")
args = p.parse_args(argv)
root = Path(args.root).resolve()
if not (root / "shows").is_dir():
print(f"warning: {root / 'shows'} does not exist — no workspaces will be listed", file=sys.stderr)
server = make_server(root, args.host, args.port)
url = f"http://{args.host}:{args.port}/"
print(f"Mover Pattern Studio → {url} (root {root}) Ctrl+C to quit")
if not args.no_browser:
threading.Timer(0.4, webbrowser.open, args=(url,)).start()
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.studio.live.stop() # type: ignore[attr-defined]
server.server_close()
return 0
if __name__ == "__main__":
sys.exit(main())
+119
View File
@@ -0,0 +1,119 @@
"""Minimal Art-Net output + a background runner that plays a pattern on the real heads."""
from __future__ import annotations
import socket
import threading
import time
from typing import Any
from .efx import Efx, Path as PathPattern, clamp8
from .qxw import Workspace
ARTNET_PORT = 6454
_HEADER = b"Art-Net\x00"
_OP_DMX = 0x5000
def build_artdmx(frame: bytes, universe: int, sequence: int) -> bytes:
data = bytearray(frame[:512])
if len(data) & 1:
data.append(0)
n = len(data)
pkt = bytearray(18 + n)
pkt[0:8] = _HEADER
pkt[8:10] = bytes((_OP_DMX & 0xFF, _OP_DMX >> 8))
pkt[10], pkt[11] = 0, 14
pkt[12] = sequence & 0xFF
pkt[13] = 0
pkt[14] = universe & 0xFF
pkt[15] = (universe >> 8) & 0x7F
pkt[16], pkt[17] = (n >> 8) & 0xFF, n & 0xFF
pkt[18:] = data
return bytes(pkt)
class LivePreview:
"""Runs one pattern at a time, ~40 Hz, until stopped. Thread-safe."""
def __init__(self):
self._lock = threading.Lock()
self._thread: threading.Thread | None = None
self._stop = threading.Event()
self.status: dict[str, Any] = {"running": False}
def start(self, ws: Workspace, pattern: Efx | PathPattern, ip: str, universe: int, hz: float = 40.0):
self.stop()
movers = {f.id: f for f in ws.fixtures if f.is_mover}
# Universe → frame; static channel values that light the head.
frames: dict[int, bytearray] = {}
for fx in pattern.fixtures:
f = movers[fx.id]
frame = frames.setdefault(f.universe, bytearray(512))
for ch, v in f.mode.preview_channels().items(): # type: ignore[union-attr]
if f.address + ch < 512:
frame[f.address + ch] = v
# QLC+ Art-Net plugin sends each QLC+ universe as `universe` + offset; we
# mirror that: QLC+ universe N goes to Art-Net universe (base + N - first).
base_uni = universe
first_uni = min(frames) if frames else 0
self._stop.clear()
self.status = {
"running": True,
"ip": ip,
"universe": universe,
"fixtures": [fx.id for fx in pattern.fixtures],
"kind": "efx" if isinstance(pattern, Efx) else "path",
}
def run():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
seq = 1
period = 1.0 / hz
t0 = time.monotonic()
try:
while not self._stop.is_set():
elapsed_ms = (time.monotonic() - t0) * 1000.0
for serial, fx in enumerate(pattern.fixtures):
f = movers[fx.id]
m = f.mode
pt = pattern.live_point(serial, elapsed_ms)
if pt is None or m is None:
continue
pan, tilt = pt
frame = frames[f.universe]
if m.pan_msb is not None:
frame[f.address + m.pan_msb] = clamp8(pan)
if m.tilt_msb is not None:
frame[f.address + m.tilt_msb] = clamp8(tilt)
if m.pan_lsb is not None:
frame[f.address + m.pan_lsb] = clamp8((pan - int(pan)) * 255)
if m.tilt_lsb is not None:
frame[f.address + m.tilt_lsb] = clamp8((tilt - int(tilt)) * 255)
for uni, frame in frames.items():
sock.sendto(build_artdmx(bytes(frame), base_uni + (uni - first_uni), seq), (ip, ARTNET_PORT))
seq = 1 if seq >= 255 else seq + 1
time.sleep(period)
# Blackout the channels we touched so the heads do not stay lit.
for uni, frame in frames.items():
for _ in range(3):
sock.sendto(build_artdmx(bytes(512), base_uni + (uni - first_uni), seq), (ip, ARTNET_PORT))
time.sleep(period)
finally:
sock.close()
with self._lock:
self.status = {"running": False}
with self._lock:
self._thread = threading.Thread(target=run, daemon=True)
self._thread.start()
def stop(self):
self._stop.set()
t = self._thread
if t and t.is_alive():
t.join(timeout=2.0)
self._thread = None
with self._lock:
self.status = {"running": False}
+418
View File
@@ -0,0 +1,418 @@
"""Pattern maths.
`EFX*` is a faithful port of QLC+ 4.12 `EFX::calculatePoint` / `rotateAndScale`
/ `EFXFixture::timeOffset`, so the preview here matches what QLC+ renders.
`Path*` samples a list of waypoints (optionally Catmull-Rom smoothed) into
keyframes that become a QLC+ Sequence.
Both produce the same output shape — a list of per-fixture keyframe tracks —
so the browser preview and the live Art-Net preview share one code path.
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
from typing import Any
ALGORITHMS = (
"Circle",
"Eight",
"Line",
"Line2",
"Diamond",
"Square",
"SquareChoppy",
"Leaf",
"Lissajous",
)
DIRECTIONS = ("Forward", "Backward")
RUN_ORDERS = ("Loop", "SingleShot", "PingPong")
PROPAGATIONS = ("Parallel", "Serial", "Asymmetric")
RELATIVE_ZERO = 127
PREVIEW_STEPS = 128 # same as EFX::preview
def clamp(v: float, lo: float = 0, hi: float = 255) -> float:
return max(lo, min(hi, v))
def clamp8(v: float) -> int:
return int(clamp(round(v)))
# --------------------------------------------------------------------------- EFX
@dataclass
class EfxFixture:
id: int
head: int = 0
direction: str = "Forward"
start_offset: int = 0
# Only used when `relative` is on: absolute home aim written to the base Scene.
pan: int = 128
tilt: int = 128
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "EfxFixture":
return cls(
id=int(d["id"]),
head=int(d.get("head", 0)),
direction="Backward" if d.get("direction") == "Backward" else "Forward",
start_offset=int(d.get("start_offset", 0)) % 360,
pan=clamp8(d.get("pan", 128)),
tilt=clamp8(d.get("tilt", 128)),
)
@dataclass
class Efx:
algorithm: str = "Circle"
width: int = 40
height: int = 40
rotation: int = 0
start_offset: int = 0
x_offset: int = 128
y_offset: int = 128
x_frequency: int = 1
y_frequency: int = 1
x_phase: int = 0
y_phase: int = 0
duration_ms: int = 8000
fade_in_ms: int = 0
fade_out_ms: int = 0
direction: str = "Forward"
run_order: str = "Loop"
propagation: str = "Parallel"
relative: bool = False
fixtures: list[EfxFixture] = field(default_factory=list)
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "Efx":
alg = d.get("algorithm", "Circle")
if alg not in ALGORITHMS:
raise ValueError(f"unknown algorithm {alg!r}")
return cls(
algorithm=alg,
width=int(clamp(int(d.get("width", 40)), 0, 127)),
height=int(clamp(int(d.get("height", 40)), 0, 127)),
rotation=int(d.get("rotation", 0)) % 360,
start_offset=int(d.get("start_offset", 0)) % 360,
x_offset=clamp8(d.get("x_offset", 128)),
y_offset=clamp8(d.get("y_offset", 128)),
x_frequency=int(clamp(int(d.get("x_frequency", 1)), 0, 5)),
y_frequency=int(clamp(int(d.get("y_frequency", 1)), 0, 5)),
x_phase=int(d.get("x_phase", 0)) % 360,
y_phase=int(d.get("y_phase", 0)) % 360,
duration_ms=max(20, int(d.get("duration_ms", 8000))),
fade_in_ms=max(0, int(d.get("fade_in_ms", 0))),
fade_out_ms=max(0, int(d.get("fade_out_ms", 0))),
direction=d.get("direction") if d.get("direction") in DIRECTIONS else "Forward",
run_order=d.get("run_order") if d.get("run_order") in RUN_ORDERS else "Loop",
propagation=d.get("propagation") if d.get("propagation") in PROPAGATIONS else "Parallel",
relative=bool(d.get("relative", False)),
fixtures=[EfxFixture.from_dict(f) for f in d.get("fixtures", [])],
)
# -- QLC+ port ---------------------------------------------------------
def _direction_iterator(self, fixture_dir: str, it: float) -> float:
if fixture_dir == self.direction:
return it
if self.algorithm == "Line":
return it - math.pi if it > math.pi else it + math.pi
return 2.0 * math.pi - it
def _raw_point(self, it: float) -> tuple[float, float]:
a = self.algorithm
if a == "Circle":
return math.cos(it + math.pi / 2), math.cos(it)
if a == "Eight":
return math.cos(it * 2 + math.pi / 2), math.cos(it)
if a == "Line":
return math.cos(it), math.cos(it)
if a == "Line2":
v = it / math.pi - 1
return v, v
if a == "Diamond":
return math.cos(it - math.pi / 2) ** 3, math.cos(it) ** 3
if a == "Square":
h = math.pi / 2
if it < h:
return (it * 2 / math.pi) * 2 - 1, 1.0
if it < math.pi:
return 1.0, (1 - (it - h) * 2 / math.pi) * 2 - 1
if it < math.pi * 1.5:
return (1 - (it - math.pi) * 2 / math.pi) * 2 - 1, -1.0
return -1.0, ((it - math.pi * 1.5) * 2 / math.pi) * 2 - 1
if a == "SquareChoppy":
return float(round(math.cos(it))), float(round(math.sin(it)))
if a == "Leaf":
return math.cos(it + math.pi / 2) ** 5, math.cos(it)
if a == "Lissajous":
return (
self._lissajous_axis(it, self.x_frequency, math.radians(self.x_phase)),
self._lissajous_axis(it, self.y_frequency, math.radians(self.y_phase)),
)
raise ValueError(a)
@staticmethod
def _lissajous_axis(it: float, freq: int, phase: float) -> float:
if freq > 0:
return math.cos(freq * it - phase)
# Frequency 0 = triangle wave (QLC+ "linear" axis).
it0 = (it + phase) / math.pi
fff = int(it0)
it0 -= fff - fff % 2
forward = 1 - math.floor(it0)
backward = 1 - forward
it0 -= math.floor(it0)
return (forward * it0 + backward * (1 - it0)) * 2 - 1
def point(self, fixture_dir: str, fixture_offset: int, it: float) -> tuple[float, float]:
"""Pan/tilt (0–255 float) for iterator `it` in 0..2π — EFX::calculatePoint."""
it = self._direction_iterator(fixture_dir, it)
it += math.radians((fixture_offset + self.start_offset) % 360)
if it >= 2 * math.pi:
it -= 2 * math.pi
x, y = self._raw_point(it)
r = math.radians(self.rotation)
c, s = math.cos(r), math.sin(r)
px = self.x_offset + x * c * self.width + y * s * self.height
py = self.y_offset + -x * s * self.width + y * c * self.height
return clamp(px), clamp(py)
def time_offset_ms(self, serial: int) -> int:
if self.propagation in ("Serial", "Asymmetric"):
return self.duration_ms // (len(self.fixtures) + 1) * serial
return 0
def sample(self, steps: int = PREVIEW_STEPS) -> dict[str, Any]:
tracks = []
for serial, fx in enumerate(self.fixtures):
pts = []
for i in range(steps):
it = 2 * math.pi * i / steps
px, py = self.point(fx.direction, fx.start_offset, it)
pts.append([round(px, 2), round(py, 2)])
tracks.append(
{
"id": fx.id,
"head": fx.head,
"points": pts,
# Asymmetric: shifted in phase, starts immediately.
# Serial: shifted in phase AND waits before starting.
"time_offset_ms": self.time_offset_ms(serial),
"start_delay_ms": self.time_offset_ms(serial) if self.propagation == "Serial" else 0,
}
)
return {
"kind": "efx",
"loop_ms": self.duration_ms,
"run_order": self.run_order,
"relative": self.relative,
"tracks": tracks,
}
def live_point(self, serial: int, elapsed_ms: float) -> tuple[float, float] | None:
"""Pan/tilt for a running fixture at wall time — EFXFixture::nextStep."""
fx = self.fixtures[serial]
loop = self.duration_ms
off = self.time_offset_ms(serial)
if self.propagation == "Serial" and elapsed_ms < off:
return None
cycles, pos = divmod(elapsed_ms, loop)
if self.run_order == "SingleShot" and cycles >= 1:
return None
d = fx.direction
if self.run_order == "PingPong" and int(cycles) % 2 == 1:
d = "Backward" if d == "Forward" else "Forward"
pos = (pos + off) % loop
it = 2 * math.pi * pos / loop
return self.point(d, fx.start_offset, it)
# --------------------------------------------------------------------------- Path
@dataclass
class PathPoint:
pan: float
tilt: float
fade_ms: int = 1000
hold_ms: int = 0
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "PathPoint":
return cls(
pan=clamp(float(d["pan"])),
tilt=clamp(float(d["tilt"])),
fade_ms=max(0, int(d.get("fade_ms", 1000))),
hold_ms=max(0, int(d.get("hold_ms", 0))),
)
@dataclass
class PathFixture:
id: int
head: int = 0
pan_offset: int = 0
tilt_offset: int = 0
mirror_pan: bool = False # head hung the other way round: pan = 255 - pan
mirror_tilt: bool = False
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "PathFixture":
return cls(
id=int(d["id"]),
head=int(d.get("head", 0)),
pan_offset=int(d.get("pan_offset", 0)),
tilt_offset=int(d.get("tilt_offset", 0)),
mirror_pan=bool(d.get("mirror_pan", False)),
mirror_tilt=bool(d.get("mirror_tilt", False)),
)
def apply(self, pan: float, tilt: float) -> tuple[float, float]:
if self.mirror_pan:
pan = 255 - pan
if self.mirror_tilt:
tilt = 255 - tilt
return clamp(pan + self.pan_offset), clamp(tilt + self.tilt_offset)
@dataclass
class Path:
points: list[PathPoint] = field(default_factory=list)
smooth: bool = False
subdivisions: int = 6 # extra steps per segment when smoothing
closed: bool = True # last point flows back into the first
run_order: str = "Loop"
direction: str = "Forward"
fixtures: list[PathFixture] = field(default_factory=list)
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "Path":
return cls(
points=[PathPoint.from_dict(p) for p in d.get("points", [])],
smooth=bool(d.get("smooth", False)),
subdivisions=int(clamp(int(d.get("subdivisions", 6)), 1, 32)),
closed=bool(d.get("closed", True)),
run_order=d.get("run_order") if d.get("run_order") in RUN_ORDERS else "Loop",
direction=d.get("direction") if d.get("direction") in DIRECTIONS else "Forward",
fixtures=[PathFixture.from_dict(f) for f in d.get("fixtures", [])],
)
# -- steps ----------------------------------------------------------------
def steps(self) -> list[PathPoint]:
"""Resolved step list (smoothing expanded), in the pattern's base frame."""
pts = self.points
if len(pts) < 2 or not self.smooth:
return list(pts)
# A waypoint's fade_ms is the travel time *into* it. When the segment
# before it is split into `sub` sub-steps, each sub-step (and the
# waypoint itself) gets fade_ms / sub so the total travel time holds.
out: list[PathPoint] = []
n = len(pts)
sub = self.subdivisions
seg_count = n if self.closed else n - 1
def split_fade(p: PathPoint) -> int:
return max(1, p.fade_ms // sub)
for i in range(seg_count):
p0 = pts[(i - 1) % n] if (self.closed or i > 0) else pts[0]
p1 = pts[i]
p2 = pts[(i + 1) % n]
p3 = pts[(i + 2) % n] if (self.closed or i + 2 < n) else pts[-1]
arrive = split_fade(p1) if (self.closed or i > 0) else p1.fade_ms
out.append(PathPoint(p1.pan, p1.tilt, fade_ms=arrive, hold_ms=p1.hold_ms))
for k in range(1, sub):
t = k / sub
pan = _catmull(p0.pan, p1.pan, p2.pan, p3.pan, t)
tilt = _catmull(p0.tilt, p1.tilt, p2.tilt, p3.tilt, t)
out.append(PathPoint(clamp(pan), clamp(tilt), fade_ms=split_fade(p2), hold_ms=0))
if not self.closed:
last = pts[-1]
out.append(PathPoint(last.pan, last.tilt, fade_ms=split_fade(last), hold_ms=last.hold_ms))
return out
def loop_ms(self) -> int:
return sum(s.fade_ms + s.hold_ms for s in self.steps())
def sample(self) -> dict[str, Any]:
steps = self.steps()
tracks = []
for fx in self.fixtures:
keys = []
t = 0
for s in steps:
pan, tilt = fx.apply(s.pan, s.tilt)
t += s.fade_ms
keys.append([t, round(pan, 2), round(tilt, 2)])
if s.hold_ms:
t += s.hold_ms
keys.append([t, round(pan, 2), round(tilt, 2)])
tracks.append({"id": fx.id, "head": fx.head, "keys": keys})
return {
"kind": "path",
"loop_ms": self.loop_ms(),
"run_order": self.run_order,
"direction": self.direction,
"tracks": tracks,
"step_count": len(steps),
}
def live_point(self, serial: int, elapsed_ms: float) -> tuple[float, float] | None:
steps = self.steps()
if not steps:
return None
loop = self.loop_ms()
if loop <= 0:
pan, tilt = steps[0].pan, steps[0].tilt
return self.fixtures[serial].apply(pan, tilt)
cycles, pos = divmod(elapsed_ms, loop)
if self.run_order == "SingleShot" and cycles >= 1:
pos = loop
reverse = self.direction == "Backward"
if self.run_order == "PingPong" and int(cycles) % 2 == 1:
reverse = not reverse
order = list(reversed(steps)) if reverse else steps
t = 0.0
prev = order[-1]
for s in order:
if pos <= t + s.fade_ms:
f = (pos - t) / s.fade_ms if s.fade_ms else 1.0
pan = prev.pan + (s.pan - prev.pan) * f
tilt = prev.tilt + (s.tilt - prev.tilt) * f
return self.fixtures[serial].apply(pan, tilt)
t += s.fade_ms
if pos <= t + s.hold_ms:
return self.fixtures[serial].apply(s.pan, s.tilt)
t += s.hold_ms
prev = s
last = order[-1]
return self.fixtures[serial].apply(last.pan, last.tilt)
def _catmull(p0: float, p1: float, p2: float, p3: float, t: float) -> float:
t2, t3 = t * t, t * t * t
return 0.5 * (
2 * p1
+ (-p0 + p2) * t
+ (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2
+ (-p0 + 3 * p1 - 3 * p2 + p3) * t3
)
# --------------------------------------------------------------------------- entry
def pattern_from_dict(d: dict[str, Any]) -> Efx | Path:
kind = d.get("type", "efx")
if kind == "efx":
return Efx.from_dict({**d.get("efx", {}), "fixtures": d.get("fixtures", [])})
if kind == "path":
return Path.from_dict({**d.get("path", {}), "fixtures": d.get("fixtures", [])})
raise ValueError(f"unknown pattern type {kind!r}")
+263
View File
@@ -0,0 +1,263 @@
"""Locate and read QLC+ fixture definitions (.qxf) and work out which channels
in a mode are pan / tilt / dimmer / shutter / colour.
"""
from __future__ import annotations
import os
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
NS = {"q": "http://www.qlcplus.org/FixtureDefinition"}
DIMMER_PRESETS = {"IntensityMasterDimmer", "IntensityDimmer"}
WHITE_PRESETS = {"IntensityWhite"}
RGB_PRESETS = ("IntensityRed", "IntensityGreen", "IntensityBlue")
@dataclass
class ChannelInfo:
index: int
name: str
preset: str | None
group: str | None
byte: int
shutter_open: int | None = None # DMX value that opens the shutter, if a shutter channel
@dataclass
class ModeInfo:
name: str
channels: list[ChannelInfo]
pan_msb: int | None = None
pan_lsb: int | None = None
tilt_msb: int | None = None
tilt_lsb: int | None = None
dimmers: list[int] = field(default_factory=list)
shutters: list[tuple[int, int]] = field(default_factory=list) # (channel, open value)
whites: list[int] = field(default_factory=list)
reds: list[int] = field(default_factory=list)
greens: list[int] = field(default_factory=list)
blues: list[int] = field(default_factory=list)
@property
def is_mover(self) -> bool:
return self.pan_msb is not None and self.tilt_msb is not None
def preview_channels(self) -> dict[int, int]:
"""Channel values that make the head visibly lit (white, open, full)."""
ch: dict[int, int] = {}
for d in self.dimmers:
ch[d] = 255
for s, v in self.shutters:
ch[s] = v
if self.whites:
for w in self.whites:
ch[w] = 255
else:
for c in self.reds + self.greens + self.blues:
ch[c] = 255
if not self.dimmers and not self.whites and not self.reds:
# Nothing we recognise as intensity — fall back to every Intensity-group channel.
for c in self.channels:
if c.group == "Intensity" or (c.preset or "").startswith("Intensity"):
ch[c.index] = 255
return ch
def to_dict(self) -> dict:
return {
"name": self.name,
"channel_count": len(self.channels),
"pan_msb": self.pan_msb,
"pan_lsb": self.pan_lsb,
"tilt_msb": self.tilt_msb,
"tilt_lsb": self.tilt_lsb,
"dimmers": self.dimmers,
"channels": [{"index": c.index, "name": c.name, "preset": c.preset, "group": c.group} for c in self.channels],
}
@dataclass
class FixtureDef:
path: Path
manufacturer: str
model: str
type: str
pan_max: int
tilt_max: int
modes: dict[str, ModeInfo]
def mode(self, name: str) -> ModeInfo | None:
if name in self.modes:
return self.modes[name]
# QLC+ sometimes stores "43 Channel" vs "43 Channel Mode" etc. — be lenient.
key = name.strip().lower()
for k, v in self.modes.items():
if k.strip().lower() == key:
return v
return None
# ----------------------------------------------------------------------------- parse
def _text(el: ET.Element | None, default: str = "") -> str:
return (el.text or default) if el is not None else default
def _parse_channel(el: ET.Element) -> ChannelInfo:
name = el.get("Name", "")
preset = el.get("Preset")
group_el = el.find("q:Group", NS)
group = _text(group_el) if group_el is not None else None
byte = int(group_el.get("Byte", "0")) if group_el is not None else 0
if preset and group is None:
# Presets imply the group; the ones we care about:
if preset.startswith("Position"):
group = "Pan" if "Pan" in preset else "Tilt"
elif preset.startswith("Intensity"):
group = "Intensity"
elif preset.startswith("Shutter") or preset.startswith("Strobe"):
group = "Shutter"
if preset.endswith("Fine"):
byte = 1
shutter_open = None
if group == "Shutter" or (preset or "").startswith("Shutter"):
caps = el.findall("q:Capability", NS)
if (preset or "").startswith("Shutter") and not caps:
shutter_open = 0 # QLC+ built-in shutter presets all start with "Open"
for cap in caps:
cp = cap.get("Preset", "")
label = (cap.text or "").strip().lower()
if cp == "ShutterOpen" or (not cp and label in ("open", "shutter open", "no function")):
shutter_open = int(cap.get("Min", "0"))
break
return ChannelInfo(index=-1, name=name, preset=preset, group=group, byte=byte, shutter_open=shutter_open)
def _resolve_mode(name: str, chans: list[ChannelInfo]) -> ModeInfo:
m = ModeInfo(name=name, channels=chans)
for c in chans:
p = c.preset or ""
if c.group == "Pan" or p in ("PositionPan", "PositionPanFine"):
if c.byte == 1 or p.endswith("Fine"):
m.pan_lsb = m.pan_lsb if m.pan_lsb is not None else c.index
else:
m.pan_msb = m.pan_msb if m.pan_msb is not None else c.index
elif c.group == "Tilt" or p in ("PositionTilt", "PositionTiltFine"):
if c.byte == 1 or p.endswith("Fine"):
m.tilt_lsb = m.tilt_lsb if m.tilt_lsb is not None else c.index
else:
m.tilt_msb = m.tilt_msb if m.tilt_msb is not None else c.index
elif p in DIMMER_PRESETS:
m.dimmers.append(c.index)
elif p in WHITE_PRESETS:
m.whites.append(c.index)
elif p == RGB_PRESETS[0]:
m.reds.append(c.index)
elif p == RGB_PRESETS[1]:
m.greens.append(c.index)
elif p == RGB_PRESETS[2]:
m.blues.append(c.index)
elif c.group == "Intensity" and not p:
lname = c.name.lower()
if "dimmer" in lname or "master" in lname or "bright" in lname:
m.dimmers.append(c.index)
if c.shutter_open is not None:
m.shutters.append((c.index, c.shutter_open))
return m
@lru_cache(maxsize=256)
def load_fixture_def(path: str) -> FixtureDef:
root = ET.parse(path).getroot()
channels: dict[str, ChannelInfo] = {}
for el in root.findall("q:Channel", NS):
ci = _parse_channel(el)
channels[ci.name] = ci
phys = root.find("q:Physical", NS)
focus = phys.find("q:Focus", NS) if phys is not None else None
pan_max = int(focus.get("PanMax", "0")) if focus is not None else 0
tilt_max = int(focus.get("TiltMax", "0")) if focus is not None else 0
modes: dict[str, ModeInfo] = {}
for mode_el in root.findall("q:Mode", NS):
name = mode_el.get("Name", "")
chans: list[ChannelInfo] = []
for ch_el in mode_el.findall("q:Channel", NS):
base = channels.get((ch_el.text or "").strip())
if base is None:
continue
ci = ChannelInfo(**{**base.__dict__, "index": int(ch_el.get("Number", len(chans)))})
chans.append(ci)
chans.sort(key=lambda c: c.index)
modes[name] = _resolve_mode(name, chans)
return FixtureDef(
path=Path(path),
manufacturer=_text(root.find("q:Manufacturer", NS)),
model=_text(root.find("q:Model", NS)),
type=_text(root.find("q:Type", NS)),
pan_max=pan_max,
tilt_max=tilt_max,
modes=modes,
)
# ----------------------------------------------------------------------------- locate
_HEAD_RE = re.compile(
rb"<Manufacturer>(.*?)</Manufacturer>.*?<Model>(.*?)</Model>", re.S
)
class FixtureLibrary:
"""Index of (manufacturer, model) → .qxf path across the usual search dirs."""
def __init__(self, project_root: Path, extra_dirs: list[Path] | None = None):
self.dirs: list[Path] = [project_root / "fixtures"]
self.dirs += extra_dirs or []
self.dirs.append(Path.home() / ".qlcplus" / "fixtures")
for d in ("/usr/share/qlcplus/fixtures", "/usr/local/share/qlcplus/fixtures"):
self.dirs.append(Path(d))
self._index: dict[tuple[str, str], Path] | None = None
def _build_index(self) -> dict[tuple[str, str], Path]:
idx: dict[tuple[str, str], Path] = {}
for d in self.dirs:
if not d.is_dir():
continue
for dirpath, _dirs, files in os.walk(d):
for fn in files:
if not fn.endswith(".qxf"):
continue
p = Path(dirpath) / fn
try:
with open(p, "rb") as fh:
head = fh.read(4096)
except OSError:
continue
m = _HEAD_RE.search(head)
if not m:
continue
key = (_unesc(m.group(1)).strip().lower(), _unesc(m.group(2)).strip().lower())
idx.setdefault(key, p) # first dir wins (project fixtures override system)
return idx
def find(self, manufacturer: str, model: str) -> FixtureDef | None:
if self._index is None:
self._index = self._build_index()
p = self._index.get((manufacturer.strip().lower(), model.strip().lower()))
if p is None:
return None
try:
return load_fixture_def(str(p))
except ET.ParseError:
return None
def _unesc(b: bytes) -> str:
s = b.decode("utf-8", "replace")
return s.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"').replace("&apos;", "'")
+577
View File
@@ -0,0 +1,577 @@
"""Read QLC+ workspaces (.qxw) and write pattern functions into them.
Reading uses ElementTree. Writing is done on the raw text so QLC+'s own
formatting, DOCTYPE and everything we do not understand are left untouched.
"""
from __future__ import annotations
import re
import shutil
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from xml.sax.saxutils import quoteattr
from .efx import Efx, Path as PathPattern, RELATIVE_ZERO, clamp8
from .fixturedefs import FixtureDef, FixtureLibrary, ModeInfo
NS = {"q": "http://www.qlcplus.org/Workspace"}
INVALID_ID = 4294967295
@dataclass
class WsFixture:
id: int
name: str
manufacturer: str
model: str
mode_name: str
universe: int
address: int
channels: int
definition: FixtureDef | None = None
mode: ModeInfo | None = None
@property
def is_mover(self) -> bool:
return self.mode is not None and self.mode.is_mover
def to_dict(self) -> dict[str, Any]:
d: dict[str, Any] = {
"id": self.id,
"name": self.name,
"manufacturer": self.manufacturer,
"model": self.model,
"mode": self.mode_name,
"universe": self.universe,
"address": self.address,
"channels": self.channels,
"is_mover": self.is_mover,
"definition_found": self.definition is not None,
}
if self.definition:
d["pan_max"] = self.definition.pan_max
d["tilt_max"] = self.definition.tilt_max
if self.mode:
d["pan_msb"] = self.mode.pan_msb
d["tilt_msb"] = self.mode.tilt_msb
d["pan_lsb"] = self.mode.pan_lsb
d["tilt_lsb"] = self.mode.tilt_lsb
return d
@dataclass
class WsFunction:
id: int
type: str
name: str
def to_dict(self) -> dict[str, Any]:
return {"id": self.id, "type": self.type, "name": self.name}
@dataclass
class Workspace:
path: Path
text: str
fixtures: list[WsFixture]
functions: list[WsFunction]
artnet: dict[int, dict[str, Any]] # universe id → {"ip":..., "universe":...}
vc_widget_ids: list[int] = field(default_factory=list)
vc_bottom: int = 0 # lowest used Y in the root VC frame
# ------------------------------------------------------------------ load
@classmethod
def load(cls, path: Path, library: FixtureLibrary) -> "Workspace":
text = path.read_text(encoding="utf-8")
root = ET.fromstring(text)
engine = root.find("q:Engine", NS)
fixtures: list[WsFixture] = []
functions: list[WsFunction] = []
artnet: dict[int, dict[str, Any]] = {}
if engine is not None:
for fx in engine.findall("q:Fixture", NS):
manu = _t(fx, "Manufacturer")
model = _t(fx, "Model")
mode_name = _t(fx, "Mode")
wsf = WsFixture(
id=int(_t(fx, "ID", "0")),
name=_t(fx, "Name"),
manufacturer=manu,
model=model,
mode_name=mode_name,
universe=int(_t(fx, "Universe", "0")),
address=int(_t(fx, "Address", "0")),
channels=int(_t(fx, "Channels", "0")),
)
if manu != "Generic" or model != "Generic":
wsf.definition = library.find(manu, model)
if wsf.definition:
wsf.mode = wsf.definition.mode(mode_name)
fixtures.append(wsf)
for fn in engine.findall("q:Function", NS):
functions.append(
WsFunction(id=int(fn.get("ID", "0")), type=fn.get("Type", ""), name=fn.get("Name", ""))
)
iomap = engine.find("q:InputOutputMap", NS)
if iomap is not None:
for uni in iomap.findall("q:Universe", NS):
out = uni.find("q:Output", NS)
if out is None or out.get("Plugin") != "ArtNet":
continue
params = out.find("q:PluginParameters", NS)
ip = params.get("outputIP") if params is not None else None
art_uni = params.get("outputUni") if params is not None else None
artnet[int(uni.get("ID", "0"))] = {
"ip": ip or out.get("UID") or "",
"universe": int(art_uni) if art_uni is not None else int(uni.get("ID", "0")),
}
widget_ids: list[int] = []
bottom = 0
vc = root.find("q:VirtualConsole", NS)
if vc is not None:
for el in vc.iter():
wid = el.get("ID")
if wid is not None and not el.tag.endswith("}Function"):
try:
widget_ids.append(int(wid))
except ValueError:
pass
frame = vc.find("q:Frame", NS)
if frame is not None:
for child in frame:
ws = child.find("q:WindowState", NS)
if ws is not None:
try:
bottom = max(bottom, int(ws.get("Y", "0")) + int(ws.get("Height", "0")))
except ValueError:
pass
return cls(
path=path,
text=text,
fixtures=fixtures,
functions=functions,
artnet=artnet,
vc_widget_ids=widget_ids,
vc_bottom=bottom,
)
def fixture(self, fid: int) -> WsFixture | None:
return next((f for f in self.fixtures if f.id == fid), None)
def next_function_id(self) -> int:
return (max((f.id for f in self.functions), default=-1)) + 1
def next_widget_id(self) -> int:
return (max(self.vc_widget_ids, default=-1)) + 1
def function_by_name(self, name: str, ftype: str | None = None) -> WsFunction | None:
for f in self.functions:
if f.name == name and (ftype is None or f.type == ftype):
return f
return None
def to_dict(self) -> dict[str, Any]:
return {
"path": str(self.path),
"name": self.path.name,
"fixtures": [f.to_dict() for f in self.fixtures],
"functions": [f.to_dict() for f in self.functions],
"artnet": {str(k): v for k, v in self.artnet.items()},
}
# ------------------------------------------------------------------ import
def pattern_from_function(self, fid: int) -> dict[str, Any] | None:
"""Turn an existing EFX or pan/tilt Sequence back into an editable pattern."""
root = ET.fromstring(self.text)
engine = root.find("q:Engine", NS)
if engine is None:
return None
for fn in engine.findall("q:Function", NS):
if int(fn.get("ID", "-1")) != fid:
continue
if fn.get("Type") == "EFX":
return _efx_to_pattern(fn)
if fn.get("Type") == "Sequence":
return _sequence_to_pattern(fn, self)
return None
def _t(el: ET.Element, tag: str, default: str = "") -> str:
child = el.find(f"q:{tag}", NS)
return (child.text or default).strip() if child is not None and child.text is not None else default
def _efx_to_pattern(fn: ET.Element) -> dict[str, Any]:
speed = fn.find("q:Speed", NS)
axes = {ax.get("Name"): ax for ax in fn.findall("q:Axis", NS)}
def axis(name: str, tag: str, default: str) -> int:
ax = axes.get(name)
return int(_t(ax, tag, default)) if ax is not None else int(default)
fixtures = []
for fx in fn.findall("q:Fixture", NS):
fixtures.append(
{
"id": int(_t(fx, "ID", "0")),
"head": int(_t(fx, "Head", "0")),
"direction": _t(fx, "Direction", "Forward"),
"start_offset": int(_t(fx, "StartOffset", "0")),
}
)
return {
"name": fn.get("Name", ""),
"type": "efx",
"source_function_id": int(fn.get("ID", "0")),
"fixtures": fixtures,
"efx": {
"algorithm": _t(fn, "Algorithm", "Circle"),
"width": int(_t(fn, "Width", "0")),
"height": int(_t(fn, "Height", "0")),
"rotation": int(_t(fn, "Rotation", "0")),
"start_offset": int(_t(fn, "StartOffset", "0")),
"relative": _t(fn, "IsRelative", "0") == "1",
"x_offset": axis("X", "Offset", "127"),
"y_offset": axis("Y", "Offset", "127"),
"x_frequency": axis("X", "Frequency", "1"),
"y_frequency": axis("Y", "Frequency", "1"),
"x_phase": axis("X", "Phase", "0"),
"y_phase": axis("Y", "Phase", "0"),
"duration_ms": int(speed.get("Duration", "8000")) if speed is not None else 8000,
"fade_in_ms": int(speed.get("FadeIn", "0")) if speed is not None else 0,
"fade_out_ms": int(speed.get("FadeOut", "0")) if speed is not None else 0,
"direction": _t(fn, "Direction", "Forward"),
"run_order": _t(fn, "RunOrder", "Loop"),
"propagation": _t(fn, "PropagationMode", "Parallel"),
},
}
def _sequence_to_pattern(fn: ET.Element, ws: Workspace) -> dict[str, Any] | None:
steps = fn.findall("q:Step", NS)
if not steps:
return None
# Which fixtures carry pan/tilt in this sequence?
fixture_ids: list[int] = []
for s in steps:
for fid, _vals in _parse_step_values(s.text or ""):
if fid not in fixture_ids:
fixture_ids.append(fid)
movers = [ws.fixture(fid) for fid in fixture_ids]
movers = [m for m in movers if m is not None and m.is_mover]
if not movers:
return None
ref = movers[0]
points = []
for s in steps:
vals = dict(_parse_step_values(s.text or "")).get(ref.id, {})
pan = vals.get(ref.mode.pan_msb) # type: ignore[union-attr]
tilt = vals.get(ref.mode.tilt_msb) # type: ignore[union-attr]
if pan is None or tilt is None:
return None
points.append(
{"pan": pan, "tilt": tilt, "fade_ms": int(s.get("FadeIn", "0")), "hold_ms": int(s.get("Hold", "0"))}
)
return {
"name": fn.get("Name", ""),
"type": "path",
"source_function_id": int(fn.get("ID", "0")),
"fixtures": [{"id": m.id} for m in movers],
"path": {
"points": points,
"smooth": False,
"closed": True,
"direction": _t(fn, "Direction", "Forward"),
"run_order": _t(fn, "RunOrder", "Loop"),
},
}
def _parse_step_values(text: str) -> list[tuple[int, dict[int, int]]]:
"""'8:0,10,2,20:9:0,30,2,40' → [(8, {0:10, 2:20}), (9, {0:30, 2:40})]."""
out: list[tuple[int, dict[int, int]]] = []
parts = text.strip().split(":")
i = 0
while i + 1 < len(parts):
try:
fid = int(parts[i])
except ValueError:
break
nums = [int(x) for x in parts[i + 1].split(",") if x.strip() != ""]
out.append((fid, {nums[k]: nums[k + 1] for k in range(0, len(nums) - 1, 2)}))
i += 2
return out
# ----------------------------------------------------------------------------- render
def _speed(fade_in: int, fade_out: int, duration: int) -> str:
return f' <Speed FadeIn="{fade_in}" FadeOut="{fade_out}" Duration="{duration}"/>'
def render_efx(fid: int, name: str, efx: Efx) -> str:
fixtures = "\n".join(
f""" <Fixture>
<ID>{fx.id}</ID>
<Head>{fx.head}</Head>
<Direction>{fx.direction}</Direction>
<StartOffset>{fx.start_offset}</StartOffset>
</Fixture>"""
for fx in efx.fixtures
)
x_off = RELATIVE_ZERO if efx.relative else efx.x_offset
y_off = RELATIVE_ZERO if efx.relative else efx.y_offset
return f""" <Function ID="{fid}" Type="EFX" Name={quoteattr(name)}>
{fixtures}
<PropagationMode>{efx.propagation}</PropagationMode>
<Speed FadeIn="{efx.fade_in_ms}" FadeOut="{efx.fade_out_ms}" Duration="{efx.duration_ms}"/>
<Direction>{efx.direction}</Direction>
<RunOrder>{efx.run_order}</RunOrder>
<Algorithm>{efx.algorithm}</Algorithm>
<Width>{efx.width}</Width>
<Height>{efx.height}</Height>
<Rotation>{efx.rotation}</Rotation>
<StartOffset>{efx.start_offset}</StartOffset>
<IsRelative>{1 if efx.relative else 0}</IsRelative>
<Axis Name="X">
<Offset>{x_off}</Offset>
<Frequency>{efx.x_frequency}</Frequency>
<Phase>{efx.x_phase}</Phase>
</Axis>
<Axis Name="Y">
<Offset>{y_off}</Offset>
<Frequency>{efx.y_frequency}</Frequency>
<Phase>{efx.y_phase}</Phase>
</Axis>
</Function>"""
def render_scene(fid: int, name: str, values: dict[int, dict[int, int]], fade_in: int = 0) -> str:
vals = "\n".join(
f' <FixtureVal ID="{fxid}">{",".join(f"{ch},{v}" for ch, v in sorted(chs.items()))}</FixtureVal>'
for fxid, chs in values.items()
if chs
)
return f""" <Function ID="{fid}" Type="Scene" Name={quoteattr(name)}>
{_speed(fade_in, 0, fade_in)}
{vals}
</Function>"""
def render_collection(fid: int, name: str, members: list[int]) -> str:
steps = "\n".join(f' <Step Number="{i}">{m}</Step>' for i, m in enumerate(members))
return f""" <Function ID="{fid}" Type="Collection" Name={quoteattr(name)}>
{steps}
</Function>"""
def render_sequence(
fid: int,
scene_id: int,
name: str,
path: PathPattern,
movers: dict[int, WsFixture],
) -> tuple[str, str]:
"""Returns (bound scene xml, sequence xml)."""
steps = path.steps()
if not steps:
raise ValueError("path has no points")
def channels_for(fx_cfg, step) -> dict[int, int]:
m = movers[fx_cfg.id].mode
assert m is not None and m.pan_msb is not None and m.tilt_msb is not None
pan, tilt = fx_cfg.apply(step.pan, step.tilt)
ch = {m.pan_msb: clamp8(pan), m.tilt_msb: clamp8(tilt)}
# Fine channels: carry the fractional part like EFXFixture does.
if m.pan_lsb is not None:
ch[m.pan_lsb] = clamp8((pan - int(pan)) * 255)
if m.tilt_lsb is not None:
ch[m.tilt_lsb] = clamp8((tilt - int(tilt)) * 255)
return ch
step_xml = []
for i, s in enumerate(steps):
chunks = []
count = 0
for fx in path.fixtures:
ch = channels_for(fx, s)
count += len(ch)
chunks.append(f"{fx.id}:" + ",".join(f"{c},{v}" for c, v in sorted(ch.items())))
step_xml.append(
f' <Step Number="{i}" FadeIn="{s.fade_ms}" Hold="{s.hold_ms}" FadeOut="0" Values="{count}">'
+ ":".join(chunks)
+ "</Step>"
)
first = {fx.id: channels_for(fx, steps[0]) for fx in path.fixtures}
scene = render_scene(scene_id, f"{name} (base)", first)
seq = f""" <Function ID="{fid}" Type="Sequence" Name={quoteattr(name)} BoundScene="{scene_id}">
{_speed(steps[0].fade_ms, 0, steps[0].fade_ms + steps[0].hold_ms)}
<Direction>{path.direction}</Direction>
<RunOrder>{path.run_order}</RunOrder>
<SpeedModes FadeIn="PerStep" FadeOut="Common" Duration="PerStep"/>
{chr(10).join(step_xml)}
</Function>"""
return scene, seq
def render_vc_button(wid: int, caption: str, fid: int, x: int, y: int, w: int = 110, h: int = 60, bg: str = "4282664004") -> str:
return f""" <Button Caption={quoteattr(caption)} ID="{wid}" Icon="">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="{fid}"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>"""
# ----------------------------------------------------------------------------- write
_FUNC_RE_TMPL = r'[ \t]*<Function ID="{fid}"[^>]*?(?:/>|>.*?</Function>)[ \t]*\r?\n?'
def remove_function(text: str, fid: int) -> str:
return re.sub(_FUNC_RE_TMPL.format(fid=fid), "", text, count=1, flags=re.S)
def insert_functions(text: str, xml: str) -> str:
"""Insert function XML at the end of the Engine section (order is not significant to QLC+)."""
idx = text.find("</Engine>")
if idx < 0:
raise ValueError("workspace has no <Engine> section")
# back up to the start of that line
line_start = text.rfind("\n", 0, idx) + 1
return text[:line_start] + xml + "\n" + text[line_start:]
def insert_vc_widget(text: str, xml: str) -> str:
vc = text.find("<VirtualConsole>")
if vc < 0:
raise ValueError("workspace has no <VirtualConsole>")
props = text.find("<Properties>", vc)
end = text.rfind("</Frame>", vc, props if props > 0 else len(text))
if end < 0:
raise ValueError("VirtualConsole has no root <Frame>")
line_start = text.rfind("\n", 0, end) + 1
return text[:line_start] + xml + "\n" + text[line_start:]
@dataclass
class ExportResult:
path: Path
backup: Path | None
function_ids: dict[str, int]
widget_id: int | None
replaced: list[int]
def to_dict(self) -> dict[str, Any]:
return {
"path": str(self.path),
"backup": str(self.backup) if self.backup else None,
"function_ids": self.function_ids,
"widget_id": self.widget_id,
"replaced": self.replaced,
}
def export_pattern(
ws: Workspace,
pattern: dict[str, Any],
*,
name: str,
overwrite: bool = True,
add_button: bool = False,
button_xy: tuple[int, int] | None = None,
out_path: Path | None = None,
backup: bool = True,
) -> ExportResult:
"""Write the pattern into `ws` (in place, or to `out_path`)."""
from .efx import pattern_from_dict
obj = pattern_from_dict(pattern)
name = name.strip() or "Mover Pattern"
text = ws.text
replaced: list[int] = []
ids: dict[str, int] = {}
xml_parts: list[str] = []
next_id = ws.next_function_id()
def alloc(kind: str, fname: str) -> int:
"""Reuse the ID of a same-named function (keeps VC buttons wired) or take a fresh one."""
nonlocal next_id, text
existing = ws.function_by_name(fname) if overwrite else None
if existing and existing.id not in replaced:
text = remove_function(text, existing.id)
replaced.append(existing.id)
ids[kind] = existing.id
return existing.id
fid = next_id
next_id += 1
ids[kind] = fid
return fid
movers = {f.id: f for f in ws.fixtures if f.is_mover}
for fx in obj.fixtures:
if fx.id not in movers:
raise ValueError(f"fixture {fx.id} is not a mover in this workspace")
if not obj.fixtures:
raise ValueError("pattern has no fixtures")
main_id: int
if isinstance(obj, Efx):
if obj.relative:
# Base positions scene + EFX around RELATIVE_ZERO + Collection to run both.
base_vals: dict[int, dict[int, int]] = {}
for fx in obj.fixtures:
m = movers[fx.id].mode
assert m is not None and m.pan_msb is not None and m.tilt_msb is not None
base_vals[fx.id] = {m.pan_msb: fx.pan, m.tilt_msb: fx.tilt}
scene_id = alloc("scene", f"{name} (home)")
efx_id = alloc("efx", f"{name} (EFX)")
coll_id = alloc("collection", name)
xml_parts.append(render_scene(scene_id, f"{name} (home)", base_vals, fade_in=obj.fade_in_ms))
xml_parts.append(render_efx(efx_id, f"{name} (EFX)", obj))
xml_parts.append(render_collection(coll_id, name, [scene_id, efx_id]))
main_id = coll_id
else:
efx_id = alloc("efx", name)
xml_parts.append(render_efx(efx_id, name, obj))
main_id = efx_id
else:
scene_id = alloc("scene", f"{name} (base)")
seq_id = alloc("sequence", name)
scene_xml, seq_xml = render_sequence(seq_id, scene_id, name, obj, movers)
xml_parts.append(scene_xml)
xml_parts.append(seq_xml)
main_id = seq_id
text = insert_functions(text, "\n".join(xml_parts))
widget_id = None
if add_button:
widget_id = ws.next_widget_id()
x, y = button_xy or (10, ws.vc_bottom + 10)
text = insert_vc_widget(text, render_vc_button(widget_id, name, main_id, x, y))
# Make sure what we are about to write is still well-formed before touching disk.
ET.fromstring(text)
target = out_path or ws.path
backup_path = None
if backup and target.exists():
backup_path = target.with_suffix(target.suffix + ".bak")
shutil.copyfile(target, backup_path)
target.write_text(text, encoding="utf-8")
return ExportResult(path=target, backup=backup_path, function_ids=ids, widget_id=widget_id, replaced=replaced)
+272
View File
@@ -0,0 +1,272 @@
"""Local HTTP server: static UI + small JSON API. Standard library only."""
from __future__ import annotations
import json
import mimetypes
import re
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlparse
from .artnet import LivePreview
from .efx import pattern_from_dict
from .fixturedefs import FixtureLibrary
from .qxw import Workspace, export_pattern
STATIC_DIR = Path(__file__).parent / "static"
_SAFE_NAME = re.compile(r"[^A-Za-z0-9 _().#+-]+")
class ApiError(Exception):
def __init__(self, message: str, status: int = 400):
super().__init__(message)
self.status = status
class Studio:
"""Application state shared by all requests."""
def __init__(self, root: Path, shows_dir: str = "shows", patterns_dir: str = "patterns"):
self.root = root.resolve()
self.shows_dir = self.root / shows_dir
self.patterns_dir = self.root / patterns_dir
self.library = FixtureLibrary(self.root)
self.live = LivePreview()
# -- helpers ---------------------------------------------------------------
def resolve(self, rel: str) -> Path:
p = (self.root / rel).resolve()
if self.root not in p.parents and p != self.root:
raise ApiError("path is outside the project", 403)
return p
def workspace(self, rel: str) -> Workspace:
p = self.resolve(rel)
if not p.is_file() or p.suffix != ".qxw":
raise ApiError(f"not a workspace: {rel}", 404)
return Workspace.load(p, self.library)
# -- API -------------------------------------------------------------------
def list_workspaces(self) -> dict[str, Any]:
items = []
if self.shows_dir.is_dir():
for p in sorted(self.shows_dir.rglob("*.qxw"), key=lambda p: (len(p.parts), str(p).lower())):
items.append({"path": str(p.relative_to(self.root)), "name": p.name, "folder": str(p.parent.relative_to(self.root))})
return {"workspaces": items}
def get_workspace(self, q: dict[str, list[str]]) -> dict[str, Any]:
return self.workspace(_one(q, "path")).to_dict()
def get_function(self, q: dict[str, list[str]]) -> dict[str, Any]:
ws = self.workspace(_one(q, "path"))
pat = ws.pattern_from_function(int(_one(q, "id")))
if pat is None:
raise ApiError("function is not an EFX or a pan/tilt Sequence", 404)
return {"pattern": pat}
def sample(self, body: dict[str, Any]) -> dict[str, Any]:
try:
return pattern_from_dict(body["pattern"]).sample()
except (KeyError, ValueError, TypeError) as exc:
raise ApiError(f"bad pattern: {exc}") from exc
def export(self, body: dict[str, Any]) -> dict[str, Any]:
ws = self.workspace(body["path"])
out_rel = body.get("out_path")
out_path = self.resolve(out_rel) if out_rel else None
if out_path is not None and out_path.suffix != ".qxw":
raise ApiError("out_path must end in .qxw")
try:
res = export_pattern(
ws,
body["pattern"],
name=body.get("name") or body["pattern"].get("name") or "Mover Pattern",
overwrite=bool(body.get("overwrite", True)),
add_button=bool(body.get("add_button", False)),
button_xy=tuple(body["button_xy"]) if body.get("button_xy") else None,
out_path=out_path,
backup=bool(body.get("backup", True)),
)
except (ValueError, KeyError) as exc:
raise ApiError(str(exc)) from exc
d = res.to_dict()
d["path"] = str(res.path.relative_to(self.root))
return d
# -- pattern library ---------------------------------------------------------
def list_patterns(self) -> dict[str, Any]:
items = []
if self.patterns_dir.is_dir():
for p in sorted(self.patterns_dir.glob("*.json")):
try:
data = json.loads(p.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
continue
items.append({"file": p.name, "name": data.get("name", p.stem), "type": data.get("type", "efx"), "pattern": data})
return {"patterns": items}
def save_pattern(self, body: dict[str, Any]) -> dict[str, Any]:
pat = body["pattern"]
name = (body.get("name") or pat.get("name") or "pattern").strip()
pat["name"] = name
pattern_from_dict(pat) # validate
self.patterns_dir.mkdir(parents=True, exist_ok=True)
fn = _SAFE_NAME.sub("", name).strip().replace(" ", "_") or "pattern"
p = self.patterns_dir / f"{fn}.json"
p.write_text(json.dumps(pat, indent=1) + "\n", encoding="utf-8")
return {"file": p.name}
def delete_pattern(self, q: dict[str, list[str]]) -> dict[str, Any]:
fn = Path(_one(q, "file")).name
p = self.patterns_dir / fn
if p.suffix != ".json" or not p.is_file():
raise ApiError("no such pattern", 404)
p.unlink()
return {"deleted": fn}
# -- live Art-Net -------------------------------------------------------------
def live_start(self, body: dict[str, Any]) -> dict[str, Any]:
ws = self.workspace(body["path"])
try:
pat = pattern_from_dict(body["pattern"])
except (KeyError, ValueError, TypeError) as exc:
raise ApiError(f"bad pattern: {exc}") from exc
movers = {f.id for f in ws.fixtures if f.is_mover}
for fx in pat.fixtures:
if fx.id not in movers:
raise ApiError(f"fixture {fx.id} is not a mover")
if not pat.fixtures:
raise ApiError("pattern has no fixtures")
ip = body.get("ip") or next((a["ip"] for a in ws.artnet.values() if a.get("ip")), None)
if not ip:
raise ApiError("no Art-Net IP configured")
uni = int(body.get("universe", next((a["universe"] for a in ws.artnet.values()), 0)))
self.live.start(ws, pat, ip, uni)
return self.live.status
def live_stop(self) -> dict[str, Any]:
self.live.stop()
return self.live.status
def _one(q: dict[str, list[str]], key: str) -> str:
v = q.get(key)
if not v:
raise ApiError(f"missing query parameter {key!r}")
return v[0]
class Handler(BaseHTTPRequestHandler):
studio: Studio # set by make_server
server_version = "PatternStudio/0.1"
def log_message(self, fmt: str, *args: Any) -> None: # quieter default log
if self.path.startswith("/api/sample"):
return
super().log_message(fmt, *args)
# -- plumbing ----------------------------------------------------------------
def _json(self, status: int, data: Any) -> None:
raw = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def _body(self) -> dict[str, Any]:
n = int(self.headers.get("Content-Length") or 0)
if n <= 0:
return {}
try:
return json.loads(self.rfile.read(n).decode("utf-8"))
except json.JSONDecodeError as exc:
raise ApiError(f"invalid JSON: {exc}") from exc
def _static(self, rel: str) -> None:
rel = rel.lstrip("/") or "index.html"
p = (STATIC_DIR / rel).resolve()
if STATIC_DIR.resolve() not in p.parents or not p.is_file():
self.send_error(404)
return
ctype = mimetypes.guess_type(p.name)[0] or "application/octet-stream"
raw = p.read_bytes()
self.send_response(200)
self.send_header("Content-Type", ctype if not ctype.startswith("text/") else f"{ctype}; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def _dispatch(self, method: str) -> None:
url = urlparse(self.path)
q = parse_qs(url.query)
s = self.studio
try:
if not url.path.startswith("/api/"):
if method != "GET":
self.send_error(405)
return
if url.path == "/favicon.ico":
self.send_response(204)
self.end_headers()
return
self._static(url.path)
return
route = (method, url.path)
if route == ("GET", "/api/workspaces"):
self._json(200, s.list_workspaces())
elif route == ("GET", "/api/workspace"):
self._json(200, s.get_workspace(q))
elif route == ("GET", "/api/function"):
self._json(200, s.get_function(q))
elif route == ("POST", "/api/sample"):
self._json(200, s.sample(self._body()))
elif route == ("POST", "/api/export"):
self._json(200, s.export(self._body()))
elif route == ("GET", "/api/patterns"):
self._json(200, s.list_patterns())
elif route == ("POST", "/api/patterns"):
self._json(200, s.save_pattern(self._body()))
elif route == ("DELETE", "/api/patterns"):
self._json(200, s.delete_pattern(q))
elif route == ("POST", "/api/live/start"):
self._json(200, s.live_start(self._body()))
elif route == ("POST", "/api/live/stop"):
self._json(200, s.live_stop())
elif route == ("GET", "/api/live/status"):
self._json(200, s.live.status)
else:
self._json(404, {"error": f"no route {method} {url.path}"})
except ApiError as exc:
self._json(exc.status, {"error": str(exc)})
except Exception as exc: # noqa: BLE001 — surface anything else to the UI
traceback.print_exc()
self._json(500, {"error": f"{type(exc).__name__}: {exc}"})
def do_GET(self) -> None: # noqa: N802
self._dispatch("GET")
def do_POST(self) -> None: # noqa: N802
self._dispatch("POST")
def do_DELETE(self) -> None: # noqa: N802
self._dispatch("DELETE")
def make_server(root: Path, host: str = "127.0.0.1", port: int = 8765) -> ThreadingHTTPServer:
studio = Studio(root)
handler = type("BoundHandler", (Handler,), {"studio": studio})
server = ThreadingHTTPServer((host, port), handler)
server.studio = studio # type: ignore[attr-defined]
return server
+785
View File
@@ -0,0 +1,785 @@
/* Mover Pattern Studio — browser UI.
* All pattern maths lives on the server (patternstudio/efx.py); this file
* edits the pattern JSON, asks the server for sampled tracks and animates them.
*/
"use strict";
const $ = (sel) => document.querySelector(sel);
const PALETTE = ["#5aa9ff", "#ffb547", "#52d273", "#ff6b6b", "#c58bff", "#4fd8d8", "#ff8ad8", "#d6e35a"];
const ALGORITHMS = ["Circle", "Eight", "Line", "Line2", "Diamond", "Square", "SquareChoppy", "Leaf", "Lissajous"];
const EFX_SLIDERS = [
["width", "Width (pan)", 0, 127],
["height", "Height (tilt)", 0, 127],
["rotation", "Rotation °", 0, 359],
["start_offset", "Start offset °", 0, 359],
["x_offset", "Centre pan", 0, 255],
["y_offset", "Centre tilt", 0, 255],
["duration_ms", "Loop ms", 200, 60000],
["fade_in_ms", "Fade in ms", 0, 20000],
];
const state = {
workspaces: [],
wsPath: null,
ws: null,
pattern: defaultPattern(),
sample: null,
selected: -1, // selected waypoint
playing: true,
speed: 1,
clock: 0, // pattern time in ms
lastFrame: 0,
live: false,
library: [],
drag: null,
};
function defaultPattern() {
return {
name: "Mover Pattern",
type: "efx",
fixtures: [],
efx: {
algorithm: "Circle", width: 40, height: 30, rotation: 0, start_offset: 0,
x_offset: 128, y_offset: 128, x_frequency: 1, y_frequency: 1, x_phase: 0, y_phase: 0,
duration_ms: 8000, fade_in_ms: 0, fade_out_ms: 0,
direction: "Forward", run_order: "Loop", propagation: "Parallel", relative: false,
},
path: {
points: [], smooth: false, subdivisions: 6, closed: true, run_order: "Loop", direction: "Forward",
},
};
}
function fixtureConfig(id) {
return { id, head: 0, direction: "Forward", start_offset: 0, pan: 128, tilt: 128,
pan_offset: 0, tilt_offset: 0, mirror_pan: false, mirror_tilt: false };
}
// ------------------------------------------------------------------ API
async function api(method, url, body) {
const res = await fetch(url, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({ error: res.statusText }));
if (!res.ok) throw new Error(data.error || res.statusText);
return data;
}
function setStatus(msg, cls = "") {
const el = $("#status");
el.textContent = msg;
el.className = cls;
}
// ------------------------------------------------------------------ workspace
async function loadWorkspaces() {
const d = await api("GET", "/api/workspaces");
state.workspaces = d.workspaces;
const sel = $("#ws-select");
sel.innerHTML = "";
for (const w of d.workspaces) {
const o = document.createElement("option");
o.value = w.path;
o.textContent = w.path.replace(/^shows\//, "");
sel.appendChild(o);
}
const remembered = localStorage.getItem("ps.ws");
const pick = d.workspaces.find((w) => w.path === remembered) || d.workspaces[0];
if (pick) {
sel.value = pick.path;
await loadWorkspace(pick.path);
} else {
setStatus("No .qxw files found in shows/", "err");
}
}
async function loadWorkspace(path) {
state.wsPath = path;
localStorage.setItem("ps.ws", path);
state.ws = await api("GET", `/api/workspace?path=${encodeURIComponent(path)}`);
const movers = state.ws.fixtures.filter((f) => f.is_mover);
// Keep fixture selections that still exist; default to all movers.
const ids = new Set(movers.map((f) => f.id));
state.pattern.fixtures = state.pattern.fixtures.filter((f) => ids.has(f.id));
if (!state.pattern.fixtures.length) state.pattern.fixtures = movers.map((m) => fixtureConfig(m.id));
const art = Object.values(state.ws.artnet)[0];
if (art) {
$("#live-ip").value = art.ip || "";
$("#live-uni").value = art.universe ?? 0;
}
renderFixtures();
renderFunctionList();
setStatus(`${movers.length} mover${movers.length === 1 ? "" : "s"} · ${state.ws.functions.length} functions`);
requestSample();
}
function moverById(id) {
return state.ws?.fixtures.find((f) => f.id === id);
}
// ------------------------------------------------------------------ fixtures panel
function renderFixtures() {
const box = $("#fixture-list");
box.innerHTML = "";
if (!state.ws) return;
const movers = state.ws.fixtures.filter((f) => f.is_mover);
const others = state.ws.fixtures.filter((f) => !f.is_mover);
$("#fixture-hint").textContent = movers.length ? "" : "no pan/tilt fixtures found";
const isEfx = state.pattern.type === "efx";
movers.forEach((m, i) => {
const cfg = state.pattern.fixtures.find((f) => f.id === m.id);
const el = document.createElement("div");
el.className = "fixture" + (cfg ? "" : " off");
const color = PALETTE[i % PALETTE.length];
const degs = m.pan_max ? ` · ${m.pan_max}°/${m.tilt_max}°` : "";
el.innerHTML = `
<label class="name">
<input type="checkbox" ${cfg ? "checked" : ""}>
<span class="swatch" style="background:${color}"></span>
<span>${esc(m.name)}</span>
<small>${esc(m.manufacturer)} ${esc(m.model)} · ${esc(m.mode)} · U${m.universe + 1} @ ${m.address + 1}${degs}</small>
</label>
<div class="opts"></div>`;
el.querySelector("input").addEventListener("change", (e) => {
if (e.target.checked) state.pattern.fixtures.push(fixtureConfig(m.id));
else state.pattern.fixtures = state.pattern.fixtures.filter((f) => f.id !== m.id);
renderFixtures();
requestSample();
});
const opts = el.querySelector(".opts");
if (cfg) {
if (isEfx) {
opts.appendChild(selectField("Dir", ["Forward", "Backward"], cfg.direction, (v) => { cfg.direction = v; requestSample(); }));
opts.appendChild(numField("Offset °", cfg.start_offset, 0, 359, (v) => { cfg.start_offset = v; requestSample(); }));
if (state.pattern.efx.relative) {
opts.appendChild(numField("Home pan", cfg.pan, 0, 255, (v) => { cfg.pan = v; requestSample(); }));
opts.appendChild(numField("Home tilt", cfg.tilt, 0, 255, (v) => { cfg.tilt = v; requestSample(); }));
}
} else {
opts.appendChild(checkField("Mirror pan", cfg.mirror_pan, (v) => { cfg.mirror_pan = v; requestSample(); }));
opts.appendChild(checkField("Mirror tilt", cfg.mirror_tilt, (v) => { cfg.mirror_tilt = v; requestSample(); }));
opts.appendChild(numField("Pan ±", cfg.pan_offset, -255, 255, (v) => { cfg.pan_offset = v; requestSample(); }));
opts.appendChild(numField("Tilt ±", cfg.tilt_offset, -255, 255, (v) => { cfg.tilt_offset = v; requestSample(); }));
}
}
box.appendChild(el);
});
if (others.length) {
const el = document.createElement("div");
el.className = "fixture notmover";
el.innerHTML = `<div class="name"><small>${others.length} non-mover fixture${others.length === 1 ? "" : "s"} hidden</small></div>`;
box.appendChild(el);
}
}
function selectField(label, options, value, onChange) {
const l = document.createElement("label");
l.append(label);
const s = document.createElement("select");
for (const o of options) { const op = document.createElement("option"); op.textContent = o; s.appendChild(op); }
s.value = value;
s.addEventListener("change", () => onChange(s.value));
l.appendChild(s);
return l;
}
function numField(label, value, min, max, onChange) {
const l = document.createElement("label");
l.append(label);
const i = document.createElement("input");
i.type = "number"; i.min = min; i.max = max; i.value = value;
i.addEventListener("input", () => { const v = Number(i.value); if (Number.isFinite(v)) onChange(v); });
l.appendChild(i);
return l;
}
function checkField(label, value, onChange) {
const l = document.createElement("label");
const i = document.createElement("input");
i.type = "checkbox"; i.checked = value;
i.addEventListener("change", () => onChange(i.checked));
l.append(i, label);
return l;
}
function esc(s) {
return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
}
// ------------------------------------------------------------------ EFX panel
function buildEfxPanel() {
const alg = $("#efx-algorithm");
for (const a of ALGORITHMS) { const o = document.createElement("option"); o.textContent = a; alg.appendChild(o); }
alg.addEventListener("change", () => { state.pattern.efx.algorithm = alg.value; syncEfxForm(); requestSample(); });
const box = $("#efx-sliders");
for (const [key, label, min, max] of EFX_SLIDERS) {
const row = document.createElement("div");
row.className = "slider";
row.innerHTML = `<span>${label}</span><input type="range" min="${min}" max="${max}" data-key="${key}"><input type="number" min="${min}" max="${max}" data-key="${key}">`;
const [range, num] = row.querySelectorAll("input");
const apply = (v) => {
v = Math.max(min, Math.min(max, Math.round(Number(v) || 0)));
state.pattern.efx[key] = v;
range.value = v; num.value = v;
requestSample();
};
range.addEventListener("input", () => apply(range.value));
num.addEventListener("input", () => apply(num.value));
box.appendChild(row);
}
for (const key of ["direction", "run_order", "propagation", "x_frequency", "y_frequency", "x_phase", "y_phase"]) {
const el = $(`#efx-${key}`);
el.addEventListener("input", () => {
state.pattern.efx[key] = el.type === "number" ? Number(el.value) : el.value;
requestSample();
});
}
$("#efx-relative").addEventListener("change", (e) => {
state.pattern.efx.relative = e.target.checked;
renderFixtures();
syncEfxForm();
requestSample();
});
}
function syncEfxForm() {
const e = state.pattern.efx;
$("#efx-algorithm").value = e.algorithm;
for (const inp of $("#efx-sliders").querySelectorAll("input")) inp.value = e[inp.dataset.key];
for (const key of ["direction", "run_order", "propagation", "x_frequency", "y_frequency", "x_phase", "y_phase"]) $(`#efx-${key}`).value = e[key];
$("#efx-relative").checked = e.relative;
$("#lissajous-row").style.display = e.algorithm === "Lissajous" ? "" : "none";
// In relative mode the centre is each head's home; the shared offsets are meaningless.
for (const inp of $("#efx-sliders").querySelectorAll("input[data-key=x_offset],input[data-key=y_offset]")) inp.disabled = e.relative;
}
// ------------------------------------------------------------------ Path panel
function buildPathPanel() {
$("#pt-add").addEventListener("click", () => {
const pts = state.pattern.path.points;
const last = pts[pts.length - 1];
pts.push({ pan: last ? Math.min(255, last.pan + 20) : 128, tilt: last ? last.tilt : 128, fade_ms: last ? last.fade_ms : 1000, hold_ms: last ? last.hold_ms : 0 });
state.selected = pts.length - 1;
renderPoints(); requestSample();
});
$("#pt-clear").addEventListener("click", () => { state.pattern.path.points = []; state.selected = -1; renderPoints(); requestSample(); });
for (const key of ["closed", "smooth"]) {
$(`#path-${key}`).addEventListener("change", (e) => { state.pattern.path[key] = e.target.checked; requestSample(); });
}
$("#path-subdivisions").addEventListener("input", (e) => { state.pattern.path.subdivisions = Number(e.target.value) || 1; requestSample(); });
for (const key of ["run_order", "direction"]) {
$(`#path-${key}`).addEventListener("input", (e) => { state.pattern.path[key] = e.target.value; requestSample(); });
}
$("#path-all-fade").addEventListener("change", (e) => {
const v = Number(e.target.value); if (!Number.isFinite(v) || e.target.value === "") return;
for (const p of state.pattern.path.points) p.fade_ms = v;
e.target.value = ""; renderPoints(); requestSample();
});
$("#path-all-hold").addEventListener("change", (e) => {
const v = Number(e.target.value); if (!Number.isFinite(v) || e.target.value === "") return;
for (const p of state.pattern.path.points) p.hold_ms = v;
e.target.value = ""; renderPoints(); requestSample();
});
}
function syncPathForm() {
const p = state.pattern.path;
$("#path-closed").checked = p.closed;
$("#path-smooth").checked = p.smooth;
$("#path-subdivisions").value = p.subdivisions;
$("#path-run_order").value = p.run_order;
$("#path-direction").value = p.direction;
renderPoints();
}
function renderPoints() {
const tb = $("#point-table tbody");
tb.innerHTML = "";
state.pattern.path.points.forEach((pt, i) => {
const tr = document.createElement("tr");
if (i === state.selected) tr.className = "sel";
tr.innerHTML = `<td>${i + 1}</td>` +
["pan", "tilt", "fade_ms", "hold_ms"].map((k) => `<td><input type="number" data-k="${k}" value="${Math.round(pt[k])}" min="0" max="${k.endsWith("ms") ? 600000 : 255}" step="${k.endsWith("ms") ? 100 : 1}"></td>`).join("") +
`<td><button class="danger" title="Remove">×</button></td>`;
tr.addEventListener("click", () => { if (state.selected !== i) { state.selected = i; renderPoints(); } });
for (const inp of tr.querySelectorAll("input")) {
inp.addEventListener("input", () => {
const v = Number(inp.value);
if (!Number.isFinite(v)) return;
pt[inp.dataset.k] = inp.dataset.k.endsWith("ms") ? Math.max(0, v) : Math.max(0, Math.min(255, v));
requestSample();
});
}
tr.querySelector("button").addEventListener("click", (e) => {
e.stopPropagation();
state.pattern.path.points.splice(i, 1);
state.selected = Math.min(state.selected, state.pattern.path.points.length - 1);
renderPoints(); requestSample();
});
tb.appendChild(tr);
});
const s = state.sample;
$("#path-summary").textContent = s && s.kind === "path"
? `${s.step_count} sequence step${s.step_count === 1 ? "" : "s"} · loop ${(s.loop_ms / 1000).toFixed(1)} s`
: "";
}
// ------------------------------------------------------------------ type tabs
function setType(type) {
state.pattern.type = type;
for (const b of $("#type-tabs").querySelectorAll("button")) b.classList.toggle("active", b.dataset.type === type);
$("#efx-panel").hidden = type !== "efx";
$("#path-panel").hidden = type !== "path";
$("#canvas-hint").textContent = type === "efx" ? "Click or drag on the grid to place the shape's centre" : "Click to add a waypoint · drag to move";
renderFixtures();
if (type === "efx") syncEfxForm(); else syncPathForm();
requestSample();
}
// ------------------------------------------------------------------ sampling
let sampleTimer = null;
let sampleInFlight = false;
let sampleQueued = false;
function requestSample() {
clearTimeout(sampleTimer);
sampleTimer = setTimeout(doSample, 30);
if (state.live) scheduleLiveRestart();
}
async function doSample() {
if (sampleInFlight) { sampleQueued = true; return; }
sampleInFlight = true;
try {
state.sample = await api("POST", "/api/sample", { pattern: state.pattern });
if (state.pattern.type === "path") renderPoints();
} catch (err) {
setStatus(err.message, "err");
} finally {
sampleInFlight = false;
if (sampleQueued) { sampleQueued = false; doSample(); }
}
}
// ------------------------------------------------------------------ playback maths
function headPosition(track, kind, tMs) {
const s = state.sample;
const loop = s.loop_ms;
if (kind === "efx") {
const pts = track.points;
if (tMs < track.start_delay_ms) return { pan: pts[0][0], tilt: pts[0][1], waiting: true };
const cycles = Math.floor(tMs / loop);
if (s.run_order === "SingleShot" && cycles >= 1) return null;
let pos = (tMs + track.time_offset_ms) % loop;
let u = pos / loop;
if (s.run_order === "PingPong" && cycles % 2 === 1) u = 1 - u;
const f = u * pts.length;
const i = Math.floor(f) % pts.length;
const j = (i + 1) % pts.length;
const k = f - Math.floor(f);
return { pan: pts[i][0] + (pts[j][0] - pts[i][0]) * k, tilt: pts[i][1] + (pts[j][1] - pts[i][1]) * k };
}
// path: keys [t, pan, tilt] — piecewise linear, wraps from last key back to first
const keys = track.keys;
if (!keys.length) return null;
if (loop <= 0) return { pan: keys[0][1], tilt: keys[0][2] };
const cycles = Math.floor(tMs / loop);
let pos = tMs % loop;
let reverse = s.direction === "Backward";
if (s.run_order === "PingPong" && cycles % 2 === 1) reverse = !reverse;
if (s.run_order === "SingleShot" && cycles >= 1) pos = loop;
if (reverse) pos = loop - pos;
let prev = keys[keys.length - 1];
let tPrev = 0;
for (const key of keys) {
const [t, pan, tilt] = key;
if (pos <= t) {
const span = t - tPrev;
const k = span > 0 ? (pos - tPrev) / span : 1;
return { pan: prev[1] + (pan - prev[1]) * k, tilt: prev[2] + (tilt - prev[2]) * k };
}
tPrev = t; prev = key;
}
return { pan: prev[1], tilt: prev[2] };
}
// ------------------------------------------------------------------ canvas
const canvas = $("#canvas");
const ctx = canvas.getContext("2d");
let geom = { x0: 0, y0: 0, size: 0 };
function resizeCanvas() {
const r = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(r.width * dpr);
canvas.height = Math.round(r.height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const margin = 44;
const size = Math.max(50, Math.min(r.width, r.height) - margin * 2);
geom = { x0: (r.width - size) / 2, y0: (r.height - size) / 2, size, w: r.width, h: r.height };
}
const toPx = (pan, tilt) => [geom.x0 + (pan / 255) * geom.size, geom.y0 + (tilt / 255) * geom.size];
const toDmx = (x, y) => [((x - geom.x0) / geom.size) * 255, ((y - geom.y0) / geom.size) * 255];
function draw(now) {
if (!state.lastFrame) state.lastFrame = now;
const dt = now - state.lastFrame;
state.lastFrame = now;
if (state.playing) state.clock += dt * state.speed;
ctx.clearRect(0, 0, geom.w, geom.h);
drawGrid();
const s = state.sample;
if (s && state.ws) {
const movers = state.ws.fixtures.filter((f) => f.is_mover);
const colorOf = (id) => PALETTE[Math.max(0, movers.findIndex((m) => m.id === id)) % PALETTE.length];
const showTrails = $("#show-trails").checked;
// Paths
for (const track of s.tracks) {
ctx.strokeStyle = colorOf(track.id);
ctx.globalAlpha = 0.55;
ctx.lineWidth = 1.5;
ctx.beginPath();
const pts = s.kind === "efx" ? track.points : track.keys.map((k) => [k[1], k[2]]);
pts.forEach((p, i) => { const [x, y] = toPx(p[0], p[1]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
if (s.kind === "efx" || state.pattern.path.closed) ctx.closePath();
ctx.stroke();
ctx.globalAlpha = 1;
}
// Waypoints (path mode)
if (s.kind === "path") {
state.pattern.path.points.forEach((p, i) => {
const [x, y] = toPx(p.pan, p.tilt);
ctx.beginPath(); ctx.arc(x, y, i === state.selected ? 8 : 6, 0, Math.PI * 2);
ctx.fillStyle = i === state.selected ? "#fff" : "#9aa3b5"; ctx.fill();
ctx.fillStyle = "#0b1220"; ctx.font = "bold 9px system-ui"; ctx.textAlign = "center"; ctx.textBaseline = "middle";
ctx.fillText(String(i + 1), x, y + 0.5);
});
}
// EFX centre handle
if (s.kind === "efx" && !state.pattern.efx.relative) {
const [cx, cy] = toPx(state.pattern.efx.x_offset, state.pattern.efx.y_offset);
ctx.strokeStyle = "#ffffff"; ctx.globalAlpha = 0.8; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(cx - 9, cy); ctx.lineTo(cx + 9, cy); ctx.moveTo(cx, cy - 9); ctx.lineTo(cx, cy + 9); ctx.stroke();
ctx.beginPath(); ctx.arc(cx, cy, 9, 0, Math.PI * 2); ctx.stroke();
ctx.globalAlpha = 1;
}
// Heads
const loop = s.loop_ms || 1;
for (const track of s.tracks) {
const color = colorOf(track.id);
if (showTrails) {
ctx.strokeStyle = color; ctx.lineWidth = 4; ctx.lineCap = "round";
const trailMs = Math.min(1200, loop * 0.15);
ctx.beginPath();
let first = true;
for (let k = 12; k >= 0; k--) {
const pos = headPosition(track, s.kind, Math.max(0, state.clock - (trailMs * k) / 12));
if (!pos) continue;
const [x, y] = toPx(pos.pan, pos.tilt);
ctx.globalAlpha = 0.05 + (1 - k / 12) * 0.35;
if (first) { ctx.moveTo(x, y); first = false; } else { ctx.lineTo(x, y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x, y); }
}
ctx.globalAlpha = 1;
}
const pos = headPosition(track, s.kind, state.clock);
if (!pos) continue;
const [x, y] = toPx(pos.pan, pos.tilt);
ctx.beginPath(); ctx.arc(x, y, 9, 0, Math.PI * 2);
ctx.fillStyle = color; ctx.globalAlpha = pos.waiting ? 0.35 : 1; ctx.fill(); ctx.globalAlpha = 1;
ctx.strokeStyle = "#0b1220"; ctx.lineWidth = 2; ctx.stroke();
ctx.fillStyle = "#e6e8ee"; ctx.font = "11px system-ui"; ctx.textAlign = "left"; ctx.textBaseline = "bottom";
const m = moverById(track.id);
ctx.fillText(`${m ? m.name : track.id} ${Math.round(pos.pan)},${Math.round(pos.tilt)}`, x + 12, y - 6);
}
$("#time").textContent = `${((state.clock % loop) / 1000).toFixed(2)} / ${(loop / 1000).toFixed(2)} s`;
}
requestAnimationFrame(draw);
}
function drawGrid() {
const { x0, y0, size } = geom;
ctx.fillStyle = "#101216";
ctx.fillRect(x0, y0, size, size);
ctx.strokeStyle = "#262a34"; ctx.lineWidth = 1;
for (let v = 0; v <= 256; v += 32) {
const p = (Math.min(v, 255) / 255) * size;
ctx.beginPath(); ctx.moveTo(x0 + p, y0); ctx.lineTo(x0 + p, y0 + size); ctx.stroke();
ctx.beginPath(); ctx.moveTo(x0, y0 + p); ctx.lineTo(x0 + size, y0 + p); ctx.stroke();
}
ctx.strokeStyle = "#3b4150"; ctx.strokeRect(x0 + 0.5, y0 + 0.5, size, size);
// Axis labels
const showDeg = $("#show-degrees").checked;
const ref = state.ws?.fixtures.find((f) => f.is_mover && f.pan_max);
ctx.fillStyle = "#8d94a6"; ctx.font = "11px system-ui";
ctx.textAlign = "center"; ctx.textBaseline = "top";
for (let v = 0; v <= 255; v += 64) {
const x = x0 + (v / 255) * size;
let label = String(v);
if (showDeg && ref) label += ` · ${Math.round((v / 255) * ref.pan_max)}°`;
ctx.fillText(label, x, y0 + size + 6);
}
ctx.fillText("PAN →", x0 + size / 2, y0 + size + 22);
ctx.textAlign = "right"; ctx.textBaseline = "middle";
for (let v = 0; v <= 255; v += 64) {
const y = y0 + (v / 255) * size;
let label = String(v);
if (showDeg && ref) label = `${Math.round((v / 255) * ref.tilt_max)}° · ` + label;
ctx.fillText(label, x0 - 6, y);
}
ctx.save(); ctx.translate(x0 - 34, y0 + size / 2); ctx.rotate(-Math.PI / 2);
ctx.textAlign = "center"; ctx.textBaseline = "bottom"; ctx.fillText("TILT (0 = top, like the QLC+ XY pad)", 0, 0); ctx.restore();
}
// Canvas interaction
function hitWaypoint(x, y) {
let best = -1, bestD = 12;
state.pattern.path.points.forEach((p, i) => {
const [px, py] = toPx(p.pan, p.tilt);
const d = Math.hypot(px - x, py - y);
if (d < bestD) { bestD = d; best = i; }
});
return best;
}
canvas.addEventListener("pointerdown", (e) => {
const r = canvas.getBoundingClientRect();
const x = e.clientX - r.left, y = e.clientY - r.top;
const inside = x >= geom.x0 && x <= geom.x0 + geom.size && y >= geom.y0 && y <= geom.y0 + geom.size;
if (state.pattern.type === "efx") {
if (state.pattern.efx.relative) return;
const [cx, cy] = toPx(state.pattern.efx.x_offset, state.pattern.efx.y_offset);
if (Math.hypot(cx - x, cy - y) < 14 || inside) {
state.drag = { kind: "centre" };
canvas.setPointerCapture(e.pointerId);
moveCentre(x, y);
}
return;
}
const hit = hitWaypoint(x, y);
if (hit >= 0) {
state.selected = hit;
state.drag = { kind: "point", index: hit };
canvas.setPointerCapture(e.pointerId);
renderPoints();
} else if (inside) {
const [pan, tilt] = toDmx(x, y);
const pts = state.pattern.path.points;
const last = pts[pts.length - 1];
const insertAt = state.selected >= 0 ? state.selected + 1 : pts.length;
pts.splice(insertAt, 0, { pan: clamp255(pan), tilt: clamp255(tilt), fade_ms: last ? last.fade_ms : 1000, hold_ms: last ? last.hold_ms : 0 });
state.selected = insertAt;
state.drag = { kind: "point", index: insertAt };
canvas.setPointerCapture(e.pointerId);
renderPoints(); requestSample();
}
});
canvas.addEventListener("pointermove", (e) => {
if (!state.drag) return;
const r = canvas.getBoundingClientRect();
const x = e.clientX - r.left, y = e.clientY - r.top;
if (state.drag.kind === "centre") moveCentre(x, y);
else {
const [pan, tilt] = toDmx(x, y);
const p = state.pattern.path.points[state.drag.index];
if (!p) return;
p.pan = clamp255(pan); p.tilt = clamp255(tilt);
const tr = $("#point-table tbody").children[state.drag.index];
if (tr) { tr.querySelector("[data-k=pan]").value = Math.round(p.pan); tr.querySelector("[data-k=tilt]").value = Math.round(p.tilt); }
requestSample();
}
});
const endDrag = () => { state.drag = null; };
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
function moveCentre(x, y) {
const [pan, tilt] = toDmx(x, y);
state.pattern.efx.x_offset = clamp255(pan);
state.pattern.efx.y_offset = clamp255(tilt);
syncEfxForm();
requestSample();
}
const clamp255 = (v) => Math.max(0, Math.min(255, Math.round(v)));
document.addEventListener("keydown", (e) => {
if (e.target.matches("input, select, textarea")) return;
if (e.code === "Space") { e.preventDefault(); togglePlay(); }
if ((e.key === "Delete" || e.key === "Backspace") && state.pattern.type === "path" && state.selected >= 0) {
state.pattern.path.points.splice(state.selected, 1);
state.selected = Math.min(state.selected, state.pattern.path.points.length - 1);
renderPoints(); requestSample();
}
});
function togglePlay() {
state.playing = !state.playing;
$("#play").textContent = state.playing ? "Pause" : "Play";
}
// ------------------------------------------------------------------ export
async function exportPattern() {
const btn = $("#exp-go"), out = $("#exp-result");
btn.disabled = true; out.textContent = "writing…"; out.className = "result";
try {
const body = {
path: state.wsPath,
pattern: state.pattern,
name: $("#pat-name").value.trim() || "Mover Pattern",
overwrite: $("#exp-overwrite").checked,
add_button: $("#exp-button").checked,
out_path: $("#exp-out").value.trim() || null,
};
const r = await api("POST", "/api/export", body);
const ids = Object.entries(r.function_ids).map(([k, v]) => `${k} #${v}`).join(", ");
out.textContent = `Wrote ${r.path} (${ids}${r.widget_id != null ? `, button #${r.widget_id}` : ""}${r.replaced.length ? `, replaced ${r.replaced.join(",")}` : ""}). Reload the workspace in QLC+.`;
out.className = "result ok";
if (!body.out_path) await loadWorkspace(state.wsPath);
else { await loadWorkspaces(); }
} catch (err) {
out.textContent = err.message; out.className = "result err";
} finally {
btn.disabled = false;
}
}
// ------------------------------------------------------------------ library + workspace functions
async function loadLibrary() {
try {
const d = await api("GET", "/api/patterns");
state.library = d.patterns;
} catch (err) { setStatus(err.message, "err"); }
const ul = $("#lib-list");
ul.innerHTML = "";
if (!state.library.length) { ul.innerHTML = '<li class="empty">No saved patterns yet</li>'; return; }
for (const item of state.library) {
const li = document.createElement("li");
li.innerHTML = `<span class="lname">${esc(item.name)} <small>${item.type}</small></span><button>Load</button><button class="danger">×</button>`;
const [load, del] = li.querySelectorAll("button");
load.addEventListener("click", () => applyPattern(item.pattern));
del.addEventListener("click", async () => {
if (!confirm(`Delete saved pattern "${item.name}"?`)) return;
await api("DELETE", `/api/patterns?file=${encodeURIComponent(item.file)}`);
loadLibrary();
});
ul.appendChild(li);
}
}
async function savePattern() {
const name = $("#pat-name").value.trim() || "Mover Pattern";
state.pattern.name = name;
try {
await api("POST", "/api/patterns", { name, pattern: state.pattern });
setStatus(`Saved "${name}" to patterns/`, "ok");
loadLibrary();
} catch (err) { setStatus(err.message, "err"); }
}
function renderFunctionList() {
const ul = $("#fn-list");
ul.innerHTML = "";
const fns = (state.ws?.functions || []).filter((f) => f.type === "EFX" || f.type === "Sequence");
if (!fns.length) { ul.innerHTML = '<li class="empty">None</li>'; return; }
for (const f of fns) {
const li = document.createElement("li");
li.innerHTML = `<span class="lname">${esc(f.name)} <small>${f.type} #${f.id}</small></span><button>Edit</button>`;
li.querySelector("button").addEventListener("click", async () => {
try {
const d = await api("GET", `/api/function?path=${encodeURIComponent(state.wsPath)}&id=${f.id}`);
applyPattern(d.pattern);
setStatus(`Loaded "${f.name}" — writing will replace it`, "ok");
} catch (err) { setStatus(err.message, "err"); }
});
ul.appendChild(li);
}
}
function applyPattern(pat) {
const base = defaultPattern();
const movers = new Set((state.ws?.fixtures || []).filter((f) => f.is_mover).map((f) => f.id));
const fixtures = (pat.fixtures || []).filter((f) => movers.has(f.id)).map((f) => ({ ...fixtureConfig(f.id), ...f }));
state.pattern = {
...base,
...pat,
efx: { ...base.efx, ...(pat.efx || {}) },
path: { ...base.path, ...(pat.path || {}) },
fixtures: fixtures.length ? fixtures : [...movers].map(fixtureConfig),
};
delete state.pattern.source_function_id;
$("#pat-name").value = state.pattern.name || "Mover Pattern";
state.selected = -1;
state.clock = 0;
setType(state.pattern.type);
syncEfxForm();
syncPathForm();
}
// ------------------------------------------------------------------ live Art-Net
let liveTimer = null;
function scheduleLiveRestart() {
clearTimeout(liveTimer);
liveTimer = setTimeout(startLive, 250);
}
async function startLive() {
try {
const st = await api("POST", "/api/live/start", {
path: state.wsPath, pattern: state.pattern,
ip: $("#live-ip").value.trim() || null, universe: Number($("#live-uni").value) || 0,
});
setStatus(`LIVE → ${st.ip} universe ${st.universe} (stop QLC+ output first)`, "ok");
} catch (err) {
setStatus(`Live failed: ${err.message}`, "err");
state.live = false; $("#live-toggle").checked = false;
}
}
async function stopLive() {
try { await api("POST", "/api/live/stop"); } catch (_) { /* ignore */ }
setStatus("Live stopped (blackout sent)");
}
window.addEventListener("pagehide", () => { if (state.live) navigator.sendBeacon("/api/live/stop", "{}"); });
// ------------------------------------------------------------------ boot
function bind() {
$("#ws-select").addEventListener("change", (e) => loadWorkspace(e.target.value).catch((err) => setStatus(err.message, "err")));
$("#ws-reload").addEventListener("click", () => loadWorkspace(state.wsPath).catch((err) => setStatus(err.message, "err")));
$("#pat-name").addEventListener("input", (e) => { state.pattern.name = e.target.value; });
for (const b of $("#type-tabs").querySelectorAll("button")) b.addEventListener("click", () => setType(b.dataset.type));
$("#play").addEventListener("click", togglePlay);
$("#speed").addEventListener("change", (e) => { state.speed = Number(e.target.value); });
$("#exp-go").addEventListener("click", exportPattern);
$("#lib-save").addEventListener("click", savePattern);
$("#live-toggle").addEventListener("change", (e) => {
state.live = e.target.checked;
if (state.live) startLive(); else stopLive();
});
window.addEventListener("resize", resizeCanvas);
}
(async function boot() {
buildEfxPanel();
buildPathPanel();
bind();
resizeCanvas();
requestAnimationFrame(draw);
setType("efx");
await loadLibrary();
try { await loadWorkspaces(); } catch (err) { setStatus(err.message, "err"); }
resizeCanvas();
})();
+151
View File
@@ -0,0 +1,151 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mover Pattern Studio</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header>
<h1>Mover Pattern Studio</h1>
<label>Workspace
<select id="ws-select"></select>
</label>
<button id="ws-reload" title="Re-read the workspace from disk">Reload</button>
<span class="spacer"></span>
<label class="live">
<input type="checkbox" id="live-toggle"> Live Art-Net
</label>
<input id="live-ip" placeholder="IP" size="14" title="Art-Net destination (from workspace)">
<input id="live-uni" type="number" min="0" max="32767" value="0" size="4" title="Art-Net universe">
<span id="status"></span>
</header>
<main>
<aside id="controls">
<section class="card">
<h2>Pattern</h2>
<div class="row">
<label class="grow">Name <input id="pat-name" value="Mover Pattern"></label>
</div>
<div class="tabs" id="type-tabs">
<button data-type="efx" class="active">EFX (QLC+ shape)</button>
<button data-type="path">Path (waypoints → Sequence)</button>
</div>
</section>
<section class="card">
<h2>Fixtures <small id="fixture-hint"></small></h2>
<div id="fixture-list"></div>
</section>
<section class="card" id="efx-panel">
<h2>Shape</h2>
<div class="row">
<label class="grow">Algorithm
<select id="efx-algorithm"></select>
</label>
<label>Direction
<select id="efx-direction"><option>Forward</option><option>Backward</option></select>
</label>
</div>
<div id="efx-sliders"></div>
<div class="row" id="lissajous-row">
<label>X freq <input type="number" id="efx-x_frequency" min="0" max="5" value="1"></label>
<label>Y freq <input type="number" id="efx-y_frequency" min="0" max="5" value="1"></label>
<label>X phase <input type="number" id="efx-x_phase" min="0" max="359" value="0"></label>
<label>Y phase <input type="number" id="efx-y_phase" min="0" max="359" value="0"></label>
</div>
<div class="row">
<label>Run order
<select id="efx-run_order"><option>Loop</option><option>PingPong</option><option>SingleShot</option></select>
</label>
<label>Propagation
<select id="efx-propagation"><option>Parallel</option><option>Serial</option><option>Asymmetric</option></select>
</label>
<label class="check" title="EFX offsets each head from its own home position (exports Scene + EFX + Collection)">
<input type="checkbox" id="efx-relative"> Relative to home
</label>
</div>
<p class="hint">Tip: for a head hung the opposite way, set its direction to <b>Backward</b> — for Circle, Eight, Diamond, Leaf and Square this mirrors the shape in pan.</p>
</section>
<section class="card" id="path-panel" hidden>
<h2>Waypoints <small>click canvas to add · drag to move · Delete key removes</small></h2>
<table id="point-table">
<thead><tr><th>#</th><th>Pan</th><th>Tilt</th><th>Fade ms</th><th>Hold ms</th><th></th></tr></thead>
<tbody></tbody>
</table>
<div class="row">
<button id="pt-add">Add point</button>
<button id="pt-clear">Clear</button>
<label class="check"><input type="checkbox" id="path-closed" checked> Closed loop</label>
<label class="check"><input type="checkbox" id="path-smooth"> Smooth</label>
<label>Subdiv <input type="number" id="path-subdivisions" min="1" max="32" value="6"></label>
</div>
<div class="row">
<label>Run order
<select id="path-run_order"><option>Loop</option><option>PingPong</option><option>SingleShot</option></select>
</label>
<label>Direction
<select id="path-direction"><option>Forward</option><option>Backward</option></select>
</label>
<label>All fades <input type="number" id="path-all-fade" min="0" step="100" placeholder="ms"></label>
<label>All holds <input type="number" id="path-all-hold" min="0" step="100" placeholder="ms"></label>
</div>
<p class="hint" id="path-summary"></p>
</section>
<section class="card">
<h2>Write to workspace</h2>
<div class="row">
<label class="check"><input type="checkbox" id="exp-overwrite" checked> Replace same-named function</label>
<label class="check"><input type="checkbox" id="exp-button" checked> Add VC button</label>
</div>
<div class="row">
<label class="grow">Save as copy (optional) <input id="exp-out" placeholder="shows/new_show.qxw"></label>
</div>
<div class="row">
<button id="exp-go" class="primary">Write pattern</button>
<span id="exp-result" class="result"></span>
</div>
</section>
<section class="card">
<h2>Pattern library <small>patterns/*.json</small></h2>
<div class="row">
<button id="lib-save">Save current</button>
</div>
<ul id="lib-list" class="list"></ul>
</section>
<section class="card">
<h2>In this workspace <small>EFX &amp; pan/tilt Sequences</small></h2>
<ul id="fn-list" class="list"></ul>
</section>
</aside>
<section id="stage">
<div class="toolbar">
<button id="play" title="Space">Pause</button>
<label>Speed
<select id="speed">
<option value="0.25">¼×</option><option value="0.5">½×</option>
<option value="1" selected>1×</option><option value="2">2×</option><option value="4">4×</option>
</select>
</label>
<label class="check"><input type="checkbox" id="show-trails" checked> Trails</label>
<label class="check"><input type="checkbox" id="show-degrees" checked> Degrees</label>
<span id="time"></span>
<span class="spacer"></span>
<span class="hint" id="canvas-hint"></span>
</div>
<canvas id="canvas"></canvas>
</section>
</main>
<script src="/app.js"></script>
</body>
</html>
+147
View File
@@ -0,0 +1,147 @@
:root {
--bg: #15171c;
--panel: #1e2129;
--panel-2: #262a34;
--line: #343946;
--text: #e6e8ee;
--muted: #8d94a6;
--accent: #5aa9ff;
--accent-2: #ffb547;
--danger: #ff6b6b;
--ok: #52d273;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
background: var(--bg);
color: var(--text);
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
display: flex;
flex-direction: column;
}
header {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 14px;
background: var(--panel);
border-bottom: 1px solid var(--line);
}
header h1 { font-size: 15px; margin: 0 12px 0 0; letter-spacing: .3px; }
header label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
header .live { color: var(--text); }
header .live:has(input:checked) { color: var(--accent-2); font-weight: 600; }
.spacer { flex: 1; }
#status { color: var(--muted); font-variant-numeric: tabular-nums; max-width: 36ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#status.err { color: var(--danger); }
#status.ok { color: var(--ok); }
main {
flex: 1;
display: grid;
grid-template-columns: 420px 1fr;
min-height: 0;
}
#controls {
overflow-y: auto;
padding: 10px;
display: flex;
flex-direction: column;
gap: 10px;
border-right: 1px solid var(--line);
}
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 10px 12px;
}
.card h2 {
margin: 0 0 8px;
font-size: 12px;
text-transform: uppercase;
letter-spacing: .8px;
color: var(--muted);
display: flex;
justify-content: space-between;
gap: 8px;
}
.card h2 small { text-transform: none; letter-spacing: 0; font-weight: 400; color: var(--muted); opacity: .8; }
.row { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: end; margin: 6px 0; }
.row label { display: flex; flex-direction: column; gap: 3px; color: var(--muted); font-size: 12px; }
.row label.grow { flex: 1; }
.row label.check { flex-direction: row; align-items: center; color: var(--text); }
.row label input:not([type=checkbox]), .row label select { width: 100%; }
input, select, button {
font: inherit;
color: var(--text);
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 5px;
padding: 5px 7px;
}
input[type=number] { width: 7ch; }
input[type=checkbox] { width: auto; accent-color: var(--accent); }
input:focus, select:focus { outline: 1px solid var(--accent); border-color: var(--accent); }
button { cursor: pointer; }
button:hover { border-color: var(--accent); }
button.primary { background: var(--accent); border-color: var(--accent); color: #0b1220; font-weight: 600; }
button.danger { color: var(--danger); }
button:disabled { opacity: .5; cursor: default; }
.tabs { display: flex; gap: 4px; margin-top: 6px; }
.tabs button { flex: 1; background: transparent; color: var(--muted); }
.tabs button.active { background: var(--panel-2); color: var(--text); border-color: var(--accent); }
.hint { color: var(--muted); font-size: 12px; margin: 6px 0 0; }
.hint b { color: var(--text); }
/* sliders: label | range | number */
.slider { display: grid; grid-template-columns: 92px 1fr 64px; gap: 8px; align-items: center; margin: 4px 0; }
.slider span { color: var(--muted); font-size: 12px; }
.slider input[type=range] { width: 100%; padding: 0; background: transparent; border: 0; accent-color: var(--accent); }
.slider input[type=number] { width: 100%; }
/* fixtures */
.fixture { display: grid; grid-template-columns: auto 1fr; gap: 4px 8px; padding: 6px 0; border-top: 1px solid var(--line); }
.fixture:first-child { border-top: 0; }
.fixture .name { display: flex; align-items: center; gap: 8px; grid-column: 1 / -1; }
.fixture .name .swatch { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
.fixture .name small { color: var(--muted); }
.fixture .opts { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; padding-left: 26px; }
.fixture .opts label { display: flex; align-items: center; gap: 4px; color: var(--muted); font-size: 12px; }
.fixture.off .opts { display: none; }
.fixture.notmover { opacity: .45; }
/* points table */
#point-table { width: 100%; border-collapse: collapse; }
#point-table th { color: var(--muted); font-weight: 500; text-align: left; font-size: 11px; padding: 2px 4px; }
#point-table td { padding: 2px 4px; }
#point-table td input { width: 100%; padding: 3px 5px; }
#point-table tr.sel td { background: rgba(90, 169, 255, .12); }
#point-table tr td:first-child { color: var(--muted); font-variant-numeric: tabular-nums; width: 2.5ch; }
.list { list-style: none; margin: 4px 0 0; padding: 0; max-height: 220px; overflow-y: auto; }
.list li { display: flex; align-items: center; gap: 8px; padding: 4px 0; border-top: 1px solid var(--line); }
.list li:first-child { border-top: 0; }
.list li .lname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.list li small { color: var(--muted); }
.list li button { padding: 2px 8px; font-size: 12px; }
.list .empty { color: var(--muted); font-style: italic; }
.result { color: var(--muted); font-size: 12px; }
.result.ok { color: var(--ok); }
.result.err { color: var(--danger); }
/* stage */
#stage { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.toolbar { display: flex; align-items: center; gap: 12px; padding: 8px 12px; border-bottom: 1px solid var(--line); background: var(--panel); }
.toolbar label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
#time { color: var(--muted); font-variant-numeric: tabular-nums; min-width: 12ch; }
#canvas { flex: 1; width: 100%; height: 100%; display: block; cursor: crosshair; touch-action: none; }
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env bash
# Flash LuxDMX onto a Seeed Studio XIAO ESP32S3.
#
# The XIAO is an ESP32-S3R8 (octal 8 MB PSRAM, native USB only). It shows up
# as an Espressif "USB JTAG/serial" port (/dev/ttyACM*), not a ttyUSB UART
# dongle. This downloads the current LuxDMX release and writes the
# octal-PSRAM image. esptool detects the flash size and rewrites the image
# header to match (this board reports 16 MB). The partition table ends at
# 4 MB, so either size fits. The write is a full erase, so the first boot
# opens the setup access point.
#
# scripts/flash_luxdmx_xiao.sh
# scripts/flash_luxdmx_xiao.sh --port /dev/ttyACM0
# scripts/flash_luxdmx_xiao.sh --plain # leave the PSRAM unused
# scripts/flash_luxdmx_xiao.sh --version v1.0.273
# scripts/flash_luxdmx_xiao.sh --dry-run
#
# A full USB flash erases saved Wi-Fi and config. To update a board that is
# already set up, use the device's own Firmware Update page instead.
#
# After it boots, join the open Wi-Fi "LuxDMX-setup" and open
# http://192.168.4.1. In /config apply the "Seeed XIAO ESP32-S3" template:
# DMX data is D0 (GPIO1) and the RDM return is D1 (GPIO2). The DevKit
# defaults (GPIO16/17) are not broken out on this board.
set -euo pipefail
REPO="tombueng/LuxDMX"
TAG="latest"
PORT=""
PLAIN=0
YES=0
DRY=0
BAUD=921600
usage() {
sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'
exit 2
}
while [[ $# -gt 0 ]]; do
case "$1" in
--port) PORT="${2:?}"; shift 2 ;;
--version) TAG="${2:?}"; shift 2 ;;
--baud) BAUD="${2:?}"; shift 2 ;;
--plain) PLAIN=1; shift ;;
--yes) YES=1; shift ;;
--dry-run) DRY=1; shift ;;
-h|--help) usage ;;
*) echo "Unknown option: $1" >&2; usage ;;
esac
done
# Ubuntu's esptool package is missing the ESP32-S3 flasher stub, so a
# version check is not enough. Use it only when that stub is actually there.
esptool_has_s3_stub() {
"$1" - << 'PY'
import pathlib, sys
try:
import esptool
except ImportError:
sys.exit(1)
root = pathlib.Path(esptool.__file__).resolve().parent / "targets" / "stub_flasher"
ok = (root / "stub_flasher_32s3.json").is_file() or any(root.glob("*/esp32s3.json"))
sys.exit(0 if ok else 1)
PY
}
if esptool_has_s3_stub python3; then
ESPTOOL=(python3 -m esptool)
else
VENV="${XDG_CACHE_HOME:-$HOME/.cache}/luxdmx/esptool-venv"
if [[ ! -x "$VENV/bin/python" ]] || ! esptool_has_s3_stub "$VENV/bin/python"; then
echo "System esptool has no ESP32-S3 stub. Installing one into ${VENV}…"
python3 -m venv "$VENV"
"$VENV/bin/pip" install -q 'esptool>=4.8,<5'
fi
ESPTOOL=("$VENV/bin/python" -m esptool)
fi
if [[ "$PLAIN" -eq 1 ]]; then
BOOT="bootloader-esp32s3.bin"
PARTS="partitions-esp32s3.bin"
APP="firmware-esp32s3.bin"
IMAGE="plain ESP32-S3 (PSRAM left unused)"
else
BOOT="bootloader-esp32s3-psram.bin"
PARTS="partitions-esp32s3-psram.bin"
APP="firmware-esp32s3-psram.bin"
IMAGE="ESP32-S3 octal PSRAM (XIAO ESP32S3 / S3R8)"
fi
find_port() {
if [[ -n "$PORT" ]]; then
[[ -e "$PORT" ]] || { echo "Port not found: $PORT" >&2; exit 1; }
echo "$PORT"
return
fi
local -a matches=()
local p
shopt -s nullglob
for p in /dev/serial/by-id/*; do
case "$p" in
*[Ee]spressif*|*[Ss]eeed*|*[Xx][Ii][Aa][Oo]*)
matches+=("$(readlink -f "$p")")
;;
esac
done
shopt -u nullglob
if [[ ${#matches[@]} -eq 1 ]]; then
echo "${matches[0]}"
return
fi
if [[ ${#matches[@]} -gt 1 ]]; then
echo "More than one Espressif/Seeed serial port. Pass --port." >&2
printf ' %s\n' "${matches[@]}" >&2
exit 1
fi
shopt -s nullglob
matches=(/dev/ttyACM*)
shopt -u nullglob
if [[ ${#matches[@]} -eq 1 && -e "${matches[0]}" ]]; then
echo "${matches[0]}"
return
fi
echo "No XIAO found. Plug in the USB-C port, then re-run." >&2
echo "If it still does not appear: hold B, tap R, release B, and pass --port." >&2
exit 1
}
CACHE_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/luxdmx"
mkdir -p "$CACHE_ROOT"
mapfile -t DL < <(python3 - "$CACHE_ROOT" "$TAG" "$BOOT" "$PARTS" "boot_app0.bin" "$APP" << 'PY'
import json, pathlib, sys, urllib.request
cache_root, tag, *names = sys.argv[1:]
api = f"https://api.github.com/repos/tombueng/LuxDMX/releases/tags/{tag}"
req = urllib.request.Request(api, headers={"Accept": "application/vnd.github+json", "User-Agent": "luxdmx-flash"})
with urllib.request.urlopen(req, timeout=60) as resp:
release = json.load(resp)
name = release.get("name") or release.get("tag_name") or tag
# "Latest → v1.0.273 (....)" — cache by the version, not the moving tag.
version = name
for token in name.replace("→", " ").replace("(", " ").split():
if token.startswith("v") and token[1:2].isdigit():
version = token
break
assets = {a["name"]: a for a in release.get("assets", [])}
missing = [n for n in names if n not in assets]
if missing:
sys.exit(f"Release {version} has no {', '.join(missing)}")
dest = pathlib.Path(cache_root) / version
dest.mkdir(parents=True, exist_ok=True)
for n in names:
path = dest / n
size = assets[n]["size"]
if path.is_file() and path.stat().st_size == size:
continue
url = assets[n]["browser_download_url"]
tmp = path.with_suffix(path.suffix + ".part")
urllib.request.urlretrieve(url, tmp)
if tmp.stat().st_size != size:
tmp.unlink(missing_ok=True)
sys.exit(f"Short download: {n}")
tmp.replace(path)
print(version)
print(dest)
PY
)
VERSION="${DL[0]}"
DIR="${DL[1]}"
PORT="$(find_port)"
echo "LuxDMX ${VERSION} (${IMAGE})"
echo "Port ${PORT} baud ${BAUD}"
echo "This erases the whole flash, including saved Wi-Fi and config."
if [[ "$DRY" -eq 1 ]]; then
echo "Dry run — not flashing."
exit 0
fi
if [[ "$YES" -ne 1 ]]; then
if [[ ! -t 0 ]]; then
echo "Pass --yes to flash without a prompt." >&2
exit 1
fi
read -r -p "Flash now? [y/N] " ans
[[ "$ans" == [yY] ]] || { echo "Cancelled."; exit 1; }
fi
set +e
"${ESPTOOL[@]}" --chip esp32s3 --port "$PORT" --baud "$BAUD" \
--before default_reset --after hard_reset \
write_flash --erase-all --flash_mode keep --flash_freq keep --flash_size detect --compress \
0x0000 "${DIR}/${BOOT}" \
0x8000 "${DIR}/${PARTS}" \
0xe000 "${DIR}/boot_app0.bin" \
0x10000 "${DIR}/${APP}"
rc=$?
set -e
if [[ $rc -ne 0 ]]; then
echo >&2
echo "Flash failed. Put the XIAO in download mode and run this again:" >&2
echo " hold B, tap R, release B, then: $0 --port $PORT --yes" >&2
exit $rc
fi
cat << 'EOF'
Flashed. On first boot the XIAO opens an open Wi-Fi network:
SSID LuxDMX-setup
URL http://192.168.4.1
In /config, apply the "Seeed XIAO ESP32-S3" template so the DMX pins
match the header (D0 = data out, D1 = RDM return). Then point QLC+
Art-Net at the address shown there, universe 0.
EOF
+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env python3
"""Build shows/midi.qxw — M-VAVE SMC-PAD controlling 20× BCC145 (Dim + RGBW)."""
from __future__ import annotations
import re
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "shows" / "midi.qxw"
PROFILE_SRC = ROOT / "inputprofiles" / "M-VAVE-SMC-PAD.qxi"
PROFILE_DST = Path.home() / ".qlcplus" / "inputprofiles" / "M-VAVE-SMC-PAD.qxi"
PROFILE_NAME = "M-VAVE SMC-PAD"
MIDI_UNIVERSE_ID = 1 # Universe 2
OMNI_MIDICHANNEL = 16 # pads ch10 + knobs ch1
PAD_MIDI_CH = 9
# 20× BCC145, 8ch mode, physical/UI start channel 88
# QLC XML Address is 0-based: Address 87 → DMX/UI channel 88 (same as xchc.qxw).
BCC_COUNT = 20
BCC_START_ADDRESS = 87
BCC_CHANNELS = 8
UNIVERSE_CHANNELS = BCC_START_ADDRESS + BCC_COUNT * BCC_CHANNELS # 247
# 8ch map: 0 Dim, 1 Strobe, 2–5 RGBW, 6 Macro, 7 Speed
STROBE_CH, MACRO_CH, SPEED_CH = 1, 6, 7
# Knob bank 1 (CC 30–37): knobs 1–8 — master Dim/RGBW/Strobe/Macro/Speed
# Knob bank 2 (CC 38–44): knobs 9–15 — Dim boost for #9–#15 (HTP vs master)
KNOB_BANK1 = [
# (cc, caption, widget_id, dmx_ch, fg, cng, value, fixtures|None)
(32, "Dim", 0, 0, "4294967295", "None", 200, None),
(36, "R", 1, 2, "4294901760", "Red", 0, None),
(37, "G", 2, 3, "4278255360", "Green", 0, None),
(34, "B", 3, 4, "4278190335", "Blue", 0, None),
(35, "W", 4, 5, "4294967295", "None", 0, None),
(33, "Strobe", 5, STROBE_CH, "4294922844", "None", 0, None),
(30, "Macro", 6, MACRO_CH, "4288256409", "None", 0, None),
(31, "Speed", 7, SPEED_CH, "4286611584", "None", 0, None),
]
KNOB_BANK2 = [
# (cc, caption, widget_id, fixture_id)
(38, "F9", 20, 8),
(39, "F10", 21, 9),
(40, "F11", 22, 10),
(41, "F12", 23, 11),
(42, "F13", 24, 12),
(43, "F14", 25, 13),
(44, "F15", 26, 14),
]
# 4×4 pads → colour flashes / utility (scenes built below)
# note 36..51 with OMNI encoding
PAD_COLORS = [
# (name, r, g, b, w) — bottom row left→right, then up
("Red", 255, 0, 0, 0),
("Green", 0, 255, 0, 0),
("Blue", 0, 0, 255, 0),
("White", 0, 0, 0, 255),
("Yellow", 255, 255, 0, 0),
("Cyan", 0, 255, 255, 0),
("Magenta", 255, 0, 255, 0),
("Orange", 255, 80, 0, 0),
("Warm", 255, 120, 40, 80),
("Cool", 80, 120, 255, 40),
("Pink", 255, 40, 120, 0),
("Lime", 120, 255, 0, 0),
("Full", 255, 255, 255, 255),
("Half", 128, 128, 128, 128),
("Dim50", 0, 0, 0, 0), # blackout colour; dim stays
("Black", 0, 0, 0, 0),
]
def detect_midi_uid() -> str:
"""Prefer smoothed virtual port when the smoother daemon is running."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
out = ""
for name in (
"SMC-PAD Smooth",
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
):
if name in out:
return name
return "SMC-PAD Bluetooth"
ARTNET_OUTPUT_IP = "192.168.1.175"
# Device Art-Net universe (IceRay SwOut); keep in sync with the box
ARTNET_OUTPUT_UNI = "0"
ARTNET_LINE = "0"
def detect_artnet_uid() -> str:
"""Local IPv4 on the same /24 as the Art-Net node (prefer wlan/eth)."""
try:
out = subprocess.check_output(["ip", "-4", "-o", "addr", "show"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return "192.168.1.90"
prefix = ".".join(ARTNET_OUTPUT_IP.split(".")[:3]) + "."
candidates: list[str] = []
for line in out.splitlines():
# 2: wlo1 inet 192.168.1.90/24 ...
parts = line.split()
if len(parts) < 4 or parts[2] != "inet":
continue
ip = parts[3].split("/", 1)[0]
iface = parts[1]
if ip.startswith(prefix) and not iface.startswith(("lo", "vir", "docker", "br-", "mpq")):
candidates.append(ip)
return candidates[0] if candidates else "192.168.1.90"
def output_xml() -> str:
uid = detect_artnet_uid()
return f""" <Output Plugin="ArtNet" UID="{uid}" Line="{ARTNET_LINE}">
<PluginParameters outputIP="{ARTNET_OUTPUT_IP}" outputUni="{ARTNET_OUTPUT_UNI}" UniverseChannels="{UNIVERSE_CHANNELS}"/>
</Output>"""
def install_profile() -> None:
PROFILE_DST.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(PROFILE_SRC, PROFILE_DST)
def appearance(fg: str = "Default") -> str:
return f""" <Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>{fg}</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>"""
def fixture_ids() -> range:
return range(BCC_COUNT)
def slider(
wid: int,
caption: str,
x: int,
y: int,
dmx_ch: int,
*,
fg: str,
cng: str,
value: int,
midi_cc: int | None,
fixtures: range | list[int] | None = None,
width: int = 60,
height: int = 280,
) -> str:
inp = ""
if midi_cc is not None:
inp = f'\n <Input Universe="{MIDI_UNIVERSE_ID}" Channel="{midi_cc}"/>'
fids = list(fixture_ids() if fixtures is None else fixtures)
channels = "\n".join(
f' <Channel Fixture="{fid}">{dmx_ch}</Channel>' for fid in fids
)
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{width}" Height="{height}"/>
{appearance(fg)}
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="true">Level</SliderMode>
<Level LowLimit="0" HighLimit="255" Value="{value}">
{channels}
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>{inp}
</Slider>"""
def scene_xml(fid: int, name: str, r: int, g: int, b: int, w: int) -> str:
# BCC145 8ch: Dim left to slider; force Strobe/Macro/Speed off; set RGBW.
vals = [
(STROBE_CH, 0),
(2, r),
(3, g),
(4, b),
(5, w),
(MACRO_CH, 0),
(SPEED_CH, 0),
]
fv = "\n".join(
f' <FixtureVal ID="{fx}" Channel="{ch}">{v}</FixtureVal>'
for fx in fixture_ids()
for ch, v in vals
)
return f""" <Function ID="{fid}" Type="Scene" Name="{name}">
<Bus Role="Fade">1</Bus>
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<Direction>Forward</Direction>
<RunOrder>Loop</RunOrder>
{fv}
</Function>"""
def fixtures_xml() -> str:
blocks = []
for i in fixture_ids():
addr = BCC_START_ADDRESS + i * BCC_CHANNELS
blocks.append(
f""" <Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>{i}</ID>
<Name>BCC145 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{addr}</Address>
<Channels>{BCC_CHANNELS}</Channels>
</Fixture>"""
)
return "\n".join(blocks)
def button_xml(wid: int, caption: str, x: int, y: int, func_id: int, midi_ch: int, bg: str) -> str:
return f""" <Button Caption="{caption}" ID="{wid}" Icon="">
<WindowState Visible="True" X="{x}" Y="{y}" Width="70" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="{func_id}"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
<Input Universe="{MIDI_UNIVERSE_ID}" Channel="{midi_ch}"/>
</Button>"""
def bg_color(r: int, g: int, b: int) -> str:
# QLC packed ARGB as decimal
return str((0xFF << 24) | (r << 16) | (g << 8) | b)
def build(uid: str) -> str:
functions = []
buttons = []
for i, (name, r, g, b, w) in enumerate(PAD_COLORS):
fid = 10 + i
note = 36 + i
midi_ch = (PAD_MIDI_CH << 12) | (128 + note)
functions.append(scene_xml(fid, name, r, g, b, w))
row, col = divmod(i, 4)
# pad grid: bottom row is notes 36-39 → visual row 3
vx = 20 + col * 80
vy = 20 + (3 - row) * 66
buttons.append(
button_xml(10 + i, name, vx, vy, fid, midi_ch, bg_color(r, g, b))
)
sliders = []
for i, (cc, cap, wid, dmx, fg, cng, val, fxs) in enumerate(KNOB_BANK1):
sliders.append(
slider(
wid,
cap,
360 + i * 58,
20,
dmx,
fg=fg,
cng=cng,
value=val,
midi_cc=cc,
fixtures=fxs,
)
)
for i, (cc, cap, wid, fx) in enumerate(KNOB_BANK2):
sliders.append(
slider(
wid,
cap,
360 + i * 58,
310,
0, # Dim
fg="4294967295",
cng="None",
value=200,
midi_cc=cc,
fixtures=[fx],
height=120,
)
)
vc_widgets = "\n".join(buttons + sliders)
funcs = "\n".join(functions)
fixtures = fixtures_xml()
dmx_out = output_xml()
return f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
{dmx_out}
</Universe>
<Universe Name="Universe 2" ID="1">
<Input Plugin="MIDI" UID="{uid}" Line="0" Profile="{PROFILE_NAME}">
<PluginParameters midichannel="{OMNI_MIDICHANNEL}"/>
</Input>
</Universe>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
{fixtures}
{funcs}
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
{vc_widgets}
</Frame>
<Properties>
<Size Width="900" Height="460"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
"""
def patch_qsettings(uid: str) -> None:
conf = Path.home() / ".config" / "qlcplus" / "Q Light Controller Plus.conf"
if not conf.exists():
return
text = conf.read_text()
key = uid.replace(" ", "%20")
pattern = rf"(Input\\{re.escape(key)}\\midichannel=)\d+"
if re.search(pattern, text):
text = re.sub(pattern, rf"\g<1>{OMNI_MIDICHANNEL}", text)
elif "[midiplugin]" in text and f"Input\\{key}\\midichannel=" not in text:
text = text.replace(
"[midiplugin]\n",
f"[midiplugin]\nInput\\{key}\\midichannel={OMNI_MIDICHANNEL}\n"
f"Input\\{key}\\mode=Control Change\n"
f"Input\\{key}\\initmessage=\n",
1,
)
conf.write_text(text)
def main() -> None:
uid = detect_midi_uid()
install_profile()
patch_qsettings(uid)
OUT.write_text(build(uid))
ui_start = BCC_START_ADDRESS + 1
ui_last = BCC_START_ADDRESS + BCC_COUNT * BCC_CHANNELS
print(f"Wrote {OUT}")
print(f" MIDI: {uid} OMNI on Universe 2")
print(
f" Art-Net → {ARTNET_OUTPUT_IP} uni {ARTNET_OUTPUT_UNI} "
f"(local {detect_artnet_uid()})"
)
print(
f" {BCC_COUNT}× BCC145 8ch @ UI {ui_start}–{ui_last} "
f"(XML Address {BCC_START_ADDRESS}–{BCC_START_ADDRESS + (BCC_COUNT - 1) * BCC_CHANNELS})"
)
print(" Bank1 knobs 1–8: Dim/RGBW/Strobe/Macro/Speed (all)")
print(" Bank2 knobs 9–15: Dim for #9–#15")
print(" 16 pads → colour scenes (all fixtures; strobe/macro forced off)")
if __name__ == "__main__":
main()
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
# Launch Mover Pattern Studio (local web app) for the shows in this repo.
# scripts/pattern_studio.sh # opens http://127.0.0.1:8765 in your browser
# scripts/pattern_studio.sh --port 9000 --no-browser
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 -m patternstudio "$@"
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""Smooth SMC-PAD knob CCs so RGBW fades feel less stepped.
Reads the physical pad (Bluetooth or USB), passes pad notes through
immediately, and eases Control Change values toward their targets at
~120 Hz before emitting on a virtual port named "SMC-PAD Smooth".
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the smoother is running).
Usage:
.venv/bin/python scripts/smooth_smc_pad.py
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
"""
from __future__ import annotations
import argparse
import math
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
import glob
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
sys.path.insert(0, p)
import rtmidi
VIRTUAL_NAME = "SMC-PAD Smooth"
SOURCE_HINTS = (
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
"SMC-PAD",
)
def find_source_port(midiin: rtmidi.MidiIn) -> int:
ports = midiin.get_ports()
for hint in SOURCE_HINTS:
for i, name in enumerate(ports):
if hint in name and VIRTUAL_NAME not in name:
return i
raise SystemExit(
"No SMC-PAD MIDI source found. Ports:\n " + "\n ".join(ports or ["(none)"])
)
def _alsa_port(client_substr: str, port_substr: str | None = None) -> str | None:
"""Return 'client:port' for an aconnect client/port name match."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return None
client = None
client_name = None
for line in out.splitlines():
m = re.match(r"client (\d+): '([^']+)'", line)
if m:
client, client_name = int(m.group(1)), m.group(2)
continue
m = re.match(r"\s+(\d+)\s+'([^']+)'", line)
if not m or client is None or client_name is None:
continue
port, pname = int(m.group(1)), m.group(2).strip()
if client_substr not in client_name and client_substr not in pname:
continue
if port_substr and port_substr not in pname and port_substr not in client_name:
continue
if VIRTUAL_NAME in pname:
continue
return f"{client}:{port}"
return None
def ensure_alsa_link() -> None:
"""Bluetooth MIDI sometimes drops the ALSA subscription; re-subscribe."""
src = None
for hint in ("SMC-PAD Bluetooth", "SINCO", "SMC-PAD"):
src = _alsa_port(hint)
if src:
break
dst = _alsa_port("smc-smooth-in")
if not src or not dst:
return
subprocess.run(["aconnect", src, dst], capture_output=True)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--tau",
type=float,
default=0.055,
help="smoothing time constant in seconds (default 0.055)",
)
ap.add_argument("--rate", type=float, default=120.0, help="update Hz")
args = ap.parse_args()
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-in")
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-out")
src = find_source_port(midiin)
src_name = midiin.get_ports()[src]
midiin.open_port(src)
midiin.ignore_types(timing=True, active_sense=True, sysex=True)
midiout.open_virtual_port(VIRTUAL_NAME)
# current/target as floats 0..127, keyed by (channel, cc)
current: dict[tuple[int, int], float] = {}
target: dict[tuple[int, int], float] = {}
last_sent: dict[tuple[int, int], int] = {}
print(f"Source: {src_name}", flush=True)
print(f"Virtual: {VIRTUAL_NAME} (tau={args.tau}s @ {args.rate} Hz)", flush=True)
print("Pass notes through; smooth CC. Ctrl+C to stop.", flush=True)
ensure_alsa_link()
dt = 1.0 / args.rate
alpha = 1.0 - math.exp(-dt / max(args.tau, 1e-4))
next_link_check = time.monotonic() + 2.0
try:
while True:
now = time.monotonic()
if now >= next_link_check:
ensure_alsa_link()
next_link_check = now + 2.0
# Drain inbound
while True:
msg = midiin.get_message()
if msg is None:
break
data, _ = msg
if not data:
continue
status = data[0]
cmd = status & 0xF0
ch = status & 0x0F
if cmd == 0xB0 and len(data) >= 3:
# Control Change → smooth
cc, val = data[1], data[2]
key = (ch, cc)
target[key] = float(val)
if key not in current:
current[key] = float(val)
last_sent[key] = -1
else:
# Notes, aftertouch, PC, etc. → immediate
midiout.send_message(data)
# Ease CC toward targets and emit when quantized value moves
for key, tgt in list(target.items()):
cur = current.get(key, tgt)
cur = cur + (tgt - cur) * alpha
# Snap when close so we actually reach the endpoint
if abs(tgt - cur) < 0.15:
cur = tgt
current[key] = cur
q = int(round(cur))
q = 0 if q < 0 else 127 if q > 127 else q
if last_sent.get(key) != q:
ch, cc = key
midiout.send_message([0xB0 | ch, cc, q])
last_sent[key] = q
time.sleep(dt)
except KeyboardInterrupt:
print("\nStopped.", flush=True)
finally:
midiin.close_port()
midiout.close_port()
del midiin
del midiout
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Reliable MIDI bring-up for shows/midi.qxw
#
# Order matters:
# 1) pad present (Bluetooth or USB)
# 2) smoother (creates "SMC-PAD Smooth")
# 3) patch workspace to that port
# 4) open QLC+ last
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
PYTHON="${ROOT}/.venv/bin/python"
[[ -x "$PYTHON" ]] || PYTHON=python3
pad_present() {
aconnect -l 2>/dev/null | grep -Eq "SMC-PAD Bluetooth|SINCO|SMC-PAD"
}
echo "Waiting for SMC-PAD (Bluetooth or USB)…"
for _ in $(seq 1 30); do
if pad_present; then
break
fi
sleep 1
done
if ! pad_present; then
echo "No SMC-PAD in aconnect -l. Pair/connect the pad, then re-run." >&2
aconnect -l >&2 || true
exit 1
fi
# Restart smoother so it re-opens the pad port cleanly (avoid pkill -f; it matches this script)
while read -r pid; do
[[ -n "$pid" ]] && kill "$pid" 2>/dev/null || true
done < <(ps -eo pid,args | awk '/[.]venv\/bin\/python .*smooth_smc_pad[.]py/ {print $1}')
sleep 0.4
nohup "$PYTHON" scripts/smooth_smc_pad.py --tau 0.055 >>/tmp/smooth_smc_pad.log 2>&1 &
for _ in $(seq 1 20); do
if aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
break
fi
sleep 0.25
done
if ! aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
echo "Smoother failed to create SMC-PAD Smooth. See /tmp/smooth_smc_pad.log" >&2
tail -20 /tmp/smooth_smc_pad.log >&2 || true
exit 1
fi
python3 scripts/patch_smc_pad.py
kill "$(pgrep -x qlcplus)" 2>/dev/null || true
sleep 0.5
nohup qlcplus --open "$ROOT/shows/midi.qxw" >/tmp/qlcplus.log 2>&1 &
sleep 1.5
echo
echo "Chain (expect pad → Smooth → qlcplus):"
aconnect -l | grep -E "SMC-PAD|SINCO|Smooth|qlcplus|smc-smooth" -A2 || aconnect -l
echo
echo "OK — twist a knob / hit a pad. If silent: re-run this script (don't pick Midi Through in IO)."
+358
View File
@@ -0,0 +1,358 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
<Output Plugin="ArtNet" UID="10.1.1.202" Line="0">
<PluginParameters outputIP="10.1.1.201" outputUni="1"/>
</Output>
</Universe>
<Universe Name="Universe 2" ID="1"/>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>0</ID>
<Name>BCC145</Name>
<Universe>0</Universe>
<Address>0</Address>
<Channels>8</Channels>
</Fixture>
<ChannelsGroup ID="0" Name="Red" Value="0">0,2</ChannelsGroup>
<ChannelsGroup ID="1" Name="Green" Value="0">0,3</ChannelsGroup>
<ChannelsGroup ID="2" Name="Blue" Value="0">0,4</ChannelsGroup>
<ChannelsGroup ID="3" Name="White" Value="0">0,5</ChannelsGroup>
<ChannelsGroup ID="4" Name="Dimmer" Value="0">0,0</ChannelsGroup>
<Function ID="0" Type="Scene" Name="Red" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,0,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="1" Type="Scene" Name="Orange" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,127,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="2" Type="Scene" Name="Yellow" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,255,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="3" Type="Scene" Name="Green" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,255,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="4" Type="Scene" Name="Cyan" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,255,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="5" Type="Scene" Name="Blue" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,0,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="6" Type="Scene" Name="Violet" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,127,3,0,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="7" Type="Scene" Name="Magenta" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,0,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="8" Type="Scene" Name="White" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,0,4,0,5,255,6,0,7,0</FixtureVal>
</Function>
<Function ID="9" Type="Scene" Name="Blackout" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,0,1,0,2,0,3,0,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="10" Type="Scene" Name="Built-in Gradient">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,0,4,0,5,0,6,225,7,80</FixtureVal>
</Function>
<Function ID="11" Type="Chaser" Name="Color Transition">
<Speed FadeIn="3000" FadeOut="0" Duration="4000"/>
<Direction>Forward</Direction>
<RunOrder>Loop</RunOrder>
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common"/>
<Step Number="0" FadeIn="3000" Hold="1000" FadeOut="0">0</Step>
<Step Number="1" FadeIn="3000" Hold="1000" FadeOut="0">1</Step>
<Step Number="2" FadeIn="3000" Hold="1000" FadeOut="0">2</Step>
<Step Number="3" FadeIn="3000" Hold="1000" FadeOut="0">3</Step>
<Step Number="4" FadeIn="3000" Hold="1000" FadeOut="0">4</Step>
<Step Number="5" FadeIn="3000" Hold="1000" FadeOut="0">5</Step>
<Step Number="6" FadeIn="3000" Hold="1000" FadeOut="0">6</Step>
<Step Number="7" FadeIn="3000" Hold="1000" FadeOut="0">7</Step>
</Function>
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Slider Caption="Dim" ID="0" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="20" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="166">
<Channel Fixture="0">0</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="R" ID="1" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="72" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294901760</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Red" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">2</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="G" ID="2" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="124" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278255360</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Green" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">3</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="B" ID="3" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="176" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278190335</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Blue" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">4</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="W" ID="4" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="228" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">5</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Button Caption="Color Transition" ID="5" Icon="">
<WindowState Visible="True" X="300" Y="20" Width="180" Height="70"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4282664004</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="11"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Built-in Gradient" ID="6" Icon="">
<WindowState Visible="True" X="490" Y="20" Width="180" Height="70"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4280427042</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="10"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Blackout" ID="7" Icon="">
<WindowState Visible="True" X="680" Y="20" Width="120" Height="70"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4278190080</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="9"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Red" ID="8" Icon="">
<WindowState Visible="True" X="300" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4294901760</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="0"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Orange" ID="9" Icon="">
<WindowState Visible="True" X="390" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294944000</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="1"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Yellow" ID="10" Icon="">
<WindowState Visible="True" X="480" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294967040</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="2"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Green" ID="11" Icon="">
<WindowState Visible="True" X="570" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4278255360</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="3"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Cyan" ID="12" Icon="">
<WindowState Visible="True" X="660" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4278255615</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="4"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Blue" ID="13" Icon="">
<WindowState Visible="True" X="300" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4278190335</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="5"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Violet" ID="14" Icon="">
<WindowState Visible="True" X="390" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4286578687</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="6"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Magenta" ID="15" Icon="">
<WindowState Visible="True" X="480" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4294902015</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="7"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="White" ID="16" Icon="">
<WindowState Visible="True" X="570" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294967295</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="8"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
</Frame>
<Properties>
<Size Width="860" Height="280"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
+272
View File
@@ -0,0 +1,272 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
<Output Plugin="ArtNet" UID="192.168.1.91" Line="7">
<PluginParameters outputIP="192.168.1.228"/>
</Output>
</Universe>
<Universe Name="Universe 2" ID="1"/>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>0</ID>
<Name>BCC145 #1</Name>
<Universe>0</Universe>
<Address>87</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>1</ID>
<Name>BCC145 #2</Name>
<Universe>0</Universe>
<Address>95</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>2</ID>
<Name>BCC145 #3</Name>
<Universe>0</Universe>
<Address>103</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>3</ID>
<Name>BCC145 #4</Name>
<Universe>0</Universe>
<Address>111</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>4</ID>
<Name>BCC145 #5</Name>
<Universe>0</Universe>
<Address>119</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>5</ID>
<Name>BCC145 #6</Name>
<Universe>0</Universe>
<Address>127</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>6</ID>
<Name>BCC145 #7</Name>
<Universe>0</Universe>
<Address>135</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>7</ID>
<Name>BCC145 #8</Name>
<Universe>0</Universe>
<Address>143</Address>
<Channels>8</Channels>
</Fixture>
<FixtureGroup ID="0">
<Name>Cans</Name>
<Size X="8" Y="1"/>
<Head X="0" Y="0" Fixture="0">0</Head>
<Head X="1" Y="0" Fixture="1">0</Head>
<Head X="2" Y="0" Fixture="2">0</Head>
<Head X="3" Y="0" Fixture="3">0</Head>
<Head X="4" Y="0" Fixture="4">0</Head>
<Head X="5" Y="0" Fixture="5">0</Head>
<Head X="6" Y="0" Fixture="6">0</Head>
<Head X="7" Y="0" Fixture="7">0</Head>
</FixtureGroup>
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Frame Caption="Cans RGBW" ID="0">
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<WindowState Visible="True" X="10" Y="10" Width="160" Height="24"/>
<AllowChildren>True</AllowChildren>
<AllowResize>True</AllowResize>
<ShowHeader>True</ShowHeader>
<ShowEnableButton>False</ShowEnableButton>
<Collapsed>False</Collapsed>
<Disabled>False</Disabled>
</Frame>
<Slider Caption="Dim" ID="1" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="10" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="255">
<Channel Fixture="0">0</Channel>
<Channel Fixture="1">0</Channel>
<Channel Fixture="2">0</Channel>
<Channel Fixture="3">0</Channel>
<Channel Fixture="4">0</Channel>
<Channel Fixture="5">0</Channel>
<Channel Fixture="6">0</Channel>
<Channel Fixture="7">0</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="R" ID="2" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="56" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294901760</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Red" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">2</Channel>
<Channel Fixture="1">2</Channel>
<Channel Fixture="2">2</Channel>
<Channel Fixture="3">2</Channel>
<Channel Fixture="4">2</Channel>
<Channel Fixture="5">2</Channel>
<Channel Fixture="6">2</Channel>
<Channel Fixture="7">2</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="G" ID="3" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="102" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278255360</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Green" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">3</Channel>
<Channel Fixture="1">3</Channel>
<Channel Fixture="2">3</Channel>
<Channel Fixture="3">3</Channel>
<Channel Fixture="4">3</Channel>
<Channel Fixture="5">3</Channel>
<Channel Fixture="6">3</Channel>
<Channel Fixture="7">3</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="B" ID="4" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="148" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278190335</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Blue" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">4</Channel>
<Channel Fixture="1">4</Channel>
<Channel Fixture="2">4</Channel>
<Channel Fixture="3">4</Channel>
<Channel Fixture="4">4</Channel>
<Channel Fixture="5">4</Channel>
<Channel Fixture="6">4</Channel>
<Channel Fixture="7">4</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="W" ID="5" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="194" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">5</Channel>
<Channel Fixture="1">5</Channel>
<Channel Fixture="2">5</Channel>
<Channel Fixture="3">5</Channel>
<Channel Fixture="4">5</Channel>
<Channel Fixture="5">5</Channel>
<Channel Fixture="6">5</Channel>
<Channel Fixture="7">5</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
</Frame>
<Properties>
<Size Width="320" Height="320"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
+3225
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff