holder + scad: SCAD source editor on /holder + new /scad universal renderer

Phase 2 — SCAD editor on /holder
================================
Some adjustments need more control than the parameter form gives
(e.g. tweaking the .scad logic itself). A collapsible CodeMirror-based
editor now slides up from the bottom of the viewport when you click
the "</> Source" button at the bottom-right.

- holder.html / holder.css: editor panel, toggle button, Reset and
  Close buttons. CodeMirror 5 loaded from cdnjs (single CSS + JS
  pair, clike mode for syntax highlighting since OpenSCAD is C-like).
- holder-app.js: lazy-initialises the editor on first show, fetches
  bundled source from /api/holder/source, tracks whether the editor
  content has been modified ("modified" tag in the panel title).
  When the editor is visible AND content differs from bundled,
  _doRender() switches from /api/holder/render -> /api/scad/render
  with {source, params}. Cell-count cap doesn't apply in that mode
  (the source may not even use the holder schema).

Phase 3 — Universal OpenSCAD playground at /scad
================================================
A standalone page for rendering arbitrary OpenSCAD. Paste code, click
Render (or Ctrl+Enter), see STL in the same Three.js viewer the
holder uses. Useful for prototyping new generators before wiring
them into a parameter form.

- New page: static/scad.html + scad.css + js/scad-app.js. Reuses
  holder-viewer.js (the Three.js scene module is generic enough).
- "Load example" populates a 6-hole rounded bracket so new users
  can verify the renderer works in two clicks.
- Same progress UI (elapsed timer + indeterminate bar + Cancel
  via AbortController) as /holder.
- Top nav now has Holder / Busbars / SCAD on every page.

Backend (shared by phase 2 & 3)
================================
- holder.py: split _run_openscad() out of render_stl(). New
  render_source(source, params=None) writes the source to a temp
  file and renders it; enforces MAX_SOURCE_BYTES (default 512 KB)
  and RENDER_TIMEOUT but skips the cell-count cap. New bundled_source()
  returns the hex_cell.scad text for editor pre-population.
- app.py: GET /api/holder/source returns the bundled .scad text.
  POST /api/scad/render takes {source, params?} and returns STL +
  X-Holder-Dimensions header. ValueError -> 400, RuntimeError -> 500.
  _stl_response() factored out so both render endpoints emit the same
  headers consistently.
