Compare commits

..
64 Commits
Author SHA1 Message Date
jimmyandClaude Opus 5.5 a985452568 Keep reading the virtual pad while the real pad is away.
The pad controller opened the pad's port as its input and closed it when the
pad went, which stopped rtmidi reading at all, so virtual pad presses never
reached QLC+ and the chases stayed on their starting blue. Its input is now a
port of its own, open for the whole run, with the pad linked into it by
aconnect (and the old link dropped when the pad moves between USB and
Bluetooth). It also starts without the pad instead of exiting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:59:44 +13:00
jimmyandClaude Opus 5.5 0b06dfdccf Add a script linking the RGB scripts, fixtures and pad profile into ~/.qlcplus.
The can patterns' Steps and Swap matrices need rgbscripts/steps.js and
swap.js in ~/.qlcplus/rgbscripts. Only can_patterns.py linked them, so a
fresh checkout's patterns did nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:27:40 +13:00
jimmyandClaude Opus 5.5 72425159b5 Add a gig show: the test show sending Art-Net to the rig.
shows/gig.qxw is shows/test.qxw with its one output changed from 127.0.0.1
to the Art-Net node at 192.168.1.175, sent from the laptop's gig address
192.168.1.143 as cabaret.qxw does (scripts/shows/make_gig.py; run it again
after changing the test show). The test show stays on the simulator.
draw_test_pads.py takes a show's name, and shows/gig-pads.png is its pad
layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:45:51 +13:00
jimmyandClaude Opus 5.5 873502b3ca Say on the pad layout how to reach each bank and layer.
Each panel's subtitle gives the buttons: PAD BANK and KNOB BANK pick the
banks, Pause puts pad bank 1 on the movers, and holding Play moves pad bank 2
to Colour 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:42:48 +13:00
jimmyandClaude Opus 5.5 9ebe3a5af1 Draw the test show's pad layout.
shows/test-pads.png shows both banks of pads on every layer (bank 1 on the
cans and, with Pause, the movers; bank 2 as Colour 1 and, with Play held,
Colour 2) and what each knob does. scripts/shows/draw_test_pads.py reads the
labels and colours from the show's virtual console, so running it again
brings the picture up to date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:38:24 +13:00
jimmyandClaude Opus 5.5 c71b6da9d9 Rearrange the test show's console and square off its colour buttons.
The layout, chase colours, mover speeds and levels as saved from QLC+: the
colour frames stacked on the left with the cans and movers pads beside them.
The Colour 1 and Colour 2 buttons are 75 px squares, and the Chase runs and
Pads layer frames below Colour 2 move down to clear them
(scripts/shows/square_colours.py). The Movers speed dial comes in from
x=1820 to beside Movers position, and both speed dials are trimmed to the
dial and its time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:38:24 +13:00
jimmyandClaude Opus 5.5 c7546e5ea9 Show in the test show whether the pads are on the cans or the movers.
A Pads layer frame under the movers pads has Cans pads and Movers pads
buttons (scripts/shows/layer_indicator.py). The pad controller holds channel
16 note 0 (cans) or 1 (movers) down and the other up whenever Pause changes,
QLC+ reloads or it starts, and the Flash buttons light while their note is
held, so the lit one is the layer and a missed message can't leave them the
wrong way round. Each flashes an empty scene of its own: with one between
them, QLC+ lit both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:09:49 +13:00
jimmyandClaude Opus 5.5 467b480c76 Put the pads on the cans or movers layer from Pause's value.
The SMC-PAD latches Pause itself: one message a press, 127 and 0 on
alternate presses, nothing on release. The pad controller flipped the layer
only on 127, so every second press did nothing. Bank 1 now follows the
value: 0 is the cans, 127 the movers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:09:47 +13:00
jimmyandClaude Opus 5.5 31ccbab340 Make a click on a cans chase button run the whole chase in the test show.
Each chase was two buttons on one pad note: the pads frame's ran the side
dimmer hold under Peak, and the Chase runs frame's ran the stripe outside it.
The pad pressed both; a click pressed only the hold, which lit nothing. Now
the pads frame's button runs a hold of the chase's own whose step is the Sides
dimmer and a Script that starts the stripe. Peak reaches the dimmer through the
chaser and collection but not the stripe through the script, as with the pad
(scripts/shows/chase_clicks.py). The Chase runs buttons no longer listen to the
pad.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:57:27 +13:00
jimmyandClaude Opus 5.5 cf94c7b1ba Press the colours again when a restarted QLC+ links itself to the pad controller.
The pad controller only took a QLC+ reload as one when it had to make the
link to QLC+ itself. A restarted QLC+ often subscribes to the virtual port on
its own as it opens the show, before the next check, so the colours stayed off.
Each check now also notes the QLC+ process and port it feeds (qlc_feeds), and a
new one counts as a reload too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:57:22 +13:00
jimmyandClaude Opus 5.5 4fd11445e8 Add cabaret's can patterns to the test show.
Eight of make_cabaret_vc.py's Can Patterns on the cans pads 1-8, in a Can
patterns solo frame in place of the pads frame's empty Buttons 53-60:
Theater, Rainbow, Odd Even, Left Right, Scanner (with a fading tail), Fill,
Center and Pairs, laid out for the test show's cans and walking the ring round
the room (scripts/shows/can_patterns.py). Collapse and Chase Out are left out.

The masks show the Colour 1 colour; Odd Even (a checkerboard) and Left Right
swap between Colour 1 and Colour 2 through four Matrix widgets in the Chase
colours frame. All of them follow the cans' Speed dial (knob 1). Each pattern is
RGB matrices running from start to stop (rgbscripts/steps.js and swap.js, linked
into ~/.qlcplus/rgbscripts), so a chase started over one lands on top, and the
pad controller restarts the pattern that is on just after a Colour 1 press so
the new colour scene doesn't cover it.

