/* Mover Pattern Studio — browser UI. * All pattern maths lives on the server (patternstudio/efx.py); this file * edits the pattern JSON, asks the server for sampled tracks and animates them. */ "use strict"; const $ = (sel) => document.querySelector(sel); const PALETTE = ["#5aa9ff", "#ffb547", "#52d273", "#ff6b6b", "#c58bff", "#4fd8d8", "#ff8ad8", "#d6e35a"]; const ALGORITHMS = ["Circle", "Eight", "Line", "Line2", "Diamond", "Square", "SquareChoppy", "Leaf", "Lissajous"]; const EFX_SLIDERS = [ ["width", "Width (pan)", 0, 127], ["height", "Height (tilt)", 0, 127], ["rotation", "Rotation °", 0, 359], ["start_offset", "Start offset °", 0, 359], ["x_offset", "Centre pan", 0, 255], ["y_offset", "Centre tilt", 0, 255], ["duration_ms", "Loop ms", 200, 60000], ["fade_in_ms", "Fade in ms", 0, 20000], ]; const state = { workspaces: [], wsPath: null, ws: null, pattern: defaultPattern(), sample: null, selected: -1, // selected waypoint playing: true, speed: 1, clock: 0, // pattern time in ms lastFrame: 0, live: false, library: [], drag: null, }; function defaultPattern() { return { name: "Mover Pattern", type: "efx", fixtures: [], efx: { algorithm: "Circle", width: 40, height: 30, rotation: 0, start_offset: 0, x_offset: 128, y_offset: 128, x_frequency: 1, y_frequency: 1, x_phase: 0, y_phase: 0, duration_ms: 8000, fade_in_ms: 0, fade_out_ms: 0, direction: "Forward", run_order: "Loop", propagation: "Parallel", relative: false, }, path: { points: [], smooth: false, subdivisions: 6, closed: true, run_order: "Loop", direction: "Forward", }, }; } function fixtureConfig(id) { return { id, head: 0, direction: "Forward", start_offset: 0, pan: 128, tilt: 128, pan_offset: 0, tilt_offset: 0, mirror_pan: false, mirror_tilt: false }; } // ------------------------------------------------------------------ API async function api(method, url, body) { const res = await fetch(url, { method, headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined, }); const data = await res.json().catch(() => ({ error: res.statusText })); if (!res.ok) throw new Error(data.error || res.statusText); return data; } function setStatus(msg, cls = "") { const el = $("#status"); el.textContent = msg; el.className = cls; } // ------------------------------------------------------------------ workspace async function loadWorkspaces() { const d = await api("GET", "/api/workspaces"); state.workspaces = d.workspaces; const sel = $("#ws-select"); sel.innerHTML = ""; for (const w of d.workspaces) { const o = document.createElement("option"); o.value = w.path; o.textContent = w.path.replace(/^shows\//, ""); sel.appendChild(o); } const remembered = localStorage.getItem("ps.ws"); const pick = d.workspaces.find((w) => w.path === remembered) || d.workspaces[0]; if (pick) { sel.value = pick.path; await loadWorkspace(pick.path); } else { setStatus("No .qxw files found in shows/", "err"); } } async function loadWorkspace(path) { state.wsPath = path; localStorage.setItem("ps.ws", path); state.ws = await api("GET", `/api/workspace?path=${encodeURIComponent(path)}`); const movers = state.ws.fixtures.filter((f) => f.is_mover); // Keep fixture selections that still exist; default to all movers. const ids = new Set(movers.map((f) => f.id)); state.pattern.fixtures = state.pattern.fixtures.filter((f) => ids.has(f.id)); if (!state.pattern.fixtures.length) state.pattern.fixtures = movers.map((m) => fixtureConfig(m.id)); const art = Object.values(state.ws.artnet)[0]; if (art) { $("#live-ip").value = art.ip || ""; $("#live-uni").value = art.universe ?? 0; } renderFixtures(); renderFunctionList(); setStatus(`${movers.length} mover${movers.length === 1 ? "" : "s"} · ${state.ws.functions.length} functions`); requestSample(); } function moverById(id) { return state.ws?.fixtures.find((f) => f.id === id); } // ------------------------------------------------------------------ fixtures panel function renderFixtures() { const box = $("#fixture-list"); box.innerHTML = ""; if (!state.ws) return; const movers = state.ws.fixtures.filter((f) => f.is_mover); const others = state.ws.fixtures.filter((f) => !f.is_mover); $("#fixture-hint").textContent = movers.length ? "" : "no pan/tilt fixtures found"; const isEfx = state.pattern.type === "efx"; movers.forEach((m, i) => { const cfg = state.pattern.fixtures.find((f) => f.id === m.id); const el = document.createElement("div"); el.className = "fixture" + (cfg ? "" : " off"); const color = PALETTE[i % PALETTE.length]; const degs = m.pan_max ? ` · ${m.pan_max}°/${m.tilt_max}°` : ""; el.innerHTML = `
`; el.querySelector("input").addEventListener("change", (e) => { if (e.target.checked) state.pattern.fixtures.push(fixtureConfig(m.id)); else state.pattern.fixtures = state.pattern.fixtures.filter((f) => f.id !== m.id); renderFixtures(); requestSample(); }); const opts = el.querySelector(".opts"); if (cfg) { if (isEfx) { opts.appendChild(selectField("Dir", ["Forward", "Backward"], cfg.direction, (v) => { cfg.direction = v; requestSample(); })); opts.appendChild(numField("Offset °", cfg.start_offset, 0, 359, (v) => { cfg.start_offset = v; requestSample(); })); if (state.pattern.efx.relative) { opts.appendChild(numField("Home pan", cfg.pan, 0, 255, (v) => { cfg.pan = v; requestSample(); })); opts.appendChild(numField("Home tilt", cfg.tilt, 0, 255, (v) => { cfg.tilt = v; requestSample(); })); } } else { opts.appendChild(checkField("Mirror pan", cfg.mirror_pan, (v) => { cfg.mirror_pan = v; requestSample(); })); opts.appendChild(checkField("Mirror tilt", cfg.mirror_tilt, (v) => { cfg.mirror_tilt = v; requestSample(); })); opts.appendChild(numField("Pan ±", cfg.pan_offset, -255, 255, (v) => { cfg.pan_offset = v; requestSample(); })); opts.appendChild(numField("Tilt ±", cfg.tilt_offset, -255, 255, (v) => { cfg.tilt_offset = v; requestSample(); })); } } box.appendChild(el); }); if (others.length) { const el = document.createElement("div"); el.className = "fixture notmover"; el.innerHTML = `
${others.length} non-mover fixture${others.length === 1 ? "" : "s"} hidden
`; box.appendChild(el); } } function selectField(label, options, value, onChange) { const l = document.createElement("label"); l.append(label); const s = document.createElement("select"); for (const o of options) { const op = document.createElement("option"); op.textContent = o; s.appendChild(op); } s.value = value; s.addEventListener("change", () => onChange(s.value)); l.appendChild(s); return l; } function numField(label, value, min, max, onChange) { const l = document.createElement("label"); l.append(label); const i = document.createElement("input"); i.type = "number"; i.min = min; i.max = max; i.value = value; i.addEventListener("input", () => { const v = Number(i.value); if (Number.isFinite(v)) onChange(v); }); l.appendChild(i); return l; } function checkField(label, value, onChange) { const l = document.createElement("label"); const i = document.createElement("input"); i.type = "checkbox"; i.checked = value; i.addEventListener("change", () => onChange(i.checked)); l.append(i, label); return l; } function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c])); } // ------------------------------------------------------------------ EFX panel function buildEfxPanel() { const alg = $("#efx-algorithm"); for (const a of ALGORITHMS) { const o = document.createElement("option"); o.textContent = a; alg.appendChild(o); } alg.addEventListener("change", () => { state.pattern.efx.algorithm = alg.value; syncEfxForm(); requestSample(); }); const box = $("#efx-sliders"); for (const [key, label, min, max] of EFX_SLIDERS) { const row = document.createElement("div"); row.className = "slider"; row.innerHTML = `${label}`; const [range, num] = row.querySelectorAll("input"); const apply = (v) => { v = Math.max(min, Math.min(max, Math.round(Number(v) || 0))); state.pattern.efx[key] = v; range.value = v; num.value = v; requestSample(); }; range.addEventListener("input", () => apply(range.value)); num.addEventListener("input", () => apply(num.value)); box.appendChild(row); } for (const key of ["direction", "run_order", "propagation", "x_frequency", "y_frequency", "x_phase", "y_phase"]) { const el = $(`#efx-${key}`); el.addEventListener("input", () => { state.pattern.efx[key] = el.type === "number" ? Number(el.value) : el.value; requestSample(); }); } $("#efx-relative").addEventListener("change", (e) => { state.pattern.efx.relative = e.target.checked; renderFixtures(); syncEfxForm(); requestSample(); }); } function syncEfxForm() { const e = state.pattern.efx; $("#efx-algorithm").value = e.algorithm; for (const inp of $("#efx-sliders").querySelectorAll("input")) inp.value = e[inp.dataset.key]; for (const key of ["direction", "run_order", "propagation", "x_frequency", "y_frequency", "x_phase", "y_phase"]) $(`#efx-${key}`).value = e[key]; $("#efx-relative").checked = e.relative; $("#lissajous-row").style.display = e.algorithm === "Lissajous" ? "" : "none"; // In relative mode the centre is each head's home; the shared offsets are meaningless. for (const inp of $("#efx-sliders").querySelectorAll("input[data-key=x_offset],input[data-key=y_offset]")) inp.disabled = e.relative; } // ------------------------------------------------------------------ Path panel function buildPathPanel() { $("#pt-add").addEventListener("click", () => { const pts = state.pattern.path.points; const last = pts[pts.length - 1]; pts.push({ pan: last ? Math.min(255, last.pan + 20) : 128, tilt: last ? last.tilt : 128, fade_ms: last ? last.fade_ms : 1000, hold_ms: last ? last.hold_ms : 0 }); state.selected = pts.length - 1; renderPoints(); requestSample(); }); $("#pt-clear").addEventListener("click", () => { state.pattern.path.points = []; state.selected = -1; renderPoints(); requestSample(); }); for (const key of ["closed", "smooth"]) { $(`#path-${key}`).addEventListener("change", (e) => { state.pattern.path[key] = e.target.checked; requestSample(); }); } $("#path-subdivisions").addEventListener("input", (e) => { state.pattern.path.subdivisions = Number(e.target.value) || 1; requestSample(); }); for (const key of ["run_order", "direction"]) { $(`#path-${key}`).addEventListener("input", (e) => { state.pattern.path[key] = e.target.value; requestSample(); }); } $("#path-all-fade").addEventListener("change", (e) => { const v = Number(e.target.value); if (!Number.isFinite(v) || e.target.value === "") return; for (const p of state.pattern.path.points) p.fade_ms = v; e.target.value = ""; renderPoints(); requestSample(); }); $("#path-all-hold").addEventListener("change", (e) => { const v = Number(e.target.value); if (!Number.isFinite(v) || e.target.value === "") return; for (const p of state.pattern.path.points) p.hold_ms = v; e.target.value = ""; renderPoints(); requestSample(); }); } function syncPathForm() { const p = state.pattern.path; $("#path-closed").checked = p.closed; $("#path-smooth").checked = p.smooth; $("#path-subdivisions").value = p.subdivisions; $("#path-run_order").value = p.run_order; $("#path-direction").value = p.direction; renderPoints(); } function renderPoints() { const tb = $("#point-table tbody"); tb.innerHTML = ""; state.pattern.path.points.forEach((pt, i) => { const tr = document.createElement("tr"); if (i === state.selected) tr.className = "sel"; tr.innerHTML = `${i + 1}` + ["pan", "tilt", "fade_ms", "hold_ms"].map((k) => ``).join("") + ``; tr.addEventListener("click", () => { if (state.selected !== i) { state.selected = i; renderPoints(); } }); for (const inp of tr.querySelectorAll("input")) { inp.addEventListener("input", () => { const v = Number(inp.value); if (!Number.isFinite(v)) return; pt[inp.dataset.k] = inp.dataset.k.endsWith("ms") ? Math.max(0, v) : Math.max(0, Math.min(255, v)); requestSample(); }); } tr.querySelector("button").addEventListener("click", (e) => { e.stopPropagation(); state.pattern.path.points.splice(i, 1); state.selected = Math.min(state.selected, state.pattern.path.points.length - 1); renderPoints(); requestSample(); }); tb.appendChild(tr); }); const s = state.sample; $("#path-summary").textContent = s && s.kind === "path" ? `${s.step_count} sequence step${s.step_count === 1 ? "" : "s"} · loop ${(s.loop_ms / 1000).toFixed(1)} s` : ""; } // ------------------------------------------------------------------ type tabs function setType(type) { state.pattern.type = type; for (const b of $("#type-tabs").querySelectorAll("button")) b.classList.toggle("active", b.dataset.type === type); $("#efx-panel").hidden = type !== "efx"; $("#path-panel").hidden = type !== "path"; $("#canvas-hint").textContent = type === "efx" ? "Click or drag on the grid to place the shape's centre" : "Click to add a waypoint · drag to move"; renderFixtures(); if (type === "efx") syncEfxForm(); else syncPathForm(); requestSample(); } // ------------------------------------------------------------------ sampling let sampleTimer = null; let sampleInFlight = false; let sampleQueued = false; function requestSample() { clearTimeout(sampleTimer); sampleTimer = setTimeout(doSample, 30); if (state.live) scheduleLiveRestart(); } async function doSample() { if (sampleInFlight) { sampleQueued = true; return; } sampleInFlight = true; try { state.sample = await api("POST", "/api/sample", { pattern: state.pattern }); if (state.pattern.type === "path") renderPoints(); } catch (err) { setStatus(err.message, "err"); } finally { sampleInFlight = false; if (sampleQueued) { sampleQueued = false; doSample(); } } } // ------------------------------------------------------------------ playback maths function headPosition(track, kind, tMs) { const s = state.sample; const loop = s.loop_ms; if (kind === "efx") { const pts = track.points; if (tMs < track.start_delay_ms) return { pan: pts[0][0], tilt: pts[0][1], waiting: true }; const cycles = Math.floor(tMs / loop); if (s.run_order === "SingleShot" && cycles >= 1) return null; let pos = (tMs + track.time_offset_ms) % loop; let u = pos / loop; if (s.run_order === "PingPong" && cycles % 2 === 1) u = 1 - u; const f = u * pts.length; const i = Math.floor(f) % pts.length; const j = (i + 1) % pts.length; const k = f - Math.floor(f); return { pan: pts[i][0] + (pts[j][0] - pts[i][0]) * k, tilt: pts[i][1] + (pts[j][1] - pts[i][1]) * k }; } // path: keys [t, pan, tilt] — piecewise linear, wraps from last key back to first const keys = track.keys; if (!keys.length) return null; if (loop <= 0) return { pan: keys[0][1], tilt: keys[0][2] }; const cycles = Math.floor(tMs / loop); let pos = tMs % loop; let reverse = s.direction === "Backward"; if (s.run_order === "PingPong" && cycles % 2 === 1) reverse = !reverse; if (s.run_order === "SingleShot" && cycles >= 1) pos = loop; if (reverse) pos = loop - pos; let prev = keys[keys.length - 1]; let tPrev = 0; for (const key of keys) { const [t, pan, tilt] = key; if (pos <= t) { const span = t - tPrev; const k = span > 0 ? (pos - tPrev) / span : 1; return { pan: prev[1] + (pan - prev[1]) * k, tilt: prev[2] + (tilt - prev[2]) * k }; } tPrev = t; prev = key; } return { pan: prev[1], tilt: prev[2] }; } // ------------------------------------------------------------------ canvas const canvas = $("#canvas"); const ctx = canvas.getContext("2d"); let geom = { x0: 0, y0: 0, size: 0 }; function resizeCanvas() { const r = canvas.getBoundingClientRect(); const dpr = window.devicePixelRatio || 1; canvas.width = Math.round(r.width * dpr); canvas.height = Math.round(r.height * dpr); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); const margin = 44; const size = Math.max(50, Math.min(r.width, r.height) - margin * 2); geom = { x0: (r.width - size) / 2, y0: (r.height - size) / 2, size, w: r.width, h: r.height }; } const toPx = (pan, tilt) => [geom.x0 + (pan / 255) * geom.size, geom.y0 + (tilt / 255) * geom.size]; const toDmx = (x, y) => [((x - geom.x0) / geom.size) * 255, ((y - geom.y0) / geom.size) * 255]; function draw(now) { if (!state.lastFrame) state.lastFrame = now; const dt = now - state.lastFrame; state.lastFrame = now; if (state.playing) state.clock += dt * state.speed; ctx.clearRect(0, 0, geom.w, geom.h); drawGrid(); const s = state.sample; if (s && state.ws) { const movers = state.ws.fixtures.filter((f) => f.is_mover); const colorOf = (id) => PALETTE[Math.max(0, movers.findIndex((m) => m.id === id)) % PALETTE.length]; const showTrails = $("#show-trails").checked; // Paths for (const track of s.tracks) { ctx.strokeStyle = colorOf(track.id); ctx.globalAlpha = 0.55; ctx.lineWidth = 1.5; ctx.beginPath(); const pts = s.kind === "efx" ? track.points : track.keys.map((k) => [k[1], k[2]]); pts.forEach((p, i) => { const [x, y] = toPx(p[0], p[1]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); }); if (s.kind === "efx" || state.pattern.path.closed) ctx.closePath(); ctx.stroke(); ctx.globalAlpha = 1; } // Waypoints (path mode) if (s.kind === "path") { state.pattern.path.points.forEach((p, i) => { const [x, y] = toPx(p.pan, p.tilt); ctx.beginPath(); ctx.arc(x, y, i === state.selected ? 8 : 6, 0, Math.PI * 2); ctx.fillStyle = i === state.selected ? "#fff" : "#9aa3b5"; ctx.fill(); ctx.fillStyle = "#0b1220"; ctx.font = "bold 9px system-ui"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(String(i + 1), x, y + 0.5); }); } // EFX centre handle if (s.kind === "efx" && !state.pattern.efx.relative) { const [cx, cy] = toPx(state.pattern.efx.x_offset, state.pattern.efx.y_offset); ctx.strokeStyle = "#ffffff"; ctx.globalAlpha = 0.8; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(cx - 9, cy); ctx.lineTo(cx + 9, cy); ctx.moveTo(cx, cy - 9); ctx.lineTo(cx, cy + 9); ctx.stroke(); ctx.beginPath(); ctx.arc(cx, cy, 9, 0, Math.PI * 2); ctx.stroke(); ctx.globalAlpha = 1; } // Heads const loop = s.loop_ms || 1; for (const track of s.tracks) { const color = colorOf(track.id); if (showTrails) { ctx.strokeStyle = color; ctx.lineWidth = 4; ctx.lineCap = "round"; const trailMs = Math.min(1200, loop * 0.15); ctx.beginPath(); let first = true; for (let k = 12; k >= 0; k--) { const pos = headPosition(track, s.kind, Math.max(0, state.clock - (trailMs * k) / 12)); if (!pos) continue; const [x, y] = toPx(pos.pan, pos.tilt); ctx.globalAlpha = 0.05 + (1 - k / 12) * 0.35; if (first) { ctx.moveTo(x, y); first = false; } else { ctx.lineTo(x, y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x, y); } } ctx.globalAlpha = 1; } const pos = headPosition(track, s.kind, state.clock); if (!pos) continue; const [x, y] = toPx(pos.pan, pos.tilt); ctx.beginPath(); ctx.arc(x, y, 9, 0, Math.PI * 2); ctx.fillStyle = color; ctx.globalAlpha = pos.waiting ? 0.35 : 1; ctx.fill(); ctx.globalAlpha = 1; ctx.strokeStyle = "#0b1220"; ctx.lineWidth = 2; ctx.stroke(); ctx.fillStyle = "#e6e8ee"; ctx.font = "11px system-ui"; ctx.textAlign = "left"; ctx.textBaseline = "bottom"; const m = moverById(track.id); ctx.fillText(`${m ? m.name : track.id} ${Math.round(pos.pan)},${Math.round(pos.tilt)}`, x + 12, y - 6); } $("#time").textContent = `${((state.clock % loop) / 1000).toFixed(2)} / ${(loop / 1000).toFixed(2)} s`; } requestAnimationFrame(draw); } function drawGrid() { const { x0, y0, size } = geom; ctx.fillStyle = "#101216"; ctx.fillRect(x0, y0, size, size); ctx.strokeStyle = "#262a34"; ctx.lineWidth = 1; for (let v = 0; v <= 256; v += 32) { const p = (Math.min(v, 255) / 255) * size; ctx.beginPath(); ctx.moveTo(x0 + p, y0); ctx.lineTo(x0 + p, y0 + size); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x0, y0 + p); ctx.lineTo(x0 + size, y0 + p); ctx.stroke(); } ctx.strokeStyle = "#3b4150"; ctx.strokeRect(x0 + 0.5, y0 + 0.5, size, size); // Axis labels const showDeg = $("#show-degrees").checked; const ref = state.ws?.fixtures.find((f) => f.is_mover && f.pan_max); ctx.fillStyle = "#8d94a6"; ctx.font = "11px system-ui"; ctx.textAlign = "center"; ctx.textBaseline = "top"; for (let v = 0; v <= 255; v += 64) { const x = x0 + (v / 255) * size; let label = String(v); if (showDeg && ref) label += ` · ${Math.round((v / 255) * ref.pan_max)}°`; ctx.fillText(label, x, y0 + size + 6); } ctx.fillText("PAN →", x0 + size / 2, y0 + size + 22); ctx.textAlign = "right"; ctx.textBaseline = "middle"; for (let v = 0; v <= 255; v += 64) { const y = y0 + (v / 255) * size; let label = String(v); if (showDeg && ref) label = `${Math.round((v / 255) * ref.tilt_max)}° · ` + label; ctx.fillText(label, x0 - 6, y); } ctx.save(); ctx.translate(x0 - 34, y0 + size / 2); ctx.rotate(-Math.PI / 2); ctx.textAlign = "center"; ctx.textBaseline = "bottom"; ctx.fillText("TILT (0 = top, like the QLC+ XY pad)", 0, 0); ctx.restore(); } // Canvas interaction function hitWaypoint(x, y) { let best = -1, bestD = 12; state.pattern.path.points.forEach((p, i) => { const [px, py] = toPx(p.pan, p.tilt); const d = Math.hypot(px - x, py - y); if (d < bestD) { bestD = d; best = i; } }); return best; } canvas.addEventListener("pointerdown", (e) => { const r = canvas.getBoundingClientRect(); const x = e.clientX - r.left, y = e.clientY - r.top; const inside = x >= geom.x0 && x <= geom.x0 + geom.size && y >= geom.y0 && y <= geom.y0 + geom.size; if (state.pattern.type === "efx") { if (state.pattern.efx.relative) return; const [cx, cy] = toPx(state.pattern.efx.x_offset, state.pattern.efx.y_offset); if (Math.hypot(cx - x, cy - y) < 14 || inside) { state.drag = { kind: "centre" }; canvas.setPointerCapture(e.pointerId); moveCentre(x, y); } return; } const hit = hitWaypoint(x, y); if (hit >= 0) { state.selected = hit; state.drag = { kind: "point", index: hit }; canvas.setPointerCapture(e.pointerId); renderPoints(); } else if (inside) { const [pan, tilt] = toDmx(x, y); const pts = state.pattern.path.points; const last = pts[pts.length - 1]; const insertAt = state.selected >= 0 ? state.selected + 1 : pts.length; pts.splice(insertAt, 0, { pan: clamp255(pan), tilt: clamp255(tilt), fade_ms: last ? last.fade_ms : 1000, hold_ms: last ? last.hold_ms : 0 }); state.selected = insertAt; state.drag = { kind: "point", index: insertAt }; canvas.setPointerCapture(e.pointerId); renderPoints(); requestSample(); } }); canvas.addEventListener("pointermove", (e) => { if (!state.drag) return; const r = canvas.getBoundingClientRect(); const x = e.clientX - r.left, y = e.clientY - r.top; if (state.drag.kind === "centre") moveCentre(x, y); else { const [pan, tilt] = toDmx(x, y); const p = state.pattern.path.points[state.drag.index]; if (!p) return; p.pan = clamp255(pan); p.tilt = clamp255(tilt); const tr = $("#point-table tbody").children[state.drag.index]; if (tr) { tr.querySelector("[data-k=pan]").value = Math.round(p.pan); tr.querySelector("[data-k=tilt]").value = Math.round(p.tilt); } requestSample(); } }); const endDrag = () => { state.drag = null; }; canvas.addEventListener("pointerup", endDrag); canvas.addEventListener("pointercancel", endDrag); function moveCentre(x, y) { const [pan, tilt] = toDmx(x, y); state.pattern.efx.x_offset = clamp255(pan); state.pattern.efx.y_offset = clamp255(tilt); syncEfxForm(); requestSample(); } const clamp255 = (v) => Math.max(0, Math.min(255, Math.round(v))); document.addEventListener("keydown", (e) => { if (e.target.matches("input, select, textarea")) return; if (e.code === "Space") { e.preventDefault(); togglePlay(); } if ((e.key === "Delete" || e.key === "Backspace") && state.pattern.type === "path" && state.selected >= 0) { state.pattern.path.points.splice(state.selected, 1); state.selected = Math.min(state.selected, state.pattern.path.points.length - 1); renderPoints(); requestSample(); } }); function togglePlay() { state.playing = !state.playing; $("#play").textContent = state.playing ? "Pause" : "Play"; } // ------------------------------------------------------------------ export async function exportPattern() { const btn = $("#exp-go"), out = $("#exp-result"); btn.disabled = true; out.textContent = "writing…"; out.className = "result"; try { const body = { path: state.wsPath, pattern: state.pattern, name: $("#pat-name").value.trim() || "Mover Pattern", overwrite: $("#exp-overwrite").checked, add_button: $("#exp-button").checked, out_path: $("#exp-out").value.trim() || null, }; const r = await api("POST", "/api/export", body); const ids = Object.entries(r.function_ids).map(([k, v]) => `${k} #${v}`).join(", "); out.textContent = `Wrote ${r.path} (${ids}${r.widget_id != null ? `, button #${r.widget_id}` : ""}${r.replaced.length ? `, replaced ${r.replaced.join(",")}` : ""}). Reload the workspace in QLC+.`; out.className = "result ok"; if (!body.out_path) await loadWorkspace(state.wsPath); else { await loadWorkspaces(); } } catch (err) { out.textContent = err.message; out.className = "result err"; } finally { btn.disabled = false; } } // ------------------------------------------------------------------ library + workspace functions async function loadLibrary() { try { const d = await api("GET", "/api/patterns"); state.library = d.patterns; } catch (err) { setStatus(err.message, "err"); } const ul = $("#lib-list"); ul.innerHTML = ""; if (!state.library.length) { ul.innerHTML = '
  • No saved patterns yet
  • '; return; } for (const item of state.library) { const li = document.createElement("li"); li.innerHTML = `${esc(item.name)} ${item.type}`; const [load, del] = li.querySelectorAll("button"); load.addEventListener("click", () => applyPattern(item.pattern)); del.addEventListener("click", async () => { if (!confirm(`Delete saved pattern "${item.name}"?`)) return; await api("DELETE", `/api/patterns?file=${encodeURIComponent(item.file)}`); loadLibrary(); }); ul.appendChild(li); } } async function savePattern() { const name = $("#pat-name").value.trim() || "Mover Pattern"; state.pattern.name = name; try { await api("POST", "/api/patterns", { name, pattern: state.pattern }); setStatus(`Saved "${name}" to patterns/`, "ok"); loadLibrary(); } catch (err) { setStatus(err.message, "err"); } } function renderFunctionList() { const ul = $("#fn-list"); ul.innerHTML = ""; const fns = (state.ws?.functions || []).filter((f) => f.type === "EFX" || f.type === "Sequence"); if (!fns.length) { ul.innerHTML = '
  • None
  • '; return; } for (const f of fns) { const li = document.createElement("li"); li.innerHTML = `${esc(f.name)} ${f.type} #${f.id}`; li.querySelector("button").addEventListener("click", async () => { try { const d = await api("GET", `/api/function?path=${encodeURIComponent(state.wsPath)}&id=${f.id}`); applyPattern(d.pattern); setStatus(`Loaded "${f.name}" — writing will replace it`, "ok"); } catch (err) { setStatus(err.message, "err"); } }); ul.appendChild(li); } } function applyPattern(pat) { const base = defaultPattern(); const movers = new Set((state.ws?.fixtures || []).filter((f) => f.is_mover).map((f) => f.id)); const fixtures = (pat.fixtures || []).filter((f) => movers.has(f.id)).map((f) => ({ ...fixtureConfig(f.id), ...f })); state.pattern = { ...base, ...pat, efx: { ...base.efx, ...(pat.efx || {}) }, path: { ...base.path, ...(pat.path || {}) }, fixtures: fixtures.length ? fixtures : [...movers].map(fixtureConfig), }; delete state.pattern.source_function_id; $("#pat-name").value = state.pattern.name || "Mover Pattern"; state.selected = -1; state.clock = 0; setType(state.pattern.type); syncEfxForm(); syncPathForm(); } // ------------------------------------------------------------------ live Art-Net let liveTimer = null; function scheduleLiveRestart() { clearTimeout(liveTimer); liveTimer = setTimeout(startLive, 250); } async function startLive() { try { const st = await api("POST", "/api/live/start", { path: state.wsPath, pattern: state.pattern, ip: $("#live-ip").value.trim() || null, universe: Number($("#live-uni").value) || 0, }); setStatus(`LIVE → ${st.ip} universe ${st.universe} (stop QLC+ output first)`, "ok"); } catch (err) { setStatus(`Live failed: ${err.message}`, "err"); state.live = false; $("#live-toggle").checked = false; } } async function stopLive() { try { await api("POST", "/api/live/stop"); } catch (_) { /* ignore */ } setStatus("Live stopped (blackout sent)"); } window.addEventListener("pagehide", () => { if (state.live) navigator.sendBeacon("/api/live/stop", "{}"); }); // ------------------------------------------------------------------ boot function bind() { $("#ws-select").addEventListener("change", (e) => loadWorkspace(e.target.value).catch((err) => setStatus(err.message, "err"))); $("#ws-reload").addEventListener("click", () => loadWorkspace(state.wsPath).catch((err) => setStatus(err.message, "err"))); $("#pat-name").addEventListener("input", (e) => { state.pattern.name = e.target.value; }); for (const b of $("#type-tabs").querySelectorAll("button")) b.addEventListener("click", () => setType(b.dataset.type)); $("#play").addEventListener("click", togglePlay); $("#speed").addEventListener("change", (e) => { state.speed = Number(e.target.value); }); $("#exp-go").addEventListener("click", exportPattern); $("#lib-save").addEventListener("click", savePattern); $("#live-toggle").addEventListener("change", (e) => { state.live = e.target.checked; if (state.live) startLive(); else stopLive(); }); window.addEventListener("resize", resizeCanvas); } (async function boot() { buildEfxPanel(); buildPathPanel(); bind(); resizeCanvas(); requestAnimationFrame(draw); setType("efx"); await loadLibrary(); try { await loadWorkspaces(); } catch (err) { setStatus(err.message, "err"); } resizeCanvas(); })();