Files
busbar-designer/static/js/tracks-app.js
T
wenil 102cfcee64 tracks: new /tracks generator for IKEA Lillabo / Brio train tracks
Wraps torwanbukaj/ikea-brio-others-compatible-train-tracks-generator
( https://github.com/torwanbukaj/... ) as a third generator alongside
holder and the universal scad playground.

Approach
--------
The upstream .scad ships as "library + one active example call". Used
include<> (rather than use<>) so the library's top-level globals
(track_width, plug/nest dimensions, $fn = 150, etc.) are available
to the modules — `use<>` does NOT propagate variables. Commented out
the upstream `track_tester();` call so include<> doesn't also emit
the tester geometry every time.

Per-render the backend builds a tiny wrapper SCAD on the fly:

    include <scad/train_tracks.scad>
    track(length=100, end1="plug", end2="nest", cutout=true, ...);

and hands it to holder.render_source().

Part types exposed (9)
----------------------
- tester        Calibration block (15-60mm)
- track         Straight (length + chamfers + grooves + plug/nest ends)
- arc           Curved (radius + angle, IKEA/Brio/J'adore radii in help text)
- dogbone       Nest-nest connector
- intersection  Crossing (angle + 2 lengths + 4 ends)
- switch        Turnout (left/right radius+angle, straight branch, common end)
- snake         S-curve (raised default target_length to 200 — the upstream
                modules's natural curvy-span at angle=45/radius=86 is ~150
                and the assert fires below that)
- adapter       BRIO <-> IKEA system adapter (plug + nest side)
- bridge        Multi-part (overview/ground/slope/pillar — value_map
                translates the UI labels to the int 0..3 the SCAD wants)

Files
-----
- scad/train_tracks.scad      Downloaded upstream (57 999 bytes), only
                              modification is the // before the top-level
                              track_tester() call.
- tracks.py                   PART_SCHEMAS dict, build_wrapper_scad,
                              render() that delegates to render_source.
- app.py                      GET /api/tracks/params, POST /api/tracks/render,
                              GET /tracks page route.
- static/tracks.html          Page with part selector + dynamic param form +
                              shared viewer markup. Reuses holder.css.
- static/js/tracks-app.js     Controller. Switching the part select redraws
                              the form (each part has its own schema).
                              Ctrl+Enter renders, Cancel uses AbortController.

Nav
---
Tracks link added to topbar on holder / index / scad.

Smoke test
----------
All 9 parts render with default params on the Manifold backend in
under 0.5s each (output sizes 440 KB - 1.8 MB).
2026-05-25 13:38:29 +03:00

217 lines
6.8 KiB
JavaScript

/* tracks-app.js — controller for the /tracks (train tracks generator) page.
*
* - GET /api/tracks/params — schema for all parts.
* - Switching the part selector rebuilds the param form for that part.
* - POST /api/tracks/render with {part, params} → STL → Three.js viewer.
* - Re-uses holder-viewer.js (Three.js scene) and the same status / progress
* markup the holder uses, styled via holder.css.
*/
const $ = (id) => document.getElementById(id);
const state = {
schema: null, // {parts: [{key, label, module, params, defaults}, ...]}
partsByKey: {}, // shortcut: key -> spec
currentPart: null, // key
params: {}, // per-part current values (replaced on part change)
rendering: false,
abortCtrl: null,
elapsedTimer: null,
lastBlob: null,
rendererReady: false,
};
function _whenViewerReady(cb) {
if (window.HolderViewer) { cb(); return; }
let tries = 0;
const t = setInterval(() => {
if (window.HolderViewer) { clearInterval(t); cb(); }
else if (++tries > 50) { clearInterval(t); console.error("HolderViewer never loaded"); }
}, 60);
}
// ----- form rendering -------------------------------------------------------
function _renderForm() {
const spec = state.partsByKey[state.currentPart];
const root = $("param-form");
root.innerHTML = "";
if (!spec) return;
for (const p of spec.params) {
const row = document.createElement("div");
row.className = "param-row";
const label = document.createElement("label");
label.textContent = p.label || p.name;
row.appendChild(label);
let inp;
if (p.kind === "select") {
inp = document.createElement("select");
for (const opt of p.options || []) {
const o = document.createElement("option");
o.value = opt; o.textContent = opt;
if (opt === state.params[p.name]) o.selected = true;
inp.appendChild(o);
}
} else if (p.kind === "bool") {
inp = document.createElement("input");
inp.type = "checkbox";
inp.checked = !!state.params[p.name];
} else {
inp = document.createElement("input");
inp.type = "number";
if (p.min != null) inp.min = p.min;
if (p.max != null) inp.max = p.max;
if (p.step != null) inp.step = p.step;
inp.value = state.params[p.name] ?? p.default;
}
inp.name = p.name;
inp.dataset.kind = p.kind;
inp.addEventListener("change", _onParamChange);
inp.addEventListener("input", _onParamChange);
row.appendChild(inp);
if (p.help) {
const h = document.createElement("div");
h.className = "param-help";
h.textContent = p.help;
row.appendChild(h);
}
root.appendChild(row);
}
$("status").textContent = spec.label;
}
function _onParamChange(e) {
const el = e.target;
const k = el.name;
let v;
if (el.dataset.kind === "bool") v = el.checked;
else if (el.dataset.kind === "number") v = el.value === "" ? null : Number(el.value);
else v = el.value;
state.params[k] = v;
}
function _switchPart(key) {
const spec = state.partsByKey[key];
if (!spec) return;
state.currentPart = key;
state.params = { ...spec.defaults };
$("part-help").textContent = spec.module ? `module: ${spec.module}()` : "";
_renderForm();
}
// ----- render orchestration -------------------------------------------------
function _showProgress(show) {
$("render-progress").hidden = !show;
$("btn-render").hidden = show;
$("btn-cancel").hidden = !show;
}
async function _doRender() {
if (state.rendering || !state.currentPart) return;
state.rendering = true;
state.abortCtrl = new AbortController();
$("render-status").textContent = "rendering…";
$("warning").textContent = "";
_showProgress(true);
const t0 = performance.now();
state.elapsedTimer = setInterval(() => {
$("render-elapsed").textContent = ((performance.now() - t0) / 1000).toFixed(1) + "s";
}, 100);
try {
const res = await fetch("/api/tracks/render", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ part: state.currentPart, params: state.params }),
signal: state.abortCtrl.signal,
});
if (!res.ok) {
let msg = res.statusText;
try { msg = (await res.json()).error || msg; } catch {}
throw new Error(msg);
}
state.lastBlob = await res.blob();
const buf = await state.lastBlob.arrayBuffer();
window.HolderViewer.loadSTL(buf);
const dt = ((performance.now() - t0) / 1000).toFixed(1);
$("render-status").textContent =
`✓ rendered in ${dt}s · ${(state.lastBlob.size/1024).toFixed(0)} kB`;
} catch (e) {
if (e.name === "AbortError") $("render-status").textContent = "✗ cancelled";
else $("render-status").textContent = `${e.message}`;
} finally {
state.rendering = false;
state.abortCtrl = null;
clearInterval(state.elapsedTimer);
_showProgress(false);
}
}
// ----- wiring ---------------------------------------------------------------
$("btn-render").addEventListener("click", _doRender);
$("btn-cancel").addEventListener("click", () => state.abortCtrl?.abort());
$("part-select").addEventListener("change", (e) => _switchPart(e.target.value));
$("btn-download-stl").addEventListener("click", () => {
if (!state.lastBlob) { alert("Nothing rendered yet."); return; }
const url = URL.createObjectURL(state.lastBlob);
const a = document.createElement("a");
a.href = url;
a.download = `track_${state.currentPart}.stl`;
document.body.appendChild(a); a.click();
setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 100);
});
// Ctrl+Enter triggers Render.
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
e.preventDefault();
_doRender();
}
});
// ----- bootstrap ------------------------------------------------------------
async function init() {
try {
const r = await fetch("/api/tracks/params");
if (!r.ok) throw new Error(r.statusText);
state.schema = await r.json();
state.partsByKey = Object.fromEntries(state.schema.parts.map((p) => [p.key, p]));
// Populate the part selector.
const sel = $("part-select");
sel.innerHTML = "";
for (const p of state.schema.parts) {
const o = document.createElement("option");
o.value = p.key; o.textContent = p.label;
sel.appendChild(o);
}
// Pick "track" (straight) by default — most useful first impression.
const defaultKey = state.partsByKey.track ? "track" : state.schema.parts[0].key;
sel.value = defaultKey;
_switchPart(defaultKey);
} catch (e) {
$("param-form").innerHTML =
`<div class="step-preview-err">Couldn't load schema: ${e.message}</div>`;
return;
}
_whenViewerReady(() => {
window.HolderViewer.init($("viewer3d"));
state.rendererReady = true;
_doRender(); // initial render so the user sees something
});
}
init();