feat: pattern gallery as a preset editor; chase steps; sim split with the preset editor

- Pattern gallery shows the controller's presets, one at a time, with a dropdown, Save, Add preset, and
  the controller's field labels, delay limits and colour counts. Edits show in the preview; Save writes to
  the controller only.
- Presets are always timed in ms (beat_time is no longer sent to drivers); beats stay in sequences.
- Chase steps of 0 hold still; the marquee style is removed from the controller, the gallery and the
  driver (submodule commit 12a8e22).
- The rig's split pane opens the preset editor too (Rig / Presets switch and a Preset editor menu entry).
- Sequence editor, room layout and simulator controls from earlier work are included.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-17 07:16:51 +13:00
1 parent 8c783ab926
commit cb51a726bc
79 files changed
+5183 -934

No files matched your search

+280 -78
View File
@@ -59,6 +59,11 @@
queue: [],
booting: 0,
view: null,
sel: new Set(), // the selected strips; app.selected is the one the drawer shows (when exactly one)
marquee: null, // the box being dragged on the floor, canvas px
zoom: 1, // the room's view: z about its fitted size, pan x/y in canvas px (view only, never saved)
pan: { x: 0, y: 0 },
spaceDown: false,
geo: [],
dirty: true,
selected: null,
@@ -456,6 +461,7 @@
}
for (const s of old.values()) {
powerOff(s);
app.sel.delete(s);
if (app.selected === s) {
app.selected = null;
}
@@ -465,9 +471,6 @@
layoutView();
updateChips();
renderDrawer();
if (app.cfg) {
renderHint();
}
}
function scheduleSave() {
@@ -515,6 +518,7 @@
powerOff(s);
}
app.strips = [];
app.sel = new Set();
app.selected = null;
applyConfig(cfg);
if (readAuto()) {
@@ -529,8 +533,9 @@
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.zoom = 1; // each room opens fitted
app.pan = { x: 0, y: 0 };
syncStrips();
renderHint();
}
/** A label for a new strip: drivers.name with n from its MAC, which no other room uses, so the name is unique too. */
@@ -551,8 +556,8 @@
async function addFixture(x, y) {
let mac;
try {
const taken = Object.values(app.room.fixtures).map((f) => f.mac).join(',');
mac = (await api('GET', `/sim/api/next-mac?taken=${encodeURIComponent(taken)}`)).mac;
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;
@@ -567,19 +572,50 @@
direction: 90,
};
changed();
app.selected = app.strips.find((s) => s.id === label) || null;
select(app.strips.find((s) => s.id === label) || null);
renderDrawer();
}
function deleteFixture(s) {
if (!s || !(s.id in app.room.fixtures)) {
/** Delete every selected strip from the room. */
function deleteSelected() {
const doomed = [...app.sel].filter((s) => s.id in app.room.fixtures);
if (!doomed.length) {
return;
}
delete app.room.fixtures[s.id];
if (app.selected === s) {
app.selected = null;
for (const s of doomed) {
delete app.room.fixtures[s.id];
}
setSelection([]);
changed();
}
/** Move every strip by one offset (snapped to 0.05 m, spacing kept) so their bounding box sits in the middle
* of the room: x = 0 (the room runs -width/2 .. width/2), y = depth / 2. */
function centreStrips() {
const infos = RigLayout.roomStrips(app.room);
if (!infos.length) {
return;
}
let x0 = Infinity;
let x1 = -Infinity;
let y0 = Infinity;
let y1 = -Infinity;
for (const i of infos) {
for (const [x, y] of [[i.x, i.y], [i.x1, i.y1]]) {
x0 = Math.min(x0, x);
x1 = Math.max(x1, x);
y0 = Math.min(y0, y);
y1 = Math.max(y1, y);
}
}
const dx = Math.round((0 - (x0 + x1) / 2) / SNAP_M) * SNAP_M;
const dy = Math.round((app.room.depth / 2 - (y0 + y1) / 2) / SNAP_M) * SNAP_M;
for (const f of Object.values(app.room.fixtures)) {
f.x = round3(f.x + dx);
f.y = round3(f.y + dy);
}
changed();
renderDrawer();
}
// ----- the controller: rig layout and the browser bridge -------------------------------
@@ -658,34 +694,10 @@
return;
}
const b = app.cfg.bridge;
$('bridge-chip').textContent = `${b.name} · ${b.mac}`;
const cc = $('controller-chip');
const on = app.wsOpen && b.running;
cc.textContent = !app.wsOpen ? 'controller: –' : b.running ? 'browser bridge: on' : 'browser bridge: off';
cc.className = `chip ${on ? 'ok' : 'warn'}`;
// "Add the browser bridge" shows when the controller is connected but its bridge is not running
$('add-bridge').hidden = !app.wsOpen || b.running;
const running = app.strips.filter((s) => s.state === 'running').length;
const booting = app.strips.filter((s) => s.state === 'queued' || s.state === 'loading').length;
const crashed = app.strips.filter((s) => s.state === 'crashed').length;
let text = `strips: ${running}/${app.strips.length} running`;
if (booting) {
text += ` · ${booting} booting`;
}
if (crashed) {
text += ` · ${crashed} stopped`;
}
const sc = $('strips-chip');
sc.textContent = text;
sc.className = `chip ${crashed ? 'warn' : running ? 'ok' : ''}`;
}
function renderHint() {
$('hint').innerHTML =
`Room <b>${app.roomName}</b>: ${app.room.width} × ${app.room.depth} m, ${app.strips.length} bars. ` +
'Each bar is the C++ led-driver; it registers with this controller when it powers on, ' +
'and its place in the room goes to the controller\'s rig layout. ' +
'<a href="/" target="_top">Open the controller</a> to drive them.';
}
function renderFacts() {
const s = app.selected;
@@ -735,6 +747,15 @@
const wasHidden = $('drawer').hidden;
$('drawer').hidden = !s && !app.edit;
$('d-empty').hidden = Boolean(s);
if (app.emptyHtml === undefined) {
app.emptyHtml = $('d-empty').innerHTML; // the default text, restored when the selection is not several strips
}
if (app.sel.size > 1) {
$('d-empty').textContent =
`${app.sel.size} strips selected. Drag one of them to move them all · Shift-click adds or removes · Delete removes them.`;
} else {
$('d-empty').innerHTML = app.emptyHtml;
}
$('d-body').hidden = !s;
if (wasHidden !== $('drawer').hidden) {
requestAnimationFrame(layoutView);
@@ -755,17 +776,20 @@
el.scrollTop = el.scrollHeight;
}
function select(s) {
app.selected = s;
/** The selection is a set of strips. The drawer shows the strip when exactly one is selected. */
function setSelection(list) {
app.sel = new Set(list);
app.selected = list.length === 1 ? list[0] : null;
app.dirty = true;
renderDrawer();
}
function select(s) {
setSelection(s ? [s] : []);
}
function setButtons() {
const ok = !app.takenOver;
for (const id of ['power-on-all', 'power-cycle-all', 'power-off-all']) {
$(id).disabled = !ok;
}
renderDrawer();
}
@@ -953,11 +977,48 @@
app.dpr = window.devicePixelRatio || 1;
c.width = Math.max(1, Math.round(rect.width * app.dpr));
c.height = Math.max(1, Math.round(rect.height * app.dpr));
app.view = RigLayout.fit(app.room, rect.width, rect.height);
app.size = { w: rect.width, h: rect.height };
app.view = RigLayout.fit(app.room, rect.width, rect.height, 28, {
z: app.zoom,
x: app.pan.x,
y: app.pan.y,
});
app.geo = RigLayout.stripGeometry(app.view, app.strips.map((s) => s.info));
app.dirty = true;
}
const ZOOM_MIN = 0.5;
const ZOOM_MAX = 8;
/** Zoom by factor f, keeping the room point under canvas (px, py) where it is (the centre without one). */
function zoomAt(f, px, py) {
if (!app.view || !app.room) {
return;
}
const cx = px == null ? app.size.w / 2 : px;
const cy = py == null ? app.size.h / 2 : py;
const wx = app.view.mx(cx);
const wy = app.view.my(cy);
const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, app.zoom * f));
const s = app.view.base * z;
app.zoom = z;
// so the point under (cx, cy) stays there: sx(wx) = cx and sy(wy) = cy at the new scale
app.pan = {
x: cx - wx * s - app.size.w / 2,
y: cy + wy * s - app.size.h / 2 - (app.room.depth / 2) * s,
};
layoutView();
}
function zoomFit() {
if (!app.room) {
return;
}
app.zoom = 1;
app.pan = { x: 0, y: 0 };
layoutView();
}
function colourAt(frame, i) {
const j = i * 3;
const r = frame[j] | 0;
@@ -983,11 +1044,13 @@
ctx.strokeStyle = GRID;
ctx.lineWidth = 1;
ctx.beginPath();
for (let x = Math.ceil(-w / 2); x <= w / 2; x += 1) {
// the grid step in metres: 1 m, or a coarser one where zoomed out so lines stay at least 6 px apart
const step = [1, 2, 5, 10, 20, 50].find((s) => s * v.scale >= 6) || 100;
for (let x = Math.ceil(-w / 2 / step) * step; x <= w / 2; x += step) {
ctx.moveTo(Math.round(v.sx(x)) + 0.5, y0);
ctx.lineTo(Math.round(v.sx(x)) + 0.5, y1);
}
for (let y = 1; y < d; y += 1) {
for (let y = step; y < d; y += step) {
ctx.moveTo(x0, Math.round(v.sy(y)) + 0.5);
ctx.lineTo(x1, Math.round(v.sy(y)) + 0.5);
}
@@ -999,7 +1062,7 @@
ctx.fillStyle = LABEL;
ctx.textAlign = 'left';
ctx.textBaseline = 'bottom';
ctx.fillText(`${app.roomName} · ${w} × ${d} m · 1 m grid`, x0, y0 - 6);
ctx.fillText(`${app.roomName} · ${w} × ${d} m · ${step} m grid · ${Math.round(app.zoom * 100)}%`, x0, y0 - 6);
}
function drawStrip(s, sg) {
@@ -1019,7 +1082,7 @@
ctx.fillStyle = col || OFF_COLOUR;
ctx.fillRect(i * sg.pitch, -LED_H / 2, Math.max(1, sg.pitch - gap), LED_H);
}
if (app.selected === s) {
if (app.sel.has(s)) {
ctx.strokeStyle = SELECT;
ctx.lineWidth = 1.5;
ctx.strokeRect(-1.5, -LED_H / 2 - 1.5, sg.len + 3, LED_H + 3);
@@ -1032,7 +1095,7 @@
ctx.restore();
if (app.edit) {
// turn handle at the strip's far end
ctx.strokeStyle = app.selected === s ? SELECT : LABEL;
ctx.strokeStyle = app.sel.has(s) ? SELECT : LABEL;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(sg.bx, sg.by, HANDLE_R, 0, Math.PI * 2);
@@ -1060,10 +1123,34 @@
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
drawRoom();
app.strips.forEach((s, i) => drawStrip(s, app.geo[i]));
if (app.marquee) {
const m = app.marquee;
ctx.save();
ctx.setLineDash([5, 4]);
ctx.strokeStyle = SELECT;
ctx.fillStyle = 'rgba(90,169,255,0.08)';
ctx.lineWidth = 1;
ctx.fillRect(m.x0, m.y0, m.x1 - m.x0, m.y1 - m.y0);
ctx.strokeRect(m.x0 + 0.5, m.y0 + 0.5, m.x1 - m.x0, m.y1 - m.y0);
ctx.restore();
}
}
requestAnimationFrame(frame);
}
/** Whether a strip's segment passes through the box (canvas px), sampled along its length. */
function stripTouchesBox(sg, x0, y0, x1, y1) {
for (let i = 0; i <= 20; i += 1) {
const t = i / 20;
const x = sg.ax + (sg.bx - sg.ax) * t;
const y = sg.ay + (sg.by - sg.ay) * t;
if (x >= x0 && x <= x1 && y >= y0 && y <= y1) {
return true;
}
}
return false;
}
/** What is under the pointer: {s, part: 'handle' | 'body'} or null. */
function hitTest(x, y) {
if (app.edit) {
@@ -1093,26 +1180,74 @@
function wireCanvas() {
const c = app.canvas;
// Middle-button drag would autoscroll the page: the canvas pans instead
c.addEventListener('mousedown', (ev) => {
if (ev.button === 1) {
ev.preventDefault();
}
});
// Right-drag pans the view, so the browser's menu stays off the canvas
c.addEventListener('contextmenu', (ev) => ev.preventDefault());
c.addEventListener(
'wheel',
(ev) => {
ev.preventDefault();
const [x, y] = pointerPos(ev);
const dy = ev.deltaMode === 1 ? ev.deltaY * 16 : ev.deltaY; // lines -> px
zoomAt(Math.exp(-dy * 0.0015), x, y);
},
{ passive: false },
);
c.addEventListener('pointerdown', (ev) => {
const [x, y] = pointerPos(ev);
if (ev.button === 1 || ev.button === 2 || app.spaceDown) {
// middle or right button, or Space held: pan the view, whatever is under the pointer
app.drag = { kind: 'pan', x, y, panX: app.pan.x, panY: app.pan.y };
c.setPointerCapture(ev.pointerId);
c.style.cursor = 'grabbing';
return;
}
const hit = hitTest(x, y);
if (!app.edit) {
if (hit) {
select(app.selected === hit.s ? null : hit.s);
} else if (app.zoom > 1) {
// zoomed in: a drag on empty floor moves the view
app.drag = { kind: 'pan', x, y, panX: app.pan.x, panY: app.pan.y };
c.setPointerCapture(ev.pointerId);
c.style.cursor = 'grabbing';
}
return;
}
if (!hit) {
app.drag = { kind: 'floor', x, y };
// a click adds a strip. A drag selects the strips in its box (Shift adds to the selection), or, zoomed in,
// pans the view (see pointermove)
app.drag = { kind: 'floor', x, y, panX: app.pan.x, panY: app.pan.y, shift: ev.shiftKey };
return;
}
const f = app.room.fixtures[hit.s.id];
select(hit.s);
const additive = ev.shiftKey || ev.ctrlKey || ev.metaKey;
if (hit.part === 'handle') {
select(hit.s);
app.drag = { kind: 'turn', s: hit.s, moved: false };
c.setPointerCapture(ev.pointerId);
return;
}
if (additive) {
if (app.sel.has(hit.s)) {
// Shift-click on a selected strip takes it out of the selection
setSelection([...app.sel].filter((s) => s !== hit.s));
return;
}
setSelection([...app.sel, hit.s]);
} else if (!app.sel.has(hit.s)) {
setSelection([hit.s]);
} // else: a strip of the selection, so the whole selection moves together
// every selected strip moves by the same offset, from where it was when the drag began
const items = [...app.sel].map((s) => ({ s, startX: app.room.fixtures[s.id].x, startY: app.room.fixtures[s.id].y }));
app.drag = {
kind: hit.part === 'handle' ? 'turn' : 'move',
kind: 'move',
s: hit.s,
startX: f.x,
startY: f.y,
items,
mx: app.view.mx(x),
my: app.view.my(y),
moved: false,
@@ -1123,15 +1258,34 @@
const [x, y] = pointerPos(ev);
const d = app.drag;
if (!d) {
if (app.edit) {
if (app.spaceDown) {
c.style.cursor = 'grab';
} else if (app.edit) {
const hit = hitTest(x, y);
c.style.cursor = hit ? (hit.part === 'handle' ? 'crosshair' : 'move') : 'copy';
c.style.cursor = hit ? (hit.part === 'handle' ? 'crosshair' : 'move') : app.zoom > 1 ? 'grab' : 'copy';
} else {
c.style.cursor = hitTest(x, y) ? 'pointer' : 'default';
c.style.cursor = hitTest(x, y) ? 'pointer' : app.zoom > 1 ? 'grab' : 'default';
}
return;
}
if (d.kind === 'pan') {
app.pan = { x: d.panX + x - d.x, y: d.panY + y - d.y };
layoutView();
return;
}
if (d.kind === 'floor' && app.zoom > 1 && !d.shift && Math.hypot(x - d.x, y - d.y) >= 4) {
// zoomed in, the drag is a pan, not a box: the view follows the pointer from where the drag began
app.drag = { kind: 'pan', x: d.x, y: d.y, panX: d.panX, panY: d.panY };
app.marquee = null;
c.setPointerCapture(ev.pointerId);
c.style.cursor = 'grabbing';
app.pan = { x: d.panX + x - d.x, y: d.panY + y - d.y };
layoutView();
return;
}
if (d.kind === 'floor') {
app.marquee = { x0: d.x, y0: d.y, x1: x, y1: y };
app.dirty = true;
return;
}
const f = app.room.fixtures[d.s.id];
@@ -1142,15 +1296,28 @@
const wx = app.view.mx(x);
const wy = app.view.my(y);
if (d.kind === 'move') {
// one snapped offset for the whole selection, so the strips keep their spacing
const snap = ev.altKey ? 0.001 : SNAP_M;
f.x = round3(Math.round((d.startX + wx - d.mx) / snap) * snap);
f.y = round3(Math.round((d.startY + wy - d.my) / snap) * snap);
const dx = Math.round((wx - d.mx) / snap) * snap;
const dy = Math.round((wy - d.my) / snap) * snap;
for (const it of d.items) {
const g = app.room.fixtures[it.s.id];
if (g) {
g.x = round3(it.startX + dx);
g.y = round3(it.startY + dy);
}
}
} 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);
}
d.moved = true;
d.s.info = Object.assign(d.s.info, RigLayout.roomStrips(app.room).find((i) => i.id === d.s.id));
const infos = new Map(RigLayout.roomStrips(app.room).map((i) => [i.id, i]));
for (const s of d.kind === 'move' ? d.items.map((it) => it.s) : [d.s]) {
if (infos.has(s.id)) {
s.info = Object.assign(s.info, infos.get(s.id));
}
}
app.geo = RigLayout.stripGeometry(app.view, app.strips.map((s) => s.info));
app.dirty = true;
renderFacts();
@@ -1163,15 +1330,30 @@
return;
}
if (d.kind === 'floor') {
const m = app.marquee;
app.marquee = null;
app.dirty = true;
const [x, y] = pointerPos(ev);
if (Math.hypot(x - d.x, y - d.y) < 4 && ev.type === 'pointerup') {
const wx = app.view.mx(x);
const wy = app.view.my(y);
if (Math.abs(wx) <= app.room.width / 2 && wy >= 0 && wy <= app.room.depth) {
addFixture(wx, wy);
} else {
select(null);
}
if (ev.type !== 'pointerup') {
return;
}
if (Math.hypot(x - d.x, y - d.y) >= 4) {
// a box: the strips it touches are selected (Shift: added to the selection)
const x0 = Math.min(d.x, x);
const x1 = Math.max(d.x, x);
const y0 = Math.min(d.y, y);
const y1 = Math.max(d.y, y);
const inside = app.strips.filter((s, i) => stripTouchesBox(app.geo[i], x0, y0, x1, y1));
const additive = ev.shiftKey || ev.ctrlKey || ev.metaKey;
setSelection(additive ? [...new Set([...app.sel, ...inside])] : inside);
return;
}
const wx = app.view.mx(x);
const wy = app.view.my(y);
if (Math.abs(wx) <= app.room.width / 2 && wy >= 0 && wy <= app.room.depth) {
addFixture(wx, wy);
} else {
select(null);
}
return;
}
@@ -1186,23 +1368,30 @@
// ----- boot --------------------------------------------------------------------
function wireUi() {
$('power-on-all').onclick = () => app.strips.forEach(powerOn);
$('power-off-all').onclick = () => app.strips.forEach(powerOff);
$('power-cycle-all').onclick = () => {
app.strips.forEach(powerOff);
app.strips.forEach(powerOn);
};
const auto = $('auto-power');
auto.checked = readAuto();
auto.onchange = () => writeAuto(auto.checked);
$('room-select').onchange = () => switchRoom($('room-select').value);
$('add-bridge').onclick = addBridge;
$('edit-toggle').onclick = () => setEdit(!app.edit);
$('zoom-in').onclick = () => zoomAt(1.25);
$('zoom-out').onclick = () => zoomAt(1 / 1.25);
$('zoom-fit').onclick = () => zoomFit();
$('add-strip').onclick = () => {
// the middle of what the canvas shows, kept inside the room
const w = app.room.width;
const d = app.room.depth;
addFixture(
Math.min(w / 2, Math.max(-w / 2, app.view.mx(app.size.w / 2))),
Math.min(d, Math.max(0, app.view.my(app.size.h / 2))),
);
};
$('centre-strips').onclick = () => centreStrips();
$('d-close').onclick = () => select(null);
$('d-on').onclick = () => app.selected && powerOn(app.selected);
$('d-off').onclick = () => app.selected && powerOff(app.selected);
$('d-reset').onclick = () => app.selected && reset(app.selected);
$('d-delete').onclick = () => deleteFixture(app.selected);
$('d-delete').onclick = () => deleteSelected();
$('d-clear').onclick = () => {
if (app.selected) {
app.selected.logs = [];
@@ -1220,13 +1409,26 @@
new ResizeObserver(() => layoutView()).observe($('rig'));
window.addEventListener('keydown', (ev) => {
const typing = /^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement && document.activeElement.tagName);
if (ev.key === 'Escape' && app.selected && !typing) {
if (ev.key === 'Escape' && app.sel.size && !typing) {
select(null);
} else if (app.edit && app.selected && !typing && (ev.key === 'Delete' || ev.key === 'Backspace')) {
} else if (app.edit && app.sel.size && !typing && (ev.key === 'Delete' || ev.key === 'Backspace')) {
ev.preventDefault();
deleteFixture(app.selected);
deleteSelected();
} else if (ev.key === ' ' && !typing) {
app.spaceDown = true; // hold Space and drag the canvas to pan
ev.preventDefault();
} else if (ev.key === '0' && !typing && !ev.ctrlKey && !ev.metaKey && !ev.altKey) {
zoomFit();
}
});
window.addEventListener('keyup', (ev) => {
if (ev.key === ' ') {
app.spaceDown = false;
}
});
window.addEventListener('blur', () => {
app.spaceDown = false;
});
}
async function main() {
+7 -3
View File
@@ -1,7 +1,6 @@
.gallery-intro { margin: 0; padding: 10px 16px 0; color: var(--muted); max-width: 900px; }
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
grid-template-columns: minmax(0, 1fr);
gap: 12px;
padding: 12px 16px 24px;
}
@@ -16,12 +15,17 @@
min-width: 0;
}
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.card[hidden] { display: none; }
.pager { display: flex; align-items: center; gap: 6px; }
.pager select { min-width: 160px; font-family: ui-monospace, Menlo, Consolas, monospace; }
.pager button { padding: 2px 10px; }
.card-name { font-weight: 600; font-family: ui-monospace, Menlo, Consolas, monospace; }
.card-head .btns { display: flex; gap: 4px; }
.save-status { color: var(--muted); font-size: 11px; min-height: 14px; }
.card-head button { padding: 2px 8px; }
.card canvas { width: 100%; height: 22px; display: block; background: #0b0c0f; border-radius: 4px; }
.card form { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px 8px; }
.card form[hidden] { display: none; }
.card form[hidden], .card form label[hidden] { display: none; }
.card form label { display: flex; flex-direction: column; gap: 2px; color: var(--muted); font-size: 11px; }
.card form label.wide { grid-column: span 2; }
.card form label.full { grid-column: 1 / -1; }
+6 -4
View File
@@ -24,16 +24,18 @@
<option value="2">2×</option><option value="4">4×</option>
</select>
</label>
<div class="pager">
<button type="button" id="g-prev" class="secondary" title="Previous pattern (←)">‹</button>
<select id="g-pick" title="Choose a pattern"></select>
<button type="button" id="g-next" class="secondary" title="Next pattern (→)">›</button>
</div>
<button type="button" id="g-add" class="secondary" title="Add a preset copied from the one shown">Add preset</button>
<button type="button" id="g-pause" class="secondary">Pause</button>
<button type="button" id="g-restart" class="secondary">Restart all</button>
<a class="button secondary" href="/sim/">Rig</a>
</div>
</header>
<div id="banner" class="banner" hidden></div>
<p class="gallery-intro">
Every pattern of the C++ led-driver, built to WebAssembly and stepped every 10 ms as on the strip. Fields are the
preset's (the names the controller sends). Leave the colour list empty for the pattern's own colours.
</p>
<main class="gallery" id="gallery"></main>
<script type="module" src="/sim/gallery.js"></script>
</body>
+240 -26
View File
@@ -11,7 +11,7 @@ const MAX_STEPS = 25; // per animation frame, after the tab was in the backgroun
const LED_CAP = 512;
const $ = (id) => document.getElementById(id);
const state = { leds: 119, speed: 1, paused: false, cards: [] };
const state = { leds: 119, speed: 1, paused: false, cards: [], current: 0, wasm: null, defs: {} };
function banner(text) {
const el = $('banner');
@@ -39,6 +39,7 @@ async function instantiate(wasmModule) {
});
}
// The preview runs the card's current values, so edits show at once. Save writes them to the controller only.
function presetJson(card) {
return JSON.stringify(card.preset);
}
@@ -118,7 +119,7 @@ function colourList(card) {
add.className = 'secondary';
add.textContent = '+';
add.title = 'Add a colour';
add.disabled = card.preset.colors.length >= 8;
add.disabled = card.preset.colors.length >= card.maxColors;
add.onclick = () => {
const last = card.preset.colors[card.preset.colors.length - 1];
card.preset.colors.push(last ? [last[2], last[0], last[1]] : [255, 0, 0]);
@@ -142,6 +143,22 @@ function colourList(card) {
return l;
}
function nameField(card) {
const l = document.createElement('label');
l.className = 'full';
l.textContent = 'Name';
const i = document.createElement('input');
i.type = 'text';
i.maxLength = 32;
i.value = card.name;
i.oninput = () => {
card.name = i.value.trim() || card.name;
card.el.querySelector('.card-name').textContent = card.name;
};
l.append(i);
return l;
}
function bgField(card) {
const l = document.createElement('label');
l.textContent = 'Background';
@@ -156,11 +173,152 @@ function bgField(card) {
return l;
}
function buildCard(mod, index) {
// The controller's pattern definitions (GET /patterns/definitions, as its preset editor reads them): the n-field
// labels, the style options (n6 "Style: 0 a, 1 b"), delay limits and how many colours a pattern takes.
function parseStyles(text) {
if (typeof text !== 'string') return null;
const out = {};
for (const part of text.replace(/^\s*Style:\s*/i, '').split(',')) {
const m = part.trim().match(/^(\d+)\s+(.*)$/);
if (m) out[Number(m[1])] = m[2];
}
return Object.keys(out).length ? out : null;
}
function defFor(pattern) {
return (state.defs && state.defs[pattern]) || {};
}
// Show only the n fields this pattern reads, with the controller's labels
function applySpec(card) {
const def = defFor(card.pattern);
for (const k of ['n1', 'n2', 'n3', 'n4']) {
const el = card.fields[k];
el.hidden = !def[k];
if (def[k]) el.firstChild.textContent = def[k];
}
card.fields.style.hidden = !parseStyles(def.n6);
}
function numFields(card) {
const fields = {};
for (const k of ['n1', 'n2', 'n3', 'n4']) fields[k] = numField(card, k, k);
fields.style = styleField(card);
card.fields = fields;
return Object.values(fields);
}
function styleField(card) {
const l = document.createElement('label');
l.textContent = 'Mode';
const sel = document.createElement('select');
const styles = parseStyles(defFor(card.pattern).n6) || {};
const values = Object.keys(styles).map(Number);
if (!values.includes(card.preset.mode)) values.push(card.preset.mode);
for (const v of values) {
sel.append(new Option(styles[v] ? `${v} ${styles[v]}` : `${v} (unknown)`, String(v)));
}
sel.value = String(card.preset.mode);
sel.onchange = () => {
card.preset.mode = Number(sel.value);
applySpec(card);
};
l.append(sel);
return l;
}
// A controller preset (GET /presets: "#RRGGBB" colours, n1..n6) as the gallery's fields
function fromSaved(s) {
const out = {};
out.colors = (s.colors || []).filter((c) => typeof c === 'string').map(rgb);
out.background = typeof s.background === 'string' ? rgb(s.background) : [0, 0, 0];
for (const k of ['delay', 'brightness', 'auto', 'reverse', 'fade', 'n1', 'n2', 'n3', 'n4', 'n5']) {
if (s[k] !== undefined && s[k] !== null) out[k] = s[k];
}
out.mode = s.n6 ?? s.mode ?? 0;
return out;
}
// The controller's preset fields for a card (colours and background as "#RRGGBB")
function payloadFor(card) {
const p = card.preset;
return {
name: card.name,
pattern: card.pattern,
colors: p.colors.map((c) => hex(c).toUpperCase()),
background: hex(p.background || [0, 0, 0]).toUpperCase(),
brightness: p.brightness,
delay: p.delay,
auto: p.auto,
reverse: p.reverse,
n1: p.n1,
n2: p.n2,
n3: p.n3,
n4: p.n4,
n5: p.n5,
n6: p.mode,
};
}
const JSON_HEADERS = { 'Content-Type': 'application/json', Accept: 'application/json' };
// Rebuild the dropdown from the cards (keeps the shown one selected)
function refreshPick() {
const sel = $('g-pick');
sel.replaceChildren(...state.cards.map((c, i) => new Option(`${i + 1}. ${c.name} (${c.pattern})`, String(i))));
sel.value = String(state.current);
}
async function save(card) {
const status = card.el.querySelector('.save-status');
status.textContent = 'Saving…';
try {
const r = await fetch(`/presets/${card.id}`, {
method: 'PUT',
headers: JSON_HEADERS,
body: JSON.stringify(payloadFor(card)),
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
card.el.querySelector('.card-name').textContent = card.name;
card.applied = JSON.parse(JSON.stringify(card.preset));
apply(card, false);
refreshPick();
status.textContent = 'Saved';
} catch (err) {
status.textContent = `Save failed: ${err.message}`;
}
}
// A new preset on the controller, copied from the shown card
async function addPreset() {
const src = state.cards[state.current];
if (!src) return;
try {
const r = await fetch('/presets', {
method: 'POST',
headers: JSON_HEADERS,
body: JSON.stringify({ ...payloadFor(src), name: `${src.name} copy` }),
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const out = await r.json();
const id = Object.keys(out)[0];
const mod = await instantiate(state.wasm);
const card = buildCard(mod, src.index, { ...out[id], id });
state.cards.push(card);
$('gallery').append(card.el);
$('g-count').textContent = `${state.cards.length} presets`;
refreshPick();
show(state.cards.length - 1);
} catch (err) {
banner(`Could not add the preset: ${err.message}`);
}
}
function buildCard(mod, index, saved) {
mod._fx_init(state.leds);
const name = mod.UTF8ToString(mod._fx_name(index));
const name = saved.name || mod.UTF8ToString(mod._fx_name(index));
const ptr = mod._fx_defaults_json(index);
const preset = JSON.parse(mod.UTF8ToString(ptr));
const preset = { ...JSON.parse(mod.UTF8ToString(ptr)), ...fromSaved(saved) };
mod._free(ptr);
preset.n5 = preset.n5 ?? 0;
@@ -169,14 +327,19 @@ function buildCard(mod, index) {
el.innerHTML =
'<div class="card-head"><span class="card-name"></span><span class="btns">' +
'<button type="button" class="secondary" data-a="restart" title="Restart the pattern">↺</button>' +
'<button type="button" class="secondary" data-a="edit" aria-expanded="false">Edit</button></span></div>' +
'<button type="button" data-a="save" title="Save this preset to the controller">Save</button></span></div>' +
'<span class="save-status" aria-live="polite"></span>' +
'<canvas></canvas>';
el.querySelector('.card-name').textContent = name;
const card = {
mod,
index,
id: saved.id,
pattern: saved.pattern,
maxColors: defFor(saved.pattern).max_colors ?? 8,
name,
preset,
applied: JSON.parse(JSON.stringify(preset)),
el,
canvas: el.querySelector('canvas'),
clock: 0,
@@ -185,30 +348,27 @@ function buildCard(mod, index) {
last: null,
};
const form = document.createElement('form');
form.hidden = true;
form.onsubmit = (ev) => ev.preventDefault();
const def = defFor(saved.pattern);
const colours = colourList(card);
colours.hidden = card.maxColors === 0; // as the controller: no colour list for a pattern that takes none
const reverse = checkField(card, 'reverse', 'reverse', false);
reverse.hidden = !def.supports_reverse; // as the controller: only for patterns that support it
form.append(
colourList(card),
nameField(card),
colours,
bgField(card),
numField(card, 'delay', 'Delay d (ms)', { min: 10, max: 10000 }),
numField(card, 'delay', 'Delay d (ms)', { min: def.min_delay ?? 10, max: def.max_delay ?? 10000 }),
numField(card, 'brightness', 'Bright b', { min: 0, max: 255 }),
numField(card, 'mode', 'Style n6', { min: 0 }),
numField(card, 'n1', 'n1'),
numField(card, 'n2', 'n2'),
numField(card, 'n3', 'n3'),
numField(card, 'n4', 'n4'),
numField(card, 'n5', 'n5'),
checkField(card, 'reverse', 'reverse', false),
numField(card, 'fade', 'Fade (ms)', { min: 0, max: 10000, step: 50 }),
...numFields(card),
reverse,
checkField(card, 'auto', 'auto a', true),
checkField(card, 'beat_time', 'beat time', false),
);
el.append(form);
el.querySelector('[data-a=edit]').onclick = (ev) => {
form.hidden = !form.hidden;
ev.currentTarget.setAttribute('aria-expanded', String(!form.hidden));
ev.currentTarget.textContent = form.hidden ? 'Edit' : 'Close';
};
el.querySelector('[data-a=save]').onclick = () => save(card);
el.querySelector('[data-a=restart]').onclick = () => apply(card, true);
applySpec(card);
apply(card, true);
return card;
}
@@ -240,6 +400,19 @@ function draw(card) {
}
}
// Show one pattern card at a time (index wraps at the ends)
function show(index) {
const n = state.cards.length;
if (!n) return;
state.current = (index + n) % n;
state.cards.forEach((c, i) => {
c.el.hidden = i !== state.current;
});
$('g-pick').value = String(state.current);
$('g-prev').disabled = n < 2;
$('g-next').disabled = n < 2;
}
let lastT = 0;
function tick(t) {
const dt = lastT ? Math.min(250, t - lastT) : 0;
@@ -256,8 +429,13 @@ function tick(t) {
if (card.next <= card.clock) {
card.next = Math.ceil(card.clock / FRAME_MS) * FRAME_MS; // fell behind: skip ahead
}
draw(card);
}
const shown = state.cards[state.current];
const status = shown.el.querySelector('.save-status');
const dirty = JSON.stringify(shown.preset) !== JSON.stringify(shown.applied);
if (dirty) status.textContent = 'Unsaved changes (press Save to keep them)';
else if (status.textContent.startsWith('Unsaved')) status.textContent = '';
draw(shown); // only the shown pattern is drawn
}
requestAnimationFrame(tick);
}
@@ -270,16 +448,43 @@ async function main() {
banner(`Could not load the pattern engine (web/wasm/led_fx.wasm): ${err}. Build it with make sim-wasm, then rebuild the controller.`);
return;
}
try {
const r = await fetch('/patterns/definitions', { headers: { Accept: 'application/json' } });
if (!r.ok) throw new Error(`HTTP ${r.status}`);
state.defs = await r.json();
} catch (err) {
banner(`Could not load the pattern definitions from the controller: ${err}. Field labels are missing.`);
}
const first = await instantiate(wasmModule);
const count = first._fx_count();
$('g-count').textContent = `${count} patterns`;
const patternNames = [];
for (let i = 0; i < count; i += 1) patternNames.push(first.UTF8ToString(first._fx_name(i)));
state.wasm = wasmModule;
let saved = [];
try {
const r = await fetch('/presets', { headers: { Accept: 'application/json' } });
if (!r.ok) throw new Error(`HTTP ${r.status}`);
saved = Object.values(await r.json());
} catch (err) {
banner(`Could not load the presets from the controller: ${err}`);
}
const list = saved
.map((p) => ({ p, index: patternNames.indexOf(p.pattern) }))
.filter((x) => x.index >= 0);
const skipped = saved.length - list.length;
if (skipped) banner(`${skipped} preset(s) use a pattern this build does not have and are not shown.`);
$('g-count').textContent = `${list.length} presets`;
const grid = $('gallery');
for (let i = 0; i < count; i += 1) {
for (let i = 0; i < list.length; i += 1) {
const mod = i === 0 ? first : await instantiate(wasmModule);
const card = buildCard(mod, i);
const card = buildCard(mod, list[i].index, list[i].p);
state.cards.push(card);
grid.append(card.el);
}
refreshPick();
$('g-pick').onchange = () => show(Number($('g-pick').value));
$('g-leds').onchange = () => {
const n = Math.max(1, Math.min(LED_CAP, Math.round(Number($('g-leds').value)) || 119));
$('g-leds').value = n;
@@ -297,6 +502,15 @@ async function main() {
$('g-pause').textContent = state.paused ? 'Play' : 'Pause';
};
$('g-restart').onclick = () => state.cards.forEach((c) => apply(c, true));
$('g-add').onclick = () => addPreset();
$('g-prev').onclick = () => show(state.current - 1);
$('g-next').onclick = () => show(state.current + 1);
document.addEventListener('keydown', (ev) => {
if (ev.target.closest('input, select, textarea')) return;
if (ev.key === 'ArrowLeft') show(state.current - 1);
if (ev.key === 'ArrowRight') show(state.current + 1);
});
show(0);
requestAnimationFrame(tick);
}
+9 -11
View File
@@ -15,16 +15,20 @@
<span class="brand-name">led-simulator</span>
</div>
<div class="chips">
<span class="chip" id="bridge-chip" title="The rig's bridge: frames from the controller come in as from this MAC">bridge</span>
<span class="chip" id="controller-chip">controller: –</span>
<button type="button" id="add-bridge" class="secondary" hidden
title="The controller sends its ESP-NOW frames only to the bridges in its settings">Add the browser bridge</button>
<span class="chip" id="strips-chip">strips: –</span>
</div>
<div class="room-bar">
<label class="field-inline">Room <select id="room-select" aria-label="Room"></select></label>
<button type="button" id="edit-toggle" class="secondary">Edit room</button>
<span class="zoom-tools" role="group" aria-label="Zoom">
<button type="button" id="zoom-out" class="secondary" aria-label="Zoom out" title="Zoom out (wheel)">−</button>
<button type="button" id="zoom-fit" class="secondary" title="Fit the room (0)">Fit</button>
<button type="button" id="zoom-in" class="secondary" aria-label="Zoom in" title="Zoom in (wheel)">+</button>
</span>
<span id="edit-tools" class="edit-tools" hidden>
<button type="button" id="add-strip">Add strip</button>
<button type="button" id="centre-strips" class="secondary" title="Move all the strips so they sit in the middle of the room">Centre strips</button>
<button type="button" id="room-settings" class="secondary">Size &amp; strip types…</button>
<button type="button" id="room-new" class="secondary">New room…</button>
<button type="button" id="room-delete" class="secondary">Delete room</button>
@@ -33,19 +37,15 @@
</div>
<div class="actions">
<a class="button secondary not-embedded" href="/">Controller</a>
<a class="button secondary" href="/sim/gallery" target="_blank" rel="noopener">Pattern gallery</a>
<button type="button" id="power-on-all">Power on all</button>
<button type="button" id="power-cycle-all">Power cycle all</button>
<button type="button" id="power-off-all" class="secondary">Power off all</button>
<label class="toggle" title="Boot every strip when this page opens">
<input type="checkbox" id="auto-power"> Power on when opened
<input type="checkbox" id="auto-power"> Auto-power
</label>
</div>
</header>
<div id="banner" class="banner" hidden></div>
<div class="edit-hint" id="edit-hint">
Click the floor to add a strip · drag a strip to move it (Alt: no snap) · drag its end circle to turn it (Shift: no snap) · Delete removes the selected strip
Add strip or click the floor to add one · drag the floor to select the strips in a box (Shift: add to the selection; zoomed in, a plain drag pans instead) ·Shift-click a strip to add or remove it · drag a selected strip to move them all (Alt: no snap) · drag its end circle to turn it (Shift: no snap) · Delete removes the selection · wheel or +/− zooms, right-drag, middle-drag or Space-drag pans
</div>
<main class="stage">
@@ -95,8 +95,6 @@
</aside>
</main>
<footer class="hint" id="hint">Loading…</footer>
<dialog id="room-dialog" aria-labelledby="r-title">
<h2 id="r-title">Room size and strip types</h2>
<div class="dialog-row">
+9 -6
View File
@@ -38,17 +38,20 @@
}
/**
* Fit the room to a width x height canvas with one scale.
* @returns {object} {scale, sx(x), sy(y), mx(px), my(py)} metres -> px and back
* Fit the room to a width x height canvas with one scale, then zoom and pan it.
* @param zoom {z, x, y}: z scales about the room's centre (1 = fitted), x and y move it in canvas px.
* @returns {object} {scale, base, sx(x), sy(y), mx(px), my(py)} metres -> px and back
*/
function fit(room, width, height, margin = 28) {
const scale = Math.max(
function fit(room, width, height, margin = 28, zoom = {}) {
const base = Math.max(
1e-3,
Math.min((width - 2 * margin) / room.width, (height - 2 * margin) / room.depth),
);
const ox = width / 2;
const oy = height / 2 + (room.depth / 2) * scale;
const scale = base * (zoom.z || 1);
const ox = width / 2 + (zoom.x || 0);
const oy = height / 2 + (room.depth / 2) * scale + (zoom.y || 0);
return {
base,
scale,
sx: (x) => ox + x * scale,
sy: (y) => oy - y * scale,
+11 -13
View File
@@ -55,8 +55,8 @@ button.link {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px 18px;
padding: 10px 16px;
gap: 6px 12px;
padding: 6px 12px;
border-bottom: 1px solid var(--line);
background: var(--panel);
}
@@ -104,6 +104,10 @@ button.link {
width: 100%;
height: 100%;
cursor: pointer;
/* A finger or pen drag moves strips and the view, not the page: without this the browser scrolls the
page and cancels the pointer, so the drag stops */
touch-action: none;
user-select: none;
}
.drawer {
@@ -151,16 +155,6 @@ button.link {
.state-running { color: var(--ok); }
.state-crashed { color: var(--bad); }
.hint {
padding: 8px 16px;
border-top: 1px solid var(--line);
color: var(--muted);
background: var(--panel);
}
.hint code {
color: var(--text);
font-family: ui-monospace, Menlo, Consolas, monospace;
}
@media (max-width: 760px) {
.stage { flex-direction: column; }
@@ -169,9 +163,13 @@ button.link {
}
/* ---- rooms and the editor ---- */
.room-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
/* The room controls and the menu sit in the top bar itself (one row, wrapping only when the window is narrow),
so the editor gets the rest of the height */
.room-bar, .actions { display: contents; }
.edit-tools { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.edit-tools[hidden] { display: none; }
.zoom-tools { display: inline-flex; align-items: center; gap: 4px; }
.zoom-tools button { min-width: 2.2em; }
.field-inline { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); }
.muted { color: var(--muted); }
select, input {