The row of 4 (#3-#6) never animates; CLAUDE.md now says so for whatever comes
next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:57:13 +13:00
jimmyandClaude Opus 5.5 e7e1cf656b Remove the sound-reactive cans from the test show.
The Sound and Threshold audio triggers go, with the Sound submaster beside the
cans' Front and Back sliders (CC 100) and the Sound peak frame with its Peak
submaster and Hit button and the Cans hit functions only Hit ran. Pads 1 and 2
are plain spare buttons again (scripts/shows/drop_sound.py). The pads frame's
own Peak (knob 6) stays: it is the chases' peak.

The pad controller drops its side of it: the Pump and Threshold modes, the
CC 100 resets, holding the side knobs at the peak and the pad lamps that showed
which mode was on. Pads 1 and 2 and knobs 5, 6 and 8 pass straight through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:57:00 +13:00
jimmyandClaude Opus 5.5 3b38df3dd0 Smooth the movers' Corners in the test show.
Corners slammed the heads about 100° of pan every 0.6 s at full motor speed.
It now runs at a quarter of the speed dial like the other shapes, about 1.4 s
a corner, and its pad starts a collection with a Movers glide scene that sets
the heads' Pan/Tilt Speed to 40 while it runs, so they ease into each corner.
That channel is forced HTP on the movers, so it drops back to full speed when
Corners stops instead of QLC+ holding it for everything after
(scripts/shows/mover_corners_glide.py).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:47:26 +13:00
jimmyandClaude Opus 5.5 f674dc9fe0 Give the movers every EFX shape and drop their Strobe in the test show.
The movers layer loses its Strobe (pad 9): its button, its scene and the
forced-HTP strobe channel it needed. Its pad, the rest of the second row
and pad 5 take the five shapes the movers did not have yet: Diamond, Square,
Corners (SquareChoppy), Leaf, and Tilt (Line2 on tilt alone). All nine sit in
the Movement solo frame, one at a time, mirrored and relative to the knobs.
Knob 13's speed dial gives Corners an eighth of its time and the rest a
quarter (scripts/shows/mover_all_efx.py). The pad controller settles the
knobs after all nine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:47:15 +13:00
jimmyandClaude Opus 5.5 c3fe965e79 Add Circle and Sweep for the movers to the test show.
They fill the movers layer's top row, pads 15 and 16 (notes 98 and 99), in
the Movement solo frame with Wander and Ballyhoo: a circle of about ±45° of
pan and ±21° of tilt, and a straight pan sweep of about ±60°, both mirrored
and relative to the knobs. Knob 13's speed dial gives them a quarter of its
time, 5.5 s a round to start with (scripts/shows/mover_more_efx.py). The pad
controller settles the knobs after them too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:47:05 +13:00
jimmyandClaude Opus 5.5 80df550916 Run the movers' Wander and Ballyhoo one at a time.
Their two buttons go into a Movement solo frame where they sit, so starting
one stops the other (scripts/shows/mover_movement_solo.py). The pad
controller follows: it tracks the one that is on, and settles the knobs only
when that one goes off. Swapping needs no settle, as the new EFX writes over
the old one's offset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:46:45 +13:00
jimmyandClaude Opus 5.5 09aab70bd6 Put the movers' Wander and Ballyhoo speed on knob 13 in the test show.
A Movers speed dial on knob 13 (CC 42), beside the cans' Speed dial, sets
how long Wander takes to go round and gives Ballyhoo an eighth of it
(scripts/shows/mover_speed.py).

QLC+ 4.12 counts an EFX's fade-in inside every round, so Wander has been
taking 22 s and Ballyhoo 2.5 s, not 24 s and 3 s. The dial keeps those as
its starting point and runs from 62 s and 7.5 s fully left to 10 s and 1 s
fully right. The fade-ins stay, so the movers don't jump when either starts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:46:27 +13:00
jimmyandClaude Opus 5.5 ae186c51ea Drop the movers' chases and put Wander and Ballyhoo on the top row.
The movers layer loses its Chase, Chase reverse, Zigzag and Opposing pads,
with their runs, holds, colour matrices, fixture groups and Speed dial
entries. Wander and Ballyhoo move up to pads 13 and 14 (notes 96 and 97),
and the pad controller settles the knobs after those notes instead
(scripts/shows/mover_pads_top_row.py).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:46:18 +13:00
jimmyandClaude Opus 5.5 913494c0aa Add a Ballyhoo pad for the movers to the test show.
Pad 11 on the movers layer (note 94) toggles a fast figure of eight around
the Pan and Tilt knobs, like Wander: about ±85° of pan and ±26° of tilt, all
four movers together so the pairs mirror left to right and front to back
(scripts/shows/mover_ballyhoo.py).

The pad controller now settles the knobs after Ballyhoo goes off as well as
Wander, and keeps track of each separately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 01:46:03 +13:00
jimmyandClaude Opus 5.5 8caf341d30 Point the back movers at the back wall at pan knob 0 in the test show.
M3 and M4 are mounted 90° round from M1 and M2, so at pan 0 they face the
middle. Knob 9 now drives a Pan slider for M1 and M2 over 0–212 and a Pan
back slider for M3 and M4 over 43–255 (scripts/shows/mover_pan_back.py).
The same span keeps the pairs 90° of pan apart all the way round: at knob 0
the front pair face the audience and the back pair the back wall, and the
left and right pairs point at the centre and the side walls together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 00:49:37 +13:00
jimmyandClaude Opus 5.5 00c8c2d35d Add a Wander pad for the movers to the test show.
Pad 10 on the movers layer (note 93) toggles a relative EFX that drifts all
four movers around the Pan and Tilt knobs: a 24 s Lissajous of about ±30° pan
and ±10° tilt, each mover a quarter of the way further round, easing in over
2 s (scripts/shows/mover_wander.py).

QLC+ 4.12 leaves a relative EFX's last offset on the movers when it stops,
until the sliders under it change. So when Wander goes off, the pad
controller nudges the Pan and Tilt knobs a step and puts them back, 0.1 s
apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 00:49:33 +13:00
jimmyandClaude Opus 5.5 f8c8cea3ef Free the pad's ALSA clients when the Private port is missing.
On Bluetooth there is no Private port, so every Sound or Threshold press
opened two sequencer clients to light the lamps and left them open when the
port lookup raised. After 29 presses the sequencer was full and aconnect
could no longer open it. set_sound_lamps and Link now close both clients
on that path too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 00:49:25 +13:00
jimmyandClaude Opus 5.5 9c1ef6f2d4 Read the pad over Bluetooth first, and USB when it isn't paired.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 00:02:08 +13:00
jimmyandClaude Opus 5.5 2586ead4fa Put the chase speed on knob 1 in the test show.
A Speed dial on knob 1 (CC 30) sets the step time of the cans' and movers'
chase and zigzag runs, from 800 ms fully left to 50 ms fully right, starting
at the old 200 ms. Zigzag forward stays at half the step, and the dimmer holds
follow at 8 steps so they stretch with the run. The 500 ms trail is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 00:02:08 +13:00
jimmyandClaude Opus 5.5 fc8abf9c99 Set the movers' zeros and pan directions, swap M1/M2's patch, and model tilt in the simulator.
The front right mover is on DMX 1 and the front left on 45, so M1 and M2
swap addresses in the stage map and test.qxw. Measured on the rig, pan 0
faces forward on the front pair and into the middle on the back pair, back
at 85. M1 and M4 turn anticlockwise, so movers get a pan_reverse flag.

Tilt 127 now points straight down: the simulator draws a spot under the
head, and past 127 the beam flips behind the pan heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:54:14 +13:00
jimmyandClaude Opus 5.5 2b0f9e2f9b Re-arrange the test show's console and put the movers' brightness with their position knobs.
The Dimmers sliders are now Middle, Front and Back, and the movers' Brightness
(knob 15) leads the Movers position frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:47:22 +13:00
jimmyandClaude Opus 5.5 e96b31ab66 Re-aim cans 1, 2, 7 and 8 on the XCHC stage map.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:03:18 +13:00
jimmyandClaude Opus 5.5 2219788904 Give the test show Dimmers knobs instead of the custom colour mixer, and add Amber.
The colour scenes leave the dimmers to Level sliders on knobs 15, 5, 7 and 8.
The Chataigne export carries Level sliders and their starting values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:03:18 +13:00
jimmyandClaude Opus 5.5 11da656ee6 Toggle the pad's bank 1 to the movers with Pause, and add a Threshold sound mode.
Pause flips bank 1 between the cans (36-51) and the movers (84-99). Threshold
flashes the cans on bass hits and is exclusive with Sound, and knob 6 is the
sides' peak. The Sound and Threshold pads light while on, and the colour pads
that were on are pressed again when QLC+ reloads the show. --lock-knobs is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:03:18 +13:00
jimmyandClaude Opus 5.5 72c227b153 Merge dev into main: the pad controller, simulator, Chataigne export and test show.
Keep main's Temple of Techno show over dev's older copy from the first venue
workspaces commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:00:21 +13:00
jimmyandClaude Opus 5.5 86d87bf8cf Add a movers bank and Pan, Tilt, Focus and Rotate knobs to the test show.
Pause toggles bank 1 between the cans and the movers (scripts/shows/mover_bank.py).
Knobs 9-12 (CC 38-41) drive all four movers' pan, tilt, focus and lens
rotate, as in templeoftechno.qxw (scripts/shows/mover_position.py).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:56:38 +13:00
jimmyandClaude Opus 5.5 18f0ac2dc5 Add a virtual pad and an end-to-end test against the simulator, and run tests with pytest.
padcontroller.virtualpad presses pads and sets knobs through padcontroller-in,
refusing unless QLC+ last opened shows/test.qxw. tests/test_e2e_pad.py uses it
to check can and mover colours in the simulator's /api/state (PAD_E2E=1).

pytest is a dev package now, so the plain test functions unittest skipped run
too. test_small_eye.py is a rig tester, not a test, so pytest leaves it alone,
and the #14 direction assertion now matches the stage map (-179).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:58:04 +13:00
jimmyandClaude Opus 5.5 d522b1a2cf Add sound-reactive cans, a strobe pad and side chases to the test show.
The Sound pad (bank 1 note 36) toggles a QLC+ Audio Triggers widget whose
volume bar drives a Sound submaster beside the can dimmers, so the cans'
brightness follows the music while the movers stay steady. padcontroller sends
CC 100 at full on every press and release of that pad, bypassing its CC
smoothing, so switching sound off always leaves the cans at full.

test.qxw also gains Chase forward/reverse, a double and an opposing zigzag
down the side cans (RGB matrices whose colour follows the Colour 2 pads), a
Strobe flash pad with the cans' strobe channel forced HTP, and the Dimmers
frame, forced-LTP side colours and dimmer-free colour scenes from parallel
sessions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:03:27 +13:00
jimmyandClaude Opus 5.5 6bbb3d5a29 Add CLAUDE.md: check the pad controller and simulator are up, and keep the test show on 127.0.0.1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:34:05 +13:00
jimmyandClaude Opus 5.5 643f7c8fb6 Send the test show's Art-Net to 127.0.0.1 for the simulator.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:34:05 +13:00
jimmyandClaude Opus 5.5 8f8c69898a Read the pad over USB when it's plugged in, and keep its links to the pad and QLC+ up.
padcontroller.midi now follows the pad every 2 s: it reopens it after a
replug, moves to USB when that turns up, and re-links QLC+ to the virtual
port after a restart, so QLC+ can stay open. Only the chosen source is
subscribed, so a USB pad no longer gets Bluetooth input as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:34:05 +13:00
jimmyandClaude Opus 5.5 a295fefac0 Pick the simulator's stage map from a drop-down, and make the QLC+ show optional.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:05:42 +13:00
jimmyandClaude Opus 5.5 df05c8ca49 Add a systemd user service and installer for the stage simulator.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:29:23 +13:00
jimmyandClaude Opus 5.5 20f018a523 Let the padcontroller installer install the service without enabling it at login.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:27:48 +13:00
jimmyandClaude Opus 5.5 9742121144 Rename padeditor to padcontroller, with the MIDI intercept as padcontroller.midi and its virtual port as padcontroller.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:25:06 +13:00
jimmyandClaude Opus 5.5 1e09cb3825 Rename the MIDI intercept to padcontroller, as a module and as a service.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:33:43 +13:00
jimmyandClaude Opus 5.5 00de2595b6 Move the SMC-PAD MIDI intercept into padeditor and add a systemd user service with an installer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:06:31 +13:00
jimmyandClaude Opus 5.5 647cfa3a75 Group scripts into pad/, shows/ and anim/ folders.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:54:36 +13:00
jimmyandClaude Opus 5.5 5f593b973c Move the SMC-PAD packet captures into captures/.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:46:01 +13:00
jimmyandCursor f4b927e0cb Update the open mic knob diagram.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 9d1d254e39 Add the Temple of Techno show for fifteen cans and four movers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 97ce89fcbd Add a simple show for eight BT270 pars.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 185d885e39 Add the Flow Forum show and its colour cues.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 68f8e1913d Add the Ludi show for the eight cans and two Small Eyes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 4b53f506e9 Repatch the default show onto fifteen cans and four movers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 10c39015b7 Preview open-mic colour on the rig and save it back to the pad.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor c9df537567 Set SMC-PAD colours over the pad's existing Bluetooth link.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor b1181e6f28 Edit mover patterns from the SMC-PAD and save the corner aims.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 1b181640dd Start twisted in all-colour-1 and let pad 1 wander the movers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 9f40933227 Drive the twisted cans and movers from the SMC-PAD over Art-Net.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor dc05192a25 Keep each mover's pan and tilt when the shared SMC-PAD knobs turn.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 7317bcb486 Rebuild the cabaret virtual console for the current patch and mover looks.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 1a4e51e449 Aim the cabaret movers from a page and keep the named positions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 6c5223eec5 Drive the two cabaret Small Eyes over Art-Net without QLC+.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor 7ff1519abc Put Small Eye lens rotate on channel 6 and zoom on channel 7.
The glass only spins with focus at full, so the chase scenes and the channel test follow the real map.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 15:53:22 +13:00
jimmyandCursor c72a8d6f26 Find MidiSuite's SMC-PAD save method without talking to the pad.
The Windows app builds the flash save when it runs, so the script reads that build and reports the method instead of guessing a packet.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 20:36:57 +13:00
jimmyandCursor 97d4449a86 Save the open mic levels and split can brightness into sides and centre.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:53:07 +13:00
jimmy 084f77c840 Merge remote main before pushing the open mic show. 2026-10-19 19:20:03 +13:00
jimmyandCursor ab364601ce Add the open mic show for the front movers and floor cans.
SMC-PAD knobs drive aim, focus, and brightness, floor fixtures sit on the gateway universe, and the Small Eye map matches the channels the show writes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:19:37 +13:00
137 changed files with 35086 additions and 8728 deletions

No files matched your search

+14 -2
View File
@@ -2,10 +2,22 @@
"version": "0.0.1",
"configurations": [
{
"name": "padeditor",
"name": "padcontroller",
"runtimeExecutable": ".venv/bin/python",
"runtimeArgs": ["-m", "padeditor", "--no-browser"],
"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
}
]
}
+51
View File
@@ -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.
+4 -4
View File
@@ -8,12 +8,12 @@ mido = "*"
python-rtmidi = "*"
[dev-packages]
pytest = "*"
[requires]
python_version = "3.12"
[scripts]
positions = "python scripts/position_movers.py"
pattern = "python -m pattern_pad"
midi = "python scripts/midi.py"
padeditor = "python -m padeditor"
midi = "python scripts/pad/midi.py"
padcontroller-midi = "python -m padcontroller.midi"
padcontroller = "python -m padcontroller"
Generated
+44 -2
View File
@@ -1,7 +1,7 @@
{
"_meta": {
"hash": {
"sha256": "2d3b4d17f2edcaf6aca89b25728de94c131f89c846aebf67a8c6ec4981497791"
"sha256": "42b99998dcced8eeecfc0b83f3589f113501d6245312302009027c9a91e11fa6"
},
"pipfile-spec": 6,
"requires": {
@@ -67,5 +67,47 @@
"version": "==1.5.8"
}
},
"develop": {}
"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"
}
}
}
+84 -10
View File
@@ -7,18 +7,30 @@ QLC+ show files, fixture definitions, and generators for the XCHC stage
```
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/ Generators / patchers for the shows
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`
@@ -26,16 +38,16 @@ tests/ Art-Net / fixture helpers used by scripts
```bash
# Rebuild simple manual board
python3 scripts/make_simple_vc.py
python3 scripts/shows/make_simple_vc.py
# Rewrite can/mover patterns from stage layout
python3 scripts/integrate_u_patterns.py
python3 scripts/shows/integrate_u_patterns.py
# Unify Patterns + Movers into one Show frame
python3 scripts/unify_vc.py
python3 scripts/shows/unify_vc.py
# Figure-of-8 (live Art-Net or write/merge workspace)
python3 scripts/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/shows/figure8_small_eye.py --write-qxw shows/small_eye.qxw
```
## Fixtures / DMX
@@ -48,20 +60,82 @@ python3 scripts/figure8_small_eye.py --write-qxw shows/small_eye.qxw
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/make_chataigne.py` turns a show spec into a Chataigne project, so the
`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/make_chataigne.py shows/test.show.json chataigne/test
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 `pad_layer.py` does for
QLC+, with no knob smoothing, so `smooth_smc_pad.py` is not needed. Set the lamps with
`scripts/pad_lamps.py`. The **Lights** (DMX) module sends Art-Net to the
`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
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
+6 -6
View File
@@ -1,7 +1,7 @@
// Pads pick colours, sliders mix a custom colour, like the QLC+ virtual console.
// It reads the pad directly: Play shifts bank 2 here, as scripts/pad_layer.py does
// 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/make_chataigne.py: edit this template, not the output.
// 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.
@@ -11,7 +11,7 @@
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 pad_layer.py
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;
@@ -40,7 +40,7 @@ function init()
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] = 0;
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.
@@ -54,7 +54,7 @@ function init()
}
for (var r = 0; r < group.sliders.length; r++)
{
sliderParams[g][r] = script.addFloatParameter(group.sliders[r].id, group.name + " " + group.sliders[r].name, 0, 0, 1);
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", "");
+50 -48
View File
@@ -1,7 +1,7 @@
// Pads pick colours, sliders mix a custom colour, like the QLC+ virtual console.
// It reads the pad directly: Play shifts bank 2 here, as scripts/pad_layer.py does
// 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/make_chataigne.py: edit this template, not the output.
// 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.
@@ -11,58 +11,60 @@ 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: [88,255,90,255,91,0,92,0,93,0,96,255,98,255,99,0,100,0,101,0,104,255,106,255,107,0,108,0,109,0,112,255,114,255,115,0,116,0,117,0,120,255,122,255,123,0,124,0,125,0,128,255,130,255,131,0,132,0,133,0,136,255,138,255,139,0,140,0,141,0,144,255,146,255,147,0,148,0,149,0,152,255,154,255,155,0,156,0,157,0,160,255,162,255,163,0,164,0,165,0,168,255,170,255,171,0,172,0,173,0,176,255,178,255,179,0,180,0,181,0,184,255,186,255,187,0,188,0,189,0,192,255,194,255,195,0,196,0,197,0,200,255,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: [88,255,90,255,91,127,92,0,93,0,96,255,98,255,99,127,100,0,101,0,104,255,106,255,107,127,108,0,109,0,112,255,114,255,115,127,116,0,117,0,120,255,122,255,123,127,124,0,125,0,128,255,130,255,131,127,132,0,133,0,136,255,138,255,139,127,140,0,141,0,144,255,146,255,147,127,148,0,149,0,152,255,154,255,155,127,156,0,157,0,160,255,162,255,163,127,164,0,165,0,168,255,170,255,171,127,172,0,173,0,176,255,178,255,179,127,180,0,181,0,184,255,186,255,187,127,188,0,189,0,192,255,194,255,195,127,196,0,197,0,200,255,202,255,203,127,204,0,205,0]},
{id: "c1Yellow", rgb: [1.0, 1.0, 0.0], note: 54, name: "Yellow", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,255,92,0,93,0,96,255,98,255,99,255,100,0,101,0,104,255,106,255,107,255,108,0,109,0,112,255,114,255,115,255,116,0,117,0,120,255,122,255,123,255,124,0,125,0,128,255,130,255,131,255,132,0,133,0,136,255,138,255,139,255,140,0,141,0,144,255,146,255,147,255,148,0,149,0,152,255,154,255,155,255,156,0,157,0,160,255,162,255,163,255,164,0,165,0,168,255,170,255,171,255,172,0,173,0,176,255,178,255,179,255,180,0,181,0,184,255,186,255,187,255,188,0,189,0,192,255,194,255,195,255,196,0,197,0,200,255,202,255,203,255,204,0,205,0]},
{id: "c1Lime", rgb: [0.498, 1.0, 0.0], note: 55, name: "Lime", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,127,91,255,92,0,93,0,96,255,98,127,99,255,100,0,101,0,104,255,106,127,107,255,108,0,109,0,112,255,114,127,115,255,116,0,117,0,120,255,122,127,123,255,124,0,125,0,128,255,130,127,131,255,132,0,133,0,136,255,138,127,139,255,140,0,141,0,144,255,146,127,147,255,148,0,149,0,152,255,154,127,155,255,156,0,157,0,160,255,162,127,163,255,164,0,165,0,168,255,170,127,171,255,172,0,173,0,176,255,178,127,179,255,180,0,181,0,184,255,186,127,187,255,188,0,189,0,192,255,194,127,195,255,196,0,197,0,200,255,202,127,203,255,204,0,205,0]},
{id: "c1Green", rgb: [0.0, 1.0, 0.0], note: 56, name: "Green", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,255,92,0,93,0,96,255,98,0,99,255,100,0,101,0,104,255,106,0,107,255,108,0,109,0,112,255,114,0,115,255,116,0,117,0,120,255,122,0,123,255,124,0,125,0,128,255,130,0,131,255,132,0,133,0,136,255,138,0,139,255,140,0,141,0,144,255,146,0,147,255,148,0,149,0,152,255,154,0,155,255,156,0,157,0,160,255,162,0,163,255,164,0,165,0,168,255,170,0,171,255,172,0,173,0,176,255,178,0,179,255,180,0,181,0,184,255,186,0,187,255,188,0,189,0,192,255,194,0,195,255,196,0,197,0,200,255,202,0,203,255,204,0,205,0]},
{id: "c1Spring", rgb: [0.0, 1.0, 0.498], note: 57, name: "Spring", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,255,92,127,93,0,96,255,98,0,99,255,100,127,101,0,104,255,106,0,107,255,108,127,109,0,112,255,114,0,115,255,116,127,117,0,120,255,122,0,123,255,124,127,125,0,128,255,130,0,131,255,132,127,133,0,136,255,138,0,139,255,140,127,141,0,144,255,146,0,147,255,148,127,149,0,152,255,154,0,155,255,156,127,157,0,160,255,162,0,163,255,164,127,165,0,168,255,170,0,171,255,172,127,173,0,176,255,178,0,179,255,180,127,181,0,184,255,186,0,187,255,188,127,189,0,192,255,194,0,195,255,196,127,197,0,200,255,202,0,203,255,204,127,205,0]},
{id: "c1Cyan", rgb: [0.0, 1.0, 1.0], note: 58, name: "Cyan", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,255,92,255,93,0,96,255,98,0,99,255,100,255,101,0,104,255,106,0,107,255,108,255,109,0,112,255,114,0,115,255,116,255,117,0,120,255,122,0,123,255,124,255,125,0,128,255,130,0,131,255,132,255,133,0,136,255,138,0,139,255,140,255,141,0,144,255,146,0,147,255,148,255,149,0,152,255,154,0,155,255,156,255,157,0,160,255,162,0,163,255,164,255,165,0,168,255,170,0,171,255,172,255,173,0,176,255,178,0,179,255,180,255,181,0,184,255,186,0,187,255,188,255,189,0,192,255,194,0,195,255,196,255,197,0,200,255,202,0,203,255,204,255,205,0]},
{id: "c1Azure", rgb: [0.0, 0.498, 1.0], note: 59, name: "Azure", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,127,92,255,93,0,96,255,98,0,99,127,100,255,101,0,104,255,106,0,107,127,108,255,109,0,112,255,114,0,115,127,116,255,117,0,120,255,122,0,123,127,124,255,125,0,128,255,130,0,131,127,132,255,133,0,136,255,138,0,139,127,140,255,141,0,144,255,146,0,147,127,148,255,149,0,152,255,154,0,155,127,156,255,157,0,160,255,162,0,163,127,164,255,165,0,168,255,170,0,171,127,172,255,173,0,176,255,178,0,179,127,180,255,181,0,184,255,186,0,187,127,188,255,189,0,192,255,194,0,195,127,196,255,197,0,200,255,202,0,203,127,204,255,205,0]},
{id: "c1Blue", rgb: [0.0, 0.0, 1.0], note: 60, name: "Blue", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,0,92,255,93,0,96,255,98,0,99,0,100,255,101,0,104,255,106,0,107,0,108,255,109,0,112,255,114,0,115,0,116,255,117,0,120,255,122,0,123,0,124,255,125,0,128,255,130,0,131,0,132,255,133,0,136,255,138,0,139,0,140,255,141,0,144,255,146,0,147,0,148,255,149,0,152,255,154,0,155,0,156,255,157,0,160,255,162,0,163,0,164,255,165,0,168,255,170,0,171,0,172,255,173,0,176,255,178,0,179,0,180,255,181,0,184,255,186,0,187,0,188,255,189,0,192,255,194,0,195,0,196,255,197,0,200,255,202,0,203,0,204,255,205,0]},
{id: "c1Violet", rgb: [0.498, 0.0, 1.0], note: 61, name: "Violet", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,127,91,0,92,255,93,0,96,255,98,127,99,0,100,255,101,0,104,255,106,127,107,0,108,255,109,0,112,255,114,127,115,0,116,255,117,0,120,255,122,127,123,0,124,255,125,0,128,255,130,127,131,0,132,255,133,0,136,255,138,127,139,0,140,255,141,0,144,255,146,127,147,0,148,255,149,0,152,255,154,127,155,0,156,255,157,0,160,255,162,127,163,0,164,255,165,0,168,255,170,127,171,0,172,255,173,0,176,255,178,127,179,0,180,255,181,0,184,255,186,127,187,0,188,255,189,0,192,255,194,127,195,0,196,255,197,0,200,255,202,127,203,0,204,255,205,0]},
{id: "c1Magenta", rgb: [1.0, 0.0, 1.0], note: 62, name: "Magenta", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,0,92,255,93,0,96,255,98,255,99,0,100,255,101,0,104,255,106,255,107,0,108,255,109,0,112,255,114,255,115,0,116,255,117,0,120,255,122,255,123,0,124,255,125,0,128,255,130,255,131,0,132,255,133,0,136,255,138,255,139,0,140,255,141,0,144,255,146,255,147,0,148,255,149,0,152,255,154,255,155,0,156,255,157,0,160,255,162,255,163,0,164,255,165,0,168,255,170,255,171,0,172,255,173,0,176,255,178,255,179,0,180,255,181,0,184,255,186,255,187,0,188,255,189,0,192,255,194,255,195,0,196,255,197,0,200,255,202,255,203,0,204,255,205,0]},
{id: "c1Pink", rgb: [1.0, 0.157, 0.471], note: 63, name: "Pink", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,40,92,120,93,0,96,255,98,255,99,40,100,120,101,0,104,255,106,255,107,40,108,120,109,0,112,255,114,255,115,40,116,120,117,0,120,255,122,255,123,40,124,120,125,0,128,255,130,255,131,40,132,120,133,0,136,255,138,255,139,40,140,120,141,0,144,255,146,255,147,40,148,120,149,0,152,255,154,255,155,40,156,120,157,0,160,255,162,255,163,40,164,120,165,0,168,255,170,255,171,40,172,120,173,0,176,255,178,255,179,40,180,120,181,0,184,255,186,255,187,40,188,120,189,0,192,255,194,255,195,40,196,120,197,0,200,255,202,255,203,40,204,120,205,0]},
{id: "c1Warm", rgb: [1.0, 0.941, 0.627], note: 64, name: "Warm", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,120,92,40,93,120,96,255,98,255,99,120,100,40,101,120,104,255,106,255,107,120,108,40,109,120,112,255,114,255,115,120,116,40,117,120,120,255,122,255,123,120,124,40,125,120,128,255,130,255,131,120,132,40,133,120,136,255,138,255,139,120,140,40,141,120,144,255,146,255,147,120,148,40,149,120,152,255,154,255,155,120,156,40,157,120,160,255,162,255,163,120,164,40,165,120,168,255,170,255,171,120,172,40,173,120,176,255,178,255,179,120,180,40,181,120,184,255,186,255,187,120,188,40,189,120,192,255,194,255,195,120,196,40,197,120,200,255,202,255,203,120,204,40,205,120]},
{id: "c1White", rgb: [1.0, 1.0, 1.0], note: 65, name: "White", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,0,92,0,93,255,96,255,98,0,99,0,100,0,101,255,104,255,106,0,107,0,108,0,109,255,112,255,114,0,115,0,116,0,117,255,120,255,122,0,123,0,124,0,125,255,128,255,130,0,131,0,132,0,133,255,136,255,138,0,139,0,140,0,141,255,144,255,146,0,147,0,148,0,149,255,152,255,154,0,155,0,156,0,157,255,160,255,162,0,163,0,164,0,165,255,168,255,170,0,171,0,172,0,173,255,176,255,178,0,179,0,180,0,181,255,184,255,186,0,187,0,188,0,189,255,192,255,194,0,195,0,196,0,197,255,200,255,202,0,203,0,204,0,205,255]},
{id: "c1Cool", rgb: [0.784, 0.941, 1.0], note: 66, name: "Cool", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,80,91,120,92,255,93,120,96,255,98,80,99,120,100,255,101,120,104,255,106,80,107,120,108,255,109,120,112,255,114,80,115,120,116,255,117,120,120,255,122,80,123,120,124,255,125,120,128,255,130,80,131,120,132,255,133,120,136,255,138,80,139,120,140,255,141,120,144,255,146,80,147,120,148,255,149,120,152,255,154,80,155,120,156,255,157,120,160,255,162,80,163,120,164,255,165,120,168,255,170,80,171,120,172,255,173,120,176,255,178,80,179,120,180,255,181,120,184,255,186,80,187,120,188,255,189,120,192,255,194,80,195,120,196,255,197,120,200,255,202,80,203,120,204,255,205,120]},
{id: "c1Custom", rgb: [1.0, 0.235, 0.0], note: 67, name: "Custom", fadeIn: 1000, fadeOut: 1000, levels: [88,0,96,0,104,0,112,0,120,0,128,0,136,0,144,0,152,0,160,0,168,0,176,0,184,0,192,0,200,0]},
{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: [
{id: "s1Dim", cc: 30, name: "Dim", levels: [88,255,96,255,104,255,112,255,120,255,128,255,136,255,144,255,152,255,160,255,168,255,176,255,184,255,192,255,200,255]},
{id: "s1R", cc: 31, name: "R", levels: [90,255,98,255,106,255,114,255,122,255,130,255,138,255,146,255,154,255,162,255,170,255,178,255,186,255,194,255,202,255]},
{id: "s1G", cc: 32, name: "G", levels: [91,255,99,255,107,255,115,255,123,255,131,255,139,255,147,255,155,255,163,255,171,255,179,255,187,255,195,255,203,255]},
{id: "s1B", cc: 33, name: "B", levels: [92,255,100,255,108,255,116,255,124,255,132,255,140,255,148,255,156,255,164,255,172,255,180,255,188,255,196,255,204,255]},
{id: "s1W", cc: 34, name: "W", levels: [93,255,101,255,109,255,117,255,125,255,133,255,141,255,149,255,157,255,165,255,173,255,181,255,189,255,197,255,205,255]},
]
},
{
name: "Colour 2",
now: "now2",
pads: [
{id: "c2Red", rgb: [1.0, 0.0, 0.0], note: 68, name: "Red", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: [9,255,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,53,255,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,266,255,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,309,255,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: "c2Yellow", rgb: [1.0, 1.0, 0.0], note: 70, name: "Yellow", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 71, name: "Lime", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 72, name: "Green", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 73, name: "Spring", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 74, name: "Cyan", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 75, name: "Azure", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 76, name: "Blue", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 77, name: "Violet", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 78, name: "Magenta", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 79, name: "Pink", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 80, name: "Warm", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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: 81, name: "White", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,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,266,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,309,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: 82, name: "Cool", fadeIn: 1000, fadeOut: 1000, levels: [9,255,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,53,255,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,266,255,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,309,255,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]},
{id: "c2Custom", rgb: [1.0, 0.235, 0.0], note: 83, name: "Custom", fadeIn: 1000, fadeOut: 1000, levels: [9,0,53,0,266,0,309,0]},
{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: [
{id: "s2Dim", cc: 35, name: "Dim", levels: [9,255,53,255,266,255,309,255]},
{id: "s2R", cc: 36, name: "R", levels: [11,255,15,255,19,255,23,255,27,255,31,255,35,255,55,255,59,255,63,255,67,255,71,255,75,255,79,255,268,255,272,255,276,255,280,255,284,255,288,255,292,255,311,255,315,255,319,255,323,255,327,255,331,255,335,255]},
{id: "s2G", cc: 37, name: "G", levels: [12,255,16,255,20,255,24,255,28,255,32,255,36,255,56,255,60,255,64,255,68,255,72,255,76,255,80,255,269,255,273,255,277,255,281,255,285,255,289,255,293,255,312,255,316,255,320,255,324,255,328,255,332,255,336,255]},
{id: "s2B", cc: 38, name: "B", levels: [13,255,17,255,21,255,25,255,29,255,33,255,37,255,57,255,61,255,65,255,69,255,73,255,77,255,81,255,270,255,274,255,278,255,282,255,286,255,290,255,294,255,313,255,317,255,321,255,325,255,329,255,333,255,337,255]},
{id: "s2W", cc: 39, name: "W", levels: [14,255,18,255,22,255,26,255,30,255,34,255,38,255,58,255,62,255,66,255,70,255,74,255,78,255,82,255,271,255,275,255,279,255,283,255,287,255,291,255,295,255,314,255,318,255,322,255,326,255,330,255,334,255,338,255]},
]
},
{
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]},
]
},
];
@@ -70,7 +72,7 @@ var GROUPS = [
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 pad_layer.py
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;
@@ -99,7 +101,7 @@ function init()
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] = 0;
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.
@@ -113,7 +115,7 @@ function init()
}
for (var r = 0; r < group.sliders.length; r++)
{
sliderParams[g][r] = script.addFloatParameter(group.sliders[r].id, group.name + " " + group.sliders[r].name, 0, 0, 1);
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", "");
File diff suppressed because it is too large. Load diff
+13 -3
View File
@@ -15,7 +15,11 @@
<Channel Name="Tilt Fine" Preset="PositionTiltFine"/>
<Channel Name="Pan/Tilt Speed" Preset="SpeedPanTiltFastSlow"/>
<Channel Name="Zoom" Preset="BeamZoomSmallBig"/>
<Channel Name="Focus" Preset="BeamFocusNearFar"/>
<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>
@@ -28,9 +32,9 @@
<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</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</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>
@@ -232,6 +236,12 @@
<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>
+96
View File
@@ -73,4 +73,100 @@
<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>
+1
View File
@@ -0,0 +1 @@
"""Set SMC-PAD colours and preview them on the open mic fixtures."""
+61
View File
@@ -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())
+338
View File
@@ -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)
+125
View File
@@ -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()
+34
View File
@@ -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; }
+110
View File
@@ -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();
+31
View File
@@ -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>
+1
View File
@@ -0,0 +1 @@
"""Pad Controller: the SMC-PAD preset editor and MIDI intercept."""
@@ -1,4 +1,4 @@
"""python3 -m padeditor [--port 8770]"""
"""python3 -m padcontroller [--port 8770]"""
from __future__ import annotations
@@ -6,18 +6,18 @@ import argparse
import threading
import webbrowser
from padeditor.server import make_server
from padcontroller.server import make_server
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="padeditor", description="SMC-PAD preset editor")
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"SMC-PAD editor → {url} Ctrl+C to quit")
print(f"Pad Controller → {url} Ctrl+C to quit")
if not args.no_browser:
threading.Timer(0.4, webbrowser.open, args=(url,)).start()
try:
+15 -11
View File
@@ -13,8 +13,8 @@ import sys
import time
from pathlib import Path
from padeditor.preset import GLOBAL_LEN, IMAGE_LEN, changed_ranges
from padeditor.sysex import (
from padcontroller.preset import GLOBAL_LEN, IMAGE_LEN, changed_ranges
from padcontroller.sysex import (
CMD_READ,
MEM_GLOBAL,
MEM_PRESET,
@@ -84,7 +84,7 @@ def transact(midiout, midiin, message: list[int], timeout: float = 0.8, expect:
def decode_body(raw: bytes) -> bytes:
from padeditor.sysex import decode
from padcontroller.sysex import decode
return decode(raw[1:-1])
@@ -96,11 +96,15 @@ class Link:
rtmidi = load_rtmidi()
self.midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA)
self.midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
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)
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):
@@ -182,7 +186,7 @@ def read_global(link: Link | None = None) -> bytes:
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 padeditor.preset import GLOBAL_BANK
from padcontroller.preset import GLOBAL_BANK
if bank not in (0, 1):
raise PadError("pad bank must be 0 or 1")
@@ -235,7 +239,7 @@ def save_image(desired: bytes, link: Link | None = None, settings: bytes | None
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 padeditor.preset import colour_offset
from padcontroller.preset import colour_offset
if len(rgb) != 3:
raise PadError("a pad colour needs red, green, and blue")
@@ -270,7 +274,7 @@ def probe_relative(listen: float = 2.5) -> str:
when a turn of that knob sends a step, ``absolute`` when it sends a
running value, or ``silent`` when nothing arrives.
"""
from padeditor.preset import KNOB_AT, KNOB_COUNT, KNOB_LEN, PRESET_COUNT, PRESET_LEN, RELATIVE_TYPE
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)]
File renamed without changes.
+153
View File
@@ -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]]
+324
View File
@@ -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()
File renamed without changes.
@@ -10,8 +10,8 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse
from padeditor.device import Link, PadError, connected, read_global, read_image, save_image, set_bank, write_colour
from padeditor.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global
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.
File renamed without changes.
@@ -3,12 +3,12 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SMC-PAD editor</title>
<title>Pad Controller</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header>
<h1>SMC-PAD</h1>
<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>
File renamed without changes.
File renamed without changes.
+55
View File
@@ -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
+154
View File
@@ -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()
-1
View File
@@ -1 +0,0 @@
"""SMC-PAD preset editor."""
+1
View File
@@ -0,0 +1 @@
"""Web editor for mover patterns, driven by the SMC-PAD and the page."""
+73
View File
@@ -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())
+386
View File
@@ -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
+141
View File
@@ -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()
+53
View File
@@ -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; }
+127
View File
@@ -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();
+53
View File
@@ -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>
+68
View File
@@ -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;
}
)();
+45
View File
@@ -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;
}
)();
@@ -3,12 +3,12 @@
Dry run (prints DMX samples, sends nothing):
python3 scripts/anim_eight.py
python3 -m showfile run scripts/anim_eight.py --seconds 1
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_eight.py --ip 127.0.0.1 --seconds 8
python3 scripts/anim/anim_eight.py --ip 127.0.0.1 --seconds 8
"""
from __future__ import annotations
@@ -16,7 +16,7 @@ from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
@@ -5,12 +5,12 @@ The patch, positions, and channel names come from stage/map.json.
Dry run (prints DMX samples, sends nothing):
python3 scripts/anim_stage.py
python3 -m showfile run scripts/anim_stage.py --seconds 1
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_stage.py --ip 127.0.0.1 --seconds 12
python3 scripts/anim/anim_stage.py --ip 127.0.0.1 --seconds 12
"""
from __future__ import annotations
@@ -18,7 +18,7 @@ from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
+648
View File
@@ -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()
+130
View File
@@ -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())
+30
View File
@@ -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
-837
View File
@@ -1,837 +0,0 @@
#!/usr/bin/env python3
"""Generate shows/cabaret.qxw — grouped can RGB + per-mover position and RGB."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "shows" / "cabaret.qxw"
M1, M2 = 8, 9
# Can groups: 1-2 | 3-4-5-6 | 7-8
GROUP_L = [0, 1]
GROUP_C = [2, 3, 4, 5]
GROUP_R = [6, 7]
# Can 8ch: Dim=0, R=2, G=3, B=4
# Mover 43ch: Pan/Tilt Speed=4, Focus=7, Center Bright=8; RGB heads 1–7
MOVER_SPEED = 4
MOVER_FOCUS = 7
MOVER_DIM = 8
MOVER_R = [10, 14, 18, 22, 26, 30, 34]
MOVER_G = [11, 15, 19, 23, 27, 31, 35]
MOVER_B = [12, 16, 20, 24, 28, 32, 36]
FOCUS_DEFAULT = 70
CANS = list(range(8))
PALETTE: dict[str, tuple[int, int, int]] = {
"Amber": (255, 90, 0),
"Pink": (255, 50, 160),
"HotBlue": (round(0.30 * 255), 0, 255), # 30% red, 100% blue
"Red": (255, 0, 0),
"Green": (0, 255, 0),
"Blue": (0, 0, 255),
"Orange": (255, 127, 0),
"Yellow": (255, 255, 0),
"Purple": (127, 0, 255),
}
CAN_ODD = [0, 2, 4, 6] # #1,3,5,7
CAN_EVEN = [1, 3, 5, 7] # #2,4,6,8
MOVER_SOLIDS = [
"Amber",
"Pink",
"Red",
"Green",
"Blue",
"Orange",
"Yellow",
"Purple",
]
# Pad display values. M2 (left) is hung 180°, so its pad pan is reversed:
# DMX pan = 255 - pad pan. M1 pad pan is DMX pan.
PAD_PAN = {M2: 181, M1: 80}
PAD_TILT = {M2: 145, M1: 161}
POSITION_FADE_MS = 2000
# name, M1 (pan, tilt), M2 (pan, tilt), button colour
# Same DMX pan = split (180° hang). Cross left was mirrored (108) = 180° out.
# Now = live pad aim (M2 pad 181/145 → DMX 74/145, M1 pad 80/161).
POSITIONS: list[tuple[str, tuple[int, int], tuple[int, int], str]] = [
("Now", (80, 161), (74, 145), "4278236360"),
("Here", (179, 0), (179, 0), "4282664004"),
("Down", (179, 36), (179, 36), "4284900966"),
("Mid", (164, 18), (144, 18), "4286611584"),
("Cross", (140, 26), (140, 26), "4281545523"),
("Out", (200, 22), (200, 22), "4279900698"),
]
POSITION_FUNC0 = 100
PADS_FUNC = POSITION_FUNC0 + len(POSITIONS)
PADS_BG = "4282800750" # #465A6E pad grey-blue
FIGURE8_FLOOR_FUNC = 110
FIGURE8_WALL_FUNC = 111
FIGURE8_MS = 12000
FIGURE8_FLOOR_BG = "4282664004"
FIGURE8_WALL_BG = "4286611584"
LOOK_PAIRS: list[tuple[str, str | None]] = [
("Amber", None),
("Pink", "Amber"),
("Pink", "HotBlue"),
("Red", "Green"),
("Blue", "Green"),
("Blue", "Red"),
("Orange", "Blue"),
("Yellow", "Purple"),
]
def color_label(name: str) -> str:
return "Blue" if name == "HotBlue" else name
def qlc_color(r: int, g: int, b: int) -> str:
return str((0xFF << 24) | (r << 16) | (g << 8) | b)
def mix_color(
a: tuple[int, int, int], b: tuple[int, int, int]
) -> tuple[int, int, int]:
return ((a[0] + b[0]) // 2, (a[1] + b[1]) // 2, (a[2] + b[2]) // 2)
RGB = [
("R", 2, MOVER_R, "4294901760", "Red"),
("G", 3, MOVER_G, "4278255360", "Green"),
("B", 4, MOVER_B, "4278190335", "Blue"),
]
def appearance(
fg: str = "Default",
bg: str = "Default",
frame: str = "Sunken",
) -> str:
return f""" <Appearance>
<FrameStyle>{frame}</FrameStyle>
<ForegroundColor>{fg}</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>"""
def slider(
wid: int,
caption: str,
x: int,
y: int,
w: int,
h: int,
channels: list[tuple[int, int]],
*,
value: int = 0,
fg: str = "Default",
cng: str = "None",
inverted: bool = False,
) -> str:
ch_xml = "\n".join(
f' <Channel Fixture="{fid}">{ch}</Channel>' for fid, ch in channels
)
inv = "true" if inverted else "false"
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="{inv}">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
{appearance(fg=fg)}
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="{value}">
{ch_xml}
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>"""
def xypad(
wid: int,
caption: str,
fid: int,
x: int,
y: int,
w: int,
h: int,
*,
reverse_pan: bool = False,
reverse_tilt: bool = False,
pan: int = 128,
tilt: int = 128,
) -> str:
pan_rev = "True" if reverse_pan else "False"
tilt_rev = "True" if reverse_tilt else "False"
return f""" <XYPad Caption="{caption}" ID="{wid}" InvertedAppearance="0">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
{appearance()}
<Fixture ID="{fid}" Head="0">
<Axis ID="X" LowLimit="0" HighLimit="1" Reverse="{pan_rev}"/>
<Axis ID="Y" LowLimit="0" HighLimit="1" Reverse="{tilt_rev}"/>
</Fixture>
<Window hMin="0" hMax="255" vMin="0" vMax="255"/>
<Pan Position="{pan}"/>
<Tilt Position="{tilt}"/>
</XYPad>"""
def label_frame(wid: int, caption: str, x: int, y: int, w: int, h: int) -> str:
return f""" <Frame 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>
<ShowIntensityButton>False</ShowIntensityButton>
<Mixing>False</Mixing>
</Frame>"""
def button(
wid: int,
caption: str,
func_id: int,
x: int,
y: int,
w: int,
h: int,
bg: str,
fg: str = "4294967295",
*,
indent: str = " ",
) -> str:
inner = indent + " "
return f"""{indent}<Button Caption="{caption}" ID="{wid}" Icon="">
{inner}<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
{inner}<Appearance>
{inner} <FrameStyle>None</FrameStyle>
{inner} <ForegroundColor>{fg}</ForegroundColor>
{inner} <BackgroundColor>{bg}</BackgroundColor>
{inner} <BackgroundImage>None</BackgroundImage>
{inner} <Font>Default</Font>
{inner}</Appearance>
{inner}<Function ID="{func_id}"/>
{inner}<Action>Toggle</Action>
{inner}<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 can_fixture_val(fid: int, r: int, g: int, b: int) -> str:
# Dimmer is owned by the Can Bright slider (HTP).
return (
f' <FixtureVal ID="{fid}">'
f"1,0,2,{r},3,{g},4,{b},5,0,6,0,7,0"
f"</FixtureVal>"
)
def mover_fixture_val(fid: int, r: int, g: int, b: int) -> str:
# Dimmer is owned by the Mover Bright slider (HTP).
parts: list[int] = []
for i in range(7):
base = 10 + i * 4
parts.extend([base, r, base + 1, g, base + 2, b, base + 3, 0])
return f' <FixtureVal ID="{fid}">{",".join(str(x) for x in parts)}</FixtureVal>'
def look_scene_xml(
func_id: int,
name: str,
can_colors: dict[int, tuple[int, int, int]] | None = None,
mover_colors: dict[int, tuple[int, int, int]] | None = None,
) -> str:
vals: list[str] = []
if can_colors:
vals += [can_fixture_val(fid, *rgb) for fid, rgb in can_colors.items()]
if mover_colors:
vals += [mover_fixture_val(fid, *rgb) for fid, rgb in mover_colors.items()]
return f""" <Function ID="{func_id}" Type="Scene" Name="{name}">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
{chr(10).join(vals)}
</Function>"""
def look_caption(kind: str, left_n: str, right_n: str | None) -> str:
ll, rl = color_label(left_n), color_label(right_n or left_n)
if right_n is None:
return ll
if kind == "cans":
return f"1-4 {ll} 5-8 {rl}"
return f"Odd {ll} Even {rl}"
def look_values(
kind: str, left: tuple[int, int, int], right: tuple[int, int, int]
) -> tuple[dict[int, tuple[int, int, int]] | None, dict[int, tuple[int, int, int]] | None]:
if kind == "cans":
return {**{i: left for i in range(4)}, **{i: right for i in range(4, 8)}}, None
if kind == "cans_oe":
return {**{i: left for i in CAN_ODD}, **{i: right for i in CAN_EVEN}}, None
raise ValueError(kind)
def build_looks() -> tuple[str, dict[str, list[tuple[str, int, str]]]]:
specs: dict[str, list[tuple[str, int, str]]] = {
"cans": [],
"movers": [],
"cans_oe": [],
}
scenes: list[str] = []
func_id = 0
for kind in ("cans", "cans_oe"):
for left_n, right_n in LOOK_PAIRS:
if kind == "cans_oe" and right_n is None:
continue
left = PALETTE[left_n]
right = PALETTE[right_n] if right_n else left
cans, movers = look_values(kind, left, right)
if right_n is None:
cans = {fid: left for fid in CANS}
movers = None
ll, rl = color_label(left_n), color_label(right_n or left_n)
name = f"{kind} {ll}" if right_n is None else f"{kind} {ll} {rl}"
scenes.append(look_scene_xml(func_id, name, cans, movers))
bg = qlc_color(*left) if right_n is None else qlc_color(*mix_color(left, right))
specs[kind].append((look_caption(kind, left_n, right_n), func_id, bg))
func_id += 1
for color_n in MOVER_SOLIDS:
rgb = PALETTE[color_n]
label = color_label(color_n)
scenes.append(
look_scene_xml(
func_id,
f"movers {label}",
mover_colors={M1: rgb, M2: rgb},
)
)
specs["movers"].append((label, func_id, qlc_color(*rgb)))
func_id += 1
return "\n".join(scenes), specs
def look_scenes_xml() -> str:
xml, _ = build_looks()
return xml
def position_scene_xml() -> str:
blocks = [
f""" <Function ID="{PADS_FUNC}" Type="Scene" Name="Mover Pads">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
</Function>"""
]
for i, (name, m1, m2, _bg) in enumerate(POSITIONS):
poses = {M1: m1, M2: m2}
vals = []
for fid in (M1, M2):
pan, tilt = poses[fid]
vals.append(
f' <FixtureVal ID="{fid}">0,{pan},1,0,2,{tilt},3,0</FixtureVal>'
)
blocks.append(
f""" <Function ID="{POSITION_FUNC0 + i}" Type="Scene" Name="Mover {name}">
<Speed FadeIn="{POSITION_FADE_MS}" FadeOut="0" Duration="{POSITION_FADE_MS}"/>
{chr(10).join(vals)}
</Function>"""
)
return "\n".join(blocks)
def position_button_specs() -> list[tuple[str, int, str]]:
return (
[("Pads", PADS_FUNC, PADS_BG)]
+ [
(name, POSITION_FUNC0 + i, bg)
for i, (name, _m1, _m2, bg) in enumerate(POSITIONS)
]
+ [
("Floor 8", FIGURE8_FLOOR_FUNC, FIGURE8_FLOOR_BG),
("Wall 8", FIGURE8_WALL_FUNC, FIGURE8_WALL_BG),
]
)
def figure8_floor_center() -> tuple[int, int]:
"""Now is the live floor aim; average both heads so the 8 stays on the ground."""
now = next((m1, m2) for name, m1, m2, _bg in POSITIONS if name == "Now")
pans = [now[0][0], now[1][0]]
tilts = [now[0][1], now[1][1]]
return (pans[0] + pans[1]) // 2, (tilts[0] + tilts[1]) // 2
def figure8_wall_bounds() -> tuple[int, int, int, int]:
"""Pan/tilt centre and amplitude covering Here–Out (the wall looks)."""
pans: list[int] = []
tilts: list[int] = []
for name, m1, m2, _bg in POSITIONS:
if name == "Now":
continue
for pan, tilt in (m1, m2):
pans.append(pan)
tilts.append(tilt)
p0, p1 = min(pans), max(pans)
t0, t1 = min(tilts), max(tilts)
return (p0 + p1) // 2, (t0 + t1) // 2, (p1 - p0) // 2, (t1 - t0) // 2
def figure8_efx_block(
func_id: int,
name: str,
width: int,
height: int,
rotation: int,
pan_c: int,
tilt_c: int,
) -> str:
fixtures = "\n".join(
f""" <Fixture>
<ID>{fid}</ID>
<Direction>Forward</Direction>
<Intensity>255</Intensity>
</Fixture>"""
for fid in (M1, M2)
)
return f""" <Function ID="{func_id}" Type="EFX" Name="{name}">
{fixtures}
<PropagationMode>Parallel</PropagationMode>
<Speed Duration="{FIGURE8_MS}" FadeOut="0" FadeIn="0"/>
<Direction>Forward</Direction>
<RunOrder>Loop</RunOrder>
<Algorithm>Eight</Algorithm>
<Width>{width}</Width>
<Height>{height}</Height>
<Rotation>{rotation}</Rotation>
<Axis Name="X">
<Offset>{pan_c}</Offset>
<Frequency>1</Frequency>
<Phase>0</Phase>
</Axis>
<Axis Name="Y">
<Offset>{tilt_c}</Offset>
<Frequency>1</Frequency>
<Phase>0</Phase>
</Axis>
</Function>"""
def figure8_efx_xml() -> str:
floor_pan, floor_tilt = figure8_floor_center()
wall_pan, wall_tilt, wall_pan_amp, wall_tilt_amp = figure8_wall_bounds()
# Floor 8: around Now, tilt stays on the ground. Rotation 90 = upright 8.
# Wall 8: Here–Out box (tilt 0–36). Rotation 0 = 8 across the wall.
return "\n".join(
[
figure8_efx_block(
FIGURE8_FLOOR_FUNC,
"Figure of 8 Floor",
16,
18,
90,
floor_pan,
floor_tilt,
),
figure8_efx_block(
FIGURE8_WALL_FUNC,
"Figure of 8 Walls",
wall_pan_amp,
wall_tilt_amp,
0,
wall_pan,
wall_tilt,
),
]
)
def fixture_xml() -> str:
parts = []
for i in range(8):
parts.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>{87 + i * 8}</Address>
<Channels>8</Channels>
</Fixture>"""
)
for i, addr in enumerate((0, 44)):
parts.append(
f""" <Fixture>
<Manufacturer>Small Eye 7</Manufacturer>
<Model>Mover</Model>
<Mode>43 Channel</Mode>
<ID>{8 + i}</ID>
<Name>Small Eye 7 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{addr}</Address>
<Channels>43</Channels>
</Fixture>"""
)
return "\n".join(parts)
def fixture_groups_xml() -> str:
def heads(fids: list[int]) -> str:
return "\n".join(
f' <Head X="{i}" Y="0" Fixture="{fid}">0</Head>'
for i, fid in enumerate(fids)
)
return f""" <FixtureGroup ID="0">
<Name>Cans 1-2</Name>
<Size X="2" Y="1"/>
{heads(GROUP_L)}
</FixtureGroup>
<FixtureGroup ID="1">
<Name>Cans 3-6</Name>
<Size X="4" Y="1"/>
{heads(GROUP_C)}
</FixtureGroup>
<FixtureGroup ID="2">
<Name>Cans 7-8</Name>
<Size X="2" Y="1"/>
{heads(GROUP_R)}
</FixtureGroup>
<FixtureGroup ID="3">
<Name>Small Eye Movers</Name>
<Size X="2" Y="1"/>
<Head X="0" Y="0" Fixture="8">0</Head>
<Head X="1" Y="0" Fixture="9">0</Head>
</FixtureGroup>"""
def main() -> None:
pad_w, pad_h = 240, 240
sl_w, sl_h = 44, 240
gap = 8
block_gap = 28
widgets: list[str] = []
wid = 0
max_x = 0
max_y = 0
def place_slider(
caption, x, y, w, h, channels, value=0, fg="Default", cng="None", inverted=False
):
nonlocal wid, max_x, max_y
widgets.append(
slider(
wid,
caption,
x,
y,
w,
h,
channels,
value=value,
fg=fg,
cng=cng,
inverted=inverted,
)
)
wid += 1
max_x = max(max_x, x + w)
max_y = max(max_y, y + h)
def place_rgb_block(prefix: str, x: int, y: int, dim_chs, rgb_chs_for):
"""Dim + R G B. rgb_chs_for(name, can_ch, mover_chs) -> channel list."""
place_slider(
f"{prefix} Dim", x, y, sl_w, sl_h, dim_chs, 0, "4294967295"
)
x += sl_w + 2
for name, can_ch, mover_chs, fg, cng in RGB:
place_slider(
f"{prefix} {name}",
x,
y,
sl_w,
sl_h,
rgb_chs_for(name, can_ch, mover_chs),
fg=fg,
cng=cng,
)
x += sl_w + 2
return x
def place_mover(prefix: str, fid: int, x: int, y: int, *, reverse_pan: bool = False) -> int:
nonlocal wid, max_y
widgets.append(
xypad(
wid,
f"{prefix} Position",
fid,
x,
y,
pad_w,
pad_h,
reverse_pan=reverse_pan,
pan=PAD_PAN[fid],
tilt=PAD_TILT[fid],
)
)
wid += 1
max_y = max(max_y, y + pad_h)
return x + pad_w + gap
def place_looks(
title: str,
looks: list[tuple[str, int, str]],
x: int,
y: int,
*,
cols: int = 2,
btn_w: int = 156,
) -> int:
nonlocal wid, max_x, max_y
header_h = 28
pad = 4
gap_x, gap_y = 6, 6
n = len(looks)
cols = max(1, min(cols, n))
rows = max(1, (n + cols - 1) // cols)
frame_w = pad * 2 + cols * btn_w + (cols - 1) * gap_x
frame_h = header_h + sl_h
inner_h = sl_h - pad
btn_h = (inner_h - gap_y * (rows - 1)) // rows
look_btns = []
frame_id = wid
wid += 1
for i, (caption, func_id, bg) in enumerate(looks):
col, row = i % cols, i // cols
look_btns.append(
button(
wid,
caption,
func_id,
pad + col * (btn_w + gap_x),
header_h + pad + row * (btn_h + gap_y),
btn_w,
btn_h,
bg,
indent=" ",
)
)
wid += 1
widgets.append(
solo_frame(
frame_id,
title,
x,
y - header_h,
frame_w,
frame_h,
"\n".join(look_btns),
)
)
max_x = max(max_x, x + frame_w)
max_y = max(max_y, y - header_h + frame_h)
return x + frame_w
_, look_specs = build_looks()
y0 = 28
x = 10
# M2 on the left, M1 on the right. Left unit is hung opposite, so pan is reversed.
x = place_mover("M2", M2, x, y0, reverse_pan=True)
x += block_gap
x = place_mover("M1", M1, x, y0)
x += block_gap
place_slider(
"M Bright",
x,
y0,
sl_w,
sl_h,
[(M1, MOVER_DIM), (M2, MOVER_DIM)],
255,
"4294967295",
)
x += sl_w + 2
place_slider(
"M Focus",
x,
y0,
sl_w,
sl_h,
[(M1, MOVER_FOCUS), (M2, MOVER_FOCUS)],
FOCUS_DEFAULT,
"4294902015",
)
x += sl_w + 2
place_slider(
"Speed",
x,
y0,
sl_w,
sl_h,
[(M1, MOVER_SPEED), (M2, MOVER_SPEED)],
0,
"4294967295",
inverted=True,
)
x += sl_w + 2
for name, _can_ch, mover_chs, fg, cng in RGB:
place_slider(
f"M {name}",
x,
y0,
sl_w,
sl_h,
[(fid, c) for fid in (M1, M2) for c in mover_chs],
fg=fg,
cng=cng,
)
x += sl_w + 2
x += block_gap - 2
x = place_looks(
"Position",
position_button_specs(),
x,
y0,
cols=2,
btn_w=72,
)
x += block_gap
x = place_looks("Movers", look_specs["movers"], x, y0)
y1 = y0 + pad_h + 40
x = 10
groups = [
("1-2", GROUP_L),
("3-6", GROUP_C),
("7-8", GROUP_R),
]
for label, fids in groups:
block_w = 4 * sl_w + 3 * 2
widgets.append(label_frame(wid, f"Cans {label}", x, y1 - 28, block_w, 24))
wid += 1
x = place_rgb_block(
label,
x,
y1,
[(f, 0) for f in fids],
lambda _n, can_ch, _m, fids=fids: [(f, can_ch) for f in fids],
)
x += block_gap
place_slider(
"C Bright",
x,
y1,
sl_w,
sl_h,
[(f, 0) for f in CANS],
255,
"4294967295",
)
x += sl_w + 2
place_slider(
"C Color",
x,
y1,
sl_w,
sl_h,
[(f, ch) for f in CANS for ch in (2, 3, 4)],
0,
"4294967295",
"RGB",
)
x += sl_w + block_gap
x = place_looks("Cans", look_specs["cans"], x, y1)
x += block_gap
place_looks("Cans Odd/Even", look_specs["cans_oe"], x, y1)
total_w = max_x + 16
total_h = max_y + 16
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>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
<Output Plugin="ArtNet" UID="192.168.1.92" Line="7">
<PluginParameters outputIP="192.168.1.228" outputUni="0"/>
</Output>
</Universe>
<Universe Name="Universe 2" ID="1"/>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
{fixture_xml()}
{fixture_groups_xml()}
{look_scenes_xml()}
{position_scene_xml()}
{figure8_efx_xml()}
</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()
+953
View File
@@ -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()
+215
View File
@@ -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()
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""Print the SMC-PAD SysEx in a usbmon capture.
sudo tcpdump -i usbmon1 -s 0 -U -w - > pad.pcap
python3 scripts/decode_usbmon.py pad.pcap --device 21
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.
@@ -15,10 +15,10 @@ import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
from padeditor.sysex import decode # noqa: E402
from padcontroller.sysex import decode # noqa: E402
LINKTYPE_USB_LINUX_MMAPPED = 220
HEADER = struct.Struct("<QBBBBHBBqiiIIQiiII") # 64 bytes
+2 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Print SMC-PAD pad and knob numbers.
pipenv run python scripts/midi.py
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).
@@ -18,7 +18,7 @@ from pathlib import Path
import mido
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
MAP_PATH = ROOT / "shows" / "midi_map.json"
# (channel, note) -> pad number. Loaded from shows/midi_map.json.
@@ -5,11 +5,11 @@ 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_colours.py --xchc --bank 2
.venv/bin/python scripts/pad_colours.py --colour-set --bank 2
.venv/bin/python scripts/pad_colours.py --dry-run
.venv/bin/python scripts/pad_colours.py --clear
.venv/bin/python scripts/pad_colours.py --identify
.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.
@@ -27,16 +27,16 @@ import glob
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts"))
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
from patch_smc_pad import PAD_COLORS # noqa: E402
from padeditor import preset # noqa: E402
from padeditor.device import PadError, read_image, save_image, transact # noqa: E402
from padeditor.device import private_port as _private_port # noqa: E402
from padeditor.preset import scale # noqa: E402
from padeditor.sysex import ( # 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,
@@ -120,6 +120,7 @@ def xchc_colours(clear: bool = False) -> list[tuple[str, bytes]]:
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 = []
@@ -1,9 +1,9 @@
#!/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_lamps.py
.venv/bin/python scripts/pad/pad_lamps.py
Needs the USB Private port. smooth_smc_pad.py does this on start; run this
Needs the USB Private port. padcontroller.midi does this on start; run this
when the pad is read by Chataigne instead.
"""
@@ -12,13 +12,13 @@ from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
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"))
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
import pad_colours
try:
@@ -8,7 +8,7 @@ import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
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"
@@ -75,13 +75,13 @@ PAD_COLORS = [
def detect_midi_uid() -> str:
"""Prefer smoothed virtual port when the smoother daemon is running."""
"""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 (
"SMC-PAD Smooth",
"padcontroller",
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
+75
View File
@@ -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)."
-64
View File
@@ -1,64 +0,0 @@
"""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.
With lock_knobs, knobs 1–5 (CC 30–34) drive colour 1's sliders and knobs 6–10
(CC 35–39) drive colour 2's, but only after the Custom pad (note 67, or 83
with Play held) has been pressed. Pressing any other bank 2 pad locks them
again, and its sliders are sent back to zero so their scenes stop.
Locked knob turns are dropped.
"""
from __future__ import annotations
PLAY_CC = 27
FIRST_NOTE = 52
LAST_NOTE = 67
SHIFT = 16
CUSTOM_NOTE = 67
KNOB_FIRST_CC = 30
KNOBS_PER_LAYER = 5
class PlayLayer:
def __init__(self, lock_knobs: bool = False) -> None:
self.lock_knobs = lock_knobs
self.unlocked: set[int] = set() # layers 0 and 1
self.held = False
# (channel, note as pressed) -> note sent, so a release matches its press
self.sent: dict[tuple[int, int], int] = {}
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 self.lock_knobs:
index = data[1] - KNOB_FIRST_CC
if 0 <= index < 2 * KNOBS_PER_LAYER and index // KNOBS_PER_LAYER not in self.unlocked:
return []
if kind not in (0x80, 0x90) or len(data) < 3:
return [list(data)]
note = data[1]
key = (channel, note)
is_on = kind == 0x90 and data[2] > 0
extra: list[list[int]] = []
if is_on and FIRST_NOTE <= note <= LAST_NOTE:
layer = 1 if self.held else 0
if note == CUSTOM_NOTE:
self.unlocked.add(layer)
elif layer in self.unlocked:
self.unlocked.discard(layer)
first = KNOB_FIRST_CC + layer * KNOBS_PER_LAYER
extra = [[0xB0, first + n, 0] for n in range(KNOBS_PER_LAYER)]
if is_on:
out = note + SHIFT if self.held and FIRST_NOTE <= note <= LAST_NOTE else note
self.sent[key] = out
else:
out = self.sent.pop(key, note)
return [[status, out, *data[2:]], *extra]
+997
View File
@@ -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()
+363
View File
@@ -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()
+106
View File
@@ -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()
@@ -4,15 +4,13 @@
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 smoother turns those notes into 68–83 while
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/colour_sets.py && python3 -m showfile write shows/test.show.json -o shows/test.qxw
The sliders are Playback sliders over five scenes per set (Dim, R, G, B, W),
so they never override a channel. Knobs 1–5 move colour 1's sliders and knobs
6–10 colour 2's. Run the smoother with --lock-knobs to make them work only
after the Custom pad is pressed; any other pad sends them back to zero (see
pad_layer.py).
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
@@ -20,23 +18,24 @@ from __future__ import annotations
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
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 # scripts/pad_layer.py sends bank 2 here while Play is held
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; colour 2's sliders follow colour 1's
PAD_PORT = "SMC-PAD Smooth" # scripts/smooth_smc_pad.py; it applies the Play layer
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),
@@ -51,10 +50,6 @@ COLOURS = (
("White", 0, 0, 0, 255),
("Cool", 80, 120, 255, 120),
)
# The top-right pad is the custom colour. Its button shows this swatch, but
# its scene is dark: the sliders next to it mix the colour from five scenes.
# Its pad lamp stays off.
CUSTOM = (("Custom", 255, 60, 0, 0),)
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.
@@ -65,41 +60,25 @@ 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)]
# Mixer beside each grid: caption, can channel, offset in a mover colour group (None is brightness).
SLIDERS = (
("Dim", DIMMER, None, [255, 255, 255]),
("R", RED, 0, [255, 0, 0]),
("G", GREEN, 1, [0, 255, 0]),
("B", BLUE, 2, [0, 0, 255]),
("W", WHITE, 3, [255, 255, 255]),
# 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 component(cans: list[str], movers: list[str], can_channel: int, offset: int | None) -> dict:
"""One channel kind of this set at full, for a Playback slider to scale."""
values = {can: {can_channel: 255} for can in cans}
for mover in movers:
if offset is None:
values[mover] = {MOVER_BRIGHTNESS: 255}
else:
values[mover] = {MOVER_FIRST_COLOUR + group * 4 + offset: 255 for group in range(MOVER_GROUPS)}
return values
def custom_off(cans: list[str], movers: list[str]) -> dict:
"""The Custom pad's own scene: dark, so the sliders' scenes set the colour."""
values = {can: {DIMMER: 0} for can in cans}
values.update({mover: {MOVER_BRIGHTNESS: 0} for mover in movers})
return values
def sliders(label: str, first_cc: int) -> list[dict]:
"""Playback sliders. Each scales its own scene, so nothing is overridden."""
return [{
"type": "slider", "caption": caption, "function": f"custom_{label}_{caption}",
"x": 400 + index * 52, "y": 10, "w": 48, "h": 200, "fg": fg,
"input": {"universe": 1, "cc": [0, first_cc + index]},
} for index, (caption, _can, _offset, fg) in enumerate(SLIDERS)]
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:
@@ -108,17 +87,14 @@ def main() -> None:
functions, frames = [], []
for si, (label, cans, movers) in enumerate((("1", CANS, []), ("2", [], MOVERS))):
buttons = []
for i, (name, r, g, b, w) in enumerate(COLOURS + CUSTOM):
for i, (name, r, g, b, w) in enumerate(COLOURS):
key = f"colour_{label}_{i + 1}"
on = 255
values = {can: {DIMMER: on, RED: r, GREEN: g, BLUE: b, WHITE: w} for can in cans}
values = {can: {RED: r, GREEN: g, BLUE: b, WHITE: w} for can in cans}
for mover in movers:
values[mover] = {MOVER_BRIGHTNESS: on, MOVER_STROBE: 0}
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})
if name == CUSTOM[0][0]:
values = custom_off(cans, movers)
functions.append({
"key": key, "type": "scene", "name": f"{label} {name}",
"fade_in": FADE_MS, "fade_out": FADE_MS, "values": values,
@@ -134,17 +110,12 @@ def main() -> None:
}
button["input"] = {"universe": 1, "note": [PAD_MIDI_CH, (HELD_FIRST_NOTE if si else PAD_BANK_2_FIRST_NOTE) + i]}
buttons.append(button)
for caption, can_channel, offset, _fg in SLIDERS:
functions.append({
"key": f"custom_{label}_{caption}", "type": "scene", "name": f"{label} Custom {caption}",
"values": component(cans, movers, can_channel, offset),
})
frames.append({
"type": "solo", "caption": f"Colour {label}", "x": 10, "y": 10 + si * 310,
"w": 400 + len(SLIDERS) * 52, "h": 300, "children": buttons + sliders(label, KNOB_FIRST_CC + si * len(SLIDERS)),
"w": 400, "h": 300, "children": buttons,
})
spec["functions"] = functions
spec["vc"] = frames
spec["vc"] = frames + [dimmers()]
SPEC.write_text(json.dumps(spec, indent=2) + "\n")
+188
View File
@@ -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()
+68
View File
@@ -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()
@@ -5,9 +5,9 @@ Traces QLC+'s Eight path (pan = -sin(2t), tilt = cos(t)), rides focus
with throw so the spot stays a similar size, and walks hue around the loop.
The whole 8 slowly drifts in a circle so it does not sit in one place.
python3 scripts/figure8_small_eye.py
python3 scripts/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/figure8_small_eye.py --merge-xchc shows/xchc.qxw
python3 scripts/shows/figure8_small_eye.py
python3 scripts/shows/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/shows/figure8_small_eye.py --merge-xchc shows/xchc.qxw
Stop QLC+ output before live mode so the two sources do not fight.
Quit live mode with Ctrl+C (sends blackout).
@@ -22,7 +22,7 @@ import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from test_small_eye import (
@@ -44,15 +44,15 @@ from test_small_eye import (
)
# Lens rotate: 0–127 index, 128–188 CCW spin, 189–193 stop, 194–255 CW spin.
# Mid CW — glass often only spins when zoom is fully narrow (0).
# Hardware limit: the glass spins only when Focus (channel 8) is at 255.
ROTATE_CW = 230
# 0-based QLC+ channel indices (same map as 43ch mode)
QLC_PAN = 0
QLC_TILT = 2
QLC_SPEED = 4
QLC_ZOOM = 5
QLC_ROTATE = 6
QLC_ROTATE = 5 # DMX channel 6
QLC_ZOOM = 6 # DMX channel 7
QLC_FOCUS = 7
QLC_DIMMER = 8
QLC_STROBE = 9
@@ -182,7 +182,7 @@ def monitor_xml() -> str:
def main():
path = Path(__file__).resolve().parents[1] / "shows" / "xchc.qxw"
path = Path(__file__).resolve().parents[2] / "shows" / "xchc.qxw"
text = path.read_text()
for i, (name, rgb) in enumerate(COLORS.items()):
+57
View File
@@ -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
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Write a Chataigne project from a show spec.
python3 scripts/make_chataigne.py shows/test.show.json chataigne/test
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
@@ -16,7 +16,7 @@ import struct
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
TEMPLATE = ROOT / "chataigne" / "show.template.js"
@@ -67,9 +67,13 @@ def collect(show: dict, stage: dict) -> dict:
pads, sliders = [], []
for widget in frame.get("children", []):
kind = widget["type"]
function = functions[widget["function"]]
binding = widget.get("input") or {}
levels = absolute_levels(show, stage, function["values"])
if "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"]),
@@ -81,12 +85,13 @@ def collect(show: dict, stage: dict) -> dict:
"fade": [function.get("fade_in") or 0, function.get("fade_out") or 0],
"levels": levels,
})
elif kind == "slider" and "cc" in binding:
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],
"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,
})
@@ -133,7 +138,7 @@ def render_data(groups: dict) -> str:
lines.append(" sliders: [")
for slider in group["sliders"]:
lines.append(
f" {{id: {json.dumps(slider['id'])}, cc: {slider['cc']}, name: {json.dumps(slider['name'])}, levels: {js_levels(slider['levels'])}}},"
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(" },")
+42
View File
@@ -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()
@@ -7,7 +7,7 @@ import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
+94
View File
@@ -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()
+87
View File
@@ -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()
+210
View File
@@ -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()
+64
View File
@@ -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()
+102
View File
@@ -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()
+57
View File
@@ -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()
+71
View File
@@ -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()
+70
View File
@@ -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()
+64
View File
@@ -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()
+64
View File
@@ -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()
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Add a Wander pad for the movers to shows/test.qxw, on note 93.
On the movers layer (Pause on), pad 10 toggles a slow relative EFX that drifts
all four movers around wherever the Pan and Tilt knobs (9 and 10, CC 38 and 39)
put them, so turning the knobs moves the middle of the wander:
93 Wander a Lissajous about ±30° of pan and ±10° of tilt, 22 s round
Each mover starts a quarter of the way further round, so they don't move as one.
It fades in over 2 s, so the movers ease off the knob position. QLC+ counts the
fade-in inside each 24 s round, which leaves 22 s. QLC+ 4.12 leaves
a relative EFX's last offset on the movers when it stops (with or without a
fade-out), so the pad controller nudges the two knobs when Wander goes off
(padcontroller/layer.py).
python3 scripts/shows/mover_wander.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 LEFT_TO_RIGHT, NO_FUNCTION, ROOT, button, note
SHOW = ROOT / "shows" / "test.qxw"
WIDTH, HEIGHT = 14, 10 # of 255 each way: 540° of pan, 270° of tilt
ROUND_MS = 24000
FADE_IN_MS = 2000
def efx(fid: int) -> str:
fixtures = "".join(f""" <Fixture>
<ID>{f}</ID>
<Head>0</Head>
<Mode>0</Mode>
<Direction>Forward</Direction>
<StartOffset>{90 * i}</StartOffset>
</Fixture>
""" for i, f in enumerate(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 wander">
{fixtures} <PropagationMode>Parallel</PropagationMode>
<Speed FadeIn="{FADE_IN_MS}" FadeOut="0" Duration="{ROUND_MS}"/>
<Direction>Forward</Direction>
<RunOrder>Loop</RunOrder>
<Algorithm>Lissajous</Algorithm>
<Width>{WIDTH}</Width>
<Height>{HEIGHT}</Height>
<Rotation>0</Rotation>
<StartOffset>0</StartOffset>
<IsRelative>1</IsRelative>
<Axis Name="X">
<Offset>127</Offset>
<Frequency>3</Frequency>
<Phase>90</Phase>
</Axis>
<Axis Name="Y">
<Offset>127</Offset>
<Frequency>2</Frequency>
<Phase>0</Phase>
</Axis>
</Function>
"""
def main() -> None:
xml = SHOW.read_text()
if 'Name="Movers wander"' in xml:
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the movers wander")
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 the movers' Strobe, where Strobe 2 sits on the cans' layer.
strobe = re.search(r' <Button Caption="Strobe" ID="89" Icon="">\n.*? </Button>\n', xml, re.S).group(0)
xml = xml.replace(strobe, strobe + button(wid, "Wander", 100, 100, 90, fid, note(45)), 1)
SHOW.write_text(xml)
print(f"Added the movers wander to {SHOW.relative_to(ROOT)} (function {fid}, widget {wid})")
if __name__ == "__main__":
main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Make the Colour 1 and Colour 2 buttons in shows/test.qxw square.
They were 90 wide and 60 high on a 96 by 66 grid. Now they are 75 square on an
81 grid, which keeps the 4 by 4 layout and makes each frame 338 wide and 338
high. The collapsed Chase runs frame, which sat just under Colour 2, moves down
to stay under it, and the Pads layer frame under that moves down to clear it;
the rest of the console stays where it is.
python3 scripts/shows/square_colours.py
It stops if the buttons are already square. 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"
FRAMES = ('<SoloFrame Caption="Colour 1" ID="0">', '<SoloFrame Caption="Colour 2" ID="22">')
SIZE, PITCH, MARGIN = 75, 81, 10
BOTTOM = 10 # below the last row
GAP = 5
COLLAPSED = 60 # room a collapsed frame takes, as the saved layout left it
# Below Colour 2, top to bottom: (caption, ID) of each frame pushed down to clear the one above
BELOW = (("Chase runs", 83), ("Pads layer", 129))
def main() -> None:
xml = SHOW.read_text()
for head in FRAMES:
start = xml.index(head)
end = xml.index("</SoloFrame>", start)
frame = xml[start:end]
spots = re.findall(r'( <WindowState Visible="True" X="(\d+)" Y="(\d+)" Width="(\d+)" Height="(\d+)"/>)', frame)
if len(spots) != 16:
raise SystemExit(f"{head} doesn't have its 16 buttons")
if all(w == h for _, _, _, w, h in spots):
raise SystemExit(f"The buttons in {head} are already square")
cols = sorted({int(x) for _, x, _, _, _ in spots})
rows = sorted({int(y) for _, _, y, _, _ in spots})
for line, x, y, _, _ in spots:
nx, ny = MARGIN + cols.index(int(x)) * PITCH, MARGIN + rows.index(int(y)) * PITCH
frame = frame.replace(line, f' <WindowState Visible="True" X="{nx}" Y="{ny}" Width="{SIZE}" Height="{SIZE}"/>', 1)
right = MARGIN + (len(cols) - 1) * PITCH + SIZE + MARGIN
bottom = MARGIN + (len(rows) - 1) * PITCH + SIZE + BOTTOM
frame = re.sub(r'( <WindowState Visible="True" X="\d+" Y="\d+") Width="\d+" Height="\d+"/>',
rf'\1 Width="{right}" Height="{bottom}"/>', frame, count=1)
xml = xml[:start] + frame + xml[end:]
# Push the frames under Colour 2 down to clear it, each under the last.
colour_2 = re.search(r'<SoloFrame Caption="Colour 2" ID="22">.*?<WindowState Visible="True" X="\d+" Y="(\d+)" '
r'Width="\d+" Height="(\d+)"/>', xml, re.S)
top = int(colour_2.group(1)) + int(colour_2.group(2)) + GAP
for caption, wid in BELOW:
m = re.search(rf'(<Frame Caption="{caption}" ID="{wid}">.*?<WindowState Visible="True" X="\d+" Y=")(\d+)'
rf'(" Width="\d+" Height=")(\d+)(".*?<Collapsed>)(\w+)', xml, re.S)
if m is None:
raise SystemExit(f"Couldn't find the {caption} frame")
y = max(int(m.group(2)), top)
xml = xml[:m.start(2)] + str(y) + xml[m.end(2):]
top = y + (COLLAPSED if m.group(6) == "True" else int(m.group(4))) + GAP
SHOW.write_text(xml)
print(f"Made the colour buttons in {SHOW.relative_to(ROOT)} square")
if __name__ == "__main__":
main()
@@ -33,7 +33,7 @@ def btn(
</Button>"""
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
def main():
+422
View File
@@ -0,0 +1,422 @@
#!/usr/bin/env python3
"""Set the colours of the SMC-PAD pads.
MidiSuite is not required. This talks to the pad over the Bluetooth
connection it already has.
python3 scripts/smc_pad.py
python3 scripts/smc_pad.py 1 blue 2 green 5 red
python3 scripts/smc_pad.py 1-4 blue 5-8 red --all off
python3 scripts/smc_pad.py --bank 8 1 ff8800
Pad 1 is the bottom-left pad. Numbers then go right, and the next row
starts at the left. A colour is a name (red, green, blue, yellow, cyan,
magenta, orange, white, off) or six hex digits, such as ff8800.
The colour shows straight away. It stays until the pad is switched off.
"""
from __future__ import annotations
import argparse
import queue
import sys
import threading
import time
from dataclasses import dataclass
PRESET_SIZE = 3539
PAD_BANKS = 8
PAD_COUNT = 16
PAD_RECORD_SIZE = 26
PAD_TABLE_OFFSET = 211
PAD_RGB_OFFSET = 5
PAD_LED_OFFSET = 8
LED_FOLLOWS_HOST = 0xFF
READ = 0x23
WRITE = 0x22
PRESET_REGION = 0x05
STATE_REGION = 0x04
ACK = bytes.fromhex("00590001000000ff")
STATE_BASE_BANK = 6
STATE_SLOT = 10
STATE_BANK_TOGGLE = 11
TOGGLE_BANK = 8
COLOURS = {
"off": (0x00, 0x00, 0x00),
"black": (0x00, 0x00, 0x00),
"red": (0xF0, 0x00, 0x00),
"green": (0x00, 0xF0, 0x00),
"blue": (0x00, 0x00, 0xF0),
"yellow": (0xF0, 0xF0, 0x00),
"cyan": (0x00, 0xF0, 0xF0),
"magenta": (0xF0, 0x00, 0xF0),
"orange": (0xF0, 0x60, 0x00),
"white": (0xF0, 0xF0, 0xF0),
}
# Top row first, so a printed grid matches the pad under your hands.
READING_ROWS = ((13, 14, 15, 16), (9, 10, 11, 12), (5, 6, 7, 8), (1, 2, 3, 4))
class PadError(Exception):
pass
def vendor_packet(command: int, region: int, address: int, data_or_count: bytes | int) -> bytes:
"""One read or write for the pad's configuration channel."""
if isinstance(data_or_count, int):
count, data = data_or_count, b""
else:
count, data = len(data_or_count), data_or_count
payload = bytes((region, *address.to_bytes(4, "little"), *count.to_bytes(3, "little"))) + data
checksum = (~sum(payload)) & 0xFF
return bytes((0x00, 0x59, command, *len(payload).to_bytes(3, "little"))) + payload + bytes((checksum,))
@dataclass(frozen=True)
class Reply:
command: int
region: int
address: int
data: bytes
checksum_ok: bool
def parse_reply(packet: bytes) -> Reply:
if len(packet) < 7 or packet[0] != 0x00 or packet[1] != 0x59:
raise PadError(f"unexpected reply {packet.hex()}")
command = packet[2]
length = int.from_bytes(packet[3:6], "little")
payload = packet[6 : 6 + length]
checksum_ok = len(packet) > 6 + length and (sum(payload) + packet[6 + length]) & 0xFF == 0xFF
if command in (READ, WRITE) and len(payload) >= 8:
count = int.from_bytes(payload[5:8], "little")
return Reply(
command,
payload[0],
int.from_bytes(payload[1:5], "little"),
payload[8 : 8 + count],
checksum_ok,
)
return Reply(command, 0, 0, payload, checksum_ok)
def bank_address(slot: int, bank: int) -> int:
if not 0 <= slot <= 7:
raise PadError(f"preset slot must be 0 to 7, got {slot}")
if not 1 <= bank <= PAD_BANKS:
raise PadError(f"bank must be 1 to {PAD_BANKS}, got {bank}")
return slot * PRESET_SIZE + PAD_TABLE_OFFSET + (bank - 1) * PAD_COUNT * PAD_RECORD_SIZE
def parse_state(block: bytes) -> tuple[int, int]:
"""Return the preset slot and the pad bank on display."""
if len(block) < 16:
raise PadError("state block is too short")
slot = block[STATE_SLOT]
base = block[STATE_BASE_BANK]
toggle = block[STATE_BANK_TOGGLE]
if not 0 <= slot <= 7 or not 0 <= base <= 7 or toggle not in (0, 1):
raise PadError(f"state block is not a preset display: {block.hex()}")
bank = TOGGLE_BANK if toggle else base + 1
return slot, bank
def colour_of(text: str) -> tuple[int, int, int]:
name = text.strip().lower()
if name in COLOURS:
return COLOURS[name]
hex_digits = name[1:] if name.startswith("#") else name
if len(hex_digits) == 6 and all(c in "0123456789abcdef" for c in hex_digits):
return tuple(int(hex_digits[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
known = ", ".join(name for name in COLOURS if name != "black")
raise PadError(f"unknown colour {text!r}. Use {known}, or six hex digits.")
def pad_numbers(text: str) -> list[int]:
"""'1', '1-4', and '1,3,5' all name pads."""
pads: list[int] = []
for part in text.split(","):
part = part.strip()
if not part:
continue
ends = part.split("-")
if len(ends) == 1:
pads.append(_one_pad(ends[0]))
elif len(ends) == 2:
first, last = _one_pad(ends[0]), _one_pad(ends[1])
step = 1 if last >= first else -1
pads.extend(range(first, last + step, step))
else:
raise PadError(f"bad pad range {text!r}")
if not pads:
raise PadError(f"bad pad {text!r}")
return pads
def _one_pad(text: str) -> int:
if not text.isdigit():
raise PadError(f"bad pad {text!r}")
number = int(text)
if not 1 <= number <= PAD_COUNT:
raise PadError(f"pad must be 1 to {PAD_COUNT}, got {number}")
return number
def colour_map(items: list[str], fill: str | None) -> dict[int, tuple[int, int, int]]:
"""Pairs of pad and colour. Later pairs win. ``fill`` paints every pad first."""
chosen: dict[int, tuple[int, int, int]] = {}
if fill is not None:
rgb = colour_of(fill)
chosen = {pad: rgb for pad in range(1, PAD_COUNT + 1)}
if len(items) % 2:
raise PadError("each pad needs a colour, for example: 1 blue 5 red")
for pad_text, colour_text in zip(items[0::2], items[1::2]):
rgb = colour_of(colour_text)
for pad in pad_numbers(pad_text):
chosen[pad] = rgb
return chosen
def rgb_at(bank: bytes, pad: int) -> tuple[int, int, int]:
start = (pad - 1) * PAD_RECORD_SIZE + PAD_RGB_OFFSET
return bank[start], bank[start + 1], bank[start + 2]
def led_at(bank: bytes, pad: int) -> int:
return bank[(pad - 1) * PAD_RECORD_SIZE + PAD_LED_OFFSET]
def paint(bank: bytes, colours: dict[int, tuple[int, int, int]]) -> bytearray:
painted = bytearray(bank)
for pad, rgb in colours.items():
start = (pad - 1) * PAD_RECORD_SIZE + PAD_RGB_OFFSET
painted[start : start + 3] = rgb
return painted
def format_colour(rgb: tuple[int, int, int]) -> str:
return "#{:02x}{:02x}{:02x}".format(*rgb)
def format_grid(bank: bytes) -> str:
lines = []
for row in READING_ROWS:
cells = []
for pad in row:
cells.append(f"{pad:2d} {format_colour(rgb_at(bank, pad))}")
lines.append(" ".join(cells))
return "\n".join(lines)
class PadLink:
"""BlueZ client for the pad's configuration characteristics."""
def __init__(self) -> None:
self._queue: queue.Queue[bytes | BaseException] = queue.Queue()
self._loop = None
self._notify = None
self._write = None
self._notify_path = ""
def __enter__(self) -> PadLink:
self.open()
return self
def __exit__(self, *_args: object) -> None:
self.close()
def open(self) -> None:
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
# Look up the pad before the GLib bus exists. On this machine a
# GLib connection does not list the configuration characteristics.
probe = dbus.SystemBus()
device = _find_device(probe, dbus)
write_path, notify_path = _find_channels(probe, dbus, device)
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus(private=True)
self._notify_path = notify_path
self._notify = dbus.Interface(bus.get_object("org.bluez", notify_path), "org.bluez.GattCharacteristic1")
self._write = dbus.Interface(bus.get_object("org.bluez", write_path), "org.bluez.GattCharacteristic1")
bus.add_signal_receiver(
self._on_value,
signal_name="PropertiesChanged",
dbus_interface="org.freedesktop.DBus.Properties",
path=notify_path,
)
self._loop = GLib.MainLoop()
threading.Thread(target=self._loop.run, daemon=True).start()
self._notify.StartNotify()
def close(self) -> None:
if self._notify is not None:
try:
self._notify.StopNotify()
except Exception:
pass
if self._loop is not None:
self._loop.quit()
def _on_value(self, _iface: str, changed: dict, _invalidated: list) -> None:
if "Value" in changed:
self._queue.put(bytes(changed["Value"]))
def request(self, packet: bytes) -> bytes:
from gi.repository import GLib
while not self._queue.empty():
self._queue.get_nowait()
def send() -> bool:
try:
import dbus
self._write.WriteValue(
dbus.Array(packet, signature="y"),
dbus.Dictionary({"type": "command"}, signature="sv"),
)
except Exception as exc:
self._queue.put(exc)
return False
GLib.idle_add(send)
try:
reply = self._queue.get(timeout=3)
except queue.Empty:
raise PadError("the pad did not answer") from None
if isinstance(reply, BaseException):
raise PadError(str(reply)) from reply
return reply
def read(self, address: int, count: int, region: int = PRESET_REGION) -> bytes:
raw = self.request(vendor_packet(READ, region, address, count))
reply = parse_reply(raw)
if reply.command != READ or not reply.checksum_ok:
raise PadError(f"bad read reply {raw.hex()}")
if reply.region != region or reply.address != address or len(reply.data) != count:
raise PadError(
f"read {region:#x}:{address:#x} returned {len(reply.data)} bytes "
f"from {reply.region:#x}:{reply.address:#x}"
)
return reply.data
def write(self, address: int, data: bytes, region: int = PRESET_REGION) -> None:
raw = self.request(vendor_packet(WRITE, region, address, data))
if raw != ACK:
reply = parse_reply(raw)
if not reply.checksum_ok:
raise PadError(f"the pad rejected the write: {raw.hex()}")
def _find_device(bus: object, dbus: object) -> str:
manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
found: list[tuple[bool, str]] = []
for path, ifaces in objects.items():
device = ifaces.get("org.bluez.Device1")
if not device:
continue
name = str(device.get("Name", "") or device.get("Alias", ""))
if "smc-pad" not in name.lower():
continue
found.append((bool(device.get("Connected", False)), str(path)))
if not found:
raise PadError("SMC-PAD not found. Turn it on, and pair it in Bluetooth settings.")
found.sort(reverse=True)
path = found[0][1]
device = dbus.Interface(bus.get_object("org.bluez", path), "org.bluez.Device1")
props = dbus.Interface(bus.get_object("org.bluez", path), "org.freedesktop.DBus.Properties")
if not bool(props.Get("org.bluez.Device1", "Connected")):
device.Connect()
deadline = time.time() + 8
while time.time() < deadline:
if bool(props.Get("org.bluez.Device1", "Connected")):
break
time.sleep(0.2)
else:
raise PadError("could not connect to the SMC-PAD")
return path
def _find_channels(bus: object, dbus: object, device: str) -> tuple[str, str]:
deadline = time.time() + 5
while True:
manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
write_path = notify_path = ""
for path, ifaces in objects.items():
if not str(path).startswith(device):
continue
char = ifaces.get("org.bluez.GattCharacteristic1")
if not char:
continue
uuid = str(char.get("UUID", "")).lower()
if uuid.startswith("0000ae41-"):
write_path = str(path)
elif uuid.startswith("0000ae42-"):
notify_path = str(path)
if write_path and notify_path:
return write_path, notify_path
if time.time() > deadline:
raise PadError("the pad is connected, but its configuration channel is missing")
time.sleep(0.2)
def showing(link: PadLink, preset: int | None, bank: int | None) -> tuple[int, int, bytes]:
slot, visible = parse_state(link.read(0, 16, STATE_REGION))
if preset is not None:
if not 1 <= preset <= 8:
raise PadError("preset must be 1 to 8")
slot = preset - 1
if bank is not None:
if not 1 <= bank <= PAD_BANKS:
raise PadError("bank must be 1 to 8")
visible = bank
image = link.read(bank_address(slot, visible), PAD_COUNT * PAD_RECORD_SIZE)
return slot, visible, image
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("items", nargs="*", help="pad colour pairs, such as 1 blue 5-8 red")
parser.add_argument("--all", metavar="COLOUR", help="paint every pad this colour first")
parser.add_argument("--bank", type=int, help="pad bank 1 to 8; the bank on display is the default")
parser.add_argument("--preset", type=int, help="preset 1 to 8; the preset on display is the default")
args = parser.parse_args(argv)
try:
colours = colour_map(args.items, args.all)
with PadLink() as link:
slot, bank, image = showing(link, args.preset, args.bank)
print(f"Preset {slot + 1}, bank {bank}. Pad 1 is the bottom-left pad.")
if not colours:
print(format_grid(image))
hidden = [pad for pad in range(1, PAD_COUNT + 1) if led_at(image, pad) != LED_FOLLOWS_HOST]
if hidden:
listed = ", ".join(str(pad) for pad in hidden)
print(f"Pads {listed} show incoming MIDI, so their stored colour stays hidden.")
return 0
updated = paint(image, colours)
if updated == image:
print(format_grid(image))
print("Those pads are already that colour.")
return 0
link.write(bank_address(slot, bank), bytes(updated))
print(format_grid(updated))
print("Saved on the pad until it is switched off.")
except PadError as exc:
print(exc, file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
-199
View File
@@ -1,199 +0,0 @@
#!/usr/bin/env python3
"""Smooth SMC-PAD knob CCs so RGBW fades feel less stepped.
Reads the physical pad (Bluetooth or USB), passes pad notes through
immediately, and eases Control Change values toward their targets at
~120 Hz before emitting on a virtual port named "SMC-PAD Smooth".
On start it also sets the pad lamps over USB (pad_colours.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 pad_layer.py).
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the smoother is running).
Usage:
.venv/bin/python scripts/smooth_smc_pad.py
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
"""
from __future__ import annotations
import argparse
import math
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
import glob
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
sys.path.insert(0, p)
import rtmidi
sys.path.insert(0, str(Path(__file__).resolve().parent))
from pad_lamps import set_lamps # noqa: E402
from pad_layer import PlayLayer # noqa: E402
VIRTUAL_NAME = "SMC-PAD Smooth"
SOURCE_HINTS = (
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
"SMC-PAD",
)
def find_source_port(midiin: rtmidi.MidiIn) -> int:
ports = midiin.get_ports()
for hint in SOURCE_HINTS:
for i, name in enumerate(ports):
if hint in name and VIRTUAL_NAME not in name:
return i
raise SystemExit(
"No SMC-PAD MIDI source found. Ports:\n " + "\n ".join(ports or ["(none)"])
)
def _alsa_port(client_substr: str, port_substr: str | None = None) -> str | None:
"""Return 'client:port' for an aconnect client/port name match."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return None
client = None
client_name = None
for line in out.splitlines():
m = re.match(r"client (\d+): '([^']+)'", line)
if m:
client, client_name = int(m.group(1)), m.group(2)
continue
m = re.match(r"\s+(\d+)\s+'([^']+)'", line)
if not m or client is None or client_name is None:
continue
port, pname = int(m.group(1)), m.group(2).strip()
if client_substr not in client_name and client_substr not in pname:
continue
if port_substr and port_substr not in pname and port_substr not in client_name:
continue
if VIRTUAL_NAME in pname:
continue
return f"{client}:{port}"
return None
def ensure_alsa_link() -> None:
"""Bluetooth MIDI sometimes drops the ALSA subscription; re-subscribe."""
src = None
for hint in ("SMC-PAD Bluetooth", "SINCO", "SMC-PAD"):
src = _alsa_port(hint)
if src:
break
dst = _alsa_port("smc-smooth-in")
if not src or not dst:
return
subprocess.run(["aconnect", src, dst], capture_output=True)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--tau",
type=float,
default=0.055,
help="smoothing time constant in seconds (default 0.055)",
)
ap.add_argument("--rate", type=float, default=120.0, help="update Hz")
ap.add_argument(
"--lock-knobs",
action="store_true",
help="knobs 1-10 move test.qxw's custom sliders only after the Custom pad is pressed",
)
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="smc-smooth-in")
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="smc-smooth-out")
src = find_source_port(midiin)
src_name = midiin.get_ports()[src]
midiin.open_port(src)
midiin.ignore_types(timing=True, active_sense=True, sysex=True)
midiout.open_virtual_port(VIRTUAL_NAME)
# current/target as floats 0..127, keyed by (channel, cc)
current: dict[tuple[int, int], float] = {}
target: dict[tuple[int, int], float] = {}
last_sent: dict[tuple[int, int], int] = {}
layer = PlayLayer(lock_knobs=args.lock_knobs)
print(f"Source: {src_name}", flush=True)
print(f"Virtual: {VIRTUAL_NAME} (tau={args.tau}s @ {args.rate} Hz)", flush=True)
print("Pass notes through (Play held shifts bank 2 up 16); smooth CC. Ctrl+C to stop.", flush=True)
ensure_alsa_link()
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:
ensure_alsa_link()
next_link_check = now + 2.0
# Drain inbound
while True:
msg = midiin.get_message()
if msg is None:
break
data, _ = msg
if not data:
continue
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)
# Ease CC toward targets and emit when quantized value moves
for key, tgt in list(target.items()):
cur = current.get(key, tgt)
cur = cur + (tgt - cur) * alpha
# Snap when close so we actually reach the endpoint
if abs(tgt - cur) < 0.15:
cur = tgt
current[key] = cur
q = int(round(cur))
q = 0 if q < 0 else 127 if q > 127 else q
if last_sent.get(key) != q:
ch, cc = key
midiout.send_message([0xB0 | ch, cc, q])
last_sent[key] = q
time.sleep(dt)
except KeyboardInterrupt:
print("\nStopped.", flush=True)
finally:
midiin.close_port()
midiout.close_port()
del midiin
del midiout
if __name__ == "__main__":
main()
-62
View File
@@ -1,62 +0,0 @@
#!/usr/bin/env bash
# Reliable MIDI bring-up for shows/midi.qxw
#
# Order matters:
# 1) pad present (Bluetooth or USB)
# 2) smoother (creates "SMC-PAD Smooth")
# 3) patch workspace to that port
# 4) open QLC+ last
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
PYTHON="${ROOT}/.venv/bin/python"
[[ -x "$PYTHON" ]] || PYTHON=python3
pad_present() {
aconnect -l 2>/dev/null | grep -Eq "SMC-PAD Bluetooth|SINCO|SMC-PAD"
}
echo "Waiting for SMC-PAD (Bluetooth or USB)…"
for _ in $(seq 1 30); do
if pad_present; then
break
fi
sleep 1
done
if ! pad_present; then
echo "No SMC-PAD in aconnect -l. Pair/connect the pad, then re-run." >&2
aconnect -l >&2 || true
exit 1
fi
# Restart smoother so it re-opens the pad port cleanly (avoid pkill -f; it matches this script)
while read -r pid; do
[[ -n "$pid" ]] && kill "$pid" 2>/dev/null || true
done < <(ps -eo pid,args | awk '/[.]venv\/bin\/python .*smooth_smc_pad[.]py/ {print $1}')
sleep 0.4
nohup "$PYTHON" scripts/smooth_smc_pad.py --tau 0.055 >>/tmp/smooth_smc_pad.log 2>&1 &
for _ in $(seq 1 20); do
if aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
break
fi
sleep 0.25
done
if ! aconnect -l 2>/dev/null | grep -q 'SMC-PAD Smooth'; then
echo "Smoother failed to create SMC-PAD Smooth. See /tmp/smooth_smc_pad.log" >&2
tail -20 /tmp/smooth_smc_pad.log >&2 || true
exit 1
fi
python3 scripts/patch_smc_pad.py
kill "$(pgrep -x qlcplus)" 2>/dev/null || true
sleep 0.5
nohup qlcplus --open "$ROOT/shows/midi.qxw" >/tmp/qlcplus.log 2>&1 &
sleep 1.5
echo
echo "Chain (expect pad → Smooth → qlcplus):"
aconnect -l | grep -E "SMC-PAD|SINCO|Smooth|qlcplus|smc-smooth" -A2 || aconnect -l
echo
echo "OK — twist a knob / hit a pad. If silent: re-run this script (don't pick Midi Through in IO)."
+265
View File
@@ -0,0 +1,265 @@
#!/usr/bin/env python3
"""Twisted show MIDI control: Color1/Color2 slots for cans + movers.
Loads shows/midi_map.json, listens to the SMC-PAD, and drives the twisted
patch over Art-Net. Stop QLC+ Art-Net output first so the two do not fight.
pipenv run python scripts/twisted_midi.py
Knob map:
Color1 k5 R, k3 G, k1 B
Color2 k6 R, k4 G, k2 B
Bright k15 cans 1–8, k16 cans 9–12, k7 cans 13–15, k13 movers
k8 chaser transition (QLC Speed Dial when using twisted.qxw)
Movers k9 pan, k10 tilt, k11 focus, k12 rotate
Pads:
5 mover LEDs all → Color1 (default)
6 mover outer → Color1, center → Color2
13 all cans → Color1 (default)
14 cans 1–12 → C1; cans 13–15 chasers (QLC)
"""
from __future__ import annotations
import argparse
import mido
from cabaret_movers import (
DEFAULT_NODE,
FOCUS_DEFAULT,
ArtNetSender,
clamp,
discover_artnet_node,
)
from midi import KNOBS, MAP_PATH, PADS, encoder_delta, find_port, load_maps
# QLC Address is 0-based; ArtNetSender.set_slot is 1-based DMX.
CAN_ADDRS = [88 + i * 8 for i in range(15)] # BCC145 #01–#15
# Front L/R normal; Back L/R hung 90° and converge inward with the same pan,
# so offset them opposite ways (±90° = ±64) to face forward with the fronts.
MOVER_ADDRS = (1, 45, 258, 301) # FL, FR, BL, BR
MOVER_PAN_OFFSET = (0, 0, 64, 192) # BL +90°, BR −90°
# Can 8ch offsets (0-based within fixture)
CAN_DIM, CAN_R, CAN_G, CAN_B = 0, 2, 3, 4
# Mover 43ch 1-based (same as cabaret_movers)
CH_PAN, CH_TILT = 1, 3
CH_ROTATE, CH_FOCUS, CH_DIMMER = 6, 8, 9
CH_RED1 = 11
PIXELS = 7
# Can numbers are 1-based in the pad map
SPLIT_C1 = frozenset(range(1, 13)) # cans 1–12
# cans 13–15 = QLC chasers (not on C1/C2)
KNOB_STEP = 2 # relative encoder → DMX step
def can_slot(can: int, mode: str) -> str | None:
"""Return 'c1', 'c2', or None (off) for a 1-based can number."""
if can in (13, 14, 15):
return None
if mode == "all_c1" or can in SPLIT_C1:
return "c1"
return None
class TwistedState:
def __init__(self, sender: ArtNetSender):
self.sender = sender
self.can_mode = "all_c1" # pad 13 / 14
self.mover_mode = "all_c1" # pad 5 / 6
self.color1 = [0, 0, 0] # R, G, B
self.color2 = [0, 0, 0]
self.bright_1_8 = 0
self.bright_9_15 = 0
self.bright_auto_cans = 0
self.pan = 128
self.tilt = 128
self.rotate = 0
self.mover_bright = 0
self.focus = FOCUS_DEFAULT
def _nudge_list(self, values: list[int], index: int, delta: int) -> bool:
nxt = clamp(values[index] + delta * KNOB_STEP)
if nxt == values[index]:
return False
values[index] = nxt
return True
def _nudge_int(self, name: str, delta: int) -> bool:
cur = getattr(self, name)
nxt = clamp(cur + delta * KNOB_STEP)
if nxt == cur:
return False
setattr(self, name, nxt)
return True
def apply_knob(self, knob: int, delta: int) -> bool:
if delta == 0:
return False
if knob == 1:
return self._nudge_list(self.color1, 2, delta)
if knob == 2:
return self._nudge_list(self.color2, 2, delta)
if knob == 3:
return self._nudge_list(self.color1, 1, delta)
if knob == 4:
return self._nudge_list(self.color2, 1, delta)
if knob == 5:
return self._nudge_list(self.color1, 0, delta)
if knob == 6:
return self._nudge_list(self.color2, 0, delta)
ints = {
7: "bright_auto_cans",
9: "pan",
10: "tilt",
11: "focus",
12: "rotate",
13: "mover_bright",
15: "bright_1_8",
16: "bright_9_15",
}
name = ints.get(knob)
if name is None:
return False
return self._nudge_int(name, delta)
def set_can_mode(self, mode: str) -> bool:
if mode == self.can_mode:
return False
self.can_mode = mode
return True
def set_mover_mode(self, mode: str) -> bool:
if mode == self.mover_mode:
return False
self.mover_mode = mode
return True
def _rgb(self, slot: str | None) -> tuple[int, int, int]:
if slot == "c1":
return tuple(self.color1) # type: ignore[return-value]
if slot == "c2":
return tuple(self.color2) # type: ignore[return-value]
return (0, 0, 0)
def _mover_slot(self, pix: int) -> str:
# Pixel 0 = center; pixels 1–6 = outer ring.
if self.mover_mode == "all_c1":
return "c1"
if pix == 0:
return "c2"
return "c1"
def render(self) -> None:
for i, dmx in enumerate(CAN_ADDRS):
can = i + 1
if can in (13, 14, 15):
bright = self.bright_auto_cans
elif can <= 8:
bright = self.bright_1_8
else:
bright = self.bright_9_15
self.sender.set_slot(dmx + CAN_DIM, bright)
if can in (13, 14, 15):
continue # RGB from QLC chasers
r, g, b = self._rgb(can_slot(can, self.can_mode))
self.sender.set_slot(dmx + CAN_R, r)
self.sender.set_slot(dmx + CAN_G, g)
self.sender.set_slot(dmx + CAN_B, b)
for addr, pan_off in zip(MOVER_ADDRS, MOVER_PAN_OFFSET):
pan = (self.pan + pan_off) & 0xFF
self.sender.set_slot(addr + CH_PAN - 1, pan)
self.sender.set_slot(addr + CH_PAN, 0) # pan fine
self.sender.set_slot(addr + CH_TILT - 1, self.tilt)
self.sender.set_slot(addr + CH_TILT, 0) # tilt fine
self.sender.set_slot(addr + CH_ROTATE - 1, self.rotate)
self.sender.set_slot(addr + CH_FOCUS - 1, self.focus)
self.sender.set_slot(addr + CH_DIMMER - 1, self.mover_bright)
for pix in range(PIXELS):
r, g, b = self._rgb(self._mover_slot(pix))
base = addr + CH_RED1 - 1 + pix * 4
self.sender.set_slot(base, r)
self.sender.set_slot(base + 1, g)
self.sender.set_slot(base + 2, b)
self.sender.set_slot(base + 3, 0)
def summary(self) -> str:
c1 = tuple(self.color1)
c2 = tuple(self.color2)
return (
f"cans={self.can_mode} movers={self.mover_mode} "
f"c1={c1} c2={c2} "
f"bright {self.bright_1_8}/{self.bright_9_15} "
f"mover pan={self.pan} tilt={self.tilt} rot={self.rotate} "
f"dim={self.mover_bright} foc={self.focus}"
)
def listen(port: str, state: TwistedState) -> None:
with mido.open_input(port) as incoming:
for msg in incoming:
if msg.type == "note_on" and msg.velocity > 0:
pad = PADS.get((msg.channel, msg.note))
changed = False
if pad == 5:
changed = state.set_mover_mode("all_c1")
elif pad == 6:
changed = state.set_mover_mode("split")
elif pad == 13:
changed = state.set_can_mode("all_c1")
elif pad == 14:
changed = state.set_can_mode("split")
if changed:
state.render()
print(state.summary(), flush=True)
elif msg.type == "control_change":
knob = KNOBS.get((msg.channel, msg.control))
if knob is None:
continue
delta = encoder_delta(msg.value)
if state.apply_knob(knob, delta):
state.render()
print(state.summary(), flush=True)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("midi", nargs="?", help="MIDI port name substring")
parser.add_argument("--ip", default=None, help="Art-Net node IP")
parser.add_argument("--universe", type=int, default=0)
args = parser.parse_args()
load_maps(MAP_PATH)
if not PADS or not KNOBS:
raise SystemExit(f"No MIDI map in {MAP_PATH}. Run scripts/midi.py first.")
ip = args.ip or discover_artnet_node(DEFAULT_NODE)
port = find_port(args.midi)
sender = ArtNetSender(ip, universe=args.universe)
state = TwistedState(sender)
state.render()
print(f"Art-Net {ip} universe {args.universe}", flush=True)
print(f"MIDI {port} map {MAP_PATH}", flush=True)
print(
"Pad 5/6 = mover LEDs. Pad 13/14 = cans. Ctrl+C to stop.",
flush=True,
)
print(state.summary(), flush=True)
try:
listen(port, state)
except KeyboardInterrupt:
pass
finally:
sender.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+3114
View File
File diff suppressed because it is too large. Load diff
+6143 -584
View File
File diff suppressed because it is too large. Load diff
+1248 -2710
View File
File diff suppressed because it is too large. Load diff
+229
View File
@@ -0,0 +1,229 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="SimpleDesk">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>tech</Author>
</Creator>
<Engine>
<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>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>0</ID>
<Name>BCC145 #01</Name>
<Universe>0</Universe>
<Address>87</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>1</ID>
<Name>BCC145 #02</Name>
<Universe>0</Universe>
<Address>95</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>2</ID>
<Name>BCC145 #03</Name>
<Universe>0</Universe>
<Address>103</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>3</ID>
<Name>BCC145 #04</Name>
<Universe>0</Universe>
<Address>111</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>4</ID>
<Name>BCC145 #05</Name>
<Universe>0</Universe>
<Address>119</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>5</ID>
<Name>BCC145 #06</Name>
<Universe>0</Universe>
<Address>127</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>6</ID>
<Name>BCC145 #07</Name>
<Universe>0</Universe>
<Address>135</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>7</ID>
<Name>BCC145 #08</Name>
<Universe>0</Universe>
<Address>143</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>8</ID>
<Name>BCC145 #09</Name>
<Universe>0</Universe>
<Address>151</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>9</ID>
<Name>BCC145 #10</Name>
<Universe>0</Universe>
<Address>159</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>10</ID>
<Name>BCC145 #11</Name>
<Universe>0</Universe>
<Address>167</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>11</ID>
<Name>BCC145 #12</Name>
<Universe>0</Universe>
<Address>175</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>12</ID>
<Name>BCC145 #13</Name>
<Universe>0</Universe>
<Address>183</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>13</ID>
<Name>BCC145 #14</Name>
<Universe>0</Universe>
<Address>191</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>14</ID>
<Name>BCC145 #15</Name>
<Universe>0</Universe>
<Address>199</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>Small Eye 7</Manufacturer>
<Model>Mover</Model>
<Mode>43 Channel</Mode>
<ID>15</ID>
<Name>Front Left Mover</Name>
<Universe>0</Universe>
<Address>0</Address>
<Channels>43</Channels>
</Fixture>
<Fixture>
<Manufacturer>Small Eye 7</Manufacturer>
<Model>Mover</Model>
<Mode>43 Channel</Mode>
<ID>16</ID>
<Name>Front Right Mover</Name>
<Universe>0</Universe>
<Address>44</Address>
<Channels>43</Channels>
</Fixture>
<Fixture>
<Manufacturer>Small Eye 7</Manufacturer>
<Model>Mover</Model>
<Mode>43 Channel</Mode>
<ID>17</ID>
<Name>Back Left Mover</Name>
<Universe>0</Universe>
<Address>257</Address>
<Channels>43</Channels>
</Fixture>
<Fixture>
<Manufacturer>Small Eye 7</Manufacturer>
<Model>Mover</Model>
<Mode>43 Channel</Mode>
<ID>18</ID>
<Name>Back Right Mover</Name>
<Universe>0</Universe>
<Address>300</Address>
<Channels>43</Channels>
</Fixture>
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
</Frame>
<Properties>
<Size Width="1920" Height="1080"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
+1374
View File
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
Jet
c2 255:108:0
0:
1st
c1 blue
c2 20:0:255
40:44:60
2nd
c1 192:0:255
10:44:0
x
c1 128:0:255
Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more