Add a show compiler so QLC+ workspaces can be described and tested.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
fee1985e1a
commit
4374ffb430
14 files changed
+3739
No files matched your search
@@ -0,0 +1,252 @@
|
||||
"""Operations behind the CLI and the MCP server."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from patternstudio.efx import (
|
||||
ALGORITHMS,
|
||||
DIRECTIONS,
|
||||
PROPAGATIONS,
|
||||
RUN_ORDERS,
|
||||
Efx,
|
||||
EfxFixture,
|
||||
Path as EfxPath,
|
||||
PathFixture,
|
||||
PathPoint,
|
||||
)
|
||||
from patternstudio.fixturedefs import load_fixture_def
|
||||
|
||||
from .play import load_show, play
|
||||
from .spec import PROJECT_ROOT, SpecError, collect_errors, from_spec, show_schema
|
||||
|
||||
__all__ = [
|
||||
"list_fixtures",
|
||||
"sample_animation",
|
||||
"show_schema",
|
||||
"validate_show",
|
||||
"write_show",
|
||||
"run_script",
|
||||
]
|
||||
|
||||
|
||||
def list_fixtures(root: Path | None = None) -> dict[str, Any]:
|
||||
"""Manufacturer, model, modes, and channel maps from the project's fixtures/ directory."""
|
||||
folder = (root or PROJECT_ROOT) / "fixtures"
|
||||
fixtures = []
|
||||
if folder.is_dir():
|
||||
for path in sorted(folder.glob("*.qxf")):
|
||||
definition = load_fixture_def(str(path))
|
||||
fixtures.append(
|
||||
{
|
||||
"manufacturer": definition.manufacturer,
|
||||
"model": definition.model,
|
||||
"type": definition.type,
|
||||
"modes": [
|
||||
{
|
||||
"name": mode.name,
|
||||
"pan_msb": mode.pan_msb,
|
||||
"pan_lsb": mode.pan_lsb,
|
||||
"tilt_msb": mode.tilt_msb,
|
||||
"tilt_lsb": mode.tilt_lsb,
|
||||
"channels": [
|
||||
{"index": ch.index, "name": ch.name, "preset": ch.preset, "group": ch.group}
|
||||
for ch in mode.channels
|
||||
],
|
||||
}
|
||||
for mode in definition.modes.values()
|
||||
],
|
||||
}
|
||||
)
|
||||
return {"fixtures": fixtures}
|
||||
|
||||
|
||||
def validate_show(spec: dict[str, Any], root: Path | None = None) -> dict[str, Any]:
|
||||
"""Check a show spec. Writes nothing."""
|
||||
errors = collect_errors(spec, root=root)
|
||||
return {"ok": not errors, "errors": errors}
|
||||
|
||||
|
||||
def write_show(spec: dict[str, Any], path: str, root: Path | None = None) -> dict[str, Any]:
|
||||
"""Write a .qxw inside the project and return the ids that were assigned."""
|
||||
base = (root or PROJECT_ROOT).resolve()
|
||||
try:
|
||||
target = _inside(base, path)
|
||||
show = from_spec(spec, root=base)
|
||||
except SpecError as exc:
|
||||
return {"ok": False, "errors": exc.errors}
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
show.write(target)
|
||||
return {"ok": True, "path": str(target.relative_to(base)), **show.summary()}
|
||||
|
||||
|
||||
def sample_animation(block: dict[str, Any], steps: int = 32) -> dict[str, Any]:
|
||||
"""Pan/tilt samples for one efx or path block, before it is written into a show."""
|
||||
if not isinstance(block, dict) or block.get("type") not in ("efx", "path"):
|
||||
return {"ok": False, "errors": [{"path": "type", "message": "sample an efx or path block"}]}
|
||||
count = max(1, min(128, int(steps)))
|
||||
try:
|
||||
if block["type"] == "efx":
|
||||
return {"ok": True, **_sample_efx(block, count)}
|
||||
return {"ok": True, **_sample_path(block)}
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
return {"ok": False, "errors": [{"path": "", "message": str(exc)}]}
|
||||
|
||||
|
||||
def run_script(
|
||||
path: str,
|
||||
*,
|
||||
seconds: float | None = None,
|
||||
ip: str | None = None,
|
||||
universe: int = 0,
|
||||
hz: float = 40.0,
|
||||
root: Path | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Play a Python build() script, or a JSON spec, and return samples or send Art-Net."""
|
||||
base = (root or PROJECT_ROOT).resolve()
|
||||
try:
|
||||
source = _inside(base, path)
|
||||
show = load_show(source)
|
||||
return play(show, seconds=seconds, ip=ip, universe=universe, hz=hz)
|
||||
except SpecError as exc:
|
||||
return {"ok": False, "errors": exc.errors}
|
||||
|
||||
|
||||
def _inside(root: Path, rel: str) -> Path:
|
||||
candidate = Path(rel)
|
||||
target = candidate.resolve() if candidate.is_absolute() else (root / candidate).resolve()
|
||||
if target != root and root not in target.parents:
|
||||
raise SpecError([{"path": "path", "message": f"{rel} is outside the project"}])
|
||||
return target
|
||||
|
||||
|
||||
def _sample_efx(block: dict[str, Any], steps: int) -> dict[str, Any]:
|
||||
algorithm = block.get("algorithm", "Circle")
|
||||
if algorithm not in ALGORITHMS:
|
||||
raise ValueError(f"unknown algorithm {algorithm!r}")
|
||||
_choice(block.get("direction", "Forward"), DIRECTIONS, "direction")
|
||||
_choice(block.get("run_order", "Loop"), RUN_ORDERS, "run_order")
|
||||
_choice(block.get("propagation", "Parallel"), PROPAGATIONS, "propagation")
|
||||
entries = block.get("fixtures") or []
|
||||
if not entries:
|
||||
raise ValueError("efx has no fixtures")
|
||||
relative = bool(block.get("relative"))
|
||||
homes = block.get("homes") or {}
|
||||
fixtures = []
|
||||
keys = []
|
||||
for index, item in enumerate(entries):
|
||||
if isinstance(item, str):
|
||||
key, direction, offset = item, "Forward", 0
|
||||
pan = tilt = 128
|
||||
elif isinstance(item, dict) and "fixture" in item:
|
||||
key = str(item["fixture"])
|
||||
direction = item.get("direction", "Forward")
|
||||
offset = int(item.get("start_offset", 0))
|
||||
pan = int(item.get("pan", 128))
|
||||
tilt = int(item.get("tilt", 128))
|
||||
else:
|
||||
raise ValueError("each efx fixture is a key or {fixture, ...}")
|
||||
if key in homes:
|
||||
pan, tilt = int(homes[key][0]), int(homes[key][1])
|
||||
keys.append(key)
|
||||
fixtures.append(EfxFixture(id=index, direction=direction, start_offset=offset, pan=pan, tilt=tilt))
|
||||
width = _bounded(block.get("width", 40), 0, 127, "width")
|
||||
height = _bounded(block.get("height", 40), 0, 127, "height")
|
||||
duration = int(block.get("duration_ms", 8000))
|
||||
if duration < 20:
|
||||
raise ValueError("duration_ms must be at least 20")
|
||||
pattern = Efx(
|
||||
algorithm=algorithm,
|
||||
width=width,
|
||||
height=height,
|
||||
rotation=int(block.get("rotation", 0)) % 360,
|
||||
start_offset=int(block.get("start_offset", 0)) % 360,
|
||||
x_offset=127 if relative else _bounded(block.get("x_offset", 128), 0, 255, "x_offset"),
|
||||
y_offset=127 if relative else _bounded(block.get("y_offset", 128), 0, 255, "y_offset"),
|
||||
x_frequency=_bounded(block.get("x_frequency", 1), 0, 5, "x_frequency"),
|
||||
y_frequency=_bounded(block.get("y_frequency", 1), 0, 5, "y_frequency"),
|
||||
x_phase=int(block.get("x_phase", 0)) % 360,
|
||||
y_phase=int(block.get("y_phase", 0)) % 360,
|
||||
duration_ms=duration,
|
||||
direction=block.get("direction", "Forward"),
|
||||
run_order=block.get("run_order", "Loop"),
|
||||
propagation=block.get("propagation", "Parallel"),
|
||||
relative=relative,
|
||||
fixtures=fixtures,
|
||||
)
|
||||
sampled = pattern.sample(steps=steps)
|
||||
for track, fx in zip(sampled["tracks"], fixtures):
|
||||
track["key"] = keys[fx.id]
|
||||
if relative:
|
||||
track["points"] = [
|
||||
[
|
||||
round(max(0.0, min(255.0, fx.pan + (x - 127))), 2),
|
||||
round(max(0.0, min(255.0, fx.tilt + (y - 127))), 2),
|
||||
]
|
||||
for x, y in track["points"]
|
||||
]
|
||||
return sampled
|
||||
|
||||
|
||||
def _sample_path(block: dict[str, Any]) -> dict[str, Any]:
|
||||
entries = block.get("fixtures") or []
|
||||
points = block.get("points") or []
|
||||
if not entries or not points:
|
||||
raise ValueError("path needs fixtures and points")
|
||||
fixtures = []
|
||||
keys = []
|
||||
for index, item in enumerate(entries):
|
||||
if isinstance(item, str):
|
||||
key, pan_offset, tilt_offset, mirror_pan, mirror_tilt = item, 0, 0, False, False
|
||||
elif isinstance(item, dict):
|
||||
key = str(item["fixture"])
|
||||
pan_offset = int(item.get("pan_offset", 0))
|
||||
tilt_offset = int(item.get("tilt_offset", 0))
|
||||
mirror_pan = bool(item.get("mirror_pan", False))
|
||||
mirror_tilt = bool(item.get("mirror_tilt", False))
|
||||
else:
|
||||
raise ValueError("each path fixture is a key or {fixture, mirror_pan}")
|
||||
keys.append(key)
|
||||
fixtures.append(
|
||||
PathFixture(
|
||||
id=index,
|
||||
pan_offset=pan_offset,
|
||||
tilt_offset=tilt_offset,
|
||||
mirror_pan=mirror_pan,
|
||||
mirror_tilt=mirror_tilt,
|
||||
)
|
||||
)
|
||||
path = EfxPath(
|
||||
points=[
|
||||
PathPoint(
|
||||
pan=float(point["pan"]),
|
||||
tilt=float(point["tilt"]),
|
||||
fade_ms=int(point.get("fade_ms", 1000)),
|
||||
hold_ms=int(point.get("hold_ms", 0)),
|
||||
)
|
||||
for point in points
|
||||
],
|
||||
smooth=bool(block.get("smooth", False)),
|
||||
subdivisions=int(block.get("subdivisions", 6)),
|
||||
closed=bool(block.get("closed", True)),
|
||||
run_order=block.get("run_order", "Loop"),
|
||||
direction=block.get("direction", "Forward"),
|
||||
fixtures=fixtures,
|
||||
)
|
||||
sampled = path.sample()
|
||||
for track in sampled["tracks"]:
|
||||
track["key"] = keys[track["id"]]
|
||||
return sampled
|
||||
|
||||
|
||||
def _choice(value: str, allowed: tuple[str, ...], label: str) -> None:
|
||||
if value not in allowed:
|
||||
raise ValueError(f"{label} must be one of {', '.join(allowed)}")
|
||||
|
||||
|
||||
def _bounded(value: Any, lo: int, hi: int, label: str) -> int:
|
||||
number = int(value)
|
||||
if not lo <= number <= hi:
|
||||
raise ValueError(f"{label} must be {lo}–{hi}")
|
||||
return number
|
||||
Reference in new issue
Block a user