From 35207a868a164748849200e1598dd953af2cb1d6 Mon Sep 17 00:00:00 2001 From: jimmy Date: Tue, 17 Nov 2026 18:13:58 +1300 Subject: [PATCH] sim: fixture editor for DDP and Art-Net/DMX fixtures The rig sim receives Art-Net (UDP 6454, answers ArtPoll) and DDP (each port the room's DDP strips use) in sim_net.c and passes changed universes and pixels to the page over /sim/ws, now with a kind byte in front of each binary frame. Rooms gain fixture types: ddp strips, artnet pixel strips, and artnet cans and movers that read named channels from the room's dmx_definitions (the qlcplus stage map's format). Overlapping DMX channels are refused. Cans and movers are decoded and drawn as in the qlcplus stage simulator (dmx.js, dmx-draw.js). In Edit mode: pick a type to add, edit port/offset/universe/address/colour order/definition, see a can's or mover's live channels, make a controller output aimed at the sim and send its test. The room dialog lists DMX definitions, with presets, a channel editor, and .qxf and stage map import. GET /sim/api/dmx shows what the receiver has had. Tests: test/api/test_sim_net.py and test/browser/dmx_decode.test.mjs. Co-Authored-By: Claude Opus 5.5 --- desktop/CMakeLists.txt | 2 +- docs/API.md | 2 + led-simulator/README.md | 48 +- led-simulator/web/app.js | 740 ++++++++++++++++++- led-simulator/web/dmx-draw.js | 343 +++++++++ led-simulator/web/dmx.js | 492 ++++++++++++ led-simulator/web/index.html | 80 +- led-simulator/web/layout.js | 28 +- led-simulator/web/styles.css | 44 ++ sim-controller/components/sim/CMakeLists.txt | 2 +- sim-controller/components/sim/sim_net.c | 443 +++++++++++ sim-controller/components/sim/sim_net.h | 32 + sim-controller/components/sim/sim_rig.c | 380 ++++++++-- test/api/test_sim_net.py | 225 ++++++ test/browser/dmx_decode.test.mjs | 114 +++ tools/build_sim_web.sh | 2 +- 16 files changed, 2859 insertions(+), 118 deletions(-) create mode 100644 led-simulator/web/dmx-draw.js create mode 100644 led-simulator/web/dmx.js create mode 100644 sim-controller/components/sim/sim_net.c create mode 100644 sim-controller/components/sim/sim_net.h create mode 100644 test/api/test_sim_net.py create mode 100644 test/browser/dmx_decode.test.mjs diff --git a/desktop/CMakeLists.txt b/desktop/CMakeLists.txt index 005b0b8..7f6a24d 100644 --- a/desktop/CMakeLists.txt +++ b/desktop/CMakeLists.txt @@ -35,7 +35,7 @@ set(MAIN_SRC list(TRANSFORM MAIN_SRC PREPEND ${ROOT}/main/) # The host stand-ins for the board's hardware (mic, OTA, littlefs, timers) and the app_main that starts it -set(SIM_SRC sim_main.c sim_stubs.c sim_timer.c sim_rig.c) +set(SIM_SRC sim_main.c sim_stubs.c sim_timer.c sim_rig.c sim_net.c) list(TRANSFORM SIM_SRC PREPEND ${ROOT}/sim-controller/components/sim/) set(THIRD_PARTY diff --git a/docs/API.md b/docs/API.md index 08c7ccf..f567d57 100644 --- a/docs/API.md +++ b/docs/API.md @@ -296,6 +296,8 @@ Network pixel fixtures. An output is `{id, name, protocol: "ddp" | "artnet" | "s Zones do not render to outputs: only the test pattern is sent. +The simulated rig (`/sim/`, host builds) receives Art-Net and DDP, so an output aimed at `127.0.0.1` shows on its DDP and Art-Net fixtures; see `led-simulator/README.md` (Network fixtures) and `GET /sim/api/dmx`. + ## WebSocket — `/ws` On connect the controller sends `{"type": "device_tcp_snapshot", "connected_ips": []}` (there are no Wi-Fi driver sessions). Each text frame is a driver message (JSON object), sent as `/presets/push` would send it: an optional `to` (MAC) addresses one driver, otherwise it is broadcast. A frame that is not a JSON object, or a failed send, gets `{"error": ...}` back. A plain GET gets 426. diff --git a/led-simulator/README.md b/led-simulator/README.md index cc956fe..36102b0 100644 --- a/led-simulator/README.md +++ b/led-simulator/README.md @@ -62,6 +62,8 @@ strip types in `definitions`, and `fixtures` keyed by id, each placed by positio `leds × pitch_m` long. `leds` on a fixture overrides its type's count (1–512). - **`mac`** identifies the driver. Each bar's flash is kept per MAC, so a bar in two rooms (a copied room, say) is the same bar with the same presets. New bars get a MAC no room uses yet. +- A fixture's **`type`** is `espnow` (the default: a bar with its own driver), `ddp` or `artnet`; see + [Network fixtures](#network-fixtures). - The first run makes the `default` room: 16 bars × 119 LEDs in 2 columns × 8 rows, pixel 0 at the centre line, `sim-01` … `sim-16` = `02:51:4d:00:00:01` … `…:10`. The rig's bridge is `02:51:4d:00:00:00`. @@ -89,6 +91,43 @@ controller's rig layout: A bar whose LED count changes keeps running with the old count until it is power-cycled, as `num_leds` is read at boot. +### Network fixtures + +Besides the ESP-NOW bars, a room can hold fixtures that something sends to over the network: the controller's own +Outputs, QLC+, or any DDP or Art-Net sender. The controller's sim receives them over UDP (`sim_net.c`: Art-Net on +6454, DDP on each port the active room's DDP strips use, 4048 by default) and passes each changed universe or +DDP buffer to the page at up to 40 frames a second. It answers ArtPoll, so QLC+ lists the node. If QLC+ on the same +machine already holds 6454, set `LED_SIM_ARTNET_PORT` to another port (`0` turns Art-Net off). + +| `type` | `kind` | Fields | What it is | +| --- | --- | --- | --- | +| `ddp` | | `def`, `leds`, `port` (4048), `offset` (first pixel), `color_order` | an LED strip fed by DDP | +| `artnet` | `pixels` | `def`, `leds`, `universe`, `address` (1–512), `color_order` | an LED strip fed by Art-Net: the first universe from `address`, then 170 pixels a universe from channel 1, as the controller's Art-Net output sends them | +| `artnet` | `can` | `dmx_def`, `universe`, `address`, `direction` | a par can | +| `artnet` | `mover` | `dmx_def`, `universe`, `address`, `zero`, `pan_reverse` | a moving head; `zero` is its heading at pan centre | + +Cans and movers behave as in the qlcplus stage simulator (technicalkiwi/qlcplus `simulator/`). Their channels come +from the room's **`dmx_definitions`**: `{name: {manufacturer, model, mode, channels: [name, ...]}}`, the same shape +as a qlcplus `stage/map.json`. The channel names choose what each slot does: `Dimmer`, `Strobe`, `Red`, `Green`, +`Blue`, `White`, `Macro`, `Speed` for cans; `Pan`, `Pan Fine`, `Tilt`, `Tilt Fine`, `Pan/Tilt Speed`, `Zoom`, +`Focus`, `Lens Rotate`, `Center Brightness`, `Center Strobe`, `Red 1` … `White 7`, `Colour Macro`, +`Colour Temperature`, `Static Effect`, `Dynamic Effect` for movers (`web/dmx.js`). Art-Net fixtures may not share +DMX channels; the room is refused if they do. + +On the page, in Edit mode: + +- Pick the type beside **Add** (ESP-NOW bar, DDP strip, Art-Net pixel strip, DMX can, DMX mover). A click on the + floor adds that type. New DDP strips start after the last one on port 4048, Art-Net pixel strips on the first + free universe, and cans and movers at the first free DMX address. +- The side panel edits the port and first pixel, the universe and address, the colour order, the DMX definition, + and a mover's pan zero and reversal. For a can or mover it lists the channels with their live values. +- **Create controller output** (DDP and Art-Net pixel strips) adds an Output to the controller aimed at the sim + (`127.0.0.1`), and **Send test** runs its red, green, blue, white, black test. Outputs send from pixel 0 and + channel 1, so the button needs First pixel 0 or DMX address 1. +- **Size, strip types & DMX…** also lists the DMX definitions: add a preset (the qlcplus beamZ BCC145 and Small Eye + 7 mover), write one (one channel name per line), import a QLC+ fixture definition (`.qxf`, one definition per + mode), or import a qlcplus `stage/map.json` (its definitions, and its cans and movers placed in the room). + ### API (on the controller) | | | @@ -99,8 +138,9 @@ boot. | `POST /sim/api/rooms` | `{name, width, depth, copy_from?}` makes a room | | `GET`, `PUT`, `DELETE /sim/api/rooms/` | one room: read it, replace it (validated), delete it (not the active one) | | `POST /sim/api/room` | `{name}` switches the rig to that room | -| `GET /sim/api/next-mac` | a MAC no room uses | -| `WS /sim/ws` | the page's radio: binary `dst_mac + packet` down, `src_mac + packet` up; text `{"t":"flash"}` up | +| `POST /sim/api/next-mac` | `{taken: [mac, ...]}`: a MAC no room or the page uses | +| `GET /sim/api/dmx[?data=1]` | what the Art-Net and DDP receiver has had: packets per universe and port, the last sender; `data=1` adds the bytes as hex | +| `WS /sim/ws` | the page's radio. Down, binary: `0x00 + dst_mac + packet` (ESP-NOW), `0x01 + u16 universe + 512 bytes` (Art-Net), `0x02 + u16 port + u32 offset + RGB` (DDP), little-endian. Up: binary `src_mac + packet`; text `{"t":"flash"}` | ## How it fits together @@ -113,14 +153,16 @@ led-controller (host build) ──"browser" bridge──▶ WS /sim/ws ──▶ | Where | What | | --- | --- | | `sim-controller/components/sim/sim_rig.c` | serves the page and the wasm from `www_dist/sim.pack`, the page's WebSocket, rooms and flash | +| `sim-controller/components/sim/sim_net.c` | receives Art-Net and DDP for the network fixtures and passes them to the page | | `main/bridge.c` | the `browser` bridge kind next to UDP and serial | | `tools/build_sim_web.sh` | packs `web/` and `web/wasm/` into `www_dist/sim.pack`. It is empty when the drivers are not built, so `make desktop` works without Emscripten. | | `../sim-driver/` | the Emscripten build of the driver (`led_driver`) and the pattern engine for the gallery (`led_fx`) | | `web/app.js` | the room canvas, editor, power control, packet routing by MAC, and placements for `POST /devices/layout` | | `web/driver-worker.js` | loads `led_driver.mjs` and boots one bar | +| `web/dmx.js`, `web/dmx-draw.js` | the DMX decoder and the can and mover drawing, ported from the qlcplus stage simulator | | `web/gallery.js` | one `led_fx` instance per pattern, each stepped every 10 ms of its own clock | -Not simulated: the drivers' Wi-Fi, their own web UI and HTTP API, DDP and USB. Bars do not hear each other's +Not simulated: the drivers' Wi-Fi, their own web UI and HTTP API, DDP to the bars themselves, sACN and USB. Bars do not hear each other's ESP-NOW. ## Headless (older) diff --git a/led-simulator/web/app.js b/led-simulator/web/app.js index 9a1e915..4d3a4c4 100644 --- a/led-simulator/web/app.js +++ b/led-simulator/web/app.js @@ -2,7 +2,9 @@ * * Each bar is a module worker running the C++ led-driver built to WebAssembly (driver-worker.js). The page is * the radio between them and the controller's "browser" bridge (WebSocket /sim/ws): - * controller -> page binary dest_mac(6) + ESP-NOW packet (the controller transmits) + * controller -> page binary 0x00 + dest_mac(6) + ESP-NOW packet (the controller transmits) + * controller -> page binary 0x01 + u16 universe + 512 bytes (an Art-Net universe changed) + * controller -> page binary 0x02 + u16 port + u32 offset + RGB (a DDP port's pixels changed) * page -> controller binary src_mac(6) + ESP-NOW packet (a driver transmits) * controller -> page text {"t":"takeover"} (another page opened the rig) * page -> controller text {"t":"flash","mac":..,"data":..} (a driver committed its NVS store) @@ -10,8 +12,12 @@ * Where the bars are is the active room. In Edit mode the room can be changed: add bars by clicking the floor, * drag to move, drag the end handle to turn, Delete to remove. Every change is saved (PUT /sim/api/rooms/) * and the bars' places go to the controller's rig layout (POST /devices/layout). + * + * Besides the ESP-NOW bars a room can hold network fixtures, which the controller's sim receives over UDP and + * passes on here: DDP strips, Art-Net pixel strips, and DMX cans and movers drawn the way the qlcplus stage + * simulator draws them (dmx.js decodes, dmx-draw.js draws). */ -/* global RigLayout */ +/* global RigLayout, RigDmx, RigDmxDraw */ (function () { 'use strict'; @@ -74,8 +80,16 @@ drag: null, saveTimer: 0, lastDef: '', + universes: new Map(), // Art-Net universe -> Uint8Array(512), as the sim last received it + ddp: new Map(), // DDP port -> Uint8Array of RGB from offset 0 + netAt: new Map(), // 'u' / 'p' -> when it last arrived (ms) + netDirty: false, + outputs: new Map(), // fixture id -> controller output id made for it on this page }; + const NET_FRESH_MS = 2000; // a network fixture is "receiving" while data came in this recently + const NET_LEDS_MAX = 4096; // SIM_NET_DDP_PIXELS in sim_net.h + // ----- helpers ----------------------------------------------------------- function macBytes(s) { @@ -152,8 +166,10 @@ return { info, id: info.id, + type: info.type, + kind: info.kind, mac: info.mac, - macBytes: macBytes(info.mac), + macBytes: info.mac ? macBytes(info.mac) : null, name: info.label, bootedLeds: 0, state: 'off', @@ -164,9 +180,14 @@ rx: 0, tx: 0, error: '', + live: null, // a can's or mover's decoded view (RigDmx.viewFixture) }; } + function isNet(s) { + return s.type !== 'espnow'; + } + function setState(s, state, error = '') { s.state = state; s.error = error; @@ -195,7 +216,7 @@ } function powerOn(s) { - if (app.takenOver) { + if (app.takenOver || isNet(s)) { return; } if (s.state !== 'off' && s.state !== 'crashed') { @@ -388,6 +409,96 @@ } } + /** An Art-Net universe or a DDP port's pixels from the sim's receiver (sim_net.h). */ + function onNetFrame(u8) { + const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength); + if (u8[0] === 1 && u8.length >= 3 + 512) { + const uni = dv.getUint16(1, true); + app.universes.set(uni, u8.slice(3, 3 + 512)); + app.netAt.set(`u${uni}`, performance.now()); + } else if (u8[0] === 2 && u8.length >= 7) { + const port = dv.getUint16(1, true); + const off = dv.getUint32(3, true); + const data = u8.subarray(7); + let buf = app.ddp.get(port); + if (!buf || buf.length < off + data.length) { + const grown = new Uint8Array(off + data.length); + if (buf) { + grown.set(buf); + } + buf = grown; + } + buf.set(data, off); + app.ddp.set(port, buf); + app.netAt.set(`p${port}`, performance.now()); + } + app.netDirty = true; + } + + /** Wire bytes to r, g, b. color_order names the colour in each wire slot ("grb": green first), as in outputs.c. */ + function toRgb(src, order) { + if (!/^(rgb|rbg|grb|gbr|brg|bgr)$/.test(order) || order === 'rgb') { + return src; + } + const at = [0, 1, 2].map((k) => 'rgb'.indexOf(order[k])); // wire slot k carries colour at[k] + const out = new Uint8Array(src.length); + for (let i = 0; i + 2 < src.length; i += 3) { + for (let k = 0; k < 3; k += 1) { + out[i + at[k]] = src[i + k]; + } + } + return out; + } + + /** Where a network fixture's data comes from, and whether it is arriving. */ + function netSource(f) { + if (f.type === 'ddp') { + return `p${f.port}`; + } + return `u${f.universe}`; + } + + function netFresh(f) { + const t = app.netAt.get(netSource(f)); + return t !== undefined && performance.now() - t < NET_FRESH_MS; + } + + /** Fill the network fixtures' frames (pixels) and views (cans, movers) from what has arrived. */ + function updateNet() { + for (const s of app.strips) { + const f = app.room.fixtures[s.id]; + if (!f || !isNet(s)) { + continue; + } + const was = s.state; + s.state = netFresh(f) ? 'running' : 'off'; + if (s.state !== was) { + app.dirty = true; + } + if (s.info.point) { + const def = (app.room.dmx_definitions || {})[f.dmx_def]; + s.live = RigDmx.viewFixture( + { kind: f.kind, universe: f.universe, address: f.address, channel_names: def ? def.channels : [], pan_reverse: f.pan_reverse }, + app.universes, + ); + continue; + } + const leds = s.info.leds; + let raw; + if (f.type === 'ddp') { + const buf = app.ddp.get(f.port); + raw = new Uint8Array(leds * 3); + if (buf) { + const a = (f.offset || 0) * 3; + raw.set(buf.subarray(a, Math.min(buf.length, a + leds * 3))); + } + } else { + raw = RigDmx.artnetPixels(app.universes, f.universe, f.address, leds); + } + s.frame = toRgb(raw, f.color_order || 'rgb'); + } + } + function connectBridge() { if (app.takenOver) { return; @@ -421,7 +532,12 @@ } return; } - onDownlink(new Uint8Array(ev.data)); + const u8 = new Uint8Array(ev.data); + if (u8[0] === 0) { + onDownlink(u8.subarray(1)); + } else if (u8[0] === 1 || u8[0] === 2) { + onNetFrame(u8); + } }; ws.onclose = () => { app.wsOpen = false; @@ -443,7 +559,7 @@ const next = []; for (const info of infos) { let s = old.get(info.id); - if (s && s.mac !== info.mac) { + if (s && (s.mac !== info.mac || s.type !== info.type || s.kind !== info.kind)) { powerOff(s); s = null; } @@ -467,7 +583,8 @@ } } app.strips = next; - app.byMac = new Map(next.map((s) => [s.mac, s])); + app.byMac = new Map(next.filter((s) => s.mac).map((s) => [s.mac, s])); + app.netDirty = true; layoutView(); updateChips(); renderDrawer(); @@ -533,6 +650,7 @@ const sel = $('room-select'); sel.replaceChildren(...cfg.rooms.map((n) => new Option(n, n, false, n === cfg.room_name))); app.lastDef = Object.keys(app.room.definitions)[0]; + app.room.dmx_definitions = app.room.dmx_definitions || {}; app.zoom = 1; // each room opens fitted app.pan = { x: 0, y: 0 }; syncStrips(); @@ -553,24 +671,101 @@ return mac.replace(/:/g, ''); } + /** A label like can-1 that no fixture in the room has. */ + function nextNetLabel(prefix) { + const taken = new Set(Object.entries(app.room.fixtures).flatMap(([id, f]) => [id, f.label])); + for (let n = 1; ; n += 1) { + if (!taken.has(`${prefix}-${n}`)) { + return `${prefix}-${n}`; + } + } + } + + /** The first DMX address from universe 0 up where count channels are free; fromStart: only at address 1 (a pixel + * strip, so a controller output, which sends from channel 1, can feed it). */ + function nextDmxAddress(count, fromStart = false) { + const used = []; + for (const f of Object.values(app.room.fixtures)) { + if (f.type === 'artnet') { + used.push(...RigDmx.dmxRuns(f, app.room, RigLayout.fixtureLeds(app.room, f))); + } + } + for (let u = 0; u < 32768; u += 1) { + const runs = used.filter((r) => r[0] === u).sort((a, b) => a[1] - b[1]); + let a = 0; + for (const [, s0, e0] of runs) { + if (s0 - a >= count || (fromStart && a === 0 && s0 >= count)) { + break; + } + a = Math.max(a, e0); + if (fromStart) { + break; // address 1 is taken in this universe + } + } + if (a + count <= 512 && !(fromStart && a > 0)) { + return { universe: u, address: a + 1 }; + } + } + return { universe: 0, address: 1 }; + } + + /** The DMX definition for a new can or mover: the last one used for that kind, else a qlcplus preset. */ + function dmxDefFor(kind) { + const defs = app.room.dmx_definitions; + const want = kind === 'mover' ? 'Small Eye 7 Mover' : 'beamZ BCC145'; + const isMover = (d) => d.channels.some((c) => /^pan$/i.test(c)) && d.channels.some((c) => /^tilt$/i.test(c)); + const used = Object.values(app.room.fixtures).find((f) => f.kind === kind && defs[f.dmx_def]); + if (used) { + return used.dmx_def; + } + const fit = Object.keys(defs).find((k) => isMover(defs[k]) === (kind === 'mover')); + if (fit) { + return fit; + } + defs[want] = JSON.parse(JSON.stringify(RigDmx.PRESET_DEFINITIONS[want])); + return want; + } + async function addFixture(x, y) { - let mac; - try { - const taken = Object.values(app.room.fixtures).map((f) => f.mac); - mac = (await api('POST', '/sim/api/next-mac', { taken })).mac; - } catch (err) { - banner(`Could not add a strip: ${err.message}`); - return; + const type = $('add-type').value || 'espnow'; + const pos = { x: round3(Math.round(x / SNAP_M) * SNAP_M), y: round3(Math.round(y / SNAP_M) * SNAP_M) }; + const def = app.lastDef in app.room.definitions ? app.lastDef : Object.keys(app.room.definitions)[0]; + let label; + if (type === 'espnow') { + let mac; + try { + const taken = Object.values(app.room.fixtures).map((f) => f.mac).filter(Boolean); + mac = (await api('POST', '/sim/api/next-mac', { taken })).mac; + } catch (err) { + banner(`Could not add a strip: ${err.message}`); + return; + } + label = nextLabel(mac); + app.room.fixtures[label] = { label, def, mac, ...pos, direction: 90 }; + } else if (type === 'ddp') { + label = nextNetLabel('ddp'); + // after the last DDP strip on 4048, so a new strip gets its own pixels + let offset = 0; + for (const f of Object.values(app.room.fixtures)) { + if (f.type === 'ddp' && f.port === 4048) { + offset = Math.max(offset, (f.offset || 0) + RigLayout.fixtureLeds(app.room, f)); + } + } + app.room.fixtures[label] = { label, type, def, port: 4048, offset: Math.min(offset, NET_LEDS_MAX - 1), color_order: 'rgb', ...pos, direction: 90 }; + } else if (type === 'artnet') { + label = nextNetLabel('art'); + const leds = app.room.definitions[def].leds; + const at = nextDmxAddress(Math.min(510, leds * 3), true); + app.room.fixtures[label] = { label, type, kind: 'pixels', def, ...at, color_order: 'rgb', ...pos, direction: 90 }; + } else { + label = nextNetLabel(type); + const dmxDef = dmxDefFor(type); + const at = nextDmxAddress(app.room.dmx_definitions[dmxDef].channels.length); + app.room.fixtures[label] = { + label, type: 'artnet', kind: type, dmx_def: dmxDef, ...at, ...pos, direction: 0, + ...(type === 'mover' ? { zero: 0, pan_reverse: false } : {}), + }; } - const label = nextLabel(mac); - app.room.fixtures[label] = { - label, - def: app.lastDef in app.room.definitions ? app.lastDef : Object.keys(app.room.definitions)[0], - mac, - x: round3(Math.round(x / SNAP_M) * SNAP_M), - y: round3(Math.round(y / SNAP_M) * SNAP_M), - direction: 90, - }; changed(); select(app.strips.find((s) => s.id === label) || null); renderDrawer(); @@ -631,6 +826,9 @@ const ty = (y) => Math.round((H / 2 + (y - app.room.depth / 2) * s) * 10) / 10; const out = {}; for (const st of RigLayout.roomStrips(app.room)) { + if (!st.mac) { + continue; // a network fixture: the controller has no device for it + } out[st.mac.replace(/:/g, '')] = { x0: tx(st.x), y0: ty(st.y), x1: tx(st.x1), y1: ty(st.y1) }; } return out; @@ -699,15 +897,36 @@ } + /** What a network fixture listens to, for the drawer's subtitle. */ + function netWhere(f) { + if (f.type === 'ddp') { + return `DDP :${f.port} · from pixel ${f.offset || 0}`; + } + const what = f.kind === 'pixels' ? 'Art-Net pixels' : `DMX ${f.kind} · ${f.dmx_def}`; + return `${what} · universe ${f.universe} · address ${f.address}`; + } + function renderFacts() { const s = app.selected; if (!s) { return; } const st = $('d-state'); + const i = s.info; + const f = app.room.fixtures[s.id] || {}; + if (isNet(s)) { + const on = netFresh(f); + st.textContent = on ? 'receiving' : 'no data'; + st.className = `state-${on ? 'running' : 'off'}`; + const where = i.point ? `heading ${f.kind === 'mover' ? f.zero || 0 : f.direction}°` : `heading ${i.direction}° · ${i.leds} LEDs`; + $('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · ${where}`; + const t = app.netAt.get(netSource(f)); + $('d-packets').textContent = t === undefined ? 'nothing yet' : `last ${((performance.now() - t) / 1000).toFixed(1)} s ago`; + $('d-note').hidden = true; + return; + } st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : ''); st.className = `state-${s.state}`; - const i = s.info; $('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · heading ${i.direction}° · ${i.leds} LEDs`; $('d-packets').textContent = `${s.rx} received · ${s.tx} sent`; const stale = s.state !== 'off' && s.bootedLeds && s.bootedLeds !== i.leds; @@ -715,6 +934,117 @@ $('d-note').textContent = stale ? `Running with ${s.bootedLeds} LEDs: power-cycle it to use ${i.leds}.` : ''; } + /** A can's or mover's channels as they arrive, like the qlcplus detail panel. */ + function renderLive() { + const s = app.selected; + const table = $('d-channels'); + const f = s && app.room.fixtures[s.id]; + if (!f || !s.info.point) { + table.hidden = true; + return; + } + renderFacts(); + const def = app.room.dmx_definitions[f.dmx_def]; + const names = def ? def.channels : []; + const values = (s.live && s.live.channels) || []; + table.hidden = false; + const body = table.tBodies[0]; + if (body.rows.length !== names.length || body.dataset.def !== f.dmx_def || body.dataset.addr !== String(f.address)) { + body.dataset.def = f.dmx_def; + body.dataset.addr = String(f.address); + body.replaceChildren(...names.map((n, k) => { + const tr = document.createElement('tr'); + tr.innerHTML = ''; + tr.cells[0].textContent = String(f.address + k); + tr.cells[1].textContent = n; + return tr; + })); + } + for (let k = 0; k < names.length; k += 1) { + const v = values[k] || 0; + const cell = body.rows[k].cells[2]; + if (cell.textContent !== String(v)) { + cell.textContent = String(v); + body.rows[k].classList.toggle('on', v > 0); + } + } + } + + /** The controller output that would send to this fixture, or why there is none. */ + function outputFor(f) { + const leds = RigLayout.fixtureLeds(app.room, f); + const base = { name: `sim ${f.label}`.slice(0, 60), host: '127.0.0.1', pixel_count: leds, color_order: f.color_order || 'rgb', enabled: true }; + if (f.type === 'ddp') { + if (f.offset) { + return { why: 'Controller outputs send DDP from pixel 0: set First pixel to 0 to make one.' }; + } + return { body: { ...base, protocol: 'ddp', port: f.port } }; + } + if (f.type === 'artnet' && f.kind === 'pixels') { + if (f.address !== 1) { + return { why: 'Controller outputs send Art-Net pixels from channel 1: set the DMX address to 1 to make one.' }; + } + return { body: { ...base, protocol: 'artnet', universe: f.universe } }; + } + return { why: '' }; + } + + function renderOutput() { + const s = app.selected; + const f = s && app.room.fixtures[s.id]; + const box = $('d-net'); + const pixels = f && isNet(s) && !s.info.point; + box.hidden = !pixels; + if (!pixels) { + return; + } + const o = outputFor(f); + $('d-mkout').disabled = !o.body; + $('d-testout').hidden = !app.outputs.has(s.id); + if (!$('d-out-note').dataset.sticky) { + $('d-out-note').textContent = o.why || 'Adds an output in the controller\'s Outputs, sending to this sim (127.0.0.1).'; + } + } + + async function makeOutput() { + const s = app.selected; + const f = s && app.room.fixtures[s.id]; + const o = f && outputFor(f); + if (!o || !o.body) { + return; + } + const note = $('d-out-note'); + try { + const out = await api('POST', '/outputs', o.body); + const id = out && (out.id || (out.output && out.output.id)); + app.outputs.set(s.id, id); + note.textContent = `Made output "${o.body.name}"${id ? ` (${id})` : ''}. Send test sends red, green, blue, white, then black.`; + } catch (err) { + note.textContent = `Could not make the output: ${err.message}`; + } + note.dataset.sticky = '1'; + renderOutput(); + } + + async function testOutput() { + const s = app.selected; + const id = s && app.outputs.get(s.id); + if (!id) { + return; + } + const note = $('d-out-note'); + $('d-testout').disabled = true; + note.textContent = 'Sending the test…'; + try { + const r = await api('POST', `/outputs/${encodeURIComponent(id)}/test`, { step_s: 1 }); + const st = (r && r.status) || {}; + note.textContent = `Test sent: ${st.packets ?? '?'} packets${st.last_error ? ` · ${st.last_error}` : ''}.`; + } catch (err) { + note.textContent = `Test failed: ${err.message}`; + } + $('d-testout').disabled = false; + } + function renderEditForm() { const s = app.selected; const f = s && app.room.fixtures[s.id]; @@ -722,23 +1052,55 @@ if (!app.edit || !f) { return; } - const sel = $('e-def'); - sel.replaceChildren( - ...Object.entries(app.room.definitions).map( - ([k, d]) => new Option(`${k} (${d.leds} LEDs, ${Math.round(1 / d.pitch_m)}/m)`, k, false, k === f.def), - ), - ); + const type = f.type || 'espnow'; + const point = RigLayout.isPoint(f); + const show = { + strip: !point, + ddp: type === 'ddp', + artnet: type === 'artnet', + pixels: type !== 'espnow' && !point, + dmx: point, + mover: point && f.kind === 'mover', + heading: !(point && f.kind === 'mover'), + }; + for (const el of $('d-edit').querySelectorAll('[data-for]')) { + el.hidden = !show[el.dataset.for]; + } + $('e-x-name').textContent = point ? 'x' : 'Pixel 0 x'; + $('e-y-name').textContent = point ? 'y' : 'Pixel 0 y'; + $('e-leds').max = String(type === 'espnow' ? 512 : NET_LEDS_MAX); const set = (id, v) => { if (document.activeElement !== $(id)) { $(id).value = v; } }; + if (!point) { + const sel = $('e-def'); + sel.replaceChildren( + ...Object.entries(app.room.definitions).map( + ([k, d]) => new Option(`${k} (${d.leds} LEDs, ${Math.round(1 / d.pitch_m)}/m)`, k, false, k === f.def), + ), + ); + set('e-leds', f.leds ?? ''); + $('e-leds').placeholder = String(app.room.definitions[f.def].leds); + } else { + $('e-dmxdef').replaceChildren( + ...Object.entries(app.room.dmx_definitions).map( + ([k, d]) => new Option(`${k} (${d.channels.length} ch)`, k, false, k === f.dmx_def), + ), + ); + } set('e-label', f.label); - set('e-leds', f.leds ?? ''); - $('e-leds').placeholder = String(app.room.definitions[f.def].leds); set('e-x', round3(f.x)); set('e-y', round3(f.y)); set('e-dir', f.direction); + set('e-port', f.port ?? 4048); + set('e-offset', f.offset ?? 0); + set('e-universe', f.universe ?? 0); + set('e-address', f.address ?? 1); + set('e-order', f.color_order || 'rgb'); + set('e-zero', f.zero ?? 0); + $('e-panrev').checked = Boolean(f.pan_reverse); } function renderDrawer() { @@ -764,9 +1126,19 @@ return; } $('d-name').textContent = s.name; - $('d-meta').textContent = `${s.id} · ${s.mac}`; + const f = app.room.fixtures[s.id] || {}; + $('d-meta').textContent = isNet(s) ? `${s.id} · ${netWhere(f)}` : `${s.id} · ${s.mac}`; + $('d-power').hidden = isNet(s); + $('d-log-head').hidden = isNet(s); + $('d-log').hidden = isNet(s); + if (app.drawerFor !== s) { + app.drawerFor = s; + delete $('d-out-note').dataset.sticky; + } renderFacts(); renderEditForm(); + renderOutput(); + renderLive(); const off = s.state === 'off' || s.state === 'crashed'; $('d-on').disabled = !off || app.takenOver; $('d-off').disabled = off; @@ -819,14 +1191,25 @@ if (raw === '' || !n) { delete f.leds; } else { - f.leds = Math.max(1, Math.min(512, n)); + f.leds = Math.max(1, Math.min(isNet(s) ? NET_LEDS_MAX : 512, n)); } + } else if (key === 'color_order' || key === 'dmx_def') { + f[key] = raw; + } else if (key === 'pan_reverse') { + f.pan_reverse = Boolean(raw); + } else if (['port', 'offset', 'universe', 'address'].includes(key)) { + const lim = { port: [1, 65535], offset: [0, NET_LEDS_MAX - 1], universe: [0, 32767], address: [1, 512] }[key]; + const n = Math.round(Number(raw)); + if (!Number.isFinite(n)) { + return; + } + f[key] = Math.max(lim[0], Math.min(lim[1], n)); } else { const v = Number(raw); if (!Number.isFinite(v)) { return; } - f[key] = key === 'direction' ? wrapDeg(v) : Math.round(v * 1000) / 1000; + f[key] = key === 'direction' || key === 'zero' ? wrapDeg(v) : Math.round(v * 1000) / 1000; } changed(); } @@ -847,9 +1230,191 @@ $('r-width').value = app.room.width; $('r-depth').value = app.room.depth; renderDefs(); + renderDmxDefs(); + $('r-dmx-edit').hidden = true; + roomNote(''); $('room-dialog').showModal(); } + // ----- DMX definitions: the channel lists of the room's cans and movers ------------------- + + /** A line under the room dialog's DMX tools: what an import did (ok) or why it failed. */ + function roomNote(text, ok = false) { + $('r-error').textContent = text; + $('r-error').className = ok ? 'muted small' : 'error'; + } + + function renderDmxDefs() { + const defs = app.room.dmx_definitions; + const rows = Object.entries(defs).map(([k, d]) => { + const used = Object.values(app.room.fixtures).filter((f) => f.dmx_def === k).length; + const tr = document.createElement('tr'); + tr.innerHTML = '
'; + tr.querySelector('code').textContent = k; + tr.querySelector('div').textContent = [d.manufacturer, d.model].filter(Boolean).join(' '); + tr.cells[1].textContent = d.mode || ''; + tr.cells[2].textContent = `${d.channels.length} ch · ${used ? `${used} fixture${used === 1 ? '' : 's'}` : 'unused'}`; + const edit = document.createElement('button'); + edit.type = 'button'; + edit.className = 'link'; + edit.textContent = 'edit'; + edit.onclick = () => openDmxEdit(k); + tr.cells[3].append(edit); + if (!used) { + const del = document.createElement('button'); + del.type = 'button'; + del.className = 'link'; + del.textContent = 'remove'; + del.onclick = () => { + delete defs[k]; + changed(); + renderDmxDefs(); + }; + tr.cells[4].append(del); + } + return tr; + }); + if (!rows.length) { + const tr = document.createElement('tr'); + tr.innerHTML = 'None yet. Adding a DMX can or mover adds a qlcplus preset.'; + rows.push(tr); + } + $('r-dmx').replaceChildren(...rows); + const presets = Object.keys(RigDmx.PRESET_DEFINITIONS).filter((k) => !(k in defs)); + $('r-dmx-preset').replaceChildren(new Option(presets.length ? 'Add a preset…' : 'Presets: all added', ''), + ...presets.map((k) => new Option(`${k} (${RigDmx.PRESET_DEFINITIONS[k].channels.length} ch)`, k))); + } + + /** Edit (or, with no name, make) a DMX definition in the form under the table. */ + function openDmxEdit(name, draft) { + const d = draft || app.room.dmx_definitions[name] || { manufacturer: '', model: '', mode: '', channels: [] }; + app.dmxEditing = { name: name || '', d }; + $('r-dmx-name').value = name || ''; + $('r-dmx-mode').value = d.mode || ''; + $('r-dmx-chans').value = d.channels.join('\n'); + $('r-dmx-error').textContent = ''; + $('r-dmx-edit').hidden = false; + $('r-dmx-name').focus(); + } + + function saveDmxEdit() { + const ed = app.dmxEditing; + const defs = app.room.dmx_definitions; + const name = $('r-dmx-name').value.trim(); + const channels = $('r-dmx-chans').value.split('\n').map((c) => c.trim()).filter(Boolean); + const err = (t) => { + $('r-dmx-error').textContent = t; + }; + if (!name || name.length > 60) { + return err('A definition needs a name (up to 60 characters).'); + } + if (name !== ed.name && name in defs) { + return err('There is already a definition with that name.'); + } + if (!channels.length || channels.length > 512 || channels.some((c) => c.length > 40)) { + return err('List 1-512 channels, one per line, each up to 40 characters.'); + } + const d = { manufacturer: ed.d.manufacturer || '', model: ed.d.model || '', mode: $('r-dmx-mode').value.trim(), channels }; + if (ed.name && ed.name !== name) { + delete defs[ed.name]; + for (const f of Object.values(app.room.fixtures)) { + if (f.dmx_def === ed.name) { + f.dmx_def = name; + } + } + } + defs[name] = d; + $('r-dmx-edit').hidden = true; + changed(); + renderDmxDefs(); + } + + async function readFile(input) { + const file = input.files && input.files[0]; + input.value = ''; + return file ? file.text() : null; + } + + /** A QLC+ fixture definition: one DMX definition per mode, named " ". */ + async function importQxf(input) { + const text = await readFile(input); + if (text === null) { + return; + } + let modes; + try { + modes = RigDmx.parseQxf(text); + } catch (err) { + roomNote(`Could not read that fixture definition: ${err.message}`); + return; + } + const defs = app.room.dmx_definitions; + for (const m of modes) { + let name = `${m.manufacturer} ${m.model}${modes.length > 1 ? ` ${m.mode}` : ''}`.trim().slice(0, 60) || 'fixture'; + for (let n = 2; name in defs; n += 1) { + name = `${name.replace(/ \(\d+\)$/, '')} (${n})`; + } + defs[name] = { manufacturer: m.manufacturer.slice(0, 60), model: m.model.slice(0, 60), mode: m.mode.slice(0, 60), + channels: m.channels.map((c) => c.slice(0, 40)) }; + } + roomNote(`Added ${modes.length} definition${modes.length === 1 ? '' : 's'} from the .qxf.`, true); + changed(); + renderDmxDefs(); + } + + /** A qlcplus stage/map.json: its definitions, and its cans and movers placed in this room (y moved so they fit). */ + async function importStageMap(input) { + const text = await readFile(input); + if (text === null) { + return; + } + let map; + try { + map = JSON.parse(text); + } catch (_e) { + roomNote('That file is not JSON.'); + return; + } + const defs = app.room.dmx_definitions; + for (const [k, d] of Object.entries(map.definitions || {})) { + if (Array.isArray(d.channels) && d.channels.length) { + defs[k.slice(0, 60)] = { manufacturer: String(d.manufacturer || ''), model: String(d.model || ''), + mode: String(d.mode || ''), channels: d.channels.map((c) => String(c).slice(0, 40)) }; + } + } + const fx = Object.entries(map.fixtures || {}).filter(([, f]) => Number.isFinite(f.x) && Number.isFinite(f.y)); + const ys = fx.map(([, f]) => f.y); + const xs = fx.map(([, f]) => Math.abs(f.x)); + const dy = ys.length ? 0.5 - Math.min(...ys) : 0; + let added = 0; + for (const [key, f] of fx) { + const kind = f.kind === 'mover' ? 'mover' : 'can'; + const dmxDef = f.def && defs[f.def] ? f.def : dmxDefFor(kind); + let id = String(key).replace(/[^A-Za-z0-9_.#-]/g, '') || nextNetLabel(kind); + while (id in app.room.fixtures) { + id = nextNetLabel(id); + } + const address = f.address != null ? Number(f.address) + 1 : f.dmx != null ? Number(f.dmx) : nextDmxAddress(defs[dmxDef].channels.length).address; + app.room.fixtures[id] = { + label: String(f.label || key).slice(0, 47), type: 'artnet', kind, dmx_def: dmxDef, + universe: Number(f.universe) || 0, address, x: round3(f.x), y: round3(f.y + dy), + direction: wrapDeg(Number(f.direction) || 0), + ...(kind === 'mover' ? { zero: wrapDeg(Number(f.zero) || 0), pan_reverse: Boolean(f.pan_reverse) } : {}), + }; + added += 1; + } + if (fx.length) { + // grow the room to hold them + app.room.width = Math.max(app.room.width, Math.ceil((Math.max(...xs) * 2 + 1) * 10) / 10, Number(map.building_width) || 0); + app.room.depth = Math.max(app.room.depth, Math.ceil((Math.max(...ys) + dy + 0.5) * 10) / 10); + $('r-width').value = app.room.width; + $('r-depth').value = app.room.depth; + } + roomNote(`Added ${Object.keys(map.definitions || {}).length} definitions and ${added} fixtures from ${map.name || 'the stage map'}.`, true); + changed(); + renderDmxDefs(); + } + function renderDefs() { const rows = Object.entries(app.room.definitions).map(([k, d]) => { const used = Object.values(app.room.fixtures).filter((f) => f.def === k).length; @@ -904,6 +1469,21 @@ } }; } + $('r-dmx-preset').onchange = () => { + const k = $('r-dmx-preset').value; + if (k && !(k in app.room.dmx_definitions)) { + app.room.dmx_definitions[k] = JSON.parse(JSON.stringify(RigDmx.PRESET_DEFINITIONS[k])); + changed(); + } + renderDmxDefs(); + }; + $('r-dmx-new').onclick = () => openDmxEdit(''); + $('r-dmx-cancel').onclick = () => { + $('r-dmx-edit').hidden = true; + }; + $('r-dmx-save').onclick = saveDmxEdit; + $('r-dmx-qxf').onchange = () => importQxf($('r-dmx-qxf')); + $('r-dmx-map').onchange = () => importStageMap($('r-dmx-map')); $('r-add-def').onclick = () => { const name = $('r-def-name').value.trim(); const leds = Math.round(Number($('r-def-leds').value)); @@ -1113,8 +1693,41 @@ s.lit = lit; } + /** A can or mover: its light under everything, its body on top (see frame). */ + function pointFixture(s) { + const f = app.room.fixtures[s.id] || {}; + return { id: s.id, kind: s.kind, label: s.name, x: s.info.x, y: s.info.y, direction: f.direction || 0, zero: f.zero || 0 }; + } + + function drawPointHandle(s, sg) { + if (!app.edit) { + return; + } + const ctx = app.ctx; + ctx.strokeStyle = app.sel.has(s) ? SELECT : LABEL; + ctx.lineWidth = 1.5; + ctx.setLineDash([3, 3]); + ctx.beginPath(); + ctx.moveTo(sg.ax, sg.ay); + ctx.lineTo(sg.bx, sg.by); + ctx.stroke(); + ctx.setLineDash([]); + ctx.beginPath(); + ctx.arc(sg.bx, sg.by, HANDLE_R, 0, Math.PI * 2); + ctx.stroke(); + } + function frame() { - if (app.view && app.dirty) { + if (app.room && app.netDirty) { + app.netDirty = false; + updateNet(); + app.dirty = true; + if (app.selected && isNet(app.selected)) { + renderLive(); + } + } + const animated = app.room && app.strips.some((s) => s.info.point && s.live && RigDmxDraw.animated(pointFixture(s), s.live)); + if (app.view && (app.dirty || animated)) { app.dirty = false; const ctx = app.ctx; const c = app.canvas; @@ -1122,7 +1735,24 @@ ctx.fillStyle = BG; ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr); drawRoom(); - app.strips.forEach((s, i) => drawStrip(s, app.geo[i])); + app.strips.forEach((s, i) => !s.info.point && drawStrip(s, app.geo[i])); + const points = app.strips.map((s, i) => [s, app.geo[i]]).filter(([s]) => s.info.point); + if (points.length) { + const v = app.view; + ctx.save(); + ctx.beginPath(); + ctx.rect(v.sx(-app.room.width / 2), v.sy(app.room.depth), app.room.width * v.scale, app.room.depth * v.scale); + ctx.clip(); // beams stay on the floor + ctx.globalCompositeOperation = 'lighter'; + for (const [s] of points) { + RigDmxDraw.drawLight(ctx, v, pointFixture(s), s.live || { patched: false }); + } + ctx.restore(); + for (const [s, sg] of points) { + drawPointHandle(s, sg); + s.bodyR = RigDmxDraw.drawBody(ctx, v, pointFixture(s), s.live || { patched: false }, app.sel.has(s)); + } + } if (app.marquee) { const m = app.marquee; ctx.save(); @@ -1140,6 +1770,9 @@ /** Whether a strip's segment passes through the box (canvas px), sampled along its length. */ function stripTouchesBox(sg, x0, y0, x1, y1) { + if (sg.point) { + return sg.ax >= x0 && sg.ax <= x1 && sg.ay >= y0 && sg.ay <= y1; + } for (let i = 0; i <= 20; i += 1) { const t = i / 20; const x = sg.ax + (sg.bx - sg.ax) * t; @@ -1164,7 +1797,8 @@ let best = null; let bestD = 10; app.strips.forEach((s, i) => { - const d = RigLayout.distToStrip(app.geo[i], x, y); + const sg = app.geo[i]; + const d = sg.point ? Math.max(0, Math.hypot(x - sg.ax, y - sg.ay) - (s.bodyR || 13)) : RigLayout.distToStrip(sg, x, y); if (d < bestD) { bestD = d; best = s; @@ -1309,7 +1943,8 @@ } } else { const deg = (Math.atan2(wx - f.x, wy - f.y) * 180) / Math.PI; - f.direction = wrapDeg(ev.shiftKey ? deg : Math.round(deg / SNAP_DEG) * SNAP_DEG); + f[f.type === 'artnet' && f.kind === 'mover' ? 'zero' : 'direction'] = + wrapDeg(ev.shiftKey ? deg : Math.round(deg / SNAP_DEG) * SNAP_DEG); } d.moved = true; const infos = new Map(RigLayout.roomStrips(app.room).map((i) => [i.id, i])); @@ -1387,6 +2022,18 @@ ); }; $('centre-strips').onclick = () => centreStrips(); + try { + $('add-type').value = localStorage.getItem('ledsim.addType') || 'espnow'; + } catch (_e) { + // storage unavailable: start with ESP-NOW bars + } + $('add-type').onchange = () => { + try { + localStorage.setItem('ledsim.addType', $('add-type').value); + } catch (_e) { + // the choice lasts for this page only + } + }; $('d-close').onclick = () => select(null); $('d-on').onclick = () => app.selected && powerOn(app.selected); $('d-off').onclick = () => app.selected && powerOff(app.selected); @@ -1404,6 +2051,21 @@ $('e-x').onchange = () => fixtureField('x', $('e-x').value); $('e-y').onchange = () => fixtureField('y', $('e-y').value); $('e-dir').onchange = () => fixtureField('direction', $('e-dir').value); + for (const [id, key] of [['e-port', 'port'], ['e-offset', 'offset'], ['e-universe', 'universe'], ['e-address', 'address'], + ['e-order', 'color_order'], ['e-dmxdef', 'dmx_def'], ['e-zero', 'zero']]) { + $(id).onchange = () => fixtureField(key, $(id).value); + } + $('e-panrev').onchange = () => fixtureField('pan_reverse', $('e-panrev').checked); + $('d-mkout').onclick = makeOutput; + $('d-testout').onclick = testOutput; + setInterval(() => { + if (app.selected && isNet(app.selected)) { + renderFacts(); // "last … s ago" + } + if (app.strips.some(isNet)) { + app.netDirty = true; // a fixture whose data stopped goes back to "no data" + } + }, 500); wireDialogs(); wireCanvas(); new ResizeObserver(() => layoutView()).observe($('rig')); diff --git a/led-simulator/web/dmx-draw.js b/led-simulator/web/dmx-draw.js new file mode 100644 index 0000000..86bc2f5 --- /dev/null +++ b/led-simulator/web/dmx-draw.js @@ -0,0 +1,343 @@ +/* Drawing the simulated rig's DMX cans and movers: glow, beam, floor spot and body. + * Ported from the qlcplus stage simulator (technicalkiwi/qlcplus simulator/static/app.js), same look and timing. + * Headings are degrees clockwise from +y, y up the screen, as in both sims. The live view is RigDmx.viewFixture(). + * + * RigDmxDraw.drawLight(ctx, view, fixture, live) beam and glow (call with globalCompositeOperation 'lighter') + * RigDmxDraw.drawBody(ctx, view, fixture, live, selected) + * RigDmxDraw.animated(live) whether it changes with time (strobe, chase, smoothing) + * + * view: {sx(x), sy(y), scale}: metres -> canvas px; fixture: {id, kind: 'can'|'mover', label, x, y, direction, zero} + */ +(function (g) { + 'use strict'; + + const PAR_PALETTE = [ + [255, 0, 0], [255, 96, 0], [255, 200, 0], [255, 255, 0], [0, 255, 0], + [0, 255, 160], [0, 64, 255], [140, 0, 255], [255, 0, 160], [255, 255, 255], + ]; + // Below this plan reach a mover is pointing near straight down. + const SPOT_M = 0.5; + // Throw to the floor for the spot under a mover. + const DROP_M = 2.5; + // A can's beam: fixed along its heading. + const CAN_BEAM = { beam: 2.2, zoom: 25, focus: 0.35 }; + + const aims = new Map(); + const now = () => performance.now() / 1000; + + function luma(r, gr, b) { + return 0.2126 * r + 0.7152 * gr + 0.0722 * b; + } + + function hsv(hue, value) { + const h = ((hue % 1) + 1) % 1; + const i = Math.floor(h * 6); + const f = h * 6 - i; + const q = value * (1 - f); + const t = value * f; + const map = [[value, t, 0], [q, value, 0], [0, value, t], [0, q, value], [t, 0, value], [value, 0, q]]; + return map[i % 6].map((c) => Math.round(c * 255)); + } + + function scaleColour(colour, dimmer) { + const level = (dimmer || 0) / 255; + return colour.map((c) => Math.round(c * level)); + } + + function paletteColour(live, gradient) { + const palette = live.palette && live.palette.length ? live.palette : PAR_PALETTE; + const phase = now() * (live.speed_hz || 0.35); + const index = Math.floor(phase) % palette.length; + if (!gradient) { + return palette[index]; + } + const next = palette[(index + 1) % palette.length]; + const blend = phase - Math.floor(phase); + return palette[index].map((c, slot) => Math.round(c + (next[slot] - c) * blend)); + } + + function canColour(live) { + const mode = live.function || 'mix'; + const dimmer = live.dimmer || 0; + if (mode === 'jump' || mode === 'gradient') { + return scaleColour(paletteColour(live, mode === 'gradient'), dimmer); + } + if (mode === 'pulse') { + const wave = 0.5 - 0.5 * Math.cos(now() * (live.speed_hz || 0.4) * Math.PI * 2); + const depth = 0.05 + 0.95 * wave; + return [live.r || 0, live.g || 0, live.b || 0].map((c) => Math.round(c * depth)); + } + if (mode === 'sound') { + const speed = live.speed_hz || 1; + const variant = live.sound === 2 ? 2 : 1; + const bpm = (variant === 2 ? 156 : 104) * (0.55 + Math.min(speed, 8) / 10); + const beat = ((now() * bpm) / 60) % 1; + let hit = beat < 0.08 ? 1 : 0.04; + if (variant === 2 && beat > 0.5 && beat < 0.58) { + hit = 1; + } + const colour = (live.palette && live.palette[variant === 2 ? 4 : 0]) || PAR_PALETTE[variant === 2 ? 4 : 0]; + return scaleColour(colour, dimmer).map((c) => Math.round(c * hit)); + } + return [live.r || 0, live.g || 0, live.b || 0]; + } + + function effectPixels(live) { + const source = (live.pixels || []).map((p) => p.slice()); + if (!live.dynamic || !source.length) { + return source; + } + const count = source.length; + const lit = source.find((p) => p[0] + p[1] + p[2] > 0); + const fallback = lit || scaleColour([255, 255, 255], live.dimmer || 0); + const t = now() * (live.speed_hz || 1); + return source.map((pixel, index) => { + const colour = pixel[0] + pixel[1] + pixel[2] > 0 ? pixel : fallback; + if (live.dynamic === 'rainbow') { + return hsv((t * 0.2 + index / count) % 1, (live.dimmer || 0) / 255); + } + let level = 1; + if (live.dynamic === 'chase') { + level = Math.floor(t) % count === index ? 1 : 0.08; + } else if (live.dynamic === 'reverse') { + level = Math.floor(t) % count === count - 1 - index ? 1 : 0.08; + } else if (live.dynamic === 'bounce') { + const span = Math.max(1, count - 1); + level = Math.round(Math.abs((t % (2 * span)) - span)) === index ? 1 : 0.08; + } else if (live.dynamic === 'pulse') { + level = 0.15 + 0.85 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2)); + } else if (live.dynamic === 'pairs') { + level = Math.floor(t) % 2 === index % 2 ? 1 : 0.08; + } + return colour.map((c) => Math.round(c * level)); + }); + } + + function mixPixels(pixels) { + let red = 0, green = 0, blue = 0, weight = 0; + for (const p of pixels) { + const w = p[0] + p[1] + p[2]; + red += p[0] * w; + green += p[1] * w; + blue += p[2] * w; + weight += w; + } + return weight <= 0 ? [0, 0, 0] : [Math.round(red / weight), Math.round(green / weight), Math.round(blue / weight)]; + } + + function shutter(live) { + if (!live.strobe_hz) { + return 1; + } + const t = now(); + if (live.strobe_mode === 'random') { + const bucket = Math.floor(t * live.strobe_hz); + return (Math.abs(Math.sin(bucket * 12.9898) * 43758.5453) % 1) > 0.55 ? 1 : 0; + } + const period = 1 / live.strobe_hz; + return t % period < period * 0.42 ? 1 : 0; + } + + // Pan and reach ease toward the target at the fixture's Pan/Tilt Speed + function aimed(id, live, zero) { + const targetPan = (zero || 0) + (live.pan_deg || 0); + const targetBeam = live.beam_m || 0; + const t = now(); + let st = aims.get(id); + if (!st) { + st = { pan: targetPan, beam: targetBeam, t, settled: true }; + aims.set(id, st); + return st; + } + const dt = Math.min(0.05, Math.max(0, t - st.t)); + st.t = t; + const fast = live.move == null ? 1 : live.move; + if (fast > 0.97) { + st.pan = targetPan; + st.beam = targetBeam; + } else { + const k = 1 - Math.exp(-dt / (0.05 + (1 - fast) * 1.8)); + st.pan += (targetPan - st.pan) * k; + st.beam += (targetBeam - st.beam) * k; + } + st.settled = Math.abs(targetPan - st.pan) < 0.05 && Math.abs(targetBeam - st.beam) < 0.002; + return st; + } + + function appearance(fixture, live) { + const pixels = fixture.kind === 'mover' ? effectPixels(live) : null; + const [r, gr, b] = fixture.kind === 'can' + ? canColour(live) + : pixels && live.dynamic ? mixPixels(pixels) : [live.r || 0, live.g || 0, live.b || 0]; + const gate = shutter(live); + return { + r: Math.round(r * gate), + g: Math.round(gr * gate), + b: Math.round(b * gate), + dimmer: live.dimmer || 0, + pixels: pixels && pixels.map((p) => p.map((c) => Math.round(c * gate))), + }; + } + + function drawGlow(ctx, v, fixture, color) { + const level = (color.r + color.g + color.b) / (255 * 3); + if (level <= 0.01) { + return; + } + const x = v.sx(fixture.x); + const y = v.sy(fixture.y); + const radius = (fixture.kind === 'mover' ? 70 : 54) * (0.45 + level) * bodyScale(v); + const gradient = ctx.createRadialGradient(x, y, 2, x, y, radius); + gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${0.55 * level + 0.15})`); + gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`); + ctx.fillStyle = gradient; + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2); + ctx.fill(); + } + + function drawSpot(ctx, v, fixture, pan, reach, half, color, spread) { + const rad = (pan * Math.PI) / 180; + const cx = v.sx(fixture.x + Math.sin(rad) * reach); + const cy = v.sy(fixture.y + Math.cos(rad) * reach); + const radius = Math.max(4, DROP_M * Math.tan(half) * v.scale); + const gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius); + const alpha = 0.85 * (1 - spread * 0.35); + gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${alpha})`); + gradient.addColorStop(0.7, `rgba(${color.r},${color.g},${color.b},${alpha * 0.6})`); + gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`); + ctx.fillStyle = gradient; + ctx.beginPath(); + ctx.arc(cx, cy, radius, 0, Math.PI * 2); + ctx.fill(); + } + + function drawBeam(ctx, v, fixture, live, color, fixed) { + const level = (color.r + color.g + color.b) / 255; + if (live.patched === false || level <= 0.02) { + return; + } + const aim = fixed || aimed(fixture.id, live, fixture.zero); + // Mover reach is signed: below zero the head has tilted past straight down. + const reach = fixed ? fixed.beam : aim.beam; + // DMX focus 0 is a wide wash. Focus 255 holds the zoom angle. Fixed beams pass spread: 0 tight, 1 wide. + const spread = fixed ? fixed.focus : 1 - (live.focus || 0); + const zoom = fixed ? fixed.zoom : live.zoom_deg || 8; + const tight = zoom / 2; + const wide = Math.max(tight, 40); + const half = ((tight + (wide - tight) * spread) * Math.PI) / 180; + if (fixture.kind === 'mover' && Math.abs(reach) < SPOT_M) { + drawSpot(ctx, v, fixture, aim.pan, reach, half, color, spread); + return; + } + const length = Math.abs(reach); + if (!length) { + return; + } + const rad = ((aim.pan + (reach < 0 ? 180 : 0)) * Math.PI) / 180; + const at = (a) => [v.sx(fixture.x + Math.sin(a) * length), v.sy(fixture.y + Math.cos(a) * length)]; + const tip = at(rad); + const left = at(rad - half); + const right = at(rad + half); + const x0 = v.sx(fixture.x); + const y0 = v.sy(fixture.y); + ctx.beginPath(); + ctx.moveTo(x0, y0); + ctx.lineTo(left[0], left[1]); + ctx.lineTo(right[0], right[1]); + ctx.closePath(); + const gradient = ctx.createLinearGradient(x0, y0, tip[0], tip[1]); + const alpha = 0.85 * (1 - spread * 0.35); + gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${alpha})`); + gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`); + ctx.fillStyle = gradient; + ctx.fill(); + } + + function lensRotation(live) { + if (live.spin_dps) { + return (now() * live.spin_dps * Math.PI) / 180; + } + return ((live.lens_deg || 0) * Math.PI) / 180; + } + + // Bodies are drawn at a fixed pixel size in qlcplus; here they follow the zoom a little so a big room stays legible + function bodyScale(v) { + return Math.max(0.6, Math.min(1.6, v.scale / 90)); + } + + /** Beam and glow. Call with ctx.globalCompositeOperation = 'lighter'. */ + function drawLight(ctx, v, fixture, live) { + const color = appearance(fixture, live); + if (fixture.kind === 'mover') { + drawBeam(ctx, v, fixture, live, color, null); + } else { + drawBeam(ctx, v, fixture, live, color, { pan: fixture.direction || 0, ...CAN_BEAM }); + } + drawGlow(ctx, v, fixture, color); + } + + function drawBody(ctx, v, fixture, live, selected) { + const color = appearance(fixture, live); + const x = v.sx(fixture.x); + const y = v.sy(fixture.y); + const pixels = color.pixels || []; + const head = fixture.kind === 'mover' && pixels.length ? pixels[0] : [color.r, color.g, color.b]; + const lit = head[0] + head[1] + head[2] > 8; + const k = bodyScale(v); + const size = (fixture.kind === 'mover' ? 15 : 13) * k; + ctx.beginPath(); + if (fixture.kind === 'mover') { + ctx.rect(x - size, y - size, size * 2, size * 2); + } else { + ctx.arc(x, y, size, 0, Math.PI * 2); + } + ctx.fillStyle = lit ? `rgb(${head[0]},${head[1]},${head[2]})` : '#2a2a30'; + ctx.fill(); + ctx.lineWidth = selected ? 2.5 : 1.5; + ctx.strokeStyle = selected ? '#5aa9ff' : live.patched === false ? '#5c5c66' : '#c8c8d0'; + ctx.stroke(); + if (fixture.kind === 'mover' && pixels.length > 1) { + const ring = pixels.slice(1); + const spin = lensRotation(live); + ring.forEach((p, index) => { + const angle = spin + (index / ring.length) * Math.PI * 2 - Math.PI / 2; + ctx.beginPath(); + ctx.arc(x + Math.cos(angle) * (size + 7 * k), y + Math.sin(angle) * (size + 7 * k), 3.5 * k, 0, Math.PI * 2); + ctx.fillStyle = p[0] + p[1] + p[2] > 0 ? `rgb(${p[0]},${p[1]},${p[2]})` : '#333'; + ctx.fill(); + }); + } + if (fixture.kind === 'can') { + // a tick on the rim shows the way the can points + const a = ((fixture.direction || 0) * Math.PI) / 180; + ctx.beginPath(); + ctx.moveTo(x + Math.sin(a) * size, y - Math.cos(a) * size); + ctx.lineTo(x + Math.sin(a) * (size + 6 * k), y - Math.cos(a) * (size + 6 * k)); + ctx.lineWidth = 2; + ctx.strokeStyle = selected ? '#5aa9ff' : '#c8c8d0'; + ctx.stroke(); + } + ctx.fillStyle = lit && luma(head[0], head[1], head[2]) > 140 ? '#16161a' : '#f2f2f4'; + ctx.font = `600 ${Math.round(11 * k)}px system-ui, sans-serif`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText(fixture.label, x, y); + ctx.textBaseline = 'alphabetic'; + return size; + } + + /** Whether the fixture's look changes with time, so the canvas must keep redrawing. */ + function animated(fixture, live) { + if (live.strobe_hz || live.dynamic || live.spin_dps) { + return true; + } + if (fixture.kind === 'can' && ['jump', 'gradient', 'pulse', 'sound'].includes(live.function)) { + return true; + } + const st = aims.get(fixture.id); + return fixture.kind === 'mover' && !!st && !st.settled; + } + + g.RigDmxDraw = { drawLight, drawBody, animated, bodyScale }; +})(typeof self !== 'undefined' ? self : globalThis); diff --git a/led-simulator/web/dmx.js b/led-simulator/web/dmx.js new file mode 100644 index 0000000..7d06f80 --- /dev/null +++ b/led-simulator/web/dmx.js @@ -0,0 +1,492 @@ +// DMX fixtures for the simulated rig: a frame's channels to colour, beam and strobe. +// Ported from the qlcplus stage simulator (technicalkiwi/qlcplus simulator/decode.py), same rules and constants. +// Channel order comes from the room's DMX definitions: names such as Dimmer, Red, Pan and Zoom select the slots. + +// Loaded as a classic script before app.js: everything is on RigDmx. +(function (g) { + 'use strict'; + + const PIXEL = /^(red|green|blue|white) (\d+)$/i; + + const PAN_DEGREES = 540.0; + // Tilt 127 is straight down. 0 leans along the pan heading, 255 away from it. + const TILT_DEGREES = 270.0; + // Plan reach of a beam at or above horizontal. + const BEAM_MAX_M = 4.7; + const ZOOM_MIN = 5.0; + const ZOOM_MAX = 45.0; + + // BCC145 8ch: strobe 0–7 is open. Small Eye centre strobe 0–3 is open. + const CAN_STROBE_OPEN = 7; + const MOVER_STROBE_OPEN = 3; + + // beamZ BCC145 8ch macro: 0–50 RGBW mix, 51–100 fixed colour, 101–150 jump, 151–200 pulse, + // 201–250 gradient, 251–255 sound. Speed is slow to fast. + const PAR_PALETTE = [ + [255, 0, 0], [255, 96, 0], [255, 200, 0], [255, 255, 0], [0, 255, 0], + [0, 255, 160], [0, 64, 255], [140, 0, 255], [255, 0, 160], [255, 255, 255], + ]; + + // Small Eye 43ch colour macros, static masks, and dynamic chases. 0–9 is no function. + const MOVER_MACROS = [ + [255, 0, 0], [255, 80, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255], + [0, 40, 255], [160, 0, 255], [255, 0, 180], [255, 255, 255], [255, 180, 80], + ]; + const STATIC_MASKS = [ + ['all', [1, 1, 1, 1, 1, 1, 1]], + ['odds', [1, 0, 1, 0, 1, 0, 1]], + ['evens', [0, 1, 0, 1, 0, 1, 0]], + ['center', [0, 0, 0, 1, 0, 0, 0]], + ['ends', [1, 0, 0, 0, 0, 0, 1]], + ['left', [1, 1, 1, 1, 0, 0, 0]], + ['right', [0, 0, 0, 1, 1, 1, 1]], + ['one', null], + ]; + const DYNAMIC = ['chase', 'reverse', 'rainbow', 'bounce', 'pulse', 'pairs']; + const DYNAMIC_LABELS = { + chase: 'chase', reverse: 'reverse chase', rainbow: 'rainbow', bounce: 'bounce', pulse: 'pixel pulse', pairs: 'pairs', + }; + + const MOVER_43 = [ + 'Pan', 'Pan Fine', 'Tilt', 'Tilt Fine', 'Pan/Tilt Speed', 'Lens Rotate', 'Zoom', 'Focus', + 'Center Brightness', 'Center Strobe', + 'Red 1', 'Green 1', 'Blue 1', 'White 1', + 'Red 2', 'Green 2', 'Blue 2', 'White 2', + 'Red 3', 'Green 3', 'Blue 3', 'White 3', + 'Red 4', 'Green 4', 'Blue 4', 'White 4', + 'Red 5', 'Green 5', 'Blue 5', 'White 5', + 'Red 6', 'Green 6', 'Blue 6', 'White 6', + 'Red 7', 'Green 7', 'Blue 7', 'White 7', + 'Colour Temperature', 'Colour Macro', 'Static Effect', 'Dynamic Effect', 'Reset', + ]; + + /** The two fixtures of the qlcplus stage map, as DMX definitions. */ + const PRESET_DEFINITIONS = { + 'beamZ BCC145': { + manufacturer: 'beamZ', model: 'BCC145', mode: '8 Channel', + channels: ['Dimmer', 'Strobe', 'Red', 'Green', 'Blue', 'White', 'Macro', 'Speed'], + }, + 'Small Eye 7 Mover': { manufacturer: 'Small Eye 7', model: 'Mover', mode: '43 Channel', channels: MOVER_43.slice() }, + }; + + const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v)); + const r2 = (v, d) => Math.round(v * 10 ** d) / 10 ** d + 0; // + 0: no -0 + + function find(names, wanted) { + const w = wanted.toLowerCase(); + const i = names.findIndex((n) => n.toLowerCase() === w); + return i < 0 ? null : i; + } + + function value(channels, names, wanted, dflt = 0) { + const i = find(names, wanted); + return i === null || i >= channels.length ? dflt : channels[i]; + } + + function mixRgbw(red, green, blue, white, dimmer) { + const level = clamp(dimmer, 0, 255) / 255; + return [ + Math.round(Math.min(255, red + white) * level), + Math.round(Math.min(255, green + white) * level), + Math.round(Math.min(255, blue + white) * level), + ]; + } + + function pixelGroups(channels, names, dimmer) { + const groups = new Map(); + names.forEach((name, i) => { + const m = PIXEL.exec(name.trim()); + if (!m) { + return; + } + const n = Number(m[2]); + if (!groups.has(n)) { + groups.set(n, {}); + } + groups.get(n)[m[1].toLowerCase()] = i; + }); + const at = (g, c) => (g[c] === undefined || g[c] >= channels.length ? 0 : channels[g[c]]); + return [...groups.keys()].sort((a, b) => a - b).map((n) => { + const g = groups.get(n); + return mixRgbw(at(g, 'red'), at(g, 'green'), at(g, 'blue'), at(g, 'white'), dimmer); + }); + } + + /** count slots from a 0-based address in a 512-byte frame */ + function slotsAt(frame, address, count) { + const out = []; + for (let o = 0; o < count; o++) { + const i = address + o; + out.push(frame && i >= 0 && i < frame.length ? frame[i] : 0); + } + return out; + } + + function strobeHz(v, openMax) { + if (v <= openMax) { + return 0; + } + const span = Math.max(1, 255 - openMax); + return r2(1 + ((v - openMax) / span) * 18, 2); + } + + /** Indexed lens position, 0–60°. Spin ranges are not an index. */ + function lensAngle(v) { + return v <= 127 ? r2((v / 127) * 60, 1) : 0; + } + + /** Degrees per second, negative counter-clockwise: 0–127 index, 128–188 CCW fast to slow, 189–193 stop, 194–255 CW. */ + function lensSpin(v) { + if (v >= 128 && v <= 188) { + return r2(-(40 + ((188 - v) / 60) * 320), 1); + } + if (v >= 194 && v <= 255) { + return r2(40 + ((v - 194) / 61) * 320, 1); + } + return 0; + } + + /** Brightness-weighted mix, so one lit pixel stays its own colour. */ + function beamColour(pixels) { + let red = 0, green = 0, blue = 0, weight = 0; + for (const [pr, pg, pb] of pixels) { + const w = pr + pg + pb; + red += pr * w; + green += pg * w; + blue += pb * w; + weight += w; + } + return weight <= 0 ? [0, 0, 0] : [Math.round(red / weight), Math.round(green / weight), Math.round(blue / weight)]; + } + + function scale(colour, dimmer) { + const level = clamp(dimmer, 0, 255) / 255; + return colour.map((c) => Math.round(c * level)); + } + + function speedHz(speed, slow = 0.35, fast = 8.0) { + return r2(slow + (clamp(speed, 0, 255) / 255) * (fast - slow), 2); + } + + function canMode(macro) { + if (macro <= 50) return 'mix'; + if (macro <= 100) return 'fixed'; + if (macro <= 150) return 'jump'; + if (macro <= 200) return 'pulse'; + if (macro <= 250) return 'gradient'; + return 'sound'; + } + + /** Map value onto count bands from start through 255: [index, 0–1 position], or null. */ + function rangePick(v, start, count) { + if (v < start || count <= 0) { + return null; + } + const span = 256 - start; + const index = Math.min(count - 1, Math.floor(((v - start) * count) / span)); + const band = span / count; + const frac = (v - start - index * band) / band; + return [index, clamp(frac, 0, 0.999)]; + } + + /** 0 leaves the colour alone. Higher values warm it, the way a CTO does. */ + function applyCto(red, green, blue, amount) { + if (amount <= 0) { + return [red, green, blue]; + } + const warm = clamp(amount, 0, 255) / 255; + return [red, Math.round(green * (1 - 0.35 * warm)), Math.round(blue * (1 - 0.75 * warm))]; + } + + const CAN_LABELS = { + mix: 'RGBW', fixed: 'fixed colour', jump: 'colour jump', pulse: 'colour pulse', gradient: 'colour gradient', + }; + + function canView(dimmer, strobe, red, green, blue, white, macro, speed, channels) { + const mode = canMode(macro); + const mixed = mixRgbw(red, green, blue, white, dimmer); + let peak = mixRgbw(red, green, blue, white, 255); + if (peak.every((c) => c === 0)) { + peak = [255, 255, 255]; + } + let shown = mixed; + let palette = null; + let sound = 0; + let hz = 0; + if (mode === 'fixed') { + const index = Math.min(PAR_PALETTE.length - 1, Math.floor((Math.max(0, macro - 51) * PAR_PALETTE.length) / 50)); + shown = scale(PAR_PALETTE[index], dimmer); + } else if (mode === 'pulse') { + shown = scale(peak, dimmer); + hz = speedHz(speed, 0.4, 6.0); + } else if (mode === 'jump' || mode === 'gradient' || mode === 'sound') { + palette = PAR_PALETTE.map((c) => c.slice()); + hz = speedHz(speed); + shown = scale(PAR_PALETTE[0], dimmer); + if (mode === 'sound') { + sound = macro >= 254 ? 2 : 1; + } + } + const view = { + r: shown[0], g: shown[1], b: shown[2], + dimmer, + strobe_hz: strobeHz(strobe, CAN_STROBE_OPEN), + strobe_mode: strobe > CAN_STROBE_OPEN ? 'strobe' : 'open', + effect: mode !== 'mix', + function: mode, + function_label: mode === 'sound' ? (sound === 2 ? 'sound 2' : 'sound 1') : CAN_LABELS[mode], + speed_hz: hz, + sound, + channels, + }; + if (palette) { + view.palette = palette; + } + return view; + } + + function decodeCan(channels) { + const at = (i) => (i < channels.length ? channels[i] : 0); + return canView(at(0), at(1), at(2), at(3), at(4), at(5), at(6), at(7), channels); + } + + function decodeCanNamed(channels, names) { + const dimmer = find(names, 'Dimmer') === null ? 255 : value(channels, names, 'Dimmer'); + return canView( + dimmer, + value(channels, names, 'Strobe'), + value(channels, names, 'Red'), + value(channels, names, 'Green'), + value(channels, names, 'Blue'), + value(channels, names, 'White'), + value(channels, names, 'Macro'), + value(channels, names, 'Speed'), + channels, + ); + } + + /** Centre strobe: open, linear strobe, then three random-strobe bands. */ + function moverStrobe(v) { + if (v <= MOVER_STROBE_OPEN) return [0, 'open']; + if (v <= 200) return [strobeHz(v, MOVER_STROBE_OPEN), 'strobe']; + if (v <= 215) return [6, 'random']; + if (v <= 234) return [12, 'random']; + return [18, 'random']; + } + + function decodeMoverNamed(channels, names) { + const v = (n) => value(channels, names, n); + const pan = (v('Pan') << 8) | v('Pan Fine'); + const tilt = (v('Tilt') << 8) | v('Tilt Fine'); + const zoom = v('Zoom'); + const rotate = v('Lens Rotate'); + const dimmer = find(names, 'Center Brightness') === null ? 255 : v('Center Brightness'); + const strobe = v('Center Strobe'); + const pixels = pixelGroups(channels, names, dimmer); + const cto = v('Colour Temperature'); + const macro = rangePick(v('Colour Macro'), 10, MOVER_MACROS.length); + const stat = rangePick(v('Static Effect'), 10, STATIC_MASKS.length); + const dynamic = rangePick(v('Dynamic Effect'), 10, DYNAMIC.length); + + let source = pixels.map((p) => p.slice()); + let fn = 'pixels'; + let label = 'pixels'; + let dynamicName = null; + let speed = 0; + if (macro) { + const colour = scale(MOVER_MACROS[macro[0]], dimmer); + source = Array.from({ length: 7 }, () => colour.slice()); + fn = 'macro'; + label = 'colour macro'; + } + if ((stat || dynamic) && !source.some((p) => p[0] + p[1] + p[2] > 0)) { + const white = scale([255, 255, 255], dimmer); + source = Array.from({ length: 7 }, () => white.slice()); + } + if (stat && !dynamic) { + let [name, mask] = STATIC_MASKS[stat[0]]; + if (name === 'one') { + const pixel = Math.min(6, Math.floor(stat[1] * 7)); + mask = Array.from({ length: 7 }, (_, i) => (i === pixel ? 1 : 0)); + } + source = source.map((p, i) => (mask[i] ? p : [0, 0, 0])); + fn = 'static'; + label = name === 'one' ? 'one pixel' : `static ${name}`; + } + if (dynamic) { + dynamicName = DYNAMIC[dynamic[0]]; + speed = r2(0.4 + dynamic[1] * 6, 2); + fn = 'dynamic'; + label = DYNAMIC_LABELS[dynamicName]; + } + const tinted = source.map((p) => applyCto(p[0], p[1], p[2], cto)); + const [red, green, blue] = beamColour(tinted); + const [rate, strobeMode] = moverStrobe(strobe); + const reset = v('Reset'); + const panSpeed = v('Pan/Tilt Speed'); + const panDeg = ((pan - 32768) / 65536) * PAN_DEGREES; + const zoomDeg = ZOOM_MIN + (zoom / 255) * (ZOOM_MAX - ZOOM_MIN); + const tiltDeg = ((tilt - 32768) / 65536) * TILT_DEGREES; + // Reach along the pan heading on the plan. Negative points behind it. + const lean = clamp(-tiltDeg, -90, 90); + const beamM = BEAM_MAX_M * Math.sin((lean * Math.PI) / 180); + return { + r: red, g: green, b: blue, + dimmer, + strobe_hz: rate, + strobe_mode: strobeMode, + effect: fn !== 'pixels', + function: fn, + function_label: label, + speed_hz: speed, + dynamic: dynamicName, + pan_deg: r2(panDeg, 2), + tilt_deg: r2(tiltDeg, 2), + zoom_deg: r2(zoomDeg, 2), + beam_m: r2(beamM, 3), + pixels: tinted, + spin_dps: lensSpin(rotate), + lens_deg: lensAngle(rotate), + focus: r2(v('Focus') / 255, 3), + move: r2(1 - panSpeed / 255, 3), + cto, + reset: reset >= 200 && reset <= 205, + channels, + }; + } + + function decodeMover(channels) { + return decodeMoverNamed(channels, MOVER_43); + } + + /** Read a fixture using the channel names of its DMX definition. */ + function decodeNamed(channels, names, { kind } = {}) { + if (kind === 'mover' || (find(names, 'Pan') !== null && find(names, 'Tilt') !== null)) { + return decodeMoverNamed(channels, names); + } + return decodeCanNamed(channels, names); + } + + /** + * The live view of a can or mover. + * fixture: {kind, universe, address (DMX 1–512), channel_names, pan_reverse}; universes: Map + */ + function viewFixture(fixture, universes) { + if (!fixture.address || fixture.universe === undefined || fixture.universe === null) { + return { patched: false, r: 0, g: 0, b: 0, dimmer: 0, strobe_hz: 0, channels: [] }; + } + const names = fixture.channel_names || []; + const count = names.length || (fixture.kind === 'mover' ? 43 : 8); + const frame = universes.get(fixture.universe); + const channels = slotsAt(frame, fixture.address - 1, count); + let view; + if (names.length) { + view = decodeNamed(channels, names, { kind: fixture.kind }); + } else if (fixture.kind === 'mover') { + view = decodeMover(channels); + } else { + view = decodeCan(channels); + } + if (fixture.pan_reverse && 'pan_deg' in view) { + view.pan_deg = -view.pan_deg; + } + view.patched = true; + return view; + } + + /** + * The RGB bytes of a pixel strip fed by Art-Net: the first universe from the address, then 170 pixels a + * universe from channel 1 (the way the controller's Art-Net output sends them). Same rule as dmx_runs() in sim_rig.c. + */ + function artnetPixels(universes, universe, address, leds) { + const out = new Uint8Array(leds * 3); + let px = 0; + let u = universe; + let a0 = address - 1; + while (px < leds) { + const frame = universes.get(u); + const fit = Math.floor((512 - a0) / 3); + const take = Math.min(fit, leds - px); + if (frame) { + out.set(frame.subarray(a0, a0 + take * 3), px * 3); + } + px += take; + u += 1; + a0 = 0; + if (u - universe > 32) { + break; + } + } + return out; + } + + /** The DMX channels [universe, start0, end0) an Art-Net fixture uses (for the editor's next free address). */ + function dmxRuns(fixture, room, leds) { + const u = fixture.universe ?? 0; + const a0 = (fixture.address ?? 1) - 1; + if ((fixture.kind ?? 'pixels') !== 'pixels') { + const d = (room.dmx_definitions || {})[fixture.dmx_def]; + return [[u, a0, a0 + (d ? d.channels.length : 0)]]; + } + const runs = []; + let left = leds; + let n = 0; + while (left > 0 && n < 32) { + const take = Math.min(n === 0 ? Math.floor((512 - a0) / 3) : 170, left); + const start = n === 0 ? a0 : 0; + runs.push([u + n, start, start + take * 3]); + left -= take; + n++; + } + return runs; + } + + /** Channel names of a QLC+ fixture definition (.qxf) for each mode: [{manufacturer, model, mode, channels}] */ + function parseQxf(text) { + const doc = new DOMParser().parseFromString(text, 'application/xml'); + if (doc.querySelector('parsererror')) { + throw new Error('not an XML file'); + } + const tag = (el, name) => [...el.children].filter((c) => c.localName === name); + const root = doc.documentElement; + const text1 = (name) => (tag(root, name)[0]?.textContent || '').trim(); + const manufacturer = text1('Manufacturer'); + const model = text1('Model'); + const modes = tag(root, 'Mode'); + if (!modes.length) { + throw new Error('no in this fixture definition'); + } + return modes.map((mode) => { + const chans = tag(mode, 'Channel') + .sort((a, b) => Number(a.getAttribute('Number')) - Number(b.getAttribute('Number'))) + .map((c) => c.textContent.trim()); + return { manufacturer, model, mode: mode.getAttribute('Name') || '', channels: chans }; + }); + } + + g.RigDmx = { + PAN_DEGREES, + TILT_DEGREES, + BEAM_MAX_M, + ZOOM_MIN, + ZOOM_MAX, + CAN_STROBE_OPEN, + MOVER_STROBE_OPEN, + PAR_PALETTE, + MOVER_43, + PRESET_DEFINITIONS, + mixRgbw, + slotsAt, + strobeHz, + lensAngle, + lensSpin, + applyCto, + decodeCan, + decodeMover, + decodeNamed, + viewFixture, + artnetPixels, + dmxRuns, + parseQxf, + }; +})(typeof self !== 'undefined' ? self : globalThis); diff --git a/led-simulator/web/index.html b/led-simulator/web/index.html index 7a9576a..34d5364 100644 --- a/led-simulator/web/index.html +++ b/led-simulator/web/index.html @@ -27,9 +27,18 @@