Compare commits
91
Commits
709dd0ea4f
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a985452568 | ||
|
|
0b06dfdccf | ||
|
|
72425159b5 | ||
|
|
873502b3ca | ||
|
|
9ebe3a5af1 | ||
|
|
c71b6da9d9 | ||
|
|
c7546e5ea9 | ||
|
|
467b480c76 | ||
|
|
31ccbab340 | ||
|
|
cf94c7b1ba | ||
|
|
4fd11445e8 | ||
|
|
e7e1cf656b | ||
|
|
3b38df3dd0 | ||
|
|
f674dc9fe0 | ||
|
|
c3fe965e79 | ||
|
|
80df550916 | ||
|
|
09aab70bd6 | ||
|
|
ae186c51ea | ||
|
|
913494c0aa | ||
|
|
8caf341d30 | ||
|
|
00c8c2d35d | ||
|
|
f8c8cea3ef | ||
|
|
9c1ef6f2d4 | ||
|
|
2586ead4fa | ||
|
|
fc8abf9c99 | ||
|
|
2b0f9e2f9b | ||
|
|
e96b31ab66 | ||
|
|
2219788904 | ||
|
|
11da656ee6 | ||
|
|
72c227b153 | ||
|
|
86d87bf8cf | ||
|
|
18f0ac2dc5 | ||
|
|
d522b1a2cf | ||
|
|
6bbb3d5a29 | ||
|
|
643f7c8fb6 | ||
|
|
8f8c69898a | ||
|
|
a295fefac0 | ||
|
|
df05c8ca49 | ||
|
|
20f018a523 | ||
|
|
9742121144 | ||
|
|
1e09cb3825 | ||
|
|
00de2595b6 | ||
|
|
647cfa3a75 | ||
|
|
5f593b973c | ||
|
|
e007978ef9 | ||
|
|
e2392ecd0b | ||
|
|
729a315c7a | ||
|
|
e413530658 | ||
|
|
6c060720ee | ||
|
|
b8e6b5f24b | ||
|
|
82e75e69de | ||
|
|
3992744a1d | ||
|
|
63b3129cca | ||
|
|
adca8e17a4 | ||
|
|
24f9ca300e | ||
|
|
9b5f6b5bdd | ||
|
|
bb6e51cdc9 | ||
|
|
4374ffb430 | ||
|
|
fee1985e1a | ||
|
|
aa287b0adc | ||
|
|
3b0920eeb2 | ||
|
|
f4b927e0cb | ||
|
|
9d1d254e39 | ||
|
|
97ce89fcbd | ||
|
|
185d885e39 | ||
|
|
68f8e1913d | ||
|
|
4b53f506e9 | ||
|
|
10c39015b7 | ||
|
|
c9df537567 | ||
|
|
b1181e6f28 | ||
|
|
1b181640dd | ||
|
|
9f40933227 | ||
|
|
dc05192a25 | ||
|
|
7317bcb486 | ||
|
|
1a4e51e449 | ||
|
|
6c5223eec5 | ||
|
|
7ff1519abc | ||
|
|
12420bec93 | ||
|
|
c72a8d6f26 | ||
|
|
97d4449a86 | ||
|
|
084f77c840 | ||
|
|
ab364601ce | ||
|
|
55a38478db | ||
|
|
054124470b | ||
|
|
68f8a594d1 | ||
|
|
b37af2234a | ||
|
|
3bb38f6ddf | ||
|
|
8f08d44188 | ||
|
|
f069a8091b | ||
|
|
5eb623d6af | ||
|
|
c92094cc26 |
No files matched your search
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "padcontroller",
|
||||
"runtimeExecutable": ".venv/bin/python",
|
||||
"runtimeArgs": ["-m", "padcontroller", "--no-browser"],
|
||||
"port": 8770
|
||||
},
|
||||
{
|
||||
"name": "simulator",
|
||||
"runtimeExecutable": ".venv/bin/python",
|
||||
"runtimeArgs": ["-m", "simulator", "--http", "127.0.0.1:8766", "--artnet", "127.0.0.1:6455", "--demo"],
|
||||
"port": 8766
|
||||
},
|
||||
{
|
||||
"name": "simulator-artnet",
|
||||
"runtimeExecutable": ".venv/bin/python",
|
||||
"runtimeArgs": ["-m", "simulator", "--http", "127.0.0.1:8767", "--artnet", "127.0.0.1:6456"],
|
||||
"port": 8767
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"qlcplus-show": {
|
||||
"command": "python3",
|
||||
"args": ["-m", "showfile.mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.qxw~
|
||||
.DS_Store
|
||||
.venv/
|
||||
chataigne/*/*_autosave/
|
||||
@@ -0,0 +1,51 @@
|
||||
# CLAUDE.md
|
||||
|
||||
## Before working on the rig
|
||||
|
||||
At the start of a session, and before testing anything that needs the pad or
|
||||
the stage view, make sure the MIDI controller is working and the simulator is on:
|
||||
|
||||
1. Both user services are running:
|
||||
|
||||
```bash
|
||||
systemctl --user is-active padcontroller simulator
|
||||
```
|
||||
|
||||
If either is not `active`, start it with `systemctl --user start <name>`.
|
||||
If the unit is missing, install it with `padcontroller/systemd/install.sh` or
|
||||
`simulator/systemd/install.sh`. Check `journalctl --user -u <name> -n 50`
|
||||
if it won't stay up.
|
||||
|
||||
2. The MIDI controller is connected and passed through:
|
||||
|
||||
```bash
|
||||
aconnect -l
|
||||
```
|
||||
|
||||
It should list the `SMC-PAD` client (USB `SINCO SMC-PAD-Master` or
|
||||
`SMC-PAD Bluetooth`) and the `padcontroller` virtual port. A service that is
|
||||
active with no `SMC-PAD` client means the pad is off or not paired: ask the
|
||||
user to switch it on rather than carrying on without it.
|
||||
|
||||
3. The simulator answers on http://127.0.0.1:8765:
|
||||
|
||||
```bash
|
||||
curl -sf -o /dev/null http://127.0.0.1:8765 && echo ok
|
||||
```
|
||||
|
||||
`shows/test.show.json` (and the `shows/test.qxw` built from it) sends Art-Net
|
||||
to 127.0.0.1 only, so testing drives the simulator and never the real rig. Keep
|
||||
it that way; don't point it at a 192.168.1.x node.
|
||||
|
||||
## Cans 3–6 are always static
|
||||
|
||||
The row of 4 (#3–#6, fixture IDs 2–5) never animates. Chases, patterns, loops,
|
||||
strobes and side dimmer holds leave them out, so they keep the Colour 1 scene
|
||||
and their own dimmer knob whatever else runs. Their colour stays HTP, unlike the
|
||||
other cans. When adding an animation for the cans, build it on the other 11
|
||||
(the groups `Sides` and `Strobe cans` in test.qxw already skip them) and don't
|
||||
write any FixtureVal for IDs 2–5.
|
||||
|
||||
Tell the user what was down and what you did about it. The preview
|
||||
configurations in `.claude/launch.json` run separate copies on other ports
|
||||
(8770, 8766) and don't count as the services being up.
|
||||
@@ -0,0 +1,19 @@
|
||||
[[source]]
|
||||
url = "https://pypi.org/simple"
|
||||
verify_ssl = true
|
||||
name = "pypi"
|
||||
|
||||
[packages]
|
||||
mido = "*"
|
||||
python-rtmidi = "*"
|
||||
|
||||
[dev-packages]
|
||||
pytest = "*"
|
||||
|
||||
[requires]
|
||||
python_version = "3.12"
|
||||
|
||||
[scripts]
|
||||
midi = "python scripts/pad/midi.py"
|
||||
padcontroller-midi = "python -m padcontroller.midi"
|
||||
padcontroller = "python -m padcontroller"
|
||||
Generated
+113
@@ -0,0 +1,113 @@
|
||||
{
|
||||
"_meta": {
|
||||
"hash": {
|
||||
"sha256": "42b99998dcced8eeecfc0b83f3589f113501d6245312302009027c9a91e11fa6"
|
||||
},
|
||||
"pipfile-spec": 6,
|
||||
"requires": {
|
||||
"python_version": "3.12"
|
||||
},
|
||||
"sources": [
|
||||
{
|
||||
"name": "pypi",
|
||||
"url": "https://pypi.org/simple",
|
||||
"verify_ssl": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"default": {
|
||||
"mido": {
|
||||
"hashes": [
|
||||
"sha256:01033c9b10b049e4436fca2762194ca839b09a4334091dd3c34e7f4ae674fd8a",
|
||||
"sha256:1aecb30b7f282404f17e43768cbf74a6a31bf22b3b783bdd117a1ce9d22cb74c"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version ~= '3.7'",
|
||||
"version": "==1.3.3"
|
||||
},
|
||||
"packaging": {
|
||||
"hashes": [
|
||||
"sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79",
|
||||
"sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"
|
||||
],
|
||||
"markers": "python_version >= '3.9'",
|
||||
"version": "==26.3"
|
||||
},
|
||||
"python-rtmidi": {
|
||||
"hashes": [
|
||||
"sha256:052c89933cae4fca354012d8ca7248f4f9e1e3f062471409d48415a7f7d7e59e",
|
||||
"sha256:1d5da765184150fb946043d59be4039b36a8060ede025f109ef20492dbf99075",
|
||||
"sha256:25f5a5db7be98911c41ca5bebb262fcf9a7c89600b88fd3c207ceafd3101e721",
|
||||
"sha256:26149186367341bf5b0a3ac17b495f6a25950bd3da6b4f13d25ac0a9ce8208dd",
|
||||
"sha256:271d625c489fffb39b3edc5aba67f7c8e29a04a0a0f056ce19e5a888a08b4c59",
|
||||
"sha256:29661939f9b7bd1a4e29835f50f4790e741dacd21a5cb143297aefb51deefdec",
|
||||
"sha256:29d9c9d9f82ce679fecad7bb4cb79f3a24574ea84600e377194b4cc1baacec0e",
|
||||
"sha256:30d117193dcad8af67c600c405f53eb096e4ff84849760be14c97270af334922",
|
||||
"sha256:46bbf32c8a4bf6c8f0df1c02a68689d0757f13cb7a69f27ccbbed3d7b2365918",
|
||||
"sha256:4e234dca7f9d783dd3f1e9c9c5c2f295f02b7af3085301d6eed3b428cf49d327",
|
||||
"sha256:5443634597eb340cdec0734f76267a827c2d366f00a6f9195141c78828016ac2",
|
||||
"sha256:5966172ed28add6ff2b76d389702931bfc7ff3cc741c0e4b0d1aaae269ab7a8e",
|
||||
"sha256:7bce7f17c71a71d8ef0bfeae3cb8a7652dd02f0d5067de882e1ee44eb38518db",
|
||||
"sha256:7f9ade68b068ae09000ecb562ae9521da3a234361ad5449e83fc734544d004fa",
|
||||
"sha256:82e61bc1b51aa91d9e615827056e80f78dbe364248eecd61698b233f7af903f6",
|
||||
"sha256:844bd12840c9d4e03dfc89b2cd57c55dcbf5ed7246504d69c6c661732249b19c",
|
||||
"sha256:878ce085dfb65c0974810a7e919f73708cbb4c0430c7924b78f25aea1dd4ebee",
|
||||
"sha256:8bbaf7c7164471712a93ac60c8f9ed146b336a294a5103223bbaf8f10709a0bf",
|
||||
"sha256:a5582983ad57ea7f0a7797ddc3e258efb00f8326113b6ddfa85b5165a4151806",
|
||||
"sha256:a706e9850e22acc57fa840c60fdc4541baafe462a05ff7631a6d9eb91c65e171",
|
||||
"sha256:c60dd180e5130fb87571e71aea30e2ef0512131aab45865a7d67063ed8e52ca4",
|
||||
"sha256:cec30924e305f55284594ccf35a71dee7216fd308dfa2dec1b3ed03e6f243803",
|
||||
"sha256:cfea32c91752fa7aecfe3d6827535c190ba0e646a9accd6604f4fc70cf4b780f",
|
||||
"sha256:dd2bcbea822488fca6b8d9fc7e78a91da12914f3b88dc086f051cb65a643449f",
|
||||
"sha256:efc07413b30b0039c0d35abe25a81d740c7405124eb58eed141a8f24388e6fe0",
|
||||
"sha256:f2138005c6bd3d8b9af05df383679f6d0827d16056e68a941110732310dcb7dd"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.8'",
|
||||
"version": "==1.5.8"
|
||||
}
|
||||
},
|
||||
"develop": {
|
||||
"iniconfig": {
|
||||
"hashes": [
|
||||
"sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960",
|
||||
"sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7"
|
||||
],
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==2.3.1"
|
||||
},
|
||||
"packaging": {
|
||||
"hashes": [
|
||||
"sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79",
|
||||
"sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"
|
||||
],
|
||||
"markers": "python_version >= '3.9'",
|
||||
"version": "==26.3"
|
||||
},
|
||||
"pluggy": {
|
||||
"hashes": [
|
||||
"sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec",
|
||||
"sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8"
|
||||
],
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==1.7.0"
|
||||
},
|
||||
"pygments": {
|
||||
"hashes": [
|
||||
"sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9",
|
||||
"sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c"
|
||||
],
|
||||
"markers": "python_version >= '3.9'",
|
||||
"version": "==2.21.0"
|
||||
},
|
||||
"pytest": {
|
||||
"hashes": [
|
||||
"sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313",
|
||||
"sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==9.1.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,145 @@
|
||||
# qlcplus
|
||||
|
||||
QLC+ show files, fixture definitions, and generators for the XCHC stage
|
||||
(8× beamZ BCC145 parcans + 2× Small Eye 7 movers).
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
fixtures/ Fixture definitions (.qxf) — install into QLC+ if needed
|
||||
rgbscripts/ RGB matrix scripts; scripts/install_qlcplus.sh links them into ~/.qlcplus/rgbscripts
|
||||
shows/ Workspaces to open in QLC+
|
||||
xchc.qxw Main show (patterns + movers, unified VC)
|
||||
simple.qxw Manual board: M1/M2 pads, shared + individual RGBW
|
||||
small_eye.qxw Movers-only figure-of-8 show
|
||||
archive/ Older scratch workspaces
|
||||
scripts/ Launchers (pattern_studio.sh, flash_luxdmx_xiao.sh)
|
||||
pad/ SMC-PAD tools: lamps, MIDI patching, capture decoding
|
||||
shows/ Generators / patchers for the shows and Chataigne
|
||||
anim/ showfile animations to preview over Art-Net
|
||||
stage/ Stage map (SVG, JSON, canvas)
|
||||
tests/ Art-Net / fixture helpers used by scripts
|
||||
```
|
||||
|
||||
## Open in QLC+
|
||||
|
||||
On a new machine, link the RGB scripts, fixtures and pad input profile into
|
||||
`~/.qlcplus` first, then (re)start QLC+. Without `rgbscripts/steps.js` and
|
||||
`swap.js` the can patterns load but do nothing.
|
||||
|
||||
```bash
|
||||
scripts/install_qlcplus.sh
|
||||
```
|
||||
|
||||
- Full show: `shows/xchc.qxw`
|
||||
- Simple RGBW + positions: `shows/simple.qxw`
|
||||
|
||||
## Scripts
|
||||
|
||||
```bash
|
||||
# Rebuild simple manual board
|
||||
python3 scripts/shows/make_simple_vc.py
|
||||
|
||||
# Rewrite can/mover patterns from stage layout
|
||||
python3 scripts/shows/integrate_u_patterns.py
|
||||
|
||||
# Unify Patterns + Movers into one Show frame
|
||||
python3 scripts/shows/unify_vc.py
|
||||
|
||||
# Figure-of-8 (live Art-Net or write/merge workspace)
|
||||
python3 scripts/shows/figure8_small_eye.py --write-qxw shows/small_eye.qxw
|
||||
```
|
||||
|
||||
## Fixtures / DMX
|
||||
|
||||
| Fixture | Mode | Addresses |
|
||||
|---------|------|-----------|
|
||||
| Small Eye 7 #1–#2 | 43ch | 1–43, 45–87 |
|
||||
| BCC145 #1–#8 | 8ch | 87–150 (starts 87, 95, …) |
|
||||
|
||||
Copy `.qxf` files from `fixtures/` into QLC+’s fixture library if the
|
||||
manufacturer/model is missing.
|
||||
|
||||
## SMC-PAD pad controller
|
||||
|
||||
`padcontroller.midi` reads the SMC-PAD, smooths its knobs, applies the Play
|
||||
layer, and sends the result on a virtual MIDI port named `padcontroller` for
|
||||
QLC+. Run it by hand with `.venv/bin/python -m padcontroller.midi`, or install
|
||||
it as a systemd user service that starts at login and waits for the pad:
|
||||
|
||||
```bash
|
||||
padcontroller/systemd/install.sh
|
||||
```
|
||||
|
||||
Options after the command go to the pad controller (for example `--no-lamps`).
|
||||
`--no-enable` installs it without starting it at login (start it with
|
||||
`systemctl --user start padcontroller`). `--uninstall` removes the service. Logs: `journalctl --user -u padcontroller -f`.
|
||||
|
||||
### Virtual pad
|
||||
|
||||
`padcontroller.virtualpad` presses pads and turns knobs without touching the
|
||||
pad. It sends into the pad controller's input, so presses get the Play layer
|
||||
and smoothing like the real thing. It refuses unless QLC+ last opened
|
||||
`shows/test.qxw` (127.0.0.1 only); `--force` skips that.
|
||||
|
||||
```bash
|
||||
.venv/bin/python -m padcontroller.virtualpad press 52 # Colour 1 Red
|
||||
.venv/bin/python -m padcontroller.virtualpad press 52 --play # Play held: Colour 2 Red
|
||||
.venv/bin/python -m padcontroller.virtualpad press --pad 1 # by pad number (shows/midi_map.json)
|
||||
.venv/bin/python -m padcontroller.virtualpad cc 34 64
|
||||
```
|
||||
|
||||
`tests/test_e2e_pad.py` uses it to press colour pads and check the simulator's
|
||||
`/api/state`. It drives the live rig, so it only runs with `PAD_E2E=1`:
|
||||
|
||||
```bash
|
||||
PAD_E2E=1 .venv/bin/python -m pytest tests/test_e2e_pad.py -v
|
||||
```
|
||||
|
||||
The rest of the suite runs offline. Use pytest, since most tests are plain
|
||||
`def test_` functions that `unittest` doesn't find (`pipenv install --dev`
|
||||
installs it):
|
||||
|
||||
```bash
|
||||
.venv/bin/python -m pytest
|
||||
```
|
||||
|
||||
## Stage simulator
|
||||
|
||||
`python -m simulator` listens for Art-Net on port 6454 and draws the rig at
|
||||
http://127.0.0.1:8765. The Stage drop-down on the page switches between the
|
||||
stage maps in `stage/`. No QLC+ show is needed: `stage/map.json` holds every
|
||||
address. `--show <file.qxw>` only fills in addresses a stage map leaves out and
|
||||
shows where that workspace sends Art-Net. It can run as a systemd user service
|
||||
the same way:
|
||||
|
||||
```bash
|
||||
simulator/systemd/install.sh
|
||||
```
|
||||
|
||||
Options after the command go to the simulator (for example `--show shows/test.qxw`).
|
||||
`--no-enable` installs it without starting it at login (start it with
|
||||
`systemctl --user start simulator`). `--uninstall` removes the service.
|
||||
Logs: `journalctl --user -u simulator -f`.
|
||||
|
||||
## Chataigne
|
||||
|
||||
`scripts/shows/make_chataigne.py` turns a show spec into a Chataigne project, so the
|
||||
SMC-PAD can drive the same colour pads and sliders without QLC+.
|
||||
|
||||
```bash
|
||||
python3 scripts/shows/make_chataigne.py shows/test.show.json chataigne/test
|
||||
```
|
||||
|
||||
Open `chataigne/test/test.noisette`. The **Pad** (MIDI) module reads the SMC-PAD
|
||||
directly (`--pad` picks the port: USB `SINCO SMC-PAD-Master` by default, or
|
||||
`SMC-PAD Bluetooth`). The script does the Play-layer shift that `padcontroller/layer.py` does for
|
||||
QLC+, with no knob smoothing, so the pad controller is not needed. Set the lamps with
|
||||
`scripts/pad/pad_lamps.py`. The **Lights** (DMX) module sends Art-Net to the
|
||||
node in the spec. The **Preview** module sends a copy to 127.0.0.1 for the simulator (`--preview ''` leaves it out). If it comes up on the wrong output, set DMX Type to Art-Net,
|
||||
the remote host, and an output universe of net 0, subnet 0, universe 0.
|
||||
The project also has a dashboard with the same buttons and sliders as the
|
||||
virtual console, coloured like it. Chataigne serves it on port 9999 for a
|
||||
phone or browser. Pads, knobs and dashboard stay in step.
|
||||
Edit `chataigne/show.template.js` for behaviour; the generated `test.js` is
|
||||
overwritten.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,210 @@
|
||||
// Pads pick colours and sliders set levels, like the QLC+ virtual console.
|
||||
// It reads the pad directly: Play shifts bank 2 here, as padcontroller/layer.py does
|
||||
// when QLC+ is used.
|
||||
// Generated by scripts/shows/make_chataigne.py: edit this template, not the output.
|
||||
//
|
||||
// Runs as a script on the MIDI module "Pad" so it gets the pad and knob events.
|
||||
// DMX goes out through the DMX module "Lights", and a copy through "Preview" if it exists.
|
||||
|
||||
/*__DATA__*/
|
||||
|
||||
var LAMP = "Lamp";
|
||||
var LAMP_OFF = 0.3; // brightness of a pad's tile when it is not playing
|
||||
var FADE_RATE = 100; // script updates per second
|
||||
var PLAY_CC = 27; // hold Play to move bank 2 (notes 52-67) up 16, like padcontroller/layer.py
|
||||
var BANK_FIRST = 52;
|
||||
var BANK_LAST = 67;
|
||||
var BANK_SHIFT = 16;
|
||||
var DMX_SIZE = 513; // channels are 1-based
|
||||
|
||||
var states = [];
|
||||
var sent = [];
|
||||
var lookup = {};
|
||||
var lampParams = [];
|
||||
var sliderParams = [];
|
||||
var nowParams = [];
|
||||
var busy = false;
|
||||
var primed = false;
|
||||
var playHeld = false;
|
||||
|
||||
function init()
|
||||
{
|
||||
script.setUpdateRate(FADE_RATE);
|
||||
for (var i = 0; i < DMX_SIZE; i++) sent[i] = -1;
|
||||
states = [];
|
||||
for (var g = 0; g < GROUPS.length; g++)
|
||||
{
|
||||
var level = [], from = [], to = [], touched = [];
|
||||
for (var c = 0; c < DMX_SIZE; c++) { level[c] = 0; from[c] = 0; to[c] = 0; touched[c] = 0; }
|
||||
var group = GROUPS[g];
|
||||
for (var p = 0; p < group.pads.length; p++) mark(touched, group.pads[p].levels);
|
||||
for (var s = 0; s < group.sliders.length; s++) mark(touched, group.sliders[s].levels);
|
||||
var mix = [];
|
||||
for (var m = 0; m < group.sliders.length; m++) mix[m] = group.sliders[m].value;
|
||||
states[g] = {active: -1, elapsed: 0, duration: 0, level: level, from: from, to: to, touched: touched, mix: mix};
|
||||
|
||||
// Controls on the script's Params, for the dashboard to show.
|
||||
sliderParams[g] = [];
|
||||
lampParams[g] = [];
|
||||
for (var q = 0; q < group.pads.length; q++)
|
||||
{
|
||||
script.addTrigger(group.pads[q].id, group.name + " " + group.pads[q].name);
|
||||
lampParams[g][q] = script.addColorParameter(group.pads[q].id + LAMP, group.name + " " + group.pads[q].name + " lamp", shade(group.pads[q].rgb, LAMP_OFF));
|
||||
lookup[group.pads[q].id] = {g: g, p: q, s: -1};
|
||||
}
|
||||
for (var r = 0; r < group.sliders.length; r++)
|
||||
{
|
||||
sliderParams[g][r] = script.addFloatParameter(group.sliders[r].id, group.name + " " + group.sliders[r].name, group.sliders[r].value, 0, 1);
|
||||
lookup[group.sliders[r].id] = {g: g, p: -1, s: r};
|
||||
}
|
||||
nowParams[g] = script.addStringParameter(group.now, group.name + " scene", "");
|
||||
}
|
||||
script.log("show script ready: " + GROUPS.length + " groups");
|
||||
}
|
||||
|
||||
function mark(touched, levels)
|
||||
{
|
||||
for (var i = 0; i < levels.length; i += 2) touched[levels[i]] = 1;
|
||||
}
|
||||
|
||||
// A pad press starts its scene and fades the others out. A second press stops it.
|
||||
function noteOnEvent(channel, pitch, velocity)
|
||||
{
|
||||
if (velocity == 0) return;
|
||||
if (playHeld && pitch >= BANK_FIRST && pitch <= BANK_LAST) pitch += BANK_SHIFT;
|
||||
for (var g = 0; g < GROUPS.length; g++)
|
||||
{
|
||||
var pads = GROUPS[g].pads;
|
||||
for (var p = 0; p < pads.length; p++)
|
||||
{
|
||||
if (pads[p].note == pitch) { press(g, p); return; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A control on the dashboard changed.
|
||||
function scriptParameterChanged(param)
|
||||
{
|
||||
if (busy) return;
|
||||
var hit = lookup[param.name];
|
||||
if (!hit) return;
|
||||
if (hit.p >= 0) press(hit.g, hit.p);
|
||||
else states[hit.g].mix[hit.s] = param.get();
|
||||
}
|
||||
|
||||
function shade(rgb, level)
|
||||
{
|
||||
return [rgb[0] * level, rgb[1] * level, rgb[2] * level, 1];
|
||||
}
|
||||
|
||||
// Light the playing pad's strip on the board and show its name.
|
||||
function show(g, name)
|
||||
{
|
||||
busy = true;
|
||||
nowParams[g].set(name);
|
||||
var pads = GROUPS[g].pads;
|
||||
for (var p = 0; p < pads.length; p++) lampParams[g][p].set(shade(pads[p].rgb, states[g].active == p ? 1 : LAMP_OFF));
|
||||
busy = false;
|
||||
}
|
||||
|
||||
function press(g, p)
|
||||
{
|
||||
var st = states[g];
|
||||
var pad = GROUPS[g].pads[p];
|
||||
for (var c = 0; c < DMX_SIZE; c++) { st.from[c] = st.level[c]; st.to[c] = 0; }
|
||||
if (st.active == p)
|
||||
{
|
||||
st.active = -1;
|
||||
st.duration = pad.fadeOut;
|
||||
show(g, "");
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < pad.levels.length; i += 2) st.to[pad.levels[i]] = pad.levels[i + 1];
|
||||
st.active = p;
|
||||
st.duration = pad.fadeIn;
|
||||
show(g, pad.name);
|
||||
}
|
||||
st.elapsed = 0;
|
||||
}
|
||||
|
||||
function ccEvent(channel, number, value)
|
||||
{
|
||||
if (number == PLAY_CC) { playHeld = value > 0; return; }
|
||||
for (var g = 0; g < GROUPS.length; g++)
|
||||
{
|
||||
var sliders = GROUPS[g].sliders;
|
||||
for (var s = 0; s < sliders.length; s++)
|
||||
{
|
||||
if (sliders[s].cc == number)
|
||||
{
|
||||
states[g].mix[s] = value / 127;
|
||||
busy = true;
|
||||
sliderParams[g][s].set(value / 127);
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The dashboard web server does not always start when a project loads with it enabled, so switch
|
||||
// it off and on once the script is running.
|
||||
function startWeb()
|
||||
{
|
||||
var settings = root.projectSettings;
|
||||
if (!settings || !settings.dashboardSettings) return;
|
||||
var web = settings.dashboardSettings.enableDashboardServer;
|
||||
if (!web) return;
|
||||
web.set(false);
|
||||
web.set(true);
|
||||
script.log("dashboard web server restarted");
|
||||
}
|
||||
|
||||
function update(deltaTime)
|
||||
{
|
||||
// A colour control's starting value is read in a different colour model and saved values load
|
||||
// after init, so paint every tile once the script is running.
|
||||
if (!primed)
|
||||
{
|
||||
primed = true;
|
||||
startWeb();
|
||||
for (var g = 0; g < GROUPS.length; g++) show(g, states[g].active >= 0 ? GROUPS[g].pads[states[g].active].name : "");
|
||||
}
|
||||
var out = [];
|
||||
for (var c = 0; c < DMX_SIZE; c++) out[c] = 0;
|
||||
for (var g = 0; g < GROUPS.length; g++) render(g, deltaTime, out);
|
||||
|
||||
var first = -1, last = -1;
|
||||
for (var i = 1; i < DMX_SIZE; i++)
|
||||
{
|
||||
if (out[i] != sent[i]) { if (first < 0) first = i; last = i; }
|
||||
}
|
||||
if (first < 0) return;
|
||||
var values = [];
|
||||
for (var j = first; j <= last; j++) { values.push(out[j]); sent[j] = out[j]; }
|
||||
root.modules.lights.send(first, values);
|
||||
if (root.modules.preview) root.modules.preview.send(first, values);
|
||||
}
|
||||
|
||||
function render(g, deltaTime, out)
|
||||
{
|
||||
var st = states[g];
|
||||
st.elapsed += deltaTime * 1000;
|
||||
var t = st.duration > 0 ? Math.min(1, st.elapsed / st.duration) : 1;
|
||||
for (var c = 1; c < DMX_SIZE; c++)
|
||||
{
|
||||
if (!st.touched[c]) continue;
|
||||
st.level[c] = st.from[c] + (st.to[c] - st.from[c]) * t;
|
||||
out[c] = Math.max(out[c], st.level[c]);
|
||||
}
|
||||
var sliders = GROUPS[g].sliders;
|
||||
for (var s = 0; s < sliders.length; s++)
|
||||
{
|
||||
var levels = sliders[s].levels;
|
||||
for (var i = 0; i < levels.length; i += 2)
|
||||
{
|
||||
out[levels[i]] = Math.max(out[levels[i]], levels[i + 1] * st.mix[s]);
|
||||
}
|
||||
}
|
||||
for (var k = 1; k < DMX_SIZE; k++) out[k] = Math.round(out[k]);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 69 B |
@@ -0,0 +1,271 @@
|
||||
// Pads pick colours and sliders set levels, like the QLC+ virtual console.
|
||||
// It reads the pad directly: Play shifts bank 2 here, as padcontroller/layer.py does
|
||||
// when QLC+ is used.
|
||||
// Generated by scripts/shows/make_chataigne.py: edit this template, not the output.
|
||||
//
|
||||
// Runs as a script on the MIDI module "Pad" so it gets the pad and knob events.
|
||||
// DMX goes out through the DMX module "Lights", and a copy through "Preview" if it exists.
|
||||
|
||||
var GROUPS = [
|
||||
{
|
||||
name: "Colour 1",
|
||||
now: "now1",
|
||||
pads: [
|
||||
{id: "c1Red", rgb: [1.0, 0.0, 0.0], note: 52, name: "Red", fadeIn: 1000, fadeOut: 1000, levels: [90,255,91,0,92,0,93,0,98,255,99,0,100,0,101,0,106,255,107,0,108,0,109,0,114,255,115,0,116,0,117,0,122,255,123,0,124,0,125,0,130,255,131,0,132,0,133,0,138,255,139,0,140,0,141,0,146,255,147,0,148,0,149,0,154,255,155,0,156,0,157,0,162,255,163,0,164,0,165,0,170,255,171,0,172,0,173,0,178,255,179,0,180,0,181,0,186,255,187,0,188,0,189,0,194,255,195,0,196,0,197,0,202,255,203,0,204,0,205,0]},
|
||||
{id: "c1Orange", rgb: [1.0, 0.498, 0.0], note: 53, name: "Orange", fadeIn: 1000, fadeOut: 1000, levels: [90,255,91,127,92,0,93,0,98,255,99,127,100,0,101,0,106,255,107,127,108,0,109,0,114,255,115,127,116,0,117,0,122,255,123,127,124,0,125,0,130,255,131,127,132,0,133,0,138,255,139,127,140,0,141,0,146,255,147,127,148,0,149,0,154,255,155,127,156,0,157,0,162,255,163,127,164,0,165,0,170,255,171,127,172,0,173,0,178,255,179,127,180,0,181,0,186,255,187,127,188,0,189,0,194,255,195,127,196,0,197,0,202,255,203,127,204,0,205,0]},
|
||||
{id: "c1Amber", rgb: [1.0, 0.749, 0.0], note: 54, name: "Amber", fadeIn: 1000, fadeOut: 1000, levels: [90,255,91,191,92,0,93,0,98,255,99,191,100,0,101,0,106,255,107,191,108,0,109,0,114,255,115,191,116,0,117,0,122,255,123,191,124,0,125,0,130,255,131,191,132,0,133,0,138,255,139,191,140,0,141,0,146,255,147,191,148,0,149,0,154,255,155,191,156,0,157,0,162,255,163,191,164,0,165,0,170,255,171,191,172,0,173,0,178,255,179,191,180,0,181,0,186,255,187,191,188,0,189,0,194,255,195,191,196,0,197,0,202,255,203,191,204,0,205,0]},
|
||||
{id: "c1Yellow", rgb: [1.0, 1.0, 0.0], note: 55, name: "Yellow", fadeIn: 1000, fadeOut: 1000, levels: [90,255,91,255,92,0,93,0,98,255,99,255,100,0,101,0,106,255,107,255,108,0,109,0,114,255,115,255,116,0,117,0,122,255,123,255,124,0,125,0,130,255,131,255,132,0,133,0,138,255,139,255,140,0,141,0,146,255,147,255,148,0,149,0,154,255,155,255,156,0,157,0,162,255,163,255,164,0,165,0,170,255,171,255,172,0,173,0,178,255,179,255,180,0,181,0,186,255,187,255,188,0,189,0,194,255,195,255,196,0,197,0,202,255,203,255,204,0,205,0]},
|
||||
{id: "c1Lime", rgb: [0.498, 1.0, 0.0], note: 56, name: "Lime", fadeIn: 1000, fadeOut: 1000, levels: [90,127,91,255,92,0,93,0,98,127,99,255,100,0,101,0,106,127,107,255,108,0,109,0,114,127,115,255,116,0,117,0,122,127,123,255,124,0,125,0,130,127,131,255,132,0,133,0,138,127,139,255,140,0,141,0,146,127,147,255,148,0,149,0,154,127,155,255,156,0,157,0,162,127,163,255,164,0,165,0,170,127,171,255,172,0,173,0,178,127,179,255,180,0,181,0,186,127,187,255,188,0,189,0,194,127,195,255,196,0,197,0,202,127,203,255,204,0,205,0]},
|
||||
{id: "c1Green", rgb: [0.0, 1.0, 0.0], note: 57, name: "Green", fadeIn: 1000, fadeOut: 1000, levels: [90,0,91,255,92,0,93,0,98,0,99,255,100,0,101,0,106,0,107,255,108,0,109,0,114,0,115,255,116,0,117,0,122,0,123,255,124,0,125,0,130,0,131,255,132,0,133,0,138,0,139,255,140,0,141,0,146,0,147,255,148,0,149,0,154,0,155,255,156,0,157,0,162,0,163,255,164,0,165,0,170,0,171,255,172,0,173,0,178,0,179,255,180,0,181,0,186,0,187,255,188,0,189,0,194,0,195,255,196,0,197,0,202,0,203,255,204,0,205,0]},
|
||||
{id: "c1Spring", rgb: [0.0, 1.0, 0.498], note: 58, name: "Spring", fadeIn: 1000, fadeOut: 1000, levels: [90,0,91,255,92,127,93,0,98,0,99,255,100,127,101,0,106,0,107,255,108,127,109,0,114,0,115,255,116,127,117,0,122,0,123,255,124,127,125,0,130,0,131,255,132,127,133,0,138,0,139,255,140,127,141,0,146,0,147,255,148,127,149,0,154,0,155,255,156,127,157,0,162,0,163,255,164,127,165,0,170,0,171,255,172,127,173,0,178,0,179,255,180,127,181,0,186,0,187,255,188,127,189,0,194,0,195,255,196,127,197,0,202,0,203,255,204,127,205,0]},
|
||||
{id: "c1Cyan", rgb: [0.0, 1.0, 1.0], note: 59, name: "Cyan", fadeIn: 1000, fadeOut: 1000, levels: [90,0,91,255,92,255,93,0,98,0,99,255,100,255,101,0,106,0,107,255,108,255,109,0,114,0,115,255,116,255,117,0,122,0,123,255,124,255,125,0,130,0,131,255,132,255,133,0,138,0,139,255,140,255,141,0,146,0,147,255,148,255,149,0,154,0,155,255,156,255,157,0,162,0,163,255,164,255,165,0,170,0,171,255,172,255,173,0,178,0,179,255,180,255,181,0,186,0,187,255,188,255,189,0,194,0,195,255,196,255,197,0,202,0,203,255,204,255,205,0]},
|
||||
{id: "c1Azure", rgb: [0.0, 0.498, 1.0], note: 60, name: "Azure", fadeIn: 1000, fadeOut: 1000, levels: [90,0,91,127,92,255,93,0,98,0,99,127,100,255,101,0,106,0,107,127,108,255,109,0,114,0,115,127,116,255,117,0,122,0,123,127,124,255,125,0,130,0,131,127,132,255,133,0,138,0,139,127,140,255,141,0,146,0,147,127,148,255,149,0,154,0,155,127,156,255,157,0,162,0,163,127,164,255,165,0,170,0,171,127,172,255,173,0,178,0,179,127,180,255,181,0,186,0,187,127,188,255,189,0,194,0,195,127,196,255,197,0,202,0,203,127,204,255,205,0]},
|
||||
{id: "c1Blue", rgb: [0.0, 0.0, 1.0], note: 61, name: "Blue", fadeIn: 1000, fadeOut: 1000, levels: [90,0,91,0,92,255,93,0,98,0,99,0,100,255,101,0,106,0,107,0,108,255,109,0,114,0,115,0,116,255,117,0,122,0,123,0,124,255,125,0,130,0,131,0,132,255,133,0,138,0,139,0,140,255,141,0,146,0,147,0,148,255,149,0,154,0,155,0,156,255,157,0,162,0,163,0,164,255,165,0,170,0,171,0,172,255,173,0,178,0,179,0,180,255,181,0,186,0,187,0,188,255,189,0,194,0,195,0,196,255,197,0,202,0,203,0,204,255,205,0]},
|
||||
{id: "c1Violet", rgb: [0.498, 0.0, 1.0], note: 62, name: "Violet", fadeIn: 1000, fadeOut: 1000, levels: [90,127,91,0,92,255,93,0,98,127,99,0,100,255,101,0,106,127,107,0,108,255,109,0,114,127,115,0,116,255,117,0,122,127,123,0,124,255,125,0,130,127,131,0,132,255,133,0,138,127,139,0,140,255,141,0,146,127,147,0,148,255,149,0,154,127,155,0,156,255,157,0,162,127,163,0,164,255,165,0,170,127,171,0,172,255,173,0,178,127,179,0,180,255,181,0,186,127,187,0,188,255,189,0,194,127,195,0,196,255,197,0,202,127,203,0,204,255,205,0]},
|
||||
{id: "c1Magenta", rgb: [1.0, 0.0, 1.0], note: 63, name: "Magenta", fadeIn: 1000, fadeOut: 1000, levels: [90,255,91,0,92,255,93,0,98,255,99,0,100,255,101,0,106,255,107,0,108,255,109,0,114,255,115,0,116,255,117,0,122,255,123,0,124,255,125,0,130,255,131,0,132,255,133,0,138,255,139,0,140,255,141,0,146,255,147,0,148,255,149,0,154,255,155,0,156,255,157,0,162,255,163,0,164,255,165,0,170,255,171,0,172,255,173,0,178,255,179,0,180,255,181,0,186,255,187,0,188,255,189,0,194,255,195,0,196,255,197,0,202,255,203,0,204,255,205,0]},
|
||||
{id: "c1Pink", rgb: [1.0, 0.157, 0.471], note: 64, name: "Pink", fadeIn: 1000, fadeOut: 1000, levels: [90,255,91,40,92,120,93,0,98,255,99,40,100,120,101,0,106,255,107,40,108,120,109,0,114,255,115,40,116,120,117,0,122,255,123,40,124,120,125,0,130,255,131,40,132,120,133,0,138,255,139,40,140,120,141,0,146,255,147,40,148,120,149,0,154,255,155,40,156,120,157,0,162,255,163,40,164,120,165,0,170,255,171,40,172,120,173,0,178,255,179,40,180,120,181,0,186,255,187,40,188,120,189,0,194,255,195,40,196,120,197,0,202,255,203,40,204,120,205,0]},
|
||||
{id: "c1Warm", rgb: [1.0, 0.941, 0.627], note: 65, name: "Warm", fadeIn: 1000, fadeOut: 1000, levels: [90,255,91,120,92,40,93,120,98,255,99,120,100,40,101,120,106,255,107,120,108,40,109,120,114,255,115,120,116,40,117,120,122,255,123,120,124,40,125,120,130,255,131,120,132,40,133,120,138,255,139,120,140,40,141,120,146,255,147,120,148,40,149,120,154,255,155,120,156,40,157,120,162,255,163,120,164,40,165,120,170,255,171,120,172,40,173,120,178,255,179,120,180,40,181,120,186,255,187,120,188,40,189,120,194,255,195,120,196,40,197,120,202,255,203,120,204,40,205,120]},
|
||||
{id: "c1White", rgb: [1.0, 1.0, 1.0], note: 66, name: "White", fadeIn: 1000, fadeOut: 1000, levels: [90,0,91,0,92,0,93,255,98,0,99,0,100,0,101,255,106,0,107,0,108,0,109,255,114,0,115,0,116,0,117,255,122,0,123,0,124,0,125,255,130,0,131,0,132,0,133,255,138,0,139,0,140,0,141,255,146,0,147,0,148,0,149,255,154,0,155,0,156,0,157,255,162,0,163,0,164,0,165,255,170,0,171,0,172,0,173,255,178,0,179,0,180,0,181,255,186,0,187,0,188,0,189,255,194,0,195,0,196,0,197,255,202,0,203,0,204,0,205,255]},
|
||||
{id: "c1Cool", rgb: [0.784, 0.941, 1.0], note: 67, name: "Cool", fadeIn: 1000, fadeOut: 1000, levels: [90,80,91,120,92,255,93,120,98,80,99,120,100,255,101,120,106,80,107,120,108,255,109,120,114,80,115,120,116,255,117,120,122,80,123,120,124,255,125,120,130,80,131,120,132,255,133,120,138,80,139,120,140,255,141,120,146,80,147,120,148,255,149,120,154,80,155,120,156,255,157,120,162,80,163,120,164,255,165,120,170,80,171,120,172,255,173,120,178,80,179,120,180,255,181,120,186,80,187,120,188,255,189,120,194,80,195,120,196,255,197,120,202,80,203,120,204,255,205,120]},
|
||||
],
|
||||
sliders: [
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "Colour 2",
|
||||
now: "now2",
|
||||
pads: [
|
||||
{id: "c2Red", rgb: [1.0, 0.0, 0.0], note: 68, name: "Red", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,255,12,0,13,0,14,0,15,255,16,0,17,0,18,0,19,255,20,0,21,0,22,0,23,255,24,0,25,0,26,0,27,255,28,0,29,0,30,0,31,255,32,0,33,0,34,0,35,255,36,0,37,0,38,0,54,0,55,255,56,0,57,0,58,0,59,255,60,0,61,0,62,0,63,255,64,0,65,0,66,0,67,255,68,0,69,0,70,0,71,255,72,0,73,0,74,0,75,255,76,0,77,0,78,0,79,255,80,0,81,0,82,0,267,0,268,255,269,0,270,0,271,0,272,255,273,0,274,0,275,0,276,255,277,0,278,0,279,0,280,255,281,0,282,0,283,0,284,255,285,0,286,0,287,0,288,255,289,0,290,0,291,0,292,255,293,0,294,0,295,0,310,0,311,255,312,0,313,0,314,0,315,255,316,0,317,0,318,0,319,255,320,0,321,0,322,0,323,255,324,0,325,0,326,0,327,255,328,0,329,0,330,0,331,255,332,0,333,0,334,0,335,255,336,0,337,0,338,0]},
|
||||
{id: "c2Orange", rgb: [1.0, 0.498, 0.0], note: 69, name: "Orange", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,255,12,127,13,0,14,0,15,255,16,127,17,0,18,0,19,255,20,127,21,0,22,0,23,255,24,127,25,0,26,0,27,255,28,127,29,0,30,0,31,255,32,127,33,0,34,0,35,255,36,127,37,0,38,0,54,0,55,255,56,127,57,0,58,0,59,255,60,127,61,0,62,0,63,255,64,127,65,0,66,0,67,255,68,127,69,0,70,0,71,255,72,127,73,0,74,0,75,255,76,127,77,0,78,0,79,255,80,127,81,0,82,0,267,0,268,255,269,127,270,0,271,0,272,255,273,127,274,0,275,0,276,255,277,127,278,0,279,0,280,255,281,127,282,0,283,0,284,255,285,127,286,0,287,0,288,255,289,127,290,0,291,0,292,255,293,127,294,0,295,0,310,0,311,255,312,127,313,0,314,0,315,255,316,127,317,0,318,0,319,255,320,127,321,0,322,0,323,255,324,127,325,0,326,0,327,255,328,127,329,0,330,0,331,255,332,127,333,0,334,0,335,255,336,127,337,0,338,0]},
|
||||
{id: "c2Amber", rgb: [1.0, 0.749, 0.0], note: 70, name: "Amber", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,255,12,191,13,0,14,0,15,255,16,191,17,0,18,0,19,255,20,191,21,0,22,0,23,255,24,191,25,0,26,0,27,255,28,191,29,0,30,0,31,255,32,191,33,0,34,0,35,255,36,191,37,0,38,0,54,0,55,255,56,191,57,0,58,0,59,255,60,191,61,0,62,0,63,255,64,191,65,0,66,0,67,255,68,191,69,0,70,0,71,255,72,191,73,0,74,0,75,255,76,191,77,0,78,0,79,255,80,191,81,0,82,0,267,0,268,255,269,191,270,0,271,0,272,255,273,191,274,0,275,0,276,255,277,191,278,0,279,0,280,255,281,191,282,0,283,0,284,255,285,191,286,0,287,0,288,255,289,191,290,0,291,0,292,255,293,191,294,0,295,0,310,0,311,255,312,191,313,0,314,0,315,255,316,191,317,0,318,0,319,255,320,191,321,0,322,0,323,255,324,191,325,0,326,0,327,255,328,191,329,0,330,0,331,255,332,191,333,0,334,0,335,255,336,191,337,0,338,0]},
|
||||
{id: "c2Yellow", rgb: [1.0, 1.0, 0.0], note: 71, name: "Yellow", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,255,12,255,13,0,14,0,15,255,16,255,17,0,18,0,19,255,20,255,21,0,22,0,23,255,24,255,25,0,26,0,27,255,28,255,29,0,30,0,31,255,32,255,33,0,34,0,35,255,36,255,37,0,38,0,54,0,55,255,56,255,57,0,58,0,59,255,60,255,61,0,62,0,63,255,64,255,65,0,66,0,67,255,68,255,69,0,70,0,71,255,72,255,73,0,74,0,75,255,76,255,77,0,78,0,79,255,80,255,81,0,82,0,267,0,268,255,269,255,270,0,271,0,272,255,273,255,274,0,275,0,276,255,277,255,278,0,279,0,280,255,281,255,282,0,283,0,284,255,285,255,286,0,287,0,288,255,289,255,290,0,291,0,292,255,293,255,294,0,295,0,310,0,311,255,312,255,313,0,314,0,315,255,316,255,317,0,318,0,319,255,320,255,321,0,322,0,323,255,324,255,325,0,326,0,327,255,328,255,329,0,330,0,331,255,332,255,333,0,334,0,335,255,336,255,337,0,338,0]},
|
||||
{id: "c2Lime", rgb: [0.498, 1.0, 0.0], note: 72, name: "Lime", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,127,12,255,13,0,14,0,15,127,16,255,17,0,18,0,19,127,20,255,21,0,22,0,23,127,24,255,25,0,26,0,27,127,28,255,29,0,30,0,31,127,32,255,33,0,34,0,35,127,36,255,37,0,38,0,54,0,55,127,56,255,57,0,58,0,59,127,60,255,61,0,62,0,63,127,64,255,65,0,66,0,67,127,68,255,69,0,70,0,71,127,72,255,73,0,74,0,75,127,76,255,77,0,78,0,79,127,80,255,81,0,82,0,267,0,268,127,269,255,270,0,271,0,272,127,273,255,274,0,275,0,276,127,277,255,278,0,279,0,280,127,281,255,282,0,283,0,284,127,285,255,286,0,287,0,288,127,289,255,290,0,291,0,292,127,293,255,294,0,295,0,310,0,311,127,312,255,313,0,314,0,315,127,316,255,317,0,318,0,319,127,320,255,321,0,322,0,323,127,324,255,325,0,326,0,327,127,328,255,329,0,330,0,331,127,332,255,333,0,334,0,335,127,336,255,337,0,338,0]},
|
||||
{id: "c2Green", rgb: [0.0, 1.0, 0.0], note: 73, name: "Green", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,0,12,255,13,0,14,0,15,0,16,255,17,0,18,0,19,0,20,255,21,0,22,0,23,0,24,255,25,0,26,0,27,0,28,255,29,0,30,0,31,0,32,255,33,0,34,0,35,0,36,255,37,0,38,0,54,0,55,0,56,255,57,0,58,0,59,0,60,255,61,0,62,0,63,0,64,255,65,0,66,0,67,0,68,255,69,0,70,0,71,0,72,255,73,0,74,0,75,0,76,255,77,0,78,0,79,0,80,255,81,0,82,0,267,0,268,0,269,255,270,0,271,0,272,0,273,255,274,0,275,0,276,0,277,255,278,0,279,0,280,0,281,255,282,0,283,0,284,0,285,255,286,0,287,0,288,0,289,255,290,0,291,0,292,0,293,255,294,0,295,0,310,0,311,0,312,255,313,0,314,0,315,0,316,255,317,0,318,0,319,0,320,255,321,0,322,0,323,0,324,255,325,0,326,0,327,0,328,255,329,0,330,0,331,0,332,255,333,0,334,0,335,0,336,255,337,0,338,0]},
|
||||
{id: "c2Spring", rgb: [0.0, 1.0, 0.498], note: 74, name: "Spring", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,0,12,255,13,127,14,0,15,0,16,255,17,127,18,0,19,0,20,255,21,127,22,0,23,0,24,255,25,127,26,0,27,0,28,255,29,127,30,0,31,0,32,255,33,127,34,0,35,0,36,255,37,127,38,0,54,0,55,0,56,255,57,127,58,0,59,0,60,255,61,127,62,0,63,0,64,255,65,127,66,0,67,0,68,255,69,127,70,0,71,0,72,255,73,127,74,0,75,0,76,255,77,127,78,0,79,0,80,255,81,127,82,0,267,0,268,0,269,255,270,127,271,0,272,0,273,255,274,127,275,0,276,0,277,255,278,127,279,0,280,0,281,255,282,127,283,0,284,0,285,255,286,127,287,0,288,0,289,255,290,127,291,0,292,0,293,255,294,127,295,0,310,0,311,0,312,255,313,127,314,0,315,0,316,255,317,127,318,0,319,0,320,255,321,127,322,0,323,0,324,255,325,127,326,0,327,0,328,255,329,127,330,0,331,0,332,255,333,127,334,0,335,0,336,255,337,127,338,0]},
|
||||
{id: "c2Cyan", rgb: [0.0, 1.0, 1.0], note: 75, name: "Cyan", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,0,12,255,13,255,14,0,15,0,16,255,17,255,18,0,19,0,20,255,21,255,22,0,23,0,24,255,25,255,26,0,27,0,28,255,29,255,30,0,31,0,32,255,33,255,34,0,35,0,36,255,37,255,38,0,54,0,55,0,56,255,57,255,58,0,59,0,60,255,61,255,62,0,63,0,64,255,65,255,66,0,67,0,68,255,69,255,70,0,71,0,72,255,73,255,74,0,75,0,76,255,77,255,78,0,79,0,80,255,81,255,82,0,267,0,268,0,269,255,270,255,271,0,272,0,273,255,274,255,275,0,276,0,277,255,278,255,279,0,280,0,281,255,282,255,283,0,284,0,285,255,286,255,287,0,288,0,289,255,290,255,291,0,292,0,293,255,294,255,295,0,310,0,311,0,312,255,313,255,314,0,315,0,316,255,317,255,318,0,319,0,320,255,321,255,322,0,323,0,324,255,325,255,326,0,327,0,328,255,329,255,330,0,331,0,332,255,333,255,334,0,335,0,336,255,337,255,338,0]},
|
||||
{id: "c2Azure", rgb: [0.0, 0.498, 1.0], note: 76, name: "Azure", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,0,12,127,13,255,14,0,15,0,16,127,17,255,18,0,19,0,20,127,21,255,22,0,23,0,24,127,25,255,26,0,27,0,28,127,29,255,30,0,31,0,32,127,33,255,34,0,35,0,36,127,37,255,38,0,54,0,55,0,56,127,57,255,58,0,59,0,60,127,61,255,62,0,63,0,64,127,65,255,66,0,67,0,68,127,69,255,70,0,71,0,72,127,73,255,74,0,75,0,76,127,77,255,78,0,79,0,80,127,81,255,82,0,267,0,268,0,269,127,270,255,271,0,272,0,273,127,274,255,275,0,276,0,277,127,278,255,279,0,280,0,281,127,282,255,283,0,284,0,285,127,286,255,287,0,288,0,289,127,290,255,291,0,292,0,293,127,294,255,295,0,310,0,311,0,312,127,313,255,314,0,315,0,316,127,317,255,318,0,319,0,320,127,321,255,322,0,323,0,324,127,325,255,326,0,327,0,328,127,329,255,330,0,331,0,332,127,333,255,334,0,335,0,336,127,337,255,338,0]},
|
||||
{id: "c2Blue", rgb: [0.0, 0.0, 1.0], note: 77, name: "Blue", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,0,12,0,13,255,14,0,15,0,16,0,17,255,18,0,19,0,20,0,21,255,22,0,23,0,24,0,25,255,26,0,27,0,28,0,29,255,30,0,31,0,32,0,33,255,34,0,35,0,36,0,37,255,38,0,54,0,55,0,56,0,57,255,58,0,59,0,60,0,61,255,62,0,63,0,64,0,65,255,66,0,67,0,68,0,69,255,70,0,71,0,72,0,73,255,74,0,75,0,76,0,77,255,78,0,79,0,80,0,81,255,82,0,267,0,268,0,269,0,270,255,271,0,272,0,273,0,274,255,275,0,276,0,277,0,278,255,279,0,280,0,281,0,282,255,283,0,284,0,285,0,286,255,287,0,288,0,289,0,290,255,291,0,292,0,293,0,294,255,295,0,310,0,311,0,312,0,313,255,314,0,315,0,316,0,317,255,318,0,319,0,320,0,321,255,322,0,323,0,324,0,325,255,326,0,327,0,328,0,329,255,330,0,331,0,332,0,333,255,334,0,335,0,336,0,337,255,338,0]},
|
||||
{id: "c2Violet", rgb: [0.498, 0.0, 1.0], note: 78, name: "Violet", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,127,12,0,13,255,14,0,15,127,16,0,17,255,18,0,19,127,20,0,21,255,22,0,23,127,24,0,25,255,26,0,27,127,28,0,29,255,30,0,31,127,32,0,33,255,34,0,35,127,36,0,37,255,38,0,54,0,55,127,56,0,57,255,58,0,59,127,60,0,61,255,62,0,63,127,64,0,65,255,66,0,67,127,68,0,69,255,70,0,71,127,72,0,73,255,74,0,75,127,76,0,77,255,78,0,79,127,80,0,81,255,82,0,267,0,268,127,269,0,270,255,271,0,272,127,273,0,274,255,275,0,276,127,277,0,278,255,279,0,280,127,281,0,282,255,283,0,284,127,285,0,286,255,287,0,288,127,289,0,290,255,291,0,292,127,293,0,294,255,295,0,310,0,311,127,312,0,313,255,314,0,315,127,316,0,317,255,318,0,319,127,320,0,321,255,322,0,323,127,324,0,325,255,326,0,327,127,328,0,329,255,330,0,331,127,332,0,333,255,334,0,335,127,336,0,337,255,338,0]},
|
||||
{id: "c2Magenta", rgb: [1.0, 0.0, 1.0], note: 79, name: "Magenta", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,255,12,0,13,255,14,0,15,255,16,0,17,255,18,0,19,255,20,0,21,255,22,0,23,255,24,0,25,255,26,0,27,255,28,0,29,255,30,0,31,255,32,0,33,255,34,0,35,255,36,0,37,255,38,0,54,0,55,255,56,0,57,255,58,0,59,255,60,0,61,255,62,0,63,255,64,0,65,255,66,0,67,255,68,0,69,255,70,0,71,255,72,0,73,255,74,0,75,255,76,0,77,255,78,0,79,255,80,0,81,255,82,0,267,0,268,255,269,0,270,255,271,0,272,255,273,0,274,255,275,0,276,255,277,0,278,255,279,0,280,255,281,0,282,255,283,0,284,255,285,0,286,255,287,0,288,255,289,0,290,255,291,0,292,255,293,0,294,255,295,0,310,0,311,255,312,0,313,255,314,0,315,255,316,0,317,255,318,0,319,255,320,0,321,255,322,0,323,255,324,0,325,255,326,0,327,255,328,0,329,255,330,0,331,255,332,0,333,255,334,0,335,255,336,0,337,255,338,0]},
|
||||
{id: "c2Pink", rgb: [1.0, 0.157, 0.471], note: 80, name: "Pink", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,255,12,40,13,120,14,0,15,255,16,40,17,120,18,0,19,255,20,40,21,120,22,0,23,255,24,40,25,120,26,0,27,255,28,40,29,120,30,0,31,255,32,40,33,120,34,0,35,255,36,40,37,120,38,0,54,0,55,255,56,40,57,120,58,0,59,255,60,40,61,120,62,0,63,255,64,40,65,120,66,0,67,255,68,40,69,120,70,0,71,255,72,40,73,120,74,0,75,255,76,40,77,120,78,0,79,255,80,40,81,120,82,0,267,0,268,255,269,40,270,120,271,0,272,255,273,40,274,120,275,0,276,255,277,40,278,120,279,0,280,255,281,40,282,120,283,0,284,255,285,40,286,120,287,0,288,255,289,40,290,120,291,0,292,255,293,40,294,120,295,0,310,0,311,255,312,40,313,120,314,0,315,255,316,40,317,120,318,0,319,255,320,40,321,120,322,0,323,255,324,40,325,120,326,0,327,255,328,40,329,120,330,0,331,255,332,40,333,120,334,0,335,255,336,40,337,120,338,0]},
|
||||
{id: "c2Warm", rgb: [1.0, 0.941, 0.627], note: 81, name: "Warm", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,255,12,120,13,40,14,120,15,255,16,120,17,40,18,120,19,255,20,120,21,40,22,120,23,255,24,120,25,40,26,120,27,255,28,120,29,40,30,120,31,255,32,120,33,40,34,120,35,255,36,120,37,40,38,120,54,0,55,255,56,120,57,40,58,120,59,255,60,120,61,40,62,120,63,255,64,120,65,40,66,120,67,255,68,120,69,40,70,120,71,255,72,120,73,40,74,120,75,255,76,120,77,40,78,120,79,255,80,120,81,40,82,120,267,0,268,255,269,120,270,40,271,120,272,255,273,120,274,40,275,120,276,255,277,120,278,40,279,120,280,255,281,120,282,40,283,120,284,255,285,120,286,40,287,120,288,255,289,120,290,40,291,120,292,255,293,120,294,40,295,120,310,0,311,255,312,120,313,40,314,120,315,255,316,120,317,40,318,120,319,255,320,120,321,40,322,120,323,255,324,120,325,40,326,120,327,255,328,120,329,40,330,120,331,255,332,120,333,40,334,120,335,255,336,120,337,40,338,120]},
|
||||
{id: "c2White", rgb: [1.0, 1.0, 1.0], note: 82, name: "White", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,0,12,0,13,0,14,255,15,0,16,0,17,0,18,255,19,0,20,0,21,0,22,255,23,0,24,0,25,0,26,255,27,0,28,0,29,0,30,255,31,0,32,0,33,0,34,255,35,0,36,0,37,0,38,255,54,0,55,0,56,0,57,0,58,255,59,0,60,0,61,0,62,255,63,0,64,0,65,0,66,255,67,0,68,0,69,0,70,255,71,0,72,0,73,0,74,255,75,0,76,0,77,0,78,255,79,0,80,0,81,0,82,255,267,0,268,0,269,0,270,0,271,255,272,0,273,0,274,0,275,255,276,0,277,0,278,0,279,255,280,0,281,0,282,0,283,255,284,0,285,0,286,0,287,255,288,0,289,0,290,0,291,255,292,0,293,0,294,0,295,255,310,0,311,0,312,0,313,0,314,255,315,0,316,0,317,0,318,255,319,0,320,0,321,0,322,255,323,0,324,0,325,0,326,255,327,0,328,0,329,0,330,255,331,0,332,0,333,0,334,255,335,0,336,0,337,0,338,255]},
|
||||
{id: "c2Cool", rgb: [0.784, 0.941, 1.0], note: 83, name: "Cool", fadeIn: 1000, fadeOut: 1000, levels: [10,0,11,80,12,120,13,255,14,120,15,80,16,120,17,255,18,120,19,80,20,120,21,255,22,120,23,80,24,120,25,255,26,120,27,80,28,120,29,255,30,120,31,80,32,120,33,255,34,120,35,80,36,120,37,255,38,120,54,0,55,80,56,120,57,255,58,120,59,80,60,120,61,255,62,120,63,80,64,120,65,255,66,120,67,80,68,120,69,255,70,120,71,80,72,120,73,255,74,120,75,80,76,120,77,255,78,120,79,80,80,120,81,255,82,120,267,0,268,80,269,120,270,255,271,120,272,80,273,120,274,255,275,120,276,80,277,120,278,255,279,120,280,80,281,120,282,255,283,120,284,80,285,120,286,255,287,120,288,80,289,120,290,255,291,120,292,80,293,120,294,255,295,120,310,0,311,80,312,120,313,255,314,120,315,80,316,120,317,255,318,120,319,80,320,120,321,255,322,120,323,80,324,120,325,255,326,120,327,80,328,120,329,255,330,120,331,80,332,120,333,255,334,120,335,80,336,120,337,255,338,120]},
|
||||
],
|
||||
sliders: [
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "Dimmers",
|
||||
now: "now3",
|
||||
pads: [
|
||||
],
|
||||
sliders: [
|
||||
{id: "s3Movers", cc: 44, name: "Movers", value: 1.0, levels: [9,255,53,255,266,255,309,255]},
|
||||
{id: "s3Cans915", cc: 34, name: "Cans 9\u201315", value: 1.0, levels: [152,255,160,255,168,255,176,255,184,255,192,255,200,255]},
|
||||
{id: "s3Cans36", cc: 36, name: "Cans 3\u20136", value: 1.0, levels: [104,255,112,255,120,255,128,255]},
|
||||
{id: "s3Cans1278", cc: 37, name: "Cans 1, 2, 7, 8", value: 1.0, levels: [88,255,96,255,136,255,144,255]},
|
||||
]
|
||||
},
|
||||
];
|
||||
|
||||
var LAMP = "Lamp";
|
||||
var LAMP_OFF = 0.3; // brightness of a pad's tile when it is not playing
|
||||
var FADE_RATE = 100; // script updates per second
|
||||
var PLAY_CC = 27; // hold Play to move bank 2 (notes 52-67) up 16, like padcontroller/layer.py
|
||||
var BANK_FIRST = 52;
|
||||
var BANK_LAST = 67;
|
||||
var BANK_SHIFT = 16;
|
||||
var DMX_SIZE = 513; // channels are 1-based
|
||||
|
||||
var states = [];
|
||||
var sent = [];
|
||||
var lookup = {};
|
||||
var lampParams = [];
|
||||
var sliderParams = [];
|
||||
var nowParams = [];
|
||||
var busy = false;
|
||||
var primed = false;
|
||||
var playHeld = false;
|
||||
|
||||
function init()
|
||||
{
|
||||
script.setUpdateRate(FADE_RATE);
|
||||
for (var i = 0; i < DMX_SIZE; i++) sent[i] = -1;
|
||||
states = [];
|
||||
for (var g = 0; g < GROUPS.length; g++)
|
||||
{
|
||||
var level = [], from = [], to = [], touched = [];
|
||||
for (var c = 0; c < DMX_SIZE; c++) { level[c] = 0; from[c] = 0; to[c] = 0; touched[c] = 0; }
|
||||
var group = GROUPS[g];
|
||||
for (var p = 0; p < group.pads.length; p++) mark(touched, group.pads[p].levels);
|
||||
for (var s = 0; s < group.sliders.length; s++) mark(touched, group.sliders[s].levels);
|
||||
var mix = [];
|
||||
for (var m = 0; m < group.sliders.length; m++) mix[m] = group.sliders[m].value;
|
||||
states[g] = {active: -1, elapsed: 0, duration: 0, level: level, from: from, to: to, touched: touched, mix: mix};
|
||||
|
||||
// Controls on the script's Params, for the dashboard to show.
|
||||
sliderParams[g] = [];
|
||||
lampParams[g] = [];
|
||||
for (var q = 0; q < group.pads.length; q++)
|
||||
{
|
||||
script.addTrigger(group.pads[q].id, group.name + " " + group.pads[q].name);
|
||||
lampParams[g][q] = script.addColorParameter(group.pads[q].id + LAMP, group.name + " " + group.pads[q].name + " lamp", shade(group.pads[q].rgb, LAMP_OFF));
|
||||
lookup[group.pads[q].id] = {g: g, p: q, s: -1};
|
||||
}
|
||||
for (var r = 0; r < group.sliders.length; r++)
|
||||
{
|
||||
sliderParams[g][r] = script.addFloatParameter(group.sliders[r].id, group.name + " " + group.sliders[r].name, group.sliders[r].value, 0, 1);
|
||||
lookup[group.sliders[r].id] = {g: g, p: -1, s: r};
|
||||
}
|
||||
nowParams[g] = script.addStringParameter(group.now, group.name + " scene", "");
|
||||
}
|
||||
script.log("show script ready: " + GROUPS.length + " groups");
|
||||
}
|
||||
|
||||
function mark(touched, levels)
|
||||
{
|
||||
for (var i = 0; i < levels.length; i += 2) touched[levels[i]] = 1;
|
||||
}
|
||||
|
||||
// A pad press starts its scene and fades the others out. A second press stops it.
|
||||
function noteOnEvent(channel, pitch, velocity)
|
||||
{
|
||||
if (velocity == 0) return;
|
||||
if (playHeld && pitch >= BANK_FIRST && pitch <= BANK_LAST) pitch += BANK_SHIFT;
|
||||
for (var g = 0; g < GROUPS.length; g++)
|
||||
{
|
||||
var pads = GROUPS[g].pads;
|
||||
for (var p = 0; p < pads.length; p++)
|
||||
{
|
||||
if (pads[p].note == pitch) { press(g, p); return; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A control on the dashboard changed.
|
||||
function scriptParameterChanged(param)
|
||||
{
|
||||
if (busy) return;
|
||||
var hit = lookup[param.name];
|
||||
if (!hit) return;
|
||||
if (hit.p >= 0) press(hit.g, hit.p);
|
||||
else states[hit.g].mix[hit.s] = param.get();
|
||||
}
|
||||
|
||||
function shade(rgb, level)
|
||||
{
|
||||
return [rgb[0] * level, rgb[1] * level, rgb[2] * level, 1];
|
||||
}
|
||||
|
||||
// Light the playing pad's strip on the board and show its name.
|
||||
function show(g, name)
|
||||
{
|
||||
busy = true;
|
||||
nowParams[g].set(name);
|
||||
var pads = GROUPS[g].pads;
|
||||
for (var p = 0; p < pads.length; p++) lampParams[g][p].set(shade(pads[p].rgb, states[g].active == p ? 1 : LAMP_OFF));
|
||||
busy = false;
|
||||
}
|
||||
|
||||
function press(g, p)
|
||||
{
|
||||
var st = states[g];
|
||||
var pad = GROUPS[g].pads[p];
|
||||
for (var c = 0; c < DMX_SIZE; c++) { st.from[c] = st.level[c]; st.to[c] = 0; }
|
||||
if (st.active == p)
|
||||
{
|
||||
st.active = -1;
|
||||
st.duration = pad.fadeOut;
|
||||
show(g, "");
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < pad.levels.length; i += 2) st.to[pad.levels[i]] = pad.levels[i + 1];
|
||||
st.active = p;
|
||||
st.duration = pad.fadeIn;
|
||||
show(g, pad.name);
|
||||
}
|
||||
st.elapsed = 0;
|
||||
}
|
||||
|
||||
function ccEvent(channel, number, value)
|
||||
{
|
||||
if (number == PLAY_CC) { playHeld = value > 0; return; }
|
||||
for (var g = 0; g < GROUPS.length; g++)
|
||||
{
|
||||
var sliders = GROUPS[g].sliders;
|
||||
for (var s = 0; s < sliders.length; s++)
|
||||
{
|
||||
if (sliders[s].cc == number)
|
||||
{
|
||||
states[g].mix[s] = value / 127;
|
||||
busy = true;
|
||||
sliderParams[g][s].set(value / 127);
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The dashboard web server does not always start when a project loads with it enabled, so switch
|
||||
// it off and on once the script is running.
|
||||
function startWeb()
|
||||
{
|
||||
var settings = root.projectSettings;
|
||||
if (!settings || !settings.dashboardSettings) return;
|
||||
var web = settings.dashboardSettings.enableDashboardServer;
|
||||
if (!web) return;
|
||||
web.set(false);
|
||||
web.set(true);
|
||||
script.log("dashboard web server restarted");
|
||||
}
|
||||
|
||||
function update(deltaTime)
|
||||
{
|
||||
// A colour control's starting value is read in a different colour model and saved values load
|
||||
// after init, so paint every tile once the script is running.
|
||||
if (!primed)
|
||||
{
|
||||
primed = true;
|
||||
startWeb();
|
||||
for (var g = 0; g < GROUPS.length; g++) show(g, states[g].active >= 0 ? GROUPS[g].pads[states[g].active].name : "");
|
||||
}
|
||||
var out = [];
|
||||
for (var c = 0; c < DMX_SIZE; c++) out[c] = 0;
|
||||
for (var g = 0; g < GROUPS.length; g++) render(g, deltaTime, out);
|
||||
|
||||
var first = -1, last = -1;
|
||||
for (var i = 1; i < DMX_SIZE; i++)
|
||||
{
|
||||
if (out[i] != sent[i]) { if (first < 0) first = i; last = i; }
|
||||
}
|
||||
if (first < 0) return;
|
||||
var values = [];
|
||||
for (var j = first; j <= last; j++) { values.push(out[j]); sent[j] = out[j]; }
|
||||
root.modules.lights.send(first, values);
|
||||
if (root.modules.preview) root.modules.preview.send(first, values);
|
||||
}
|
||||
|
||||
function render(g, deltaTime, out)
|
||||
{
|
||||
var st = states[g];
|
||||
st.elapsed += deltaTime * 1000;
|
||||
var t = st.duration > 0 ? Math.min(1, st.elapsed / st.duration) : 1;
|
||||
for (var c = 1; c < DMX_SIZE; c++)
|
||||
{
|
||||
if (!st.touched[c]) continue;
|
||||
st.level[c] = st.from[c] + (st.to[c] - st.from[c]) * t;
|
||||
out[c] = Math.max(out[c], st.level[c]);
|
||||
}
|
||||
var sliders = GROUPS[g].sliders;
|
||||
for (var s = 0; s < sliders.length; s++)
|
||||
{
|
||||
var levels = sliders[s].levels;
|
||||
for (var i = 0; i < levels.length; i += 2)
|
||||
{
|
||||
out[levels[i]] = Math.max(out[levels[i]], levels[i + 1] * st.mix[s]);
|
||||
}
|
||||
}
|
||||
for (var k = 1; k < DMX_SIZE; k++) out[k] = Math.round(out[k]);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,143 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE FixtureDefinition>
|
||||
<FixtureDefinition xmlns="http://www.qlcplus.org/FixtureDefinition">
|
||||
<Creator>
|
||||
<Name>Q Light Controller Plus</Name>
|
||||
<Version>4.12.7</Version>
|
||||
<Author>Jimmy</Author>
|
||||
</Creator>
|
||||
<Manufacturer>Chauvet</Manufacturer>
|
||||
<Model>Scorpion Dual RGB</Model>
|
||||
<Type>Laser</Type>
|
||||
<Channel Name="Control Mode" Default="0">
|
||||
<Group Byte="0">Maintenance</Group>
|
||||
<Capability Min="0" Max="17">Manual control mode</Capability>
|
||||
<Capability Min="18" Max="34">Automatic mode (multi-colour)</Capability>
|
||||
<Capability Min="35" Max="51">Automatic mode (red)</Capability>
|
||||
<Capability Min="52" Max="68">Automatic mode (green)</Capability>
|
||||
<Capability Min="69" Max="85">Automatic mode (blue)</Capability>
|
||||
<Capability Min="86" Max="102">Automatic mode (yellow)</Capability>
|
||||
<Capability Min="103" Max="119">Automatic mode (magenta)</Capability>
|
||||
<Capability Min="120" Max="136">Automatic mode (cyan)</Capability>
|
||||
<Capability Min="137" Max="153">Sound-active mode (multi-colour)</Capability>
|
||||
<Capability Min="154" Max="170">Sound-active mode (red)</Capability>
|
||||
<Capability Min="171" Max="187">Sound-active mode (green)</Capability>
|
||||
<Capability Min="188" Max="204">Sound-active mode (blue)</Capability>
|
||||
<Capability Min="205" Max="221">Sound-active mode (yellow)</Capability>
|
||||
<Capability Min="222" Max="238">Sound-active mode (magenta)</Capability>
|
||||
<Capability Min="239" Max="255">Sound-active mode (cyan)</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Pattern">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="7">1 Circle</Capability>
|
||||
<Capability Min="8" Max="15">2 Dashed circle</Capability>
|
||||
<Capability Min="16" Max="23">3 Triangle</Capability>
|
||||
<Capability Min="24" Max="31">4 Square</Capability>
|
||||
<Capability Min="32" Max="39">5 Dashed square</Capability>
|
||||
<Capability Min="40" Max="47">6 Square in a square</Capability>
|
||||
<Capability Min="48" Max="55">7 Cross</Capability>
|
||||
<Capability Min="56" Max="63">8 Star</Capability>
|
||||
<Capability Min="64" Max="71">9 Backwards L</Capability>
|
||||
<Capability Min="72" Max="79">10 Bow-tie</Capability>
|
||||
<Capability Min="80" Max="87">11 Spiral</Capability>
|
||||
<Capability Min="88" Max="95">12 Half circles</Capability>
|
||||
<Capability Min="96" Max="103">13 Fibonacci spiral</Capability>
|
||||
<Capability Min="104" Max="111">14 Parenthesis</Capability>
|
||||
<Capability Min="112" Max="119">15 Two triangles</Capability>
|
||||
<Capability Min="120" Max="127">16 Zig-zag</Capability>
|
||||
<Capability Min="128" Max="135">17 V-line</Capability>
|
||||
<Capability Min="136" Max="143">18 Sawtooth</Capability>
|
||||
<Capability Min="144" Max="151">19 Square wave</Capability>
|
||||
<Capability Min="152" Max="159">20 Line</Capability>
|
||||
<Capability Min="160" Max="167">21 Dashed line</Capability>
|
||||
<Capability Min="168" Max="175">22 Strobed line</Capability>
|
||||
<Capability Min="176" Max="183">23 Parallel lines</Capability>
|
||||
<Capability Min="184" Max="191">24 Crosshair</Capability>
|
||||
<Capability Min="192" Max="199">25 Two dashes</Capability>
|
||||
<Capability Min="200" Max="207">26 Four lines (square)</Capability>
|
||||
<Capability Min="208" Max="215">27 Two squares</Capability>
|
||||
<Capability Min="216" Max="223">28 Four squares</Capability>
|
||||
<Capability Min="224" Max="231">29 Small circle</Capability>
|
||||
<Capability Min="232" Max="239">30 Dotted line</Capability>
|
||||
<Capability Min="240" Max="247">31 Dotted half-circle</Capability>
|
||||
<Capability Min="248" Max="255">32 Cluster dashes</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Colour" Default="0">
|
||||
<Group Byte="0">Colour</Group>
|
||||
<Capability Min="0" Max="14">No function (laser off)</Capability>
|
||||
<Capability Min="15" Max="30" Preset="GenericPicture" Res1="Others/rainbow.png">Multi-colour</Capability>
|
||||
<Capability Min="31" Max="46" Preset="ColorMacro" Res1="#ff0000">Red</Capability>
|
||||
<Capability Min="47" Max="62" Preset="ColorMacro" Res1="#00ff00">Green</Capability>
|
||||
<Capability Min="63" Max="78" Preset="ColorMacro" Res1="#0030ff">Blue</Capability>
|
||||
<Capability Min="79" Max="94" Preset="ColorMacro" Res1="#ffff00">Yellow</Capability>
|
||||
<Capability Min="95" Max="110" Preset="ColorMacro" Res1="#d105f5">Magenta</Capability>
|
||||
<Capability Min="111" Max="126" Preset="ColorMacro" Res1="#00ffff">Cyan</Capability>
|
||||
<Capability Min="127" Max="149" Preset="ColorDoubleMacro" Res1="#ff0000" Res2="#00ff00">Red and green program</Capability>
|
||||
<Capability Min="150" Max="174" Preset="ColorDoubleMacro" Res1="#00ff00" Res2="#1f52ff">Green and blue program</Capability>
|
||||
<Capability Min="175" Max="199" Preset="ColorDoubleMacro" Res1="#ff0000" Res2="#0549ff">Red and blue program</Capability>
|
||||
<Capability Min="200" Max="224">All colours program</Capability>
|
||||
<Capability Min="225" Max="255" Preset="GenericPicture" Res1="Others/rainbow.png">Multi-colour program</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Strobe / Speed">
|
||||
<Group Byte="0">Shutter</Group>
|
||||
<Capability Min="0" Max="4" Preset="ShutterOpen">Open / slowest program</Capability>
|
||||
<Capability Min="5" Max="255" Preset="StrobeSlowToFast">Strobe or colour-program speed, slow to fast</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Zoom">
|
||||
<Group Byte="0">Beam</Group>
|
||||
<Capability Min="0" Max="127">Manual zoom, 100–5%</Capability>
|
||||
<Capability Min="128" Max="169">Auto zoom, 100–5%, slow to fast</Capability>
|
||||
<Capability Min="170" Max="209">Auto zoom, 5–100%, slow to fast</Capability>
|
||||
<Capability Min="210" Max="255">Auto zoom, 100–5–100%, slow to fast</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Pan" Default="64">
|
||||
<Group Byte="0">Pan</Group>
|
||||
<Capability Min="0" Max="127">Manual pan (128 points, 30°)</Capability>
|
||||
<Capability Min="128" Max="191">Auto pan, slow to fast</Capability>
|
||||
<Capability Min="192" Max="255">Reverse auto pan, fast to slow</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Tilt" Default="64">
|
||||
<Group Byte="0">Tilt</Group>
|
||||
<Capability Min="0" Max="127">Manual tilt (128 points, 30°)</Capability>
|
||||
<Capability Min="128" Max="191">Auto tilt, slow to fast</Capability>
|
||||
<Capability Min="192" Max="255">Reverse auto tilt, fast to slow</Capability>
|
||||
</Channel>
|
||||
<Channel Name="X-Axis Rolling">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="127">Manual x-axis rolling (0–359°)</Capability>
|
||||
<Capability Min="128" Max="191">Auto rolling, slow to fast</Capability>
|
||||
<Capability Min="192" Max="255">Reverse auto rolling, fast to slow</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Y-Axis Rolling">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="127">Manual y-axis rolling (0–359°)</Capability>
|
||||
<Capability Min="128" Max="191">Auto rolling, slow to fast</Capability>
|
||||
<Capability Min="192" Max="255">Reverse auto rolling, fast to slow</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Z-Axis Rolling">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="127">Manual z-axis rolling (0–359°)</Capability>
|
||||
<Capability Min="128" Max="191">Auto rolling, slow to fast</Capability>
|
||||
<Capability Min="192" Max="255">Reverse auto rolling, fast to slow</Capability>
|
||||
</Channel>
|
||||
<Mode Name="10 Channel">
|
||||
<Channel Number="0">Control Mode</Channel>
|
||||
<Channel Number="1">Pattern</Channel>
|
||||
<Channel Number="2">Colour</Channel>
|
||||
<Channel Number="3">Strobe / Speed</Channel>
|
||||
<Channel Number="4">Zoom</Channel>
|
||||
<Channel Number="5">Pan</Channel>
|
||||
<Channel Number="6">Tilt</Channel>
|
||||
<Channel Number="7">X-Axis Rolling</Channel>
|
||||
<Channel Number="8">Y-Axis Rolling</Channel>
|
||||
<Channel Number="9">Z-Axis Rolling</Channel>
|
||||
</Mode>
|
||||
<Physical>
|
||||
<Bulb Type="Laser" Lumens="0" ColourTemperature="0"/>
|
||||
<Dimensions Weight="1.7" Width="216" Height="180" Depth="161"/>
|
||||
<Lens Name="Other" DegreesMin="1" DegreesMax="29"/>
|
||||
<Focus Type="Fixed" PanMax="30" TiltMax="30"/>
|
||||
<Layout Width="2" Height="1"/>
|
||||
<Technical PowerConsumption="20" DmxConnector="3-pin"/>
|
||||
</Physical>
|
||||
</FixtureDefinition>
|
||||
@@ -0,0 +1,453 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE FixtureDefinition>
|
||||
<FixtureDefinition xmlns="http://www.qlcplus.org/FixtureDefinition">
|
||||
<Creator>
|
||||
<Name>Q Light Controller Plus</Name>
|
||||
<Version>4.12.7</Version>
|
||||
<Author>Jimmy</Author>
|
||||
</Creator>
|
||||
<Manufacturer>Small Eye 7</Manufacturer>
|
||||
<Model>Mover</Model>
|
||||
<Type>Moving Head</Type>
|
||||
<Channel Name="Pan" Preset="PositionPan"/>
|
||||
<Channel Name="Pan Fine" Preset="PositionPanFine"/>
|
||||
<Channel Name="Tilt" Preset="PositionTilt"/>
|
||||
<Channel Name="Tilt Fine" Preset="PositionTiltFine"/>
|
||||
<Channel Name="Pan/Tilt Speed" Preset="SpeedPanTiltFastSlow"/>
|
||||
<Channel Name="Zoom" Preset="BeamZoomSmallBig"/>
|
||||
<Channel Name="Focus" Preset="BeamFocusNearFar">
|
||||
<Group Byte="0">Beam</Group>
|
||||
<Capability Min="0" Max="254">Focus — lens rotate will not spin</Capability>
|
||||
<Capability Min="255" Max="255">Full focus — lens rotate enabled</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Center Brightness" Preset="IntensityMasterDimmer"/>
|
||||
<Channel Name="Center Strobe">
|
||||
<Group Byte="0">Shutter</Group>
|
||||
<Capability Min="0" Max="3" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="4" Max="200" Preset="StrobeSlowToFast">Strobe slow to fast</Capability>
|
||||
<Capability Min="201" Max="215" Preset="StrobeRandom">Random strobe low</Capability>
|
||||
<Capability Min="216" Max="234" Preset="StrobeRandom">Random strobe mid</Capability>
|
||||
<Capability Min="235" Max="255" Preset="StrobeRandom">Random strobe high</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Lens Rotate">
|
||||
<Group Byte="0">Prism</Group>
|
||||
<Capability Min="0" Max="127">Index 0–60° (no spin)</Capability>
|
||||
<Capability Min="128" Max="188" Preset="RotationCounterClockwiseFastToSlow">Spin CCW fast to slow (only at full focus)</Capability>
|
||||
<Capability Min="189" Max="193">Stop</Capability>
|
||||
<Capability Min="194" Max="255" Preset="RotationClockwiseSlowToFast">Spin CW slow to fast (only at full focus)</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Lens Rotate 35">
|
||||
<Group Byte="0">Prism</Group>
|
||||
<Capability Min="0" Max="127">Index 0–60°</Capability>
|
||||
<Capability Min="128" Max="191" Preset="RotationClockwise">Rotate CW infinite</Capability>
|
||||
<Capability Min="192" Max="255" Preset="RotationCounterClockwise">Rotate CCW infinite</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Dimmer" Preset="IntensityMasterDimmer"/>
|
||||
<Channel Name="Dimmer Fine" Preset="IntensityMasterDimmerFine"/>
|
||||
<Channel Name="Strobe">
|
||||
<Group Byte="0">Shutter</Group>
|
||||
<Capability Min="0" Max="3" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="4" Max="200" Preset="StrobeSlowToFast">Strobe slow to fast</Capability>
|
||||
<Capability Min="201" Max="215" Preset="StrobeRandom">Random strobe low</Capability>
|
||||
<Capability Min="216" Max="234" Preset="StrobeRandom">Random strobe mid</Capability>
|
||||
<Capability Min="235" Max="255" Preset="StrobeRandom">Random strobe high</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Strobe 35">
|
||||
<Group Byte="0">Shutter</Group>
|
||||
<Capability Min="0" Max="3" Preset="ShutterClose">Closed</Capability>
|
||||
<Capability Min="4" Max="103" Preset="StrobeSlowToFast">Sync strobe 1–25 Hz</Capability>
|
||||
<Capability Min="104" Max="107" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="108" Max="207" Preset="StrobeSlowToFast">Pulse strobe 1–25 Hz</Capability>
|
||||
<Capability Min="208" Max="212" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="213" Max="225" Preset="StrobeRandom">Random strobe low</Capability>
|
||||
<Capability Min="226" Max="238" Preset="StrobeRandom">Random strobe mid</Capability>
|
||||
<Capability Min="239" Max="251" Preset="StrobeRandom">Random strobe high</Capability>
|
||||
<Capability Min="252" Max="255" Preset="ShutterOpen">Open</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Red" Preset="IntensityRed"/>
|
||||
<Channel Name="Red Fine" Preset="IntensityRedFine"/>
|
||||
<Channel Name="Green" Preset="IntensityGreen"/>
|
||||
<Channel Name="Green Fine" Preset="IntensityGreenFine"/>
|
||||
<Channel Name="Blue" Preset="IntensityBlue"/>
|
||||
<Channel Name="Blue Fine" Preset="IntensityBlueFine"/>
|
||||
<Channel Name="White" Preset="IntensityWhite"/>
|
||||
<Channel Name="White Fine" Preset="IntensityWhiteFine"/>
|
||||
<Channel Name="Colour Temperature">
|
||||
<Group Byte="0">Colour</Group>
|
||||
<Capability Min="0" Max="255">Linear CTO / colour temperature</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Colour Macro">
|
||||
<Group Byte="0">Colour</Group>
|
||||
<Capability Min="0" Max="9">No function</Capability>
|
||||
<Capability Min="10" Max="255">Built-in colour macros</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Static Effect">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="9">No function</Capability>
|
||||
<Capability Min="10" Max="255">Static pixel effect select</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Dynamic Effect">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="9">No function</Capability>
|
||||
<Capability Min="10" Max="255">Dynamic pixel effect select</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Dynamic Effect Speed">
|
||||
<Group Byte="0">Speed</Group>
|
||||
<Capability Min="0" Max="127">Forward fast to slow</Capability>
|
||||
<Capability Min="128" Max="255">Reverse slow to fast</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Background Red" Preset="IntensityRed"/>
|
||||
<Channel Name="Background Green" Preset="IntensityGreen"/>
|
||||
<Channel Name="Background Blue" Preset="IntensityBlue"/>
|
||||
<Channel Name="Background White" Preset="IntensityWhite"/>
|
||||
<Channel Name="Reset">
|
||||
<Group Byte="0">Maintenance</Group>
|
||||
<Capability Min="0" Max="199">No function</Capability>
|
||||
<Capability Min="200" Max="205" Preset="ResetMotors">Reset all (hold ~5 s)</Capability>
|
||||
<Capability Min="206" Max="255">No function</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Function">
|
||||
<Group Byte="0">Maintenance</Group>
|
||||
<Capability Min="0" Max="255">Reserved</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Pattern Select">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="255">Pattern / gobo select</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Pattern Speed">
|
||||
<Group Byte="0">Speed</Group>
|
||||
<Capability Min="0" Max="255">Pattern effect speed</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Pattern Fade">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="255">Pattern fade</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Pattern Red" Preset="IntensityRed"/>
|
||||
<Channel Name="Pattern Green" Preset="IntensityGreen"/>
|
||||
<Channel Name="Pattern Blue" Preset="IntensityBlue"/>
|
||||
<Channel Name="Pattern White" Preset="IntensityWhite"/>
|
||||
<Channel Name="Pattern Dimmer" Preset="IntensityDimmer"/>
|
||||
<Channel Name="Background Dimmer" Preset="IntensityDimmer"/>
|
||||
<Channel Name="Pattern Transition">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="255">Pattern transition</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Pattern Angle">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="255">Pattern angle / translation</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Foreground Strobe">
|
||||
<Group Byte="0">Shutter</Group>
|
||||
<Capability Min="0" Max="3" Preset="ShutterClose">Closed</Capability>
|
||||
<Capability Min="4" Max="103" Preset="StrobeSlowToFast">Sync strobe 1–25 Hz</Capability>
|
||||
<Capability Min="104" Max="107" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="108" Max="207" Preset="StrobeSlowToFast">Pulse strobe 1–25 Hz</Capability>
|
||||
<Capability Min="208" Max="212" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="213" Max="225" Preset="StrobeRandom">Random strobe low</Capability>
|
||||
<Capability Min="226" Max="238" Preset="StrobeRandom">Random strobe mid</Capability>
|
||||
<Capability Min="239" Max="251" Preset="StrobeRandom">Random strobe high</Capability>
|
||||
<Capability Min="252" Max="255" Preset="ShutterOpen">Open</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Background Strobe">
|
||||
<Group Byte="0">Shutter</Group>
|
||||
<Capability Min="0" Max="3" Preset="ShutterClose">Closed</Capability>
|
||||
<Capability Min="4" Max="103" Preset="StrobeSlowToFast">Sync strobe 1–25 Hz</Capability>
|
||||
<Capability Min="104" Max="107" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="108" Max="207" Preset="StrobeSlowToFast">Pulse strobe 1–25 Hz</Capability>
|
||||
<Capability Min="208" Max="212" Preset="ShutterOpen">Open</Capability>
|
||||
<Capability Min="213" Max="225" Preset="StrobeRandom">Random strobe low</Capability>
|
||||
<Capability Min="226" Max="238" Preset="StrobeRandom">Random strobe mid</Capability>
|
||||
<Capability Min="239" Max="251" Preset="StrobeRandom">Random strobe high</Capability>
|
||||
<Capability Min="252" Max="255" Preset="ShutterOpen">Open</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Background Select">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="255">Background pattern select</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Red 1" Preset="IntensityRed"/>
|
||||
<Channel Name="Green 1" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue 1" Preset="IntensityBlue"/>
|
||||
<Channel Name="White 1" Preset="IntensityWhite"/>
|
||||
<Channel Name="Red 2" Preset="IntensityRed"/>
|
||||
<Channel Name="Green 2" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue 2" Preset="IntensityBlue"/>
|
||||
<Channel Name="White 2" Preset="IntensityWhite"/>
|
||||
<Channel Name="Red 3" Preset="IntensityRed"/>
|
||||
<Channel Name="Green 3" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue 3" Preset="IntensityBlue"/>
|
||||
<Channel Name="White 3" Preset="IntensityWhite"/>
|
||||
<Channel Name="Red 4" Preset="IntensityRed"/>
|
||||
<Channel Name="Green 4" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue 4" Preset="IntensityBlue"/>
|
||||
<Channel Name="White 4" Preset="IntensityWhite"/>
|
||||
<Channel Name="Red 5" Preset="IntensityRed"/>
|
||||
<Channel Name="Green 5" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue 5" Preset="IntensityBlue"/>
|
||||
<Channel Name="White 5" Preset="IntensityWhite"/>
|
||||
<Channel Name="Red 6" Preset="IntensityRed"/>
|
||||
<Channel Name="Green 6" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue 6" Preset="IntensityBlue"/>
|
||||
<Channel Name="White 6" Preset="IntensityWhite"/>
|
||||
<Channel Name="Red 7" Preset="IntensityRed"/>
|
||||
<Channel Name="Green 7" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue 7" Preset="IntensityBlue"/>
|
||||
<Channel Name="White 7" Preset="IntensityWhite"/>
|
||||
<Mode Name="43 Channel">
|
||||
<Channel Number="0">Pan</Channel>
|
||||
<Channel Number="1">Pan Fine</Channel>
|
||||
<Channel Number="2">Tilt</Channel>
|
||||
<Channel Number="3">Tilt Fine</Channel>
|
||||
<Channel Number="4">Pan/Tilt Speed</Channel>
|
||||
<Channel Number="5">Lens Rotate</Channel>
|
||||
<Channel Number="6">Zoom</Channel>
|
||||
<Channel Number="7">Focus</Channel>
|
||||
<Channel Number="8">Center Brightness</Channel>
|
||||
<Channel Number="9">Center Strobe</Channel>
|
||||
<Channel Number="10">Red 1</Channel>
|
||||
<Channel Number="11">Green 1</Channel>
|
||||
<Channel Number="12">Blue 1</Channel>
|
||||
<Channel Number="13">White 1</Channel>
|
||||
<Channel Number="14">Red 2</Channel>
|
||||
<Channel Number="15">Green 2</Channel>
|
||||
<Channel Number="16">Blue 2</Channel>
|
||||
<Channel Number="17">White 2</Channel>
|
||||
<Channel Number="18">Red 3</Channel>
|
||||
<Channel Number="19">Green 3</Channel>
|
||||
<Channel Number="20">Blue 3</Channel>
|
||||
<Channel Number="21">White 3</Channel>
|
||||
<Channel Number="22">Red 4</Channel>
|
||||
<Channel Number="23">Green 4</Channel>
|
||||
<Channel Number="24">Blue 4</Channel>
|
||||
<Channel Number="25">White 4</Channel>
|
||||
<Channel Number="26">Red 5</Channel>
|
||||
<Channel Number="27">Green 5</Channel>
|
||||
<Channel Number="28">Blue 5</Channel>
|
||||
<Channel Number="29">White 5</Channel>
|
||||
<Channel Number="30">Red 6</Channel>
|
||||
<Channel Number="31">Green 6</Channel>
|
||||
<Channel Number="32">Blue 6</Channel>
|
||||
<Channel Number="33">White 6</Channel>
|
||||
<Channel Number="34">Red 7</Channel>
|
||||
<Channel Number="35">Green 7</Channel>
|
||||
<Channel Number="36">Blue 7</Channel>
|
||||
<Channel Number="37">White 7</Channel>
|
||||
<Channel Number="38">Colour Temperature</Channel>
|
||||
<Channel Number="39">Colour Macro</Channel>
|
||||
<Channel Number="40">Static Effect</Channel>
|
||||
<Channel Number="41">Dynamic Effect</Channel>
|
||||
<Channel Number="42">Reset</Channel>
|
||||
<Head>
|
||||
<Channel>0</Channel>
|
||||
<Channel>1</Channel>
|
||||
<Channel>2</Channel>
|
||||
<Channel>3</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>10</Channel>
|
||||
<Channel>11</Channel>
|
||||
<Channel>12</Channel>
|
||||
<Channel>13</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>14</Channel>
|
||||
<Channel>15</Channel>
|
||||
<Channel>16</Channel>
|
||||
<Channel>17</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>18</Channel>
|
||||
<Channel>19</Channel>
|
||||
<Channel>20</Channel>
|
||||
<Channel>21</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>22</Channel>
|
||||
<Channel>23</Channel>
|
||||
<Channel>24</Channel>
|
||||
<Channel>25</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>26</Channel>
|
||||
<Channel>27</Channel>
|
||||
<Channel>28</Channel>
|
||||
<Channel>29</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>30</Channel>
|
||||
<Channel>31</Channel>
|
||||
<Channel>32</Channel>
|
||||
<Channel>33</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>34</Channel>
|
||||
<Channel>35</Channel>
|
||||
<Channel>36</Channel>
|
||||
<Channel>37</Channel>
|
||||
</Head>
|
||||
</Mode>
|
||||
<Mode Name="23 Channel">
|
||||
<Channel Number="0">Pan</Channel>
|
||||
<Channel Number="1">Pan Fine</Channel>
|
||||
<Channel Number="2">Tilt</Channel>
|
||||
<Channel Number="3">Tilt Fine</Channel>
|
||||
<Channel Number="4">Pan/Tilt Speed</Channel>
|
||||
<Channel Number="5">Lens Rotate</Channel>
|
||||
<Channel Number="6">Zoom</Channel>
|
||||
<Channel Number="7">Focus</Channel>
|
||||
<Channel Number="8">Center Brightness</Channel>
|
||||
<Channel Number="9">Center Strobe</Channel>
|
||||
<Channel Number="10">Red</Channel>
|
||||
<Channel Number="11">Green</Channel>
|
||||
<Channel Number="12">Blue</Channel>
|
||||
<Channel Number="13">White</Channel>
|
||||
<Channel Number="14">Colour Macro</Channel>
|
||||
<Channel Number="15">Static Effect</Channel>
|
||||
<Channel Number="16">Dynamic Effect</Channel>
|
||||
<Channel Number="17">Dynamic Effect Speed</Channel>
|
||||
<Channel Number="18">Background Red</Channel>
|
||||
<Channel Number="19">Background Green</Channel>
|
||||
<Channel Number="20">Background Blue</Channel>
|
||||
<Channel Number="21">Background White</Channel>
|
||||
<Channel Number="22">Reset</Channel>
|
||||
</Mode>
|
||||
<Mode Name="35 Channel">
|
||||
<Channel Number="0">Red</Channel>
|
||||
<Channel Number="1">Red Fine</Channel>
|
||||
<Channel Number="2">Green</Channel>
|
||||
<Channel Number="3">Green Fine</Channel>
|
||||
<Channel Number="4">Blue</Channel>
|
||||
<Channel Number="5">Blue Fine</Channel>
|
||||
<Channel Number="6">White</Channel>
|
||||
<Channel Number="7">White Fine</Channel>
|
||||
<Channel Number="8">Colour Temperature</Channel>
|
||||
<Channel Number="9">Colour Macro</Channel>
|
||||
<Channel Number="10">Strobe 35</Channel>
|
||||
<Channel Number="11">Dimmer</Channel>
|
||||
<Channel Number="12">Dimmer Fine</Channel>
|
||||
<Channel Number="13">Pan</Channel>
|
||||
<Channel Number="14">Pan Fine</Channel>
|
||||
<Channel Number="15">Tilt</Channel>
|
||||
<Channel Number="16">Tilt Fine</Channel>
|
||||
<Channel Number="17">Function</Channel>
|
||||
<Channel Number="18">Reset</Channel>
|
||||
<Channel Number="19">Zoom</Channel>
|
||||
<Channel Number="20">Lens Rotate 35</Channel>
|
||||
<Channel Number="21">Pattern Select</Channel>
|
||||
<Channel Number="22">Pattern Speed</Channel>
|
||||
<Channel Number="23">Pattern Fade</Channel>
|
||||
<Channel Number="24">Pattern Red</Channel>
|
||||
<Channel Number="25">Pattern Green</Channel>
|
||||
<Channel Number="26">Pattern Blue</Channel>
|
||||
<Channel Number="27">Pattern White</Channel>
|
||||
<Channel Number="28">Pattern Dimmer</Channel>
|
||||
<Channel Number="29">Background Dimmer</Channel>
|
||||
<Channel Number="30">Pattern Transition</Channel>
|
||||
<Channel Number="31">Pattern Angle</Channel>
|
||||
<Channel Number="32">Foreground Strobe</Channel>
|
||||
<Channel Number="33">Background Strobe</Channel>
|
||||
<Channel Number="34">Background Select</Channel>
|
||||
</Mode>
|
||||
<Mode Name="51 Channel">
|
||||
<Channel Number="0">Pan</Channel>
|
||||
<Channel Number="1">Pan Fine</Channel>
|
||||
<Channel Number="2">Tilt</Channel>
|
||||
<Channel Number="3">Tilt Fine</Channel>
|
||||
<Channel Number="4">Pan/Tilt Speed</Channel>
|
||||
<Channel Number="5">Lens Rotate</Channel>
|
||||
<Channel Number="6">Zoom</Channel>
|
||||
<Channel Number="7">Focus</Channel>
|
||||
<Channel Number="8">Center Brightness</Channel>
|
||||
<Channel Number="9">Center Strobe</Channel>
|
||||
<Channel Number="10">Red</Channel>
|
||||
<Channel Number="11">Green</Channel>
|
||||
<Channel Number="12">Blue</Channel>
|
||||
<Channel Number="13">White</Channel>
|
||||
<Channel Number="14">Colour Macro</Channel>
|
||||
<Channel Number="15">Static Effect</Channel>
|
||||
<Channel Number="16">Dynamic Effect</Channel>
|
||||
<Channel Number="17">Dynamic Effect Speed</Channel>
|
||||
<Channel Number="18">Background Red</Channel>
|
||||
<Channel Number="19">Background Green</Channel>
|
||||
<Channel Number="20">Background Blue</Channel>
|
||||
<Channel Number="21">Background White</Channel>
|
||||
<Channel Number="22">Reset</Channel>
|
||||
<Channel Number="23">Red 1</Channel>
|
||||
<Channel Number="24">Green 1</Channel>
|
||||
<Channel Number="25">Blue 1</Channel>
|
||||
<Channel Number="26">White 1</Channel>
|
||||
<Channel Number="27">Red 2</Channel>
|
||||
<Channel Number="28">Green 2</Channel>
|
||||
<Channel Number="29">Blue 2</Channel>
|
||||
<Channel Number="30">White 2</Channel>
|
||||
<Channel Number="31">Red 3</Channel>
|
||||
<Channel Number="32">Green 3</Channel>
|
||||
<Channel Number="33">Blue 3</Channel>
|
||||
<Channel Number="34">White 3</Channel>
|
||||
<Channel Number="35">Red 4</Channel>
|
||||
<Channel Number="36">Green 4</Channel>
|
||||
<Channel Number="37">Blue 4</Channel>
|
||||
<Channel Number="38">White 4</Channel>
|
||||
<Channel Number="39">Red 5</Channel>
|
||||
<Channel Number="40">Green 5</Channel>
|
||||
<Channel Number="41">Blue 5</Channel>
|
||||
<Channel Number="42">White 5</Channel>
|
||||
<Channel Number="43">Red 6</Channel>
|
||||
<Channel Number="44">Green 6</Channel>
|
||||
<Channel Number="45">Blue 6</Channel>
|
||||
<Channel Number="46">White 6</Channel>
|
||||
<Channel Number="47">Red 7</Channel>
|
||||
<Channel Number="48">Green 7</Channel>
|
||||
<Channel Number="49">Blue 7</Channel>
|
||||
<Channel Number="50">White 7</Channel>
|
||||
<Head>
|
||||
<Channel>23</Channel>
|
||||
<Channel>24</Channel>
|
||||
<Channel>25</Channel>
|
||||
<Channel>26</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>27</Channel>
|
||||
<Channel>28</Channel>
|
||||
<Channel>29</Channel>
|
||||
<Channel>30</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>31</Channel>
|
||||
<Channel>32</Channel>
|
||||
<Channel>33</Channel>
|
||||
<Channel>34</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>35</Channel>
|
||||
<Channel>36</Channel>
|
||||
<Channel>37</Channel>
|
||||
<Channel>38</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>39</Channel>
|
||||
<Channel>40</Channel>
|
||||
<Channel>41</Channel>
|
||||
<Channel>42</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>43</Channel>
|
||||
<Channel>44</Channel>
|
||||
<Channel>45</Channel>
|
||||
<Channel>46</Channel>
|
||||
</Head>
|
||||
<Head>
|
||||
<Channel>47</Channel>
|
||||
<Channel>48</Channel>
|
||||
<Channel>49</Channel>
|
||||
<Channel>50</Channel>
|
||||
</Head>
|
||||
</Mode>
|
||||
<Physical>
|
||||
<Bulb Type="LED" Lumens="0" ColourTemperature="0"/>
|
||||
<Dimensions Weight="5.6" Width="242" Height="313" Depth="184"/>
|
||||
<Lens Name="Other" DegreesMin="5" DegreesMax="45"/>
|
||||
<Focus Type="Head" PanMax="540" TiltMax="270"/>
|
||||
<Layout Width="7" Height="1"/>
|
||||
<Technical PowerConsumption="300" DmxConnector="3-pin"/>
|
||||
</Physical>
|
||||
</FixtureDefinition>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE FixtureDefinition>
|
||||
<FixtureDefinition xmlns="http://www.qlcplus.org/FixtureDefinition">
|
||||
<Creator>
|
||||
<Name>Q Light Controller Plus</Name>
|
||||
<Version>4.12.7</Version>
|
||||
<Author>Jimmy</Author>
|
||||
</Creator>
|
||||
<Manufacturer>beamZ</Manufacturer>
|
||||
<Model>BCC145</Model>
|
||||
<Type>Color Changer</Type>
|
||||
<Channel Name="Dimmer" Default="255" Preset="IntensityMasterDimmer"/>
|
||||
<Channel Name="Red" Preset="IntensityRed"/>
|
||||
<Channel Name="Green" Preset="IntensityGreen"/>
|
||||
<Channel Name="Blue" Preset="IntensityBlue"/>
|
||||
<Channel Name="White" Preset="IntensityWhite"/>
|
||||
<Channel Name="Strobe">
|
||||
<Group Byte="0">Shutter</Group>
|
||||
<Capability Min="0" Max="7" Preset="ShutterOpen">No function</Capability>
|
||||
<Capability Min="8" Max="255" Preset="StrobeSlowToFast">Strobe slow to fast</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Macro">
|
||||
<Group Byte="0">Effect</Group>
|
||||
<Capability Min="0" Max="50">RGBW mix</Capability>
|
||||
<Capability Min="51" Max="100">Fixed colour</Capability>
|
||||
<Capability Min="101" Max="150">Colour jump</Capability>
|
||||
<Capability Min="151" Max="200">Colour pulse</Capability>
|
||||
<Capability Min="201" Max="250">Colour gradient</Capability>
|
||||
<Capability Min="251" Max="253">Sound 1</Capability>
|
||||
<Capability Min="254" Max="255">Sound 2</Capability>
|
||||
</Channel>
|
||||
<Channel Name="Speed">
|
||||
<Group Byte="0">Speed</Group>
|
||||
<Capability Min="0" Max="255">Macro speed from slow to fast</Capability>
|
||||
</Channel>
|
||||
<Mode Name="4 Channel">
|
||||
<Channel Number="0">Red</Channel>
|
||||
<Channel Number="1">Green</Channel>
|
||||
<Channel Number="2">Blue</Channel>
|
||||
<Channel Number="3">White</Channel>
|
||||
</Mode>
|
||||
<Mode Name="8 Channel">
|
||||
<Channel Number="0">Dimmer</Channel>
|
||||
<Channel Number="1">Strobe</Channel>
|
||||
<Channel Number="2">Red</Channel>
|
||||
<Channel Number="3">Green</Channel>
|
||||
<Channel Number="4">Blue</Channel>
|
||||
<Channel Number="5">White</Channel>
|
||||
<Channel Number="6">Macro</Channel>
|
||||
<Channel Number="7">Speed</Channel>
|
||||
</Mode>
|
||||
<Physical>
|
||||
<Bulb Type="LED" Lumens="0" ColourTemperature="0"/>
|
||||
<Dimensions Weight="1.15" Width="232" Height="225" Depth="110"/>
|
||||
<Lens Name="Other" DegreesMin="25" DegreesMax="25"/>
|
||||
<Focus Type="Fixed" PanMax="0" TiltMax="0"/>
|
||||
<Technical PowerConsumption="56" DmxConnector="3-pin"/>
|
||||
</Physical>
|
||||
</FixtureDefinition>
|
||||
@@ -0,0 +1,172 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE InputProfile>
|
||||
<InputProfile xmlns="http://www.qlcplus.org/InputProfile">
|
||||
<Creator>
|
||||
<Name>Q Light Controller Plus</Name>
|
||||
<Version>4.12.7</Version>
|
||||
<Author>tech</Author>
|
||||
</Creator>
|
||||
<Manufacturer>M-VAVE</Manufacturer>
|
||||
<Model>SMC-PAD</Model>
|
||||
<Type>MIDI</Type>
|
||||
<Channel Number="30">
|
||||
<Name>Knob 1</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="31">
|
||||
<Name>Knob 2</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="32">
|
||||
<Name>Knob 3</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="33">
|
||||
<Name>Knob 4</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="34">
|
||||
<Name>Knob 5</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="35">
|
||||
<Name>Knob 6</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="36">
|
||||
<Name>Knob 7</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="37">
|
||||
<Name>Knob 8</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="38">
|
||||
<Name>Knob 9</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="39">
|
||||
<Name>Knob 10</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="40">
|
||||
<Name>Knob 11</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="41">
|
||||
<Name>Knob 12</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="42">
|
||||
<Name>Knob 13</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="43">
|
||||
<Name>Knob 14</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="44">
|
||||
<Name>Knob 15</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="45">
|
||||
<Name>Knob 16</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="50">
|
||||
<Name>Pan FL</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="51">
|
||||
<Name>Pan FR</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="52">
|
||||
<Name>Pan BL</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="53">
|
||||
<Name>Pan BR</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="54">
|
||||
<Name>Tilt FL</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="55">
|
||||
<Name>Tilt FR</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="56">
|
||||
<Name>Tilt BL</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="57">
|
||||
<Name>Tilt BR</Name>
|
||||
<Type>Knob</Type>
|
||||
</Channel>
|
||||
<Channel Number="164">
|
||||
<Name>Pad 1</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="165">
|
||||
<Name>Pad 2</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="166">
|
||||
<Name>Pad 3</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="167">
|
||||
<Name>Pad 4</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="168">
|
||||
<Name>Pad 5</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="169">
|
||||
<Name>Pad 6</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="170">
|
||||
<Name>Pad 7</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="171">
|
||||
<Name>Pad 8</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="172">
|
||||
<Name>Pad 9</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="173">
|
||||
<Name>Pad 10</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="174">
|
||||
<Name>Pad 11</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="175">
|
||||
<Name>Pad 12</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="176">
|
||||
<Name>Pad 13</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="177">
|
||||
<Name>Pad 14</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="178">
|
||||
<Name>Pad 15</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
<Channel Number="179">
|
||||
<Name>Pad 16</Name>
|
||||
<Type>Button</Type>
|
||||
</Channel>
|
||||
</InputProfile>
|
||||
@@ -0,0 +1 @@
|
||||
"""Set SMC-PAD colours and preview them on the open mic fixtures."""
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Reload the pad colour page when its Python changes.
|
||||
|
||||
python3 -m pad_color
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
PKG = Path(__file__).resolve().parent
|
||||
ROOT = PKG.parent
|
||||
|
||||
|
||||
def stamp(root: Path) -> dict[str, int]:
|
||||
found: dict[str, int] = {}
|
||||
for path in root.rglob("*.py"):
|
||||
if "__pycache__" in path.parts or not path.is_file():
|
||||
continue
|
||||
found[str(path)] = path.stat().st_mtime_ns
|
||||
return found
|
||||
|
||||
|
||||
def stop_child(proc: subprocess.Popen) -> None:
|
||||
if proc.poll() is not None:
|
||||
return
|
||||
proc.send_signal(signal.SIGINT)
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
os.chdir(ROOT)
|
||||
cmd = [sys.executable, "-m", "pad_color.server", *sys.argv[1:]]
|
||||
while True:
|
||||
py = stamp(PKG)
|
||||
proc = subprocess.Popen(cmd)
|
||||
try:
|
||||
while proc.poll() is None:
|
||||
time.sleep(0.25)
|
||||
if stamp(PKG) != py:
|
||||
print("reload backend", flush=True)
|
||||
stop_child(proc)
|
||||
break
|
||||
else:
|
||||
return proc.returncode or 0
|
||||
except KeyboardInterrupt:
|
||||
print("\nstopped", flush=True)
|
||||
stop_child(proc)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,338 @@
|
||||
"""Pad picks, knob colours, open-mic preview, and saving the pad light."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPTS = ROOT / "scripts"
|
||||
if str(SCRIPTS) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
from cabaret_movers import ( # noqa: E402
|
||||
ARTNET_PORT,
|
||||
DEFAULT_NODE,
|
||||
build_artdmx,
|
||||
discover_artnet_node,
|
||||
)
|
||||
from pattern_pad.engine import list_smc_ports, parse_midi_line # noqa: E402
|
||||
|
||||
PAD_COUNT = 16
|
||||
NOTE_PAD1 = 36
|
||||
# Knobs 1–4, factory preset: CC 30 red, 31 green, 32 blue, 33 white.
|
||||
KNOB_PART = {30: 0, 31: 1, 32: 2, 33: 3}
|
||||
PRESS_GAP = 0.35
|
||||
|
||||
# QLC addresses are 0-based. Universe 0 holds the cans and movers.
|
||||
# Universe 2 holds the two floor cans.
|
||||
CANS = (87, 95, 103, 111, 119, 127, 135, 143, 151, 159, 167, 175, 183, 191, 199)
|
||||
FLOOR = (207, 215)
|
||||
# Front right, front left, back left, back right. Pan and tilt stay put.
|
||||
MOVERS = {
|
||||
0: (80, 180),
|
||||
44: (12, 190),
|
||||
257: (12, 190),
|
||||
300: (80, 180),
|
||||
}
|
||||
|
||||
|
||||
def midi_level(value: int) -> int:
|
||||
"""Absolute knob 0–127 onto a DMX channel."""
|
||||
return max(0, min(127, value)) * 255 // 127
|
||||
|
||||
|
||||
def pad_from_note(note: int) -> int | None:
|
||||
if NOTE_PAD1 <= note < NOTE_PAD1 + PAD_COUNT:
|
||||
return note - NOTE_PAD1 + 1
|
||||
return None
|
||||
|
||||
|
||||
def paint_openmic(frames: dict[int, bytearray], color: tuple[int, int, int, int]) -> None:
|
||||
"""Write one RGBW colour onto every open-mic can and mover pixel."""
|
||||
red, green, blue, white = color
|
||||
room = frames[0]
|
||||
floor = frames[2]
|
||||
for addr in CANS:
|
||||
_can(room, addr, red, green, blue, white)
|
||||
for addr in FLOOR:
|
||||
_can(floor, addr, red, green, blue, white)
|
||||
for addr, (pan, tilt) in MOVERS.items():
|
||||
room[addr] = pan
|
||||
room[addr + 2] = tilt
|
||||
room[addr + 7] = 0
|
||||
room[addr + 8] = 255
|
||||
room[addr + 9] = 0
|
||||
for pixel in range(7):
|
||||
base = addr + 10 + pixel * 4
|
||||
room[base] = red
|
||||
room[base + 1] = green
|
||||
room[base + 2] = blue
|
||||
room[base + 3] = white
|
||||
|
||||
|
||||
def _can(frame: bytearray, addr: int, red: int, green: int, blue: int, white: int) -> None:
|
||||
frame[addr] = 255
|
||||
frame[addr + 1] = 0
|
||||
frame[addr + 2] = red
|
||||
frame[addr + 3] = green
|
||||
frame[addr + 4] = blue
|
||||
frame[addr + 5] = white
|
||||
frame[addr + 6] = 0
|
||||
|
||||
|
||||
class Preview:
|
||||
"""Art-Net for universe 0 and universe 2. Sends only while a colour is being chosen."""
|
||||
|
||||
def __init__(self, dest: str):
|
||||
import socket
|
||||
|
||||
self.dest = dest
|
||||
self.frames = {0: bytearray(512), 2: bytearray(512)}
|
||||
self.active = False
|
||||
self._running = True
|
||||
self._lock = threading.Lock()
|
||||
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
self._sequence = 1
|
||||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def show(self, color: tuple[int, int, int, int]) -> None:
|
||||
with self._lock:
|
||||
for frame in self.frames.values():
|
||||
frame[:] = b"\x00" * 512
|
||||
paint_openmic(self.frames, color)
|
||||
self.active = True
|
||||
|
||||
def hold(self) -> None:
|
||||
with self._lock:
|
||||
self.active = False
|
||||
|
||||
def _loop(self) -> None:
|
||||
while self._running:
|
||||
with self._lock:
|
||||
active = self.active
|
||||
packets = [
|
||||
(universe, build_artdmx(bytes(frame), universe, self._sequence))
|
||||
for universe, frame in self.frames.items()
|
||||
]
|
||||
if active:
|
||||
self._sequence = 1 if self._sequence >= 255 else self._sequence + 1
|
||||
if active:
|
||||
for _universe, packet in packets:
|
||||
try:
|
||||
self._sock.sendto(packet, (self.dest, ARTNET_PORT))
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.04)
|
||||
|
||||
def close(self) -> None:
|
||||
self.hold()
|
||||
self._running = False
|
||||
self._thread.join(timeout=1.0)
|
||||
self._sock.close()
|
||||
|
||||
|
||||
class Desk:
|
||||
"""Which pad is being coloured, and the four knob values."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.colors = [(0xF0, 0x00, 0xF0, 0) for _ in range(PAD_COUNT)]
|
||||
self.selected: int | None = None
|
||||
self.editing = False
|
||||
self.status = "Hit a pad, then turn knobs 1–4."
|
||||
self._last = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def press(self, pad: int, now: float | None = None) -> str:
|
||||
if not 1 <= pad <= PAD_COUNT:
|
||||
raise ValueError("pad must be 1 to 16")
|
||||
moment = time.monotonic() if now is None else now
|
||||
with self._lock:
|
||||
if moment - self._last < PRESS_GAP:
|
||||
return "ignore"
|
||||
self._last = moment
|
||||
if self.editing and self.selected == pad:
|
||||
self.editing = False
|
||||
self.status = f"Pad {pad} saved."
|
||||
return "save"
|
||||
self.selected = pad
|
||||
self.editing = True
|
||||
red, green, blue, white = self.colors[pad - 1]
|
||||
self.status = f"Pad {pad} {red} {green} {blue} {white}. Hit it again to save."
|
||||
return "edit"
|
||||
|
||||
def set_part(self, part: int, level: int) -> None:
|
||||
if part not in (0, 1, 2, 3):
|
||||
raise ValueError("part must be 0 to 3")
|
||||
level = max(0, min(255, level))
|
||||
with self._lock:
|
||||
if not self.editing or self.selected is None:
|
||||
return
|
||||
color = list(self.colors[self.selected - 1])
|
||||
color[part] = level
|
||||
self.colors[self.selected - 1] = (color[0], color[1], color[2], color[3])
|
||||
red, green, blue, white = self.colors[self.selected - 1]
|
||||
self.status = (
|
||||
f"Pad {self.selected} {red} {green} {blue} {white}. Hit it again to save."
|
||||
)
|
||||
|
||||
def color(self) -> tuple[int, int, int, int] | None:
|
||||
with self._lock:
|
||||
if not self.editing or self.selected is None:
|
||||
return None
|
||||
return self.colors[self.selected - 1]
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
with self._lock:
|
||||
return {
|
||||
"selected": self.selected,
|
||||
"editing": self.editing,
|
||||
"status": self.status,
|
||||
"pads": [
|
||||
{
|
||||
"pad": index + 1,
|
||||
"r": color[0],
|
||||
"g": color[1],
|
||||
"b": color[2],
|
||||
"w": color[3],
|
||||
}
|
||||
for index, color in enumerate(self.colors)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class Studio:
|
||||
def __init__(self, desk: Desk, preview: Preview, midi_port: str | None, midi_label: str):
|
||||
self.desk = desk
|
||||
self.preview = preview
|
||||
self.artnet = preview.dest
|
||||
self.midi_label = midi_label
|
||||
self._midi_port = midi_port
|
||||
self._running = True
|
||||
self._midi: subprocess.Popen[str] | None = None
|
||||
self._threads: list[threading.Thread] = []
|
||||
self._link = None
|
||||
self._slot = 0
|
||||
self._bank = 3
|
||||
|
||||
def state(self) -> dict:
|
||||
data = self.desk.snapshot()
|
||||
data["artnet"] = self.artnet
|
||||
data["midi"] = self.midi_label
|
||||
return data
|
||||
|
||||
def press(self, pad: int) -> None:
|
||||
action = self.desk.press(pad)
|
||||
if action == "edit":
|
||||
color = self.desk.color()
|
||||
if color is not None:
|
||||
self.preview.show(color)
|
||||
elif action == "save":
|
||||
self._save_pad(pad)
|
||||
self.preview.hold()
|
||||
|
||||
def set_part(self, part: int, level: int) -> None:
|
||||
self.desk.set_part(part, level)
|
||||
color = self.desk.color()
|
||||
if color is not None:
|
||||
self.preview.show(color)
|
||||
|
||||
def _save_pad(self, pad: int) -> None:
|
||||
color = self.desk.colors[pad - 1]
|
||||
if self._link is None:
|
||||
self.desk.status = f"Pad {pad} colour is on the fixtures. The pad light was not reached."
|
||||
return
|
||||
from smc_pad import PAD_RECORD_SIZE, PAD_RGB_OFFSET, bank_address
|
||||
|
||||
address = bank_address(self._slot, self._bank) + (pad - 1) * PAD_RECORD_SIZE + PAD_RGB_OFFSET
|
||||
try:
|
||||
self._link.write(address, bytes(color[:3]))
|
||||
except Exception as exc:
|
||||
self.desk.status = f"Pad {pad} did not save: {exc}"
|
||||
return
|
||||
self.desk.status = f"Pad {pad} saved."
|
||||
|
||||
def load_device(self) -> None:
|
||||
from smc_pad import PadError, PadLink, rgb_at, showing
|
||||
|
||||
try:
|
||||
link = PadLink()
|
||||
link.open()
|
||||
slot, bank, image = showing(link, None, None)
|
||||
except (PadError, OSError, Exception) as exc:
|
||||
self.desk.status = f"Pad colours stayed on the page. {exc}"
|
||||
return
|
||||
self._link = link
|
||||
self._slot = slot
|
||||
self._bank = bank
|
||||
for pad in range(1, PAD_COUNT + 1):
|
||||
red, green, blue = rgb_at(image, pad)
|
||||
white = self.desk.colors[pad - 1][3]
|
||||
self.desk.colors[pad - 1] = (red, green, blue, white)
|
||||
self.desk.status = f"Preset {slot + 1}, bank {bank}. Hit a pad, then turn knobs 1–4."
|
||||
|
||||
def handle_midi(self, kind: str, number: int, value: int) -> None:
|
||||
if kind == "note":
|
||||
pad = pad_from_note(number)
|
||||
if pad is None:
|
||||
return
|
||||
self.press(pad)
|
||||
return
|
||||
part = KNOB_PART.get(number)
|
||||
if part is None:
|
||||
return
|
||||
self.set_part(part, midi_level(value))
|
||||
|
||||
def midi_loop(self, port: str) -> None:
|
||||
self._midi = subprocess.Popen(
|
||||
["aseqdump", "-p", port],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
assert self._midi.stdout is not None
|
||||
for line in self._midi.stdout:
|
||||
if not self._running:
|
||||
break
|
||||
parsed = parse_midi_line(line)
|
||||
if parsed:
|
||||
self.handle_midi(*parsed)
|
||||
|
||||
def start(self) -> None:
|
||||
self.load_device()
|
||||
if self._midi_port:
|
||||
thread = threading.Thread(target=self.midi_loop, args=(self._midi_port,), daemon=True)
|
||||
self._threads.append(thread)
|
||||
thread.start()
|
||||
|
||||
def close(self) -> None:
|
||||
self._running = False
|
||||
self.preview.close()
|
||||
midi = self._midi
|
||||
if midi is not None and midi.poll() is None:
|
||||
midi.send_signal(signal.SIGINT)
|
||||
try:
|
||||
midi.wait(timeout=1.0)
|
||||
except subprocess.TimeoutExpired:
|
||||
midi.kill()
|
||||
if self._link is not None:
|
||||
self._link.close()
|
||||
|
||||
|
||||
def open_studio(ip: str | None, midi: str | None) -> Studio:
|
||||
ports = list_smc_ports()
|
||||
if midi:
|
||||
midi_port, midi_label = midi, midi
|
||||
elif ports:
|
||||
midi_port, midi_label = ports[0]
|
||||
else:
|
||||
midi_port, midi_label = None, "SMC-PAD not found"
|
||||
node = ip or discover_artnet_node(DEFAULT_NODE)
|
||||
return Studio(Desk(), Preview(node), midi_port, midi_label)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""HTTP server for the pad colour page. Run via `python -m pad_color`."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from pad_color.engine import open_studio
|
||||
|
||||
STATIC = Path(__file__).resolve().parent / "static"
|
||||
BOOT = str(time.time_ns())
|
||||
HOST = "127.0.0.1"
|
||||
PORT = 8767
|
||||
|
||||
MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
}
|
||||
|
||||
|
||||
def static_stamp(directory: Path) -> str:
|
||||
latest = 0
|
||||
if directory.is_dir():
|
||||
for path in directory.rglob("*"):
|
||||
if path.is_file():
|
||||
latest = max(latest, path.stat().st_mtime_ns)
|
||||
return str(latest)
|
||||
|
||||
|
||||
def make_handler(studio):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt: str, *args) -> None:
|
||||
return
|
||||
|
||||
def _send(self, code: int, body: bytes, content_type: str) -> None:
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _json(self, code: int, payload: dict) -> None:
|
||||
self._send(code, json.dumps(payload).encode(), "application/json")
|
||||
|
||||
def _read_json(self) -> dict:
|
||||
length = int(self.headers.get("Content-Length", "0") or 0)
|
||||
if length <= 0:
|
||||
return {}
|
||||
data = json.loads(self.rfile.read(length).decode() or "{}")
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Expected a JSON object")
|
||||
return data
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
path = self.path.split("?", 1)[0]
|
||||
if path == "/api/state":
|
||||
self._json(200, studio.state())
|
||||
return
|
||||
if path == "/api/dev":
|
||||
self._json(200, {"boot": BOOT, "static": static_stamp(STATIC)})
|
||||
return
|
||||
if path == "/":
|
||||
path = "/index.html"
|
||||
file_path = (STATIC / path.lstrip("/")).resolve()
|
||||
if not str(file_path).startswith(str(STATIC)) or not file_path.is_file():
|
||||
self._send(404, b"not found", "text/plain; charset=utf-8")
|
||||
return
|
||||
self._send(200, file_path.read_bytes(), MIME.get(file_path.suffix, "application/octet-stream"))
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
path = self.path.split("?", 1)[0]
|
||||
try:
|
||||
body = self._read_json()
|
||||
if path == "/api/pad":
|
||||
studio.press(int(body["pad"]))
|
||||
elif path == "/api/part":
|
||||
studio.set_part(int(body["part"]), int(body["level"]))
|
||||
else:
|
||||
self._json(404, {"error": "Unknown request"})
|
||||
return
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
self._json(400, {"error": str(exc) or "Bad request"})
|
||||
return
|
||||
self._json(200, studio.state())
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Pad colour page")
|
||||
parser.add_argument("--host", default=HOST)
|
||||
parser.add_argument("--port", type=int, default=PORT)
|
||||
parser.add_argument("--ip", default=None, help="Art-Net destination")
|
||||
parser.add_argument("--midi", default=None, help="ALSA port, for example 128:0")
|
||||
args = parser.parse_args()
|
||||
|
||||
studio = open_studio(args.ip, args.midi)
|
||||
studio.start()
|
||||
ThreadingHTTPServer.allow_reuse_address = True
|
||||
httpd = ThreadingHTTPServer((args.host, args.port), make_handler(studio))
|
||||
|
||||
def stop(_signum, _frame) -> None:
|
||||
threading.Thread(target=httpd.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
print(f"http://{args.host}:{args.port}", flush=True)
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
finally:
|
||||
httpd.server_close()
|
||||
studio.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,34 @@
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font: 16px/1.4 system-ui, sans-serif;
|
||||
background: #12141a;
|
||||
color: #eee;
|
||||
}
|
||||
main { max-width: 36rem; margin: 0 auto; padding: 1.25rem 1.25rem 3rem; }
|
||||
h1 { font-size: 1.35rem; font-weight: 650; margin: 0 0 0.2rem; }
|
||||
.meta, .hint, .status { color: #8e98a8; font-size: 0.85rem; }
|
||||
.meta { margin: 0 0 1rem; word-break: break-all; }
|
||||
.hint { margin: 0.75rem 0 1rem; }
|
||||
.pads {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.pads button {
|
||||
aspect-ratio: 1;
|
||||
border: 1px solid #3a4050;
|
||||
border-radius: 12px;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pads button.selected {
|
||||
outline: 3px solid #fff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.slider { display: block; margin: 0.75rem 0; }
|
||||
.slider output { float: right; font-variant-numeric: tabular-nums; }
|
||||
input[type="range"] { width: 100%; margin-top: 0.25rem; }
|
||||
.status { min-height: 1.2em; }
|
||||
@@ -0,0 +1,110 @@
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const pads = $("pads");
|
||||
const sliders = [...document.querySelectorAll("input[type=range]")];
|
||||
const ROWS = [[13, 14, 15, 16], [9, 10, 11, 12], [5, 6, 7, 8], [1, 2, 3, 4]];
|
||||
let dragging = false;
|
||||
let seenDev = null;
|
||||
let devDown = false;
|
||||
|
||||
for (const row of ROWS) {
|
||||
for (const pad of row) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.dataset.pad = String(pad);
|
||||
button.textContent = String(pad);
|
||||
pads.appendChild(button);
|
||||
}
|
||||
}
|
||||
|
||||
function hex(part) {
|
||||
return part.toString(16).padStart(2, "0");
|
||||
}
|
||||
|
||||
function ink(r, g, b) {
|
||||
return r * 0.3 + g * 0.6 + b * 0.1 > 140 ? "#1a1206" : "#fff";
|
||||
}
|
||||
|
||||
function paint(data) {
|
||||
$("meta").textContent = `${data.artnet} · ${data.midi}`;
|
||||
$("status").textContent = data.status;
|
||||
const byPad = new Map(data.pads.map((item) => [item.pad, item]));
|
||||
for (const button of pads.querySelectorAll("button")) {
|
||||
const item = byPad.get(Number(button.dataset.pad));
|
||||
button.style.background = `#${hex(item.r)}${hex(item.g)}${hex(item.b)}`;
|
||||
button.style.color = ink(item.r, item.g, item.b);
|
||||
button.classList.toggle("selected", data.editing && item.pad === data.selected);
|
||||
}
|
||||
if (!dragging && data.selected) {
|
||||
const item = byPad.get(data.selected);
|
||||
sliders[0].value = item.r;
|
||||
sliders[1].value = item.g;
|
||||
sliders[2].value = item.b;
|
||||
sliders[3].value = item.w;
|
||||
}
|
||||
for (const slider of sliders) {
|
||||
slider.parentElement.querySelector("output").textContent = slider.value;
|
||||
}
|
||||
}
|
||||
|
||||
async function post(url, body) {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "request failed");
|
||||
paint(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
pads.addEventListener("click", (ev) => {
|
||||
const button = ev.target.closest("button");
|
||||
if (!button) return;
|
||||
post("/api/pad", {pad: Number(button.dataset.pad)}).catch((err) => {
|
||||
$("status").textContent = err.message;
|
||||
});
|
||||
});
|
||||
|
||||
for (const slider of sliders) {
|
||||
slider.addEventListener("pointerdown", () => {
|
||||
dragging = true;
|
||||
});
|
||||
slider.addEventListener("input", () => {
|
||||
slider.parentElement.querySelector("output").textContent = slider.value;
|
||||
post("/api/part", {part: Number(slider.dataset.part), level: Number(slider.value)}).catch((err) => {
|
||||
$("status").textContent = err.message;
|
||||
});
|
||||
});
|
||||
}
|
||||
window.addEventListener("pointerup", () => {
|
||||
dragging = false;
|
||||
});
|
||||
|
||||
async function poll() {
|
||||
try {
|
||||
const data = await fetch("/api/state", {cache: "no-store"}).then((res) => res.json());
|
||||
paint(data);
|
||||
} catch {
|
||||
$("meta").textContent = "Reconnecting…";
|
||||
}
|
||||
setTimeout(poll, 200);
|
||||
}
|
||||
|
||||
async function watchDev() {
|
||||
try {
|
||||
const dev = await fetch("/api/dev", {cache: "no-store"}).then((res) => res.json());
|
||||
if (devDown || (seenDev && (dev.boot !== seenDev.boot || dev.static !== seenDev.static))) {
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
seenDev = dev;
|
||||
devDown = false;
|
||||
} catch {
|
||||
devDown = seenDev !== null;
|
||||
}
|
||||
setTimeout(watchDev, 400);
|
||||
}
|
||||
|
||||
poll();
|
||||
watchDev();
|
||||
@@ -0,0 +1,31 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Pad colours</title>
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Pad colours</h1>
|
||||
<p class="meta" id="meta">Connecting…</p>
|
||||
<div class="pads" id="pads"></div>
|
||||
<p class="hint">Pad 1 is bottom-left. Hit a pad, turn knobs 1–4 for red, green, blue, and white. The open mic fixtures follow. Hit the same pad again to save. The pad light keeps red, green, and blue until the pad is switched off.</p>
|
||||
<label class="slider">Red <output id="r-out"></output>
|
||||
<input id="r" data-part="0" type="range" min="0" max="255" value="0">
|
||||
</label>
|
||||
<label class="slider">Green <output id="g-out"></output>
|
||||
<input id="g" data-part="1" type="range" min="0" max="255" value="0">
|
||||
</label>
|
||||
<label class="slider">Blue <output id="b-out"></output>
|
||||
<input id="b" data-part="2" type="range" min="0" max="255" value="0">
|
||||
</label>
|
||||
<label class="slider">White <output id="w-out"></output>
|
||||
<input id="w" data-part="3" type="range" min="0" max="255" value="0">
|
||||
</label>
|
||||
<p class="status" id="status"></p>
|
||||
</main>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
"""Pad Controller: the SMC-PAD preset editor and MIDI intercept."""
|
||||
@@ -0,0 +1,33 @@
|
||||
"""python3 -m padcontroller [--port 8770]"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import threading
|
||||
import webbrowser
|
||||
|
||||
from padcontroller.server import make_server
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="padcontroller", description="Pad Controller: SMC-PAD preset editor")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=8770)
|
||||
parser.add_argument("--no-browser", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
server = make_server(args.host, args.port)
|
||||
url = f"http://{args.host}:{args.port}/"
|
||||
print(f"Pad Controller → {url} 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.server_close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,340 @@
|
||||
"""Read and save the SMC-PAD preset over the Private USB port.
|
||||
|
||||
Writes go to the preset address, as MidiSuite sends them; the lamps follow
|
||||
straight away. Save writes the bytes that differ, checks each read-back,
|
||||
then sends the empty write MidiSuite's Save button sends, which keeps the
|
||||
preset after a power cycle. It never sends erase.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from padcontroller.preset import GLOBAL_LEN, IMAGE_LEN, changed_ranges
|
||||
from padcontroller.sysex import (
|
||||
CMD_READ,
|
||||
MEM_GLOBAL,
|
||||
MEM_PRESET,
|
||||
RAM,
|
||||
payload_data,
|
||||
read_request,
|
||||
save_request,
|
||||
write_request,
|
||||
)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
READ_CHUNK = 512
|
||||
WRITE_CHUNK = 64
|
||||
|
||||
|
||||
class PadError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def load_rtmidi():
|
||||
for path in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
|
||||
if path not in sys.path:
|
||||
sys.path.insert(0, path)
|
||||
import rtmidi
|
||||
|
||||
return rtmidi
|
||||
|
||||
|
||||
def private_port(names: list[str]) -> str:
|
||||
for name in names:
|
||||
if "Private" in name:
|
||||
return name
|
||||
raise PadError(
|
||||
"SMC-PAD Private port not found. Ports:\n " + "\n ".join(names or ["(none)"])
|
||||
)
|
||||
|
||||
|
||||
def master_port(names: list[str]) -> str:
|
||||
for name in names:
|
||||
if "Master" in name:
|
||||
return name
|
||||
raise PadError(
|
||||
"SMC-PAD Master port not found. Ports:\n " + "\n ".join(names or ["(none)"])
|
||||
)
|
||||
|
||||
|
||||
def transact(midiout, midiin, message: list[int], timeout: float = 0.8, expect: int | None = None) -> bytes:
|
||||
while True:
|
||||
item = midiin.get_message()
|
||||
if not item or not item[0]:
|
||||
break
|
||||
midiout.send_message(message)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
item = midiin.get_message()
|
||||
if not item or not item[0]:
|
||||
time.sleep(0.004)
|
||||
continue
|
||||
raw = bytes(item[0])
|
||||
if raw[:1] != b"\xf0" or raw[-1:] != b"\xf7":
|
||||
continue
|
||||
decoded = decode_body(raw)
|
||||
if expect is not None and (len(decoded) < 3 or decoded[2] != expect):
|
||||
continue
|
||||
return decoded
|
||||
raise PadError("the pad did not answer")
|
||||
|
||||
|
||||
def decode_body(raw: bytes) -> bytes:
|
||||
from padcontroller.sysex import decode
|
||||
|
||||
return decode(raw[1:-1])
|
||||
|
||||
|
||||
class Link:
|
||||
"""One open Private port, input and output."""
|
||||
|
||||
def __init__(self):
|
||||
rtmidi = load_rtmidi()
|
||||
self.midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA)
|
||||
self.midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
|
||||
try:
|
||||
self.name = private_port(self.midiout.get_ports())
|
||||
index = self.midiout.get_ports().index(self.name)
|
||||
self.midiin.open_port(index)
|
||||
self.midiin.ignore_types(sysex=False, timing=True, active_sense=True)
|
||||
self.midiout.open_port(index)
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
for port in (self.midiout, self.midiin):
|
||||
port.close_port()
|
||||
port.delete()
|
||||
|
||||
def read(self, address: int, size: int, memory: int = MEM_PRESET) -> bytes:
|
||||
reply = transact(self.midiout, self.midiin, read_request(address, size, memory), expect=CMD_READ)
|
||||
data = payload_data(reply)
|
||||
return data[:size]
|
||||
|
||||
def write(self, address: int, data: bytes, memory: int = MEM_PRESET) -> None:
|
||||
transact(self.midiout, self.midiin, write_request(address, data, memory))
|
||||
|
||||
def __enter__(self) -> "Link":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
def read_image(link: Link | None = None) -> bytes:
|
||||
own = link is None
|
||||
if link is None:
|
||||
link = Link()
|
||||
try:
|
||||
got = bytearray()
|
||||
while len(got) < IMAGE_LEN:
|
||||
ask = min(READ_CHUNK, IMAGE_LEN - len(got))
|
||||
part = link.read(len(got), ask)
|
||||
if not part:
|
||||
raise PadError(f"empty read at {len(got)}")
|
||||
got += part[:ask]
|
||||
return bytes(got[:IMAGE_LEN])
|
||||
finally:
|
||||
if own:
|
||||
link.close()
|
||||
|
||||
|
||||
def _port_names(kind: str) -> list[str]:
|
||||
rtmidi = load_rtmidi()
|
||||
probe = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) if kind == "out" else rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
|
||||
try:
|
||||
return list(probe.get_ports())
|
||||
finally:
|
||||
probe.delete()
|
||||
|
||||
|
||||
def read_port_names() -> list[str]:
|
||||
return _port_names("out")
|
||||
|
||||
|
||||
def input_names() -> list[str]:
|
||||
return _port_names("in")
|
||||
|
||||
|
||||
def connected() -> str | None:
|
||||
try:
|
||||
return private_port(read_port_names())
|
||||
except PadError:
|
||||
return None
|
||||
|
||||
|
||||
def read_global(link: Link | None = None) -> bytes:
|
||||
"""The 12-byte settings block MidiSuite polls: tempo, swing, curve, transpose."""
|
||||
own = link is None
|
||||
if link is None:
|
||||
link = Link()
|
||||
try:
|
||||
data = link.read(0, GLOBAL_LEN, MEM_GLOBAL)
|
||||
if len(data) < GLOBAL_LEN:
|
||||
raise PadError(f"global block read {len(data)} bytes, expected {GLOBAL_LEN}")
|
||||
return data[:GLOBAL_LEN]
|
||||
finally:
|
||||
if own:
|
||||
link.close()
|
||||
|
||||
|
||||
def set_bank(bank: int, link: Link | None = None) -> int:
|
||||
"""Switch the pad bank the way MidiSuite does: one live byte in the
|
||||
global block. It does not commit; Save keeps whatever the block holds."""
|
||||
from padcontroller.preset import GLOBAL_BANK
|
||||
|
||||
if bank not in (0, 1):
|
||||
raise PadError("pad bank must be 0 or 1")
|
||||
own = link is None
|
||||
if link is None:
|
||||
link = Link()
|
||||
try:
|
||||
link.write(GLOBAL_BANK, bytes((bank,)), MEM_GLOBAL)
|
||||
got = read_global(link)[GLOBAL_BANK]
|
||||
if got != bank:
|
||||
raise PadError(f"the pad is on bank {got + 1}, not {bank + 1}")
|
||||
return bank
|
||||
finally:
|
||||
if own:
|
||||
link.close()
|
||||
|
||||
|
||||
def save_image(desired: bytes, link: Link | None = None, settings: bytes | None = None) -> int:
|
||||
"""Write differing bytes to the preset and commit them.
|
||||
|
||||
Returns how many bytes were written. An unchanged image still gets
|
||||
MidiSuite's empty save, so Save always commits. The settings block,
|
||||
when given and changed, is written whole, as MidiSuite does.
|
||||
"""
|
||||
if len(desired) != IMAGE_LEN:
|
||||
raise PadError(f"preset image is {len(desired)} bytes, expected {IMAGE_LEN}")
|
||||
if settings is not None and len(settings) != GLOBAL_LEN:
|
||||
raise PadError(f"global block is {len(settings)} bytes, expected {GLOBAL_LEN}")
|
||||
own = link is None
|
||||
if link is None:
|
||||
link = Link()
|
||||
try:
|
||||
current = read_image(link)
|
||||
ranges = changed_ranges(current, desired, WRITE_CHUNK)
|
||||
for address, data in ranges:
|
||||
_write_checked(link, address, data)
|
||||
written = sum(len(data) for _address, data in ranges)
|
||||
if settings is not None and read_global(link) != settings:
|
||||
link.write(0, settings, MEM_GLOBAL)
|
||||
if read_global(link) != settings:
|
||||
raise PadError("the pad did not keep the global settings")
|
||||
written += len(settings)
|
||||
_commit(link)
|
||||
return written
|
||||
finally:
|
||||
if own:
|
||||
link.close()
|
||||
|
||||
|
||||
def write_colour(preset: int, index: int, rgb: tuple[int, int, int] | list[int]) -> int:
|
||||
"""Light one pad. The same three-byte write MidiSuite sends while its
|
||||
colour picker moves. It does not commit; Save does that."""
|
||||
from padcontroller.preset import colour_offset
|
||||
|
||||
if len(rgb) != 3:
|
||||
raise PadError("a pad colour needs red, green, and blue")
|
||||
payload = bytes(int(channel) & 0xFF for channel in rgb)
|
||||
offset = colour_offset(preset, index)
|
||||
with Link() as link:
|
||||
_write_checked(link, offset, payload)
|
||||
return offset
|
||||
|
||||
|
||||
def _write_checked(link: Link, address: int, data: bytes) -> None:
|
||||
"""Write the preset address, as MidiSuite does, then read it back."""
|
||||
link.write(address, data)
|
||||
reply = transact(link.midiout, link.midiin, read_request(address, len(data)))
|
||||
got = payload_data(reply)
|
||||
if got[:len(data)] != data:
|
||||
raise PadError(
|
||||
f"read-back at {address:#x} was {got[:len(data)].hex()}, expected {data.hex()}"
|
||||
)
|
||||
|
||||
|
||||
def _commit(link: Link) -> None:
|
||||
reply = transact(link.midiout, link.midiin, save_request())
|
||||
if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00":
|
||||
raise PadError(f"the pad did not accept the save ({reply.hex()})")
|
||||
|
||||
|
||||
def probe_relative(listen: float = 2.5) -> str:
|
||||
"""Try knob type 0x03 in RAM only, on every preset's last knob.
|
||||
|
||||
Restores the original six bytes. Does not save. Returns ``relative``
|
||||
when a turn of that knob sends a step, ``absolute`` when it sends a
|
||||
running value, or ``silent`` when nothing arrives.
|
||||
"""
|
||||
from padcontroller.preset import KNOB_AT, KNOB_COUNT, KNOB_LEN, PRESET_COUNT, PRESET_LEN, RELATIVE_TYPE
|
||||
|
||||
knob = KNOB_COUNT - 1
|
||||
offsets = [index * PRESET_LEN + KNOB_AT + knob * KNOB_LEN for index in range(PRESET_COUNT)]
|
||||
rtmidi = load_rtmidi()
|
||||
master_name = master_port(input_names())
|
||||
heard: list[tuple[int, int, int]] = []
|
||||
watched: set[tuple[int, int]] = set()
|
||||
with Link() as link:
|
||||
original = [link.read(offset, KNOB_LEN) for offset in offsets]
|
||||
watched = {(rec[2], rec[3]) for rec in original}
|
||||
try:
|
||||
for offset, rec in zip(offsets, original):
|
||||
link.write(RAM + offset, bytes((RELATIVE_TYPE,)) + rec[1:])
|
||||
heard = _listen_cc(rtmidi, master_name, listen)
|
||||
finally:
|
||||
for offset, rec in zip(offsets, original):
|
||||
link.write(RAM + offset, rec)
|
||||
matched = [item for item in heard if (item[0], item[1]) in watched]
|
||||
return _classify(matched)
|
||||
|
||||
|
||||
def _listen_cc(rtmidi, port_name: str, listen: float) -> list[tuple[int, int, int]]:
|
||||
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
|
||||
names = midiin.get_ports()
|
||||
midiin.open_port(names.index(port_name))
|
||||
midiin.ignore_types(sysex=True, timing=True, active_sense=True)
|
||||
found: list[tuple[int, int, int]] = []
|
||||
try:
|
||||
deadline = time.time() + listen
|
||||
while time.time() < deadline:
|
||||
item = midiin.get_message()
|
||||
if not item or not item[0]:
|
||||
time.sleep(0.004)
|
||||
continue
|
||||
data = bytes(item[0])
|
||||
if len(data) >= 3 and (data[0] & 0xF0) == 0xB0:
|
||||
found.append((data[0] & 0x0F, data[1], data[2]))
|
||||
finally:
|
||||
midiin.close_port()
|
||||
midiin.delete()
|
||||
return found
|
||||
|
||||
|
||||
def _classify(messages: list[tuple[int, int, int]]) -> str:
|
||||
if not messages:
|
||||
return "silent"
|
||||
values = [value for _channel, _cc, value in messages]
|
||||
unique = set(values)
|
||||
if unique <= {0, 1, 127} or unique <= {63, 64, 65} or _steps(values):
|
||||
return "relative"
|
||||
if len(unique) >= 4:
|
||||
return "absolute"
|
||||
return "silent"
|
||||
|
||||
|
||||
def _steps(values: list[int]) -> bool:
|
||||
"""1..63 clockwise and 65..127 counter-clockwise, with no running ramp."""
|
||||
for value in values:
|
||||
if value == 0 or value == 64 or value > 127:
|
||||
return False
|
||||
if value >= 16 and value <= 111:
|
||||
return False
|
||||
return True
|
||||
Binary file not shown.
@@ -0,0 +1,153 @@
|
||||
"""Hold Play to move the bank 2 pads up a layer.
|
||||
|
||||
The SMC-PAD sends CC 27 as 127 when Play goes down and 0 when it comes up.
|
||||
While it is down, pad notes 52–67 go out as 68–83, so QLC+ can tell a
|
||||
second set of buttons from the first. Play itself is not passed on.
|
||||
|
||||
Pause (CC 28) does the same for bank 1, but latches: the SMC-PAD sends one
|
||||
message a press, 127 and 0 on alternate presses and nothing on release, and
|
||||
bank 1 follows it. At 0, bank 1 pads 36–51 go out as they are, for the cans.
|
||||
At 127, they go out as 84–99, for the movers. Pause itself is not passed on;
|
||||
instead layer_lamp() tells QLC+ which layer is on, holding channel 16 note 0
|
||||
(cans) or 1 (movers) down and the other up, for the test show's Pads layer
|
||||
buttons.
|
||||
|
||||
colours holds the last colour pad pressed in each set, as sent (52–67 for the
|
||||
cans, 68–83 for the movers), or None once it is pressed again: the colour
|
||||
buttons toggle in a solo frame. QLC+ does not save which buttons are on, so
|
||||
reopen() presses them again when QLC+ loads the show.
|
||||
|
||||
The movers' movement pads (pads 13–16, 9–12 and 5 on the movers layer: notes
|
||||
96–99, 92–95 and 88) each toggle a relative EFX around the Pan and Tilt knobs (9
|
||||
and 10, CC 38 and 39). They share a solo frame in QLC+, so starting one stops the others.
|
||||
QLC+ 4.12 leaves an EFX's last offset on the movers when it stops, until those
|
||||
sliders change, so when the one that is on goes off, settle asks for the two
|
||||
knobs one step off and then back (nudge() and positions()). Swapping needs
|
||||
none: the new EFX writes over the old one's offset. moving holds the note whose
|
||||
EFX is on, from the presses: only a guess, as QLC+ sends no feedback for it.
|
||||
|
||||
The cans' pattern pads (pads 1–8 on the cans layer: notes 36–43) each toggle a
|
||||
pattern, in a solo frame like the movement pads; pattern holds the note of the
|
||||
one that is on. A Colour 1 pad starts a colour scene on the cans, and the
|
||||
newest function wins their colour, so the scene would cover the pattern. While
|
||||
a pattern is on, a Colour 1 press sets restart_pattern, and the caller sends
|
||||
pattern_tap() twice a moment later, off and on again, so the pattern restarts on
|
||||
top in the new colour. Taps sent with the colour itself land in the same QLC+
|
||||
tick and change nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
PLAY_CC = 27
|
||||
FIRST_NOTE = 52
|
||||
LAST_NOTE = 67
|
||||
SHIFT = 16
|
||||
PAUSE_CC = 28
|
||||
BANK_1_FIRST = 36
|
||||
BANK_1_LAST = 51
|
||||
MOVERS_SHIFT = 48 # bank 1 goes out as 84–99 while Pause is on, above bank 2's held layer
|
||||
LAMP_CHANNEL = 15 # channel 16: the Pads layer buttons in QLC+, clear of the pads and knobs
|
||||
CANS_LAMP, MOVERS_LAMP = 0, 1 # their notes
|
||||
KNOB_CHANNEL = 0
|
||||
# Wander, Ballyhoo, Circle, Sweep; Diamond, Square, Corners, Leaf; Tilt: pads 13–16, 9–12, 5
|
||||
RELATIVE_NOTES = (96, 97, 98, 99, 92, 93, 94, 95, 88)
|
||||
POSITION_CCS = (38, 39) # knobs 9 and 10: the movers' Pan and Tilt
|
||||
PATTERN_NOTES = range(36, 44) # the can patterns: pads 1–8 on the cans layer
|
||||
|
||||
|
||||
class PlayLayer:
|
||||
def __init__(self) -> None:
|
||||
self.held = False
|
||||
self.movers = False # Pause latched on puts bank 1 on the movers
|
||||
# (channel, note as pressed) -> note sent, so a release matches its press
|
||||
self.sent: dict[tuple[int, int], int] = {}
|
||||
# Pan and Tilt as last sent; QLC+ starts them at 0.
|
||||
self.position = {cc: 0 for cc in POSITION_CCS}
|
||||
self.moving: int | None = None
|
||||
self.settle = False # a relative EFX just went off: the caller sends nudge(), then positions()
|
||||
self.pattern: int | None = None
|
||||
self.pattern_channel = 0
|
||||
self.restart_pattern = False # a Colour 1 press covered the pattern: the caller sends pattern_tap() twice
|
||||
# set -> (channel, note sent) of the colour that is on
|
||||
self.colours: dict[int, tuple[int, int] | None] = {1: None, 2: None}
|
||||
|
||||
def handle(self, data: list[int]) -> list[list[int]]:
|
||||
"""The messages to send on. Empty when the message is swallowed."""
|
||||
status = data[0]
|
||||
kind = status & 0xF0
|
||||
channel = status & 0x0F
|
||||
if kind == 0xB0 and len(data) >= 3 and data[1] == PLAY_CC:
|
||||
self.held = data[2] > 0
|
||||
return []
|
||||
if kind == 0xB0 and len(data) >= 3 and data[1] == PAUSE_CC:
|
||||
self.movers = data[2] > 0
|
||||
return self.layer_lamp()
|
||||
if kind == 0xB0 and len(data) >= 3 and channel == KNOB_CHANNEL and data[1] in self.position:
|
||||
self.position[data[1]] = data[2]
|
||||
return [list(data)]
|
||||
if kind not in (0x80, 0x90) or len(data) < 3:
|
||||
return [list(data)]
|
||||
key = (channel, data[1])
|
||||
is_on = kind == 0x90 and data[2] > 0
|
||||
if is_on:
|
||||
out = self.shifted(data[1])
|
||||
self.sent[key] = out
|
||||
else:
|
||||
out = self.sent.pop(key, data[1])
|
||||
note = out
|
||||
if note in RELATIVE_NOTES and is_on:
|
||||
if note == self.moving:
|
||||
self.moving = None
|
||||
self.settle = True
|
||||
else:
|
||||
self.moving = note
|
||||
elif note in PATTERN_NOTES and is_on:
|
||||
self.pattern = None if note == self.pattern else note
|
||||
self.pattern_channel = channel
|
||||
elif FIRST_NOTE <= note <= LAST_NOTE and is_on and self.pattern is not None:
|
||||
self.restart_pattern = True
|
||||
if is_on and FIRST_NOTE <= out <= LAST_NOTE + SHIFT:
|
||||
colour_set = 1 if out <= LAST_NOTE else 2
|
||||
pressed = (channel, out)
|
||||
self.colours[colour_set] = None if self.colours[colour_set] == pressed else pressed
|
||||
return [[status, out, *data[2:]]]
|
||||
|
||||
def shifted(self, note: int) -> int:
|
||||
"""The note a press goes out as: bank 2 up while Play is held, bank 1 up while Pause is on."""
|
||||
if self.held and FIRST_NOTE <= note <= LAST_NOTE:
|
||||
return note + SHIFT
|
||||
if self.movers and BANK_1_FIRST <= note <= BANK_1_LAST:
|
||||
return note + MOVERS_SHIFT
|
||||
return note
|
||||
|
||||
def reopen(self) -> list[list[int]]:
|
||||
"""QLC+ has loaded the show: everything is off. Press the colours that were on."""
|
||||
self.moving = None
|
||||
self.pattern = None
|
||||
out = self.layer_lamp()
|
||||
for colour in self.colours.values():
|
||||
if colour is not None:
|
||||
out += tap(*colour)
|
||||
return out
|
||||
|
||||
def layer_lamp(self) -> list[list[int]]:
|
||||
"""The active layer's lamp note held down and the other's let go."""
|
||||
on, off = (MOVERS_LAMP, CANS_LAMP) if self.movers else (CANS_LAMP, MOVERS_LAMP)
|
||||
return [[0x80 | LAMP_CHANNEL, off, 0], [0x90 | LAMP_CHANNEL, on, 127]]
|
||||
|
||||
def pattern_tap(self) -> list[list[int]]:
|
||||
"""A tap of the can pattern that is on, to toggle it; nothing once none is."""
|
||||
return [] if self.pattern is None else tap(self.pattern_channel, self.pattern)
|
||||
|
||||
def nudge(self) -> list[list[int]]:
|
||||
"""Pan and Tilt one step off their knobs, so QLC+ writes them again."""
|
||||
return [[0xB0 | KNOB_CHANNEL, cc, v - 1 if v else 1] for cc, v in self.position.items()]
|
||||
|
||||
def positions(self) -> list[list[int]]:
|
||||
"""Pan and Tilt back at their knobs."""
|
||||
return [[0xB0 | KNOB_CHANNEL, cc, v] for cc, v in self.position.items()]
|
||||
|
||||
|
||||
def tap(channel: int, note: int) -> list[list[int]]:
|
||||
"""A press and release of note, to toggle a QLC+ button off."""
|
||||
return [[0x90 | channel, note, 127], [0x80 | channel, note, 0]]
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Pad controller: intercept the SMC-PAD's MIDI and smooth its 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 "padcontroller".
|
||||
|
||||
On start it also sets the pad lamps over USB (scripts/pad/pad_lamps.py): bank 1 off and
|
||||
bank 2 in the colours from shows/test.qxw. On Bluetooth it says so and carries on.
|
||||
While Play is held, bank 2 notes 52–67 go out as 68–83 (see padcontroller/layer.py).
|
||||
|
||||
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
|
||||
patch_smc_pad.py once the pad controller is running). Every 2 s it checks the
|
||||
links: it reopens the pad when it is replugged (or moves to Bluetooth when that
|
||||
turns up) and re-links QLC+ to the virtual port after a restart, so QLC+ can stay open.
|
||||
|
||||
QLC+ reopens its MIDI port when it loads a show, so a new link to QLC+ while
|
||||
the pad controller runs means the show has just loaded with every button off.
|
||||
That is a link the pad controller had to make, or one QLC+ made itself: a
|
||||
restarted QLC+ subscribes to the virtual port on its own as it opens the show,
|
||||
before the next check, so a QLC+ process or port fed that wasn't at the last
|
||||
check counts too (qlc_feeds). REOPEN_DELAY later it presses the last colour pads
|
||||
again (see PlayLayer.colours), which it keeps in COLOURS_FILE so they outlive a
|
||||
restart of the pad controller.
|
||||
|
||||
When one of the movers' movement pads goes off, SETTLE_DELAY later it
|
||||
nudges the Pan and Tilt knobs a step and puts them back, so QLC+ drops
|
||||
the EFX's last offset (see PlayLayer.settle).
|
||||
|
||||
Usage:
|
||||
.venv/bin/python -m padcontroller.midi
|
||||
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
|
||||
|
||||
padcontroller/systemd/install.sh runs it as a systemd user service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
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
|
||||
|
||||
from padcontroller.layer import LAMP_CHANNEL, PlayLayer # noqa: E402
|
||||
|
||||
# The lamp colours come from the show scripts, which are not part of this package.
|
||||
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
|
||||
from pad_lamps import set_lamps # noqa: E402
|
||||
|
||||
VIRTUAL_NAME = "padcontroller"
|
||||
COLOURS_FILE = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local" / "state")) / "padcontroller" / "colours.json"
|
||||
REOPEN_DELAY = 1.5 # s for QLC+ to finish loading the virtual console
|
||||
SETTLE_DELAY = 0.1 # s for QLC+ to stop a relative EFX before the knob nudge, and between its two steps
|
||||
RESTART_DELAY = 0.1 # s after a Colour 1 press before the can pattern's off tap, and between it and the on tap
|
||||
# Bluetooth first when the pad is paired, USB otherwise.
|
||||
SOURCE_HINTS = (
|
||||
"SMC-PAD Bluetooth",
|
||||
"SINCO SMC-PAD-Master",
|
||||
"SINCO SMC-PAD-Private",
|
||||
"SINCO",
|
||||
"SMC-PAD",
|
||||
)
|
||||
|
||||
|
||||
def pick_source(names: list[str]) -> int | None:
|
||||
"""Index of the best SMC-PAD port in names, or None when the pad is not there."""
|
||||
for hint in SOURCE_HINTS:
|
||||
for i, name in enumerate(names):
|
||||
if hint in name and VIRTUAL_NAME not in name:
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AlsaPort:
|
||||
addr: str # "client:port"
|
||||
client: str
|
||||
name: str
|
||||
pid: str | None = None # the client's process, for user clients
|
||||
to: set[str] = field(default_factory=set)
|
||||
sources: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
def parse_aconnect(text: str) -> list[AlsaPort]:
|
||||
"""The ports in `aconnect -l` output, with who they connect to and from."""
|
||||
ports: list[AlsaPort] = []
|
||||
client = client_name = pid = None
|
||||
for line in text.splitlines():
|
||||
m = re.match(r"client (\d+): '([^']+)'(?:.*\bpid=(\d+))?", line)
|
||||
if m:
|
||||
client, client_name, pid = m.groups()
|
||||
continue
|
||||
m = re.match(r"\s+(\d+)\s+'([^']+)'", line)
|
||||
if m and client is not None:
|
||||
ports.append(AlsaPort(f"{client}:{m.group(1)}", client_name, m.group(2).strip(), pid))
|
||||
continue
|
||||
m = re.match(r"\s+(Connecting To|Connected From):(.*)", line)
|
||||
if m and ports:
|
||||
addrs = set(re.findall(r"\d+:\d+", m.group(2)))
|
||||
(ports[-1].to if m.group(1) == "Connecting To" else ports[-1].sources).update(addrs)
|
||||
return ports
|
||||
|
||||
|
||||
def missing_links(ports: list[AlsaPort], src_name: str | None) -> list[tuple[str, str]]:
|
||||
"""(from, to) ALSA links the pad controller should have but doesn't.
|
||||
|
||||
The pad into padcontroller-in (Bluetooth MIDI sometimes drops it, and a replugged
|
||||
USB pad comes back without it), and padcontroller out to every QLC+ client
|
||||
(QLC+ only subscribes when it opens the port, so it loses it when we restart).
|
||||
"""
|
||||
links = []
|
||||
ours_in = next((p for p in ports if p.client == "padcontroller-in"), None)
|
||||
ours_out = next((p for p in ports if p.client == "padcontroller-out"), None)
|
||||
m = re.search(r"(\d+:\d+)$", src_name or "")
|
||||
if ours_in and m and m.group(1) not in ours_in.sources:
|
||||
links.append((m.group(1), ours_in.addr))
|
||||
if ours_out:
|
||||
for p in ports:
|
||||
if p.client == "qlcplus" and p.addr not in ours_out.to:
|
||||
links.append((ours_out.addr, p.addr))
|
||||
return links
|
||||
|
||||
|
||||
def qlc_feeds(ports: list[AlsaPort]) -> set[tuple[str | None, str]]:
|
||||
"""(pid, address) of each QLC+ port the pad controller's output is linked to."""
|
||||
ours_out = next((p for p in ports if p.client == "padcontroller-out"), None)
|
||||
if ours_out is None:
|
||||
return set()
|
||||
return {(p.pid, p.addr) for p in ports if p.client == "qlcplus" and p.addr in ours_out.to}
|
||||
|
||||
|
||||
def ensure_links(src_name: str | None) -> tuple[bool, set[tuple[str | None, str]]]:
|
||||
"""Make the missing links. Whether one of them was to QLC+, and the QLC+ ports fed after."""
|
||||
try:
|
||||
out = subprocess.check_output(["aconnect", "-l"], text=True)
|
||||
except (FileNotFoundError, subprocess.CalledProcessError):
|
||||
return False, set()
|
||||
ports = parse_aconnect(out)
|
||||
qlc = {p.addr: p.pid for p in ports if p.client == "qlcplus"}
|
||||
fed = qlc_feeds(ports)
|
||||
to_qlc = False
|
||||
for src, dst in missing_links(ports, src_name):
|
||||
if subprocess.run(["aconnect", src, dst], capture_output=True).returncode == 0:
|
||||
print(f"Linked {src} -> {dst}", flush=True)
|
||||
if dst in qlc:
|
||||
to_qlc = True
|
||||
fed.add((qlc[dst], dst))
|
||||
return to_qlc, fed
|
||||
|
||||
|
||||
def unlink_source(src_name: str | None) -> None:
|
||||
"""Take the pad's old port off padcontroller-in, so a pad moving from USB to Bluetooth isn't heard twice."""
|
||||
m = re.search(r"(\d+:\d+)$", src_name or "")
|
||||
if m:
|
||||
subprocess.run(["aconnect", "-d", m.group(1), "padcontroller-in:0"], capture_output=True)
|
||||
|
||||
|
||||
def load_colours(layer: PlayLayer) -> None:
|
||||
try:
|
||||
saved = json.loads(COLOURS_FILE.read_text())
|
||||
layer.colours = {int(k): tuple(v) if v else None for k, v in saved.items()}
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass
|
||||
|
||||
|
||||
def save_colours(layer: PlayLayer) -> None:
|
||||
try:
|
||||
COLOURS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
COLOURS_FILE.write_text(json.dumps(layer.colours) + "\n")
|
||||
except OSError as exc:
|
||||
print(f"Colours not saved: {exc}", flush=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")
|
||||
ap.add_argument("--no-lamps", action="store_true", help="leave the pad lamp colours alone")
|
||||
args = ap.parse_args()
|
||||
|
||||
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA, name="padcontroller-in")
|
||||
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="padcontroller-out")
|
||||
|
||||
names = midiin.get_ports()
|
||||
src = pick_source(names)
|
||||
src_name = names[src] if src is not None else None
|
||||
# Our own input port, with the pad linked into it by ensure_links: it keeps reading while
|
||||
# the pad is away (rtmidi stops reading when an opened port closes), so the virtual pad
|
||||
# still gets through.
|
||||
midiin.open_virtual_port("RtMidi input")
|
||||
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] = {}
|
||||
layer = PlayLayer()
|
||||
load_colours(layer)
|
||||
saved_colours = dict(layer.colours)
|
||||
reopen_at: float | None = None
|
||||
# (when, messages to send then), for the settle after a mover EFX
|
||||
later: list[tuple[float, Callable[[], list[list[int]]]]] = []
|
||||
# Links made this soon after start are ours being restored, with QLC+'s buttons as they were.
|
||||
reopen_from = time.monotonic() + 5.0
|
||||
|
||||
print(f"Source: {src_name or '(pad gone, waiting)'}", flush=True)
|
||||
print(f"Virtual: {VIRTUAL_NAME} (tau={args.tau}s @ {args.rate} Hz)", flush=True)
|
||||
print("Pass notes through (Play held shifts bank 2 up 16); smooth CC. Ctrl+C to stop.", flush=True)
|
||||
_, fed = ensure_links(src_name)
|
||||
for out in layer.layer_lamp():
|
||||
midiout.send_message(out)
|
||||
if not args.no_lamps:
|
||||
set_lamps()
|
||||
|
||||
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:
|
||||
# Follow the pad: reopen it when it comes back, and move to Bluetooth when paired.
|
||||
names = midiin.get_ports()
|
||||
best = pick_source(names)
|
||||
best_name = names[best] if best is not None else None
|
||||
if best_name != src_name:
|
||||
unlink_source(src_name)
|
||||
print(f"Source: {best_name or '(pad gone, waiting)'}", flush=True)
|
||||
src_name = best_name
|
||||
linked, now_fed = ensure_links(src_name)
|
||||
if (linked or now_fed - fed) and now >= reopen_from:
|
||||
reopen_at = now + REOPEN_DELAY
|
||||
fed = now_fed
|
||||
next_link_check = now + 2.0
|
||||
|
||||
if reopen_at is not None and now >= reopen_at:
|
||||
reopen_at = None
|
||||
taps = layer.reopen()
|
||||
for out in taps:
|
||||
midiout.send_message(out)
|
||||
pressed = sum(out[0] & 0xF0 == 0x90 and out[0] & 0x0F != LAMP_CHANNEL for out in taps)
|
||||
print(f"QLC+ reopened: pressed {pressed} colour pad(s) again", flush=True)
|
||||
|
||||
# Drain inbound
|
||||
while True:
|
||||
msg = midiin.get_message()
|
||||
if msg is None:
|
||||
break
|
||||
data, _ = msg
|
||||
if not data:
|
||||
continue
|
||||
for out in layer.handle(list(data)):
|
||||
cmd = out[0] & 0xF0
|
||||
if cmd == 0xB0 and len(out) >= 3:
|
||||
# Control Change → smooth
|
||||
key = (out[0] & 0x0F, out[1])
|
||||
target[key] = float(out[2])
|
||||
if key not in current:
|
||||
current[key] = float(out[2])
|
||||
last_sent[key] = -1
|
||||
else:
|
||||
# Notes, aftertouch, PC, etc. → immediate
|
||||
midiout.send_message(out)
|
||||
if layer.settle:
|
||||
layer.settle = False
|
||||
later += [(now + SETTLE_DELAY, layer.nudge), (now + 2 * SETTLE_DELAY, layer.positions)]
|
||||
if layer.restart_pattern:
|
||||
layer.restart_pattern = False
|
||||
later += [(now + RESTART_DELAY, layer.pattern_tap), (now + 2 * RESTART_DELAY, layer.pattern_tap)]
|
||||
for due in [item for item in later if now >= item[0]]:
|
||||
later.remove(due)
|
||||
for out in due[1]():
|
||||
midiout.send_message(out)
|
||||
if layer.colours != saved_colours:
|
||||
save_colours(layer)
|
||||
saved_colours = dict(layer.colours)
|
||||
|
||||
# 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()
|
||||
@@ -0,0 +1,317 @@
|
||||
"""SMC-PAD preset image: 8 × 3539 bytes, the map MidiSuite edits."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
IMAGE_LEN = 28312
|
||||
PRESET_LEN = 3539
|
||||
PRESET_COUNT = 8
|
||||
|
||||
BUTTON_COUNT = 5
|
||||
BUTTON_LEN = 23
|
||||
BUTTON_NAMES = ("Left", "Right", "Play", "Stop", "Record")
|
||||
|
||||
KNOB_AT = 115
|
||||
KNOB_COUNT = 16
|
||||
KNOB_LEN = 6
|
||||
KNOB_BANK = 8
|
||||
|
||||
GAP_AT = 211
|
||||
|
||||
PAD_AT = 212
|
||||
PAD_LEN = 26
|
||||
PAD_COUNT = 128
|
||||
PAGE_LEN = 16
|
||||
PAGE_COUNT = 8
|
||||
RGB_AT = 4
|
||||
|
||||
# Global settings, memory type 4. Offsets are the fields MidiSuite's Glob
|
||||
# panel showed against the factory block 78 00 32 04 00 00 02 00 01 01 00 00.
|
||||
GLOBAL_LEN = 12
|
||||
GLOBAL_TEMPO = 0 # two bytes, little-endian
|
||||
GLOBAL_SWING = 2
|
||||
GLOBAL_CURVE = 6
|
||||
GLOBAL_TRANSPOSE = 7 # signed
|
||||
GLOBAL_BANK = 11 # 0 is pad bank 1, 1 is pad bank 2; MidiSuite writes it to switch banks
|
||||
|
||||
# File bytes. Names are only values MidiSuite has shown for this pad's
|
||||
# factory image, or a RAM probe on this pad has heard.
|
||||
KNOB_TYPES = {0x00: "CC"}
|
||||
BUTTON_TYPES = {0x02: "CC Push"}
|
||||
|
||||
# Set after a RAM-only probe hears a relative step from type 0x03.
|
||||
RELATIVE_TYPE = 0x03
|
||||
RELATIVE_CONFIRMED = False
|
||||
|
||||
FULL = 0xF0
|
||||
SYSEX_ROOM = 16 # button bytes 6..21; byte 22 is the flag
|
||||
|
||||
|
||||
def scale(value: int) -> int:
|
||||
"""Map 0–255 onto the pad's 0–240 colour range."""
|
||||
return (value * FULL + 127) // 255
|
||||
|
||||
|
||||
def knob_type_names() -> dict[int, str]:
|
||||
names = dict(KNOB_TYPES)
|
||||
if RELATIVE_CONFIRMED:
|
||||
names[RELATIVE_TYPE] = "Relative"
|
||||
return names
|
||||
|
||||
|
||||
def type_catalog() -> dict[str, list[dict[str, int | str]]]:
|
||||
def rows(names: dict[int, str]) -> list[dict[str, int | str]]:
|
||||
return [{"value": value, "name": name} for value, name in sorted(names.items())]
|
||||
|
||||
return {
|
||||
"knob": rows(knob_type_names()),
|
||||
"button": rows(BUTTON_TYPES),
|
||||
}
|
||||
|
||||
|
||||
class PresetError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _byte(value: object, label: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 255:
|
||||
raise PresetError(f"{label} must be a byte")
|
||||
return value
|
||||
|
||||
|
||||
def _channel(value: object, label: str) -> int:
|
||||
"""MIDI channel 1–16 as stored, which is 0–15."""
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 16:
|
||||
raise PresetError(f"{label} must be MIDI channel 1–16")
|
||||
return value - 1
|
||||
|
||||
|
||||
def _hex(value: object, label: str) -> bytes:
|
||||
if not isinstance(value, str) or len(value) % 2:
|
||||
raise PresetError(f"{label} must be even-length hex")
|
||||
try:
|
||||
return bytes.fromhex(value)
|
||||
except ValueError as exc:
|
||||
raise PresetError(f"{label} is not hex") from exc
|
||||
|
||||
|
||||
def unpack(image: bytes) -> dict:
|
||||
if len(image) != IMAGE_LEN:
|
||||
raise PresetError(f"preset image is {len(image)} bytes, expected {IMAGE_LEN}")
|
||||
presets = []
|
||||
for index in range(PRESET_COUNT):
|
||||
block = image[index * PRESET_LEN:(index + 1) * PRESET_LEN]
|
||||
presets.append(_unpack_preset(block))
|
||||
return {"presets": presets, "types": type_catalog(), "relative": RELATIVE_CONFIRMED}
|
||||
|
||||
|
||||
def pack(document: dict) -> bytes:
|
||||
presets = document.get("presets")
|
||||
if not isinstance(presets, list) or len(presets) != PRESET_COUNT:
|
||||
raise PresetError(f"expected {PRESET_COUNT} presets")
|
||||
out = bytearray()
|
||||
for index, preset in enumerate(presets):
|
||||
out += _pack_preset(preset, index)
|
||||
if len(out) != IMAGE_LEN:
|
||||
raise PresetError(f"packed {len(out)} bytes, expected {IMAGE_LEN}")
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def colour_offset(preset: int, index: int) -> int:
|
||||
"""Where one pad's colour sits. MidiSuite writes only this address."""
|
||||
if not 0 <= preset < PRESET_COUNT:
|
||||
raise PresetError(f"preset {preset + 1} is not on this controller")
|
||||
if not 0 <= index < PAD_COUNT:
|
||||
raise PresetError(f"pad {index + 1} is not on this controller")
|
||||
return preset * PRESET_LEN + PAD_AT + index * PAD_LEN + RGB_AT
|
||||
|
||||
|
||||
def unpack_global(raw: bytes) -> dict:
|
||||
if len(raw) != GLOBAL_LEN:
|
||||
raise PresetError(f"global block is {len(raw)} bytes, expected {GLOBAL_LEN}")
|
||||
return {
|
||||
"tempo": int.from_bytes(raw[GLOBAL_TEMPO:GLOBAL_TEMPO + 2], "little"),
|
||||
"swing": raw[GLOBAL_SWING],
|
||||
"curve": raw[GLOBAL_CURVE],
|
||||
"transpose": int.from_bytes(raw[GLOBAL_TRANSPOSE:GLOBAL_TRANSPOSE + 1], "little", signed=True),
|
||||
"bank": raw[GLOBAL_BANK],
|
||||
"raw": raw.hex(),
|
||||
}
|
||||
|
||||
|
||||
def pack_global(block: dict) -> bytes:
|
||||
"""The named fields over the bytes that were read, so unknown ones stay put."""
|
||||
out = bytearray(_hex(block.get("raw", ""), "global block"))
|
||||
if len(out) != GLOBAL_LEN:
|
||||
raise PresetError(f"global block is {len(out)} bytes, expected {GLOBAL_LEN}")
|
||||
tempo = block.get("tempo")
|
||||
if isinstance(tempo, bool) or not isinstance(tempo, int) or not 1 <= tempo <= 0xFFFF:
|
||||
raise PresetError("tempo must be a whole number of BPM")
|
||||
out[GLOBAL_TEMPO:GLOBAL_TEMPO + 2] = tempo.to_bytes(2, "little")
|
||||
out[GLOBAL_SWING] = _byte(block.get("swing"), "swing")
|
||||
out[GLOBAL_CURVE] = _byte(block.get("curve"), "pad curve")
|
||||
transpose = block.get("transpose")
|
||||
if isinstance(transpose, bool) or not isinstance(transpose, int) or not -128 <= transpose <= 127:
|
||||
raise PresetError("transpose must be -128 to 127")
|
||||
out[GLOBAL_TRANSPOSE] = transpose & 0xFF
|
||||
bank = block.get("bank", out[GLOBAL_BANK])
|
||||
if isinstance(bank, bool) or bank not in (0, 1):
|
||||
raise PresetError("pad bank must be 0 or 1")
|
||||
out[GLOBAL_BANK] = bank
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def changed_ranges(before: bytes, after: bytes, limit: int = 64) -> list[tuple[int, bytes]]:
|
||||
"""Coalesce differing bytes, then split each run into write-sized pieces."""
|
||||
if len(before) != len(after):
|
||||
raise PresetError(f"cannot compare {len(before)} bytes with {len(after)}")
|
||||
runs: list[tuple[int, int]] = []
|
||||
start = None
|
||||
for index, (old, new) in enumerate(zip(before, after)):
|
||||
if old != new:
|
||||
if start is None:
|
||||
start = index
|
||||
elif start is not None:
|
||||
runs.append((start, index))
|
||||
start = None
|
||||
if start is not None:
|
||||
runs.append((start, len(after)))
|
||||
pieces: list[tuple[int, bytes]] = []
|
||||
for run_at, run_end in runs:
|
||||
at = run_at
|
||||
while at < run_end:
|
||||
stop = min(run_end, at + limit)
|
||||
pieces.append((at, after[at:stop]))
|
||||
at = stop
|
||||
return pieces
|
||||
|
||||
|
||||
def _unpack_preset(block: bytes) -> dict:
|
||||
buttons = []
|
||||
for index in range(BUTTON_COUNT):
|
||||
rec = block[index * BUTTON_LEN:(index + 1) * BUTTON_LEN]
|
||||
length = rec[5]
|
||||
if length > SYSEX_ROOM:
|
||||
sysex, padding = rec[6:22], b""
|
||||
else:
|
||||
sysex, padding = rec[6:6 + length], rec[6 + length:22]
|
||||
buttons.append({
|
||||
"name": BUTTON_NAMES[index],
|
||||
"type": rec[0],
|
||||
"channel": rec[1] + 1,
|
||||
"number": rec[2],
|
||||
"min": rec[3],
|
||||
"max": rec[4],
|
||||
"sysex": sysex.hex(),
|
||||
"padding": padding.hex(),
|
||||
"led": rec[22],
|
||||
})
|
||||
knobs = []
|
||||
for index in range(KNOB_COUNT):
|
||||
at = KNOB_AT + index * KNOB_LEN
|
||||
rec = block[at:at + KNOB_LEN]
|
||||
knobs.append({
|
||||
"type": rec[0],
|
||||
"speed": rec[1],
|
||||
"channel": rec[2] + 1,
|
||||
"number": rec[3],
|
||||
"left": rec[4],
|
||||
"right": rec[5],
|
||||
})
|
||||
pads = []
|
||||
for index in range(PAD_COUNT):
|
||||
at = PAD_AT + index * PAD_LEN
|
||||
rec = block[at:at + PAD_LEN]
|
||||
pads.append({
|
||||
"channel": rec[0] + 1,
|
||||
"note": rec[1],
|
||||
"min": rec[2],
|
||||
"max": rec[3],
|
||||
"rgb": [rec[4], rec[5], rec[6]],
|
||||
"led": rec[7],
|
||||
"tail": rec[8:].hex(),
|
||||
})
|
||||
return {"gap": block[GAP_AT], "buttons": buttons, "knobs": knobs, "pads": pads}
|
||||
|
||||
|
||||
def _pack_preset(preset: dict, index: int) -> bytes:
|
||||
out = bytearray(PRESET_LEN)
|
||||
buttons = preset.get("buttons")
|
||||
knobs = preset.get("knobs")
|
||||
pads = preset.get("pads")
|
||||
if not isinstance(buttons, list) or len(buttons) != BUTTON_COUNT:
|
||||
raise PresetError(f"preset {index + 1} needs {BUTTON_COUNT} buttons")
|
||||
if not isinstance(knobs, list) or len(knobs) != KNOB_COUNT:
|
||||
raise PresetError(f"preset {index + 1} needs {KNOB_COUNT} knobs")
|
||||
if not isinstance(pads, list) or len(pads) != PAD_COUNT:
|
||||
raise PresetError(f"preset {index + 1} needs {PAD_COUNT} pads")
|
||||
for number, button in enumerate(buttons):
|
||||
out[number * BUTTON_LEN:(number + 1) * BUTTON_LEN] = _pack_button(button, index, number)
|
||||
for number, knob in enumerate(knobs):
|
||||
at = KNOB_AT + number * KNOB_LEN
|
||||
out[at:at + KNOB_LEN] = _pack_knob(knob, index, number)
|
||||
out[GAP_AT] = _byte(preset.get("gap", 0), f"preset {index + 1} gap")
|
||||
for number, pad in enumerate(pads):
|
||||
at = PAD_AT + number * PAD_LEN
|
||||
rec = _pack_pad(pad, index, number)
|
||||
room = PRESET_LEN - at
|
||||
if len(rec) > room:
|
||||
raise PresetError(f"preset {index + 1} pad {number + 1} does not fit")
|
||||
out[at:at + len(rec)] = rec
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _pack_button(button: dict, preset: int, index: int) -> bytes:
|
||||
label = f"preset {preset + 1} {BUTTON_NAMES[index]}"
|
||||
sysex = _hex(button.get("sysex", ""), f"{label} sysex")
|
||||
if len(sysex) > SYSEX_ROOM:
|
||||
raise PresetError(f"{label} sysex is longer than {SYSEX_ROOM} bytes")
|
||||
padding = _hex(button.get("padding", ""), f"{label} padding")
|
||||
room = SYSEX_ROOM - len(sysex)
|
||||
padding = padding[:room]
|
||||
rec = bytearray(BUTTON_LEN)
|
||||
rec[0] = _byte(button.get("type"), f"{label} type")
|
||||
rec[1] = _channel(button.get("channel"), f"{label} channel")
|
||||
rec[2] = _byte(button.get("number"), f"{label} number")
|
||||
rec[3] = _byte(button.get("min"), f"{label} min")
|
||||
rec[4] = _byte(button.get("max"), f"{label} max")
|
||||
rec[5] = len(sysex)
|
||||
rec[6:6 + len(sysex)] = sysex
|
||||
rec[6 + len(sysex):22] = padding + bytes(room - len(padding))
|
||||
rec[22] = _byte(button.get("led"), f"{label} led")
|
||||
return bytes(rec)
|
||||
|
||||
|
||||
def _pack_knob(knob: dict, preset: int, index: int) -> bytes:
|
||||
label = f"preset {preset + 1} knob {index + 1}"
|
||||
# Any stored type byte round-trips. The editor only offers names it has seen.
|
||||
return bytes((
|
||||
_byte(knob.get("type"), f"{label} type"),
|
||||
_byte(knob.get("speed"), f"{label} speed"),
|
||||
_channel(knob.get("channel"), f"{label} channel"),
|
||||
_byte(knob.get("number"), f"{label} number"),
|
||||
_byte(knob.get("left"), f"{label} left"),
|
||||
_byte(knob.get("right"), f"{label} right"),
|
||||
))
|
||||
|
||||
|
||||
def _pack_pad(pad: dict, preset: int, index: int) -> bytes:
|
||||
label = f"preset {preset + 1} pad {index + 1}"
|
||||
rgb = pad.get("rgb")
|
||||
if not isinstance(rgb, list) or len(rgb) != 3:
|
||||
raise PresetError(f"{label} colour needs three bytes")
|
||||
tail = _hex(pad.get("tail", ""), f"{label} tail")
|
||||
stored = PAD_LEN if index < PAD_COUNT - 1 else PRESET_LEN - (PAD_AT + (PAD_COUNT - 1) * PAD_LEN)
|
||||
tail_room = stored - 8
|
||||
if len(tail) > tail_room:
|
||||
raise PresetError(f"{label} tail is longer than {tail_room} bytes")
|
||||
rec = bytearray(stored)
|
||||
rec[0] = _channel(pad.get("channel"), f"{label} channel")
|
||||
rec[1] = _byte(pad.get("note"), f"{label} note")
|
||||
rec[2] = _byte(pad.get("min"), f"{label} min velocity")
|
||||
rec[3] = _byte(pad.get("max"), f"{label} max velocity")
|
||||
rec[4] = _byte(rgb[0], f"{label} red")
|
||||
rec[5] = _byte(rgb[1], f"{label} green")
|
||||
rec[6] = _byte(rgb[2], f"{label} blue")
|
||||
rec[7] = _byte(pad.get("led"), f"{label} led")
|
||||
rec[8:8 + len(tail)] = tail
|
||||
return bytes(rec)
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Local editor: load the SMC-PAD preset, edit it, save it back."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import mimetypes
|
||||
import threading
|
||||
import traceback
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from padcontroller.device import Link, PadError, connected, read_global, read_image, save_image, set_bank, write_colour
|
||||
from padcontroller.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global
|
||||
|
||||
STATIC_DIR = Path(__file__).parent / "static"
|
||||
# The image MidiSuite uploads for its factory reset, and its global block.
|
||||
FACTORY_IMAGE = Path(__file__).parent / "factory.bin"
|
||||
FACTORY_GLOBAL = bytes.fromhex("780032040000020001010000")
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, message: str, status: int = 400):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
class Editor:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def status(self) -> dict:
|
||||
port = connected()
|
||||
return {"connected": port is not None, "port": port}
|
||||
|
||||
def load(self) -> dict:
|
||||
with self.lock:
|
||||
try:
|
||||
with Link() as link:
|
||||
document = unpack(read_image(link))
|
||||
document["global"] = unpack_global(read_global(link))
|
||||
return document
|
||||
except PadError as exc:
|
||||
raise ApiError(str(exc), 503) from exc
|
||||
|
||||
def save(self, document: dict) -> dict:
|
||||
try:
|
||||
desired = pack(document)
|
||||
block = document.get("global")
|
||||
settings = pack_global(block) if isinstance(block, dict) else None
|
||||
except PresetError as exc:
|
||||
raise ApiError(str(exc)) from exc
|
||||
with self.lock:
|
||||
try:
|
||||
written = save_image(desired, settings=settings)
|
||||
except PadError as exc:
|
||||
raise ApiError(str(exc), 503) from exc
|
||||
if written:
|
||||
message = f"Saved on the pad. {written} bytes written."
|
||||
else:
|
||||
message = "Saved on the pad."
|
||||
return {"ok": True, "message": message, "bytes": written}
|
||||
|
||||
def colour(self, body: dict) -> dict:
|
||||
try:
|
||||
preset = int(body["preset"])
|
||||
index = int(body["index"])
|
||||
rgb = body["rgb"]
|
||||
if not isinstance(rgb, list) or len(rgb) != 3:
|
||||
raise PresetError("a pad colour needs red, green, and blue")
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ApiError("colour needs a preset, a pad, and an rgb colour") from exc
|
||||
with self.lock:
|
||||
try:
|
||||
offset = write_colour(preset, index, rgb)
|
||||
except PresetError as exc:
|
||||
raise ApiError(str(exc)) from exc
|
||||
except PadError as exc:
|
||||
raise ApiError(str(exc), 503) from exc
|
||||
return {"ok": True, "offset": offset}
|
||||
|
||||
def bank(self, body: dict) -> dict:
|
||||
bank = body.get("bank")
|
||||
if isinstance(bank, bool) or bank not in (0, 1):
|
||||
raise ApiError("bank must be 0 or 1")
|
||||
with self.lock:
|
||||
try:
|
||||
set_bank(bank)
|
||||
except PadError as exc:
|
||||
raise ApiError(str(exc), 503) from exc
|
||||
return {"ok": True, "bank": bank}
|
||||
|
||||
def imported(self, raw: bytes) -> dict:
|
||||
try:
|
||||
return unpack(raw)
|
||||
except PresetError as exc:
|
||||
raise ApiError(str(exc)) from exc
|
||||
|
||||
def factory(self) -> dict:
|
||||
document = unpack(FACTORY_IMAGE.read_bytes())
|
||||
document["global"] = unpack_global(FACTORY_GLOBAL)
|
||||
return document
|
||||
|
||||
def exported(self, document: dict) -> bytes:
|
||||
try:
|
||||
return pack(document)
|
||||
except PresetError as exc:
|
||||
raise ApiError(str(exc)) from exc
|
||||
|
||||
|
||||
def make_server(host: str = "127.0.0.1", port: int = 8770) -> ThreadingHTTPServer:
|
||||
editor = Editor()
|
||||
handler = type("BoundHandler", (Handler,), {"editor": editor})
|
||||
server = ThreadingHTTPServer((host, port), handler)
|
||||
server.editor = editor # type: ignore[attr-defined]
|
||||
return server
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
editor: Editor
|
||||
|
||||
def log_message(self, fmt: str, *args) -> None:
|
||||
return
|
||||
|
||||
def _json(self, status: int, body: dict) -> None:
|
||||
raw = json.dumps(body).encode()
|
||||
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 _bytes(self, raw: bytes, content_type: str, filename: str | None = None) -> None:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
if filename:
|
||||
self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _read(self) -> bytes:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
return self.rfile.read(n) if n > 0 else b""
|
||||
|
||||
def _json_body(self) -> dict:
|
||||
raw = self._read()
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
body = json.loads(raw.decode("utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ApiError(f"invalid JSON: {exc}") from exc
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError("expected a JSON object")
|
||||
return body
|
||||
|
||||
def _static(self, rel: str) -> None:
|
||||
rel = rel.lstrip("/") or "index.html"
|
||||
path = (STATIC_DIR / rel).resolve()
|
||||
if STATIC_DIR.resolve() not in path.parents or not path.is_file():
|
||||
self.send_error(404)
|
||||
return
|
||||
ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
|
||||
if ctype.startswith("text/") or ctype.endswith(("javascript", "json")):
|
||||
ctype = f"{ctype}; charset=utf-8"
|
||||
self._bytes(path.read_bytes(), ctype)
|
||||
|
||||
def _dispatch(self, method: str) -> None:
|
||||
url = urlparse(self.path)
|
||||
editor = self.editor
|
||||
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.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
self._static(url.path)
|
||||
return
|
||||
route = (method, url.path)
|
||||
if route == ("GET", "/api/status"):
|
||||
self._json(200, editor.status())
|
||||
elif route == ("POST", "/api/load"):
|
||||
self._json(200, editor.load())
|
||||
elif route == ("POST", "/api/save"):
|
||||
self._json(200, editor.save(self._json_body()))
|
||||
elif route == ("POST", "/api/colour"):
|
||||
self._json(200, editor.colour(self._json_body()))
|
||||
elif route == ("POST", "/api/bank"):
|
||||
self._json(200, editor.bank(self._json_body()))
|
||||
elif route == ("POST", "/api/import"):
|
||||
raw = self._read()
|
||||
if len(raw) != IMAGE_LEN:
|
||||
raise ApiError(f"preset file is {len(raw)} bytes, expected {IMAGE_LEN}")
|
||||
self._json(200, editor.imported(raw))
|
||||
elif route == ("POST", "/api/factory"):
|
||||
self._json(200, editor.factory())
|
||||
elif route == ("POST", "/api/export"):
|
||||
self._bytes(editor.exported(self._json_body()), "application/octet-stream", "smc-pad-preset.bin")
|
||||
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")
|
||||
@@ -0,0 +1,490 @@
|
||||
const PAGE = 16;
|
||||
const state = {
|
||||
doc: null,
|
||||
saved: null,
|
||||
preset: 0,
|
||||
page: 2,
|
||||
bank: 0,
|
||||
kind: null,
|
||||
index: 0,
|
||||
};
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Colours are stored as the picker gives them, 0–255, as MidiSuite writes them.
|
||||
function cssColour(rgb) {
|
||||
return `rgb(${rgb.join(",")})`;
|
||||
}
|
||||
|
||||
function ink(rgb) {
|
||||
const [r, g, b] = rgb;
|
||||
return (r * 0.3 + g * 0.59 + b * 0.11) > 150 ? "#111" : "#f4f6fb";
|
||||
}
|
||||
|
||||
function hexColour(rgb) {
|
||||
return `#${rgb.map((part) => part.toString(16).padStart(2, "0")).join("")}`;
|
||||
}
|
||||
|
||||
function setStatus(text, kind) {
|
||||
const node = $("status");
|
||||
node.textContent = text;
|
||||
node.className = kind || "";
|
||||
}
|
||||
|
||||
function dirty() {
|
||||
return state.doc !== null && JSON.stringify(state.doc) !== state.saved;
|
||||
}
|
||||
|
||||
function preset() {
|
||||
return state.doc.presets[state.preset];
|
||||
}
|
||||
|
||||
function selected() {
|
||||
if (!state.doc || !state.kind) return null;
|
||||
const block = preset();
|
||||
if (state.kind === "pad") return block.pads[state.page * PAGE + state.index];
|
||||
if (state.kind === "knob") return block.knobs[state.bank * 8 + state.index];
|
||||
return block.buttons[state.index];
|
||||
}
|
||||
|
||||
function typeChoices(kind, current) {
|
||||
const known = (state.doc.types && state.doc.types[kind]) || [];
|
||||
const options = known.map((item) => ({ value: item.value, name: item.name }));
|
||||
if (!options.some((item) => item.value === current)) {
|
||||
const hex = current.toString(16).padStart(2, "0");
|
||||
options.push({ value: current, name: `0x${hex}` });
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
async function request(url, options) {
|
||||
const response = await fetch(url, options);
|
||||
const type = response.headers.get("Content-Type") || "";
|
||||
if (type.includes("application/json")) {
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new Error(body.error || response.statusText);
|
||||
return body;
|
||||
}
|
||||
if (!response.ok) throw new Error(response.statusText);
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
function mark() {
|
||||
const unsaved = dirty();
|
||||
$("save").disabled = !state.doc;
|
||||
$("export").disabled = !state.doc;
|
||||
$("save").classList.toggle("dirty", unsaved);
|
||||
return unsaved;
|
||||
}
|
||||
|
||||
function touch() {
|
||||
if (mark()) setStatus("Not saved on the pad.", "dirty");
|
||||
else setStatus("No unsaved edits.", "ok");
|
||||
}
|
||||
|
||||
function showEmpty(text, kind) {
|
||||
const node = $("empty");
|
||||
node.hidden = false;
|
||||
node.textContent = text;
|
||||
node.className = kind || "";
|
||||
$("board").classList.remove("ready");
|
||||
}
|
||||
|
||||
async function load(manual) {
|
||||
if (manual && dirty() && !window.confirm("Load from the pad and drop these edits?")) return;
|
||||
setStatus("Loading the pad…");
|
||||
showEmpty("Loading the pad…");
|
||||
try {
|
||||
state.doc = await request("/api/load", { method: "POST" });
|
||||
state.saved = JSON.stringify(state.doc);
|
||||
render();
|
||||
setStatus("Loaded from the pad.", "ok");
|
||||
} catch (error) {
|
||||
setStatus(error.message, "err");
|
||||
showEmpty(error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!state.doc) return;
|
||||
setStatus("Saving…");
|
||||
$("save").disabled = true;
|
||||
try {
|
||||
const body = await request("/api/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(state.doc),
|
||||
});
|
||||
state.saved = JSON.stringify(state.doc);
|
||||
setStatus(body.message, "ok");
|
||||
} catch (error) {
|
||||
setStatus(error.message, "err");
|
||||
}
|
||||
mark();
|
||||
}
|
||||
|
||||
async function exportFile() {
|
||||
if (!state.doc) return;
|
||||
try {
|
||||
const blob = await request("/api/export", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(state.doc),
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "smc-pad-preset.bin";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (error) {
|
||||
setStatus(error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
async function importFile(file) {
|
||||
setStatus("Reading file…");
|
||||
try {
|
||||
const raw = new Uint8Array(await file.arrayBuffer());
|
||||
state.doc = await request("/api/import", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
body: raw,
|
||||
});
|
||||
render();
|
||||
setStatus("Imported. Save to pad to store it.", "dirty");
|
||||
} catch (error) {
|
||||
setStatus(error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
function withBank(global, bank) {
|
||||
const raw = global.raw.slice(0, 22) + bank.toString(16).padStart(2, "0") + global.raw.slice(24);
|
||||
return { ...global, bank, raw };
|
||||
}
|
||||
|
||||
async function switchBank(bank) {
|
||||
try {
|
||||
await request("/api/bank", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ bank }),
|
||||
});
|
||||
const wasDirty = dirty();
|
||||
state.doc.global = withBank(state.doc.global, bank);
|
||||
if (!wasDirty) {
|
||||
const saved = JSON.parse(state.saved);
|
||||
saved.global = withBank(saved.global, bank);
|
||||
state.saved = JSON.stringify(saved);
|
||||
}
|
||||
state.page = bank ? 7 : 2;
|
||||
$("page").value = String(state.page);
|
||||
state.kind = state.kind === "pad" ? null : state.kind;
|
||||
render();
|
||||
setStatus(`Pad bank ${bank + 1}.`, "ok");
|
||||
} catch (error) {
|
||||
setStatus(error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
async function factory() {
|
||||
if (!window.confirm("Replace all eight presets with the factory settings? Nothing reaches the pad until you Save.")) return;
|
||||
setStatus("Reading the factory preset…");
|
||||
try {
|
||||
state.doc = await request("/api/factory", { method: "POST" });
|
||||
render();
|
||||
setStatus("Factory settings loaded. Save to pad to store them.", "dirty");
|
||||
} catch (error) {
|
||||
setStatus(error.message, "err");
|
||||
}
|
||||
mark();
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (!state.doc) return;
|
||||
$("board").classList.add("ready");
|
||||
renderGlobal();
|
||||
renderPresets();
|
||||
renderPages();
|
||||
renderPads();
|
||||
renderKnobs();
|
||||
renderButtons();
|
||||
renderInspector();
|
||||
mark();
|
||||
}
|
||||
|
||||
function renderGlobal() {
|
||||
const row = $("global");
|
||||
row.replaceChildren();
|
||||
const block = state.doc.global;
|
||||
if (!block) return;
|
||||
const fields = [
|
||||
["Tempo", "tempo", 1, 999],
|
||||
["Swing", "swing", 0, 255],
|
||||
["Pad curve", "curve", 0, 255],
|
||||
["Transpose", "transpose", -128, 127],
|
||||
];
|
||||
for (const [label, key, min, max] of fields) {
|
||||
row.append(field(label, numberInput(block, key, min, max)));
|
||||
}
|
||||
const toggle = document.createElement("button");
|
||||
toggle.type = "button";
|
||||
toggle.textContent = `Pad bank ${block.bank + 1}`;
|
||||
toggle.title = "Switch the pad's bank now, as MidiSuite does";
|
||||
toggle.addEventListener("click", () => switchBank(1 - block.bank));
|
||||
row.append(toggle);
|
||||
}
|
||||
|
||||
function renderPresets() {
|
||||
const row = $("presets");
|
||||
row.replaceChildren();
|
||||
state.doc.presets.forEach((_preset, index) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = String(index + 1);
|
||||
button.classList.toggle("selected", index === state.preset);
|
||||
button.addEventListener("click", () => {
|
||||
state.preset = index;
|
||||
render();
|
||||
});
|
||||
row.append(button);
|
||||
});
|
||||
}
|
||||
|
||||
function renderPages() {
|
||||
const select = $("page");
|
||||
const current = select.value;
|
||||
select.replaceChildren();
|
||||
const order = [2, 7, 0, 1, 3, 4, 5, 6];
|
||||
const names = { 2: "Bank 1", 7: "Bank 2", 3: "Page 4 (not lit)" };
|
||||
for (const page of order) {
|
||||
const pads = preset().pads.slice(page * PAGE, page * PAGE + PAGE);
|
||||
const option = document.createElement("option");
|
||||
option.value = String(page);
|
||||
const name = names[page] || `Page ${page + 1}`;
|
||||
option.textContent = `${name} · notes ${pads[0].note}–${pads[PAGE - 1].note}`;
|
||||
select.append(option);
|
||||
}
|
||||
select.value = current || String(state.page);
|
||||
state.page = Number(select.value);
|
||||
const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE);
|
||||
$("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`;
|
||||
}
|
||||
|
||||
function paint(node, rgb) {
|
||||
node.style.background = cssColour(rgb);
|
||||
node.style.color = ink(rgb);
|
||||
}
|
||||
|
||||
function renderPads() {
|
||||
const grid = $("pads");
|
||||
grid.replaceChildren();
|
||||
const pads = preset().pads;
|
||||
for (let row = 3; row >= 0; row -= 1) {
|
||||
for (let col = 0; col < 4; col += 1) {
|
||||
const index = row * 4 + col;
|
||||
const pad = pads[state.page * PAGE + index];
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "pad";
|
||||
button.textContent = String(index + 1);
|
||||
paint(button, pad.rgb);
|
||||
button.style.opacity = pad.led ? "" : "0.35";
|
||||
button.classList.toggle("selected", state.kind === "pad" && state.index === index);
|
||||
button.addEventListener("click", () => select("pad", index));
|
||||
grid.append(button);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderKnobs() {
|
||||
const row = $("knobs");
|
||||
row.replaceChildren();
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
const knob = preset().knobs[state.bank * 8 + index];
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "knob";
|
||||
button.textContent = String(state.bank * 8 + index + 1);
|
||||
button.title = `CC ${knob.number}`;
|
||||
button.classList.toggle("selected", state.kind === "knob" && state.index === index);
|
||||
button.addEventListener("click", () => select("knob", index));
|
||||
row.append(button);
|
||||
}
|
||||
}
|
||||
|
||||
function renderButtons() {
|
||||
const row = $("buttons");
|
||||
row.replaceChildren();
|
||||
preset().buttons.forEach((button, index) => {
|
||||
const node = document.createElement("button");
|
||||
node.type = "button";
|
||||
node.className = "btn";
|
||||
node.textContent = button.name;
|
||||
node.classList.toggle("selected", state.kind === "button" && state.index === index);
|
||||
node.addEventListener("click", () => select("button", index));
|
||||
row.append(node);
|
||||
});
|
||||
}
|
||||
|
||||
let colourTimer = 0;
|
||||
|
||||
function paintColour(index, rgb) {
|
||||
const edited = state.preset;
|
||||
preset().pads[index].rgb = rgb.slice();
|
||||
renderPads();
|
||||
window.clearTimeout(colourTimer);
|
||||
colourTimer = window.setTimeout(() => sendColour(edited, index, rgb), 180);
|
||||
}
|
||||
|
||||
async function sendColour(preset, index, rgb) {
|
||||
try {
|
||||
await request("/api/colour", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ preset, index, rgb }),
|
||||
});
|
||||
} catch (error) {
|
||||
setStatus(error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
function select(kind, index) {
|
||||
state.kind = kind;
|
||||
state.index = index;
|
||||
render();
|
||||
}
|
||||
|
||||
function field(label, node) {
|
||||
const wrap = document.createElement("label");
|
||||
wrap.className = "field";
|
||||
wrap.append(label, node);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function numberInput(item, key, min, max) {
|
||||
const input = document.createElement("input");
|
||||
input.type = "number";
|
||||
input.min = String(min);
|
||||
input.max = String(max);
|
||||
input.value = String(item[key]);
|
||||
input.addEventListener("input", () => {
|
||||
const value = Number(input.value);
|
||||
if (!Number.isInteger(value) || value < min || value > max) return;
|
||||
item[key] = value;
|
||||
if (key === "led") renderPads();
|
||||
if (key === "note") {
|
||||
const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE);
|
||||
$("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`;
|
||||
}
|
||||
touch();
|
||||
});
|
||||
return input;
|
||||
}
|
||||
|
||||
function renderInspector() {
|
||||
const aside = $("inspector");
|
||||
const item = selected();
|
||||
aside.replaceChildren();
|
||||
const title = document.createElement("h2");
|
||||
if (!item) {
|
||||
title.textContent = "Control";
|
||||
const note = document.createElement("p");
|
||||
note.className = "muted";
|
||||
note.textContent = "Pick a pad, knob, or button.";
|
||||
aside.append(title, note);
|
||||
return;
|
||||
}
|
||||
if (state.kind === "pad") title.textContent = `Pad ${state.index + 1}`;
|
||||
else if (state.kind === "knob") title.textContent = `Knob ${state.bank * 8 + state.index + 1}`;
|
||||
else title.textContent = item.name;
|
||||
aside.append(title);
|
||||
|
||||
if (state.kind !== "pad") {
|
||||
const type = document.createElement("select");
|
||||
typeChoices(state.kind, item.type).forEach((option) => {
|
||||
const node = document.createElement("option");
|
||||
node.value = String(option.value);
|
||||
node.textContent = option.name;
|
||||
node.selected = option.value === item.type;
|
||||
type.append(node);
|
||||
});
|
||||
type.addEventListener("change", () => {
|
||||
item.type = Number(type.value);
|
||||
touch();
|
||||
});
|
||||
aside.append(field(state.kind === "button" ? "Mode" : "Type", type));
|
||||
}
|
||||
aside.append(field("Channel", numberInput(item, "channel", 1, 16)));
|
||||
|
||||
if (state.kind === "pad") {
|
||||
aside.append(field("Note", numberInput(item, "note", 0, 127)));
|
||||
aside.append(field("Min velocity", numberInput(item, "min", 0, 127)));
|
||||
aside.append(field("Max velocity", numberInput(item, "max", 0, 127)));
|
||||
const colour = document.createElement("input");
|
||||
colour.type = "color";
|
||||
colour.value = hexColour(item.rgb);
|
||||
colour.addEventListener("input", () => {
|
||||
const hex = colour.value;
|
||||
const rgb = [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16));
|
||||
paintColour(state.page * PAGE + state.index, rgb);
|
||||
touch();
|
||||
});
|
||||
aside.append(field("Colour", colour));
|
||||
aside.append(field("Led", numberInput(item, "led", 0, 255)));
|
||||
} else if (state.kind === "knob") {
|
||||
aside.append(field("CC", numberInput(item, "number", 0, 127)));
|
||||
aside.append(field("Speed", numberInput(item, "speed", 0, 127)));
|
||||
aside.append(field("Min", numberInput(item, "left", 0, 127)));
|
||||
aside.append(field("Max", numberInput(item, "right", 0, 127)));
|
||||
if (state.doc.relative) {
|
||||
const hint = document.createElement("p");
|
||||
hint.className = "hint";
|
||||
hint.textContent = "Relative sends the left value one way and the right value the other.";
|
||||
aside.append(hint);
|
||||
}
|
||||
} else {
|
||||
aside.append(field("CC", numberInput(item, "number", 0, 127)));
|
||||
aside.append(field("Value 1", numberInput(item, "min", 0, 127)));
|
||||
aside.append(field("Value 2", numberInput(item, "max", 0, 127)));
|
||||
aside.append(field("Led", numberInput(item, "led", 0, 255)));
|
||||
const sysex = document.createElement("input");
|
||||
sysex.type = "text";
|
||||
sysex.value = item.sysex;
|
||||
sysex.spellcheck = false;
|
||||
sysex.addEventListener("input", () => {
|
||||
const hex = sysex.value.replace(/\s+/g, "").toLowerCase();
|
||||
if (hex.length % 2 || /[^0-9a-f]/.test(hex) || hex.length > 32) return;
|
||||
item.sysex = hex;
|
||||
touch();
|
||||
});
|
||||
aside.append(field("SysEx", sysex));
|
||||
}
|
||||
|
||||
const hint = document.createElement("p");
|
||||
hint.className = "hint";
|
||||
hint.textContent = "A pad colour lights the lamp as you pick it. Save keeps every edit after a power cycle.";
|
||||
aside.append(hint);
|
||||
}
|
||||
|
||||
$("load").addEventListener("click", () => load(true));
|
||||
$("save").addEventListener("click", save);
|
||||
$("export").addEventListener("click", exportFile);
|
||||
$("factory").addEventListener("click", factory);
|
||||
$("import").addEventListener("change", () => {
|
||||
const file = $("import").files[0];
|
||||
$("import").value = "";
|
||||
if (file) importFile(file);
|
||||
});
|
||||
$("page").addEventListener("change", () => {
|
||||
state.page = Number($("page").value);
|
||||
state.kind = state.kind === "pad" ? null : state.kind;
|
||||
render();
|
||||
});
|
||||
$("bank").addEventListener("change", () => {
|
||||
state.bank = Number($("bank").value);
|
||||
state.kind = state.kind === "knob" ? null : state.kind;
|
||||
render();
|
||||
});
|
||||
|
||||
load(false);
|
||||
@@ -0,0 +1,46 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Pad Controller</title>
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>Pad Controller</h1>
|
||||
<button id="load" type="button">Load</button>
|
||||
<button id="save" type="button" class="primary" disabled>Save to pad</button>
|
||||
<button id="factory" type="button">Factory reset</button>
|
||||
<button id="export" type="button" disabled>Export</button>
|
||||
<label class="file">Import
|
||||
<input id="import" type="file" accept=".bin,application/octet-stream">
|
||||
</label>
|
||||
<span class="spacer"></span>
|
||||
<span id="status">Load the preset from the pad.</span>
|
||||
</header>
|
||||
<main>
|
||||
<section id="board">
|
||||
<p id="empty">Loading the pad…</p>
|
||||
<div class="row" id="global"></div>
|
||||
<div class="row" id="presets"></div>
|
||||
<div class="row">
|
||||
<label>Pad page <select id="page"></select></label>
|
||||
<label>Knob bank <select id="bank">
|
||||
<option value="0">1 · knobs 1–8</option>
|
||||
<option value="1">2 · knobs 9–16</option>
|
||||
</select></label>
|
||||
<span id="page-notes" class="muted"></span>
|
||||
</div>
|
||||
<div id="pads"></div>
|
||||
<div id="knobs"></div>
|
||||
<div id="buttons"></div>
|
||||
</section>
|
||||
<aside id="inspector">
|
||||
<h2>Control</h2>
|
||||
<p class="muted">Load a preset, then pick a pad, knob, or button.</p>
|
||||
</aside>
|
||||
</main>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,102 @@
|
||||
:root {
|
||||
--bg: #15171c;
|
||||
--panel: #1e2129;
|
||||
--panel-2: #262a34;
|
||||
--line: #343946;
|
||||
--text: #e6e8ee;
|
||||
--muted: #8d94a6;
|
||||
--accent: #5aa9ff;
|
||||
--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: 10px;
|
||||
padding: 8px 14px;
|
||||
background: var(--panel);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
header h1 { font-size: 15px; margin: 0 8px 0 0; }
|
||||
.spacer { flex: 1; }
|
||||
#status { color: var(--muted); max-width: 46ch; }
|
||||
#status.err { color: var(--danger); }
|
||||
#status.ok { color: var(--ok); }
|
||||
#status.dirty { color: var(--accent); }
|
||||
|
||||
button, select, input[type="number"], input[type="text"] {
|
||||
background: var(--panel-2);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
padding: 6px 10px;
|
||||
font: inherit;
|
||||
}
|
||||
button { cursor: pointer; }
|
||||
button:disabled { opacity: 0.45; cursor: default; }
|
||||
button.primary { background: #245a9e; border-color: #3d7dcc; }
|
||||
button.primary.dirty { background: #1e6b38; border-color: var(--ok); }
|
||||
button.selected, .pad.selected, .knob.selected, .btn.selected {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
label.file { color: var(--muted); }
|
||||
label.file input { display: none; }
|
||||
label.file { cursor: pointer; border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; background: var(--panel-2); color: var(--text); }
|
||||
|
||||
main { display: flex; min-height: 0; flex: 1; }
|
||||
#empty { color: var(--muted); margin: 48px 0; }
|
||||
#empty.err { color: var(--danger); }
|
||||
#board.ready #empty { display: none; }
|
||||
#board, #inspector { padding: 16px; }
|
||||
#board { flex: 1; }
|
||||
#inspector {
|
||||
width: 320px;
|
||||
background: var(--panel);
|
||||
border-left: 1px solid var(--line);
|
||||
overflow: auto;
|
||||
}
|
||||
#inspector h2 { margin: 0 0 12px; font-size: 15px; }
|
||||
.muted { color: var(--muted); }
|
||||
.row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; }
|
||||
.row label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
|
||||
|
||||
#presets { gap: 6px; }
|
||||
#pads {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 76px);
|
||||
gap: 8px;
|
||||
margin: 8px 0 18px;
|
||||
}
|
||||
.pad, .knob, .btn {
|
||||
border: 1px solid #0008;
|
||||
color: #111;
|
||||
font-weight: 650;
|
||||
text-align: center;
|
||||
}
|
||||
.pad { height: 64px; border-radius: 8px; }
|
||||
.knob {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
border-radius: 50%;
|
||||
background: #d7dbe6;
|
||||
}
|
||||
#knobs, #buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; }
|
||||
.btn { min-width: 72px; height: 36px; border-radius: 6px; background: #c9ceda; }
|
||||
.field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px; color: var(--muted); }
|
||||
.field input, .field select { width: 100%; }
|
||||
.hint { color: var(--muted); margin-top: 8px; }
|
||||
#global .field { margin-bottom: 0; }
|
||||
#global input { width: 90px; }
|
||||
@@ -0,0 +1,81 @@
|
||||
"""SINCO / M-VAVE SysEx codec used by MidiSuite and the SMC-PAD."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
MEM_GLOBAL = 4
|
||||
MEM_PRESET = 5
|
||||
CMD_ACK = 0x00
|
||||
CMD_WRITE = 0x22
|
||||
CMD_READ = 0x23
|
||||
RAM = 0x80000000
|
||||
|
||||
|
||||
def encode(source: bytes) -> bytes:
|
||||
"""Pack a protocol message into the 7-bit SysEx body."""
|
||||
bit_num = 0
|
||||
accum = 0
|
||||
out = bytearray()
|
||||
for byte in source:
|
||||
accum = ((byte << (bit_num & 0x1F)) | accum) & 0xFFFFFFFF
|
||||
bit_num += 1
|
||||
while True:
|
||||
out.append(accum & 0x7F)
|
||||
accum = (accum >> 7) & 0xFFFFFFFF
|
||||
if bit_num < 7:
|
||||
break
|
||||
bit_num -= 7
|
||||
out.append(accum & 0x7F)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def decode(source: bytes) -> bytes:
|
||||
bit_num = 0
|
||||
last_val = 0
|
||||
out = bytearray()
|
||||
for byte in source:
|
||||
accum = byte & (0xFFFFFFFF >> (32 - bit_num) if bit_num else 0)
|
||||
if bit_num > 0:
|
||||
out.append((last_val & 0x7F) | ((accum << (8 - bit_num)) & 0xFF))
|
||||
last_val = byte >> bit_num
|
||||
bit_num = (bit_num + 1) % 8
|
||||
if last_val > 0:
|
||||
out.append(last_val)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def checksum(payload: bytes) -> int:
|
||||
total = 0
|
||||
for byte in payload:
|
||||
total = (total + byte) & 0xFF
|
||||
return (~total) & 0xFF
|
||||
|
||||
|
||||
def frame(command: int, payload: bytes) -> list[int]:
|
||||
data = bytearray((0x00, 0x59, command))
|
||||
data += len(payload).to_bytes(3, "little")
|
||||
data += payload
|
||||
data.append(checksum(payload))
|
||||
return [0xF0, *encode(bytes(data)), 0xF7]
|
||||
|
||||
|
||||
def read_request(address: int, size: int, memory: int = MEM_PRESET) -> list[int]:
|
||||
payload = bytes([memory]) + address.to_bytes(4, "little") + size.to_bytes(3, "little")
|
||||
return frame(CMD_READ, payload)
|
||||
|
||||
|
||||
def write_request(address: int, data: bytes, memory: int = MEM_PRESET) -> list[int]:
|
||||
payload = bytes([memory]) + address.to_bytes(4, "little") + len(data).to_bytes(3, "little") + data
|
||||
return frame(CMD_WRITE, payload)
|
||||
|
||||
|
||||
def save_request() -> list[int]:
|
||||
"""Commit the running preset. MidiSuite's Save is this empty write."""
|
||||
return write_request(0, b"")
|
||||
|
||||
|
||||
def payload_data(decoded: bytes) -> bytes:
|
||||
"""Bytes after the type, address, and length in a read reply."""
|
||||
if decoded[:3] != b"\x00\x59\x23":
|
||||
raise ValueError(f"unexpected reply {decoded[:8].hex()}")
|
||||
payload = decoded[6:-1]
|
||||
return payload[8:]
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install the SMC-PAD pad controller as a systemd user service and start it.
|
||||
#
|
||||
# padcontroller/systemd/install.sh # install, enable, start
|
||||
# padcontroller/systemd/install.sh --no-lamps # pass options to the pad controller
|
||||
# padcontroller/systemd/install.sh --no-enable # install only; start it with
|
||||
# # systemctl --user start padcontroller
|
||||
# padcontroller/systemd/install.sh --uninstall
|
||||
#
|
||||
# Logs: journalctl --user -u padcontroller -f
|
||||
set -euo pipefail
|
||||
|
||||
UNIT=padcontroller.service
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT="$(cd "$HERE/../.." && pwd)"
|
||||
DEST="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
|
||||
|
||||
if [[ "${1:-}" == "--uninstall" ]]; then
|
||||
systemctl --user disable --now "$UNIT" 2>/dev/null || true
|
||||
rm -f "$DEST/$UNIT"
|
||||
systemctl --user daemon-reload
|
||||
echo "Removed $UNIT."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
PYTHON="$ROOT/.venv/bin/python"
|
||||
[[ -x "$PYTHON" ]] || PYTHON="$(command -v python3)"
|
||||
"$PYTHON" -c "import rtmidi" 2>/dev/null || {
|
||||
echo "$PYTHON cannot import rtmidi. Run pipenv install (or pip install python-rtmidi) first." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
ENABLE=1
|
||||
if [[ "${1:-}" == "--no-enable" ]]; then
|
||||
ENABLE=
|
||||
shift
|
||||
fi
|
||||
|
||||
ARGS="$*"
|
||||
mkdir -p "$DEST"
|
||||
sed -e "s|@ROOT@|$ROOT|g" -e "s|@PYTHON@|$PYTHON|g" -e "s|@ARGS@|$ARGS|g" \
|
||||
"$HERE/$UNIT" >"$DEST/$UNIT"
|
||||
|
||||
systemctl --user daemon-reload
|
||||
if [[ -z "$ENABLE" ]]; then
|
||||
# Undo an earlier enable, so it does not start at login here.
|
||||
systemctl --user disable "$UNIT" 2>/dev/null || true
|
||||
echo "Installed $DEST/$UNIT. It does not start at login."
|
||||
echo "Start it with: systemctl --user start padcontroller"
|
||||
exit 0
|
||||
fi
|
||||
systemctl --user enable "$UNIT"
|
||||
systemctl --user restart "$UNIT"
|
||||
echo "Installed $DEST/$UNIT and started it."
|
||||
systemctl --user --no-pager status "$UNIT" | head -5 || true
|
||||
@@ -0,0 +1,22 @@
|
||||
# SMC-PAD pad controller (padcontroller.midi) as a systemd user service.
|
||||
# install.sh fills in @ROOT@, @PYTHON@ and @ARGS@ and copies it to
|
||||
# ~/.config/systemd/user/.
|
||||
|
||||
[Unit]
|
||||
Description=SMC-PAD pad controller (virtual port "padcontroller")
|
||||
After=sound.target
|
||||
# Keep retrying while the pad is switched off or not paired yet.
|
||||
StartLimitIntervalSec=0
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=@ROOT@
|
||||
ExecStart=@PYTHON@ -m padcontroller.midi @ARGS@
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
# The pad controller closes its ports on Ctrl+C.
|
||||
KillSignal=SIGINT
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Virtual pad: press SMC-PAD pads and turn knobs from the command line or a test.
|
||||
|
||||
Sends into the pad controller's input port (padcontroller-in), so presses go
|
||||
through the same Play layer and CC smoothing as the real pad before QLC+ sees
|
||||
them. The real pad stays connected; both feed the same port.
|
||||
|
||||
Before sending it checks that the workspace QLC+ opened last is shows/test.qxw,
|
||||
which only sends Art-Net to 127.0.0.1 (the simulator). Pass --force to skip that.
|
||||
|
||||
Usage:
|
||||
.venv/bin/python -m padcontroller.virtualpad press 52 # note 52 on channel 10
|
||||
.venv/bin/python -m padcontroller.virtualpad press --pad 17 # pad number from shows/midi_map.json
|
||||
.venv/bin/python -m padcontroller.virtualpad press 52 --play # with Play held (52 -> 68)
|
||||
.venv/bin/python -m padcontroller.virtualpad cc 34 64 # knob CC 34 to 64 on channel 1
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import configparser
|
||||
import json
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Iterator
|
||||
|
||||
import rtmidi
|
||||
|
||||
from padcontroller.layer import PLAY_CC
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MIDI_MAP = ROOT / "shows" / "midi_map.json"
|
||||
TEST_SHOW = ROOT / "shows" / "test.qxw"
|
||||
QLC_CONF = Path.home() / ".config" / "qlcplus" / "Q Light Controller Plus.conf"
|
||||
TARGET_CLIENT = "padcontroller-in"
|
||||
# The SMC-PAD sends pads on MIDI channel 10 and knobs on channel 1 (0-based here).
|
||||
PAD_CHANNEL = 9
|
||||
KNOB_CHANNEL = 0
|
||||
|
||||
|
||||
def last_workspace(conf: Path = QLC_CONF) -> Path | None:
|
||||
"""The workspace QLC+ opened most recently, from its recent-files list."""
|
||||
parser = configparser.ConfigParser(interpolation=None, strict=False)
|
||||
try:
|
||||
parser.read(conf)
|
||||
recent = parser.get("workspace", "recent0")
|
||||
except (configparser.Error, OSError):
|
||||
return None
|
||||
path = Path(recent)
|
||||
return path if path.is_absolute() else Path.home() / path
|
||||
|
||||
|
||||
def check_test_show(conf: Path = QLC_CONF) -> None:
|
||||
"""Refuse to drive QLC+ unless its last workspace is the 127.0.0.1-only test show."""
|
||||
ws = last_workspace(conf)
|
||||
if ws is None or ws.resolve() != TEST_SHOW.resolve():
|
||||
raise SystemExit(
|
||||
f"QLC+'s last workspace is {ws or '(unknown)'}, not {TEST_SHOW.relative_to(ROOT)}. "
|
||||
"Open the test show in QLC+ (or pass --force) so presses can't reach the real rig."
|
||||
)
|
||||
|
||||
|
||||
def pad_note(pad: int, midi_map: Path = MIDI_MAP) -> tuple[int, int]:
|
||||
"""(channel, note) for a pad number in shows/midi_map.json."""
|
||||
for entry in json.loads(midi_map.read_text())["pads"]:
|
||||
if entry["pad"] == pad:
|
||||
return entry["channel"], entry["note"]
|
||||
raise SystemExit(f"Pad {pad} is not in {midi_map.relative_to(ROOT)}")
|
||||
|
||||
|
||||
class VirtualPad:
|
||||
"""An ALSA MIDI output linked to padcontroller-in."""
|
||||
|
||||
def __init__(self, target: str = TARGET_CLIENT) -> None:
|
||||
self.out = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="virtualpad")
|
||||
ports = self.out.get_ports()
|
||||
i = next((i for i, name in enumerate(ports) if name.startswith(target + ":")), None)
|
||||
if i is None:
|
||||
raise RuntimeError(
|
||||
f"No {target} MIDI port; is the padcontroller service running? Ports:\n "
|
||||
+ "\n ".join(ports or ["(none)"])
|
||||
)
|
||||
self.out.open_port(i, "virtualpad")
|
||||
|
||||
def close(self) -> None:
|
||||
self.out.close_port()
|
||||
|
||||
def __enter__(self) -> VirtualPad:
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: object) -> None:
|
||||
self.close()
|
||||
|
||||
def send(self, data: list[int]) -> None:
|
||||
self.out.send_message(data)
|
||||
|
||||
def press(self, note: int, channel: int = PAD_CHANNEL, velocity: int = 127, hold: float = 0.05) -> None:
|
||||
"""Note on, wait hold seconds, note off: one tap of a pad."""
|
||||
self.send([0x90 | channel, note, velocity])
|
||||
time.sleep(hold)
|
||||
self.send([0x80 | channel, note, 0])
|
||||
|
||||
def cc(self, cc: int, value: int, channel: int = KNOB_CHANNEL) -> None:
|
||||
self.send([0xB0 | channel, cc, max(0, min(127, value))])
|
||||
|
||||
@contextmanager
|
||||
def play(self) -> Iterator[None]:
|
||||
"""Hold Play for the block, so bank 2 pads go out a layer up."""
|
||||
self.cc(PLAY_CC, 127)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.cc(PLAY_CC, 0)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--force", action="store_true", help="skip the check that QLC+ has the test show open")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
p = sub.add_parser("press", help="tap a pad")
|
||||
p.add_argument("note", type=int, nargs="?", help="MIDI note (channel 10 unless --channel)")
|
||||
p.add_argument("--pad", type=int, help="pad number from shows/midi_map.json instead of a note")
|
||||
p.add_argument("--channel", type=int, default=PAD_CHANNEL + 1, help="MIDI channel 1-16 (default 10)")
|
||||
p.add_argument("--hold", type=float, default=0.05, help="seconds between note on and off")
|
||||
p.add_argument("--play", action="store_true", help="hold Play while pressing")
|
||||
c = sub.add_parser("cc", help="set a knob")
|
||||
c.add_argument("cc", type=int)
|
||||
c.add_argument("value", type=int)
|
||||
c.add_argument("--channel", type=int, default=KNOB_CHANNEL + 1, help="MIDI channel 1-16 (default 1)")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not args.force:
|
||||
check_test_show()
|
||||
with VirtualPad() as pad:
|
||||
if args.cmd == "cc":
|
||||
pad.cc(args.cc, args.value, args.channel - 1)
|
||||
print(f"CC {args.cc} = {args.value} (channel {args.channel})")
|
||||
return
|
||||
if args.pad is not None:
|
||||
channel, note = pad_note(args.pad)
|
||||
elif args.note is not None:
|
||||
channel, note = args.channel - 1, args.note
|
||||
else:
|
||||
raise SystemExit("press needs a note or --pad")
|
||||
if args.play:
|
||||
with pad.play():
|
||||
pad.press(note, channel, hold=args.hold)
|
||||
else:
|
||||
pad.press(note, channel, hold=args.hold)
|
||||
print(f"Pressed note {note} (channel {channel + 1}){' with Play held' if args.play else ''}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
"""Web editor for mover patterns, driven by the SMC-PAD and the page."""
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Dev runner: restart the server when Python changes.
|
||||
|
||||
The page reloads itself when static files change, and again after the
|
||||
server comes back from a Python restart.
|
||||
|
||||
pipenv run pattern
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
PKG = Path(__file__).resolve().parent
|
||||
ROOT = PKG.parent
|
||||
|
||||
|
||||
def stamp(root: Path, suffix: str) -> dict[str, int]:
|
||||
found: dict[str, int] = {}
|
||||
for path in root.rglob(f"*{suffix}"):
|
||||
if "__pycache__" in path.parts or not path.is_file():
|
||||
continue
|
||||
found[str(path)] = path.stat().st_mtime_ns
|
||||
return found
|
||||
|
||||
|
||||
def stop_child(proc: subprocess.Popen) -> None:
|
||||
if proc.poll() is not None:
|
||||
return
|
||||
proc.send_signal(signal.SIGINT)
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
os.chdir(ROOT)
|
||||
cmd = [sys.executable, "-m", "pattern_pad.server", *sys.argv[1:]]
|
||||
print("pattern editor — reload on Python and page changes", flush=True)
|
||||
while True:
|
||||
py = stamp(PKG, ".py")
|
||||
parent = Path(__file__).stat().st_mtime_ns
|
||||
proc = subprocess.Popen(cmd)
|
||||
try:
|
||||
while proc.poll() is None:
|
||||
time.sleep(0.25)
|
||||
if Path(__file__).stat().st_mtime_ns != parent:
|
||||
stop_child(proc)
|
||||
os.execv(sys.executable, [sys.executable, "-m", "pattern_pad", *sys.argv[1:]])
|
||||
if stamp(PKG, ".py") != py:
|
||||
print("reload backend", flush=True)
|
||||
stop_child(proc)
|
||||
break
|
||||
else:
|
||||
code = proc.returncode or 0
|
||||
if code not in (0, -signal.SIGINT, 128 + signal.SIGINT):
|
||||
print(f"server exited ({code})", flush=True)
|
||||
return code
|
||||
return 0
|
||||
except KeyboardInterrupt:
|
||||
print("\nstopped", flush=True)
|
||||
stop_child(proc)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,386 @@
|
||||
"""Corner aims, SMC-PAD input, and Art-Net output for the pattern editor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPTS = ROOT / "scripts"
|
||||
if str(SCRIPTS) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
from cabaret_movers import ( # noqa: E402
|
||||
M1_ADDR,
|
||||
M2_ADDR,
|
||||
ArtNetSender,
|
||||
Mover,
|
||||
clamp,
|
||||
discover_artnet_node,
|
||||
)
|
||||
|
||||
DEFAULT_PATH = ROOT / "shows" / "pad_pattern.json"
|
||||
FOCUS_FULL = 255
|
||||
|
||||
# SMC-PAD preset 1. Pad 1 (bottom-left) is note 36, counting right then up.
|
||||
PAD_NOTES = {
|
||||
48: "front_left", # pad 13
|
||||
49: "front_right", # pad 14
|
||||
44: "back_left", # pad 9
|
||||
45: "back_right", # pad 10
|
||||
}
|
||||
CC_PAN = 16 # knob 7
|
||||
CC_TILT = 80 # knob 8
|
||||
CC_ROTATE = 17 # knob 5
|
||||
|
||||
CORNERS = ("front_left", "front_right", "back_left", "back_right")
|
||||
MODES = ("hold", "box", "cross", "circle", "figure8")
|
||||
ROUTES = {
|
||||
"box": ("front_left", "front_right", "back_right", "back_left"),
|
||||
"cross": ("front_left", "back_right", "front_right", "back_left"),
|
||||
"circle": ("front_left", "front_right", "back_right", "back_left"),
|
||||
}
|
||||
|
||||
NOTE_ON_RE = re.compile(r"Note on\s+\d+,\s+note (\d+),\s+velocity (\d+)")
|
||||
CC_RE = re.compile(r"Control change\s+\d+,\s+controller (\d+),\s+value (\d+)")
|
||||
CLIENT_RE = re.compile(r"^client (\d+): '([^']*)'")
|
||||
PORT_RE = re.compile(r"^\s+(\d+) '([^']*)'")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Aim:
|
||||
pan: int = 133
|
||||
tilt: int = 113
|
||||
rotate: int = 0
|
||||
|
||||
def clamped(self) -> Aim:
|
||||
return Aim(clamp(self.pan), clamp(self.tilt), clamp(self.rotate))
|
||||
|
||||
def as_dict(self) -> dict[str, int]:
|
||||
return {"pan": self.pan, "tilt": self.tilt, "rotate": self.rotate}
|
||||
|
||||
|
||||
def encoder_delta(value: int) -> int:
|
||||
"""Relative encoder step. 1..63 clockwise, 65..127 counter-clockwise."""
|
||||
if value <= 0 or value == 64 or value > 127:
|
||||
return 0
|
||||
if value < 64:
|
||||
return value
|
||||
return value - 128
|
||||
|
||||
|
||||
def lerp_aim(a: Aim, b: Aim, frac: float) -> Aim:
|
||||
def mix(x: int, y: int) -> int:
|
||||
return clamp(x + (y - x) * frac)
|
||||
|
||||
return Aim(mix(a.pan, b.pan), mix(a.tilt, b.tilt), mix(a.rotate, b.rotate))
|
||||
|
||||
|
||||
def ease(frac: float) -> float:
|
||||
return 0.5 - 0.5 * math.cos(math.pi * frac)
|
||||
|
||||
|
||||
class Pattern:
|
||||
def __init__(self, corners: dict[str, Aim]):
|
||||
self.corners = corners
|
||||
self.selected = "front_left"
|
||||
self.mode = "hold"
|
||||
self.loop_s = 6.0
|
||||
self.t0 = time.monotonic()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def select(self, name: str) -> None:
|
||||
if name not in self.corners:
|
||||
raise ValueError("Unknown corner")
|
||||
with self._lock:
|
||||
self.selected = name
|
||||
self.mode = "hold"
|
||||
|
||||
def nudge(self, channel: str, delta: int) -> None:
|
||||
if delta == 0:
|
||||
return
|
||||
with self._lock:
|
||||
aim = self.corners[self.selected]
|
||||
if channel == "pan":
|
||||
aim.pan = clamp(aim.pan + delta)
|
||||
elif channel == "tilt":
|
||||
aim.tilt = clamp(aim.tilt + delta)
|
||||
elif channel == "rotate":
|
||||
aim.rotate = clamp(aim.rotate + delta)
|
||||
|
||||
def set_aim(self, pan: int, tilt: int, rotate: int) -> None:
|
||||
with self._lock:
|
||||
aim = self.corners[self.selected]
|
||||
aim.pan = clamp(pan)
|
||||
aim.tilt = clamp(tilt)
|
||||
aim.rotate = clamp(rotate)
|
||||
|
||||
def play(self, mode: str) -> None:
|
||||
if mode not in MODES:
|
||||
raise ValueError("Unknown pattern")
|
||||
with self._lock:
|
||||
self.mode = mode
|
||||
self.t0 = time.monotonic()
|
||||
|
||||
def set_loop(self, seconds: float) -> None:
|
||||
with self._lock:
|
||||
self.loop_s = max(0.4, float(seconds))
|
||||
self.t0 = time.monotonic()
|
||||
|
||||
def sample(self, now: float) -> tuple[Aim, str]:
|
||||
with self._lock:
|
||||
if self.mode == "hold":
|
||||
aim = self.corners[self.selected]
|
||||
return Aim(aim.pan, aim.tilt, aim.rotate), self.selected.replace("_", " ")
|
||||
if self.mode == "figure8":
|
||||
return self._figure8(now), "figure of 8"
|
||||
aim = self._route(now)
|
||||
return aim, self._route_label
|
||||
|
||||
def _route(self, now: float) -> Aim:
|
||||
order = ROUTES[self.mode]
|
||||
u = ((now - self.t0) / self.loop_s) % 1.0
|
||||
x = u * len(order)
|
||||
i = int(x) % len(order)
|
||||
frac = x - int(x)
|
||||
if self.mode == "circle":
|
||||
frac = ease(frac)
|
||||
here = order[i].replace("_", " ")
|
||||
nxt = order[(i + 1) % len(order)].replace("_", " ")
|
||||
self._route_label = f"{here} → {nxt}"
|
||||
a = self.corners[order[i]]
|
||||
b = self.corners[order[(i + 1) % len(order)]]
|
||||
return lerp_aim(a, b, frac)
|
||||
|
||||
def _figure8(self, now: float) -> Aim:
|
||||
pans = [self.corners[name].pan for name in CORNERS]
|
||||
tilts = [self.corners[name].tilt for name in CORNERS]
|
||||
cx = (min(pans) + max(pans)) / 2.0
|
||||
cy = (min(tilts) + max(tilts)) / 2.0
|
||||
hw = (max(pans) - min(pans)) / 2.0
|
||||
hh = (max(tilts) - min(tilts)) / 2.0
|
||||
t = ((now - self.t0) / self.loop_s) % 1.0 * 2.0 * math.pi
|
||||
return Aim(
|
||||
clamp(cx + (-math.sin(2.0 * t)) * hw),
|
||||
clamp(cy + math.cos(t) * hh),
|
||||
self.corners[self.selected].rotate,
|
||||
)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
with self._lock:
|
||||
return {
|
||||
"corners": {name: self.corners[name].as_dict() for name in CORNERS},
|
||||
"loop_s": self.loop_s,
|
||||
}
|
||||
|
||||
def state(self, now: float) -> dict:
|
||||
live, label = self.sample(now)
|
||||
with self._lock:
|
||||
return {
|
||||
"selected": self.selected,
|
||||
"mode": self.mode,
|
||||
"loop_s": self.loop_s,
|
||||
"label": label,
|
||||
"live": live.as_dict(),
|
||||
"corners": {name: self.corners[name].as_dict() for name in CORNERS},
|
||||
}
|
||||
|
||||
|
||||
def default_aim() -> Aim:
|
||||
path = ROOT / "shows" / "mover_positions.json"
|
||||
try:
|
||||
down = json.loads(path.read_text())["positions"]["Down"]["m1"]
|
||||
return Aim(int(down["pan"]), int(down["tilt"]), 0)
|
||||
except (OSError, KeyError, TypeError, ValueError):
|
||||
return Aim()
|
||||
|
||||
|
||||
def load_pattern(path: Path) -> Pattern:
|
||||
seed = default_aim()
|
||||
corners = {name: Aim(seed.pan, seed.tilt, seed.rotate) for name in CORNERS}
|
||||
loop_s = 6.0
|
||||
if path.is_file():
|
||||
data = json.loads(path.read_text())
|
||||
loop_s = float(data.get("loop_s", loop_s))
|
||||
for name in CORNERS:
|
||||
raw = data.get("corners", {}).get(name, {})
|
||||
corners[name] = Aim(
|
||||
int(raw.get("pan", seed.pan)),
|
||||
int(raw.get("tilt", seed.tilt)),
|
||||
int(raw.get("rotate", 0)),
|
||||
).clamped()
|
||||
pattern = Pattern(corners)
|
||||
pattern.loop_s = max(0.4, loop_s)
|
||||
return pattern
|
||||
|
||||
|
||||
def save_pattern(path: Path, pattern: Pattern) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(pattern.snapshot(), indent=2) + "\n")
|
||||
|
||||
|
||||
def list_smc_ports() -> list[tuple[str, str]]:
|
||||
try:
|
||||
text = subprocess.check_output(["aconnect", "-l"], text=True, stderr=subprocess.DEVNULL)
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
return []
|
||||
found: list[tuple[str, str]] = []
|
||||
client_id = ""
|
||||
client_name = ""
|
||||
for line in text.splitlines():
|
||||
client = CLIENT_RE.match(line)
|
||||
if client:
|
||||
client_id = client.group(1)
|
||||
client_name = client.group(2)
|
||||
continue
|
||||
port = PORT_RE.match(line)
|
||||
if not port or not client_id:
|
||||
continue
|
||||
label = f"{client_name} {port.group(2)}".strip()
|
||||
if "smc-pad" not in label.lower() and "sinco" not in label.lower():
|
||||
continue
|
||||
if "private" in port.group(2).lower():
|
||||
continue
|
||||
found.append((f"{client_id}:{port.group(1)}", label))
|
||||
return found
|
||||
|
||||
|
||||
def parse_midi_line(line: str) -> tuple[str, int, int] | None:
|
||||
note = NOTE_ON_RE.search(line)
|
||||
if note and int(note.group(2)) > 0:
|
||||
return ("note", int(note.group(1)), int(note.group(2)))
|
||||
cc = CC_RE.search(line)
|
||||
if cc:
|
||||
return ("cc", int(cc.group(1)), int(cc.group(2)))
|
||||
return None
|
||||
|
||||
|
||||
class Studio:
|
||||
"""Holds the pattern, sends Art-Net, and listens to the SMC-PAD."""
|
||||
|
||||
def __init__(self, pattern: Pattern, sender: ArtNetSender, movers: list[Mover], path: Path, midi_port: str | None, midi_label: str):
|
||||
self.pattern = pattern
|
||||
self.sender = sender
|
||||
self.movers = movers
|
||||
self.path = path
|
||||
self.artnet = sender.destination()
|
||||
self.midi_port = midi_port
|
||||
self.midi_label = midi_label
|
||||
self._running = True
|
||||
self._midi: subprocess.Popen[str] | None = None
|
||||
self._threads: list[threading.Thread] = []
|
||||
self._seen_notes: set[int] = set()
|
||||
|
||||
def state(self) -> dict:
|
||||
data = self.pattern.state(time.monotonic())
|
||||
data["artnet"] = self.artnet
|
||||
data["midi"] = self.midi_label
|
||||
data["file"] = str(self.path)
|
||||
return data
|
||||
|
||||
def apply(self, aim: Aim) -> None:
|
||||
rgb = (255, 255, 255)
|
||||
for mover in self.movers:
|
||||
mover.apply(
|
||||
pan=aim.pan,
|
||||
tilt=aim.tilt,
|
||||
rgb=rgb,
|
||||
dimmer=255,
|
||||
focus=FOCUS_FULL,
|
||||
speed=0,
|
||||
zoom=0,
|
||||
rotate=aim.rotate,
|
||||
)
|
||||
|
||||
def output_loop(self) -> None:
|
||||
while self._running:
|
||||
aim, _label = self.pattern.sample(time.monotonic())
|
||||
self.apply(aim)
|
||||
time.sleep(0.025)
|
||||
|
||||
def handle_midi(self, kind: str, number: int, value: int) -> None:
|
||||
if kind == "note":
|
||||
name = PAD_NOTES.get(number)
|
||||
if name is None:
|
||||
if number not in self._seen_notes:
|
||||
self._seen_notes.add(number)
|
||||
print(f"pad note {number} is not a corner", flush=True)
|
||||
return
|
||||
self.pattern.select(name)
|
||||
return
|
||||
channel = {CC_PAN: "pan", CC_TILT: "tilt", CC_ROTATE: "rotate"}.get(number)
|
||||
if channel is None:
|
||||
return
|
||||
self.pattern.nudge(channel, encoder_delta(value))
|
||||
|
||||
def midi_loop(self, port: str) -> None:
|
||||
self._midi = subprocess.Popen(
|
||||
["aseqdump", "-p", port],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
assert self._midi.stdout is not None
|
||||
for line in self._midi.stdout:
|
||||
if not self._running:
|
||||
break
|
||||
parsed = parse_midi_line(line)
|
||||
if parsed:
|
||||
self.handle_midi(*parsed)
|
||||
if self._running and self._midi.poll() not in (None, 0):
|
||||
self.midi_label = "SMC-PAD disconnected"
|
||||
print("MIDI input stopped. Is the SMC-PAD still connected?", flush=True)
|
||||
|
||||
def start(self) -> None:
|
||||
out = threading.Thread(target=self.output_loop, daemon=True)
|
||||
self._threads.append(out)
|
||||
out.start()
|
||||
if self.midi_port:
|
||||
midi = threading.Thread(target=self.midi_loop, args=(self.midi_port,), daemon=True)
|
||||
self._threads.append(midi)
|
||||
midi.start()
|
||||
|
||||
def save(self) -> None:
|
||||
save_pattern(self.path, self.pattern)
|
||||
|
||||
def close(self) -> None:
|
||||
self._running = False
|
||||
midi = self._midi
|
||||
if midi is not None and midi.poll() is None:
|
||||
midi.send_signal(signal.SIGINT)
|
||||
try:
|
||||
midi.wait(timeout=1.0)
|
||||
except subprocess.TimeoutExpired:
|
||||
midi.kill()
|
||||
for thread in self._threads:
|
||||
thread.join(timeout=1.0)
|
||||
self.save()
|
||||
self.sender.close()
|
||||
|
||||
|
||||
def open_studio(path: Path, ip: str | None, universe: int, address: int, address2: int, midi: str | None) -> Studio:
|
||||
ports = list_smc_ports()
|
||||
if midi:
|
||||
midi_port, midi_label = midi, midi
|
||||
elif ports:
|
||||
midi_port, midi_label = ports[0]
|
||||
else:
|
||||
midi_port, midi_label = None, "SMC-PAD not found"
|
||||
pattern = load_pattern(path)
|
||||
node = ip or discover_artnet_node()
|
||||
sender = ArtNetSender(node, universe=universe)
|
||||
movers = [Mover(sender, address, "M1"), Mover(sender, address2, "M2")]
|
||||
studio = Studio(pattern, sender, movers, path, midi_port, midi_label)
|
||||
print(f"Art-Net → {node} universe {universe} M1 @{address} M2 @{address2}")
|
||||
print(f"MIDI {midi_label}")
|
||||
print("Stop QLC+ Art-Net output first. Focus stays at 255 so rotate can spin.")
|
||||
return studio
|
||||
@@ -0,0 +1,141 @@
|
||||
"""HTTP server for the pattern editor. Run via `python -m pattern_pad`."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from pattern_pad.engine import DEFAULT_PATH, M1_ADDR, M2_ADDR, MODES, ROOT, open_studio
|
||||
|
||||
STATIC = Path(__file__).resolve().parent / "static"
|
||||
BOOT = str(time.time_ns())
|
||||
HOST = "127.0.0.1"
|
||||
PORT = 8766
|
||||
|
||||
MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
}
|
||||
|
||||
|
||||
def static_stamp(directory: Path) -> str:
|
||||
latest = 0
|
||||
if directory.is_dir():
|
||||
for path in directory.rglob("*"):
|
||||
if path.is_file():
|
||||
latest = max(latest, path.stat().st_mtime_ns)
|
||||
return str(latest)
|
||||
|
||||
|
||||
def make_handler(studio):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt: str, *args) -> None:
|
||||
return
|
||||
|
||||
def _send(self, code: int, body: bytes, content_type: str) -> None:
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _json(self, code: int, payload: dict) -> None:
|
||||
self._send(code, json.dumps(payload).encode(), "application/json")
|
||||
|
||||
def _read_json(self) -> dict:
|
||||
length = int(self.headers.get("Content-Length", "0") or 0)
|
||||
if length <= 0:
|
||||
return {}
|
||||
raw = self.rfile.read(length)
|
||||
data = json.loads(raw.decode() or "{}")
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Expected a JSON object")
|
||||
return data
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
path = self.path.split("?", 1)[0]
|
||||
if path == "/api/state":
|
||||
self._json(200, studio.state())
|
||||
return
|
||||
if path == "/api/dev":
|
||||
self._json(200, {"boot": BOOT, "static": static_stamp(STATIC)})
|
||||
return
|
||||
if path == "/":
|
||||
path = "/index.html"
|
||||
file_path = (STATIC / path.lstrip("/")).resolve()
|
||||
if not str(file_path).startswith(str(STATIC)) or not file_path.is_file():
|
||||
self._send(404, b"not found", "text/plain; charset=utf-8")
|
||||
return
|
||||
self._send(200, file_path.read_bytes(), MIME.get(file_path.suffix, "application/octet-stream"))
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
path = self.path.split("?", 1)[0]
|
||||
try:
|
||||
body = self._read_json()
|
||||
if path == "/api/select":
|
||||
studio.pattern.select(str(body.get("name", "")))
|
||||
elif path == "/api/aim":
|
||||
studio.pattern.set_aim(int(body["pan"]), int(body["tilt"]), int(body["rotate"]))
|
||||
elif path == "/api/play":
|
||||
studio.pattern.play(str(body.get("mode", "")))
|
||||
elif path == "/api/loop":
|
||||
studio.pattern.set_loop(float(body["seconds"]))
|
||||
elif path == "/api/save":
|
||||
studio.save()
|
||||
else:
|
||||
self._json(404, {"error": "Unknown request"})
|
||||
return
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
self._json(400, {"error": str(exc) or "Bad request"})
|
||||
return
|
||||
self._json(200, studio.state())
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def parse_args():
|
||||
p = argparse.ArgumentParser(description="Pattern editor web server")
|
||||
p.add_argument("--host", default=HOST)
|
||||
p.add_argument("--port", type=int, default=PORT)
|
||||
p.add_argument("--ip", default=None, help="Art-Net destination (default: poll the network)")
|
||||
p.add_argument("--universe", type=int, default=0)
|
||||
p.add_argument("--address", type=int, default=M1_ADDR, help="M1 DMX start, 1-based")
|
||||
p.add_argument("--address2", type=int, default=M2_ADDR, help="M2 DMX start, 1-based")
|
||||
p.add_argument("--midi", default=None, help="ALSA port, for example 128:0")
|
||||
p.add_argument("--file", type=Path, default=DEFAULT_PATH, help="Corner file to load and save")
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
path = args.file if args.file.is_absolute() else ROOT / args.file
|
||||
studio = open_studio(path, args.ip, args.universe, args.address, args.address2, args.midi)
|
||||
studio.start()
|
||||
ThreadingHTTPServer.allow_reuse_address = True
|
||||
httpd = ThreadingHTTPServer((args.host, args.port), make_handler(studio))
|
||||
|
||||
def stop(_signum, _frame) -> None:
|
||||
threading.Thread(target=httpd.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
print(f"http://{args.host}:{args.port}", flush=True)
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
finally:
|
||||
httpd.server_close()
|
||||
studio.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,53 @@
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font: 16px/1.4 system-ui, sans-serif;
|
||||
background: #12141a;
|
||||
color: #eee;
|
||||
}
|
||||
main { max-width: 36rem; margin: 0 auto; padding: 1.25rem 1.25rem 3rem; }
|
||||
h1 { font-size: 1.35rem; font-weight: 650; margin: 0 0 0.2rem; }
|
||||
.meta, .hint, .status { color: #8e98a8; font-size: 0.85rem; }
|
||||
.meta { margin: 0 0 1rem; word-break: break-all; }
|
||||
.hint { margin: 0.35rem 0 1rem; }
|
||||
.corners, .modes, .row { display: flex; gap: 0.5rem; }
|
||||
.corners { display: grid; grid-template-columns: 1fr 1fr; }
|
||||
button, input { font: inherit; color: inherit; }
|
||||
button {
|
||||
border: 1px solid #3a4050;
|
||||
background: #1c2030;
|
||||
border-radius: 8px;
|
||||
padding: 0.7rem 0.8rem;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
.corners button small {
|
||||
display: block;
|
||||
color: #8e98a8;
|
||||
font-size: 0.75rem;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
button.active {
|
||||
background: #f0a030;
|
||||
border-color: #f0a030;
|
||||
color: #1a1206;
|
||||
font-weight: 650;
|
||||
}
|
||||
button.active small { color: #5c4316; }
|
||||
.modes { flex-wrap: wrap; margin: 0.4rem 0 1rem; }
|
||||
.modes button { text-align: center; }
|
||||
.slider { display: block; margin: 0.75rem 0; }
|
||||
.slider output { float: right; font-variant-numeric: tabular-nums; }
|
||||
input[type="range"] { width: 100%; margin-top: 0.25rem; }
|
||||
.row { align-items: center; margin-top: 0.5rem; }
|
||||
.row label { display: flex; align-items: center; gap: 0.35rem; }
|
||||
input[type="number"] {
|
||||
width: 4.5rem;
|
||||
border: 1px solid #3a4050;
|
||||
background: #1c2030;
|
||||
border-radius: 8px;
|
||||
padding: 0.45rem 0.5rem;
|
||||
}
|
||||
#live { margin-left: auto; font-variant-numeric: tabular-nums; color: #d5dbe6; }
|
||||
.status { min-height: 1.2em; }
|
||||
@@ -0,0 +1,127 @@
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const pan = $("pan");
|
||||
const tilt = $("tilt");
|
||||
const rotate = $("rotate");
|
||||
const loop = $("loop");
|
||||
let dragging = false;
|
||||
let seenDev = null;
|
||||
let devDown = false;
|
||||
|
||||
function paint(data, writeSliders) {
|
||||
$("meta").textContent = `${data.artnet} · ${data.midi}`;
|
||||
for (const button of document.querySelectorAll("#corners button")) {
|
||||
const name = button.dataset.corner;
|
||||
const aim = data.corners[name];
|
||||
button.classList.toggle("active", name === data.selected);
|
||||
button.querySelector("small").textContent = `pan ${aim.pan} tilt ${aim.tilt} rot ${aim.rotate}`;
|
||||
}
|
||||
for (const button of document.querySelectorAll("#modes button")) {
|
||||
button.classList.toggle("active", button.dataset.mode === data.mode);
|
||||
}
|
||||
if (writeSliders) {
|
||||
const aim = data.corners[data.selected];
|
||||
pan.value = aim.pan;
|
||||
tilt.value = aim.tilt;
|
||||
rotate.value = aim.rotate;
|
||||
}
|
||||
$("pan-out").textContent = pan.value;
|
||||
$("tilt-out").textContent = tilt.value;
|
||||
$("rot-out").textContent = rotate.value;
|
||||
if (document.activeElement !== loop) loop.value = data.loop_s;
|
||||
const live = data.live;
|
||||
$("live").textContent = `${data.label} ${live.pan} / ${live.tilt} / ${live.rotate}`;
|
||||
}
|
||||
|
||||
async function post(url, body) {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify(body || {}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "request failed");
|
||||
paint(data, !dragging);
|
||||
return data;
|
||||
}
|
||||
|
||||
function sendAim() {
|
||||
$("pan-out").textContent = pan.value;
|
||||
$("tilt-out").textContent = tilt.value;
|
||||
$("rot-out").textContent = rotate.value;
|
||||
post("/api/aim", {
|
||||
pan: Number(pan.value),
|
||||
tilt: Number(tilt.value),
|
||||
rotate: Number(rotate.value),
|
||||
}).catch((err) => {
|
||||
$("status").textContent = err.message;
|
||||
});
|
||||
}
|
||||
|
||||
for (const input of [pan, tilt, rotate]) {
|
||||
input.addEventListener("pointerdown", () => {
|
||||
dragging = true;
|
||||
});
|
||||
input.addEventListener("input", sendAim);
|
||||
}
|
||||
window.addEventListener("pointerup", () => {
|
||||
dragging = false;
|
||||
});
|
||||
|
||||
$("corners").addEventListener("click", (ev) => {
|
||||
const button = ev.target.closest("button");
|
||||
if (!button) return;
|
||||
post("/api/select", {name: button.dataset.corner}).catch((err) => {
|
||||
$("status").textContent = err.message;
|
||||
});
|
||||
});
|
||||
|
||||
$("modes").addEventListener("click", (ev) => {
|
||||
const button = ev.target.closest("button");
|
||||
if (!button) return;
|
||||
post("/api/play", {mode: button.dataset.mode}).catch((err) => {
|
||||
$("status").textContent = err.message;
|
||||
});
|
||||
});
|
||||
|
||||
loop.addEventListener("change", () => {
|
||||
post("/api/loop", {seconds: Number(loop.value)}).catch((err) => {
|
||||
$("status").textContent = err.message;
|
||||
});
|
||||
});
|
||||
|
||||
$("save").addEventListener("click", () => {
|
||||
post("/api/save").then(() => {
|
||||
$("status").textContent = "Saved";
|
||||
}).catch((err) => {
|
||||
$("status").textContent = err.message;
|
||||
});
|
||||
});
|
||||
|
||||
async function poll() {
|
||||
try {
|
||||
const data = await fetch("/api/state", {cache: "no-store"}).then((res) => res.json());
|
||||
paint(data, !dragging);
|
||||
} catch {
|
||||
$("meta").textContent = "Reconnecting…";
|
||||
}
|
||||
setTimeout(poll, 200);
|
||||
}
|
||||
|
||||
async function watchDev() {
|
||||
try {
|
||||
const dev = await fetch("/api/dev", {cache: "no-store"}).then((res) => res.json());
|
||||
if (devDown || (seenDev && (dev.boot !== seenDev.boot || dev.static !== seenDev.static))) {
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
seenDev = dev;
|
||||
devDown = false;
|
||||
} catch {
|
||||
devDown = seenDev !== null;
|
||||
}
|
||||
setTimeout(watchDev, 400);
|
||||
}
|
||||
|
||||
poll();
|
||||
watchDev();
|
||||
@@ -0,0 +1,53 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Patterns</title>
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Patterns</h1>
|
||||
<p class="meta" id="meta">Connecting…</p>
|
||||
|
||||
<div class="corners" id="corners">
|
||||
<button type="button" data-corner="front_left">Front left<small></small></button>
|
||||
<button type="button" data-corner="front_right">Front right<small></small></button>
|
||||
<button type="button" data-corner="back_left">Back left<small></small></button>
|
||||
<button type="button" data-corner="back_right">Back right<small></small></button>
|
||||
</div>
|
||||
<p class="hint">Pad 13 front left, 14 front right, 9 back left, 10 back right.</p>
|
||||
|
||||
<label class="slider">Pan <output id="pan-out"></output>
|
||||
<input id="pan" type="range" min="0" max="255" value="0">
|
||||
</label>
|
||||
<label class="slider">Tilt <output id="tilt-out"></output>
|
||||
<input id="tilt" type="range" min="0" max="255" value="0">
|
||||
</label>
|
||||
<label class="slider">Rotate <output id="rot-out"></output>
|
||||
<input id="rotate" type="range" min="0" max="255" value="0">
|
||||
</label>
|
||||
<p class="hint">Knob 7 pan, knob 8 tilt, knob 5 rotate. Focus stays at 255 so the lens can spin.</p>
|
||||
|
||||
<div class="modes" id="modes">
|
||||
<button type="button" data-mode="hold">Hold</button>
|
||||
<button type="button" data-mode="box">Box</button>
|
||||
<button type="button" data-mode="cross">Cross</button>
|
||||
<button type="button" data-mode="circle">Circle</button>
|
||||
<button type="button" data-mode="figure8">Figure 8</button>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<label>Loop
|
||||
<input id="loop" type="number" min="0.4" max="60" step="0.1" value="6">
|
||||
s
|
||||
</label>
|
||||
<button type="button" id="save">Save</button>
|
||||
<span id="live"></span>
|
||||
</div>
|
||||
<p class="status" id="status"></p>
|
||||
</main>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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"
|
||||
@@ -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())
|
||||
@@ -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}
|
||||
@@ -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}")
|
||||
@@ -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("&", "&").replace("<", "<").replace(">", ">").replace(""", '"').replace("'", "'")
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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();
|
||||
})();
|
||||
@@ -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 & 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>
|
||||
@@ -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; }
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Steps: play the steps written in the "steps" property, one after another.
|
||||
|
||||
steps is the steps separated by ";", each the pixels' colours as rrggbb hex
|
||||
separated by ",", left to right and then top to bottom. Missing pixels are
|
||||
off. The matrix's own colour is not used.
|
||||
|
||||
shows/test.qxw's can patterns use it (scripts/shows/can_patterns.py): each is
|
||||
one RGB matrix running for as long as the pattern does, so a chase started
|
||||
after it lands on top, where a chaser of scenes would start a newer scene
|
||||
every step. With a Mask blend, grey levels dim the colour under it.
|
||||
QLC+ loads it from ~/.qlcplus/rgbscripts, where can_patterns.py links it.
|
||||
*/
|
||||
|
||||
var testAlgo;
|
||||
|
||||
(
|
||||
function()
|
||||
{
|
||||
var algo = new Object;
|
||||
algo.apiVersion = 2;
|
||||
algo.name = "Steps";
|
||||
algo.author = "qlcplus shows";
|
||||
algo.acceptColors = 0;
|
||||
algo.properties = new Array();
|
||||
algo.steps = [[0]];
|
||||
algo.text = "000000";
|
||||
|
||||
algo.properties.push("name:steps|type:string|display:Steps|write:setSteps|read:getSteps");
|
||||
|
||||
algo.setSteps = function(_steps)
|
||||
{
|
||||
algo.text = _steps;
|
||||
algo.steps = String(_steps).split(";").map(function(step) {
|
||||
return step.split(",").map(function(hex) { return parseInt(hex, 16) || 0; });
|
||||
});
|
||||
};
|
||||
|
||||
algo.getSteps = function()
|
||||
{
|
||||
return algo.text;
|
||||
};
|
||||
|
||||
algo.rgbMap = function(width, height, rgb, step)
|
||||
{
|
||||
var pixels = algo.steps[step % algo.steps.length];
|
||||
var map = new Array(height);
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
map[y] = new Array(width);
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var i = y * width + x;
|
||||
map[y][x] = i < pixels.length ? pixels[i] : 0;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
algo.rgbMapStepCount = function(width, height)
|
||||
{
|
||||
return algo.steps.length;
|
||||
};
|
||||
|
||||
testAlgo = algo;
|
||||
return algo;
|
||||
}
|
||||
)();
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
Swap: every pixel in one colour, then every pixel in the other.
|
||||
|
||||
Two steps, all pixels lit with the step's colour. Give the RGB matrix a start
|
||||
and an end colour and QLC+ hands step 0 the start colour and step 1 the end
|
||||
colour, so the matrix swaps between them; with a fade in it crossfades.
|
||||
|
||||
shows/test.qxw's Odd Even and Left Right cans patterns use it, two matrices
|
||||
at once with their colours the other way round (scripts/shows/can_patterns.py).
|
||||
QLC+ loads it from ~/.qlcplus/rgbscripts, where can_patterns.py links it.
|
||||
*/
|
||||
|
||||
var testAlgo;
|
||||
|
||||
(
|
||||
function()
|
||||
{
|
||||
var algo = new Object;
|
||||
algo.apiVersion = 2;
|
||||
algo.name = "Swap";
|
||||
algo.author = "qlcplus shows";
|
||||
algo.acceptColors = 2;
|
||||
algo.properties = new Array();
|
||||
|
||||
algo.rgbMap = function(width, height, rgb, step)
|
||||
{
|
||||
var map = new Array(height);
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
map[y] = new Array(width);
|
||||
for (var x = 0; x < width; x++)
|
||||
map[y][x] = rgb;
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
algo.rgbMapStepCount = function(width, height)
|
||||
{
|
||||
return 2;
|
||||
};
|
||||
|
||||
testAlgo = algo;
|
||||
return algo;
|
||||
}
|
||||
)();
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Figure-of-8 on the two Small Eye movers.
|
||||
|
||||
Dry run (prints DMX samples, sends nothing):
|
||||
|
||||
python3 scripts/anim/anim_eight.py
|
||||
python3 -m showfile run scripts/anim/anim_eight.py --seconds 1
|
||||
|
||||
Send Art-Net, for example at the stage simulator:
|
||||
|
||||
python3 scripts/anim/anim_eight.py --ip 127.0.0.1 --seconds 8
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from showfile import Show
|
||||
from showfile.play import script_main
|
||||
|
||||
|
||||
def build() -> Show:
|
||||
show = Show(author="Jimmy")
|
||||
m1 = show.patch(
|
||||
"Small Eye 7", "Mover", "43 Channel", name="Small Eye 7 #1", address=0, key="m1"
|
||||
)
|
||||
m2 = show.patch(
|
||||
"Small Eye 7", "Mover", "43 Channel", name="Small Eye 7 #2", address=44, key="m2"
|
||||
)
|
||||
show.efx(
|
||||
"Figure of 8",
|
||||
[m1, m2],
|
||||
algorithm="Eight",
|
||||
width=40,
|
||||
height=30,
|
||||
x_offset=128,
|
||||
y_offset=140,
|
||||
duration_ms=8000,
|
||||
key="eight",
|
||||
)
|
||||
show.run("eight")
|
||||
return show
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
script_main(build)
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The whole stage: a colour chase on the cans and a figure-8 on every mover.
|
||||
|
||||
The patch, positions, and channel names come from stage/map.json.
|
||||
|
||||
Dry run (prints DMX samples, sends nothing):
|
||||
|
||||
python3 scripts/anim/anim_stage.py
|
||||
python3 -m showfile run scripts/anim/anim_stage.py --seconds 1
|
||||
|
||||
Send Art-Net at the stage simulator:
|
||||
|
||||
python3 scripts/anim/anim_stage.py --ip 127.0.0.1 --seconds 12
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from showfile import Show
|
||||
from showfile.play import script_main
|
||||
|
||||
|
||||
def build() -> Show:
|
||||
show = Show(author="Jimmy")
|
||||
rig = show.patch_stage(ROOT / "stage" / "map.json")
|
||||
red, green, blue = (rig.cans[0].channel(name) for name in ("Red", "Green", "Blue"))
|
||||
dimmers = {
|
||||
can.key: {can.channel("Dimmer"): 255, can.channel("Strobe"): 0}
|
||||
for can in rig.cans
|
||||
}
|
||||
show.scene("Can dimmers", dimmers, key="dim")
|
||||
frames = []
|
||||
count = len(rig.cans)
|
||||
for head in range(count):
|
||||
frame = []
|
||||
for index in range(count):
|
||||
colour = _hsv(index / count)
|
||||
distance = min((index - head) % count, (head - index) % count)
|
||||
if distance == 0:
|
||||
frame.append(colour)
|
||||
elif distance == 1:
|
||||
frame.append(tuple(channel // 3 for channel in colour))
|
||||
else:
|
||||
frame.append((0, 0, 0))
|
||||
frames.append(frame)
|
||||
show.colour_chase(
|
||||
"Can chase",
|
||||
rig.cans,
|
||||
{"r": red, "g": green, "b": blue},
|
||||
frames,
|
||||
fade_ms=80,
|
||||
hold_ms=140,
|
||||
key="chase",
|
||||
)
|
||||
look = {}
|
||||
movers = []
|
||||
for index, mover in enumerate(rig.movers):
|
||||
colour = (255, 40, 0) if index % 2 == 0 else (40, 80, 255)
|
||||
values = {
|
||||
mover.channel("Zoom"): 40,
|
||||
mover.channel("Dynamic Effect"): 30 if index % 2 == 0 else 160,
|
||||
mover.channel("Lens Rotate"): 210 if index % 2 == 0 else 40,
|
||||
}
|
||||
for channel in mover.named("White"):
|
||||
values[channel] = 0
|
||||
for red_ch, green_ch, blue_ch in zip(mover.named("Red"), mover.named("Green"), mover.named("Blue")):
|
||||
values[red_ch] = colour[0]
|
||||
values[green_ch] = colour[1]
|
||||
values[blue_ch] = colour[2]
|
||||
look[mover.key] = values
|
||||
movers.append({"fixture": mover, "start_offset": index * 90})
|
||||
show.scene("Mover look", look, key="look")
|
||||
show.efx(
|
||||
"Movers",
|
||||
movers,
|
||||
algorithm="Eight",
|
||||
width=36,
|
||||
height=22,
|
||||
x_offset=128,
|
||||
y_offset=140,
|
||||
duration_ms=12000,
|
||||
key="movers",
|
||||
)
|
||||
show.collection("Stage", ["dim", "chase", "look", "movers"], key="stage")
|
||||
show.run("stage")
|
||||
return show
|
||||
|
||||
|
||||
def _hsv(hue: float) -> tuple[int, int, int]:
|
||||
hue = hue % 1.0
|
||||
segment = int(hue * 6) % 6
|
||||
frac = hue * 6 - int(hue * 6)
|
||||
fade = int(255 * (1 - frac))
|
||||
rise = int(255 * frac)
|
||||
if segment == 0:
|
||||
return 255, rise, 0
|
||||
if segment == 1:
|
||||
return fade, 255, 0
|
||||
if segment == 2:
|
||||
return 0, 255, rise
|
||||
if segment == 3:
|
||||
return 0, fade, 255
|
||||
if segment == 4:
|
||||
return rise, 0, 255
|
||||
return 255, 0, fade
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
script_main(build)
|
||||
Executable
+648
@@ -0,0 +1,648 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Drive the two cabaret Small Eye 7 movers over Art-Net.
|
||||
|
||||
Self-contained: no QLC+, no other repo imports. Stop QLC+ output first so
|
||||
the two sources do not fight. Ctrl+C blackout.
|
||||
|
||||
Patch (same as shows/cabaret.qxw, 43ch pixel mode):
|
||||
M1 DMX 1–43 Small Eye 7 #1
|
||||
M2 DMX 45–87 Small Eye 7 #2 (hung 180° — same DMX pan = split)
|
||||
|
||||
Examples:
|
||||
python3 scripts/cabaret_movers.py
|
||||
python3 scripts/cabaret_movers.py --position Wall --color Pink
|
||||
python3 scripts/cabaret_movers.py --pattern figure8 --position Down
|
||||
python3 scripts/cabaret_movers.py --interactive
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ARTNET_PORT = 6454
|
||||
HEADER = b"Art-Net\x00"
|
||||
OP_DMX = 0x5000
|
||||
OP_POLL = 0x2000
|
||||
OP_POLL_REPLY = 0x2100
|
||||
PROT_VER = 14
|
||||
DEFAULT_NODE = "192.168.1.227"
|
||||
|
||||
# 1-based 43ch map (QLC channel index = these − 1)
|
||||
CH_PAN, CH_TILT = 1, 3
|
||||
CH_SPEED, CH_ROTATE, CH_ZOOM, CH_FOCUS = 5, 6, 7, 8
|
||||
CH_DIMMER, CH_STROBE = 9, 10
|
||||
CH_RED1 = 11
|
||||
FIXTURE_CHANNELS = 43
|
||||
PIXELS = 7
|
||||
|
||||
M1_ADDR, M2_ADDR = 1, 45
|
||||
FADE_S = 2.0
|
||||
LOOP_S = 3.0 # cabaret EFX duration
|
||||
FOCUS_DEFAULT = 70
|
||||
|
||||
# name -> (M1 pan/tilt, M2 pan/tilt)
|
||||
POSITIONS: dict[str, tuple[tuple[int, int], tuple[int, int]]] = {
|
||||
"down": ((80, 161), (74, 145)),
|
||||
"roof": ((179, 0), (179, 0)),
|
||||
"wall": ((179, 36), (179, 36)),
|
||||
"mid": ((164, 18), (164, 18)),
|
||||
"cross": ((140, 26), (140, 26)),
|
||||
"out": ((200, 22), (200, 22)),
|
||||
}
|
||||
POSITION_ORDER = ("down", "roof", "wall", "mid", "cross", "out")
|
||||
|
||||
PALETTE: dict[str, tuple[int, int, int]] = {
|
||||
"amber": (255, 90, 0),
|
||||
"pink": (255, 50, 160),
|
||||
"red": (255, 0, 0),
|
||||
"green": (0, 255, 0),
|
||||
"blue": (0, 0, 255),
|
||||
"orange": (255, 127, 0),
|
||||
"yellow": (255, 255, 0),
|
||||
"purple": (127, 0, 255),
|
||||
}
|
||||
COLOR_ORDER = tuple(PALETTE)
|
||||
|
||||
# name -> (algorithm, width, height, extras)
|
||||
PATTERNS: dict[str, tuple[str, int, int, dict]] = {
|
||||
"still": ("Still", 0, 0, {}),
|
||||
"figure8": ("Eight", 56, 56, {}),
|
||||
"zigzag": ("Lissajous", 80, 40, {"x_freq": 3, "cross": True}),
|
||||
"swirl": ("Circle", 50, 50, {}),
|
||||
}
|
||||
PATTERN_ORDER = ("still", "figure8", "zigzag", "swirl")
|
||||
|
||||
|
||||
def clamp(value: float, lo: int = 0, hi: int = 255) -> int:
|
||||
return max(lo, min(hi, int(round(value))))
|
||||
|
||||
|
||||
def efx_fit(tilt: int, height: int) -> tuple[int, int]:
|
||||
"""Keep the Position aim. Shrink height to fit; only nudge off a hard stop."""
|
||||
height = min(int(height), 127)
|
||||
if tilt <= 0:
|
||||
h = min(height, 24)
|
||||
return h, h
|
||||
if tilt >= 255:
|
||||
h = min(height, 24)
|
||||
return 255 - h, h
|
||||
h = min(height, tilt, 255 - tilt)
|
||||
if h < 8:
|
||||
h = min(height, 16)
|
||||
return max(h, min(255 - h, tilt)), h
|
||||
return tilt, h
|
||||
|
||||
|
||||
def efx_xy(algorithm: str, t: float, x_freq: int = 1) -> tuple[float, float]:
|
||||
"""QLC+ EFX unit path, t in 0..2π → x,y in -1..1."""
|
||||
if algorithm == "Eight":
|
||||
return -math.sin(2.0 * t), math.cos(t)
|
||||
if algorithm == "Circle":
|
||||
return math.cos(t), math.sin(t)
|
||||
if algorithm == "Lissajous":
|
||||
return math.sin(x_freq * t), math.cos(t)
|
||||
return 0.0, 0.0
|
||||
|
||||
|
||||
def build_artdmx(channels: bytes, universe: int = 0, sequence: int = 1) -> bytes:
|
||||
data = bytearray(channels)
|
||||
n = len(data)
|
||||
if n < 2:
|
||||
data.extend(b"\x00" * (2 - n))
|
||||
n = 2
|
||||
if n & 1:
|
||||
data.append(0)
|
||||
n += 1
|
||||
if n > 512:
|
||||
data = data[:512]
|
||||
n = 512
|
||||
pkt = bytearray(18 + n)
|
||||
pkt[0:8] = HEADER
|
||||
pkt[8:10] = bytes((OP_DMX & 0xFF, OP_DMX >> 8))
|
||||
pkt[10] = 0
|
||||
pkt[11] = PROT_VER
|
||||
pkt[12] = sequence & 0xFF
|
||||
pkt[13] = 0
|
||||
pkt[14] = universe & 0xFF
|
||||
pkt[15] = 0
|
||||
pkt[16] = (n >> 8) & 0xFF
|
||||
pkt[17] = n & 0xFF
|
||||
pkt[18 : 18 + n] = data
|
||||
return bytes(pkt)
|
||||
|
||||
|
||||
def _artnet_name(data: bytes) -> str:
|
||||
short = data[26:44].split(b"\x00", 1)[0].decode("latin1", "replace").strip()
|
||||
if short or len(data) < 108:
|
||||
return short
|
||||
return data[44:108].split(b"\x00", 1)[0].decode("latin1", "replace").strip()
|
||||
|
||||
|
||||
def discover_artnet_nodes(fallback: str = DEFAULT_NODE) -> list[dict[str, str]]:
|
||||
"""Art-Net PollReply nodes as {ip, name}. Falls back to one saved address."""
|
||||
poll = bytearray(14)
|
||||
poll[0:8] = HEADER
|
||||
poll[8:10] = bytes((OP_POLL & 0xFF, OP_POLL >> 8))
|
||||
poll[11] = PROT_VER
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.settimeout(0.25)
|
||||
found: list[dict[str, str]] = []
|
||||
try:
|
||||
sock.bind(("", 0))
|
||||
for dest in ("255.255.255.255", "192.168.1.255", fallback):
|
||||
try:
|
||||
sock.sendto(poll, (dest, ARTNET_PORT))
|
||||
except OSError:
|
||||
pass
|
||||
seen: set[str] = set()
|
||||
deadline = time.monotonic() + 1.2
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
data, addr = sock.recvfrom(1024)
|
||||
except (TimeoutError, socket.timeout):
|
||||
continue
|
||||
if not data.startswith(HEADER) or len(data) < 44:
|
||||
continue
|
||||
opcode = data[8] | (data[9] << 8)
|
||||
if opcode != OP_POLL_REPLY:
|
||||
continue
|
||||
ip = addr[0]
|
||||
if ip.startswith("127.") or ip in seen:
|
||||
continue
|
||||
seen.add(ip)
|
||||
found.append({"ip": ip, "name": _artnet_name(data)})
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
if not found:
|
||||
return [{"ip": fallback, "name": "no reply"}]
|
||||
return found
|
||||
|
||||
|
||||
def discover_artnet_node(fallback: str = DEFAULT_NODE) -> str:
|
||||
nodes = discover_artnet_nodes(fallback)
|
||||
for node in nodes:
|
||||
name = node["name"].lower()
|
||||
if "gateway" in name or "dmx" in name:
|
||||
return node["ip"]
|
||||
return nodes[0]["ip"]
|
||||
|
||||
|
||||
class ArtNetSender:
|
||||
def __init__(self, dest: str, universe: int = 0, hz: float = 40.0):
|
||||
self.dest = dest
|
||||
self.universe = universe
|
||||
self.period = 1.0 / hz
|
||||
self.frame = bytearray(512)
|
||||
self.sequence = 1
|
||||
self._lock = threading.Lock()
|
||||
self._running = True
|
||||
self._blackout_dest = ""
|
||||
self._blackout_left = 0
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _loop(self):
|
||||
while self._running:
|
||||
with self._lock:
|
||||
pkt = build_artdmx(self.frame, self.universe, self.sequence)
|
||||
self.sequence = 1 if self.sequence >= 255 else self.sequence + 1
|
||||
dest = self.dest
|
||||
black_dest = ""
|
||||
black_pkt = b""
|
||||
if self._blackout_left and self._blackout_dest != dest:
|
||||
black_dest = self._blackout_dest
|
||||
black_pkt = build_artdmx(bytes(512), self.universe, self.sequence)
|
||||
self.sequence = 1 if self.sequence >= 255 else self.sequence + 1
|
||||
self._blackout_left -= 1
|
||||
if black_dest:
|
||||
try:
|
||||
self.sock.sendto(black_pkt, (black_dest, ARTNET_PORT))
|
||||
except OSError as exc:
|
||||
print(f"Art-Net blackout failed: {exc}", file=sys.stderr)
|
||||
try:
|
||||
self.sock.sendto(pkt, (dest, ARTNET_PORT))
|
||||
except OSError as exc:
|
||||
print(f"Art-Net send failed: {exc}", file=sys.stderr)
|
||||
time.sleep(self.period)
|
||||
|
||||
def destination(self) -> str:
|
||||
with self._lock:
|
||||
return self.dest
|
||||
|
||||
def set_dest(self, dest: str):
|
||||
"""Send the next frames to dest and black out the previous node."""
|
||||
with self._lock:
|
||||
if dest == self.dest:
|
||||
return
|
||||
self._blackout_dest = self.dest
|
||||
self._blackout_left = 4
|
||||
self.dest = dest
|
||||
|
||||
def set_universe(self, universe: int):
|
||||
with self._lock:
|
||||
self.universe = int(universe) & 0x7FFF
|
||||
|
||||
def set_slot(self, dmx_addr: int, value: int):
|
||||
with self._lock:
|
||||
self.frame[dmx_addr - 1] = clamp(value)
|
||||
|
||||
def blackout(self):
|
||||
with self._lock:
|
||||
self.frame[:] = b"\x00" * 512
|
||||
|
||||
def close(self):
|
||||
self.blackout()
|
||||
time.sleep(self.period * 3)
|
||||
self._running = False
|
||||
self._thread.join(timeout=1.0)
|
||||
self.sock.close()
|
||||
|
||||
|
||||
class Mover:
|
||||
def __init__(self, sender: ArtNetSender, address: int, name: str):
|
||||
self.artnet = sender
|
||||
self.address = address
|
||||
self.name = name
|
||||
|
||||
def set(self, channel: int, value: int):
|
||||
self.artnet.set_slot(self.address + channel - 1, value)
|
||||
|
||||
def apply(
|
||||
self,
|
||||
*,
|
||||
pan: int,
|
||||
tilt: int,
|
||||
rgb: tuple[int, int, int],
|
||||
dimmer: int,
|
||||
focus: int,
|
||||
speed: int,
|
||||
zoom: int = 0,
|
||||
rotate: int = 0,
|
||||
):
|
||||
r, g, b = rgb
|
||||
self.set(CH_PAN, pan)
|
||||
self.set(CH_PAN + 1, 0)
|
||||
self.set(CH_TILT, tilt)
|
||||
self.set(CH_TILT + 1, 0)
|
||||
self.set(CH_SPEED, speed)
|
||||
self.set(CH_ZOOM, zoom)
|
||||
self.set(CH_ROTATE, rotate)
|
||||
self.set(CH_FOCUS, focus)
|
||||
self.set(CH_DIMMER, dimmer)
|
||||
self.set(CH_STROBE, 0)
|
||||
for i in range(PIXELS):
|
||||
base = CH_RED1 + i * 4
|
||||
self.set(base, r)
|
||||
self.set(base + 1, g)
|
||||
self.set(base + 2, b)
|
||||
self.set(base + 3, 0)
|
||||
|
||||
|
||||
class CabaretMovers:
|
||||
def __init__(
|
||||
self,
|
||||
movers: list[Mover],
|
||||
*,
|
||||
position: str = "down",
|
||||
color: str = "amber",
|
||||
pattern: str = "still",
|
||||
dimmer: int = 255,
|
||||
focus: int = FOCUS_DEFAULT,
|
||||
speed: int = 0,
|
||||
loop_s: float = LOOP_S,
|
||||
which: str = "both",
|
||||
):
|
||||
self.movers = movers
|
||||
self.position = position
|
||||
self.color = color
|
||||
self.pattern = pattern
|
||||
self.dimmer = dimmer
|
||||
self.focus = focus
|
||||
self.speed = speed
|
||||
self.loop_s = max(0.2, loop_s)
|
||||
self.which = which
|
||||
self._lock = threading.Lock()
|
||||
self._t0 = time.monotonic()
|
||||
self._fade_from = self._current_pts()
|
||||
self._fade_t0 = time.monotonic()
|
||||
|
||||
def _enabled(self) -> list[Mover]:
|
||||
if self.which == "1":
|
||||
return self.movers[:1]
|
||||
if self.which == "2":
|
||||
return self.movers[1:]
|
||||
return self.movers
|
||||
|
||||
def _current_pts(self) -> list[tuple[int, int]]:
|
||||
m1, m2 = POSITIONS[self.position]
|
||||
pts = [m1, m2]
|
||||
return pts[: len(self.movers)]
|
||||
|
||||
def set_look(
|
||||
self,
|
||||
*,
|
||||
position: str | None = None,
|
||||
color: str | None = None,
|
||||
pattern: str | None = None,
|
||||
dimmer: int | None = None,
|
||||
focus: int | None = None,
|
||||
speed: int | None = None,
|
||||
loop_s: float | None = None,
|
||||
which: str | None = None,
|
||||
fade: bool = True,
|
||||
):
|
||||
with self._lock:
|
||||
from_pts = self.tick_points(time.monotonic(), fading=False)
|
||||
if position is not None:
|
||||
self.position = position
|
||||
if color is not None:
|
||||
self.color = color
|
||||
if pattern is not None:
|
||||
self.pattern = pattern
|
||||
if dimmer is not None:
|
||||
self.dimmer = clamp(dimmer)
|
||||
if focus is not None:
|
||||
self.focus = clamp(focus)
|
||||
if speed is not None:
|
||||
self.speed = clamp(speed)
|
||||
if loop_s is not None:
|
||||
self.loop_s = max(0.2, loop_s)
|
||||
if which is not None:
|
||||
self.which = which
|
||||
if fade:
|
||||
self._fade_from = from_pts
|
||||
self._fade_t0 = time.monotonic()
|
||||
print(self.status(), flush=True)
|
||||
|
||||
def status(self) -> str:
|
||||
rgb = PALETTE[self.color]
|
||||
return (
|
||||
f"{self.position} {self.color} {rgb} {self.pattern} "
|
||||
f"dim {self.dimmer} focus {self.focus} {self.which}"
|
||||
)
|
||||
|
||||
def tick_points(self, now: float, *, fading: bool = True) -> list[tuple[int, int]]:
|
||||
algo, width, height, extra = PATTERNS[self.pattern]
|
||||
m1, m2 = POSITIONS[self.position]
|
||||
homes = [m1, m2]
|
||||
elapsed = now - self._t0
|
||||
t = (elapsed / self.loop_s) * 2.0 * math.pi
|
||||
pts: list[tuple[int, int]] = []
|
||||
for i, (pan0, tilt0) in enumerate(homes[: len(self.movers)]):
|
||||
if algo == "Still":
|
||||
pan, tilt = pan0, tilt0
|
||||
else:
|
||||
y, h = efx_fit(tilt0, height)
|
||||
x_freq = int(extra.get("x_freq", 1))
|
||||
cross = bool(extra.get("cross"))
|
||||
tt = t
|
||||
if cross and i == 1:
|
||||
tt = -t + math.pi
|
||||
x, y_u = efx_xy(algo, tt, x_freq=x_freq)
|
||||
pan = clamp(pan0 + x * (width / 2.0))
|
||||
tilt = clamp(y + y_u * (h / 2.0))
|
||||
pts.append((pan, tilt))
|
||||
if fading:
|
||||
fade_u = (now - self._fade_t0) / FADE_S
|
||||
if fade_u < 1.0:
|
||||
out = []
|
||||
for (p0, t0), (p1, t1) in zip(self._fade_from, pts):
|
||||
u = fade_u
|
||||
out.append((clamp(p0 + (p1 - p0) * u), clamp(t0 + (t1 - t0) * u)))
|
||||
return out
|
||||
return pts
|
||||
|
||||
def tick(self, now: float | None = None):
|
||||
now = time.monotonic() if now is None else now
|
||||
with self._lock:
|
||||
pts = self.tick_points(now)
|
||||
rgb = PALETTE[self.color]
|
||||
enabled = set(id(m) for m in self._enabled())
|
||||
for mover, (pan, tilt) in zip(self.movers, pts):
|
||||
if id(mover) not in enabled:
|
||||
mover.apply(
|
||||
pan=pan,
|
||||
tilt=tilt,
|
||||
rgb=(0, 0, 0),
|
||||
dimmer=0,
|
||||
focus=self.focus,
|
||||
speed=self.speed,
|
||||
)
|
||||
continue
|
||||
mover.apply(
|
||||
pan=pan,
|
||||
tilt=tilt,
|
||||
rgb=rgb,
|
||||
dimmer=self.dimmer,
|
||||
focus=self.focus,
|
||||
speed=self.speed,
|
||||
)
|
||||
|
||||
|
||||
class Animator:
|
||||
def __init__(self, show: CabaretMovers, hz: float = 40.0):
|
||||
self.show = show
|
||||
self.period = 1.0 / hz
|
||||
self._running = True
|
||||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _loop(self):
|
||||
while self._running:
|
||||
self.show.tick()
|
||||
time.sleep(self.period)
|
||||
|
||||
def close(self):
|
||||
self._running = False
|
||||
self._thread.join(timeout=1.0)
|
||||
|
||||
|
||||
def print_map():
|
||||
print("Cabaret movers (43ch, universe 0)")
|
||||
print(f" M1 start {M1_ADDR:3d} M2 start {M2_ADDR:3d} (M2 hung 180°)")
|
||||
print("Positions (DMX pan/tilt):")
|
||||
for name in POSITION_ORDER:
|
||||
m1, m2 = POSITIONS[name]
|
||||
print(f" {name:6s} M1 {m1[0]:3d}/{m1[1]:3d} M2 {m2[0]:3d}/{m2[1]:3d}")
|
||||
print("Colours:", ", ".join(COLOR_ORDER))
|
||||
print("Patterns:", ", ".join(PATTERN_ORDER))
|
||||
|
||||
|
||||
def run_demo(show: CabaretMovers, hold_s: float):
|
||||
print(f"Demo: positions, then patterns. {hold_s:.1f}s each. Ctrl+C to stop.")
|
||||
colours = list(COLOR_ORDER)
|
||||
ci = 0
|
||||
while True:
|
||||
show.set_look(pattern="still")
|
||||
for pos in POSITION_ORDER:
|
||||
show.set_look(position=pos, color=colours[ci % len(colours)])
|
||||
ci += 1
|
||||
time.sleep(hold_s)
|
||||
for pat in PATTERN_ORDER[1:]:
|
||||
for pos in POSITION_ORDER:
|
||||
show.set_look(
|
||||
position=pos,
|
||||
pattern=pat,
|
||||
color=colours[ci % len(colours)],
|
||||
)
|
||||
ci += 1
|
||||
time.sleep(hold_s)
|
||||
|
||||
|
||||
def run_hold(show: CabaretMovers):
|
||||
print("Holding look. Ctrl+C to blackout.")
|
||||
while True:
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def parse_token(token: str) -> str:
|
||||
return token.strip().lower().replace(" ", "").replace("-", "").replace("_", "")
|
||||
|
||||
|
||||
HELP = """commands:
|
||||
down roof wall mid cross out
|
||||
still figure8|f8 zigzag|zz swirl
|
||||
amber pink red green blue orange yellow purple
|
||||
dim N focus N speed N loop N m1|m2|both
|
||||
demo status help quit
|
||||
"""
|
||||
|
||||
|
||||
def run_interactive(show: CabaretMovers):
|
||||
print(HELP)
|
||||
print(show.status())
|
||||
while True:
|
||||
try:
|
||||
line = input("> ").strip()
|
||||
except EOFError:
|
||||
break
|
||||
if not line:
|
||||
continue
|
||||
parts = line.split()
|
||||
cmd = parse_token(parts[0])
|
||||
if cmd in ("quit", "exit", "q"):
|
||||
break
|
||||
if cmd in ("help", "?"):
|
||||
print(HELP)
|
||||
continue
|
||||
if cmd == "status":
|
||||
print(show.status())
|
||||
continue
|
||||
if cmd == "demo":
|
||||
try:
|
||||
run_demo(show, hold_s=4.0)
|
||||
except KeyboardInterrupt:
|
||||
print("\nback to prompt")
|
||||
continue
|
||||
if cmd in POSITIONS:
|
||||
show.set_look(position=cmd)
|
||||
continue
|
||||
aliases = {"f8": "figure8", "eight": "figure8", "zz": "zigzag", "circle": "swirl"}
|
||||
pat = aliases.get(cmd, cmd)
|
||||
if pat in PATTERNS:
|
||||
show.set_look(pattern=pat)
|
||||
continue
|
||||
if cmd in PALETTE:
|
||||
show.set_look(color=cmd)
|
||||
continue
|
||||
if cmd in ("m1", "1"):
|
||||
show.set_look(which="1", fade=False)
|
||||
continue
|
||||
if cmd in ("m2", "2"):
|
||||
show.set_look(which="2", fade=False)
|
||||
continue
|
||||
if cmd == "both":
|
||||
show.set_look(which="both", fade=False)
|
||||
continue
|
||||
if cmd in ("dim", "focus", "speed", "loop") and len(parts) >= 2:
|
||||
try:
|
||||
value = float(parts[1])
|
||||
except ValueError:
|
||||
print("need a number")
|
||||
continue
|
||||
kw = {"dim": "dimmer", "focus": "focus", "speed": "speed", "loop": "loop_s"}
|
||||
show.set_look(**{kw[cmd]: value}, fade=False)
|
||||
continue
|
||||
print(f"unknown: {line!r} (help)")
|
||||
|
||||
|
||||
def parse_args():
|
||||
p = argparse.ArgumentParser(
|
||||
description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
)
|
||||
p.add_argument("--ip", default=None, help=f"Art-Net destination (default: poll, else {DEFAULT_NODE})")
|
||||
p.add_argument("--universe", type=int, default=0)
|
||||
p.add_argument("--address", type=int, default=M1_ADDR, help="M1 DMX start, 1-based")
|
||||
p.add_argument("--address2", type=int, default=M2_ADDR, help="M2 DMX start, 1-based")
|
||||
p.add_argument("--position", default="down", choices=POSITION_ORDER)
|
||||
p.add_argument("--color", default="amber", choices=COLOR_ORDER)
|
||||
p.add_argument("--pattern", default="still", choices=PATTERN_ORDER)
|
||||
p.add_argument("--dimmer", type=int, default=255)
|
||||
p.add_argument("--focus", type=int, default=FOCUS_DEFAULT)
|
||||
p.add_argument("--speed", type=int, default=0, help="Pan/tilt speed: 0=fast, 255=slow")
|
||||
p.add_argument("--loop", type=float, default=LOOP_S, help="Seconds per EFX loop")
|
||||
p.add_argument("--which", choices=("both", "1", "2"), default="both")
|
||||
p.add_argument("--hold", type=float, default=4.0, help="Seconds per demo step")
|
||||
p.add_argument("--demo", action="store_true", help="Walk every position then every pattern")
|
||||
p.add_argument("--interactive", action="store_true", help="Type looks at a prompt")
|
||||
p.add_argument("--list", action="store_true", help="Print cabaret mover map and exit")
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
if args.list:
|
||||
print_map()
|
||||
return
|
||||
|
||||
ip = args.ip or discover_artnet_node()
|
||||
print_map()
|
||||
print(f"Art-Net → {ip} universe {args.universe}")
|
||||
print("Stop QLC+ Art-Net output first. Ctrl+C blackout.")
|
||||
|
||||
sender = ArtNetSender(ip, universe=args.universe)
|
||||
movers = [
|
||||
Mover(sender, args.address, "M1"),
|
||||
Mover(sender, args.address2, "M2"),
|
||||
]
|
||||
show = CabaretMovers(
|
||||
movers,
|
||||
position=args.position,
|
||||
color=args.color,
|
||||
pattern=args.pattern,
|
||||
dimmer=args.dimmer,
|
||||
focus=args.focus,
|
||||
speed=args.speed,
|
||||
loop_s=args.loop,
|
||||
which=args.which,
|
||||
)
|
||||
animator = Animator(show)
|
||||
try:
|
||||
print(show.status())
|
||||
if args.interactive or (not args.demo and sys.stdin.isatty() and args.pattern == "still"):
|
||||
run_interactive(show)
|
||||
elif args.demo:
|
||||
run_demo(show, args.hold)
|
||||
else:
|
||||
run_hold(show)
|
||||
except KeyboardInterrupt:
|
||||
print("\nstopped")
|
||||
finally:
|
||||
animator.close()
|
||||
sender.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Find how MidiSuite saves an SMC-PAD preset.
|
||||
|
||||
Downloads the current Windows MidiSuite and reads the compiled app.
|
||||
It prints the save method names and any finished vendor packets stored
|
||||
in the file. It does not connect to the pad.
|
||||
|
||||
python3 scripts/find_midisuite_save.py
|
||||
python3 scripts/find_midisuite_save.py --zip ~/MidiSuite_new.zip
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import sys
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
MIDISUITE_URL = "https://yms-file-store.oss-cn-hongkong.aliyuncs.com/software/pc/MidiSuite_new.zip"
|
||||
APP_SO = "Midi Suite/data/app.so"
|
||||
|
||||
# Names compiled into MidiSuite's SMC-PAD save path.
|
||||
SAVE_NAMES = (
|
||||
"flashSave0",
|
||||
"save0Packet",
|
||||
"flashWrite",
|
||||
"flashRead",
|
||||
"flashErase",
|
||||
"smc_pad_desktop_save",
|
||||
)
|
||||
|
||||
READ_COMMAND = 0x23
|
||||
WRITE_COMMAND = 0x22
|
||||
|
||||
|
||||
def strings(blob: bytes, shortest: int = 4) -> list[str]:
|
||||
found: list[str] = []
|
||||
current = bytearray()
|
||||
for byte in blob:
|
||||
if 32 <= byte < 127:
|
||||
current.append(byte)
|
||||
continue
|
||||
if len(current) >= shortest:
|
||||
found.append(current.decode())
|
||||
current = bytearray()
|
||||
if len(current) >= shortest:
|
||||
found.append(current.decode())
|
||||
return found
|
||||
|
||||
|
||||
def save_names(blob: bytes) -> list[str]:
|
||||
present = set(strings(blob))
|
||||
return [name for name in SAVE_NAMES if name in present]
|
||||
|
||||
|
||||
def literal_packets(blob: bytes) -> list[tuple[int, int]]:
|
||||
"""Offsets of stored ``00 59`` read or write packets."""
|
||||
found: list[tuple[int, int]] = []
|
||||
start = 0
|
||||
marker = b"\x00\x59"
|
||||
while True:
|
||||
index = blob.find(marker, start)
|
||||
if index < 0 or index + 2 >= len(blob):
|
||||
break
|
||||
command = blob[index + 2]
|
||||
if command in (READ_COMMAND, WRITE_COMMAND):
|
||||
found.append((index, command))
|
||||
start = index + 1
|
||||
return found
|
||||
|
||||
|
||||
def app_so(package: bytes) -> bytes:
|
||||
with zipfile.ZipFile(io.BytesIO(package)) as archive:
|
||||
try:
|
||||
return archive.read(APP_SO)
|
||||
except KeyError:
|
||||
names = [name for name in archive.namelist() if name.endswith("app.so")]
|
||||
if not names:
|
||||
raise SystemExit("MidiSuite zip has no app.so")
|
||||
return archive.read(names[0])
|
||||
|
||||
|
||||
def report(blob: bytes) -> str:
|
||||
names = save_names(blob)
|
||||
packets = literal_packets(blob)
|
||||
lines = ["MidiSuite save names:"]
|
||||
if names:
|
||||
lines.extend(f" {name}" for name in names)
|
||||
else:
|
||||
lines.append(" none")
|
||||
lines.append("Stored 00 59 read/write packets:")
|
||||
if packets:
|
||||
for offset, command in packets:
|
||||
kind = "write" if command == WRITE_COMMAND else "read"
|
||||
lines.append(f" {offset:#x} command {command:#04x} {kind}")
|
||||
else:
|
||||
lines.append(" none")
|
||||
if "flashSave0" in names and not packets:
|
||||
lines.append(
|
||||
"Save is the flashSave0 method. It builds save0Packet when MidiSuite runs. "
|
||||
"The finished packet is not stored in the file."
|
||||
)
|
||||
lines.append("Nothing was sent to the pad.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def download(url: str = MIDISUITE_URL) -> bytes:
|
||||
with urllib.request.urlopen(url, timeout=120) as response:
|
||||
return response.read()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--zip", type=Path, help="MidiSuite_new.zip, downloaded when omitted")
|
||||
parser.add_argument("--so", type=Path, help="an already extracted app.so")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.so:
|
||||
blob = args.so.read_bytes()
|
||||
else:
|
||||
package = args.zip.read_bytes() if args.zip else download()
|
||||
blob = app_so(package)
|
||||
print(report(blob))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+219
@@ -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
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# Link this repo's RGB scripts, fixtures and input profiles into ~/.qlcplus,
|
||||
# where QLC+ looks for them. The shows' can patterns use rgbscripts/steps.js
|
||||
# and swap.js, so without them those matrices do nothing. Restart QLC+ after
|
||||
# running this: it reads these folders at startup.
|
||||
#
|
||||
# scripts/install_qlcplus.sh # link what is missing; keep files that differ
|
||||
# scripts/install_qlcplus.sh --force # replace files that differ with links
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
USER_DIR="$HOME/.qlcplus"
|
||||
FORCE=
|
||||
[[ "${1:-}" == "--force" ]] && FORCE=1
|
||||
|
||||
for dir in rgbscripts fixtures inputprofiles; do
|
||||
mkdir -p "$USER_DIR/$dir"
|
||||
for src in "$ROOT/$dir"/*; do
|
||||
dest="$USER_DIR/$dir/$(basename "$src")"
|
||||
if [[ -L "$dest" && "$(readlink -f "$dest")" == "$src" ]]; then
|
||||
continue
|
||||
fi
|
||||
if [[ -e "$dest" && ! -L "$dest" ]] && ! cmp -s "$src" "$dest" && [[ -z "$FORCE" ]]; then
|
||||
echo "Kept $dest: it differs from $dir/$(basename "$src"). --force replaces it." >&2
|
||||
continue
|
||||
fi
|
||||
ln -sfn "$src" "$dest"
|
||||
echo "Linked $dest"
|
||||
done
|
||||
done
|
||||
@@ -0,0 +1,953 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate shows/twisted.qxw — 15 cans + 4 movers with SMC-PAD MIDI.
|
||||
|
||||
Level sliders: knobs 1–16 (MIDI CC 30–45 on Universe 2).
|
||||
Pad banks (8 each, SoloFrame + MIDI notes):
|
||||
Movers 1–8 pad 1 wander, pad 5 all Colour 1, pad 6 outer 1 / centre 2
|
||||
Cans 9–16 pad 13 all Colour 1, pad 14 split
|
||||
|
||||
Can colour (one writer per fixture channel):
|
||||
Colour 1 knobs → Level on C1 cans + mover outer; Playback scenes on the
|
||||
other cans (All C1 only). Same MIDI, disjoint fixtures.
|
||||
Colour 2 knobs → Level on mover centre only; Playback on C2 cans (Split).
|
||||
No fixture channel is wired to two sliders at once.
|
||||
|
||||
pipenv run python scripts/make_twisted_vc.py
|
||||
|
||||
shows/twisted.qxw also has hand-built functions (venue wave, static,
|
||||
mover centre off). Regenerating from this script drops those.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "shows" / "twisted.qxw"
|
||||
|
||||
# Fixture IDs
|
||||
CAN_1_8 = list(range(8))
|
||||
# Cans 9–12 (13–15 dim on shared auto-cans slider)
|
||||
CAN_9_12 = [8, 9, 10, 11]
|
||||
ALL_CANS = list(range(15))
|
||||
# Cans 13–15: R→purple→yellow chasers, one full fade apart (≈120° on the cycle).
|
||||
CAN13_FID = 12
|
||||
CAN14_FID = 13
|
||||
CAN15_FID = 14
|
||||
AUTO_COLOR_CANS = frozenset({CAN13_FID, CAN14_FID, CAN15_FID})
|
||||
# Colour 1: cans 1–12 only.
|
||||
C1_CANS = list(range(12)) # fixtures 0–11
|
||||
C2_CANS: list[int] = [] # split pad stops C1ext; no can Colour 2
|
||||
C1_EXT_CANS = sorted(set(ALL_CANS) - set(C1_CANS) - AUTO_COLOR_CANS)
|
||||
MOVERS = [15, 16, 17, 18] # Front L/R, Back L/R
|
||||
MOVERS_FRONT = [15, 16]
|
||||
MOVER_BACK_LEFT = 17
|
||||
MOVER_BACK_RIGHT = 18
|
||||
PAN_OFFSET_BL = 64 # +90°
|
||||
PAN_OFFSET_BR = 192 # −90°
|
||||
# Private CCs. Knob 9/10 stay on CC 38/39; scripts/mover_offsets_midi.py
|
||||
# adds that encoder step onto each of these so the corrections survive.
|
||||
PAN_MIDI = (50, 51, 52, 53) # FL FR BL BR
|
||||
TILT_MIDI = (54, 55, 56, 57)
|
||||
|
||||
FID_WANDER = 0 # pad 1
|
||||
FID_WANDER_FRONT = 54
|
||||
FID_WANDER_BACK = 55
|
||||
# One slow circle around the live aim. ±18 pan, ±12 tilt, 24s.
|
||||
WANDER_MS = 24000
|
||||
WANDER_FADE_MS = 4000
|
||||
WANDER_PAN = 18
|
||||
WANDER_TILT = 12
|
||||
WANDER_BG = "4294953472"
|
||||
FID_MOVER_ALL_C1 = 4
|
||||
FID_MOVER_SPLIT = 5
|
||||
FID_CAN_ALL_C1 = 12
|
||||
FID_CAN_SPLIT = 13
|
||||
FID_C1EXT_R, FID_C1EXT_G, FID_C1EXT_B = 16, 17, 18
|
||||
FID_C2PB_R, FID_C2PB_G, FID_C2PB_B = 19, 20, 21
|
||||
FID_CAN13_RED, FID_CAN13_PURPLE, FID_CAN13_YELLOW = 23, 24, 25
|
||||
FID_CAN13_CHASER = 26
|
||||
FID_CAN14_RED, FID_CAN14_PURPLE, FID_CAN14_YELLOW = 27, 28, 29
|
||||
FID_CAN14_CHASER = 30
|
||||
FID_CAN_AUTOCHASER_START = 31
|
||||
FID_CAN15_RED, FID_CAN15_PURPLE, FID_CAN15_YELLOW = 32, 33, 34
|
||||
FID_CAN15_CHASER = 35
|
||||
STARTUP_ID = 22
|
||||
CAN_CHASE_MS = 3500
|
||||
CAN_CHASE_PHASE_MS = CAN_CHASE_MS
|
||||
CAN_TRANSITION_MIN_MS = 500
|
||||
CAN_TRANSITION_MAX_MS = 10000
|
||||
# Speed Dial visibility: PlusMinus=2 Seconds=32 Milliseconds=64
|
||||
SPEED_VIS_FADER = 2 | 32 | 64
|
||||
|
||||
MOVER_R_CENTER = [10]
|
||||
MOVER_G_CENTER = [11]
|
||||
MOVER_B_CENTER = [12]
|
||||
MOVER_R_OUTER = [14, 18, 22, 26, 30, 34]
|
||||
MOVER_G_OUTER = [15, 19, 23, 27, 31, 35]
|
||||
MOVER_B_OUTER = [16, 20, 24, 28, 32, 36]
|
||||
|
||||
MOVER_ADDRS = (0, 44, 257, 300)
|
||||
MOVER_NAMES = (
|
||||
"Front Left Mover",
|
||||
"Front Right Mover",
|
||||
"Back Left Mover",
|
||||
"Back Right Mover",
|
||||
)
|
||||
|
||||
|
||||
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 label_frame(caption: str, x: int, y: int, w: int, h: int = 28) -> str:
|
||||
return f""" <Frame Caption="{caption}">
|
||||
<Appearance>
|
||||
<FrameStyle>Sunken</FrameStyle>
|
||||
<ForegroundColor>Default</ForegroundColor>
|
||||
<BackgroundColor>Default</BackgroundColor>
|
||||
<BackgroundImage>None</BackgroundImage>
|
||||
<Font>Default</Font>
|
||||
</Appearance>
|
||||
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
|
||||
<AllowChildren>True</AllowChildren>
|
||||
<AllowResize>True</AllowResize>
|
||||
<ShowHeader>True</ShowHeader>
|
||||
<ShowEnableButton>False</ShowEnableButton>
|
||||
<ShowIntensityButton>False</ShowIntensityButton>
|
||||
<Mixing>False</Mixing>
|
||||
</Frame>"""
|
||||
|
||||
|
||||
def knob_cc(knob: int) -> int:
|
||||
return 29 + knob
|
||||
|
||||
|
||||
def pad_input_channel(pad: int) -> int:
|
||||
note = 35 + pad
|
||||
return 128 + note
|
||||
|
||||
|
||||
def relative_circle(
|
||||
func_id: int,
|
||||
name: str,
|
||||
fixtures: list[tuple[int, int]],
|
||||
*,
|
||||
rotation: int,
|
||||
) -> str:
|
||||
"""Relative circle around the live pan/tilt. Offset 127 is no shift."""
|
||||
fixture_xml = "\n".join(
|
||||
f""" <Fixture>
|
||||
<ID>{fid}</ID>
|
||||
<Head>0</Head>
|
||||
<Mode>0</Mode>
|
||||
<Direction>Forward</Direction>
|
||||
<StartOffset>{offset}</StartOffset>
|
||||
</Fixture>"""
|
||||
for fid, offset in fixtures
|
||||
)
|
||||
return f""" <Function ID="{func_id}" Type="EFX" Name="{name}">
|
||||
{fixture_xml}
|
||||
<PropagationMode>Parallel</PropagationMode>
|
||||
<Speed FadeIn="{WANDER_FADE_MS}" FadeOut="0" Duration="{WANDER_MS}"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>Loop</RunOrder>
|
||||
<Algorithm>Circle</Algorithm>
|
||||
<Width>{WANDER_PAN}</Width>
|
||||
<Height>{WANDER_TILT}</Height>
|
||||
<Rotation>{rotation}</Rotation>
|
||||
<StartOffset>0</StartOffset>
|
||||
<IsRelative>1</IsRelative>
|
||||
<Axis Name="X">
|
||||
<Offset>127</Offset>
|
||||
<Frequency>1</Frequency>
|
||||
<Phase>0</Phase>
|
||||
</Axis>
|
||||
<Axis Name="Y">
|
||||
<Offset>127</Offset>
|
||||
<Frequency>1</Frequency>
|
||||
<Phase>0</Phase>
|
||||
</Axis>
|
||||
</Function>"""
|
||||
|
||||
|
||||
def collection(func_id: int, name: str, steps: list[int]) -> str:
|
||||
step_xml = "\n".join(
|
||||
f' <Step Number="{i}">{sid}</Step>' for i, sid in enumerate(steps)
|
||||
)
|
||||
return f""" <Function ID="{func_id}" Type="Collection" Name="{name}">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
|
||||
{step_xml}
|
||||
</Function>"""
|
||||
|
||||
|
||||
def scene(func_id: int, name: str) -> str:
|
||||
return f""" <Function ID="{func_id}" Type="Scene" Name="{name}">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
|
||||
</Function>"""
|
||||
|
||||
|
||||
def chaser_xml(
|
||||
func_id: int,
|
||||
name: str,
|
||||
steps: list[int],
|
||||
*,
|
||||
fade_in: int,
|
||||
hold: int = 0,
|
||||
fade_out: int = 0,
|
||||
) -> str:
|
||||
duration = fade_in + hold + fade_out
|
||||
step_xml = "\n".join(
|
||||
f' <Step Number="{i}" FadeIn="{fade_in}" Hold="{hold}" FadeOut="{fade_out}">{sid}</Step>'
|
||||
for i, sid in enumerate(steps)
|
||||
)
|
||||
return f""" <Function ID="{func_id}" Type="Chaser" Name="{name}">
|
||||
<Speed FadeIn="{fade_in}" FadeOut="{fade_out}" Duration="{duration}"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>Loop</RunOrder>
|
||||
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common"/>
|
||||
{step_xml}
|
||||
</Function>"""
|
||||
|
||||
|
||||
def solo_can_color_scene(
|
||||
can_fid: int, func_id: int, name: str, r: int, g: int, b: int
|
||||
) -> str:
|
||||
return channel_scene(
|
||||
func_id,
|
||||
name,
|
||||
[can_fid],
|
||||
[(2, r), (3, g), (4, b)],
|
||||
)
|
||||
|
||||
|
||||
def channel_scene(
|
||||
func_id: int,
|
||||
name: str,
|
||||
fixtures: list[int],
|
||||
values: list[tuple[int, int]],
|
||||
) -> str:
|
||||
payload = ",".join(f"{ch},{val}" for ch, val in values)
|
||||
vals = "\n".join(
|
||||
f' <FixtureVal ID="{fid}">{payload}</FixtureVal>' for fid in fixtures
|
||||
)
|
||||
return f""" <Function ID="{func_id}" Type="Scene" Name="{name}">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
|
||||
{vals}
|
||||
</Function>"""
|
||||
|
||||
|
||||
def script(func_id: int, name: str, lines: list[str]) -> str:
|
||||
cmds = "\n".join(
|
||||
f" <Command>{quote(line, safe='')}</Command>" for line in lines
|
||||
)
|
||||
return f""" <Function ID="{func_id}" Type="Script" Name="{name}">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>Loop</RunOrder>
|
||||
{cmds}
|
||||
</Function>"""
|
||||
|
||||
|
||||
def hold_mode_script(
|
||||
func_id: int,
|
||||
name: str,
|
||||
*,
|
||||
start: list[int] | None = None,
|
||||
stop: list[int] | None = None,
|
||||
) -> str:
|
||||
lines = ["stoponexit:false"]
|
||||
for fid in stop or []:
|
||||
lines.append(f"stopfunction:{fid}")
|
||||
for fid in start or []:
|
||||
lines.append(f"startfunction:{fid}")
|
||||
lines.extend(["label:keep", "wait:3600000", "jump:keep"])
|
||||
return script(func_id, name, lines)
|
||||
|
||||
|
||||
def button(
|
||||
wid: int,
|
||||
caption: str,
|
||||
func_id: int,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
*,
|
||||
pad: int | None = None,
|
||||
bg: str = "4282664004",
|
||||
fg: str = "4294967295",
|
||||
indent: str = " ",
|
||||
) -> str:
|
||||
midi = ""
|
||||
if pad is not None:
|
||||
midi = f"\n{indent} <Input Universe=\"1\" Channel=\"{pad_input_channel(pad)}\"/>"
|
||||
return f"""{indent}<Button Caption="{caption}" ID="{wid}" Icon="">
|
||||
{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
|
||||
{indent} <Appearance>
|
||||
{indent} <FrameStyle>None</FrameStyle>
|
||||
{indent} <ForegroundColor>{fg}</ForegroundColor>
|
||||
{indent} <BackgroundColor>{bg}</BackgroundColor>
|
||||
{indent} <BackgroundImage>None</BackgroundImage>
|
||||
{indent} <Font>Default</Font>
|
||||
{indent} </Appearance>{midi}
|
||||
{indent} <Function ID="{func_id}"/>
|
||||
{indent} <Action>Toggle</Action>
|
||||
{indent} <Intensity Adjust="False">100</Intensity>
|
||||
{indent}</Button>"""
|
||||
|
||||
|
||||
def solo_frame(
|
||||
wid: int,
|
||||
caption: str,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
children: str,
|
||||
) -> str:
|
||||
return f""" <SoloFrame Caption="{caption}" ID="{wid}">
|
||||
<Appearance>
|
||||
<FrameStyle>Sunken</FrameStyle>
|
||||
<ForegroundColor>Default</ForegroundColor>
|
||||
<BackgroundColor>Default</BackgroundColor>
|
||||
<BackgroundImage>None</BackgroundImage>
|
||||
<Font>Default</Font>
|
||||
</Appearance>
|
||||
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
|
||||
<AllowChildren>True</AllowChildren>
|
||||
<AllowResize>True</AllowResize>
|
||||
<ShowHeader>True</ShowHeader>
|
||||
<ShowEnableButton>False</ShowEnableButton>
|
||||
<Mixing>False</Mixing>
|
||||
{children}
|
||||
</SoloFrame>"""
|
||||
|
||||
|
||||
def slider(
|
||||
wid: int,
|
||||
caption: str,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
channels: list[tuple[int, int]],
|
||||
*,
|
||||
knob: int | None = None,
|
||||
midi: int | None = None,
|
||||
value: int = 0,
|
||||
fg: str = "Default",
|
||||
cng: str = "None",
|
||||
) -> str:
|
||||
ch_xml = "\n".join(
|
||||
f' <Channel Fixture="{fid}">{ch}</Channel>' for fid, ch in channels
|
||||
)
|
||||
channel = midi if midi is not None else (None if knob is None else knob_cc(knob))
|
||||
midi_xml = ""
|
||||
if channel is not None:
|
||||
midi_xml = f'\n <Input Universe="1" Channel="{channel}"/>'
|
||||
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">
|
||||
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
|
||||
{appearance(fg=fg)}{midi_xml}
|
||||
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="false">Level</SliderMode>
|
||||
<Level LowLimit="0" HighLimit="255" Value="{value}">
|
||||
{ch_xml}
|
||||
</Level>
|
||||
<Playback>
|
||||
<Function>4294967295</Function>
|
||||
</Playback>
|
||||
</Slider>"""
|
||||
|
||||
|
||||
def speed_dial(
|
||||
wid: int,
|
||||
caption: str,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
time_ms: int,
|
||||
functions: list[tuple[int, int, int]],
|
||||
*,
|
||||
min_ms: int = CAN_TRANSITION_MIN_MS,
|
||||
max_ms: int = CAN_TRANSITION_MAX_MS,
|
||||
visibility: int = SPEED_VIS_FADER,
|
||||
knob: int | None = None,
|
||||
) -> str:
|
||||
"""functions are (func_id, duration_mult, fade_in_mult); 0 = not sent."""
|
||||
fn_xml = "\n".join(
|
||||
f' <Function FadeIn="{fade}" FadeOut="0" Duration="{dur}">{fid}</Function>'
|
||||
for fid, dur, fade in functions
|
||||
)
|
||||
midi = ""
|
||||
if knob is not None:
|
||||
midi = f'\n <Input Universe="1" Channel="{knob_cc(knob)}"/>'
|
||||
return f""" <SpeedDial Caption="{caption}" ID="{wid}">
|
||||
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
|
||||
{appearance()}{midi}
|
||||
<Visibility>{visibility}</Visibility>
|
||||
<AbsoluteValue Minimum="{min_ms}" Maximum="{max_ms}"/>
|
||||
<Time>{time_ms}</Time>
|
||||
{fn_xml}
|
||||
</SpeedDial>"""
|
||||
|
||||
|
||||
def playback_slider(
|
||||
wid: int,
|
||||
caption: str,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
func_id: int,
|
||||
*,
|
||||
knob: int,
|
||||
fg: str = "Default",
|
||||
cng: str = "None",
|
||||
) -> str:
|
||||
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">
|
||||
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
|
||||
{appearance(fg=fg)}
|
||||
<Input Universe="1" Channel="{knob_cc(knob)}"/>
|
||||
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="false">Playback</SliderMode>
|
||||
<Level LowLimit="0" HighLimit="255" Value="0"/>
|
||||
<Playback>
|
||||
<Function>{func_id}</Function>
|
||||
</Playback>
|
||||
</Slider>"""
|
||||
|
||||
|
||||
def fixture_xml() -> str:
|
||||
parts: list[str] = []
|
||||
for i in range(15):
|
||||
parts.append(
|
||||
f""" <Fixture>
|
||||
<Manufacturer>beamZ</Manufacturer>
|
||||
<Model>BCC145</Model>
|
||||
<Mode>8 Channel</Mode>
|
||||
<ID>{i}</ID>
|
||||
<Name>BCC145 #{i + 1:02d}</Name>
|
||||
<Universe>0</Universe>
|
||||
<Address>{87 + i * 8}</Address>
|
||||
<Channels>8</Channels>
|
||||
</Fixture>"""
|
||||
)
|
||||
for i, (addr, name) in enumerate(zip(MOVER_ADDRS, MOVER_NAMES)):
|
||||
parts.append(
|
||||
f""" <Fixture>
|
||||
<Manufacturer>Small Eye 7</Manufacturer>
|
||||
<Model>Mover</Model>
|
||||
<Mode>43 Channel</Mode>
|
||||
<ID>{15 + i}</ID>
|
||||
<Name>{name}</Name>
|
||||
<Universe>0</Universe>
|
||||
<Address>{addr}</Address>
|
||||
<Channels>43</Channels>
|
||||
</Fixture>"""
|
||||
)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
sl_w, sl_h = 52, 200
|
||||
gap = 8
|
||||
group_gap = 24
|
||||
row_gap = 20
|
||||
widgets: list[str] = []
|
||||
wid = 0
|
||||
max_x = 0
|
||||
max_y = 0
|
||||
|
||||
def place(caption, x, y, channels, *, knob=None, midi=None, value=0, fg="Default", cng="None"):
|
||||
nonlocal wid, max_x, max_y
|
||||
widgets.append(
|
||||
slider(
|
||||
wid,
|
||||
caption,
|
||||
x,
|
||||
y,
|
||||
sl_w,
|
||||
sl_h,
|
||||
channels,
|
||||
knob=knob,
|
||||
midi=midi,
|
||||
value=value,
|
||||
fg=fg,
|
||||
cng=cng,
|
||||
)
|
||||
)
|
||||
wid += 1
|
||||
max_x = max(max_x, x + sl_w)
|
||||
max_y = max(max_y, y + sl_h)
|
||||
|
||||
def header(caption: str, x: int, y: int, cols: int) -> None:
|
||||
w = cols * sl_w + (cols - 1) * gap
|
||||
widgets.append(label_frame(caption, x, y, w))
|
||||
|
||||
btn_w, btn_h = 72, 48
|
||||
btn_gap = 6
|
||||
bank_pad = 10
|
||||
cols, rows = 4, 2
|
||||
bank_inner_w = cols * btn_w + (cols - 1) * btn_gap
|
||||
bank_w = bank_pad * 2 + bank_inner_w
|
||||
bank_h = 28 + rows * btn_h + (rows - 1) * btn_gap + bank_pad
|
||||
|
||||
mover_labels = {
|
||||
1: ("Wander", WANDER_BG),
|
||||
5: ("All C1", "4278236360"),
|
||||
6: ("Outer/Ctr", "4282664004"),
|
||||
}
|
||||
can_labels = {
|
||||
13: ("All C1", "4284900966"),
|
||||
14: ("Split 1/2", "4286611584"),
|
||||
}
|
||||
|
||||
c1ext_ids = (FID_C1EXT_R, FID_C1EXT_G, FID_C1EXT_B)
|
||||
c2pb_ids = (FID_C2PB_R, FID_C2PB_G, FID_C2PB_B)
|
||||
|
||||
functions_list = [scene(i, f"Pad {i + 1}") for i in range(16)]
|
||||
# Back heads are hung 90°, so their box is rotated to match the room.
|
||||
functions_list[FID_WANDER] = collection(
|
||||
FID_WANDER,
|
||||
"Wander",
|
||||
[FID_WANDER_FRONT, FID_WANDER_BACK],
|
||||
)
|
||||
functions_list[FID_MOVER_ALL_C1] = scene(FID_MOVER_ALL_C1, "Movers: All Colour 1")
|
||||
functions_list[FID_MOVER_SPLIT] = scene(FID_MOVER_SPLIT, "Movers: Outer 1 / Centre 2")
|
||||
functions_list[FID_CAN_ALL_C1] = hold_mode_script(
|
||||
FID_CAN_ALL_C1,
|
||||
"Cans: All Colour 1",
|
||||
stop=list(c2pb_ids),
|
||||
)
|
||||
functions_list[FID_CAN_SPLIT] = hold_mode_script(
|
||||
FID_CAN_SPLIT,
|
||||
"Cans: Split Colour 1 / 2",
|
||||
stop=list(c1ext_ids),
|
||||
)
|
||||
functions_list.extend(
|
||||
[
|
||||
channel_scene(FID_C1EXT_R, "C1ext R", C1_EXT_CANS, [(2, 255)]),
|
||||
channel_scene(FID_C1EXT_G, "C1ext G", C1_EXT_CANS, [(3, 255)]),
|
||||
channel_scene(FID_C1EXT_B, "C1ext B", C1_EXT_CANS, [(4, 255)]),
|
||||
channel_scene(FID_C2PB_R, "C2 cans R", C2_CANS, [(2, 255)]),
|
||||
channel_scene(FID_C2PB_G, "C2 cans G", C2_CANS, [(3, 255)]),
|
||||
channel_scene(FID_C2PB_B, "C2 cans B", C2_CANS, [(4, 255)]),
|
||||
solo_can_color_scene(
|
||||
CAN13_FID, FID_CAN13_RED, "Can 13 Red", 255, 0, 0
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN13_FID, FID_CAN13_PURPLE, "Can 13 Purple", 200, 0, 255
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN13_FID, FID_CAN13_YELLOW, "Can 13 Yellow", 255, 200, 0
|
||||
),
|
||||
chaser_xml(
|
||||
FID_CAN13_CHASER,
|
||||
"Can 13 Red Purple Yellow",
|
||||
[FID_CAN13_RED, FID_CAN13_PURPLE, FID_CAN13_YELLOW],
|
||||
fade_in=CAN_CHASE_MS,
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN14_FID, FID_CAN14_RED, "Can 14 Red", 255, 0, 0
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN14_FID, FID_CAN14_PURPLE, "Can 14 Purple", 200, 0, 255
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN14_FID, FID_CAN14_YELLOW, "Can 14 Yellow", 255, 200, 0
|
||||
),
|
||||
chaser_xml(
|
||||
FID_CAN14_CHASER,
|
||||
"Can 14 Red Purple Yellow",
|
||||
[FID_CAN14_RED, FID_CAN14_PURPLE, FID_CAN14_YELLOW],
|
||||
fade_in=CAN_CHASE_MS,
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN15_FID, FID_CAN15_RED, "Can 15 Red", 255, 0, 0
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN15_FID, FID_CAN15_PURPLE, "Can 15 Purple", 200, 0, 255
|
||||
),
|
||||
solo_can_color_scene(
|
||||
CAN15_FID, FID_CAN15_YELLOW, "Can 15 Yellow", 255, 200, 0
|
||||
),
|
||||
chaser_xml(
|
||||
FID_CAN15_CHASER,
|
||||
"Can 15 Red Purple Yellow",
|
||||
[FID_CAN15_RED, FID_CAN15_PURPLE, FID_CAN15_YELLOW],
|
||||
fade_in=CAN_CHASE_MS,
|
||||
),
|
||||
script(
|
||||
FID_CAN_AUTOCHASER_START,
|
||||
"Start can 13/14/15 chasers phased",
|
||||
[
|
||||
"stoponexit:false",
|
||||
f"startfunction:{FID_CAN13_CHASER}",
|
||||
f"wait:{CAN_CHASE_PHASE_MS}",
|
||||
f"startfunction:{FID_CAN14_CHASER}",
|
||||
f"wait:{CAN_CHASE_PHASE_MS}",
|
||||
f"startfunction:{FID_CAN15_CHASER}",
|
||||
"label:keep",
|
||||
"wait:3600000",
|
||||
"jump:keep",
|
||||
],
|
||||
),
|
||||
f""" <Function ID="{STARTUP_ID}" Type="Collection" Name="Startup: All Colour 1">
|
||||
<Step Number="0">{FID_CAN_ALL_C1}</Step>
|
||||
<Step Number="1">{FID_MOVER_ALL_C1}</Step>
|
||||
<Step Number="2">{FID_CAN_AUTOCHASER_START}</Step>
|
||||
<Step Number="3">{FID_WANDER}</Step>
|
||||
</Function>""",
|
||||
relative_circle(
|
||||
FID_WANDER_FRONT,
|
||||
"Wander front",
|
||||
[(MOVERS_FRONT[0], 0), (MOVERS_FRONT[1], 180)],
|
||||
rotation=0,
|
||||
),
|
||||
relative_circle(
|
||||
FID_WANDER_BACK,
|
||||
"Wander back",
|
||||
[(MOVER_BACK_LEFT, 90), (MOVER_BACK_RIGHT, 270)],
|
||||
rotation=90,
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
def pad_bank(
|
||||
title: str,
|
||||
pads: range,
|
||||
labels: dict[int, tuple[str, str]],
|
||||
x0: int,
|
||||
y0: int,
|
||||
default_bg: str,
|
||||
) -> None:
|
||||
nonlocal wid, max_x, max_y
|
||||
kids: list[str] = []
|
||||
for i, pad in enumerate(pads):
|
||||
col = i % cols
|
||||
row = (rows - 1) - (i // cols)
|
||||
bx = bank_pad + col * (btn_w + btn_gap)
|
||||
by = 28 + row * (btn_h + btn_gap)
|
||||
if pad in labels:
|
||||
caption, bg = labels[pad]
|
||||
else:
|
||||
caption, bg = "", default_bg
|
||||
kids.append(
|
||||
button(
|
||||
wid + i,
|
||||
caption,
|
||||
pad - 1,
|
||||
bx,
|
||||
by,
|
||||
btn_w,
|
||||
btn_h,
|
||||
pad=pad,
|
||||
bg=bg,
|
||||
)
|
||||
)
|
||||
frame_id = wid + len(pads)
|
||||
widgets.append(
|
||||
solo_frame(frame_id, title, x0, y0, bank_w, bank_h, "\n".join(kids))
|
||||
)
|
||||
wid = frame_id + 1
|
||||
max_x = max(max_x, x0 + bank_w)
|
||||
max_y = max(max_y, y0 + bank_h)
|
||||
|
||||
left_x = 16
|
||||
label_y1 = 12
|
||||
y1 = 44
|
||||
x = left_x
|
||||
|
||||
header("Colour 1 (outer)", x, label_y1, 3)
|
||||
place(
|
||||
"R",
|
||||
x,
|
||||
y1,
|
||||
[(f, 2) for f in C1_CANS] + [(m, c) for m in MOVERS for c in MOVER_R_OUTER],
|
||||
knob=5,
|
||||
fg="4294901760",
|
||||
cng="Red",
|
||||
)
|
||||
place(
|
||||
"G",
|
||||
x + sl_w + gap,
|
||||
y1,
|
||||
[(f, 3) for f in C1_CANS] + [(m, c) for m in MOVERS for c in MOVER_G_OUTER],
|
||||
knob=3,
|
||||
fg="4278255360",
|
||||
cng="Green",
|
||||
)
|
||||
place(
|
||||
"B",
|
||||
x + 2 * (sl_w + gap),
|
||||
y1,
|
||||
[(f, 4) for f in C1_CANS] + [(m, c) for m in MOVERS for c in MOVER_B_OUTER],
|
||||
knob=1,
|
||||
fg="4278190335",
|
||||
cng="Blue",
|
||||
)
|
||||
c1_x = x
|
||||
x += 3 * (sl_w + gap) + group_gap
|
||||
|
||||
header("Colour 2 (centre)", x, label_y1, 3)
|
||||
place(
|
||||
"R",
|
||||
x,
|
||||
y1,
|
||||
[(m, c) for m in MOVERS for c in MOVER_R_CENTER],
|
||||
knob=6,
|
||||
fg="4294901760",
|
||||
cng="Red",
|
||||
)
|
||||
place(
|
||||
"G",
|
||||
x + sl_w + gap,
|
||||
y1,
|
||||
[(m, c) for m in MOVERS for c in MOVER_G_CENTER],
|
||||
knob=4,
|
||||
fg="4278255360",
|
||||
cng="Green",
|
||||
)
|
||||
place(
|
||||
"B",
|
||||
x + 2 * (sl_w + gap),
|
||||
y1,
|
||||
[(m, c) for m in MOVERS for c in MOVER_B_CENTER],
|
||||
knob=2,
|
||||
fg="4278190335",
|
||||
cng="Blue",
|
||||
)
|
||||
c2_x = x
|
||||
colours_right = x + 3 * (sl_w + gap)
|
||||
auto_dim_x = colours_right + group_gap
|
||||
header("Can 13–15", auto_dim_x, label_y1, 2)
|
||||
place(
|
||||
"Bright",
|
||||
auto_dim_x,
|
||||
y1,
|
||||
[(CAN13_FID, 0), (CAN14_FID, 0), (CAN15_FID, 0)],
|
||||
knob=7,
|
||||
)
|
||||
transition_funcs = [
|
||||
(FID_CAN13_CHASER, 6, 6),
|
||||
(FID_CAN14_CHASER, 6, 6),
|
||||
(FID_CAN15_CHASER, 6, 6),
|
||||
(FID_CAN_AUTOCHASER_START, 6, 0),
|
||||
]
|
||||
widgets.append(
|
||||
speed_dial(
|
||||
wid,
|
||||
"Transition",
|
||||
auto_dim_x + sl_w + gap,
|
||||
y1,
|
||||
sl_w,
|
||||
sl_h,
|
||||
CAN_CHASE_MS,
|
||||
transition_funcs,
|
||||
knob=8,
|
||||
)
|
||||
)
|
||||
wid += 1
|
||||
max_x = max(max_x, auto_dim_x + 2 * sl_w + gap)
|
||||
max_y = max(max_y, y1 + sl_h)
|
||||
auto_dim_right = auto_dim_x + 2 * sl_w + gap
|
||||
# Width of brightness (3) + mover row for pattern bank alignment.
|
||||
row2_right = (
|
||||
left_x
|
||||
+ 3 * sl_w
|
||||
+ 2 * gap
|
||||
+ group_gap
|
||||
+ 10 * sl_w
|
||||
+ 9 * gap
|
||||
)
|
||||
pattern_x = max(auto_dim_right, row2_right) + group_gap
|
||||
|
||||
pad_bank(
|
||||
"Can patterns",
|
||||
range(9, 17),
|
||||
can_labels,
|
||||
pattern_x,
|
||||
label_y1,
|
||||
"4284900966",
|
||||
)
|
||||
|
||||
label_y2 = y1 + sl_h + row_gap
|
||||
y2 = label_y2 + 32
|
||||
x = left_x
|
||||
|
||||
header("Brightness", x, label_y2, 3)
|
||||
place("Cans 1–8", x, y2, [(f, 0) for f in CAN_1_8], knob=15)
|
||||
place(
|
||||
"Cans 9–12",
|
||||
x + sl_w + gap,
|
||||
y2,
|
||||
[(f, 0) for f in CAN_9_12],
|
||||
knob=16,
|
||||
)
|
||||
place(
|
||||
"Movers",
|
||||
x + 2 * (sl_w + gap),
|
||||
y2,
|
||||
[(m, 8) for m in MOVERS],
|
||||
knob=13,
|
||||
)
|
||||
x += 3 * (sl_w + gap) + group_gap
|
||||
|
||||
header("Movers", x, label_y2, 10)
|
||||
place("FL", x, y2, [(MOVERS_FRONT[0], 0)], midi=PAN_MIDI[0])
|
||||
place("FR", x + sl_w + gap, y2, [(MOVERS_FRONT[1], 0)], midi=PAN_MIDI[1])
|
||||
place(
|
||||
"BL +90°",
|
||||
x + 2 * (sl_w + gap),
|
||||
y2,
|
||||
[(MOVER_BACK_LEFT, 0)],
|
||||
midi=PAN_MIDI[2],
|
||||
value=PAN_OFFSET_BL,
|
||||
)
|
||||
place(
|
||||
"BR −90°",
|
||||
x + 3 * (sl_w + gap),
|
||||
y2,
|
||||
[(MOVER_BACK_RIGHT, 0)],
|
||||
midi=PAN_MIDI[3],
|
||||
value=PAN_OFFSET_BR,
|
||||
)
|
||||
place("Tilt FL", x + 4 * (sl_w + gap), y2, [(MOVERS_FRONT[0], 2)], midi=TILT_MIDI[0])
|
||||
place("Tilt FR", x + 5 * (sl_w + gap), y2, [(MOVERS_FRONT[1], 2)], midi=TILT_MIDI[1])
|
||||
place("Tilt BL", x + 6 * (sl_w + gap), y2, [(MOVER_BACK_LEFT, 2)], midi=TILT_MIDI[2])
|
||||
place("Tilt BR", x + 7 * (sl_w + gap), y2, [(MOVER_BACK_RIGHT, 2)], midi=TILT_MIDI[3])
|
||||
place(
|
||||
"Focus",
|
||||
x + 8 * (sl_w + gap),
|
||||
y2,
|
||||
[(m, 7) for m in MOVERS],
|
||||
knob=11,
|
||||
value=70,
|
||||
)
|
||||
place("Rotate", x + 9 * (sl_w + gap), y2, [(m, 5) for m in MOVERS], knob=12)
|
||||
|
||||
pad_bank(
|
||||
"Mover patterns",
|
||||
range(1, 9),
|
||||
mover_labels,
|
||||
pattern_x,
|
||||
label_y2,
|
||||
"4278218076",
|
||||
)
|
||||
|
||||
# C1ext Playback: same knobs as Colour 1, disjoint cans (All C1). Stop via pad 14 script.
|
||||
pb_y = max_y + 12
|
||||
pb_h = 28
|
||||
pb_w = 3 * sl_w + 2 * gap
|
||||
pb_kids = []
|
||||
for i, (cap, fid, knob, fg, cng) in enumerate(
|
||||
[
|
||||
("C1ext R", FID_C1EXT_R, 5, "4294901760", "Red"),
|
||||
("C1ext G", FID_C1EXT_G, 3, "4278255360", "Green"),
|
||||
("C1ext B", FID_C1EXT_B, 1, "4278190335", "Blue"),
|
||||
]
|
||||
):
|
||||
pb_kids.append(
|
||||
playback_slider(
|
||||
wid + i,
|
||||
cap,
|
||||
c1_x + i * (sl_w + gap),
|
||||
pb_y,
|
||||
sl_w,
|
||||
pb_h,
|
||||
fid,
|
||||
knob=knob,
|
||||
fg=fg,
|
||||
cng=cng,
|
||||
)
|
||||
)
|
||||
wid += 3
|
||||
for i, (cap, fid, knob, fg, cng) in enumerate(
|
||||
[
|
||||
("C2can R", FID_C2PB_R, 6, "4294901760", "Red"),
|
||||
("C2can G", FID_C2PB_G, 4, "4278255360", "Green"),
|
||||
("C2can B", FID_C2PB_B, 2, "4278190335", "Blue"),
|
||||
]
|
||||
):
|
||||
pb_kids.append(
|
||||
playback_slider(
|
||||
wid + i,
|
||||
cap,
|
||||
c2_x + i * (sl_w + gap),
|
||||
pb_y,
|
||||
sl_w,
|
||||
pb_h,
|
||||
fid,
|
||||
knob=knob,
|
||||
fg=fg,
|
||||
cng=cng,
|
||||
)
|
||||
)
|
||||
wid += 3
|
||||
widgets.extend(pb_kids)
|
||||
max_y = max(max_y, pb_y + pb_h)
|
||||
max_x = max(max_x, c1_x + pb_w, c2_x + pb_w)
|
||||
|
||||
functions = "\n".join(functions_list)
|
||||
margin = 24
|
||||
canvas_scale = 2
|
||||
total_w = (max_x + margin) * canvas_scale
|
||||
total_h = (max_y + margin) * canvas_scale
|
||||
|
||||
qxw = 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>tech</Author>
|
||||
</Creator>
|
||||
<Engine Autostart="{STARTUP_ID}">
|
||||
<InputOutputMap>
|
||||
<Universe Name="Universe 1" ID="0">
|
||||
<Output Plugin="ArtNet" UID="192.168.1.143" Line="1"/>
|
||||
</Universe>
|
||||
<Universe Name="Universe 2" ID="1">
|
||||
<Input Plugin="MIDI" UID="SMC-PAD Bluetooth" Line="1"/>
|
||||
</Universe>
|
||||
<Universe Name="Universe 3" ID="2"/>
|
||||
<Universe Name="Universe 4" ID="3"/>
|
||||
</InputOutputMap>
|
||||
{fixture_xml()}
|
||||
{functions}
|
||||
</Engine>
|
||||
<VirtualConsole>
|
||||
<Frame Caption="">
|
||||
<Appearance>
|
||||
<FrameStyle>None</FrameStyle>
|
||||
<ForegroundColor>Default</ForegroundColor>
|
||||
<BackgroundColor>Default</BackgroundColor>
|
||||
<BackgroundImage>None</BackgroundImage>
|
||||
<Font>Default</Font>
|
||||
</Appearance>
|
||||
{"\n".join(widgets)}
|
||||
</Frame>
|
||||
<Properties>
|
||||
<Size Width="{total_w}" Height="{total_h}"/>
|
||||
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
|
||||
</Properties>
|
||||
</VirtualConsole>
|
||||
<SimpleDesk>
|
||||
<Engine/>
|
||||
</SimpleDesk>
|
||||
</Workspace>
|
||||
"""
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT.write_text(qxw)
|
||||
print(f"Wrote {OUT} ({total_w}x{total_h}, {wid} widgets)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,215 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep each mover's pan and tilt correction when the knobs turn.
|
||||
|
||||
Knob 9 (CC 38) and knob 10 (CC 39) are relative encoders, but QLC reads
|
||||
the CC as an absolute position. Every slider bound to that CC jumps to
|
||||
the same value, so the per-head offsets collapse.
|
||||
|
||||
This sits between the SMC-PAD and QLC+. It forwards every message, and
|
||||
on CC 38/39 it also adds the encoder step to each head and sends that
|
||||
head's own position on CC 50–53 (pan) and 54–57 (tilt).
|
||||
|
||||
pipenv run python scripts/mover_offsets_midi.py
|
||||
|
||||
Reload shows/twisted.qxw after it is running. Stopping this script puts
|
||||
the pad straight back onto QLC+.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
import mido
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SHOW = ROOT / "shows" / "twisted.qxw"
|
||||
|
||||
PAN_KNOB = 38
|
||||
TILT_KNOB = 39
|
||||
# FL, FR, BL, BR. These are the slider input channels in the show.
|
||||
PAN_CC = (50, 51, 52, 53)
|
||||
TILT_CC = (54, 55, 56, 57)
|
||||
HEADS = PAN_CC + TILT_CC
|
||||
|
||||
NS = {"w": "http://www.qlcplus.org/Workspace"}
|
||||
CLIENT_RE = re.compile(r"^client (\d+): '([^']*)'")
|
||||
PORT_RE = re.compile(r"^\s+(\d+) '([^']*)'")
|
||||
|
||||
|
||||
def midi_to_dmx(midi: int) -> int:
|
||||
"""QLC+ MIDI2DMX: (value * 255) / 127."""
|
||||
return (max(0, min(127, midi)) * 255) // 127
|
||||
|
||||
|
||||
_DMX_TO_MIDI = [
|
||||
min(range(128), key=lambda midi, dmx=dmx: (abs(midi_to_dmx(midi) - dmx), midi))
|
||||
for dmx in range(256)
|
||||
]
|
||||
|
||||
|
||||
def dmx_to_midi(dmx: int) -> int:
|
||||
return _DMX_TO_MIDI[max(0, min(255, dmx))]
|
||||
|
||||
|
||||
def encoder_delta(value: int) -> int:
|
||||
"""1..63 clockwise, 65..127 counter-clockwise."""
|
||||
if value <= 0 or value == 64 or value > 127:
|
||||
return 0
|
||||
if value < 64:
|
||||
return value
|
||||
return value - 128
|
||||
|
||||
|
||||
def load_positions(path: Path = SHOW) -> dict[int, int]:
|
||||
"""DMX value of each offset slider, keyed by its MIDI channel."""
|
||||
positions = {cc: 0 for cc in HEADS}
|
||||
root = ET.parse(path).getroot()
|
||||
for slider in root.findall(".//w:Slider", NS):
|
||||
source = slider.find("w:Input", NS)
|
||||
level = slider.find("w:Level", NS)
|
||||
if source is None or level is None:
|
||||
continue
|
||||
channel = source.get("Channel")
|
||||
if channel is None or int(channel) not in positions:
|
||||
continue
|
||||
value = level.get("Value")
|
||||
if value is not None:
|
||||
positions[int(channel)] = int(value)
|
||||
return positions
|
||||
|
||||
|
||||
def alsa_ports() -> list[tuple[int, int, str, str]]:
|
||||
text = subprocess.check_output(["aconnect", "-l"], text=True)
|
||||
client = 0
|
||||
client_name = ""
|
||||
found: list[tuple[int, int, str, str]] = []
|
||||
for line in text.splitlines():
|
||||
match = CLIENT_RE.match(line)
|
||||
if match:
|
||||
client = int(match.group(1))
|
||||
client_name = match.group(2)
|
||||
continue
|
||||
match = PORT_RE.match(line)
|
||||
if match:
|
||||
found.append((client, int(match.group(1)), client_name, match.group(2).strip()))
|
||||
return found
|
||||
|
||||
|
||||
def find_port(ports: list[tuple[int, int, str, str]], name: str) -> tuple[int, int]:
|
||||
for client, port, client_name, port_name in ports:
|
||||
if name in client_name or name in port_name:
|
||||
return client, port
|
||||
raise SystemExit(f"ALSA port {name!r} not found")
|
||||
|
||||
|
||||
def connect(src: tuple[int, int], dst: tuple[int, int]) -> None:
|
||||
subprocess.check_call(["aconnect", f"{src[0]}:{src[1]}", f"{dst[0]}:{dst[1]}"])
|
||||
|
||||
|
||||
def disconnect(src: tuple[int, int], dst: tuple[int, int]) -> None:
|
||||
subprocess.call(["aconnect", "-d", f"{src[0]}:{src[1]}", f"{dst[0]}:{dst[1]}"])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
positions = load_positions()
|
||||
print(
|
||||
"pan "
|
||||
+ " ".join(str(positions[cc]) for cc in PAN_CC)
|
||||
+ " tilt "
|
||||
+ " ".join(str(positions[cc]) for cc in TILT_CC),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
pad = find_port(alsa_ports(), "SMC-PAD Bluetooth")
|
||||
qlc = find_port(alsa_ports(), "qlcplus")
|
||||
|
||||
pad_in = mido.open_input("mover-offset-in", virtual=True)
|
||||
qlc_out = mido.open_output("mover-offset-out", virtual=True)
|
||||
feedback = mido.open_input("mover-offset-fb", virtual=True)
|
||||
time.sleep(0.2)
|
||||
ports = alsa_ports()
|
||||
bridge_in = find_port(ports, "mover-offset-in")
|
||||
bridge_out = find_port(ports, "mover-offset-out")
|
||||
bridge_fb = find_port(ports, "mover-offset-fb")
|
||||
|
||||
lock = threading.Lock()
|
||||
ignore_until: dict[int, float] = {}
|
||||
|
||||
def on_feedback(msg: mido.Message) -> None:
|
||||
if msg.type != "control_change" or msg.control not in positions:
|
||||
return
|
||||
if time.monotonic() < ignore_until.get(msg.control, 0):
|
||||
return
|
||||
with lock:
|
||||
positions[msg.control] = midi_to_dmx(msg.value)
|
||||
|
||||
feedback.callback = on_feedback
|
||||
|
||||
def fan(ccs: tuple[int, ...], channel: int, delta: int) -> None:
|
||||
if delta == 0:
|
||||
return
|
||||
with lock:
|
||||
for cc in ccs:
|
||||
nxt = max(0, min(255, positions[cc] + delta))
|
||||
midi = dmx_to_midi(nxt)
|
||||
positions[cc] = midi_to_dmx(midi)
|
||||
ignore_until[cc] = time.monotonic() + 0.05
|
||||
qlc_out.send(
|
||||
mido.Message(
|
||||
"control_change", channel=channel, control=cc, value=midi
|
||||
)
|
||||
)
|
||||
|
||||
wired = False
|
||||
|
||||
def restore(*_args: object) -> None:
|
||||
nonlocal wired
|
||||
if not wired:
|
||||
return
|
||||
wired = False
|
||||
feedback.callback = None
|
||||
disconnect(pad, bridge_in)
|
||||
disconnect(bridge_out, qlc)
|
||||
disconnect(qlc, bridge_fb)
|
||||
connect(pad, qlc)
|
||||
print("pad connected straight to QLC+", flush=True)
|
||||
|
||||
def stop(*_args: object) -> None:
|
||||
restore()
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
|
||||
disconnect(pad, qlc)
|
||||
connect(pad, bridge_in)
|
||||
connect(bridge_out, qlc)
|
||||
connect(qlc, bridge_fb)
|
||||
wired = True
|
||||
print(
|
||||
f"SMC-PAD {pad[0]}:{pad[1]} → offsets → QLC+ {qlc[0]}:{qlc[1]}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
try:
|
||||
for msg in pad_in:
|
||||
qlc_out.send(msg)
|
||||
if msg.type != "control_change":
|
||||
continue
|
||||
if msg.control == PAN_KNOB:
|
||||
fan(PAN_CC, msg.channel, encoder_delta(msg.value))
|
||||
elif msg.control == TILT_KNOB:
|
||||
fan(TILT_CC, msg.channel, encoder_delta(msg.value))
|
||||
finally:
|
||||
restore()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print the SMC-PAD SysEx in a usbmon capture.
|
||||
|
||||
sudo tcpdump -i usbmon1 -s 0 -U -w - > captures/pad.pcap
|
||||
python3 scripts/pad/decode_usbmon.py captures/pad.pcap --device 21
|
||||
|
||||
Each USB-MIDI packet is reassembled into messages per cable, then SINCO
|
||||
SysEx is decoded to its command, memory, address, and data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from padcontroller.sysex import decode # noqa: E402
|
||||
|
||||
LINKTYPE_USB_LINUX_MMAPPED = 220
|
||||
HEADER = struct.Struct("<QBBBBHBBqiiIIQiiII") # 64 bytes
|
||||
# Payload bytes carried by each USB-MIDI code index number.
|
||||
CIN_SIZE = {0x2: 2, 0x3: 3, 0x4: 3, 0x5: 1, 0x6: 2, 0x7: 3, 0x8: 3, 0x9: 3,
|
||||
0xA: 3, 0xB: 3, 0xC: 2, 0xD: 2, 0xE: 3, 0xF: 1}
|
||||
COMMANDS = {0x00: "ack", 0x22: "write", 0x23: "read"}
|
||||
|
||||
|
||||
def packets(path: Path):
|
||||
raw = path.read_bytes()
|
||||
magic = struct.unpack_from("<I", raw)[0]
|
||||
if magic not in (0xA1B2C3D4, 0xA1B23C4D):
|
||||
raise SystemExit(f"{path} is not a little-endian pcap")
|
||||
linktype = struct.unpack_from("<I", raw, 20)[0]
|
||||
if linktype != LINKTYPE_USB_LINUX_MMAPPED:
|
||||
raise SystemExit(f"{path} has link type {linktype}, expected usbmon ({LINKTYPE_USB_LINUX_MMAPPED})")
|
||||
at = 24
|
||||
while at + 16 <= len(raw):
|
||||
sec, frac, incl, _orig = struct.unpack_from("<IIII", raw, at)
|
||||
at += 16
|
||||
yield sec + frac / 1e6, raw[at:at + incl]
|
||||
at += incl
|
||||
|
||||
|
||||
def transfers(path: Path, device: int | None):
|
||||
"""(time, direction, data) for bulk and interrupt transfers that carry data."""
|
||||
for stamp, frame in packets(path):
|
||||
if len(frame) < HEADER.size:
|
||||
continue
|
||||
fields = HEADER.unpack_from(frame)
|
||||
kind, xfer, endpoint, devnum = fields[1], fields[2], fields[3], fields[4]
|
||||
if device is not None and devnum != device:
|
||||
continue
|
||||
if xfer not in (1, 3):
|
||||
continue
|
||||
data = frame[HEADER.size:]
|
||||
inbound = bool(endpoint & 0x80)
|
||||
# Host-to-pad data rides on the submit, pad-to-host on the completion.
|
||||
if data and ((not inbound and kind == ord("S")) or (inbound and kind == ord("C"))):
|
||||
yield stamp, "pad→host" if inbound else "host→pad", data
|
||||
|
||||
|
||||
def messages(path: Path, device: int | None):
|
||||
pending: dict[tuple[str, int], bytearray] = {}
|
||||
for stamp, direction, data in transfers(path, device):
|
||||
for at in range(0, len(data) - 3, 4):
|
||||
head = data[at]
|
||||
cin, cable = head & 0x0F, head >> 4
|
||||
if head == 0:
|
||||
continue
|
||||
body = data[at + 1:at + 1 + CIN_SIZE.get(cin, 0)]
|
||||
key = (direction, cable)
|
||||
if cin in (0x4, 0x5, 0x6, 0x7) or (pending.get(key) and cin == 0xF):
|
||||
buf = pending.setdefault(key, bytearray())
|
||||
buf += body
|
||||
if cin != 0x4 and buf.endswith(b"\xf7"):
|
||||
yield stamp, direction, cable, bytes(buf)
|
||||
del pending[key]
|
||||
else:
|
||||
yield stamp, direction, cable, bytes(body)
|
||||
|
||||
|
||||
def describe(message: bytes) -> str:
|
||||
if message[:1] != b"\xf0" or message[-1:] != b"\xf7":
|
||||
return message.hex(" ")
|
||||
inner = decode(message[1:-1])
|
||||
if inner[:2] != b"\x00\x59" or len(inner) < 7:
|
||||
return f"sysex {inner.hex(' ')}"
|
||||
command = COMMANDS.get(inner[2], f"cmd {inner[2]:#04x}")
|
||||
length = int.from_bytes(inner[3:6], "little")
|
||||
payload = inner[6:6 + length]
|
||||
if inner[2] in (0x22, 0x23) and len(payload) >= 8:
|
||||
memory = payload[0]
|
||||
address = int.from_bytes(payload[1:5], "little")
|
||||
size = int.from_bytes(payload[5:8], "little")
|
||||
data = payload[8:]
|
||||
text = f"{command} mem {memory} addr {address:#010x} len {size}"
|
||||
return f"{text} data {data.hex()}" if data else text
|
||||
return f"{command} {payload.hex(' ')}"
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("capture", type=Path)
|
||||
parser.add_argument("--device", type=int, help="USB device number from lsusb")
|
||||
args = parser.parse_args(argv)
|
||||
start = None
|
||||
for stamp, direction, cable, message in messages(args.capture, args.device):
|
||||
start = stamp if start is None else start
|
||||
print(f"{stamp - start:8.3f} {direction} cable {cable} {describe(message)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print SMC-PAD pad and knob numbers.
|
||||
|
||||
pipenv run python scripts/pad/midi.py
|
||||
|
||||
Each pad press prints pad N. Each knob turn prints knob N and its step
|
||||
(+ for up, - for down).
|
||||
Type 1 on pad 1 to store pads 1–16, or 17 on pad 17 to store pads 17–32.
|
||||
Type 1 on knob 1 to store knobs 1–8, or 9 on knob 9 to store knobs 9–16.
|
||||
Mappings are saved to shows/midi_map.json.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import mido
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MAP_PATH = ROOT / "shows" / "midi_map.json"
|
||||
|
||||
# (channel, note) -> pad number. Loaded from shows/midi_map.json.
|
||||
PADS: dict[tuple[int, int], int] = {}
|
||||
# (channel, controller) -> knob number.
|
||||
KNOBS: dict[tuple[int, int], int] = {}
|
||||
|
||||
PAD_BANK = 16
|
||||
KNOB_BANK = 8
|
||||
|
||||
|
||||
def load_maps(path: Path = MAP_PATH) -> None:
|
||||
PADS.clear()
|
||||
KNOBS.clear()
|
||||
if not path.is_file():
|
||||
return
|
||||
data = json.loads(path.read_text())
|
||||
for item in data.get("pads", []):
|
||||
PADS[(int(item["channel"]), int(item["note"]))] = int(item["pad"])
|
||||
for item in data.get("knobs", []):
|
||||
KNOBS[(int(item["channel"]), int(item["cc"]))] = int(item["knob"])
|
||||
|
||||
|
||||
def save_maps(path: Path = MAP_PATH) -> None:
|
||||
data = {
|
||||
"pads": [
|
||||
{"channel": channel, "note": note, "pad": pad}
|
||||
for (channel, note), pad in sorted(PADS.items())
|
||||
],
|
||||
"knobs": [
|
||||
{"channel": channel, "cc": cc, "knob": knob}
|
||||
for (channel, cc), knob in sorted(KNOBS.items())
|
||||
],
|
||||
}
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(data, indent=2) + "\n")
|
||||
|
||||
|
||||
def ask(kind: str) -> int | None:
|
||||
word = "pad" if kind == "note" else "knob"
|
||||
raw = input(f"{word}: ").strip()
|
||||
if raw == "":
|
||||
return None
|
||||
if not raw.isdigit():
|
||||
print("enter a number", flush=True)
|
||||
return None
|
||||
return int(raw)
|
||||
|
||||
|
||||
def assign_bank(kind: str, channel: int, number: int, name: int) -> tuple[int, int]:
|
||||
"""Store one control, or a whole bank when name is the first in that bank."""
|
||||
size = PAD_BANK if kind == "note" else KNOB_BANK
|
||||
target = PADS if kind == "note" else KNOBS
|
||||
if name % size != 1:
|
||||
target[(channel, number)] = name
|
||||
return name, name
|
||||
for key, value in list(target.items()):
|
||||
if name <= value < name + size:
|
||||
del target[key]
|
||||
for offset in range(size):
|
||||
target[(channel, number + offset)] = name + offset
|
||||
return name, name + size - 1
|
||||
|
||||
|
||||
def remember(kind: str, channel: int, number: int, name: int) -> None:
|
||||
first, last = assign_bank(kind, channel, number, name)
|
||||
word = "pad" if kind == "note" else "knob"
|
||||
if first == last:
|
||||
print(f"{word} {first}", flush=True)
|
||||
else:
|
||||
print(f"{word}s {first}–{last}", flush=True)
|
||||
save_maps()
|
||||
print(f"saved {MAP_PATH}", flush=True)
|
||||
|
||||
|
||||
def encoder_delta(value: int) -> int:
|
||||
"""Relative encoder step. 1..63 clockwise, 65..127 counter-clockwise."""
|
||||
if value <= 0 or value == 64 or value > 127:
|
||||
return 0
|
||||
if value < 64:
|
||||
return value
|
||||
return value - 128
|
||||
|
||||
|
||||
def label(kind: str, channel: int, number: int, value: int | None = None) -> str | None:
|
||||
if kind == "note":
|
||||
pad = PADS.get((channel, number))
|
||||
if pad is None:
|
||||
return None
|
||||
return f"pad {pad}"
|
||||
knob = KNOBS.get((channel, number))
|
||||
if knob is None:
|
||||
return None
|
||||
if value is None:
|
||||
return f"knob {knob}"
|
||||
delta = encoder_delta(value)
|
||||
if delta == 0:
|
||||
return None
|
||||
return f"knob {knob} {delta:+d}"
|
||||
|
||||
|
||||
def find_port(wanted: str | None) -> str:
|
||||
names = mido.get_input_names()
|
||||
if wanted:
|
||||
for name in names:
|
||||
if wanted in name:
|
||||
return name
|
||||
raise SystemExit(f"No MIDI input matching {wanted}. Ports: {', '.join(names) or 'none'}")
|
||||
for name in names:
|
||||
low = name.lower()
|
||||
if "private" in low:
|
||||
continue
|
||||
if "smc-pad" in low or "sinco" in low:
|
||||
return name
|
||||
raise SystemExit("SMC-PAD not found. Plug it in, or pass part of the port name.")
|
||||
|
||||
|
||||
def midi_hint(kind: str, channel: int, number: int, value: int) -> str:
|
||||
if kind == "note":
|
||||
return f"channel {channel} note {number} velocity {value}"
|
||||
return f"channel {channel} cc {number} value {value}"
|
||||
|
||||
|
||||
def listen(port: str) -> None:
|
||||
skipped: set[tuple[str, int, int]] = set()
|
||||
with mido.open_input(port) as incoming:
|
||||
for msg in incoming:
|
||||
if msg.type == "note_on" and msg.velocity > 0:
|
||||
kind, number, value = "note", msg.note, msg.velocity
|
||||
elif msg.type == "control_change":
|
||||
kind, number, value = "cc", msg.control, msg.value
|
||||
else:
|
||||
continue
|
||||
name = label(kind, msg.channel, number, value)
|
||||
if name:
|
||||
print(name, flush=True)
|
||||
continue
|
||||
if kind == "cc" and (msg.channel, number) in KNOBS:
|
||||
continue
|
||||
print(midi_hint(kind, msg.channel, number, value), flush=True)
|
||||
key = (kind, msg.channel, number)
|
||||
if key in skipped:
|
||||
continue
|
||||
try:
|
||||
entered = ask(kind)
|
||||
except EOFError:
|
||||
return
|
||||
if entered is None:
|
||||
skipped.add(key)
|
||||
continue
|
||||
remember(kind, msg.channel, number, entered)
|
||||
name = label(kind, msg.channel, number, value)
|
||||
if name:
|
||||
print(name, flush=True)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
load_maps()
|
||||
wanted = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
port = find_port(wanted)
|
||||
print(f"Listening on {port}. Mappings in {MAP_PATH}.", flush=True)
|
||||
print("Pad 1 stores pads 1–16. Pad 17 stores pads 17–32.", flush=True)
|
||||
print("Knob 1 stores knobs 1–8. Knob 9 stores knobs 9–16.", flush=True)
|
||||
print("Ctrl+C to stop.", flush=True)
|
||||
try:
|
||||
listen(port)
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,268 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Store scene colours in an SMC-PAD preset bank.
|
||||
|
||||
Pad bank 1 is notes 36–51 and pad bank 2 is notes 52–67, bottom-left
|
||||
first. Note messages do not change these lamps. The colour is three
|
||||
bytes in the preset, written over the Private USB port.
|
||||
|
||||
.venv/bin/python scripts/pad/pad_colours.py --xchc --bank 2
|
||||
.venv/bin/python scripts/pad/pad_colours.py --colour-set --bank 2
|
||||
.venv/bin/python scripts/pad/pad_colours.py --dry-run
|
||||
.venv/bin/python scripts/pad/pad_colours.py --clear
|
||||
.venv/bin/python scripts/pad/pad_colours.py --identify
|
||||
|
||||
--identify lights every pad on a page in that page's colour, in rainbow
|
||||
order, in all eight presets, so the page on show can be read at a glance.
|
||||
|
||||
The write is checked by reading it back. It is sent to the running copy
|
||||
and to the stored preset, and it leaves notes, channels, and knobs as
|
||||
they are. An empty write at the start of the preset then commits it,
|
||||
which is what MidiSuite's Save button sends.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
|
||||
|
||||
from patch_smc_pad import PAD_COLORS # noqa: E402
|
||||
from padcontroller import preset # noqa: E402
|
||||
from padcontroller.device import PadError, read_image, save_image, transact # noqa: E402
|
||||
from padcontroller.device import private_port as _private_port # noqa: E402
|
||||
from padcontroller.preset import scale # noqa: E402
|
||||
from padcontroller.sysex import ( # noqa: E402
|
||||
RAM,
|
||||
decode,
|
||||
encode,
|
||||
payload_data,
|
||||
read_request,
|
||||
save_request,
|
||||
write_request,
|
||||
)
|
||||
|
||||
# Preset image, memory type 5. Each of these offsets is a note-36 pad,
|
||||
# and the next 15 records are notes 37–51. The running copy is at RAM.
|
||||
RECORD = 26
|
||||
RGB_AT = 4
|
||||
BANKS = (1044, 8122, 11661, 15200, 18739, 22278, 25817)
|
||||
|
||||
|
||||
def led_rgb(r: int, g: int, b: int, w: int) -> tuple[int, int, int]:
|
||||
return (min(255, r + w), min(255, g + w), min(255, b + w))
|
||||
|
||||
|
||||
# shows/xchc.qxw functions 0–8, in that order. The pad lamps are RGB, so
|
||||
# the white scene is stored as white rather than the can's white channel.
|
||||
XCHC_COLOURS = (
|
||||
("Red", 255, 0, 0),
|
||||
("Orange", 255, 127, 0),
|
||||
("Yellow", 255, 255, 0),
|
||||
("Green", 0, 255, 0),
|
||||
("Cyan", 0, 255, 255),
|
||||
("Blue", 0, 0, 255),
|
||||
("Violet", 127, 0, 255),
|
||||
("Magenta", 255, 0, 255),
|
||||
("White", 255, 255, 255),
|
||||
)
|
||||
|
||||
|
||||
# One colour per pad page, page 1 first. Rainbow order, so the page
|
||||
# number can be counted from red.
|
||||
PAGE_COLOURS = (
|
||||
("Red", 255, 0, 0),
|
||||
("Orange", 255, 100, 0),
|
||||
("Yellow", 255, 255, 0),
|
||||
("Green", 0, 255, 0),
|
||||
("Cyan", 0, 255, 255),
|
||||
("Blue", 0, 0, 255),
|
||||
("Violet", 160, 0, 255),
|
||||
("White", 255, 255, 255),
|
||||
)
|
||||
|
||||
|
||||
def identify_image(image: bytes) -> bytes:
|
||||
"""The image with each pad page lit in its PAGE_COLOURS colour."""
|
||||
out = bytearray(image)
|
||||
for number in range(preset.PRESET_COUNT):
|
||||
for index in range(preset.PAD_COUNT):
|
||||
_name, red, green, blue = PAGE_COLOURS[index // preset.PAGE_LEN]
|
||||
at = preset.colour_offset(number, index)
|
||||
out[at:at + 3] = bytes((scale(red), scale(green), scale(blue)))
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def scene_colours(clear: bool = False) -> list[tuple[str, bytes]]:
|
||||
colours = []
|
||||
for name, r, g, b, w in PAD_COLORS:
|
||||
if clear:
|
||||
colours.append((name, b"\x00\x00\x00"))
|
||||
continue
|
||||
red, green, blue = led_rgb(r, g, b, w)
|
||||
colours.append((name, bytes((scale(red), scale(green), scale(blue)))))
|
||||
return colours
|
||||
|
||||
|
||||
def xchc_colours(clear: bool = False) -> list[tuple[str, bytes]]:
|
||||
"""The nine xchc colour scenes, then the rest of the 16-pad bank off."""
|
||||
colours = []
|
||||
for name, red, green, blue in XCHC_COLOURS:
|
||||
rgb = b"\x00\x00\x00" if clear else bytes((scale(red), scale(green), scale(blue)))
|
||||
colours.append((name, rgb))
|
||||
colours.extend(("", b"\x00\x00\x00") for _ in range(16 - len(colours)))
|
||||
return colours
|
||||
|
||||
|
||||
def colour_set(clear: bool = False) -> list[tuple[str, bytes]]:
|
||||
"""The colours of shows/test.qxw in pad order, then the rest of the bank off."""
|
||||
sys.path.insert(0, str(ROOT / "scripts" / "shows"))
|
||||
from colour_sets import COLOURS
|
||||
|
||||
colours = []
|
||||
for name, r, g, b, w in COLOURS:
|
||||
rgb = b"\x00\x00\x00" if clear else bytes(scale(c) for c in led_rgb(r, g, b, w))
|
||||
colours.append((name, rgb))
|
||||
colours.extend(("", b"\x00\x00\x00") for _ in range(16 - len(colours)))
|
||||
return colours
|
||||
|
||||
|
||||
# Preset page whose records light each pad bank. Page 3 also sends notes
|
||||
# 52–67 but its colours are not shown; bank 2 takes them from page 7.
|
||||
BANK_PAGE = {1: 2, 2: 7}
|
||||
|
||||
|
||||
def bank_bases(bank: int) -> tuple[int, ...]:
|
||||
"""Preset addresses where this pad bank's note records start."""
|
||||
if bank < 1:
|
||||
raise ValueError(f"pad bank {bank} is not on this controller")
|
||||
page = BANK_PAGE.get(bank, bank + 1)
|
||||
skip = (page - 2) * 16 * RECORD
|
||||
return tuple(base + skip for base in BANKS)
|
||||
|
||||
|
||||
def colour_writes(
|
||||
clear: bool = False,
|
||||
bank: int = 1,
|
||||
colours: list[tuple[str, bytes]] | None = None,
|
||||
) -> list[tuple[str, int, bytes]]:
|
||||
"""(name, address, rgb) for one pad bank in every preset."""
|
||||
palette = scene_colours(clear) if colours is None else list(colours)
|
||||
if clear and colours is not None:
|
||||
palette = [(name, b"\x00\x00\x00") for name, _rgb in palette]
|
||||
placed = []
|
||||
for base in bank_bases(bank):
|
||||
for index, (name, rgb) in enumerate(palette):
|
||||
placed.append((name, base + index * RECORD + RGB_AT, rgb))
|
||||
return placed
|
||||
|
||||
|
||||
def payload_data(decoded: bytes) -> bytes:
|
||||
"""Bytes after the type, address, and length in a read reply."""
|
||||
if decoded[:3] != b"\x00\x59\x23":
|
||||
raise ValueError(f"unexpected reply {decoded[:8].hex()}")
|
||||
payload = decoded[6:-1]
|
||||
return payload[8:]
|
||||
|
||||
|
||||
def private_port(names: list[str]) -> str:
|
||||
try:
|
||||
return _private_port(names)
|
||||
except PadError as exc:
|
||||
raise SystemExit(str(exc)) from exc
|
||||
|
||||
|
||||
def apply(
|
||||
clear: bool,
|
||||
bank: int = 1,
|
||||
colours: list[tuple[str, bytes]] | None = None,
|
||||
any_note: bool = False,
|
||||
) -> None:
|
||||
for path in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
|
||||
if path not in sys.path:
|
||||
sys.path.insert(0, path)
|
||||
import rtmidi
|
||||
|
||||
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA)
|
||||
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
|
||||
port = private_port(midiout.get_ports())
|
||||
index = midiout.get_ports().index(port)
|
||||
midiin.open_port(index)
|
||||
midiin.ignore_types(sysex=False, timing=True, active_sense=True)
|
||||
midiout.open_port(index)
|
||||
print(f"Port: {port}", flush=True)
|
||||
try:
|
||||
note = 36 + (bank - 1) * 16
|
||||
for base in bank_bases(bank):
|
||||
reply = transact(midiout, midiin, read_request(base, 2))
|
||||
mark = payload_data(reply)
|
||||
if mark[0] != 0x09 or (not any_note and mark[1] != note):
|
||||
raise SystemExit(
|
||||
f"preset at {base} is {mark.hex()}, not the note-{note} pads; nothing was written"
|
||||
)
|
||||
bases = (RAM, 0)
|
||||
shown = set()
|
||||
for name, address, rgb in colour_writes(clear, bank, colours):
|
||||
for base in bases:
|
||||
transact(midiout, midiin, write_request(base + address, rgb))
|
||||
if name in shown:
|
||||
continue
|
||||
check = payload_data(transact(midiout, midiin, read_request(address, 3)))
|
||||
if check != rgb:
|
||||
raise SystemExit(f"{name or 'pad'} read back {check.hex()}, expected {rgb.hex()}")
|
||||
shown.add(name)
|
||||
if name:
|
||||
print(f" {name:<8} {address:#06x} {rgb.hex()}", flush=True)
|
||||
reply = transact(midiout, midiin, save_request())
|
||||
if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00":
|
||||
raise SystemExit(f"the pad did not accept the save ({reply.hex()})")
|
||||
print("Saved on the pad.", flush=True)
|
||||
finally:
|
||||
for port in (midiout, midiin):
|
||||
port.close_port()
|
||||
port.delete()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--bank", type=int, default=1, help="pad bank to write (2 is notes 52–67)")
|
||||
parser.add_argument("--page", type=int, help="write preset page 0–7 instead (page 2 is bank 1, 3 is bank 2; 7 repeats 52–67)")
|
||||
parser.add_argument("--xchc", action="store_true", help="use the solid colour scenes from shows/xchc.qxw")
|
||||
parser.add_argument("--colour-set", action="store_true", help="use the 16 colours from shows/test.qxw")
|
||||
parser.add_argument("--clear", action="store_true", help="store black on every scene pad")
|
||||
parser.add_argument("--identify", action="store_true", help="light each pad page in its own colour")
|
||||
parser.add_argument("--dry-run", action="store_true", help="print the colours and do not open a port")
|
||||
args = parser.parse_args(argv)
|
||||
if args.page is not None:
|
||||
if not 2 <= args.page < preset.PAGE_COUNT:
|
||||
parser.error("--page must be 2–7")
|
||||
args.bank = args.page - 1
|
||||
if args.identify:
|
||||
for page, (name, red, green, blue) in enumerate(PAGE_COLOURS, 1):
|
||||
print(f"page {page} {name:<7} {bytes((scale(red), scale(green), scale(blue))).hex()}")
|
||||
if not args.dry_run:
|
||||
try:
|
||||
written = save_image(identify_image(read_image()))
|
||||
except PadError as exc:
|
||||
raise SystemExit(str(exc)) from exc
|
||||
print(f"Saved on the pad ({written} bytes changed).")
|
||||
return 0
|
||||
palette = xchc_colours(args.clear) if args.xchc else colour_set(args.clear) if args.colour_set else None
|
||||
if args.dry_run:
|
||||
seen = set()
|
||||
for name, address, rgb in colour_writes(args.clear, args.bank, palette):
|
||||
if not name or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
print(f"{name:<8} {address:#06x} {rgb.hex()}")
|
||||
return 0
|
||||
apply(args.clear, args.bank, palette, any_note=args.page is not None)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Set the SMC-PAD lamps: bank 1 off, bank 2 in the colours of shows/test.qxw.
|
||||
|
||||
.venv/bin/python scripts/pad/pad_lamps.py
|
||||
|
||||
Needs the USB Private port. padcontroller.midi does this on start; run this
|
||||
when the pad is read by Chataigne instead.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def set_lamps() -> None:
|
||||
"""Bank 1 lamps off, bank 2 lamps from shows/test.qxw. Needs the USB Private port."""
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
|
||||
import pad_colours
|
||||
|
||||
try:
|
||||
pad_colours.apply(True, bank=1)
|
||||
pad_colours.apply(False, bank=2, colours=pad_colours.colour_set())
|
||||
except (SystemExit, Exception) as exc: # the Bluetooth link has no Private port
|
||||
print(f"Lamps not set: {exc}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
set_lamps()
|
||||
@@ -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[2]
|
||||
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 pad controller (padcontroller.midi) is running."""
|
||||
try:
|
||||
out = subprocess.check_output(["aconnect", "-l"], text=True)
|
||||
except (FileNotFoundError, subprocess.CalledProcessError):
|
||||
out = ""
|
||||
for name in (
|
||||
"padcontroller",
|
||||
"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()
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env bash
|
||||
# Reliable MIDI bring-up for shows/midi.qxw
|
||||
#
|
||||
# Order matters:
|
||||
# 1) pad present (Bluetooth or USB)
|
||||
# 2) pad controller (creates "padcontroller")
|
||||
# 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 the pad controller so it re-opens the pad port cleanly. Use the systemd
|
||||
# user service when it is installed (padcontroller/systemd/install.sh).
|
||||
SERVICE=padcontroller.service
|
||||
LOG=/tmp/padcontroller.log
|
||||
if systemctl --user is-enabled --quiet "$SERVICE" 2>/dev/null; then
|
||||
systemctl --user restart "$SERVICE"
|
||||
LOG=
|
||||
else
|
||||
# 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 '/python.* -m padcontroller[.]midi/ {print $1}')
|
||||
sleep 0.4
|
||||
nohup "$PYTHON" -m padcontroller.midi --tau 0.055 >>"$LOG" 2>&1 &
|
||||
fi
|
||||
for _ in $(seq 1 20); do
|
||||
if aconnect -l 2>/dev/null | grep -q 'padcontroller'; then
|
||||
break
|
||||
fi
|
||||
sleep 0.25
|
||||
done
|
||||
if ! aconnect -l 2>/dev/null | grep -q 'padcontroller'; then
|
||||
echo "The pad controller failed to create padcontroller." >&2
|
||||
if [[ -n "$LOG" ]]; then
|
||||
tail -20 "$LOG" >&2 || true
|
||||
else
|
||||
journalctl --user -u "$SERVICE" -n 20 --no-pager >&2 || true
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
|
||||
python3 scripts/pad/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 → padcontroller → qlcplus):"
|
||||
aconnect -l | grep -E "SMC-PAD|SINCO|padcontroller|qlcplus" -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)."
|
||||
@@ -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 "$@"
|
||||
@@ -0,0 +1,997 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Web page to aim the two cabaret movers and save pan/tilt positions.
|
||||
|
||||
Drives the Small Eye 7 heads over Art-Net while the sliders move, then
|
||||
writes named looks to a JSON file. Stop QLC+ Art-Net output first so the
|
||||
two sources do not fight. Ctrl+C blackout.
|
||||
|
||||
pipenv run positions
|
||||
open http://127.0.0.1:8765
|
||||
|
||||
Saved file (default shows/mover_positions.json):
|
||||
|
||||
{
|
||||
"positions": {
|
||||
"wall": {
|
||||
"m1": {"pan": 179, "tilt": 36},
|
||||
"m2": {"pan": 179, "tilt": 36}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from cabaret_movers import (
|
||||
DEFAULT_NODE,
|
||||
FOCUS_DEFAULT,
|
||||
M1_ADDR,
|
||||
M2_ADDR,
|
||||
PALETTE,
|
||||
POSITIONS,
|
||||
ArtNetSender,
|
||||
Mover,
|
||||
clamp,
|
||||
discover_artnet_nodes,
|
||||
)
|
||||
|
||||
# Aiming colours. White is listed first because it shows the beam clearly.
|
||||
COLORS: dict[str, tuple[int, int, int]] = {"white": (255, 255, 255), **PALETTE}
|
||||
COLOR_NAMES = ("white", "amber", "red", "orange", "yellow", "green", "blue", "pink", "purple")
|
||||
|
||||
PAGE = """<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Mover positions</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font: 16px/1.4 system-ui, sans-serif;
|
||||
background: #12141a;
|
||||
color: #eee;
|
||||
}
|
||||
main { max-width: 34rem; margin: 0 auto; padding: 1.25rem 1.25rem 3rem; }
|
||||
h1 { font-size: 1.35rem; font-weight: 650; margin: 0 0 0.2rem; }
|
||||
h2 { font-size: 0.95rem; font-weight: 600; margin: 1.4rem 0 0.2rem; color: #bbb; }
|
||||
.meta, .hint { color: #8e98a8; font-size: 0.85rem; }
|
||||
.meta { margin: 0 0 1rem; word-break: break-all; }
|
||||
.targets, .colors { display: flex; gap: 0.5rem; margin: 0.4rem 0 0.6rem; }
|
||||
.colors { flex-wrap: wrap; }
|
||||
button, input[type="text"], input[type="number"], select { font: inherit; color: inherit; }
|
||||
.device { display: flex; gap: 0.5rem; margin: 0 0 1rem; }
|
||||
.device select, .device button, .colors button {
|
||||
border: 1px solid #3a4050;
|
||||
background: #1c2030;
|
||||
border-radius: 8px;
|
||||
padding: 0.55rem 0.75rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.device select { flex: 1; min-width: 0; }
|
||||
.colors button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
border-radius: 999px;
|
||||
padding: 0.28rem 0.7rem 0.28rem 0.3rem;
|
||||
}
|
||||
.swatch {
|
||||
width: 1.15rem;
|
||||
height: 1.15rem;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
.colors button.active { border-color: #f0a030; box-shadow: 0 0 0 1px #f0a030; }
|
||||
.section { margin: 0.9rem 0 0.15rem; color: #bbb; font-size: 0.95rem; }
|
||||
.targets button, .add, .del {
|
||||
border: 1px solid #3a4050;
|
||||
background: #1c2030;
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem 0.9rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.targets button { flex: 1; }
|
||||
.targets button.active {
|
||||
background: #f0a030;
|
||||
border-color: #f0a030;
|
||||
color: #1a1206;
|
||||
font-weight: 650;
|
||||
}
|
||||
.slider { margin: 0.85rem 0; }
|
||||
.slider .top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.15rem;
|
||||
}
|
||||
input[type="number"] {
|
||||
width: 4.5rem;
|
||||
text-align: right;
|
||||
background: #1c2030;
|
||||
border: 1px solid #3a4050;
|
||||
border-radius: 6px;
|
||||
padding: 0.2rem 0.4rem;
|
||||
}
|
||||
input[type="range"] {
|
||||
width: 100%;
|
||||
height: 2rem;
|
||||
accent-color: #f0a030;
|
||||
cursor: pointer;
|
||||
}
|
||||
.save { display: flex; gap: 0.5rem; margin-top: 1.1rem; }
|
||||
.save input[type="text"] {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
background: #1c2030;
|
||||
border: 1px solid #3a4050;
|
||||
border-radius: 8px;
|
||||
padding: 0.6rem 0.75rem;
|
||||
}
|
||||
.add {
|
||||
background: #f0a030;
|
||||
border-color: #f0a030;
|
||||
color: #1a1206;
|
||||
font-weight: 650;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.add:disabled { opacity: 0.45; cursor: default; }
|
||||
.status { min-height: 1.3rem; margin: 0.6rem 0 0; color: #f0a030; }
|
||||
ul { list-style: none; padding: 0; margin: 0; }
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
padding: 0.35rem 0;
|
||||
border-bottom: 1px solid #262b38;
|
||||
}
|
||||
li .name {
|
||||
flex: 1;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0.35rem 0;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
li .name:hover { color: #f0a030; }
|
||||
li .nums {
|
||||
color: #8e98a8;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 0.82rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.del { padding: 0.3rem 0.55rem; color: #e07a7a; }
|
||||
.empty { color: #8e98a8; margin: 0.4rem 0 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Mover positions</h1>
|
||||
<p class="meta" id="meta">Connecting…</p>
|
||||
<div class="section">Art-Net to DMX</div>
|
||||
<div class="device">
|
||||
<select id="node" aria-label="Art-Net to DMX device"></select>
|
||||
<button type="button" id="refresh-nodes">Refresh</button>
|
||||
</div>
|
||||
<p class="hint">Both movers share this DMX output.</p>
|
||||
<div class="targets" id="targets">
|
||||
<button type="button" data-target="m1">M1</button>
|
||||
<button type="button" data-target="m2">M2</button>
|
||||
<button type="button" data-target="both" class="active">Both</button>
|
||||
</div>
|
||||
<p class="hint" id="differ" hidden>M1 and M2 are aimed differently. Moving a slider sets both.</p>
|
||||
<div class="section">Color <span class="hint" id="color-note"></span></div>
|
||||
<div class="colors" id="colors"></div>
|
||||
<div class="slider">
|
||||
<div class="top"><span>Pan</span>
|
||||
<input id="pan-num" type="number" min="0" max="255" value="128" inputmode="numeric">
|
||||
</div>
|
||||
<input id="pan" type="range" min="0" max="255" value="128">
|
||||
</div>
|
||||
<div class="slider">
|
||||
<div class="top"><span>Tilt</span>
|
||||
<input id="tilt-num" type="number" min="0" max="255" value="128" inputmode="numeric">
|
||||
</div>
|
||||
<input id="tilt" type="range" min="0" max="255" value="128">
|
||||
</div>
|
||||
<div class="slider">
|
||||
<div class="top"><span>Dimmer</span>
|
||||
<input id="dim-num" type="number" min="0" max="255" value="255" inputmode="numeric">
|
||||
</div>
|
||||
<input id="dim" type="range" min="0" max="255" value="255">
|
||||
</div>
|
||||
<form class="save" id="save-form">
|
||||
<input id="name" type="text" placeholder="Position name" maxlength="48" autocomplete="off">
|
||||
<button class="add" id="add" type="submit" disabled>Add position</button>
|
||||
</form>
|
||||
<p class="status" id="status"></p>
|
||||
<h2>Saved</h2>
|
||||
<p class="empty" id="empty">Aim the beam, name it, then add the position.</p>
|
||||
<ul id="list"></ul>
|
||||
<p class="hint">Arrow keys nudge pan and tilt. Shift moves by 10. Up sends the beam toward tilt 0.</p>
|
||||
</main>
|
||||
<script>
|
||||
const pan = document.getElementById("pan");
|
||||
const tilt = document.getElementById("tilt");
|
||||
const dim = document.getElementById("dim");
|
||||
const panNum = document.getElementById("pan-num");
|
||||
const tiltNum = document.getElementById("tilt-num");
|
||||
const dimNum = document.getElementById("dim-num");
|
||||
const nameInput = document.getElementById("name");
|
||||
const addBtn = document.getElementById("add");
|
||||
const statusEl = document.getElementById("status");
|
||||
const listEl = document.getElementById("list");
|
||||
const emptyEl = document.getElementById("empty");
|
||||
const differEl = document.getElementById("differ");
|
||||
const nodeSel = document.getElementById("node");
|
||||
const colorBox = document.getElementById("colors");
|
||||
const colorNote = document.getElementById("color-note");
|
||||
const refreshBtn = document.getElementById("refresh-nodes");
|
||||
|
||||
let state = null;
|
||||
let target = "both";
|
||||
let mute = false;
|
||||
let aimBody = null;
|
||||
let aiming = false;
|
||||
|
||||
function clampByte(value) {
|
||||
const n = Math.round(Number(value));
|
||||
if (Number.isNaN(n)) return 0;
|
||||
return Math.max(0, Math.min(255, n));
|
||||
}
|
||||
|
||||
function source() {
|
||||
return target === "m2" ? state.m2 : state.m1;
|
||||
}
|
||||
|
||||
function applySliders() {
|
||||
mute = true;
|
||||
const src = source();
|
||||
pan.value = panNum.value = src.pan;
|
||||
tilt.value = tiltNum.value = src.tilt;
|
||||
dim.value = dimNum.value = state.dimmer;
|
||||
mute = false;
|
||||
const differ = state.m1.pan !== state.m2.pan || state.m1.tilt !== state.m2.tilt;
|
||||
differEl.hidden = !(target === "both" && differ);
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
listEl.replaceChildren();
|
||||
const positions = state.positions || [];
|
||||
emptyEl.hidden = positions.length > 0;
|
||||
for (const pos of positions) {
|
||||
const li = document.createElement("li");
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.className = "name";
|
||||
btn.textContent = pos.name;
|
||||
btn.addEventListener("click", () => recall(pos.name));
|
||||
const nums = document.createElement("span");
|
||||
nums.className = "nums";
|
||||
nums.textContent = "M1 " + pos.m1.pan + "/" + pos.m1.tilt + " M2 " + pos.m2.pan + "/" + pos.m2.tilt;
|
||||
const del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "del";
|
||||
del.textContent = "Remove";
|
||||
del.addEventListener("click", () => removePosition(pos.name));
|
||||
li.append(btn, nums, del);
|
||||
listEl.append(li);
|
||||
}
|
||||
}
|
||||
|
||||
function renderNodes() {
|
||||
const ips = (state.nodes || []).map((node) => node.ip + "=" + node.name + "=" + (node.universe || "")).join("|");
|
||||
if (nodeSel.dataset.ips !== ips) {
|
||||
nodeSel.dataset.ips = ips;
|
||||
nodeSel.replaceChildren();
|
||||
for (const node of state.nodes || []) {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = node.ip;
|
||||
const bits = [];
|
||||
if (node.name) bits.push(node.name);
|
||||
bits.push(node.ip);
|
||||
if (node.universe != null && node.universe !== "") bits.push("universe " + node.universe);
|
||||
opt.textContent = bits.join(" ");
|
||||
nodeSel.append(opt);
|
||||
}
|
||||
}
|
||||
if (nodeSel.value !== state.artnet) nodeSel.value = state.artnet;
|
||||
}
|
||||
|
||||
function renderColors() {
|
||||
const chosen = target === "m2" ? state.color.m2 : state.color.m1;
|
||||
const mixed = target === "both" && state.color.m1 !== state.color.m2;
|
||||
colorNote.textContent = mixed ? "M1 " + state.color.m1 + " · M2 " + state.color.m2 : chosen;
|
||||
colorBox.replaceChildren();
|
||||
for (const color of state.colors || []) {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.classList.toggle("active", !mixed && color.name === chosen);
|
||||
const swatch = document.createElement("span");
|
||||
swatch.className = "swatch";
|
||||
swatch.style.background = "rgb(" + color.rgb.join(",") + ")";
|
||||
btn.append(swatch, document.createTextNode(color.name));
|
||||
btn.addEventListener("click", () => setColor(color.name));
|
||||
colorBox.append(btn);
|
||||
}
|
||||
}
|
||||
|
||||
function showState(next) {
|
||||
state = next;
|
||||
document.getElementById("meta").textContent = state.file;
|
||||
renderNodes();
|
||||
renderColors();
|
||||
applySliders();
|
||||
renderList();
|
||||
}
|
||||
|
||||
async function postJSON(url, body) {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify(body || {}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "Request failed");
|
||||
return data;
|
||||
}
|
||||
|
||||
async function setColor(name) {
|
||||
try {
|
||||
const data = await postJSON("/api/color", {target, color: name});
|
||||
showState(data);
|
||||
statusEl.textContent = name.charAt(0).toUpperCase() + name.slice(1) + " on";
|
||||
} catch (err) {
|
||||
statusEl.textContent = err.message || "Can't reach the position server";
|
||||
}
|
||||
}
|
||||
|
||||
async function queueAim() {
|
||||
if (mute || !state) return;
|
||||
const panV = clampByte(pan.value);
|
||||
const tiltV = clampByte(tilt.value);
|
||||
const dimV = clampByte(dim.value);
|
||||
panNum.value = panV;
|
||||
tiltNum.value = tiltV;
|
||||
dimNum.value = dimV;
|
||||
if (target === "both" || target === "m1") state.m1 = {pan: panV, tilt: tiltV};
|
||||
if (target === "both" || target === "m2") state.m2 = {pan: panV, tilt: tiltV};
|
||||
state.dimmer = dimV;
|
||||
differEl.hidden = true;
|
||||
aimBody = {target, pan: panV, tilt: tiltV, dimmer: dimV};
|
||||
if (aiming) return;
|
||||
aiming = true;
|
||||
try {
|
||||
while (aimBody) {
|
||||
const body = aimBody;
|
||||
aimBody = null;
|
||||
const res = await fetch("/api/aim", {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) statusEl.textContent = "Aim failed";
|
||||
}
|
||||
} catch (err) {
|
||||
statusEl.textContent = "Can't reach the position server";
|
||||
} finally {
|
||||
aiming = false;
|
||||
}
|
||||
}
|
||||
|
||||
function bindPair(range, number) {
|
||||
range.addEventListener("input", () => {
|
||||
number.value = range.value;
|
||||
queueAim();
|
||||
});
|
||||
number.addEventListener("input", () => {
|
||||
range.value = clampByte(number.value);
|
||||
queueAim();
|
||||
});
|
||||
}
|
||||
|
||||
bindPair(pan, panNum);
|
||||
bindPair(tilt, tiltNum);
|
||||
bindPair(dim, dimNum);
|
||||
|
||||
document.getElementById("targets").addEventListener("click", (ev) => {
|
||||
const btn = ev.target.closest("button");
|
||||
if (!btn || !state) return;
|
||||
target = btn.dataset.target;
|
||||
for (const el of document.querySelectorAll("#targets button")) {
|
||||
el.classList.toggle("active", el === btn);
|
||||
}
|
||||
applySliders();
|
||||
renderColors();
|
||||
});
|
||||
|
||||
nodeSel.addEventListener("change", async () => {
|
||||
const ip = nodeSel.value;
|
||||
if (!state || ip === state.artnet) return;
|
||||
nodeSel.disabled = true;
|
||||
try {
|
||||
const data = await postJSON("/api/node", {ip});
|
||||
showState(data);
|
||||
statusEl.textContent = "Art-Net " + ip;
|
||||
} catch (err) {
|
||||
statusEl.textContent = err.message || "Could not change Art-Net device";
|
||||
nodeSel.value = state.artnet;
|
||||
} finally {
|
||||
nodeSel.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
refreshBtn.addEventListener("click", async () => {
|
||||
refreshBtn.disabled = true;
|
||||
refreshBtn.textContent = "Looking…";
|
||||
try {
|
||||
const data = await postJSON("/api/nodes", {});
|
||||
showState(data);
|
||||
const count = (state.nodes || []).length;
|
||||
statusEl.textContent = count + " Art-Net device" + (count === 1 ? "" : "s");
|
||||
} catch (err) {
|
||||
statusEl.textContent = err.message || "Could not look for Art-Net devices";
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
refreshBtn.textContent = "Refresh";
|
||||
}
|
||||
});
|
||||
|
||||
nameInput.addEventListener("input", () => {
|
||||
addBtn.disabled = !nameInput.value.trim();
|
||||
});
|
||||
|
||||
document.getElementById("save-form").addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
const name = nameInput.value.trim();
|
||||
if (!name) return;
|
||||
addBtn.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/api/positions", {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({name}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
statusEl.textContent = data.error || "Could not save";
|
||||
addBtn.disabled = !nameInput.value.trim();
|
||||
return;
|
||||
}
|
||||
showState(data);
|
||||
nameInput.value = "";
|
||||
statusEl.textContent = "Saved " + data.saved;
|
||||
} catch (err) {
|
||||
statusEl.textContent = "Can't reach the position server";
|
||||
addBtn.disabled = !nameInput.value.trim();
|
||||
}
|
||||
});
|
||||
|
||||
async function recall(name) {
|
||||
try {
|
||||
const res = await fetch("/api/recall", {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({name}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
statusEl.textContent = data.error || "Could not recall";
|
||||
return;
|
||||
}
|
||||
showState(data);
|
||||
statusEl.textContent = "Recalled " + name;
|
||||
} catch (err) {
|
||||
statusEl.textContent = "Can't reach the position server";
|
||||
}
|
||||
}
|
||||
|
||||
async function removePosition(name) {
|
||||
try {
|
||||
const res = await fetch("/api/delete", {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({name}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
statusEl.textContent = data.error || "Could not remove";
|
||||
return;
|
||||
}
|
||||
showState(data);
|
||||
statusEl.textContent = "Removed " + name;
|
||||
} catch (err) {
|
||||
statusEl.textContent = "Can't reach the position server";
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", (ev) => {
|
||||
if (!state || ev.target === nameInput) return;
|
||||
const step = ev.shiftKey ? 10 : 1;
|
||||
let handled = true;
|
||||
if (ev.key === "ArrowLeft") pan.value = clampByte(Number(pan.value) - step);
|
||||
else if (ev.key === "ArrowRight") pan.value = clampByte(Number(pan.value) + step);
|
||||
else if (ev.key === "ArrowUp") tilt.value = clampByte(Number(tilt.value) - step);
|
||||
else if (ev.key === "ArrowDown") tilt.value = clampByte(Number(tilt.value) + step);
|
||||
else handled = false;
|
||||
if (!handled) return;
|
||||
ev.preventDefault();
|
||||
queueAim();
|
||||
});
|
||||
|
||||
fetch("/api/state").then((res) => res.json()).then(showState).catch(() => {
|
||||
document.getElementById("meta").textContent = "Can't reach the position server";
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def read_positions(path: Path) -> dict[str, dict]:
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise SystemExit(f"{path} is not valid JSON: {exc}") from exc
|
||||
raw = data.get("positions", data) if isinstance(data, dict) else None
|
||||
if not isinstance(raw, dict):
|
||||
raise SystemExit(f"{path} must contain a positions object")
|
||||
out: dict[str, dict] = {}
|
||||
for name, entry in raw.items():
|
||||
if not isinstance(entry, dict) or "m1" not in entry or "m2" not in entry:
|
||||
raise SystemExit(f"{path}: position {name!r} needs m1 and m2 pan/tilt")
|
||||
out[str(name)] = {"m1": point(entry["m1"]), "m2": point(entry["m2"])}
|
||||
return out
|
||||
|
||||
|
||||
def point(entry) -> dict[str, int]:
|
||||
if isinstance(entry, (list, tuple)) and len(entry) == 2:
|
||||
pan, tilt = entry
|
||||
elif isinstance(entry, dict) and "pan" in entry and "tilt" in entry:
|
||||
pan, tilt = entry["pan"], entry["tilt"]
|
||||
else:
|
||||
raise SystemExit("each mover needs pan and tilt")
|
||||
return {"pan": clamp(pan), "tilt": clamp(tilt)}
|
||||
|
||||
|
||||
def write_positions(path: Path, positions: dict[str, dict]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
text = json.dumps({"positions": positions}, indent=2) + "\n"
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_text(text, encoding="utf-8")
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def position_list(positions: dict[str, dict]) -> list[dict]:
|
||||
return [{"name": name, "m1": entry["m1"], "m2": entry["m2"]} for name, entry in positions.items()]
|
||||
|
||||
|
||||
def clean_name(value) -> str:
|
||||
name = " ".join(str(value).split())
|
||||
if not name:
|
||||
raise ValueError("Enter a position name")
|
||||
if len(name) > 48:
|
||||
raise ValueError("Name must be 48 characters or fewer")
|
||||
return name
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
self.positions = read_positions(path)
|
||||
|
||||
def snapshot(self) -> list[dict]:
|
||||
with self._lock:
|
||||
return position_list(self.positions)
|
||||
|
||||
def upsert(self, name: str, m1: dict, m2: dict) -> None:
|
||||
with self._lock:
|
||||
self.positions[name] = {
|
||||
"m1": {"pan": m1["pan"], "tilt": m1["tilt"]},
|
||||
"m2": {"pan": m2["pan"], "tilt": m2["tilt"]},
|
||||
}
|
||||
write_positions(self.path, self.positions)
|
||||
|
||||
def get(self, name: str) -> dict | None:
|
||||
with self._lock:
|
||||
entry = self.positions.get(name)
|
||||
if entry is None:
|
||||
return None
|
||||
return {"m1": dict(entry["m1"]), "m2": dict(entry["m2"])}
|
||||
|
||||
def delete(self, name: str) -> bool:
|
||||
with self._lock:
|
||||
if name not in self.positions:
|
||||
return False
|
||||
del self.positions[name]
|
||||
write_positions(self.path, self.positions)
|
||||
return True
|
||||
|
||||
|
||||
def clean_ip(value) -> str:
|
||||
text = str(value).strip()
|
||||
try:
|
||||
addr = ipaddress.ip_address(text)
|
||||
except ValueError as exc:
|
||||
raise ValueError("Enter an Art-Net address") from exc
|
||||
if not isinstance(addr, ipaddress.IPv4Address):
|
||||
raise ValueError("Art-Net needs an IPv4 address")
|
||||
return str(addr)
|
||||
|
||||
|
||||
def clean_color(value) -> str:
|
||||
name = str(value).strip().lower()
|
||||
if name not in COLORS:
|
||||
raise ValueError("Unknown color")
|
||||
return name
|
||||
|
||||
|
||||
GATEWAY_HOST = "dmx-gateway.local"
|
||||
|
||||
|
||||
def lookup_gateway() -> dict[str, str] | None:
|
||||
"""The LuxDMX Art-Net to DMX box at dmx-gateway.local, if it answers."""
|
||||
ip = ""
|
||||
name = GATEWAY_HOST
|
||||
universe = ""
|
||||
try:
|
||||
with urllib.request.urlopen(f"http://{GATEWAY_HOST}/info.json", timeout=1.5) as res:
|
||||
info = json.loads(res.read().decode("utf-8"))
|
||||
if isinstance(info, dict):
|
||||
ip = str(info.get("ip") or "")
|
||||
host = str(info.get("hostname") or "dmx-gateway").strip()
|
||||
name = host if "." in host else f"{host}.local"
|
||||
for output in info.get("outputs") or []:
|
||||
if isinstance(output, dict) and output.get("en"):
|
||||
universe = str(int(output.get("uni", 0)))
|
||||
break
|
||||
except (OSError, json.JSONDecodeError, ValueError, TypeError):
|
||||
pass
|
||||
if not ip:
|
||||
try:
|
||||
ip = socket.getaddrinfo(GATEWAY_HOST, 6454, socket.AF_INET, socket.SOCK_DGRAM)[0][4][0]
|
||||
except OSError:
|
||||
return None
|
||||
try:
|
||||
ip = str(ipaddress.IPv4Address(ip))
|
||||
except ValueError:
|
||||
return None
|
||||
node = {"ip": ip, "name": name}
|
||||
if universe != "":
|
||||
node["universe"] = universe
|
||||
return node
|
||||
|
||||
|
||||
def pin_gateway(nodes: list[dict[str, str]]) -> list[dict[str, str]]:
|
||||
gateway = lookup_gateway()
|
||||
if gateway is None:
|
||||
return nodes
|
||||
rest = [
|
||||
node
|
||||
for node in nodes
|
||||
if node["ip"] != gateway["ip"] and node.get("name") != "no reply"
|
||||
]
|
||||
return [gateway] + rest
|
||||
|
||||
|
||||
def include_ip(nodes: list[dict[str, str]], ip: str) -> list[dict[str, str]]:
|
||||
kept = [node for node in nodes if node.get("name") != "no reply" or node["ip"] == ip]
|
||||
if any(node["ip"] == ip for node in kept):
|
||||
return kept
|
||||
return [{"ip": ip, "name": ""}] + kept
|
||||
|
||||
|
||||
class Rig:
|
||||
def __init__(self, movers: dict[str, Mover]):
|
||||
self.movers = movers
|
||||
down_m1, down_m2 = POSITIONS["down"]
|
||||
self.pan = {"m1": down_m1[0], "m2": down_m2[0]}
|
||||
self.tilt = {"m1": down_m1[1], "m2": down_m2[1]}
|
||||
self.color = {"m1": "white", "m2": "white"}
|
||||
self.dimmer = 255
|
||||
self._lock = threading.Lock()
|
||||
self.push()
|
||||
|
||||
def push(self):
|
||||
with self._lock:
|
||||
self._push_locked()
|
||||
|
||||
def _push_locked(self):
|
||||
for key, mover in self.movers.items():
|
||||
mover.apply(
|
||||
pan=self.pan[key],
|
||||
tilt=self.tilt[key],
|
||||
rgb=COLORS[self.color[key]],
|
||||
dimmer=self.dimmer,
|
||||
focus=FOCUS_DEFAULT,
|
||||
speed=0,
|
||||
)
|
||||
|
||||
def set_color(self, target: str, name: str):
|
||||
if target not in ("m1", "m2", "both"):
|
||||
raise ValueError("target must be m1, m2, or both")
|
||||
name = clean_color(name)
|
||||
with self._lock:
|
||||
keys = ("m1", "m2") if target == "both" else (target,)
|
||||
for key in keys:
|
||||
self.color[key] = name
|
||||
if self.dimmer == 0:
|
||||
self.dimmer = 255
|
||||
self._push_locked()
|
||||
|
||||
def update(self, *, target: str, pan: int, tilt: int, dimmer: int):
|
||||
if target not in ("m1", "m2", "both"):
|
||||
raise ValueError("target must be m1, m2, or both")
|
||||
with self._lock:
|
||||
keys = ("m1", "m2") if target == "both" else (target,)
|
||||
for key in keys:
|
||||
self.pan[key] = clamp(pan)
|
||||
self.tilt[key] = clamp(tilt)
|
||||
self.dimmer = clamp(dimmer)
|
||||
self._push_locked()
|
||||
|
||||
def recall(self, entry: dict):
|
||||
with self._lock:
|
||||
self.pan["m1"] = entry["m1"]["pan"]
|
||||
self.tilt["m1"] = entry["m1"]["tilt"]
|
||||
self.pan["m2"] = entry["m2"]["pan"]
|
||||
self.tilt["m2"] = entry["m2"]["tilt"]
|
||||
self._push_locked()
|
||||
|
||||
def live(self) -> dict:
|
||||
with self._lock:
|
||||
return {
|
||||
"m1": {"pan": self.pan["m1"], "tilt": self.tilt["m1"]},
|
||||
"m2": {"pan": self.pan["m2"], "tilt": self.tilt["m2"]},
|
||||
"color": {"m1": self.color["m1"], "m2": self.color["m2"]},
|
||||
"dimmer": self.dimmer,
|
||||
}
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(
|
||||
self,
|
||||
rig: Rig,
|
||||
store: Store,
|
||||
sender: ArtNetSender,
|
||||
nodes: list[dict[str, str]],
|
||||
universe: int,
|
||||
):
|
||||
self.rig = rig
|
||||
self.store = store
|
||||
self.sender = sender
|
||||
self.nodes = nodes
|
||||
self.universe = universe
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def state(self, *, saved: str | None = None) -> dict:
|
||||
payload = self.rig.live()
|
||||
artnet = self.sender.destination()
|
||||
with self._lock:
|
||||
payload["nodes"] = [dict(node) for node in self.nodes]
|
||||
payload["artnet"] = artnet
|
||||
payload["colors"] = [{"name": name, "rgb": list(COLORS[name])} for name in COLOR_NAMES]
|
||||
payload["file"] = str(self.store.path)
|
||||
payload["positions"] = self.store.snapshot()
|
||||
if saved is not None:
|
||||
payload["saved"] = saved
|
||||
return payload
|
||||
|
||||
def _universe_for(self, ip: str) -> int:
|
||||
match = next((node for node in self.nodes if node["ip"] == ip), None)
|
||||
if match and match.get("universe", "") != "":
|
||||
return int(match["universe"])
|
||||
return self.universe
|
||||
|
||||
def select_node(self, ip: str):
|
||||
ip = clean_ip(ip)
|
||||
with self._lock:
|
||||
nodes = include_ip(self.nodes, ip)
|
||||
nodes = pin_gateway(nodes)
|
||||
with self._lock:
|
||||
self.nodes = nodes
|
||||
universe = self._universe_for(ip)
|
||||
label = next((node["name"] for node in self.nodes if node["ip"] == ip and node.get("name")), "")
|
||||
self.sender.set_dest(ip)
|
||||
self.sender.set_universe(universe)
|
||||
self.rig.push()
|
||||
print(f"Art-Net → {ip} {label} universe {universe}".rstrip(), flush=True)
|
||||
|
||||
def refresh_nodes(self):
|
||||
found = pin_gateway(discover_artnet_nodes())
|
||||
current = self.sender.destination()
|
||||
with self._lock:
|
||||
self.nodes = include_ip(found, current)
|
||||
|
||||
|
||||
def make_handler(app: App):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_request(self, code="-", size="-"):
|
||||
if str(code).startswith("2"):
|
||||
return
|
||||
super().log_request(code, size)
|
||||
|
||||
def _body(self) -> dict:
|
||||
length = int(self.headers.get("Content-Length", "0") or 0)
|
||||
raw = self.rfile.read(length) if length else b"{}"
|
||||
data = json.loads(raw.decode("utf-8") or "{}")
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("JSON object required")
|
||||
return data
|
||||
|
||||
def _send(self, code: int, payload, content_type: str):
|
||||
if isinstance(payload, str):
|
||||
raw = payload.encode("utf-8")
|
||||
else:
|
||||
raw = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _json(self, code: int, payload: dict):
|
||||
self._send(code, payload, "application/json")
|
||||
|
||||
def _error(self, code: int, message: str):
|
||||
self._json(code, {"error": message})
|
||||
|
||||
def do_GET(self):
|
||||
path = urlparse(self.path).path
|
||||
if path == "/":
|
||||
self._send(200, PAGE, "text/html; charset=utf-8")
|
||||
return
|
||||
if path == "/api/state":
|
||||
self._json(200, app.state())
|
||||
return
|
||||
if path == "/favicon.ico":
|
||||
self.send_response(204)
|
||||
self.end_headers()
|
||||
return
|
||||
self._error(404, "Not found")
|
||||
|
||||
def do_POST(self):
|
||||
path = urlparse(self.path).path
|
||||
try:
|
||||
data = self._body()
|
||||
except (json.JSONDecodeError, UnicodeDecodeError, ValueError):
|
||||
self._error(400, "Need a JSON object")
|
||||
return
|
||||
try:
|
||||
if path == "/api/aim":
|
||||
app.rig.update(
|
||||
target=str(data.get("target", "both")),
|
||||
pan=data["pan"],
|
||||
tilt=data["tilt"],
|
||||
dimmer=data.get("dimmer", app.rig.dimmer),
|
||||
)
|
||||
self._json(200, {"ok": True})
|
||||
return
|
||||
if path == "/api/color":
|
||||
app.rig.set_color(str(data.get("target", "both")), data.get("color", ""))
|
||||
self._json(200, app.state())
|
||||
return
|
||||
if path == "/api/node":
|
||||
app.select_node(data.get("ip", ""))
|
||||
self._json(200, app.state())
|
||||
return
|
||||
if path == "/api/nodes":
|
||||
app.refresh_nodes()
|
||||
self._json(200, app.state())
|
||||
return
|
||||
if path == "/api/positions":
|
||||
name = clean_name(data.get("name", ""))
|
||||
live = app.rig.live()
|
||||
app.store.upsert(name, live["m1"], live["m2"])
|
||||
self._json(200, app.state(saved=name))
|
||||
return
|
||||
if path == "/api/recall":
|
||||
name = clean_name(data.get("name", ""))
|
||||
entry = app.store.get(name)
|
||||
if entry is None:
|
||||
self._error(404, f"No position named {name}")
|
||||
return
|
||||
app.rig.recall(entry)
|
||||
self._json(200, app.state())
|
||||
return
|
||||
if path == "/api/delete":
|
||||
name = clean_name(data.get("name", ""))
|
||||
if not app.store.delete(name):
|
||||
self._error(404, f"No position named {name}")
|
||||
return
|
||||
self._json(200, app.state())
|
||||
return
|
||||
except KeyError:
|
||||
self._error(400, "Need pan and tilt")
|
||||
return
|
||||
except ValueError as exc:
|
||||
self._error(400, str(exc))
|
||||
return
|
||||
except OSError as exc:
|
||||
self._error(500, f"Could not write positions: {exc}")
|
||||
return
|
||||
self._error(404, "Not found")
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def parse_args():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--host", default="127.0.0.1", help="Web bind address")
|
||||
parser.add_argument("--port", type=int, default=8765)
|
||||
parser.add_argument(
|
||||
"--file",
|
||||
type=Path,
|
||||
default=root / "shows" / "mover_positions.json",
|
||||
help="JSON file for saved positions",
|
||||
)
|
||||
parser.add_argument("--ip", default=None, help=f"Art-Net destination (default: poll, else {DEFAULT_NODE})")
|
||||
parser.add_argument("--universe", type=int, default=0)
|
||||
parser.add_argument("--address", type=int, default=M1_ADDR, help="M1 DMX start, 1-based")
|
||||
parser.add_argument("--address2", type=int, default=M2_ADDR, help="M2 DMX start, 1-based")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
store = Store(args.file)
|
||||
nodes = pin_gateway(discover_artnet_nodes())
|
||||
if args.ip:
|
||||
ip = clean_ip(args.ip)
|
||||
nodes = include_ip(nodes, ip)
|
||||
else:
|
||||
ip = nodes[0]["ip"]
|
||||
universe = args.universe
|
||||
chosen = next((node for node in nodes if node["ip"] == ip), None)
|
||||
if chosen and chosen.get("universe", "") != "" and args.universe == 0:
|
||||
universe = int(chosen["universe"])
|
||||
name = chosen["name"] if chosen and chosen.get("name") else ""
|
||||
print(f"Art-Net → {ip} {name} universe {universe}".replace(" ", " ").strip(), flush=True)
|
||||
for node in nodes:
|
||||
label = f" {node['ip']}"
|
||||
if node["name"]:
|
||||
label += f" {node['name']}"
|
||||
print(label, flush=True)
|
||||
print(f"Positions → {args.file}", flush=True)
|
||||
print("Stop QLC+ Art-Net output first. Ctrl+C blackout.", flush=True)
|
||||
sender = ArtNetSender(ip, universe=universe)
|
||||
rig = Rig(
|
||||
{
|
||||
"m1": Mover(sender, args.address, "M1"),
|
||||
"m2": Mover(sender, args.address2, "M2"),
|
||||
}
|
||||
)
|
||||
app = App(rig, store, sender, nodes, args.universe)
|
||||
httpd = ThreadingHTTPServer((args.host, args.port), make_handler(app))
|
||||
url_host = "127.0.0.1" if args.host in ("0.0.0.0", "::") else args.host
|
||||
print(f"Open http://{url_host}:{args.port}", flush=True)
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("\nstopped")
|
||||
finally:
|
||||
httpd.server_close()
|
||||
sender.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,363 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add cabaret's can patterns to shows/test.qxw, on the cans pads 1–8.
|
||||
|
||||
Eight of make_cabaret_vc.py's Can Patterns, laid out for the test show's
|
||||
test show's cans instead of cabaret's 8. The row of 4 (#3–#6) is always
|
||||
static (see CLAUDE.md): the patterns leave it out, so it keeps the Colour 1
|
||||
colour whatever runs. Where cabaret walks its U (#1, #2, the row of 4, #7, #8),
|
||||
these walk the other 11 cans round the room: #1, #2, #9, #11, #13, #14, #15,
|
||||
#12, #10, #7, #8.
|
||||
|
||||
Most are masks over the Colour 1 colour (the cans' own), so they show whatever
|
||||
colour is on:
|
||||
|
||||
40 Scanner pad 5 one can at a time round the ring, two fading behind it
|
||||
41 Fill pad 6 the ring fills up and empties again
|
||||
42 Center pad 7 out from the middle of the room to the back wall, and back in
|
||||
43 Pairs pad 8 mirrored pairs, outside in and back out
|
||||
36 Theater pad 1 every third can round the ring
|
||||
|
||||
Rainbow brings its own colours, as in cabaret:
|
||||
|
||||
37 Rainbow pad 2 a rainbow turning slowly round the ring
|
||||
|
||||
Where cabaret's Odd Even and Left Right trade blue and red, these trade the
|
||||
Colour 1 and Colour 2 colours:
|
||||
|
||||
38 Odd Even pad 3 a checkerboard: alternate cans front to back down each
|
||||
side, and opposite across the room, every can swapping
|
||||
39 Left Right pad 4 Colour 1 on the left and Colour 2 on the right, swapping
|
||||
|
||||
Each is two RGB matrices with the rgbscripts/swap.js script, one per half of
|
||||
the cans, swapping between the two colours the other way round. Four Matrix
|
||||
widgets in the collapsed Chase colours frame give them their start and end
|
||||
colours from the Colour 1 and Colour 2 pads, as the chases get theirs from
|
||||
Colour 2.
|
||||
|
||||
The rest are RGB matrices too, with the rgbscripts/steps.js script playing
|
||||
their steps, so each pattern runs as the same few functions from start to stop
|
||||
and a chase started while it runs lands on top of it. (A chaser of scenes would
|
||||
start a newer scene every step: newer than the chase, so a mask step would
|
||||
blank the chase and a colour step cover it.) A mask pattern is a pair of Mask
|
||||
matrices, one on red, green and blue and one on white, so the white in Warm,
|
||||
White and Cool is masked too; Rainbow and the swaps run Can no white beside
|
||||
them to take the Colour 1 white off the animated cans. For the same reason a
|
||||
Colour 1 scene started after a pattern would cover it, so padcontroller/layer.py
|
||||
restarts the pattern that is on just after a Colour 1 press. Both scripts are
|
||||
linked into ~/.qlcplus/rgbscripts, where QLC+ looks.
|
||||
|
||||
All of them follow the cans' Speed dial (knob 1, CC 30) like the chases. The
|
||||
dial scales its time by powers of 2, so their fades and step times are its
|
||||
200 ms default times 1, 2, 4, 8 or 16, the nearest to cabaret's:
|
||||
|
||||
Scanner, Theater 0.4 s a step (cabaret 0.4 s)
|
||||
Fill, Center 0.2 s fade + 0.2 s (0.2 s + 0.3 s)
|
||||
Pairs 0.2 s fade + 0.6 s (0.2 s + 0.4 s)
|
||||
Rainbow 1.6 s fade + 1.6 s (2 s + 0.5 s)
|
||||
Odd Even, Left 1.6 s fade + 1.6 s (3 s + 1 s)
|
||||
Right
|
||||
|
||||
Cabaret's Collapse and Chase Out, which only replay Center's and Scanner's
|
||||
steps with a dark one after, are left out.
|
||||
|
||||
They only set the cans' red, green, blue and white, so the Front, Back and
|
||||
Middle knobs still set how bright they are. They take the empty buttons of the
|
||||
pads frame (Buttons 53–60), beside the chases, in a Can patterns solo frame
|
||||
so only one runs at a time. Like the chases they sit under the pads frame's
|
||||
Peak (CC 35). #14 gets its colour forced LTP, as the other animated cans
|
||||
already have, so the colour patterns cover the Colour 1 scene there too.
|
||||
|
||||
python3 scripts/shows/can_patterns.py
|
||||
|
||||
Run it once; it stops if the patterns are already there. QLC+ has to reopen the
|
||||
show to see them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from mover_bank import NO_FUNCTION, NOTE_BASE, ROOT, appearance, button
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
STAGE = ROOT / "stage" / "map.json"
|
||||
|
||||
# Can name -> fixture ID in test.qxw
|
||||
CANS = {f"#{n}": n - 1 for n in range(1, 9)} | {f"#{n}": n + 1 for n in range(9, 16)}
|
||||
STATIC = ("#3", "#4", "#5", "#6") # the row of 4 never animates
|
||||
ANIMATED = {n: fid for n, fid in CANS.items() if n not in STATIC}
|
||||
RING = ("#1", "#2", "#9", "#11", "#13", "#14", "#15", "#12", "#10", "#7", "#8")
|
||||
HTP_COLOUR = ("#14",)
|
||||
F_FIRST = 80
|
||||
SIZE = 90
|
||||
# Note -> the empty pads frame button on that pad
|
||||
EMPTY_BUTTONS = {36: 57, 37: 58, 38: 59, 39: 60, 40: 53, 41: 54, 42: 55, 43: 56}
|
||||
|
||||
# make_cabaret_vc.py's colours
|
||||
RAINBOW_RGB = [(255, 0, 0), (255, 127, 0), (255, 255, 0), (0, 255, 0),
|
||||
(0, 255, 255), (0, 0, 255), (127, 0, 255), (255, 0, 255)]
|
||||
GROUP_ODD, GROUP_EVEN, GROUP_LEFT, GROUP_RIGHT, GROUP_RING = 9, 10, 11, 12, 13
|
||||
SCRIPTS = (ROOT / "rgbscripts" / "swap.js", ROOT / "rgbscripts" / "steps.js")
|
||||
USER_SCRIPTS = Path.home() / ".qlcplus" / "rgbscripts"
|
||||
CYAN, BLUE = 4278255615, 4278190335 # the chases' starting colour; Colour 2 Blue
|
||||
COLOUR_2_NOTE, COLOUR_1_NOTE = 68, 52 # first pad of each colour set
|
||||
SPEED_DIAL = 111 # the cans' Speed dial, knob 1
|
||||
SPEED_MS = 200 # its starting time
|
||||
# Index into QLC+'s speed dial factors: (Not Sent), 0, 1/16, 1/8, 1/4, 1/2, 1, 2, 4, 8, 16
|
||||
FACTORS = {SPEED_MS * 2 ** k: 6 + k for k in range(5)} # 1x to 16x
|
||||
NOT_SENT = 0
|
||||
SWAP_FADE_MS, SWAP_STEP_MS = 1600, 3200
|
||||
SCANNER_TAIL = (110, 35) # mask levels of the cans one and two behind the lit one
|
||||
|
||||
|
||||
def positions() -> dict[str, tuple[float, float]]:
|
||||
fixtures = json.loads(STAGE.read_text())["fixtures"]
|
||||
return {name: (f["x"], f["y"]) for name, f in fixtures.items() if name in ANIMATED}
|
||||
|
||||
|
||||
def hex_rgb(rgb: tuple[int, int, int]) -> str:
|
||||
return "%02x%02x%02x" % rgb
|
||||
|
||||
|
||||
def steps_matrix(fid: int, name: str, steps: list[list[tuple[int, int, int]]], fade_in: int, step_ms: int,
|
||||
run_order: str = "Loop", mode: str = "RGB", blend: str = "Normal") -> str:
|
||||
"""An RGB matrix on the ring group playing steps (each the ring's colours) with rgbscripts/steps.js."""
|
||||
text = ";".join(",".join(hex_rgb(c) for c in step) for step in steps)
|
||||
blend_attr = f' BlendMode="{blend}"' if blend != "Normal" else ""
|
||||
return f''' <Function ID="{fid}" Type="RGBMatrix" Name="{name}"{blend_attr}>
|
||||
<Speed FadeIn="{fade_in}" FadeOut="0" Duration="{step_ms}"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>{run_order}</RunOrder>
|
||||
<Algorithm Type="Script">Steps</Algorithm>
|
||||
<MonoColor>{CYAN}</MonoColor>
|
||||
<ControlMode>{mode}</ControlMode>
|
||||
<FixtureGroup>{GROUP_RING}</FixtureGroup>
|
||||
<Property Name="steps" Value="{text}"/>
|
||||
</Function>
|
||||
'''
|
||||
|
||||
|
||||
def group(gid: int, name: str, cans: list[str]) -> str:
|
||||
heads = "\n".join(f' <Head X="{x}" Y="0" Fixture="{ANIMATED[n]}">0</Head>' for x, n in enumerate(cans))
|
||||
return f''' <FixtureGroup ID="{gid}">
|
||||
<Name>{name}</Name>
|
||||
<Size X="{len(cans)}" Y="1"/>
|
||||
{heads}
|
||||
</FixtureGroup>
|
||||
'''
|
||||
|
||||
|
||||
def swap_matrix(fid: int, name: str, gid: int, start: int, end: int) -> str:
|
||||
"""Every can in its group in the start colour, then the end colour, crossfading."""
|
||||
return f''' <Function ID="{fid}" Type="RGBMatrix" Name="{name}">
|
||||
<Speed FadeIn="{SWAP_FADE_MS}" FadeOut="1000" Duration="{SWAP_STEP_MS}"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>Loop</RunOrder>
|
||||
<Algorithm Type="Script">Swap</Algorithm>
|
||||
<MonoColor>{start}</MonoColor>
|
||||
<EndColor>{end}</EndColor>
|
||||
<ControlMode>RGB</ControlMode>
|
||||
<FixtureGroup>{gid}</FixtureGroup>
|
||||
</Function>
|
||||
'''
|
||||
|
||||
|
||||
def collection(fid: int, name: str, steps: list[int]) -> str:
|
||||
rows = "\n".join(f' <Step Number="{i}">{s}</Step>' for i, s in enumerate(steps))
|
||||
return f' <Function ID="{fid}" Type="Collection" Name="{name}">\n{rows}\n </Function>\n'
|
||||
|
||||
|
||||
def rainbow_at(t: float) -> tuple[int, int, int]:
|
||||
"""RAINBOW_RGB as a wheel, t from 0 to 8, blending between neighbours."""
|
||||
i = math.floor(t) % 8
|
||||
a, b = RAINBOW_RGB[i], RAINBOW_RGB[(i + 1) % 8]
|
||||
w = t - math.floor(t)
|
||||
return tuple(round(x + (y - x) * w) for x, y in zip(a, b))
|
||||
|
||||
|
||||
def factor(ms: int) -> int:
|
||||
"""The speed dial factor that gives ms at its starting time; 0 ms is left alone."""
|
||||
if ms == 0:
|
||||
return NOT_SENT
|
||||
if ms not in FACTORS:
|
||||
raise SystemExit(f"{ms} ms is not the Speed dial's {SPEED_MS} ms times 1, 2, 4, 8 or 16")
|
||||
return FACTORS[ms]
|
||||
|
||||
|
||||
def build() -> tuple[str, str, list[tuple[str, int, int]], list[tuple[str, int, int]], list[tuple[int, int, int]]]:
|
||||
"""The groups, the functions, (caption, function ID, note) for each button in pad order,
|
||||
(name, matrix ID, first note of its start colour's pads) for each swap matrix, and
|
||||
(function ID, fade in, step time) for each function on the Speed dial."""
|
||||
pos = positions()
|
||||
fid = F_FIRST
|
||||
blocks: list[str] = []
|
||||
patterns: dict[str, int] = {}
|
||||
speeds: list[tuple[int, int, int]] = []
|
||||
|
||||
def add(xml_for) -> int:
|
||||
nonlocal fid
|
||||
blocks.append(xml_for(fid))
|
||||
fid += 1
|
||||
return fid - 1
|
||||
|
||||
def add_pattern(caption: str, matrices: list[int], fade_in: int, step_ms: int) -> None:
|
||||
speeds.extend((m, fade_in, step_ms) for m in matrices if m != no_white)
|
||||
patterns[caption] = add(lambda f: collection(f, f"Can {caption}", matrices))
|
||||
|
||||
def add_mask(caption: str, levels: list[dict[str, int]], fade_in: int, hold: int, run_order: str = "Loop") -> None:
|
||||
"""A mask pattern: each step the ring's levels, 255 keeping the colour under it and 0 a hole."""
|
||||
steps = [[(lv.get(n, 0),) * 3 for n in RING] for lv in levels]
|
||||
rgb = add(lambda f: steps_matrix(f, f"Can {caption}", steps, fade_in, fade_in + hold, run_order, "RGB", "Mask"))
|
||||
white = add(lambda f: steps_matrix(f, f"Can {caption} white", steps, fade_in, fade_in + hold, run_order,
|
||||
"White", "Mask"))
|
||||
add_pattern(caption, [rgb, white], fade_in, fade_in + hold)
|
||||
|
||||
no_white = add(lambda f: steps_matrix(f, "Can no white", [[(0, 0, 0)] * len(RING)], 0, 1000, mode="White"))
|
||||
|
||||
rainbow = [[rainbow_at(i * 8 / len(RING) + s) for i in range(len(RING))] for s in range(8)]
|
||||
add_pattern("Rainbow", [add(lambda f: steps_matrix(f, "Can Rainbow", rainbow, 1600, 3200)), no_white], 1600, 3200)
|
||||
|
||||
# Odd Even and Left Right: one swap matrix per half, Colour 1 first on one and Colour 2 first on the other.
|
||||
left = {n for n in ANIMATED if pos[n][0] <= 0} # #14, in the middle of the back wall, goes left
|
||||
rows = sorted({y for _, y in pos.values()}, reverse=True) # front first
|
||||
odd = [n for n in ANIMATED if (rows.index(pos[n][1]) + (n not in left)) % 2 == 0]
|
||||
halves = {"Odd Even": ((GROUP_ODD, "Cans odd", odd), (GROUP_EVEN, "Cans even", [n for n in ANIMATED if n not in odd])),
|
||||
"Left Right": ((GROUP_LEFT, "Cans left", sorted(left, key=RING.index)),
|
||||
(GROUP_RIGHT, "Cans right", [n for n in RING if n not in left]))}
|
||||
groups = "".join(group(gid, name, cans) for pair in halves.values() for gid, name, cans in pair)
|
||||
swaps = []
|
||||
for caption, ((gid_a, name_a, _), (gid_b, name_b, _)) in halves.items():
|
||||
a = add(lambda f: swap_matrix(f, f"Can {caption} {name_a[5:]}", gid_a, CYAN, BLUE))
|
||||
b = add(lambda f: swap_matrix(f, f"Can {caption} {name_b[5:]}", gid_b, BLUE, CYAN))
|
||||
swaps += [(f"{caption} {name_a[5:]}", a, COLOUR_1_NOTE), (f"{caption} {name_b[5:]}", b, COLOUR_2_NOTE)]
|
||||
add_pattern(caption, [a, b, no_white], SWAP_FADE_MS, SWAP_STEP_MS)
|
||||
groups += group(GROUP_RING, "Cans ring", list(RING))
|
||||
|
||||
def scanner_step(i: int) -> dict[str, int]:
|
||||
"""The can at i lit, and the tail behind it round the ring."""
|
||||
return {RING[(i - k) % len(RING)]: level for k, level in enumerate((255, *SCANNER_TAIL))}
|
||||
|
||||
add_mask("Scanner", [scanner_step(i) for i in range(len(RING))], 0, 400)
|
||||
add_mask("Fill", [dict.fromkeys(RING[:k], 255) for k in range(1, len(RING) + 1)], 200, 200, "PingPong")
|
||||
|
||||
# Rings out from the middle of the room, nearest first; the back wall comes in last.
|
||||
rings = [{"#2", "#7", "#9", "#10"}, {"#1", "#8"}, set(ANIMATED)]
|
||||
assert set().union(*rings) == set(ANIMATED)
|
||||
center, lit = [], set()
|
||||
for ring in rings:
|
||||
lit |= ring
|
||||
center.append(dict.fromkeys(lit, 255))
|
||||
add_mask("Center", center, 200, 200, "PingPong")
|
||||
|
||||
# Mirrored pairs, furthest from the middle first; #14 goes with the back corners.
|
||||
pairs = sorted(({n, m} for n in ANIMATED for m in ANIMATED
|
||||
if pos[n][0] < 0 and pos[m][0] == -pos[n][0] and pos[m][1] == pos[n][1]),
|
||||
key=lambda p: -math.hypot(*pos[min(p)]))
|
||||
pairs[0] |= {"#14"}
|
||||
add_mask("Pairs", [dict.fromkeys(p, 255) for p in pairs], 200, 600, "PingPong")
|
||||
add_mask("Theater", [{n: 255 for i, n in enumerate(RING) if i % 3 == s} for s in range(3)], 0, 400)
|
||||
|
||||
order = [("Theater", 36), ("Rainbow", 37), ("Odd Even", 38), ("Left Right", 39),
|
||||
("Scanner", 40), ("Fill", 41), ("Center", 42), ("Pairs", 43)]
|
||||
return groups, "".join(blocks), [(caption, patterns[caption], note) for caption, note in order], swaps, speeds
|
||||
|
||||
|
||||
def solo_frame(wid: int, x: int, y: int, buttons: str) -> str:
|
||||
indent = " "
|
||||
return (f'{indent}<SoloFrame Caption="Can patterns" ID="{wid}">\n'
|
||||
+ appearance(indent + " ")
|
||||
+ f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{4 * SIZE}" Height="{2 * SIZE}"/>\n'
|
||||
f'{indent} <AllowChildren>True</AllowChildren>\n{indent} <AllowResize>True</AllowResize>\n'
|
||||
f'{indent} <ShowHeader>False</ShowHeader>\n{indent} <ShowEnableButton>False</ShowEnableButton>\n'
|
||||
f'{indent} <Mixing>False</Mixing>\n{indent} <Collapsed>False</Collapsed>\n{indent} <Disabled>False</Disabled>\n'
|
||||
f'{buttons}{indent}</SoloFrame>\n')
|
||||
|
||||
|
||||
def colour_matrix(xml: str, wid: int, caption: str, fid: int, start_note: int, x: int, y: int) -> str:
|
||||
"""A copy of the chases' Forward colour widget for a swap matrix: its start colour from the pads
|
||||
from start_note, its end colour from the other colour set's."""
|
||||
m = re.search(r' <Matrix Caption="Forward colour" ID="61">.*? </Matrix>\n', xml, re.S).group(0)
|
||||
head = m[:m.index(" <Control ")]
|
||||
head = head.replace('Caption="Forward colour" ID="61"', f'Caption="{caption}" ID="{wid}"')
|
||||
head = head.replace('<Function ID="43" InstantApply', f'<Function ID="{fid}" InstantApply')
|
||||
head = re.sub(r'X="\d+" Y="\d+" Width', f'X="{x}" Y="{y}" Width', head, count=1)
|
||||
colours = re.findall(r'<Color>(#[0-9a-f]{6})</Color>', m)
|
||||
end_note = COLOUR_1_NOTE if start_note == COLOUR_2_NOTE else COLOUR_2_NOTE
|
||||
controls = "".join(
|
||||
f' <Control ID="{k * 16 + i + 1}">\n <Type>{kind}</Type>\n <Color>{c}</Color>\n'
|
||||
f' <Input Universe="1" Channel="{NOTE_BASE + note + i}"/>\n </Control>\n'
|
||||
for k, (kind, note) in enumerate((("StartColor", start_note), ("EndColor", end_note)))
|
||||
for i, c in enumerate(colours))
|
||||
return head + controls + " </Matrix>\n"
|
||||
|
||||
|
||||
def link_scripts() -> None:
|
||||
USER_SCRIPTS.mkdir(parents=True, exist_ok=True)
|
||||
for script in SCRIPTS:
|
||||
link = USER_SCRIPTS / script.name
|
||||
if not link.is_symlink() or link.resolve() != script:
|
||||
link.unlink(missing_ok=True)
|
||||
link.symlink_to(script)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if "Can Scanner" in xml or "Can Rainbow" in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the can patterns")
|
||||
groups, functions, specs, swaps, speeds = build()
|
||||
used = {int(i) for i in re.findall(r'<Function ID="(\d+)" Type', xml)}
|
||||
if used & set(range(F_FIRST, F_FIRST + functions.count("<Function "))):
|
||||
raise SystemExit(f"Function IDs from {F_FIRST} are taken")
|
||||
taken = {int(i) for i in re.findall(r'<Input Universe="1" Channel="(\d+)"', xml)}
|
||||
if taken & {NOTE_BASE + n for _, _, n in specs}:
|
||||
raise SystemExit("Some of the free cans pads are taken")
|
||||
|
||||
# Buttons 53–60 are the bottom two rows of the pads frame; a solo frame takes their place.
|
||||
empty = re.search(r' <Button Caption="Button 53" ID="53".*? <Button Caption="Button 60" ID="60".*? </Button>\n',
|
||||
xml, re.S)
|
||||
if empty is None or "<Input" in empty.group(0) or empty.group(0).count("<Button ") != 8:
|
||||
raise SystemExit("Buttons 53–60 are not the empty rows they were")
|
||||
spots = {int(w): (int(x), int(y)) for w, x, y in re.findall(
|
||||
r'<Button Caption="Button (\d+)" ID="\d+" Icon="">\n <WindowState Visible="True" X="(\d+)" Y="(\d+)"',
|
||||
empty.group(0))}
|
||||
left, top = min(x for x, _ in spots.values()), min(y for _, y in spots.values())
|
||||
buttons = "".join(button(EMPTY_BUTTONS[note], caption, spots[EMPTY_BUTTONS[note]][0] - left,
|
||||
spots[EMPTY_BUTTONS[note]][1] - top, SIZE, fid, NOTE_BASE + note, indent=" ")
|
||||
for caption, fid, note in specs)
|
||||
next_id = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
|
||||
if int(i) != NO_FUNCTION) + 1
|
||||
xml = xml.replace(empty.group(0), solo_frame(next_id, left, top, buttons), 1)
|
||||
|
||||
# The swap matrices' colour widgets go under the Strobe 2 colour slider in the collapsed Chase colours frame.
|
||||
strobe_slider = re.search(r' <Slider Caption="Strobe 2 colour" ID="105".*? </Slider>\n', xml, re.S).group(0)
|
||||
widgets = "".join(colour_matrix(xml, next_id + 1 + k, f"{name} colour", fid, note, 10 + (k % 2) * 310, 735 + (k // 2) * 230)
|
||||
for k, (name, fid, note) in enumerate(swaps))
|
||||
xml = xml.replace(strobe_slider, strobe_slider + widgets, 1)
|
||||
old = '<WindowState Visible="True" X="330" Y="910" Width="640" Height="740"/>'
|
||||
if old not in xml:
|
||||
raise SystemExit("Couldn't find the Chase colours frame at 740 high")
|
||||
xml = xml.replace(old, old.replace('Height="740"', f'Height="{740 + 230 * ((len(swaps) + 1) // 2)}"'), 1)
|
||||
|
||||
for name in HTP_COLOUR:
|
||||
xml, n = re.subn(rf"( <ID>{CANS[name]}</ID>\n <Name>{name}</Name>\n(?: .*\n)*? <ForcedHTP>1</ForcedHTP>\n)(?! <ForcedLTP>)",
|
||||
r"\1 <ForcedLTP>2,3,4,5</ForcedLTP>\n", xml, count=1)
|
||||
if n != 1:
|
||||
raise SystemExit(f"Couldn't find {name}'s forced HTP strobe to put its colour LTP beside")
|
||||
dial = re.search(rf' <SpeedDial Caption="Speed" ID="{SPEED_DIAL}">.*? </SpeedDial>\n', xml, re.S)
|
||||
if dial is None or f"<Time>{SPEED_MS}</Time>" not in dial.group(0):
|
||||
raise SystemExit(f"Couldn't find the Speed dial at {SPEED_MS} ms")
|
||||
rows = "".join(f' <Function FadeIn="{factor(fade)}" FadeOut="{NOT_SENT}" Duration="{factor(step)}">{fid}</Function>\n'
|
||||
for fid, fade, step in speeds)
|
||||
xml = xml.replace(dial.group(0), dial.group(0).replace(" </SpeedDial>\n", rows + " </SpeedDial>\n"), 1)
|
||||
xml = xml.replace(' <Function ID="0" Type="Scene"', groups + ' <Function ID="0" Type="Scene"', 1)
|
||||
xml = xml.replace(" </Engine>", functions + " </Engine>", 1)
|
||||
SHOW.write_text(xml)
|
||||
link_scripts()
|
||||
print(f"Added the can patterns to {SHOW.relative_to(ROOT)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Make a click on a chase button in shows/test.qxw do what its pad does.
|
||||
|
||||
Each cans chase was two buttons on one pad note: the pads frame's button runs
|
||||
the side dimmer hold, under the frame's Peak (CC 35), and the Chase runs frame's
|
||||
button runs the stripe matrix, outside it, so Peak caps the dimmers and not the
|
||||
stripe's colour. The pad pressed both; a click pressed only the hold.
|
||||
|
||||
Now the pads frame's button runs a hold of the chase's own, which runs both.
|
||||
Its one step is a collection of the Sides dimmer scene and a Script that starts
|
||||
the stripe and waits. A chaser and a collection pass Peak on to what they run,
|
||||
but a script doesn't, so the dimmers are capped and the stripe isn't, as with
|
||||
the pad. QLC+ 4.12 stops what a script started when the script ends (it has no
|
||||
stoponexit), so the script waits until the hold's step ends and the chaser stops
|
||||
it; the stripe has run its course by then. The holds are on the Speed dial (knob
|
||||
1) as the shared ones were. The Chase runs buttons no longer listen to the pad,
|
||||
which would otherwise toggle the stripe straight back off; clicked, they still
|
||||
run the stripe on its own.
|
||||
|
||||
python3 scripts/shows/chase_clicks.py
|
||||
|
||||
Run it once; it stops if the chases' own holds are already there. QLC+ has to
|
||||
reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import ROOT
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
SPEED_DIAL = 111 # the cans' Speed dial, knob 1
|
||||
SIDES_DIMMER = 44 # the Sides dimmer scene the shared holds run
|
||||
WAIT_MS = 3600000 # longer than any hold: the chaser stops the script first
|
||||
|
||||
# pads frame button, Chase runs button, collection, stripe matrix, shared hold
|
||||
CHASES = (
|
||||
("Chase forward", 45, 79, 46, 43, 45),
|
||||
("Chase reverse", 46, 80, 48, 47, 45),
|
||||
("Zigzag forward", 47, 81, 51, 49, 50),
|
||||
("Opposing zigzag", 48, 82, 53, 52, 45),
|
||||
)
|
||||
|
||||
|
||||
def script(fid: int, name: str, start: int) -> str:
|
||||
return f""" <Function ID="{fid}" Type="Script" Name="{name}">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>SingleShot</RunOrder>
|
||||
<Command>startfunction%3A{start}</Command>
|
||||
<Command>wait%3A{WAIT_MS}</Command>
|
||||
</Function>
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if any(f'Name="{name} hold"' in xml for name, *_ in CHASES):
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the chases' own holds")
|
||||
next_fid = max(int(i) for i in re.findall(r'<Function ID="(\d+)" Type', xml)) + 1
|
||||
dial = re.search(rf' <SpeedDial Caption="Speed" ID="{SPEED_DIAL}">.*? </SpeedDial>\n', xml, re.S)
|
||||
if dial is None:
|
||||
raise SystemExit("Couldn't find the Speed dial")
|
||||
new_dial = dial.group(0)
|
||||
functions = ""
|
||||
for k, (name, pad_button, run_button, coll, stripe, hold) in enumerate(CHASES):
|
||||
sid, hid = next_fid + 2 * k, next_fid + 2 * k + 1
|
||||
functions += script(sid, f"{name} start", stripe)
|
||||
|
||||
# The chase's own hold: the shared one, running the dimmer and the stripe's script.
|
||||
shared = re.search(rf' <Function ID="{hold}" Type="Chaser" Name="[^"]*">\n.*? </Function>\n', xml, re.S).group(0)
|
||||
if f">{SIDES_DIMMER}</Step>" not in shared:
|
||||
raise SystemExit(f"Hold {hold} doesn't run the Sides dimmer")
|
||||
own = re.sub(r'<Function ID="\d+" Type="Chaser" Name="[^"]*">',
|
||||
f'<Function ID="{hid}" Type="Chaser" Name="{name} hold">', shared)
|
||||
functions += own.replace(f">{SIDES_DIMMER}</Step>", f">{coll}</Step>")
|
||||
row = re.search(rf' <Function FadeIn="\d+" FadeOut="\d+" Duration="\d+">{hold}</Function>\n', new_dial)
|
||||
if row is None:
|
||||
raise SystemExit(f"Hold {hold} isn't on the Speed dial")
|
||||
new_dial = new_dial.replace(" </SpeedDial>\n", row.group(0).replace(f">{hold}<", f">{hid}<") + " </SpeedDial>\n")
|
||||
|
||||
old = re.search(rf' <Function ID="{coll}" Type="Collection" Name="{name}">\n.*? </Function>\n', xml, re.S)
|
||||
if old is None or f">{stripe}</Step>" not in old.group(0) or f">{hold}</Step>" not in old.group(0):
|
||||
raise SystemExit(f"The {name} collection is not the stripe and hold it was")
|
||||
xml = xml.replace(old.group(0), f' <Function ID="{coll}" Type="Collection" Name="{name}">\n'
|
||||
f' <Step Number="0">{SIDES_DIMMER}</Step>\n <Step Number="1">{sid}</Step>\n </Function>\n', 1)
|
||||
|
||||
btn = re.search(rf'<Button Caption="{name}" ID="{pad_button}" .*?</Button>', xml, re.S)
|
||||
if btn is None or f'<Function ID="{hold}"/>' not in btn.group(0):
|
||||
raise SystemExit(f"The {name} button doesn't run its hold")
|
||||
xml = xml.replace(btn.group(0), btn.group(0).replace(f'<Function ID="{hold}"/>', f'<Function ID="{hid}"/>'), 1)
|
||||
|
||||
run = re.search(rf'<Button Caption="{name} run" ID="{run_button}" .*?</Button>', xml, re.S)
|
||||
if run is None:
|
||||
raise SystemExit(f"Couldn't find the {name} run button")
|
||||
xml = xml.replace(run.group(0), re.sub(r'\n\s*<Input Universe="1" Channel="\d+"/>', "", run.group(0)), 1)
|
||||
|
||||
xml = xml.replace(dial.group(0), new_dial, 1)
|
||||
xml = xml.replace(" </Engine>", functions + " </Engine>", 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Chase buttons in {SHOW.relative_to(ROOT)} now run the whole chase")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add two sets of 16 colour scenes and their buttons to shows/test.show.json.
|
||||
|
||||
Colour 1 paints all 15 cans and colour 2 the four movers, so one colour
|
||||
for each can be on at once. Each set is a solo frame and every scene
|
||||
fades in and out over FADE_MS. Bank 2 (notes 52–67) picks colour 1.
|
||||
Holding Play picks set B: the pad controller turns those notes into 68–83 while
|
||||
Play is down. Bank 1 is kept for animations.
|
||||
|
||||
python3 scripts/shows/colour_sets.py && python3 -m showfile write shows/test.show.json -o shows/test.qxw
|
||||
The colour scenes leave the dimmers alone: the Dimmers frame's Level sliders
|
||||
own them, on knob 15 (movers), knob 5 (cans 9–15), knob 7 (cans 3–6) and
|
||||
knob 8 (cans 1, 2, 7, 8).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SPEC = ROOT / "shows" / "test.show.json"
|
||||
|
||||
FADE_MS = 1000
|
||||
DIMMER, RED, GREEN, BLUE, WHITE = 0, 2, 3, 4, 5
|
||||
PAD_BANK_2_FIRST_NOTE = 52
|
||||
HELD_FIRST_NOTE = 68 # padcontroller/layer.py sends bank 2 here while Play is held
|
||||
PROFILE = "M-VAVE SMC-PAD"
|
||||
OMNI = 16 # QLC+ MIDI plugin channel that accepts every MIDI channel
|
||||
PAD_MIDI_CH = 9 # the pads send notes on channel 10
|
||||
KNOB_FIRST_CC = 30 # pad knob 1
|
||||
PAD_PORT = "padcontroller" # padcontroller/midi.py; it applies the Play layer
|
||||
|
||||
# name, r, g, b, w. Bottom row first, four to a row. The cans have a white emitter, so the whites use it.
|
||||
COLOURS = (
|
||||
("Red", 255, 0, 0, 0),
|
||||
("Orange", 255, 127, 0, 0),
|
||||
("Amber", 255, 191, 0, 0),
|
||||
("Yellow", 255, 255, 0, 0),
|
||||
("Lime", 127, 255, 0, 0),
|
||||
("Green", 0, 255, 0, 0),
|
||||
("Spring", 0, 255, 127, 0),
|
||||
("Cyan", 0, 255, 255, 0),
|
||||
("Azure", 0, 127, 255, 0),
|
||||
("Blue", 0, 0, 255, 0),
|
||||
("Violet", 127, 0, 255, 0),
|
||||
("Magenta", 255, 0, 255, 0),
|
||||
("Pink", 255, 40, 120, 0),
|
||||
("Warm", 255, 120, 40, 120),
|
||||
("White", 0, 0, 0, 255),
|
||||
("Cool", 80, 120, 255, 120),
|
||||
)
|
||||
CANS = [f"#{n}" for n in range(1, 16)]
|
||||
MOVERS = ["M1", "M2", "M3", "M4"]
|
||||
# Mover channels: 8 is centre brightness, 9 centre strobe, then seven R G B W groups from 10.
|
||||
MOVER_BRIGHTNESS, MOVER_STROBE, MOVER_GROUPS, MOVER_FIRST_COLOUR = 8, 9, 7, 10
|
||||
|
||||
|
||||
def swatch(r: int, g: int, b: int, w: int) -> list[int]:
|
||||
return [min(255, r + w), min(255, g + w), min(255, b + w)]
|
||||
|
||||
|
||||
# Level sliders on the dimmer channels: caption, knob (from 1), fixtures, channel.
|
||||
DIMMERS = (
|
||||
("Movers", 15, MOVERS, MOVER_BRIGHTNESS),
|
||||
("Cans 9–15", 5, CANS[8:], DIMMER),
|
||||
("Cans 3–6", 7, CANS[2:6], DIMMER),
|
||||
("Cans 1, 2, 7, 8", 8, CANS[0:2] + CANS[6:8], DIMMER),
|
||||
)
|
||||
|
||||
|
||||
def dimmers() -> dict:
|
||||
return {
|
||||
"type": "frame", "caption": "Dimmers", "x": 10, "y": 630, "w": 250, "h": 250,
|
||||
"children": [{
|
||||
"type": "slider", "caption": caption, "value": 255,
|
||||
"channels": [[fixture, channel] for fixture in fixtures],
|
||||
"x": 10 + index * 58, "y": 10, "w": 52, "h": 200,
|
||||
"input": {"universe": 1, "cc": [0, KNOB_FIRST_CC + knob - 1]},
|
||||
} for index, (caption, knob, fixtures, channel) in enumerate(DIMMERS)],
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
spec = json.loads(SPEC.read_text())
|
||||
spec["universes"][1]["input"] = {"plugin": "MIDI", "uid": PAD_PORT, "profile": PROFILE, "channel": OMNI, "line": 0}
|
||||
functions, frames = [], []
|
||||
for si, (label, cans, movers) in enumerate((("1", CANS, []), ("2", [], MOVERS))):
|
||||
buttons = []
|
||||
for i, (name, r, g, b, w) in enumerate(COLOURS):
|
||||
key = f"colour_{label}_{i + 1}"
|
||||
values = {can: {RED: r, GREEN: g, BLUE: b, WHITE: w} for can in cans}
|
||||
for mover in movers:
|
||||
values[mover] = {MOVER_STROBE: 0}
|
||||
for group in range(MOVER_GROUPS):
|
||||
first = MOVER_FIRST_COLOUR + group * 4
|
||||
values[mover].update({first: r, first + 1: g, first + 2: b, first + 3: w})
|
||||
functions.append({
|
||||
"key": key, "type": "scene", "name": f"{label} {name}",
|
||||
"fade_in": FADE_MS, "fade_out": FADE_MS, "values": values,
|
||||
})
|
||||
sw = swatch(r, g, b, w)
|
||||
dark = sum(sw) > 380
|
||||
button = {
|
||||
"type": "button", "caption": name, "function": key,
|
||||
# 4 wide like the pads: the first four colours are the bottom row.
|
||||
"x": 10 + (i % 4) * 96, "y": 10 + (3 - i // 4) * 66, "w": 90, "h": 60,
|
||||
"bg": sw,
|
||||
"fg": [0, 0, 0] if dark else [255, 255, 255],
|
||||
}
|
||||
button["input"] = {"universe": 1, "note": [PAD_MIDI_CH, (HELD_FIRST_NOTE if si else PAD_BANK_2_FIRST_NOTE) + i]}
|
||||
buttons.append(button)
|
||||
frames.append({
|
||||
"type": "solo", "caption": f"Colour {label}", "x": 10, "y": 10 + si * 310,
|
||||
"w": 400, "h": 300, "children": buttons,
|
||||
})
|
||||
spec["functions"] = functions
|
||||
spec["vc"] = frames + [dimmers()]
|
||||
SPEC.write_text(json.dumps(spec, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Draw the SMC-PAD layout for shows/test.qxw as shows/test-pads.png, or another show's.
|
||||
|
||||
Every label and colour comes from the show's virtual console: a pad shows the
|
||||
caption of the button on its note, and a colour pad that button's colour, so
|
||||
running this again after changing the show brings the picture up to date.
|
||||
|
||||
Bank 1, Pause off notes 36–51 the cans layer
|
||||
Bank 1, Pause on notes 84–99 the movers layer (padcontroller adds 48)
|
||||
Bank 2 notes 52–67 Colour 1, the cans
|
||||
Bank 2, Play held notes 68–83 Colour 2, the movers and the chases (adds 16)
|
||||
|
||||
Pad 1 is bottom left, as on the pad; knobs are laid out as in
|
||||
shows/openmic-knobs.png. A knob shows the sliders and speed dials on its CC.
|
||||
Each title says how to get there: the pad's PAD BANK and KNOB BANK buttons pick
|
||||
the banks, Pause (CC 28) latches bank 1 onto the movers, and Play held moves
|
||||
bank 2 to Colour 2.
|
||||
|
||||
python3 scripts/shows/draw_test_pads.py # shows/test.qxw -> shows/test-pads.png
|
||||
python3 scripts/shows/draw_test_pads.py gig # shows/gig.qxw -> shows/gig-pads.png
|
||||
|
||||
It needs Inkscape to turn the drawing into a PNG.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from mover_bank import NOTE_BASE, ROOT
|
||||
|
||||
|
||||
BG, PANEL, TEXT, MUTED, EDGE = "#1a1a1c", "#232327", "#f2f2f2", "#9a9aa4", "#3a3a42"
|
||||
PAD_W, PAD_H, GAP = 150, 90, 10
|
||||
KNOB_R, KNOB_DX, KNOB_DY = 40, 150, 130
|
||||
KNOB_BANK_H = 70 + 2 * KNOB_R + 3 * KNOB_DY + 100 # with room for the bottom labels
|
||||
# Function pads, by the frame their button is in: (fill, edge)
|
||||
GROUPS = {"Can patterns": ("#3b2a55", "#b79cff"), "Movement": ("#14423f", "#6fe0d2")}
|
||||
CHASE, STROBE = ("#1d3557", "#8fb8ff"), ("#4a4a50", "#ffffff")
|
||||
|
||||
# (title, how to get there on the pad, first note)
|
||||
LAYERS = (
|
||||
("Pad bank 1 · cans", "PAD BANK to bank 1, Pause off", 36),
|
||||
("Pad bank 1 · movers", "PAD BANK to bank 1, Pause on", 84),
|
||||
("Pad bank 2 · Colour 1", "PAD BANK to bank 2 · the cans", 52),
|
||||
("Pad bank 2 · Colour 2", "PAD BANK to bank 2, hold Play · movers, chases", 68),
|
||||
)
|
||||
|
||||
|
||||
def argb(value: str) -> str | None:
|
||||
"""#rrggbb from a QLC+ colour, or None for Default."""
|
||||
return None if value == "Default" else "#%06x" % (int(value) & 0xFFFFFF)
|
||||
|
||||
|
||||
def text_colour(fill: str) -> str:
|
||||
r, g, b = (int(fill[i:i + 2], 16) for i in (1, 3, 5))
|
||||
return "#111111" if 0.299 * r + 0.587 * g + 0.114 * b > 150 else TEXT
|
||||
|
||||
|
||||
def buttons(vc: str) -> dict[int, tuple[str, str | None, str]]:
|
||||
"""note -> (caption, background colour, the solo frame or frame it's in) for each button on a channel-10 note."""
|
||||
out = {}
|
||||
frames: list[tuple[int, str]] = [] # (position, caption) of each frame opening
|
||||
for m in re.finditer(r'<(?:Solo)?Frame Caption="([^"]*)"', vc):
|
||||
frames.append((m.start(), m.group(1)))
|
||||
for m in re.finditer(r'<Button Caption="([^"]*)" ID="\d+" Icon="">(.*?)</Button>', vc, re.S):
|
||||
inp = re.search(r'<Input Universe="1" Channel="(\d+)"/>', m.group(2))
|
||||
if inp is None or not 0 <= int(inp.group(1)) - NOTE_BASE < 128:
|
||||
continue
|
||||
frame = max((f for f in frames if f[0] < m.start()), default=(0, ""))[1]
|
||||
bg = re.search(r"<BackgroundColor>([^<]*)</BackgroundColor>", m.group(2))
|
||||
out[int(inp.group(1)) - NOTE_BASE] = (html.unescape(m.group(1)), argb(bg.group(1)) if bg else None, frame)
|
||||
return out
|
||||
|
||||
|
||||
def knobs(vc: str) -> dict[int, list[str]]:
|
||||
"""CC -> captions of the sliders and speed dials on it."""
|
||||
out: dict[int, list[str]] = {}
|
||||
for m in re.finditer(r'<(Slider|SpeedDial) Caption="([^"]*)" ID="\d+"(.*?)</\1>', vc, re.S):
|
||||
inp = re.search(r'<Input Universe="1" Channel="(\d+)"/>', m.group(3))
|
||||
if inp and int(inp.group(1)) < 128:
|
||||
out.setdefault(int(inp.group(1)), []).append(html.unescape(m.group(2)))
|
||||
return out
|
||||
|
||||
|
||||
def wrap(caption: str) -> list[str]:
|
||||
words, lines = caption.split(), [""]
|
||||
for w in words:
|
||||
if lines[-1] and len(lines[-1]) + 1 + len(w) > 11:
|
||||
lines.append(w)
|
||||
else:
|
||||
lines[-1] = f"{lines[-1]} {w}".strip()
|
||||
return lines
|
||||
|
||||
|
||||
def pad(x: int, y: int, number: int, info: tuple[str, str | None, str] | None) -> str:
|
||||
if info is None or info[0].startswith("Button "):
|
||||
return (f'<rect x="{x}" y="{y}" width="{PAD_W}" height="{PAD_H}" rx="10" fill="none" stroke="{EDGE}" '
|
||||
f'stroke-width="2" stroke-dasharray="6 6"/>'
|
||||
f'<text x="{x + 10}" y="{y + 22}" class="num" style="fill:{MUTED}">{number}</text>')
|
||||
caption, colour, frame = info
|
||||
if colour:
|
||||
fill, edge = colour, "#ffffff"
|
||||
elif frame in GROUPS:
|
||||
fill, edge = GROUPS[frame]
|
||||
elif "Strobe" in caption:
|
||||
fill, edge = STROBE
|
||||
else:
|
||||
fill, edge = CHASE
|
||||
ink = text_colour(fill)
|
||||
lines = wrap(caption)
|
||||
first = y + PAD_H / 2 + 8 - (len(lines) - 1) * 12
|
||||
label = "".join(f'<text x="{x + PAD_W / 2}" y="{first + i * 24}" class="label" style="fill:{ink}" '
|
||||
f'text-anchor="middle">{html.escape(t)}</text>' for i, t in enumerate(lines))
|
||||
return (f'<rect x="{x}" y="{y}" width="{PAD_W}" height="{PAD_H}" rx="10" fill="{fill}" stroke="{edge}" '
|
||||
f'stroke-width="3"/><text x="{x + 10}" y="{y + 22}" class="num" style="fill:{ink}" opacity="0.7">{number}</text>'
|
||||
+ label)
|
||||
|
||||
|
||||
def grid(x: int, y: int, title: str, sub: str, base: int, info: dict, first_pad: int) -> str:
|
||||
out = [f'<text x="{x}" y="{y}" class="title">{html.escape(title)}</text>',
|
||||
f'<text x="{x}" y="{y + 30}" class="sub">{html.escape(sub)}</text>']
|
||||
top = y + 55
|
||||
for i in range(16):
|
||||
col, row = i % 4, 3 - i // 4 # pad 1 bottom left
|
||||
out.append(pad(x + col * (PAD_W + GAP), top + row * (PAD_H + GAP), first_pad + i, info.get(base + i)))
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def knob_bank(x: int, y: int, bank: int, info: dict[int, list[str]]) -> str:
|
||||
out = [f'<text x="{x}" y="{y}" class="title">Knob bank {bank}</text>',
|
||||
f'<text x="{x}" y="{y + 30}" class="sub">KNOB BANK to bank {bank}</text>']
|
||||
for i in range(8):
|
||||
number = (bank - 1) * 8 + i + 1
|
||||
cx, cy = x + KNOB_R + 20 + (i % 2) * KNOB_DX, y + 70 + KNOB_R + (3 - i // 2) * KNOB_DY
|
||||
names = info.get(29 + number, [])
|
||||
stroke = TEXT if names else EDGE
|
||||
out.append(f'<circle cx="{cx}" cy="{cy}" r="{KNOB_R}" fill="{PANEL}" stroke="{stroke}" stroke-width="3"/>'
|
||||
f'<text x="{cx}" y="{cy + 9}" class="knob" style="fill:{stroke}" text-anchor="middle">{number}</text>')
|
||||
label = " / ".join(dict.fromkeys(names)) # Peak and Brightness share knob 15
|
||||
if label:
|
||||
out.append(f'<text x="{cx}" y="{cy + KNOB_R + 24}" class="small" text-anchor="middle">'
|
||||
f'{html.escape(label)}</text>')
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else "test"
|
||||
show, out = ROOT / "shows" / f"{name}.qxw", ROOT / "shows" / f"{name}-pads.png"
|
||||
vc = show.read_text().split("<VirtualConsole>")[1]
|
||||
info, knob_info = buttons(vc), knobs(vc)
|
||||
panel_w = 4 * PAD_W + 3 * GAP
|
||||
col2, col3 = 60 + panel_w + 70, 60 + 2 * (panel_w + 70)
|
||||
row_h = 55 + 4 * PAD_H + 3 * GAP + 80
|
||||
width, height = col3 + 2 * KNOB_DX + 60, max(60 + 2 * row_h, 70 + 2 * KNOB_BANK_H)
|
||||
body = []
|
||||
for k, (title, sub, base) in enumerate(LAYERS):
|
||||
x, y = (60, col2)[k % 2], 70 + (k // 2) * row_h
|
||||
body.append(grid(x, y, title, sub, base, info, 1 if base in (36, 84) else 17))
|
||||
body += [knob_bank(col3, 70, 1, knob_info), knob_bank(col3, 70 + KNOB_BANK_H, 2, knob_info)]
|
||||
svg = f'''<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">
|
||||
<style>
|
||||
text {{ font-family: "DejaVu Sans", sans-serif; fill: {TEXT}; }}
|
||||
.title {{ font-size: 30px; font-weight: bold; }}
|
||||
.sub {{ font-size: 20px; fill: {MUTED}; }}
|
||||
.num {{ font-size: 15px; font-weight: bold; }}
|
||||
.label {{ font-size: 19px; }}
|
||||
.knob {{ font-size: 26px; font-weight: bold; }}
|
||||
.small {{ font-size: 18px; }}
|
||||
</style>
|
||||
<rect width="100%" height="100%" fill="{BG}"/>
|
||||
{"".join(body)}
|
||||
</svg>
|
||||
'''
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "test-pads.svg"
|
||||
src.write_text(svg)
|
||||
subprocess.run(["inkscape", str(src), "--export-type=png", f"--export-filename={out}", "--export-dpi=96"],
|
||||
check=True, capture_output=True)
|
||||
print(f"Drew {out.relative_to(ROOT)} ({width}x{height})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Take the sound-reactive cans out of shows/test.qxw.
|
||||
|
||||
Removes the Sound and Threshold audio triggers, the Sound submaster beside the
|
||||
cans' Front and Back sliders (CC 100), and the Sound peak frame with its Peak
|
||||
submaster and Hit button, with the Cans hit scene and chaser that only Hit ran.
|
||||
The Pump and Threshold buttons on pads 1 and 2 (notes 36 and 37) were empty;
|
||||
they go back to plain spare buttons like the rest of that row. The pads frame's
|
||||
own Peak (CC 35) stays: it is the chases' peak.
|
||||
|
||||
padcontroller/layer.py drops its side of it in the same change: the two pads'
|
||||
modes, the CC 100 resets and the pad lamps that showed which was on.
|
||||
|
||||
python3 scripts/shows/drop_sound.py
|
||||
|
||||
Run it once; it stops if the audio triggers are already gone. QLC+ has to
|
||||
reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import ROOT
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
SOUND_SLIDER_W = 55 # the Sound slider and the gap before it in the Cans frame
|
||||
|
||||
|
||||
def cut(xml: str, pattern: str, what: str) -> str:
|
||||
xml, n = re.subn(pattern, "", xml, count=1, flags=re.S)
|
||||
if n != 1:
|
||||
raise SystemExit(f"Couldn't find {what}")
|
||||
return xml
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if "<AudioTriggers" not in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} has no sound triggers left")
|
||||
for caption in ("Sound", "Threshold"):
|
||||
xml = cut(xml, rf' <AudioTriggers BarsNumber="\d+" Caption="{caption}" ID="\d+">\n.*? </AudioTriggers>\n',
|
||||
f"the {caption} audio trigger")
|
||||
xml = cut(xml, r' <Slider Caption="Sound" ID="66" .*? </Slider>\n', "the Sound submaster")
|
||||
xml = cut(xml, r' <Frame Caption="Sound peak" ID="76">\n.*? </Frame>\n', "the Sound peak frame")
|
||||
for fid, name in ((55, "Cans hit"), (56, "Cans hit 100 ms")):
|
||||
xml = cut(xml, rf' <Function ID="{fid}" Type="\w+" Name="{name}">\n.*? </Function>\n', name)
|
||||
|
||||
# The Dimmers frame and its Cans frame lose the Sound slider's width.
|
||||
for caption, wid, x, y, w, h in (("Dimmers", 68, 880, 15, 264, 250), ("Cans", 73, 70, 40, 165, 205)):
|
||||
old = f'<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>'
|
||||
frame = re.search(rf'<Frame Caption="{caption}" ID="{wid}">\n(?:.*\n){{0,8}}?\s*{re.escape(old)}', xml)
|
||||
if frame is None:
|
||||
raise SystemExit(f"Couldn't find the {caption} frame at {w} wide")
|
||||
xml = xml.replace(frame.group(0), frame.group(0).replace(f'Width="{w}"', f'Width="{w - SOUND_SLIDER_W}"'), 1)
|
||||
|
||||
for caption, wid in (("Pump", 57), ("Threshold", 58)):
|
||||
old = f'<Button Caption="{caption}" ID="{wid}" Icon="">'
|
||||
if old not in xml:
|
||||
raise SystemExit(f"Couldn't find the {caption} button")
|
||||
xml = xml.replace(old, f'<Button Caption="Button {wid}" ID="{wid}" Icon="">', 1)
|
||||
|
||||
SHOW.write_text(xml)
|
||||
print(f"Took the sound pieces out of {SHOW.relative_to(ROOT)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,366 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rewrite xchc pattern scenes so the U of cans + centre movers act as one.
|
||||
|
||||
Building 7 m wide. Coordinates in metres:
|
||||
X = 0 at centre line, +X to the right
|
||||
Y = 0 at the row of 4, +Y toward audience (in front of the 4)
|
||||
|
||||
Audience
|
||||
1 8 ← wall-mounted sides @ 2.4 m in front of the 4
|
||||
2 M1 M2 7 ← wall-mounted sides @ 1.2 m; movers @ 1.1 m, ±0.3 m
|
||||
3 — 4 — 5 — 6 ← row of 4 at ±0.6 m and ±1.8 m from centre
|
||||
|
||||
Building 7 m → side walls at ±3.5 m. #1,#2 left wall; #7,#8 right wall.
|
||||
#1 front left. Movers 1.1 m in front of the row of 4, 0.3 m off centre.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
CANS = list(range(8))
|
||||
MOVERS = (8, 9)
|
||||
|
||||
WALL = 3.5 # building half-width
|
||||
|
||||
# Fixture ID → (x_m, y_m) — Y=0 = row of 4; +Y toward audience
|
||||
LAYOUT_M = {
|
||||
0: (-WALL, 2.4), # #1 front left — left wall
|
||||
1: (-WALL, 1.2), # #2 — left wall
|
||||
2: (-1.8, 0.0), # #3 row of 4
|
||||
3: (-0.6, 0.0), # #4 row of 4
|
||||
4: (0.6, 0.0), # #5 row of 4
|
||||
5: (1.8, 0.0), # #6 row of 4
|
||||
6: (WALL, 1.2), # #7 — right wall
|
||||
7: (WALL, 2.4), # #8 front right — right wall
|
||||
8: (-0.3, 1.1), # Small Eye #1 — 0.3 m off centre, 1.1 m in front of row of 4
|
||||
9: (0.3, 1.1), # Small Eye #2 — 0.3 m off centre, 1.1 m in front of row of 4
|
||||
}
|
||||
|
||||
# Walk U: #1 → #2 → along row of 4 L→R → #7 → #8
|
||||
U_WALK = [0, 1, 2, 3, 4, 5, 6, 7]
|
||||
LEFT_SIDE = {0, 1}
|
||||
RIGHT_SIDE = {6, 7}
|
||||
ROW4 = {2, 3, 4, 5}
|
||||
RINGS = [
|
||||
{8, 9},
|
||||
{8, 9, 3, 4}, # movers + centre of row of 4
|
||||
{8, 9, *ROW4},
|
||||
{8, 9, *CANS},
|
||||
]
|
||||
LEFT = LEFT_SIDE | {2, 3, 8}
|
||||
RIGHT = RIGHT_SIDE | {4, 5, 9}
|
||||
|
||||
GRID_W = 7.0
|
||||
GRID_H = 3.2
|
||||
X_ORIGIN = -3.5
|
||||
|
||||
|
||||
def m_to_grid(x_m: float, y_m: float) -> tuple[float, float]:
|
||||
gx = round(x_m - X_ORIGIN, 2)
|
||||
# Row of 4 (y=0) toward top; audience / front sides toward bottom
|
||||
gy = round(y_m, 2)
|
||||
return gx, gy
|
||||
|
||||
|
||||
COLORS = {
|
||||
"Red": (255, 0, 0),
|
||||
"Orange": (255, 127, 0),
|
||||
"Yellow": (255, 255, 0),
|
||||
"Green": (0, 255, 0),
|
||||
"Cyan": (0, 255, 255),
|
||||
"Blue": (0, 0, 255),
|
||||
"Violet": (127, 0, 255),
|
||||
"Magenta": (255, 0, 255),
|
||||
"White": (255, 255, 255),
|
||||
}
|
||||
|
||||
RAINBOW = [
|
||||
(255, 0, 0),
|
||||
(255, 127, 0),
|
||||
(255, 255, 0),
|
||||
(0, 255, 0),
|
||||
(0, 255, 255),
|
||||
(0, 0, 255),
|
||||
(127, 0, 255),
|
||||
(255, 0, 255),
|
||||
]
|
||||
|
||||
|
||||
def can_channels(r: int, g: int, b: int, *, white: int = 0, on: bool = True) -> str:
|
||||
if not on:
|
||||
return "0,0,1,0,2,0,3,0,4,0,5,0,6,0,7,0"
|
||||
if white:
|
||||
return f"1,0,2,0,3,0,4,0,5,{white},6,0,7,0"
|
||||
return f"1,0,2,{r},3,{g},4,{b},5,0,6,0,7,0"
|
||||
|
||||
|
||||
def mover_channels(r: int, g: int, b: int, *, on: bool = True, dim: int = 255) -> str:
|
||||
if not on or (r == g == b == 0):
|
||||
dim = 0
|
||||
r = g = b = 0
|
||||
parts = [
|
||||
0, 128, 2, 80, 4, 0, 5, 0, 6, 191, 7, 70, 8, dim, 9, 0,
|
||||
10, r, 11, g, 12, b, 13, 0,
|
||||
]
|
||||
for pixel in range(1, 7):
|
||||
base = 10 + pixel * 4
|
||||
parts.extend([base, 0, base + 1, 0, base + 2, 0, base + 3, 0])
|
||||
return ",".join(str(x) for x in parts)
|
||||
|
||||
|
||||
def fixture_vals(
|
||||
lit: dict[int, tuple[int, int, int] | None], *, white_ids: set[int] | None = None
|
||||
) -> str:
|
||||
white_ids = white_ids or set()
|
||||
lines = []
|
||||
for fid in list(CANS) + list(MOVERS):
|
||||
rgb = lit.get(fid)
|
||||
if rgb is None:
|
||||
ch = (
|
||||
mover_channels(0, 0, 0, on=False)
|
||||
if fid in MOVERS
|
||||
else can_channels(0, 0, 0, on=False)
|
||||
)
|
||||
lines.append(f' <FixtureVal ID="{fid}">{ch}</FixtureVal>')
|
||||
continue
|
||||
r, g, b = rgb
|
||||
if fid in MOVERS:
|
||||
ch = mover_channels(r, g, b)
|
||||
elif fid in white_ids:
|
||||
ch = can_channels(0, 0, 0, white=255)
|
||||
else:
|
||||
ch = can_channels(r, g, b)
|
||||
lines.append(f' <FixtureVal ID="{fid}">{ch}</FixtureVal>')
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def scene(
|
||||
fid: int,
|
||||
name: str,
|
||||
lit: dict,
|
||||
*,
|
||||
white_ids: set[int] | None = None,
|
||||
fade: int = 0,
|
||||
) -> str:
|
||||
return f""" <Function ID="{fid}" Type="Scene" Name="{name}">
|
||||
<Speed FadeIn="{fade}" FadeOut="0" Duration="{fade}" />
|
||||
{fixture_vals(lit, white_ids=white_ids)}
|
||||
</Function>"""
|
||||
|
||||
|
||||
def replace_function(text: str, function_id: int, new_xml: str) -> str:
|
||||
pattern = re.compile(
|
||||
rf' <Function ID="{function_id}"[\s\S]*?</Function>\n',
|
||||
re.MULTILINE,
|
||||
)
|
||||
if not pattern.search(text):
|
||||
raise SystemExit(f"Function ID {function_id} not found")
|
||||
return pattern.sub(new_xml.rstrip() + "\n", text, count=1)
|
||||
|
||||
|
||||
def all_color(rgb: tuple[int, int, int]) -> dict:
|
||||
lit = {i: rgb for i in CANS}
|
||||
lit[8] = rgb
|
||||
lit[9] = rgb
|
||||
return lit
|
||||
|
||||
|
||||
def monitor_xml() -> str:
|
||||
items = []
|
||||
for fid, (xm, ym) in LAYOUT_M.items():
|
||||
gx, gy = m_to_grid(xm, ym)
|
||||
items.append(f' <FxItem ID="{fid}" XPos="{gx}" YPos="{gy}" />')
|
||||
return f""" <Monitor DisplayMode="1" ShowLabels="1">
|
||||
<Font>Arial,12,-1,5,50,0,0,0,0,0</Font>
|
||||
<ChannelStyle>0</ChannelStyle>
|
||||
<ValueStyle>0</ValueStyle>
|
||||
<Grid Width="{GRID_W}" Height="{GRID_H}" Depth="5" Units="0" />
|
||||
{chr(10).join(items)}
|
||||
</Monitor>"""
|
||||
|
||||
|
||||
def main():
|
||||
path = Path(__file__).resolve().parents[2] / "shows" / "xchc.qxw"
|
||||
text = path.read_text()
|
||||
|
||||
for i, (name, rgb) in enumerate(COLORS.items()):
|
||||
white_ids = set(CANS) if name == "White" else None
|
||||
text = replace_function(text, i, scene(i, name, all_color(rgb), white_ids=white_ids))
|
||||
|
||||
for step in range(8):
|
||||
lit = {}
|
||||
for ci, can in enumerate(U_WALK):
|
||||
lit[can] = RAINBOW[(ci + step) % 8]
|
||||
lit[8] = RAINBOW[(3 + step) % 8]
|
||||
lit[9] = RAINBOW[(4 + step) % 8]
|
||||
text = replace_function(text, 10 + step, scene(10 + step, f"Rainbow {step + 1}", lit))
|
||||
|
||||
blue, red = (0, 0, 255), (255, 0, 0)
|
||||
odd_blue, odd_red = {}, {}
|
||||
for i in CANS:
|
||||
if i % 2 == 0:
|
||||
odd_blue[i], odd_red[i] = blue, red
|
||||
else:
|
||||
odd_blue[i], odd_red[i] = red, blue
|
||||
odd_blue[8], odd_blue[9] = blue, red
|
||||
odd_red[8], odd_red[9] = red, blue
|
||||
text = replace_function(text, 20, scene(20, "Odd Blue Even Red", odd_blue))
|
||||
text = replace_function(text, 21, scene(21, "Odd Red Even Blue", odd_red))
|
||||
|
||||
off = {i: None for i in list(CANS) + list(MOVERS)}
|
||||
text = replace_function(text, 23, scene(23, "Test Off", off))
|
||||
text = replace_function(text, 72, scene(72, "Soft Blackout", off, fade=4000))
|
||||
|
||||
for i, can in enumerate(U_WALK):
|
||||
lit = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
lit[can] = (255, 255, 255)
|
||||
text = replace_function(
|
||||
text, 33 + i, scene(33 + i, f"Scanner {i + 1}", lit, white_ids={can})
|
||||
)
|
||||
for mid, name, ids in ((99, "Scanner Movers", {8, 9}), (100, "Scanner Off", set())):
|
||||
lit = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
for m in ids:
|
||||
lit[m] = (255, 255, 255)
|
||||
block = scene(mid, name, lit)
|
||||
if f'Function ID="{mid}"' in text:
|
||||
text = replace_function(text, mid, block)
|
||||
else:
|
||||
text = text.replace(
|
||||
' <Function ID="41" Type="Chaser" Name="Scanner">',
|
||||
block + '\n <Function ID="41" Type="Chaser" Name="Scanner">',
|
||||
1,
|
||||
)
|
||||
|
||||
scanner_steps = "\n".join(
|
||||
f' <Step Number="{i}" FadeIn="0" Hold="400" FadeOut="0">{sid}</Step>'
|
||||
for i, sid in enumerate([*range(33, 41), 99, 100])
|
||||
)
|
||||
text = replace_function(
|
||||
text,
|
||||
41,
|
||||
f""" <Function ID="41" Type="Chaser" Name="Scanner">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="400" />
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>Loop</RunOrder>
|
||||
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common" />
|
||||
{scanner_steps}
|
||||
</Function>""",
|
||||
)
|
||||
|
||||
for n in range(1, 9):
|
||||
lit = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
for can in U_WALK[:n]:
|
||||
lit[can] = (255, 255, 255)
|
||||
if n >= 3:
|
||||
lit[8] = lit[9] = (255, 255, 255)
|
||||
white = {c for c in U_WALK[:n]}
|
||||
text = replace_function(
|
||||
text, 41 + n, scene(41 + n, f"Fill {n}", lit, white_ids=white)
|
||||
)
|
||||
|
||||
for i, ring in enumerate(RINGS):
|
||||
lit = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
white = {f for f in ring if f in CANS}
|
||||
for fid in ring:
|
||||
lit[fid] = (255, 255, 255)
|
||||
text = replace_function(
|
||||
text, 51 + i, scene(51 + i, f"Center {i + 1}", lit, white_ids=white)
|
||||
)
|
||||
|
||||
for i, (ids, name) in enumerate(
|
||||
[
|
||||
({0, 7}, "Pairs 1"),
|
||||
({1, 6}, "Pairs 2"),
|
||||
({2, 5}, "Pairs 3"),
|
||||
({3, 4, 8, 9}, "Pairs 4"),
|
||||
]
|
||||
):
|
||||
lit = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
white = {f for f in ids if f in CANS}
|
||||
for fid in ids:
|
||||
lit[fid] = (255, 255, 255)
|
||||
text = replace_function(text, 56 + i, scene(56 + i, name, lit, white_ids=white))
|
||||
|
||||
lbrr = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
lrbr = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
for fid in LEFT:
|
||||
lbrr[fid], lrbr[fid] = (0, 0, 255), (255, 0, 0)
|
||||
for fid in RIGHT:
|
||||
lbrr[fid], lrbr[fid] = (255, 0, 0), (0, 0, 255)
|
||||
text = replace_function(text, 61, scene(61, "Left Blue Right Red", lbrr))
|
||||
text = replace_function(text, 62, scene(62, "Left Red Right Blue", lrbr))
|
||||
|
||||
for step in range(3):
|
||||
lit = {fid: None for fid in list(CANS) + list(MOVERS)}
|
||||
white = set()
|
||||
for can in CANS:
|
||||
if can % 3 == step:
|
||||
lit[can] = (255, 255, 255)
|
||||
white.add(can)
|
||||
if step == 0:
|
||||
lit[8] = (255, 255, 255)
|
||||
elif step == 1:
|
||||
lit[9] = (255, 255, 255)
|
||||
else:
|
||||
lit[8] = lit[9] = (255, 200, 140)
|
||||
text = replace_function(
|
||||
text, 64 + step, scene(64 + step, f"Theater {step + 1}", lit, white_ids=white)
|
||||
)
|
||||
|
||||
collapse_steps = "\n".join(
|
||||
f' <Step Number="{i}" FadeIn="200" Hold="300" FadeOut="0">{sid}</Step>'
|
||||
for i, sid in enumerate([54, 53, 52, 51, 23])
|
||||
)
|
||||
text = replace_function(
|
||||
text,
|
||||
68,
|
||||
f""" <Function ID="68" Type="Chaser" Name="Collapse In">
|
||||
<Speed FadeIn="200" FadeOut="0" Duration="500" />
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>SingleShot</RunOrder>
|
||||
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common" />
|
||||
{collapse_steps}
|
||||
</Function>""",
|
||||
)
|
||||
|
||||
chase_steps = "\n".join(
|
||||
f' <Step Number="{i}" FadeIn="0" Hold="300" FadeOut="0">{sid}</Step>'
|
||||
for i, sid in enumerate([*range(33, 41), 99, 23])
|
||||
)
|
||||
text = replace_function(
|
||||
text,
|
||||
69,
|
||||
f""" <Function ID="69" Type="Chaser" Name="Chase Out">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="400" />
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>SingleShot</RunOrder>
|
||||
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common" />
|
||||
{chase_steps}
|
||||
</Function>""",
|
||||
)
|
||||
|
||||
text = replace_function(
|
||||
text, 70, scene(70, "Home Soft", all_color((255, 180, 80)), fade=2500)
|
||||
)
|
||||
|
||||
text = re.sub(
|
||||
r' <Monitor DisplayMode="1" ShowLabels="1">[\s\S]*?</Monitor>',
|
||||
lambda _m: monitor_xml(),
|
||||
text,
|
||||
count=1,
|
||||
)
|
||||
text = text.replace("<Name>BCC145 Line</Name>", "<Name>BCC145 U</Name>", 1)
|
||||
|
||||
path.write_text(text)
|
||||
print("Updated", path)
|
||||
print("Y=0 row of 4; +Y toward audience (in front of the 4)")
|
||||
for fid in sorted(LAYOUT_M):
|
||||
x, y = LAYOUT_M[fid]
|
||||
label = f"Can #{fid + 1}" if fid < 8 else f"Mover #{fid - 7}"
|
||||
print(f" {label:10} x={x:+.1f} y={y:.1f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Show in shows/test.qxw whether the pad's bank 1 is on the cans or the movers.
|
||||
|
||||
Pause on the pad latches bank 1 onto the cans or the movers, but only
|
||||
padcontroller knows which is on (padcontroller/layer.py). It now says so on
|
||||
MIDI channel 16: note 0 held down for the cans and note 1 for the movers, the
|
||||
other released. Two Flash buttons in a Pads layer frame, under the movers
|
||||
pads frame, light while their note is held, so whichever is lit is the layer
|
||||
the pads are on. Flash rather than Toggle, so each message sets the state outright and a
|
||||
missed one can't leave them the wrong way round. Each flashes an empty scene
|
||||
of its own: QLC+ lights every button whose function is flashing, so with one
|
||||
scene between them both would light.
|
||||
|
||||
python3 scripts/shows/layer_indicator.py
|
||||
|
||||
Run it once; it stops if the frame is already there. QLC+ has to reopen the
|
||||
show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import NO_FUNCTION, ROOT, button, frame
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
LAYER_NOTE_BASE = 15 * 4096 + 128 # QLC+ input channel of a channel-16 note: this plus the note
|
||||
CANS_NOTE, MOVERS_NOTE = 0, 1 # padcontroller/layer.py
|
||||
SIZE = 90
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Caption="Pads layer"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the pads layer indicator")
|
||||
fid = max(int(i) for i in re.findall(r'<Function ID="(\d+)" Type', xml)) + 1
|
||||
wid = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1]) if int(i) != NO_FUNCTION) + 1
|
||||
|
||||
layers = (("Cans pads", CANS_NOTE), ("Movers pads", MOVERS_NOTE))
|
||||
scenes = "".join(f' <Function ID="{fid + k}" Type="Scene" Name="{caption} lamp">\n'
|
||||
' <Speed FadeIn="0" FadeOut="0" Duration="0"/>\n </Function>\n'
|
||||
for k, (caption, _) in enumerate(layers))
|
||||
buttons = "".join(button(wid + 1 + k, caption, 10 + k * SIZE, 10, SIZE, fid + k, LAYER_NOTE_BASE + note, "Flash")
|
||||
for k, (caption, note) in enumerate(layers))
|
||||
widget = frame(wid, "Pads layer", 470, 700, 2 * SIZE + 20, SIZE + 20, buttons, header=False)
|
||||
|
||||
anchor = ' <Frame Caption="Movers position" ID="106">' # after the movers pads in the console
|
||||
if anchor not in xml:
|
||||
raise SystemExit("Couldn't find the Movers position frame")
|
||||
xml = xml.replace(anchor, widget + anchor, 1)
|
||||
xml = xml.replace(" </Engine>", scenes + " </Engine>", 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Added the pads layer indicator to {SHOW.relative_to(ROOT)} (widgets from ID {wid})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,330 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write a Chataigne project from a show spec.
|
||||
|
||||
python3 scripts/shows/make_chataigne.py shows/test.show.json chataigne/test
|
||||
|
||||
Writes <out>/<name>.noisette and <out>/<name>.js. The script holds the scenes and
|
||||
the pad and slider mapping, and sends DMX through the project's DMX module, named Lights, and a copy to Preview. Solo
|
||||
frames and scene fades follow what QLC+ does with the same spec.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TEMPLATE = ROOT / "chataigne" / "show.template.js"
|
||||
|
||||
|
||||
def absolute_levels(show: dict, stage: dict, values: dict[str, dict[str, int]]) -> dict[int, int]:
|
||||
"""Map a scene's fixture channels to 1-based DMX channels in the output universe."""
|
||||
levels: dict[int, int] = {}
|
||||
for key, channels in values.items():
|
||||
fixture = stage["fixtures"][key]
|
||||
for offset, level in channels.items():
|
||||
levels[int(fixture["address"]) + int(offset) + 1] = int(level)
|
||||
return levels
|
||||
|
||||
|
||||
SCALE = 1.25
|
||||
MARGIN = 10
|
||||
BUTTON = 28
|
||||
|
||||
|
||||
def clear_png() -> bytes:
|
||||
"""A 4x4 fully transparent PNG, for a trigger that should show what is behind it."""
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
body = kind + data
|
||||
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
|
||||
|
||||
rows = b"".join(b"\x00" + b"\x00" * 16 for _ in range(4))
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 6, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(rows))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def script_path(name: str) -> str:
|
||||
"""Chataigne names the script after its file and the module after its title."""
|
||||
return f"/modules/pad/scripts/{name}/params/"
|
||||
|
||||
|
||||
def ident(prefix: str, number: int, name: str) -> str:
|
||||
"""A control name Chataigne keeps as written: letters and digits, lower-case first."""
|
||||
return f"{prefix}{number}" + "".join(c for c in name if c.isalnum())
|
||||
|
||||
|
||||
def collect(show: dict, stage: dict) -> dict:
|
||||
functions = {f["key"]: f for f in show["functions"]}
|
||||
groups: dict[str, dict] = {}
|
||||
for number, frame in enumerate(show["vc"], 1):
|
||||
pads, sliders = [], []
|
||||
for widget in frame.get("children", []):
|
||||
kind = widget["type"]
|
||||
binding = widget.get("input") or {}
|
||||
if "function" in widget:
|
||||
function = functions[widget["function"]]
|
||||
values = function["values"]
|
||||
else: # a Level slider: its channels at full, scaled by the slider
|
||||
values = {fixture: {channel: 255} for fixture, channel in widget.get("channels", [])}
|
||||
levels = absolute_levels(show, stage, values)
|
||||
if kind == "button" and "note" in binding:
|
||||
pads.append({
|
||||
"id": ident("c", number, widget["caption"]),
|
||||
"box": box(frame, widget),
|
||||
"bg": widget.get("bg", [60, 60, 60]),
|
||||
"fg": widget.get("fg", [255, 255, 255]),
|
||||
"note": binding["note"][1],
|
||||
"name": widget["caption"],
|
||||
"fade": [function.get("fade_in") or 0, function.get("fade_out") or 0],
|
||||
"levels": levels,
|
||||
})
|
||||
elif kind == "slider":
|
||||
sliders.append({
|
||||
"id": ident("s", number, widget["caption"]),
|
||||
"box": box(frame, widget),
|
||||
"fg": widget.get("fg", [255, 255, 255]),
|
||||
"cc": binding["cc"][1] if "cc" in binding else -1, # -1: dashboard only
|
||||
"value": round(int(widget.get("value", 0)) / 255, 3),
|
||||
"name": widget["caption"],
|
||||
"levels": levels,
|
||||
})
|
||||
if pads or sliders:
|
||||
groups[frame["caption"]] = {
|
||||
"name": frame["caption"],
|
||||
"now": f"now{number}",
|
||||
"box": box(frame, {"x": 0, "y": -30, "w": frame["w"], "h": 26}),
|
||||
"pads": pads,
|
||||
"sliders": sliders,
|
||||
}
|
||||
return groups
|
||||
|
||||
|
||||
def box(frame: dict, widget: dict) -> list[int]:
|
||||
"""x, y, w, h of a widget on the dashboard. Frames sit side by side, as on the virtual console."""
|
||||
return [round((frame["x"] + widget["x"]) * SCALE), round((frame["y"] + widget["y"]) * SCALE + 40),
|
||||
round(widget["w"] * SCALE), round(widget["h"] * SCALE)]
|
||||
|
||||
|
||||
def colour(rgb: list[int]) -> int:
|
||||
"""A Chataigne colour value: ARGB as a signed 32-bit int."""
|
||||
argb = (255 << 24) | (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]
|
||||
return argb - (1 << 32) if argb >= 1 << 31 else argb
|
||||
|
||||
|
||||
def js_levels(levels: dict[int, int]) -> str:
|
||||
return "[" + ",".join(f"{ch},{level}" for ch, level in sorted(levels.items())) + "]"
|
||||
|
||||
|
||||
def render_data(groups: dict) -> str:
|
||||
lines = ["var GROUPS = ["]
|
||||
for caption, group in groups.items():
|
||||
lines.append(" {")
|
||||
lines.append(f" name: {json.dumps(caption)},")
|
||||
lines.append(f" now: {json.dumps(group['now'])},")
|
||||
lines.append(" pads: [")
|
||||
for pad in group["pads"]:
|
||||
lines.append(
|
||||
f" {{id: {json.dumps(pad['id'])}, rgb: {json.dumps([round(c / 255, 3) for c in pad['bg']])}, note: {pad['note']}, name: {json.dumps(pad['name'])}, "
|
||||
f"fadeIn: {pad['fade'][0]}, fadeOut: {pad['fade'][1]}, levels: {js_levels(pad['levels'])}}},"
|
||||
)
|
||||
lines.append(" ],")
|
||||
lines.append(" sliders: [")
|
||||
for slider in group["sliders"]:
|
||||
lines.append(
|
||||
f" {{id: {json.dumps(slider['id'])}, cc: {slider['cc']}, name: {json.dumps(slider['name'])}, value: {slider['value']}, levels: {js_levels(slider['levels'])}}},"
|
||||
)
|
||||
lines.append(" ]")
|
||||
lines.append(" },")
|
||||
lines.append("];")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def dashboard_item(index: int, kind: str, target: str, box: list[int], label: str, colours: dict[str, list[int]]) -> dict:
|
||||
parameters = [
|
||||
{"value": [float(box[0]), float(box[1])], "controlAddress": "/viewUIPosition"},
|
||||
{"value": [float(box[2]), float(box[3])], "controlAddress": "/viewUISize"},
|
||||
{"value": target, "controlAddress": "/target"},
|
||||
{"value": label, "controlAddress": "/customText", "enabled": True},
|
||||
]
|
||||
for address, rgb in colours.items():
|
||||
parameters.append({"value": colour(rgb), "controlAddress": address, "enabled": True})
|
||||
return {
|
||||
"parameters": parameters,
|
||||
"niceName": f"Item {index}",
|
||||
"type": kind,
|
||||
"ghostAddress": target,
|
||||
"controllable": target,
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def dashboard(groups: dict, name: str, view: tuple[int, int], overlay: str | None) -> dict:
|
||||
"""A dashboard with a tile and button per pad, a slider per knob, and what each group is showing."""
|
||||
items = []
|
||||
for group in groups.values():
|
||||
items.append(dashboard_item(
|
||||
len(items) + 1, "DashboardParameterItem", script_path(name) + group["now"],
|
||||
group["box"], group["name"], {},
|
||||
))
|
||||
for pad in group["pads"]:
|
||||
x, y, w, h = pad["box"]
|
||||
# Triggers draw grey whatever colour they are given, but a colour control always paints.
|
||||
# The tile carries the colour and name; the trigger on it is a transparent image that takes the press.
|
||||
small = overlay is None
|
||||
tile = dashboard_item(
|
||||
len(items) + 1, "DashboardParameterItem", script_path(name) + pad["id"] + "Lamp",
|
||||
[x, y, w, h - BUTTON - 2 if small else h], pad["name"], {"/textColor": [255, 255, 255]},
|
||||
)
|
||||
tile["parameters"] += [
|
||||
{"value": True, "controlAddress": "/readOnly"},
|
||||
{"value": False, "controlAddress": "/showValue"},
|
||||
]
|
||||
items.append(tile)
|
||||
press = dashboard_item(
|
||||
len(items) + 1, "DashboardTriggerItem", script_path(name) + pad["id"],
|
||||
[x, y + h - BUTTON, w, BUTTON] if small else [x, y, w, h], "Select" if small else "",
|
||||
{"/backgroundColor": pad["bg"], "/textColor": pad["fg"]},
|
||||
)
|
||||
if overlay:
|
||||
# A custom label that is a single space: with none, the trigger draws its own name.
|
||||
press["parameters"][3].update({"value": " ", "enabled": True})
|
||||
press["parameters"].append({"value": False, "controlAddress": "/showLabel"})
|
||||
press["parameters"].append({"value": overlay, "controlAddress": "/customImage", "enabled": True})
|
||||
items.append(press)
|
||||
for slider in group["sliders"]:
|
||||
items.append(dashboard_item(
|
||||
len(items) + 1, "DashboardParameterItem", script_path(name) + slider["id"], slider["box"], slider["name"],
|
||||
{"/foregroundColor": slider["fg"]},
|
||||
))
|
||||
# Dashboard coordinates start at the middle of the view, so move the board to its top left.
|
||||
left = min(i["parameters"][0]["value"][0] for i in items)
|
||||
top = min(i["parameters"][0]["value"][1] for i in items)
|
||||
for i in items:
|
||||
position = i["parameters"][0]["value"]
|
||||
position[0] += MARGIN - view[0] / 2 - left
|
||||
position[1] += MARGIN - view[1] / 2 - top
|
||||
return {
|
||||
"parameters": [{"value": False, "controlAddress": "/editMode"}],
|
||||
"items": [
|
||||
{
|
||||
"niceName": "Board",
|
||||
"type": "BaseItem",
|
||||
"itemManager": {
|
||||
# The web page puts the middle of the canvas at 0, 0, so the canvas has to be the view's size
|
||||
# for the board to start at its top left.
|
||||
"parameters": [{"value": [float(view[0]), float(view[1])], "controlAddress": "/canvasSize", "enabled": True}],
|
||||
"items": items,
|
||||
"viewOffset": [0, 0],
|
||||
"viewZoom": 1.0,
|
||||
},
|
||||
}
|
||||
],
|
||||
"viewOffset": [0, 0],
|
||||
"viewZoom": 1.0,
|
||||
}
|
||||
|
||||
|
||||
|
||||
def dmx_module(name: str, host: str, universe: int, interface: str | None) -> dict:
|
||||
device: dict = {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}}
|
||||
if interface:
|
||||
device["parameters"] = [{"value": interface, "controlAddress": "/networkInterface"}]
|
||||
return {
|
||||
"niceName": name,
|
||||
"type": "DMX",
|
||||
"params": {
|
||||
"parameters": [
|
||||
{"value": "Art-Net", "controlAddress": "/dmxType"},
|
||||
{"value": 40, "controlAddress": "/sendRate"},
|
||||
],
|
||||
"containers": {
|
||||
"artNet": {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}},
|
||||
"outputUniverses": {
|
||||
"items": [
|
||||
{
|
||||
"niceName": "Universe",
|
||||
"parameters": [
|
||||
{"value": 0, "controlAddress": "/net"},
|
||||
{"value": 0, "controlAddress": "/subnet"},
|
||||
{"value": universe, "controlAddress": "/universe"},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
},
|
||||
"device": device,
|
||||
}
|
||||
|
||||
|
||||
def project(
|
||||
script: str, host: str, universe: int, interface: str, groups: dict, preview: str | None, pad: str, view: tuple[int, int], overlay: str | None
|
||||
) -> dict:
|
||||
"""A Chataigne project: a DMX module on Art-Net and a MIDI module that runs the show script."""
|
||||
dmx = [dmx_module("Lights", host, universe, interface)]
|
||||
if preview:
|
||||
dmx.append(dmx_module("Preview", preview, universe, None))
|
||||
midi = {
|
||||
"niceName": "Pad",
|
||||
"type": "MIDI",
|
||||
"params": {"parameters": [{"value": [pad, ""], "inputName": pad, "controlAddress": "/devices"}]},
|
||||
"scripts": {
|
||||
"items": [{"niceName": "Show", "parameters": [{"value": script, "controlAddress": "/filePath"}]}]
|
||||
},
|
||||
}
|
||||
return {
|
||||
"metaData": {"version": "1.10.4"},
|
||||
"projectSettings": {
|
||||
"containers": {
|
||||
"dashboardSettings": {
|
||||
"parameters": [
|
||||
{"value": True, "controlAddress": "/enableDashboardServer"},
|
||||
{"value": 9999, "hexMode": False, "controlAddress": "/serverPort"},
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"dashboardManager": dashboard(groups, Path(script).stem, view, overlay),
|
||||
"modules": {"viewOffset": [0, 0], "viewZoom": 1.0, "items": [*dmx, midi]},
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("show", type=Path)
|
||||
parser.add_argument("out", type=Path, help="directory to write into")
|
||||
parser.add_argument("--host", help="Art-Net destination (default: from the show's output universe)")
|
||||
parser.add_argument("--pad", default="SINCO SMC-PAD-Master", help="MIDI input the pad arrives on (Bluetooth: SMC-PAD Bluetooth)")
|
||||
parser.add_argument("--view", default="1574x953", help="dashboard panel size in pixels, for the top-left placement")
|
||||
parser.add_argument("--small-buttons", action="store_true", help="a grey Select button under each tile, instead of the whole tile pressing")
|
||||
parser.add_argument("--preview", default="127.0.0.1", help="second Art-Net destination for the simulator; empty for none")
|
||||
args = parser.parse_args()
|
||||
|
||||
show = json.loads(args.show.read_text())
|
||||
stage = json.loads((ROOT / show["stage"]).read_text())
|
||||
output = next(u["output"] for u in show["universes"] if u.get("output", {}).get("plugin") == "ArtNet")
|
||||
name = args.show.name.removesuffix(".show.json")
|
||||
|
||||
groups = collect(show, stage)
|
||||
source = TEMPLATE.read_text().replace("/*__DATA__*/", render_data(groups))
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
(args.out / f"{name}.js").write_text(source)
|
||||
overlay = None if args.small_buttons else str((args.out / "clear.png").resolve())
|
||||
if overlay:
|
||||
(args.out / "clear.png").write_bytes(clear_png())
|
||||
doc = project(f"{name}.js", args.host or output["ip"], int(output["universe"]), output["uid"], groups, args.preview or None, args.pad, tuple(int(n) for n in args.view.split("x")), overlay)
|
||||
(args.out / f"{name}.noisette").write_text(json.dumps(doc, indent=2) + "\n")
|
||||
print(f"{args.out / (name + '.noisette')}: {len(groups)} groups, {sum(len(g['pads']) for g in groups.values())} pads")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Copy shows/test.qxw to shows/gig.qxw, sending Art-Net to the rig.
|
||||
|
||||
The test show sends Art-Net to 127.0.0.1 only, so it drives the simulator and
|
||||
never the rig (see CLAUDE.md). The gig show is the same show sending from the
|
||||
laptop's address on the gig network to the Art-Net node, as cabaret.qxw does.
|
||||
Everything else, from the pads to the console, is the test show's, so run this
|
||||
again after changing the test show.
|
||||
|
||||
python3 scripts/shows/make_gig.py
|
||||
python3 scripts/shows/draw_test_pads.py gig # its pad layout picture
|
||||
|
||||
Don't open gig.qxw on a network where 192.168.1.175 is the real node unless
|
||||
the rig should light up.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from mover_bank import ROOT
|
||||
|
||||
TEST = ROOT / "shows" / "test.qxw"
|
||||
GIG = ROOT / "shows" / "gig.qxw"
|
||||
LAPTOP = "192.168.1.143" # the laptop's address on the gig network, as in cabaret.qxw
|
||||
LINE = 1 # QLC+'s Art-Net line for it there
|
||||
NODE = "192.168.1.175"
|
||||
|
||||
TEST_OUTPUT = ' <Output Plugin="ArtNet" UID="127.0.0.1" Line="4"/>\n'
|
||||
GIG_OUTPUT = (f' <Output Plugin="ArtNet" UID="{LAPTOP}" Line="{LINE}">\n'
|
||||
f' <PluginParameters outputIP="{NODE}" outputUni="0"/>\n'
|
||||
' </Output>\n')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = TEST.read_text()
|
||||
if xml.count(TEST_OUTPUT) != 1:
|
||||
raise SystemExit(f"{TEST.relative_to(ROOT)} doesn't have its one Art-Net output to 127.0.0.1")
|
||||
GIG.write_text(xml.replace(TEST_OUTPUT, GIG_OUTPUT, 1))
|
||||
print(f"Copied {TEST.relative_to(ROOT)} to {GIG.relative_to(ROOT)}, sending Art-Net to {NODE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile shows/simple.show.json into shows/simple.qxw."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from showfile.tools import write_show
|
||||
|
||||
|
||||
def main() -> None:
|
||||
spec = json.loads((ROOT / "shows" / "simple.show.json").read_text(encoding="utf-8"))
|
||||
result = write_show(spec, "shows/simple.qxw", root=ROOT)
|
||||
if not result["ok"]:
|
||||
raise SystemExit(json.dumps(result, indent=2))
|
||||
print(f"Wrote {result['path']} ({len(result['widgets'])} widgets)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Drop the movers' Strobe from shows/test.qxw and add the rest of QLC+'s EFX shapes.
|
||||
|
||||
The movers layer has no Strobe any more (pad 9, note 92): its button, its scene
|
||||
and the HTP strobe channel that let it beat the colour scenes all go. Its pad and
|
||||
the rest of the second row, and pad 5, take the five EFX shapes the movers did
|
||||
not have yet. They join Wander, Ballyhoo, Circle and Sweep in the Movement solo
|
||||
frame, now three rows deep, so still only one runs at a time:
|
||||
|
||||
92 Diamond pad 9 a diamond, about ±64° of pan and ±21° of tilt
|
||||
93 Square pad 10 a square, about ±53° of pan and ±16° of tilt
|
||||
94 Corners pad 11 SquareChoppy: jumps corner to corner of the same square
|
||||
95 Leaf pad 12 a four-petal leaf, about ±53° of pan and ±26° of tilt
|
||||
88 Tilt pad 5 Line2 on tilt alone, about ±26° up and down
|
||||
|
||||
Like the others each is a relative EFX around the Pan and Tilt knobs, with all
|
||||
four movers together so the pairs mirror, fading in over 0.5 s. Knob 13's speed
|
||||
dial gives Corners an eighth of its time (2.5 s a round to start with) and the
|
||||
rest a quarter (5.5 s). padcontroller/layer.py settles the knobs after all nine.
|
||||
|
||||
python3 scripts/shows/mover_all_efx.py
|
||||
|
||||
Run it once on a show with Circle and Sweep and the movers' Strobe; it stops if
|
||||
Diamond is already there. QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import M1, M2, M3, M4, NO_FUNCTION, ROOT, STROBE, button, note
|
||||
from mover_more_efx import SIZE, START_MS, efx
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
# Speed dial factor indexes: (Not Sent), 0, 1/16, 1/8, 1/4, ...
|
||||
TIMES_1_8, TIMES_1_4 = 3, 4
|
||||
|
||||
# Caption, function name, algorithm, width, height (of 255 each way), can note, column, row, dial factor
|
||||
MOVES = (
|
||||
("Diamond", "Movers diamond", "Diamond", 30, 20, 44, 0, 1, TIMES_1_4),
|
||||
("Square", "Movers square", "Square", 25, 15, 45, 1, 1, TIMES_1_4),
|
||||
("Corners", "Movers corners", "SquareChoppy", 25, 15, 46, 2, 1, TIMES_1_8),
|
||||
("Leaf", "Movers leaf", "Leaf", 25, 25, 47, 3, 1, TIMES_1_4),
|
||||
("Tilt", "Movers tilt", "Line2", 0, 25, 40, 0, 2, TIMES_1_4),
|
||||
)
|
||||
ROWS = 3
|
||||
|
||||
|
||||
def cut(xml: str, pattern: str) -> str:
|
||||
xml, n = re.subn(pattern, "", xml, count=1, flags=re.S)
|
||||
assert n == 1, pattern
|
||||
return xml
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Name="Movers diamond"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the movers diamond")
|
||||
|
||||
strobe = int(re.search(r'<Function ID="(\d+)" Type="Scene" Name="Movers strobe">', xml).group(1))
|
||||
xml = cut(xml, rf' <Function ID="{strobe}" Type="Scene" Name="Movers strobe">\n.*? </Function>\n')
|
||||
# The cans' Strobe has the same caption; the movers' one is widget 89 (scripts/shows/mover_bank.py).
|
||||
xml = cut(xml, r' <Button Caption="Strobe" ID="89" Icon="">\n.*? </Button>\n')
|
||||
for fid in (M1, M2, M3, M4):
|
||||
xml, n = re.subn(rf'( <ID>{fid}</ID>\n(?: .*\n)*?) <ForcedHTP>{STROBE}</ForcedHTP>\n', r"\1", xml, count=1)
|
||||
assert n == 1, fid
|
||||
|
||||
engine, console = xml.split("<VirtualConsole>")
|
||||
fid = max(int(i) for i in re.findall(r'<Function ID="(\d+)" Type', engine)) + 1
|
||||
wid = max(int(i) for i in re.findall(r' ID="(\d+)"', console) if int(i) != NO_FUNCTION) + 1
|
||||
|
||||
solo = re.search(r' <SoloFrame Caption="Movement" ID="\d+">\n.*? </SoloFrame>\n', xml, re.S).group(0)
|
||||
dial = re.search(r' <SpeedDial Caption="Movers speed" ID="\d+">\n.*? </SpeedDial>\n', xml, re.S).group(0)
|
||||
functions, buttons, rows = "", "", ""
|
||||
for i, (caption, name, algorithm, width, height, can_note, column, row, factor) in enumerate(MOVES):
|
||||
start_ms = START_MS // 2 if factor == TIMES_1_8 else START_MS
|
||||
functions += efx(fid + i, name, algorithm, width, height, start_ms)
|
||||
buttons += button(wid + i, caption, SIZE * column, SIZE * row, SIZE, fid + i, note(can_note), indent=" ")
|
||||
rows += f' <Function FadeIn="0" FadeOut="0" Duration="{factor}">{fid + i}</Function>\n'
|
||||
|
||||
grown = re.sub(r'(<WindowState Visible="True" X="10" Y="10" Width="\d+" Height=")\d+"', rf'\g<1>{SIZE * ROWS}"',
|
||||
solo, count=1)
|
||||
grown = grown.replace(" </SoloFrame>\n", buttons + " </SoloFrame>\n")
|
||||
xml = xml.replace(solo, grown, 1)
|
||||
xml = xml.replace(dial, dial.replace(" </SpeedDial>\n", rows + " </SpeedDial>\n"), 1)
|
||||
xml = xml.replace(" </Engine>", functions + " </Engine>", 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Dropped the movers' Strobe and added {len(MOVES)} shapes to {SHOW.relative_to(ROOT)} "
|
||||
f"(functions {fid}–{fid + len(MOVES) - 1}, widgets {wid}–{wid + len(MOVES) - 1})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add a Ballyhoo pad for the movers to shows/test.qxw, on note 94.
|
||||
|
||||
On the movers layer (Pause on), pad 11 toggles a fast, wide figure of eight
|
||||
around wherever the Pan and Tilt knobs (9 and 10, CC 38 and 39) put the movers,
|
||||
as Wander does:
|
||||
|
||||
94 Ballyhoo an Eight about ±85° of pan and ±26° of tilt, 2.5 s round
|
||||
|
||||
All four start together. M1 and M4 turn the other way to M2 and M3, so the
|
||||
same move mirrors left to right and front to back, and the beams sweep out
|
||||
and cross in the middle together. It fades in over 0.5 s, which QLC+ counts inside each 3 s round. When it goes off,
|
||||
the pad controller nudges the two knobs so QLC+ drops its last offset
|
||||
(padcontroller/layer.py).
|
||||
|
||||
python3 scripts/shows/mover_ballyhoo.py
|
||||
|
||||
Run it once on a show with Wander and without Ballyhoo; it stops if Ballyhoo
|
||||
is already there. QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import LEFT_TO_RIGHT, NO_FUNCTION, ROOT, button, note
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
WIDTH, HEIGHT = 40, 24 # of 255 each way: 540° of pan, 270° of tilt
|
||||
ROUND_MS = 3000
|
||||
FADE_IN_MS = 500
|
||||
|
||||
|
||||
def efx(fid: int) -> str:
|
||||
fixtures = "".join(f""" <Fixture>
|
||||
<ID>{f}</ID>
|
||||
<Head>0</Head>
|
||||
<Mode>0</Mode>
|
||||
<Direction>Forward</Direction>
|
||||
<StartOffset>0</StartOffset>
|
||||
</Fixture>
|
||||
""" for f in LEFT_TO_RIGHT)
|
||||
# Relative: the EFX adds its offset from 127 to the Pan and Tilt sliders' levels.
|
||||
return f""" <Function ID="{fid}" Type="EFX" Name="Movers ballyhoo">
|
||||
{fixtures} <PropagationMode>Parallel</PropagationMode>
|
||||
<Speed FadeIn="{FADE_IN_MS}" FadeOut="0" Duration="{ROUND_MS}"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>Loop</RunOrder>
|
||||
<Algorithm>Eight</Algorithm>
|
||||
<Width>{WIDTH}</Width>
|
||||
<Height>{HEIGHT}</Height>
|
||||
<Rotation>0</Rotation>
|
||||
<StartOffset>0</StartOffset>
|
||||
<IsRelative>1</IsRelative>
|
||||
<Axis Name="X">
|
||||
<Offset>127</Offset>
|
||||
<Frequency>1</Frequency>
|
||||
<Phase>0</Phase>
|
||||
</Axis>
|
||||
<Axis Name="Y">
|
||||
<Offset>127</Offset>
|
||||
<Frequency>1</Frequency>
|
||||
<Phase>0</Phase>
|
||||
</Axis>
|
||||
</Function>
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Name="Movers ballyhoo"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the movers ballyhoo")
|
||||
engine, console = xml.split("<VirtualConsole>")
|
||||
fid = max(int(i) for i in re.findall(r'<Function ID="(\d+)" Type', engine)) + 1
|
||||
wid = max(int(i) for i in re.findall(r' ID="(\d+)"', console) if int(i) != NO_FUNCTION) + 1
|
||||
|
||||
xml = xml.replace(" </Engine>", efx(fid) + " </Engine>", 1)
|
||||
# Beside Wander, on the pad after it.
|
||||
wander = re.search(r' <Button Caption="Wander" ID="\d+" Icon="">\n.*? </Button>\n', xml, re.S).group(0)
|
||||
xml = xml.replace(wander, wander + button(wid, "Ballyhoo", 190, 100, 90, fid, note(46)), 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Added the movers ballyhoo to {SHOW.relative_to(ROOT)} (function {fid}, widget {wid})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add mover versions of the bank 1 pads to shows/test.qxw, on notes 84–99.
|
||||
|
||||
Pause on the pad toggles bank 1 between the cans and the movers: padcontroller
|
||||
sends bank 1 (notes 36–51) as 84–99 while it is on (padcontroller/layer.py).
|
||||
Each mover pad sits on its can pad's note plus 48:
|
||||
|
||||
92 Strobe flash the movers' centre strobe
|
||||
96 Chase a stripe through the 7 rings of all four movers
|
||||
97 Reverse the same, the other way
|
||||
98 Zigzag mover by mover, M3, M1, M2, M4 (back, front, front, back)
|
||||
99 Opposing rings outwards on the left movers, inwards on the right
|
||||
|
||||
The chases take their colour from the Colour 1 (cans) pads, as the cans'
|
||||
chases take theirs from Colour 2, so they stand out. Knob 15 (CC 44), the
|
||||
movers' level, is also their peak. The movers are not sound reactive: Sound and
|
||||
Threshold (84 and 85) do nothing on their layer.
|
||||
|
||||
python3 scripts/shows/mover_bank.py
|
||||
|
||||
Run it once on a show without them; it stops if they are already there.
|
||||
QLC+ has to reopen the show to see them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
MOVERS_SHIFT = 48 # padcontroller/layer.py
|
||||
NOTE_BASE = 36992 # QLC+ input channel of a channel-10 note: this plus the note
|
||||
LEVEL_CC = 44 # knob 15: the Movers level slider, and the movers' peak here
|
||||
|
||||
# Fixture IDs left to right on stage: M3 back left, M1 and M2 front, M4 back right.
|
||||
M1, M2, M3, M4 = 8, 9, 17, 18
|
||||
LEFT_TO_RIGHT = (M3, M1, M2, M4)
|
||||
RINGS = 7
|
||||
BRIGHTNESS, STROBE = 8, 9
|
||||
|
||||
GROUP_RINGS, GROUP_ZIGZAG, GROUP_OPPOSING = 5, 6, 7
|
||||
F_DIMMER, F_FWD, F_HOLD, F_REV, F_ZIG, F_ZIG_HOLD, F_OPP, F_STROBE = range(57, 65)
|
||||
NO_FUNCTION = 4294967295
|
||||
|
||||
|
||||
def note(can_note: int) -> int:
|
||||
return NOTE_BASE + can_note + MOVERS_SHIFT
|
||||
|
||||
|
||||
def group(gid: int, name: str, w: int, h: int, heads: list[tuple[int, int, int, int]]) -> str:
|
||||
rows = "\n".join(f' <Head X="{x}" Y="{y}" Fixture="{f}">{head}</Head>' for x, y, f, head in heads)
|
||||
return f' <FixtureGroup ID="{gid}">\n <Name>{name}</Name>\n <Size X="{w}" Y="{h}"/>\n{rows}\n </FixtureGroup>\n'
|
||||
|
||||
|
||||
def groups() -> str:
|
||||
# Rings down Y, one mover per column.
|
||||
rings = [(x, r, f, r) for x, f in enumerate(LEFT_TO_RIGHT) for r in range(RINGS)]
|
||||
# One mover per row, its rings across.
|
||||
zigzag = [(r, y, f, r) for y, f in enumerate(LEFT_TO_RIGHT) for r in range(RINGS)]
|
||||
# Left movers' rings run outwards as the right movers' run inwards.
|
||||
opposing = [(x, y, f, y if x < 2 else RINGS - 1 - y) for x, f in enumerate(LEFT_TO_RIGHT) for y in range(RINGS)]
|
||||
return (group(GROUP_RINGS, "Movers rings", 4, RINGS, rings)
|
||||
+ group(GROUP_ZIGZAG, "Movers zigzag", RINGS, 4, zigzag)
|
||||
+ group(GROUP_OPPOSING, "Movers opposing", 4, RINGS, opposing))
|
||||
|
||||
|
||||
def scene(fid: int, name: str, values: dict[int, int], fade_out: int = 0) -> str:
|
||||
vals = ",".join(f"{c},{v}" for c, v in values.items())
|
||||
rows = "\n".join(f' <FixtureVal ID="{f}">{vals}</FixtureVal>' for f in LEFT_TO_RIGHT)
|
||||
return (f' <Function ID="{fid}" Type="Scene" Name="{name}">\n'
|
||||
f' <Speed FadeIn="0" FadeOut="{fade_out}" Duration="0"/>\n{rows}\n </Function>\n')
|
||||
|
||||
|
||||
def matrix(fid: int, name: str, gid: int, direction: str, step_ms: int) -> str:
|
||||
return f""" <Function ID="{fid}" Type="RGBMatrix" Name="{name}">
|
||||
<Speed FadeIn="0" FadeOut="500" Duration="{step_ms}"/>
|
||||
<Direction>{direction}</Direction>
|
||||
<RunOrder>SingleShot</RunOrder>
|
||||
<Algorithm Type="Script">Stripes</Algorithm>
|
||||
<MonoColor>4294967040</MonoColor>
|
||||
<ControlMode>RGB</ControlMode>
|
||||
<FixtureGroup>{gid}</FixtureGroup>
|
||||
<Property Name="orientation" Value="Vertical"/>
|
||||
</Function>
|
||||
"""
|
||||
|
||||
|
||||
def chaser(fid: int, name: str, ms: int, step: int) -> str:
|
||||
return f""" <Function ID="{fid}" Type="Chaser" Name="{name}">
|
||||
<Speed FadeIn="0" FadeOut="0" Duration="{ms}"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>SingleShot</RunOrder>
|
||||
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common"/>
|
||||
<Step Number="0" FadeIn="0" Hold="0" FadeOut="0">{step}</Step>
|
||||
</Function>
|
||||
"""
|
||||
|
||||
|
||||
def functions() -> str:
|
||||
# Each hold keeps the movers up while its run steps through, plus the run's fade.
|
||||
return (scene(F_DIMMER, "Movers dimmer", {BRIGHTNESS: 255, STROBE: 0})
|
||||
+ matrix(F_FWD, "Movers chase forward run", GROUP_RINGS, "Forward", 200)
|
||||
+ chaser(F_HOLD, "Movers dimmer hold", RINGS * 200 + 500, F_DIMMER)
|
||||
+ matrix(F_REV, "Movers chase reverse run", GROUP_RINGS, "Backward", 200)
|
||||
+ matrix(F_ZIG, "Movers zigzag run", GROUP_ZIGZAG, "Forward", 200)
|
||||
+ chaser(F_ZIG_HOLD, "Movers zigzag hold", 4 * 200 + 500, F_DIMMER)
|
||||
+ matrix(F_OPP, "Movers opposing run", GROUP_OPPOSING, "Forward", 200)
|
||||
+ scene(F_STROBE, "Movers strobe", {BRIGHTNESS: 255, STROBE: 230}, fade_out=50))
|
||||
|
||||
|
||||
def appearance(indent: str, style: str = "None") -> str:
|
||||
return (f"{indent}<Appearance>\n{indent} <FrameStyle>{style}</FrameStyle>\n"
|
||||
f"{indent} <ForegroundColor>Default</ForegroundColor>\n{indent} <BackgroundColor>Default</BackgroundColor>\n"
|
||||
f"{indent} <BackgroundImage>None</BackgroundImage>\n{indent} <Font>Default</Font>\n{indent}</Appearance>\n")
|
||||
|
||||
|
||||
def button(wid: int, caption: str, x: int, y: int, size: int, function: int, channel: int | None,
|
||||
action: str = "Toggle", indent: str = " ") -> str:
|
||||
inp = f'{indent} <Input Universe="1" Channel="{channel}"/>\n' if channel is not None else ""
|
||||
return (f'{indent}<Button Caption="{caption}" ID="{wid}" Icon="">\n'
|
||||
f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{size}" Height="{size}"/>\n'
|
||||
+ appearance(indent + " ")
|
||||
+ f'{indent} <Function ID="{function}"/>\n{indent} <Action>{action}</Action>\n'
|
||||
f'{indent} <Intensity Adjust="False">100</Intensity>\n{inp}{indent}</Button>\n')
|
||||
|
||||
|
||||
def submaster(wid: int, caption: str, x: int, y: int, h: int, cc: int, indent: str) -> str:
|
||||
return (f'{indent}<Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">\n'
|
||||
f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="52" Height="{h}"/>\n'
|
||||
+ appearance(indent + " ", "Sunken")
|
||||
+ f'{indent} <Input Universe="1" Channel="{cc}"/>\n'
|
||||
f'{indent} <SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None">Submaster</SliderMode>\n'
|
||||
f'{indent} <Level LowLimit="0" HighLimit="255" Value="255"/>\n'
|
||||
f'{indent} <Playback>\n{indent} <Function>{NO_FUNCTION}</Function>\n{indent} </Playback>\n{indent}</Slider>\n')
|
||||
|
||||
|
||||
def frame(wid: int, caption: str, x: int, y: int, w: int, h: int, body: str, indent: str = " ",
|
||||
header: bool = True, collapsed: bool = False) -> str:
|
||||
return (f'{indent}<Frame Caption="{caption}" ID="{wid}">\n'
|
||||
+ appearance(indent + " ", "Sunken")
|
||||
+ f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>\n'
|
||||
f'{indent} <AllowChildren>True</AllowChildren>\n{indent} <AllowResize>True</AllowResize>\n'
|
||||
f'{indent} <ShowHeader>{header}</ShowHeader>\n{indent} <ShowEnableButton>False</ShowEnableButton>\n'
|
||||
f'{indent} <Collapsed>{collapsed}</Collapsed>\n{indent} <Disabled>False</Disabled>\n'
|
||||
f'{body}{indent}</Frame>\n')
|
||||
|
||||
|
||||
def vc(xml: str, next_id: int) -> str:
|
||||
"""The new widgets."""
|
||||
ids = iter(range(next_id, next_id + 100))
|
||||
w = {name: next(ids) for name in (
|
||||
"bank", "fwd", "rev", "zig", "opp", "strobe", "peak",
|
||||
"runs", "fwd_run", "rev_run", "zig_run", "opp_run",
|
||||
"colours", "fwd_col", "rev_col", "zig_col", "opp_col")}
|
||||
|
||||
bank = (button(w["fwd"], "Chase", 10, 10, 90, F_HOLD, note(48))
|
||||
+ button(w["rev"], "Chase reverse", 100, 10, 90, F_HOLD, note(49))
|
||||
+ button(w["zig"], "Zigzag", 190, 10, 90, F_ZIG_HOLD, note(50))
|
||||
+ button(w["opp"], "Opposing", 280, 10, 90, F_HOLD, note(51))
|
||||
+ button(w["strobe"], "Strobe", 10, 100, 90, F_STROBE, note(44), action="Flash")
|
||||
+ submaster(w["peak"], "Peak", 378, 10, 360, LEVEL_CC, " "))
|
||||
runs = (button(w["fwd_run"], "Chase run", 10, 10, 70, F_FWD, note(48))
|
||||
+ button(w["rev_run"], "Reverse run", 80, 10, 70, F_REV, note(49))
|
||||
+ button(w["zig_run"], "Zigzag run", 150, 10, 70, F_ZIG, note(50))
|
||||
+ button(w["opp_run"], "Opposing run", 220, 10, 70, F_OPP, note(51)))
|
||||
|
||||
# The cans' Forward colour matrix follows the Colour 2 pads; these follow Colour 1, 16 notes lower.
|
||||
template = re.search(r' <Matrix Caption="Forward colour" ID="61">.*? </Matrix>\n', xml, re.S).group(0)
|
||||
|
||||
def colour_matrix(wid: int, caption: str, fid: int, x: int, y: int) -> str:
|
||||
m = template.replace('Caption="Forward colour" ID="61"', f'Caption="{caption}" ID="{wid}"')
|
||||
m = m.replace('<Function ID="43" InstantApply', f'<Function ID="{fid}" InstantApply')
|
||||
m = re.sub(r'X="\d+" Y="\d+" Width', f'X="{x}" Y="{y}" Width', m, count=1)
|
||||
return re.sub(r'Channel="(\d+)"', lambda c: f'Channel="{int(c.group(1)) - 16}"', m)
|
||||
|
||||
colours = (colour_matrix(w["fwd_col"], "Movers chase colour", F_FWD, 10, 45)
|
||||
+ colour_matrix(w["rev_col"], "Movers reverse colour", F_REV, 320, 45)
|
||||
+ colour_matrix(w["zig_col"], "Movers zigzag colour", F_ZIG, 10, 275)
|
||||
+ colour_matrix(w["opp_col"], "Movers opposing colour", F_OPP, 320, 275))
|
||||
|
||||
return (frame(w["bank"], "Movers pads", 1740, 5, 440, 380, bank, header=False)
|
||||
+ frame(w["runs"], "Movers chase runs", 1740, 400, 310, 120, runs)
|
||||
+ frame(w["colours"], "Movers chase colours", 1740, 530, 640, 510, colours, collapsed=True))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if "Movers chase forward run" in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the mover pads")
|
||||
next_id = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
|
||||
if int(i) != NO_FUNCTION) + 1
|
||||
widgets = vc(xml, next_id)
|
||||
|
||||
# The strobe flash is HTP so it beats the colour scenes' centre strobe of 0, as on the cans.
|
||||
for fid in LEFT_TO_RIGHT:
|
||||
xml = re.sub(rf"( <ID>{fid}</ID>\n(?: .*\n)*? <Channels>43</Channels>\n)",
|
||||
rf"\1 <ForcedHTP>{STROBE}</ForcedHTP>\n", xml, count=1)
|
||||
xml = xml.replace(' <Function ID="0" Type="Scene"', groups() + ' <Function ID="0" Type="Scene"', 1)
|
||||
xml = xml.replace(" </Engine>", functions() + " </Engine>", 1)
|
||||
|
||||
xml = xml.replace(" </Frame>\n <Properties>", widgets + " </Frame>\n <Properties>", 1)
|
||||
xml = xml.replace('<Size Width="1880" Height="950"/>', '<Size Width="2400" Height="1050"/>', 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Added the mover pads to {SHOW.relative_to(ROOT)} (widgets from ID {next_id})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Smooth the movers' Corners in shows/test.qxw.
|
||||
|
||||
Corners (pad 11 on the movers layer) jumps the heads corner to corner of a
|
||||
square. At full motor speed each jump is a slam of about 100° of pan, and at an
|
||||
eighth of the speed dial the next comes 0.6 s later. Now it runs at a quarter,
|
||||
like the other shapes (about 1.4 s a corner, 5.5 s a round to start with), and
|
||||
its pad starts a collection of the EFX and a Movers glide scene that sets the
|
||||
heads' Pan/Tilt Speed to GLIDE while it runs (0 is fastest, 255 slowest), so
|
||||
they ease into each corner and settle there before the next. The channel is
|
||||
forced HTP on the movers, so like a dimmer it drops back to 0, full speed, when
|
||||
Corners stops; left LTP, QLC+ would hold it at GLIDE for everything after.
|
||||
|
||||
python3 scripts/shows/mover_corners_glide.py
|
||||
|
||||
Run it once on a show with Corners; it stops if the glide is already there.
|
||||
QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import M1, M2, M3, M4, ROOT, scene
|
||||
from mover_more_efx import START_MS
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
PAN_TILT_SPEED = 4 # mover channel
|
||||
GLIDE = 40
|
||||
TIMES_1_4 = 4 # speed dial factor index: (Not Sent), 0, 1/16, 1/8, 1/4, ...
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Name="Movers glide"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the movers glide")
|
||||
engine = xml.split("<VirtualConsole>")[0]
|
||||
corners = int(re.search(r'<Function ID="(\d+)" Type="EFX" Name="Movers corners">', engine).group(1))
|
||||
glide = max(int(i) for i in re.findall(r'<Function ID="(\d+)" Type', engine)) + 1
|
||||
collection = glide + 1
|
||||
|
||||
xml, n = re.subn(rf'(<Function ID="{corners}" Type="EFX" Name="Movers corners">\n.*?<Speed FadeIn="\d+" FadeOut="0" Duration=")\d+"',
|
||||
rf'\g<1>{START_MS}"', xml, count=1, flags=re.S)
|
||||
assert n == 1
|
||||
xml, n = re.subn(rf'(<Function FadeIn="0" FadeOut="0" Duration=")\d+(">{corners}</Function>)', rf"\g<1>{TIMES_1_4}\2", xml)
|
||||
assert n == 1
|
||||
functions = (scene(glide, "Movers glide", {PAN_TILT_SPEED: GLIDE})
|
||||
+ f' <Function ID="{collection}" Type="Collection" Name="Movers corners glide">\n'
|
||||
f' <Step Number="0">{corners}</Step>\n <Step Number="1">{glide}</Step>\n </Function>\n')
|
||||
xml = xml.replace(" </Engine>", functions + " </Engine>", 1)
|
||||
for fid in (M1, M2, M3, M4):
|
||||
xml, n = re.subn(rf'( <ID>{fid}</ID>\n(?: .*\n)*? <Channels>43</Channels>\n)',
|
||||
rf"\1 <ForcedHTP>{PAN_TILT_SPEED}</ForcedHTP>\n", xml, count=1)
|
||||
assert n == 1, fid
|
||||
xml, n = re.subn(r'(<Button Caption="Corners" ID="\d+" Icon="">\n.*?<Function ID=")\d+"', rf'\g<1>{collection}"',
|
||||
xml, count=1, flags=re.S)
|
||||
assert n == 1
|
||||
SHOW.write_text(xml)
|
||||
print(f"Corners in {SHOW.relative_to(ROOT)} now glides (scene {glide}, collection {collection})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add Circle and Sweep for the movers to shows/test.qxw, on notes 98 and 99.
|
||||
|
||||
They fill the top row of the movers layer after Wander and Ballyhoo, in the same
|
||||
Movement solo frame, so only one of the four runs at a time. Like them, each is
|
||||
a relative EFX around wherever the Pan and Tilt knobs (9 and 10) put the movers:
|
||||
|
||||
98 Circle pad 15 a circle about ±45° of pan and ±21° of tilt
|
||||
99 Sweep pad 16 a straight pan sweep, about ±60° side to side
|
||||
|
||||
All four movers start together, so the pairs mirror left to right and front to
|
||||
back as in Ballyhoo. Each fades in over 0.5 s. Knob 13's Movers speed dial gives
|
||||
them a quarter of its time, less the fade-in that QLC+ counts in each round:
|
||||
5.5 s a round to start with, from 15.5 s fully left to 2.5 s fully right.
|
||||
padcontroller/layer.py settles the knobs after them too.
|
||||
|
||||
python3 scripts/shows/mover_more_efx.py
|
||||
|
||||
Run it once on a show with the Movement solo frame and the Movers speed dial;
|
||||
it stops if Circle is already there. QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import LEFT_TO_RIGHT, NO_FUNCTION, ROOT, button, note
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
FADE_IN_MS = 500
|
||||
START_MS = 6000 # a quarter of the speed dial's starting 24 s
|
||||
TIMES_1_4 = 4 # speed dial factor index: (Not Sent), 0, 1/16, 1/8, 1/4, ...
|
||||
SIZE = 90
|
||||
|
||||
# Caption, function name, algorithm, width, height (of 255 each way), can note, column
|
||||
MOVES = (
|
||||
("Circle", "Movers circle", "Circle", 21, 20, 50, 2),
|
||||
("Sweep", "Movers sweep", "Line", 28, 0, 51, 3),
|
||||
)
|
||||
|
||||
|
||||
def efx(fid: int, name: str, algorithm: str, width: int, height: int, start_ms: int = START_MS) -> str:
|
||||
fixtures = "".join(f""" <Fixture>
|
||||
<ID>{f}</ID>
|
||||
<Head>0</Head>
|
||||
<Mode>0</Mode>
|
||||
<Direction>Forward</Direction>
|
||||
<StartOffset>0</StartOffset>
|
||||
</Fixture>
|
||||
""" for f in LEFT_TO_RIGHT)
|
||||
axes = "".join(f""" <Axis Name="{axis}">
|
||||
<Offset>127</Offset>
|
||||
<Frequency>1</Frequency>
|
||||
<Phase>0</Phase>
|
||||
</Axis>
|
||||
""" for axis in "XY")
|
||||
# Relative: the EFX adds its offset from 127 to the Pan and Tilt sliders' levels.
|
||||
return f""" <Function ID="{fid}" Type="EFX" Name="{name}">
|
||||
{fixtures} <PropagationMode>Parallel</PropagationMode>
|
||||
<Speed FadeIn="{FADE_IN_MS}" FadeOut="0" Duration="{start_ms}"/>
|
||||
<Direction>Forward</Direction>
|
||||
<RunOrder>Loop</RunOrder>
|
||||
<Algorithm>{algorithm}</Algorithm>
|
||||
<Width>{width}</Width>
|
||||
<Height>{height}</Height>
|
||||
<Rotation>0</Rotation>
|
||||
<StartOffset>0</StartOffset>
|
||||
<IsRelative>1</IsRelative>
|
||||
{axes} </Function>
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Name="Movers circle"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the movers circle")
|
||||
engine, console = xml.split("<VirtualConsole>")
|
||||
fid = max(int(i) for i in re.findall(r'<Function ID="(\d+)" Type', engine)) + 1
|
||||
wid = max(int(i) for i in re.findall(r' ID="(\d+)"', console) if int(i) != NO_FUNCTION) + 1
|
||||
|
||||
solo = re.search(r' <SoloFrame Caption="Movement" ID="\d+">\n.*? </SoloFrame>\n', xml, re.S).group(0)
|
||||
dial = re.search(r' <SpeedDial Caption="Movers speed" ID="\d+">\n.*? </SpeedDial>\n', xml, re.S).group(0)
|
||||
functions, buttons, rows = "", "", ""
|
||||
for i, (caption, name, algorithm, width, height, can_note, column) in enumerate(MOVES):
|
||||
functions += efx(fid + i, name, algorithm, width, height)
|
||||
buttons += button(wid + i, caption, SIZE * column, 0, SIZE, fid + i, note(can_note), indent=" ")
|
||||
rows += f' <Function FadeIn="0" FadeOut="0" Duration="{TIMES_1_4}">{fid + i}</Function>\n'
|
||||
|
||||
columns = 2 + len(MOVES)
|
||||
grown = re.sub(r'(<WindowState Visible="True" X="10" Y="10" Width=")\d+"', rf'\g<1>{SIZE * columns}"', solo, count=1)
|
||||
grown = grown.replace(" </SoloFrame>\n", buttons + " </SoloFrame>\n")
|
||||
xml = xml.replace(solo, grown, 1)
|
||||
xml = xml.replace(dial, dial.replace(" </SpeedDial>\n", rows + " </SpeedDial>\n"), 1)
|
||||
xml = xml.replace(" </Engine>", functions + " </Engine>", 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Added Circle and Sweep to {SHOW.relative_to(ROOT)} (functions {fid}–{fid + len(MOVES) - 1}, "
|
||||
f"widgets {wid}–{wid + len(MOVES) - 1})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Make Wander and Ballyhoo one at a time in shows/test.qxw.
|
||||
|
||||
Their two buttons go into a solo frame, Movement, where they already sit on the
|
||||
top row of the movers pads, so starting one stops the other, as the colour sets
|
||||
do. padcontroller/layer.py follows the same rule.
|
||||
|
||||
python3 scripts/shows/mover_movement_solo.py
|
||||
|
||||
Run it once on a show with Wander and Ballyhoo on the top row; it stops if the
|
||||
solo frame is already there. QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import NO_FUNCTION, ROOT, appearance
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
BUTTONS = ("Wander", "Ballyhoo")
|
||||
SIZE = 90
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Caption="Movement"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the Movement solo frame")
|
||||
wid = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
|
||||
if int(i) != NO_FUNCTION) + 1
|
||||
|
||||
found = [re.search(rf' <Button Caption="{caption}" ID="\d+" Icon="">\n.*? </Button>\n', xml, re.S).group(0)
|
||||
for caption in BUTTONS]
|
||||
body = ""
|
||||
for i, button in enumerate(found):
|
||||
xml = xml.replace(button, "", 1)
|
||||
# Inside the frame each sits at its place in the row, one level deeper.
|
||||
moved = re.sub(r'X="\d+" Y="\d+"', f'X="{SIZE * i}" Y="0"', button, count=1)
|
||||
body += "".join(" " + line if line else line for line in moved.splitlines(keepends=True))
|
||||
|
||||
frame = (f' <SoloFrame Caption="Movement" ID="{wid}">\n'
|
||||
+ appearance(" ")
|
||||
+ f' <WindowState Visible="True" X="10" Y="10" Width="{SIZE * len(BUTTONS)}" Height="{SIZE}"/>\n'
|
||||
' <AllowChildren>True</AllowChildren>\n <AllowResize>True</AllowResize>\n'
|
||||
' <ShowHeader>False</ShowHeader>\n <ShowEnableButton>False</ShowEnableButton>\n'
|
||||
' <Mixing>False</Mixing>\n <Collapsed>False</Collapsed>\n <Disabled>False</Disabled>\n'
|
||||
+ body + ' </SoloFrame>\n')
|
||||
|
||||
strobe = re.search(r' <Button Caption="Strobe" ID="89" Icon="">\n', xml).group(0)
|
||||
xml = xml.replace(strobe, frame + strobe, 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Put Wander and Ballyhoo in the Movement solo frame in {SHOW.relative_to(ROOT)} (widget {wid})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Drop the movers' chases from shows/test.qxw and put Wander and Ballyhoo on the top row.
|
||||
|
||||
The movers layer loses its Chase, Chase reverse, Zigzag and Opposing pads
|
||||
(notes 96–99), their runs, holds, colour matrices and fixture groups, and their
|
||||
place on the Speed dial. Wander and Ballyhoo move up from notes 93 and 94 to
|
||||
the first two pads of the top row:
|
||||
|
||||
96 Wander pad 13 on the movers layer
|
||||
97 Ballyhoo pad 14 on the movers layer
|
||||
|
||||
The movers' Strobe (92) and Peak stay. padcontroller/layer.py settles the knobs
|
||||
after notes 96 and 97.
|
||||
|
||||
python3 scripts/shows/mover_pads_top_row.py
|
||||
|
||||
Run it once on a show with the mover chases; it stops if they are gone.
|
||||
QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import (F_DIMMER, F_OPP, GROUP_OPPOSING, GROUP_RINGS, GROUP_ZIGZAG, ROOT, note)
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
CHASE_FUNCTIONS = range(F_DIMMER, F_OPP + 1) # 57–63
|
||||
CHASE_GROUPS = (GROUP_RINGS, GROUP_ZIGZAG, GROUP_OPPOSING)
|
||||
CHASE_PADS = ("Chase", "Chase reverse", "Zigzag", "Opposing")
|
||||
TOP_ROW = (("Wander", 10, note(48)), ("Ballyhoo", 100, note(49)))
|
||||
|
||||
|
||||
def cut(xml: str, pattern: str) -> str:
|
||||
xml, n = re.subn(pattern, "", xml, count=1, flags=re.S)
|
||||
assert n == 1, pattern
|
||||
return xml
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Name="Movers chase forward run"' not in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} has no mover chases")
|
||||
|
||||
for fid in CHASE_FUNCTIONS:
|
||||
xml = cut(xml, rf' <Function ID="{fid}" Type=.*?\n </Function>\n')
|
||||
xml = re.sub(rf' <Function FadeIn="0" FadeOut="0" Duration="\d+">{fid}</Function>\n', "", xml)
|
||||
for gid in CHASE_GROUPS:
|
||||
xml = cut(xml, rf' <FixtureGroup ID="{gid}">\n.*? </FixtureGroup>\n')
|
||||
|
||||
pads = re.search(r' <Frame Caption="Movers pads" ID="\d+">\n.*?\n </Frame>\n', xml, re.S).group(0)
|
||||
kept = pads
|
||||
for caption in CHASE_PADS:
|
||||
kept = cut(kept, rf' <Button Caption="{caption}" ID="\d+" Icon="">\n.*? </Button>\n')
|
||||
for caption, x, channel in TOP_ROW:
|
||||
kept, n = re.subn(rf'( <Button Caption="{caption}" ID="\d+" Icon="">\n <WindowState Visible="True" X=")\d+" Y="\d+"'
|
||||
rf'(.*?<Input Universe="1" Channel=")\d+"',
|
||||
rf'\g<1>{x}" Y="10"\g<2>{channel}"', kept, count=1, flags=re.S)
|
||||
assert n == 1, caption
|
||||
xml = xml.replace(pads, kept, 1)
|
||||
for caption in ("Movers chase runs", "Movers chase colours"):
|
||||
xml = cut(xml, rf' <Frame Caption="{caption}" ID="\d+">\n.*?\n </Frame>\n')
|
||||
|
||||
assert not re.search(rf'(?:Function ID="|>)(?:{"|".join(map(str, CHASE_FUNCTIONS))})(?:"|<)', xml)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Dropped the mover chases from {SHOW.relative_to(ROOT)}; Wander and Ballyhoo are on notes 96 and 97")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Split the movers' Pan slider in shows/test.qxw so the back pair face the back wall at knob 0.
|
||||
|
||||
M3 and M4 are mounted 90° round from M1 and M2: at pan 0 the front pair face
|
||||
the audience and the back pair face the middle. Knob 9 (CC 38) now drives two
|
||||
sliders over the same span of 212 steps, so the pairs keep that 90° of pan
|
||||
(about 43 steps of 540°) between them all the way round:
|
||||
|
||||
Pan M1, M2 0–212
|
||||
Pan back M3, M4 43–255
|
||||
|
||||
At knob 0 the front pair face the audience and the back pair the back wall.
|
||||
Turning it, the left pair (M1, M3) and the right pair (M2, M4) point at the
|
||||
centre together and at the side walls together.
|
||||
|
||||
python3 scripts/shows/mover_pan_back.py
|
||||
|
||||
Run it once on a show without it; it stops if it is already there.
|
||||
QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import M1, M2, M3, M4, NO_FUNCTION, ROOT
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
BACK_OFFSET = 43 # 90° of pan, of 540° over 256 steps
|
||||
ORDER = ("Brightness", "Pan", "Pan back", "Tilt", "Focus", "Rotate")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Caption="Pan back"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the back movers' pan")
|
||||
wid = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
|
||||
if int(i) != NO_FUNCTION) + 1
|
||||
start = xml.index('<Frame Caption="Movers position"')
|
||||
end = xml.index("</Frame>", start)
|
||||
frame = xml[start:end]
|
||||
|
||||
pan = re.search(r' <Slider Caption="Pan" ID="\d+".*? </Slider>\n', frame, re.S).group(0)
|
||||
level = re.search(r'<Level LowLimit="0" HighLimit="255" Value="\d+">', pan).group(0)
|
||||
|
||||
def rows(*fixtures: int) -> str:
|
||||
return "".join(f' <Channel Fixture="{f}">0</Channel>\n' for f in fixtures)
|
||||
|
||||
channels = rows(M1, M2, M3, M4)
|
||||
assert channels in pan
|
||||
front = (pan.replace(level, f'<Level LowLimit="0" HighLimit="{255 - BACK_OFFSET}" Value="0">')
|
||||
.replace(channels, rows(M1, M2)))
|
||||
back = (re.sub(r'Caption="Pan" ID="\d+"', f'Caption="Pan back" ID="{wid}"', pan)
|
||||
.replace(level, f'<Level LowLimit="{BACK_OFFSET}" HighLimit="255" Value="{BACK_OFFSET}">')
|
||||
.replace(channels, rows(M3, M4)))
|
||||
frame = frame.replace(pan, front + back)
|
||||
|
||||
# Six sliders 58 apart fit the frame as it is.
|
||||
for i, caption in enumerate(ORDER):
|
||||
frame, n = re.subn(rf'(<Slider Caption="{caption}" ID="\d+"[^>]*>\n\s*<WindowState Visible="True" X=")\d+"',
|
||||
rf'\g<1>{5 + 58 * i}"', frame)
|
||||
assert n == 1, caption
|
||||
|
||||
SHOW.write_text(xml[:start] + frame + xml[end:])
|
||||
print(f"Split the movers' Pan in {SHOW.relative_to(ROOT)} (Pan back is widget {wid})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add Pan, Tilt, Focus and Rotate sliders for the movers to shows/test.qxw.
|
||||
|
||||
As in templeoftechno.qxw, knobs 9–12 (CC 38–41) drive all four movers at once:
|
||||
|
||||
Knob 9 CC 38 Pan channel 0
|
||||
Knob 10 CC 39 Tilt channel 2
|
||||
Knob 11 CC 40 Focus channel 7
|
||||
Knob 12 CC 41 Rotate channel 5 (Lens Rotate)
|
||||
|
||||
They sit in a Movers position frame beside Sound peak, below the cans' chase runs.
|
||||
|
||||
python3 scripts/shows/mover_position.py
|
||||
|
||||
Run it once on a show without them; it stops if they are already there.
|
||||
QLC+ has to reopen the show to see them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from mover_bank import LEFT_TO_RIGHT, NO_FUNCTION, ROOT, appearance, frame
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
# Caption, CC, mover channel, starting value: temple techno's.
|
||||
SLIDERS = (
|
||||
("Pan", 38, 0, 0),
|
||||
("Tilt", 39, 2, 0),
|
||||
("Focus", 40, 7, 70),
|
||||
("Rotate", 41, 5, 0),
|
||||
)
|
||||
|
||||
|
||||
def level(wid: int, caption: str, x: int, cc: int, channel: int, value: int, indent: str = " ") -> str:
|
||||
rows = "".join(f'{indent} <Channel Fixture="{f}">{channel}</Channel>\n' for f in LEFT_TO_RIGHT)
|
||||
return (f'{indent}<Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">\n'
|
||||
f'{indent} <WindowState Visible="True" X="{x}" Y="10" Width="52" Height="200"/>\n'
|
||||
+ appearance(indent + " ", "Sunken")
|
||||
+ f'{indent} <Input Universe="1" Channel="{cc}"/>\n'
|
||||
f'{indent} <SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="false">Level</SliderMode>\n'
|
||||
f'{indent} <Level LowLimit="0" HighLimit="255" Value="{value}">\n{rows}{indent} </Level>\n'
|
||||
f'{indent} <Playback>\n{indent} <Function>{NO_FUNCTION}</Function>\n{indent} </Playback>\n{indent}</Slider>\n')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Caption="Movers position"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the mover position sliders")
|
||||
next_id = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
|
||||
if int(i) != NO_FUNCTION) + 1
|
||||
sliders = "".join(level(next_id + 1 + i, caption, 10 + 58 * i, cc, channel, value)
|
||||
for i, (caption, cc, channel, value) in enumerate(SLIDERS))
|
||||
widgets = frame(next_id, "Movers position", 420, 630, 10 + 58 * len(SLIDERS), 250, sliders)
|
||||
|
||||
xml = xml.replace(" </Frame>\n <Properties>", widgets + " </Frame>\n <Properties>", 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Added the mover position sliders to {SHOW.relative_to(ROOT)} (widgets from ID {next_id})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Add a Movers speed dial on knob 13 to shows/test.qxw.
|
||||
|
||||
Knob 13 (CC 42) sets how long Wander and Ballyhoo take to go round, as knob 1
|
||||
does for the cans' chases. Wander gets the dial's time and Ballyhoo an eighth of
|
||||
it. QLC+ 4.12 counts an EFX's fade-in inside every round, not just the first, so
|
||||
a round takes that less its fade-in (2 s for Wander, 0.5 s for Ballyhoo):
|
||||
|
||||
Knob fully left 62 s Wander, 7.5 s Ballyhoo
|
||||
Starting value 22 s Wander, 2.5 s Ballyhoo (as before the dial)
|
||||
Knob fully right 10 s Wander, 1 s Ballyhoo
|
||||
|
||||
The fade-ins stay, so the movers don't jump when either starts. The dial sits
|
||||
beside the cans' Speed dial.
|
||||
|
||||
python3 scripts/shows/mover_speed.py
|
||||
|
||||
Run it once on a show with Wander and Ballyhoo; it stops if the dial is already there.
|
||||
QLC+ has to reopen the show to see it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from mover_bank import NO_FUNCTION, ROOT, appearance
|
||||
|
||||
SHOW = ROOT / "shows" / "test.qxw"
|
||||
|
||||
SPEED_CC = 42 # knob 13
|
||||
SLOWEST_MS, FASTEST_MS, START_MS = 64000, 12000, 24000
|
||||
# Index into QLC+'s speed dial factors: (Not Sent), 0, 1/16, 1/8, 1/4, 1/2, 1, 2, 4, 8, 16
|
||||
TIMES_1, TIMES_1_8 = 6, 3
|
||||
NOT_SENT = 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
xml = SHOW.read_text()
|
||||
if 'Caption="Movers speed"' in xml:
|
||||
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the movers speed dial")
|
||||
engine, console = xml.split("<VirtualConsole>")
|
||||
wid = max(int(i) for i in re.findall(r' ID="(\d+)"', console) if int(i) != NO_FUNCTION) + 1
|
||||
|
||||
def function(name: str) -> int:
|
||||
return int(re.search(rf'<Function ID="(\d+)" Type="EFX" Name="{name}">', engine).group(1))
|
||||
|
||||
rows = "".join(f' <Function FadeIn="{NOT_SENT}" FadeOut="{NOT_SENT}" Duration="{factor}">{function(name)}</Function>\n'
|
||||
for name, factor in (("Movers wander", TIMES_1), ("Movers ballyhoo", TIMES_1_8)))
|
||||
dial = (f' <SpeedDial Caption="Movers speed" ID="{wid}">\n'
|
||||
' <WindowState Visible="True" X="1820" Y="10" Width="110" Height="240"/>\n'
|
||||
+ appearance(" ", "Sunken")
|
||||
+ f' <AbsoluteValue Minimum="{SLOWEST_MS}" Maximum="{FASTEST_MS}">\n'
|
||||
f' <Input Universe="1" Channel="{SPEED_CC}"/>\n'
|
||||
' </AbsoluteValue>\n'
|
||||
f' <Time>{START_MS}</Time>\n'
|
||||
+ rows + ' </SpeedDial>\n')
|
||||
|
||||
xml = xml.replace(" </Frame>\n <Properties>", dial + " </Frame>\n <Properties>", 1)
|
||||
SHOW.write_text(xml)
|
||||
print(f"Added the movers speed dial to {SHOW.relative_to(ROOT)} (widget {wid}, knob 13)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user