This commit is contained in:
wenil
2026-05-25 12:52:18 +03:00
parent 5bba0e3c4a
commit 676d976937
9 changed files with 470 additions and 29 deletions
+47 -14
View File
@@ -44,6 +44,12 @@ def holder_page():
return send_from_directory(STATIC_DIR, "holder.html")
@app.get("/scad")
def scad_page():
"""Universal OpenSCAD renderer (paste any source, get STL)."""
return send_from_directory(STATIC_DIR, "scad.html")
@app.get("/api/health")
def health():
return jsonify({"status": "ok", "openscad": holder.openscad_available()})
@@ -64,9 +70,21 @@ def holder_params():
})
def _stl_response(data: bytes, dims: dict, filename: str) -> Response:
return Response(
data,
mimetype="model/stl",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"X-Holder-Dimensions": json.dumps(dims),
"Access-Control-Expose-Headers": "X-Holder-Dimensions",
},
)
@app.post("/api/holder/render")
def holder_render():
"""Render STL for the supplied parameter overrides."""
"""Render STL for the bundled hex holder with parameter overrides."""
body = request.get_json(silent=True) or {}
try:
data, dims = holder.render_stl(body.get("params", {}))
@@ -74,19 +92,34 @@ def holder_render():
return jsonify({"error": str(e)}), 400
except (FileNotFoundError, RuntimeError) as e:
return jsonify({"error": str(e)}), 500
return Response(
data,
mimetype="model/stl",
headers={
"Content-Disposition": 'attachment; filename="hex_holder.stl"',
# ECHO values from hex_cell.scad (pack/box dimensions). Used by
# the viewer to draw a max-bounding-box ghost for fit-check.
"X-Holder-Dimensions": json.dumps(dims),
# Make the custom header visible to fetch() in any CORS/proxy
# setup (Access-Control-Expose-Headers; harmless on same-origin).
"Access-Control-Expose-Headers": "X-Holder-Dimensions",
},
)
return _stl_response(data, dims, "hex_holder.stl")
@app.get("/api/holder/source")
def holder_source():
"""Return the bundled hex_cell.scad text (for editor pre-population)."""
try:
return Response(holder.bundled_source(), mimetype="text/plain; charset=utf-8")
except FileNotFoundError as e:
return jsonify({"error": str(e)}), 500
@app.post("/api/scad/render")
def scad_render():
"""Render arbitrary user-supplied OpenSCAD source (no holder schema).
Body: {"source": "...", "params": {optional -D overrides}}
"""
body = request.get_json(silent=True) or {}
source = body.get("source")
params = body.get("params") # may be None
try:
data, dims = holder.render_source(source, params)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except (FileNotFoundError, RuntimeError) as e:
return jsonify({"error": str(e)}), 500
return _stl_response(data, dims, "rendered.stl")
@app.post("/api/holder/cells")
+48 -13
View File
@@ -338,30 +338,26 @@ def _parse_echo_dims(stderr_bytes: bytes) -> dict:
return out
def render_stl(params: dict) -> tuple[bytes, dict]:
"""Render the .scad with given parameter overrides.
MAX_SOURCE_BYTES = int(os.environ.get("OPENSCAD_MAX_SOURCE_BYTES", str(512 * 1024)))
Returns (stl_bytes, dimensions) where dimensions is a {name: float}
dict harvested from openscad ECHO output (pack/box/holder sizes).
"""
_check_cell_limit(params)
def _run_openscad(scad_path: Path, params: dict | None) -> tuple[bytes, dict]:
if not openscad_available():
raise RuntimeError(
f"`{OPENSCAD_BIN}` not found on PATH. Install OpenSCAD "
"(e.g. `apt install openscad` on Debian/Ubuntu)."
)
if not SCAD_FILE.is_file():
raise FileNotFoundError(f"SCAD source not found at {SCAD_FILE}")
clean = _filter_params(params)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "out.stl"
cmd = [OPENSCAD_BIN, "-o", str(out)]
if OPENSCAD_BACKEND:
cmd += ["--backend", OPENSCAD_BACKEND]
for k, v in clean.items():
cmd += ["-D", f"{k}={_to_scad_literal(v)}"]
cmd.append(str(SCAD_FILE))
# Only the bundled-schema render passes -D overrides; raw source
# may not know about those variable names.
if params is not None:
for k, v in _filter_params(params).items():
cmd += ["-D", f"{k}={_to_scad_literal(v)}"]
cmd.append(str(scad_path))
try:
r = subprocess.run(cmd, capture_output=True, timeout=RENDER_TIMEOUT)
except subprocess.TimeoutExpired:
@@ -372,3 +368,42 @@ def render_stl(params: dict) -> tuple[bytes, dict]:
if not out.exists() or out.stat().st_size == 0:
raise RuntimeError("openscad produced no STL (geometry empty?)")
return out.read_bytes(), _parse_echo_dims(r.stderr or b"")
def render_stl(params: dict) -> tuple[bytes, dict]:
"""Render the bundled hex_cell.scad with parameter overrides.
Enforces the holder cell-count cap (PARAMS-schema is assumed). For
rendering arbitrary user-supplied OpenSCAD source, use render_source.
"""
_check_cell_limit(params)
if not SCAD_FILE.is_file():
raise FileNotFoundError(f"SCAD source not found at {SCAD_FILE}")
return _run_openscad(SCAD_FILE, params)
def render_source(source: str, params: dict | None = None) -> tuple[bytes, dict]:
"""Render arbitrary user-supplied OpenSCAD source.
Source size is capped (MAX_SOURCE_BYTES). Cell-count limit does NOT
apply — the source defines its own variables. RENDER_TIMEOUT still
bounds runaway computation.
"""
if not isinstance(source, str) or not source.strip():
raise ValueError("Empty SCAD source.")
src_bytes = source.encode("utf-8", errors="replace")
if len(src_bytes) > MAX_SOURCE_BYTES:
raise ValueError(
f"SCAD source too large ({len(src_bytes)} > {MAX_SOURCE_BYTES} bytes)."
)
with tempfile.TemporaryDirectory() as tmp:
scad = Path(tmp) / "user.scad"
scad.write_bytes(src_bytes)
return _run_openscad(scad, params)
def bundled_source() -> str:
"""Read the bundled hex_cell.scad for editor pre-population."""
if not SCAD_FILE.is_file():
raise FileNotFoundError(f"SCAD source not found at {SCAD_FILE}")
return SCAD_FILE.read_text(encoding="utf-8", errors="replace")
+39
View File
@@ -165,3 +165,42 @@
#fit-verdict.fit-ok { color: #4ad97a; font-weight: 600; }
#fit-verdict.fit-bad { color: var(--danger, #d94a4a); font-weight: 600; }
/* SCAD editor — slides up from the bottom of the viewport */
.scad-toggle {
position: absolute;
bottom: 8px;
right: 8px;
font-size: 12px;
padding: 4px 10px;
z-index: 3;
}
.scad-panel {
position: absolute;
left: 0; right: 0; bottom: 0;
height: 45%;
background: var(--bg, #11141a);
border-top: 1px solid var(--border, #2a2f3a);
display: flex;
flex-direction: column;
z-index: 2;
}
.scad-panel-bar {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 10px;
border-bottom: 1px solid var(--border, #2a2f3a);
font-size: 12px;
}
.scad-panel-title { flex: 1; color: var(--muted); }
.scad-dirty { color: var(--accent, #4a9eff); font-weight: 600; }
#scad-editor {
flex: 1;
overflow: hidden;
font-size: 12px;
}
#scad-editor .CodeMirror {
height: 100%;
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
}
+21
View File
@@ -6,6 +6,9 @@
<title>Hex Holder Designer</title>
<link rel="stylesheet" href="styles.css" />
<link rel="stylesheet" href="holder.css" />
<!-- CodeMirror 5 for the SCAD source editor -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/dracula.min.css" />
<script type="importmap">
{
@@ -23,6 +26,7 @@
<nav class="topbar-nav">
<a href="/holder" class="active">Holder</a>
<a href="/">Busbars</a>
<a href="/scad">SCAD</a>
</nav>
<span id="status" class="topbar-status">— cells</span>
@@ -89,10 +93,27 @@
<div class="viewport-overlay">
<div id="hint-controls">left-drag: rotate · right-drag: pan · wheel: zoom</div>
</div>
<!-- Collapsible SCAD source editor (slides up from the bottom of the viewport) -->
<div id="scad-panel" class="scad-panel" hidden>
<div class="scad-panel-bar">
<span class="scad-panel-title">SCAD source <span id="scad-dirty-tag" class="scad-dirty" hidden>· modified</span></span>
<button id="btn-scad-reset" type="button" title="Discard edits and reload bundled hex_cell.scad">Reset</button>
<button id="btn-scad-close" type="button" title="Hide the editor (changes kept until reload)">Close</button>
</div>
<div id="scad-editor"></div>
</div>
<button id="btn-scad-toggle" class="scad-toggle" type="button"
title="Show / hide the bundled SCAD source. When edits are present, renders use your source instead of the bundled file.">
&lt;/&gt; Source
</button>
</section>
</main>
<script src="js/api.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/clike/clike.min.js"></script>
<script type="module" src="js/holder-viewer.js"></script>
<script type="module" src="js/holder-app.js"></script>
</body>
+1
View File
@@ -13,6 +13,7 @@
<nav class="topbar-nav">
<a href="/holder">Holder</a>
<a href="/" class="active">Busbars</a>
<a href="/scad">SCAD</a>
</nav>
<div class="project-bar">
+64 -2
View File
@@ -23,6 +23,9 @@ const state = {
dimensions: null, // last ECHO dims dict from X-Holder-Dimensions
maxBox: null, // {w, d, h} of assembled-battery bounding box
enclosure: null, // {w, d, h} of user-defined case (or null)
scadEditor: null, // CodeMirror instance (lazy-initialised on first show)
bundledSource: null, // text fetched from /api/holder/source
scadVisible: false,
};
const COLOR_MAX_BOX = 0x4a9eff; // blue
@@ -209,10 +212,16 @@ async function _doRender() {
}, 100);
try {
const res = await fetch("/api/holder/render", {
const useCustomSource = state.scadVisible && state.scadEditor &&
state.scadEditor.getValue() !== state.bundledSource;
const url = useCustomSource ? "/api/scad/render" : "/api/holder/render";
const body = useCustomSource
? { source: state.scadEditor.getValue(), params: state.params }
: { params: state.params };
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ params: state.params }),
body: JSON.stringify(body),
signal: state.abortCtrl.signal,
});
if (!res.ok) {
@@ -348,6 +357,59 @@ function _updateFitCheck() {
}
}
// ----- SCAD editor ----------------------------------------------------------
async function _ensureBundledSource() {
if (state.bundledSource !== null) return;
const r = await fetch("/api/holder/source");
if (!r.ok) throw new Error(`source fetch failed: ${r.statusText}`);
state.bundledSource = await r.text();
}
function _updateScadDirtyTag() {
if (!state.scadEditor) return;
const dirty = state.scadEditor.getValue() !== state.bundledSource;
$("scad-dirty-tag").hidden = !dirty;
}
async function _showScadEditor() {
await _ensureBundledSource();
$("scad-panel").hidden = false;
state.scadVisible = true;
if (!state.scadEditor) {
state.scadEditor = window.CodeMirror($("scad-editor"), {
value: state.bundledSource,
mode: "text/x-csrc", // closest built-in mode for OpenSCAD
theme: "dracula",
lineNumbers: true,
indentUnit: 4,
tabSize: 4,
lineWrapping: false,
viewportMargin: Infinity, // render whole document so CM fills the panel
});
state.scadEditor.on("change", _updateScadDirtyTag);
} else {
state.scadEditor.refresh();
}
_updateScadDirtyTag();
}
function _hideScadEditor() {
$("scad-panel").hidden = true;
state.scadVisible = false;
}
$("btn-scad-toggle").addEventListener("click", () => {
if (state.scadVisible) _hideScadEditor();
else _showScadEditor().catch((e) => alert("Couldn't load SCAD: " + e.message));
});
$("btn-scad-close").addEventListener("click", _hideScadEditor);
$("btn-scad-reset").addEventListener("click", () => {
if (!state.scadEditor || state.bundledSource == null) return;
state.scadEditor.setValue(state.bundledSource);
_updateScadDirtyTag();
});
// ----- buttons --------------------------------------------------------------
$("show-max-box").addEventListener("change", _updateFitCheck);
+139
View File
@@ -0,0 +1,139 @@
/* scad-app.js controller for the /scad universal OpenSCAD playground.
*
* Reuses the same Three.js viewer module (holder-viewer.js) and the same
* /api/scad/render backend endpoint that the holder editor uses.
*/
const $ = (id) => document.getElementById(id);
const state = {
editor: null,
rendering: false,
abortCtrl: null,
elapsedTimer: null,
lastBlob: null,
rendererReady: false,
};
const EXAMPLE_SOURCE = `// Tiny example to sanity-check the renderer.
// Click Render. Then start editing.
\$fn = 80;
difference() {
// Outer rounded box
hull() {
for (x = [-20, 20], y = [-12, 12])
translate([x, y, 0]) cylinder(h = 8, r = 4);
}
// Six holes
for (i = [-2 : 2])
translate([i * 8, 0, -1]) cylinder(h = 10, d = 3);
}
`;
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);
}
function _initEditor(initialValue) {
state.editor = window.CodeMirror($("scad-editor"), {
value: initialValue,
mode: "text/x-csrc",
theme: "dracula",
lineNumbers: true,
indentUnit: 4,
tabSize: 4,
lineWrapping: false,
viewportMargin: Infinity,
});
}
function _showProgress(show) {
$("render-progress").hidden = !show;
$("btn-render").hidden = show;
$("btn-cancel").hidden = !show;
}
async function _doRender() {
if (state.rendering || !state.editor) return;
const source = state.editor.getValue().trim();
if (!source) {
$("render-status").textContent = "✗ source is empty";
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/scad/render", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ source }),
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);
}
}
$("btn-render").addEventListener("click", _doRender);
$("btn-cancel").addEventListener("click", () => state.abortCtrl?.abort());
$("btn-load-example").addEventListener("click", () => {
if (state.editor) state.editor.setValue(EXAMPLE_SOURCE);
});
$("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 = "rendered.stl";
document.body.appendChild(a); a.click();
setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 100);
});
// Ctrl+Enter from inside the editor triggers Render.
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
e.preventDefault();
_doRender();
}
});
// Bootstrap: viewer + editor with an empty buffer (or example).
_whenViewerReady(() => {
window.HolderViewer.init($("viewer3d"));
state.rendererReady = true;
_initEditor(EXAMPLE_SOURCE);
});
+37
View File
@@ -0,0 +1,37 @@
/* OpenSCAD playground — wide left pane for code, viewer on the right. */
.scad-main {
display: flex;
height: calc(100vh - 50px);
}
.scad-left {
width: 50%;
min-width: 320px;
border-right: 1px solid var(--border, #2a2f3a);
display: flex;
flex-direction: column;
}
.scad-left .panel {
border-bottom: 1px solid var(--border, #2a2f3a);
padding: 8px 12px;
}
.scad-left .panel h2 {
font-size: 11px;
color: var(--muted);
text-transform: uppercase;
margin: 0 0 6px;
letter-spacing: 0.05em;
}
#scad-editor {
flex: 1;
min-height: 250px;
border: 1px solid var(--border, #2a2f3a);
border-radius: 3px;
overflow: hidden;
font-size: 12px;
}
#scad-editor .CodeMirror {
height: 100%;
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
}
+74
View File
@@ -0,0 +1,74 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>OpenSCAD playground</title>
<link rel="stylesheet" href="styles.css" />
<link rel="stylesheet" href="holder.css" />
<link rel="stylesheet" href="scad.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/dracula.min.css" />
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.165.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.165.0/examples/jsm/"
}
}
</script>
</head>
<body>
<header class="topbar">
<h1>OpenSCAD playground</h1>
<nav class="topbar-nav">
<a href="/holder">Holder</a>
<a href="/">Busbars</a>
<a href="/scad" class="active">SCAD</a>
</nav>
<span id="status" class="topbar-status">paste OpenSCAD code →</span>
<div class="actions">
<button id="btn-render" class="primary" title="Render the SCAD source as STL">Render</button>
<button id="btn-cancel" title="Cancel running render" hidden>Cancel</button>
<button id="btn-download-stl" title="Download the rendered STL">Download STL</button>
<span class="sep"></span>
<button id="btn-load-example" title="Load a small example to verify the renderer works">Load example</button>
</div>
</header>
<main class="scad-main">
<aside class="left scad-left">
<section class="panel" style="flex:1; display:flex; flex-direction:column;">
<h2>Source</h2>
<div id="scad-editor" style="flex:1;"></div>
</section>
<section class="panel">
<h2>Status</h2>
<p class="hint" id="render-status">idle</p>
<div id="render-progress" class="render-progress" hidden>
<div class="render-progress-bar"><div class="render-progress-fill"></div></div>
<span id="render-elapsed" class="render-elapsed">0.0s</span>
</div>
<p class="hint" id="warning"></p>
</section>
</aside>
<section class="right">
<div id="viewer3d" class="viewer3d"></div>
<div class="viewport-overlay">
<div id="hint-controls">left-drag: rotate · right-drag: pan · wheel: zoom</div>
</div>
</section>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/clike/clike.min.js"></script>
<script type="module" src="js/holder-viewer.js"></script>
<script type="module" src="js/scad-app.js"></script>
</body>
</html>