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 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-17 18:13:58 +13:00
1 parent 2fdd55323b
commit 35207a868a
16 files changed
+2859 -118

No files matched your search

+701 -39
View File
@@ -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/<name>)
* 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<n>' / 'p<port>' -> 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 = '<td class="muted"></td><td></td><td class="num"></td>';
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 = '<td><code></code><div class="muted small"></div></td><td></td><td class="muted"></td><td></td><td></td>';
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 = '<td colspan="5" class="muted">None yet. Adding a DMX can or mover adds a qlcplus preset.</td>';
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 "<model> <mode>". */
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'));