Single place to convert your 2D floor plans to 3d model (no LLM)
Python
Tests: detector, furniture, walking, browser
23f2005639120f8576f61f
diff --git a/tests/run_all.sh b/tests/run_all.shnew file mode 100755index 0000000..bd64fe7--- /dev/null+++ b/tests/run_all.sh@@ -0,0 +1,15 @@+#!/usr/bin/env bash+# detector on the sample drawing (and on the private fixtures when present), furniture clashes on the sample and on+# every detected plan, and stair / wall walking on every built house. The browser test is separate: tests/test_site.mjs+cd "$(dirname "$0")/.."+set -e+python3 tests/test_sample.py+python3 tests/test_detect.py+python3 detect.py examples/sample_plan.pdf /tmp/planto3d_sample.json > /dev/null+for p in /tmp/planto3d_sample.json jobs/*/plan.json; do+ [ -f "$p" ] || continue+ out=$(python3 furnish.py "$p")+ echo "$out" | grep -q CLASH && { echo "$p"; echo "$out"; exit 1; } || echo "no furniture clashes: $p"+done+for m in jobs/*/meta.json; do [ -f "$m" ] && node tests/test_walk.mjs "$m"; done+echo ALL PASSdiff --git a/tests/test_detect.py b/tests/test_detect.pynew file mode 100644index 0000000..02e7e41--- /dev/null+++ b/tests/test_detect.py@@ -0,0 +1,123 @@+"""Detector accuracy against two hand-measured real plans. Those drawings are private and not part of the repository:+set PLANTO3D_FIXTURES to a folder holding plan.py, plan6.py (the measurements), opt6.pdf and sf.pdf, or this test is skipped.+Run: python3 tests/test_detect.py -> per floor scores, fails if below the thresholds. (tests/test_sample.py always runs.)"""+import os, sys++HERE = os.path.dirname(os.path.abspath(__file__))+FIX = os.environ.get("PLANTO3D_FIXTURES", "")+if not all(os.path.exists(os.path.join(FIX, f)) for f in ("plan.py", "plan6.py", "opt6.pdf", "sf.pdf")):+ print("skip test_detect.py: private fixtures not found (PLANTO3D_FIXTURES)")+ sys.exit(0)+sys.path[:0] = [os.path.dirname(HERE), FIX]+import detect # noqa+import plan as P1 # noqa+import plan6 as P6 # noqa++OPT6, SF = os.path.join(FIX, "opt6.pdf"), os.path.join(FIX, "sf.pdf")+G = 0.25 # raster cell, feet+TOL = 2 # cells of slack (0.5 ft) for wall placement+++def kind(key):+ k = key.split("_")[-1].rstrip("0123456789")+ return {"bed": "bedroom", "toi": "toilet", "mtoi": "toilet", "dress": "toilet", "kit": "kitchen",+ "liv": "living", "drg": "living", "din": "dining", "puja": "puja", "wash": "wash",+ "pass": "passage", "lobby": "passage", "ver": "balcony"}.get(k)+++def truth():+ sh = lambda bs, dx: [(b[0] + dx, b[1] + dx, *b[2:]) for b in bs]+ gf = dict(walls=P6.GF_WALLS + [b for b, h in P6.GF_LOW], doors=P6.GF_DOORS,+ windows=[w[:4] for w in P6.GF_WINDOWS], rooms=[(kind(k), r[2][0]) for k, r in P6.GF_ROOMS.items()])+ fw = P6.FF_WALLS + [b for b, h in P6.FF_LOW]+ fd, fwin, fr = list(P6.FF_DOORS), [w[:4] for w in P6.FF_WINDOWS], []+ for tag, dx in (("A", 0), ("B", P6.SHIFT)):+ fw += sh(P6.FLAT_WALLS, dx) + sh([b for b, h in P6.FLAT_LOW], dx)+ fd += sh(P6.FLAT_DOORS, dx)+ fwin += sh([w[:4] for w in P6.FLAT_WINDOWS], dx)+ fr += [(kind(k), rects[0]) for k, _, _, rects in P6.flat_rooms(tag)]+ ff = dict(walls=fw, doors=fd, windows=fwin, rooms=fr)+ sf = dict(walls=P1.WALLS + [b for b, h in P1.LOW_WALLS], doors=[d[:4] for d in P1.DOORS],+ windows=[w[:4] for w in P1.WINDOWS], rooms=[(kind(k), r[2][0]) for k, r in P1.ROOMS.items()])+ return [(OPT6, 0, "opt6 ground", gf), (OPT6, 1, "opt6 first", ff), (SF, 0, "sf first", sf)]+++def cells(rects):+ out = set()+ for r in rects:+ for i in range(round(r[0] / G), round(r[1] / G)):+ for j in range(round(r[2] / G), round(r[3] / G)):+ out.add((i, j))+ return out+++def near(a, b, t=TOL):+ """fraction of cells of a within t cells of some cell of b"""+ if not a:+ return 0.0+ grow = {(i + di, j + dj) for i, j in b for di in range(-t, t + 1) for dj in range(-t, t + 1)}+ return sum(c in grow for c in a) / len(a)+++def match(det, tru, d=1.6):+ """greedy centre matching of opening rects -> (recall, precision)"""+ c = lambda r: ((r[0] + r[1]) / 2, (r[2] + r[3]) / 2)+ used, hit = set(), 0+ for t in tru:+ tc = c(t)+ best = min(((abs(c(r)[0] - tc[0]) + abs(c(r)[1] - tc[1]), k) for k, r in enumerate(det) if k not in used),+ default=(99, None))+ if best[0] <= d:+ used.add(best[1]); hit += 1+ return hit / max(1, len(tru)), hit / max(1, len(det))+++def score(f, t):+ det_w = [w[:4] for w in f["walls"]]+ det_o = [o["rect"] for o in f["openings"]]+ tw = cells(t["walls"])+ # detected walls + openings ~ truth walls (truth walls run through their openings); find the best shift+ best = None+ for dx in range(-6, 7):+ for dy in range(-6, 7):+ dw = {(i + dx, j + dy) for i, j in cells(det_w + det_o)}+ sc = near(dw, tw) + near(tw, dw)+ if not best or sc > best[0]:+ best = (sc, dx, dy, near(dw, tw), near(tw, dw))+ _, dx, dy, wp, wr = best+ sx, sy = dx * G, dy * G+ mv = lambda r: (r[0] + sx, r[1] + sx, r[2] + sy, r[3] + sy)+ doors = [mv(o["rect"]) for o in f["openings"] if o["type"] in ("door", "opening")]+ wins = [mv(o["rect"]) for o in f["openings"] if o["type"] == "window"]+ dr, dp = match(doors, t["doors"])+ wr_, wp_ = match(wins, t["windows"])+ ok = 0+ for typ, r in t["rooms"]:+ x, y = (r[0] + r[1]) / 2 - sx, (r[2] + r[3]) / 2 - sy+ got = next((z["type"] for z in f["rooms"] for q in z["rects"] if q[0] <= x <= q[1] and q[2] <= y <= q[3]), None)+ ok += got == typ or {got, typ} == {"living", "dining"}+ return dict(shift=(sx, sy), wall_precision=wp, wall_recall=wr, door_recall=dr, door_precision=dp,+ window_recall=wr_, window_precision=wp_, rooms=ok / len(t["rooms"]))+++# regression guards (current scores minus a margin), not targets+MIN = dict(wall_precision=0.85, wall_recall=0.9, door_recall=0.8, door_precision=0.55, window_recall=0.9,+ window_precision=0.9, rooms=0.95)++if __name__ == "__main__":+ cache, fails = {}, []+ for pdf, k, name, t in truth():+ if not os.path.exists(pdf):+ print(f"skip {name}: {pdf} missing")+ continue+ plan = cache.setdefault(pdf, detect.detect(pdf))+ sc = score(plan["floors"][k], t)+ print(f"{name:12s} " + " ".join(f"{a}={b:.2f}" if isinstance(b, float) else f"{a}={b}" for a, b in sc.items()))+ fails += [f"{name} {a}={sc[a]:.2f} < {m}" for a, m in MIN.items() if sc[a] < m]+ s6 = cache.get(OPT6, {}).get("scale_pt_per_ft")+ if s6:+ print(f"opt6 scale {s6} (true 12.204)")+ if abs(s6 - 12.204) > 0.06:+ fails.append("opt6 scale off")+ print("FAIL:\n " + "\n ".join(fails) if fails else "PASS")+ sys.exit(1 if fails else 0)diff --git a/tests/test_sample.py b/tests/test_sample.pynew file mode 100644index 0000000..162d4b5--- /dev/null+++ b/tests/test_sample.py@@ -0,0 +1,24 @@+"""The detector on the made-up sample drawing (examples/sample_plan.pdf): every wall, door, window and room must be+found, and the scale read from the room sizes. python3 tests/test_sample.py"""+import os, sys++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path[:0] = [os.path.dirname(HERE), os.path.join(os.path.dirname(HERE), "examples")]+import detect # noqa: E402+import make_sample as M # noqa: E402++plan = detect.detect(os.path.join(HERE, "..", "examples", "sample_plan.pdf"))+assert plan["scale_source"] == "labels" and abs(plan["scale_pt_per_ft"] - M.S) < 0.02 * M.S, plan["scale_pt_per_ft"]+assert len(plan["floors"]) == 1, [f["name"] for f in plan["floors"]]+f = plan["floors"][0]+assert f["name"] == "Ground Floor" and all(abs(a - b) < 0.1 for a, b in zip(f["size"], M.EXPECT["size"])), (f["name"], f["size"])+kinds = [o["type"] for o in f["openings"]]+assert (kinds.count("door"), kinds.count("window")) == (M.EXPECT["doors"], M.EXPECT["windows"]), kinds+assert sorted(r["type"] for r in f["rooms"]) == M.EXPECT["rooms"], [r["type"] for r in f["rooms"]]+# every drawn opening is where the drawing puts it (to a tenth of a foot)+drawn = [(k, *((c0, c1, y0, y1) if x1 - x0 > y1 - y0 else (x0, x1, c0, c1)))+ for (x0, x1, y0, y1), cuts in M.WALLS for k, c0, c1, _ in cuts]+for k, *r in drawn:+ assert any(o["type"] == k and all(abs(a - b) < 0.1 for a, b in zip(o["rect"], r)) for o in f["openings"]), (k, r)+print("ok sample plan: %d walls, %d doors, %d windows, %d rooms, scale %.1f pt/ft" % (+ len(f["walls"]), kinds.count("door"), kinds.count("window"), len(f["rooms"]), plan["scale_pt_per_ft"]))diff --git a/tests/test_site.mjs b/tests/test_site.mjsnew file mode 100644index 0000000..1c40bf1--- /dev/null+++ b/tests/test_site.mjs@@ -0,0 +1,107 @@+// End-to-end check of the site in a real (headless) browser, against a running server:+// the upload page rejects a non-PDF and accepts a PDF; the review page's "Furniture" box, unticked, gives a draft build+// whose saved plan has furnish=false, and the build box shows status words and the time left; in the walkthrough, P saves a 4K-size PNG, R records a video, M enlarges the map and T-T returns to walking.+// Takes about 2 min (one draft build); removes its own job.+// CHROME=/path/to/chromium node tests/test_site.mjs <plan.pdf> [http://127.0.0.1:8080]+import { spawn } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import assert from 'node:assert';+import { entrance } from '../web/walk.js';+const [pdf, base = 'http://127.0.0.1:8080'] = process.argv.slice(2);+const sleep = (t) => new Promise((r) => setTimeout(r, t));+const CH = process.env.CHROME || 'chromium';+const port = 9400 + Math.floor(Math.random() * 400);+const ch = spawn(CH, ['--headless=new', '--no-sandbox', `--remote-debugging-port=${port}`, '--use-angle=gl-egl', '--ignore-gpu-blocklist', '--enable-gpu', 'about:blank'], { stdio: 'ignore' });+let job;+try {+ let targets;+ for (let i = 0; i < 100 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); } catch { await sleep(200); } }+ const ws = new WebSocket(targets.find((t) => t.type === 'page').webSocketDebuggerUrl);+ await new Promise((r) => ws.addEventListener('open', r));+ let id = 0; const pend = new Map();+ ws.addEventListener('message', (e) => { const m = JSON.parse(e.data); if (m.id && pend.has(m.id)) { pend.get(m.id)(m); pend.delete(m.id); } });+ const cdp = (method, params = {}) => new Promise((r) => { const i = ++id; pend.set(i, r); ws.send(JSON.stringify({ id: i, method, params })); });+ const ev = async (expr) => (await cdp('Runtime.evaluate', { expression: expr, returnByValue: true })).result?.result?.value;+ const choose = async (file) => {+ const { result } = await cdp('Runtime.evaluate', { expression: `document.getElementById('file')` });+ await cdp('DOM.setFileInputFiles', { files: [file], objectId: result.result.objectId });+ };+ await cdp('Page.navigate', { url: base + '/' });+ await sleep(1000);+ await choose(new URL(import.meta.url).pathname); // this script: not a PDF+ for (let i = 0; i < 50 && !(await ev(`document.getElementById('msg').className`)); i++) await sleep(100);+ assert.match(await ev(`document.getElementById('msg').textContent`), /PDF/, 'a non-PDF should be refused with a message');+ assert.equal(await ev(`document.getElementById('drop').classList.contains('busy')`), false, 'upload box should be usable again');+ await choose(path.resolve(pdf));+ for (let i = 0; i < 100 && !job; i++) { await sleep(200); job = /edit\.html\?job=([a-f0-9]{12})/.exec(await ev('location.href') || '')?.[1]; }+ assert(job, 'a PDF should open the review page');+ for (let i = 0; i < 150 && (await ev(`getComputedStyle(document.getElementById('wait')).display`)) !== 'none'; i++) await sleep(200);+ assert.equal(await ev(`document.getElementById('furn').checked`), true, 'Furniture box should start ticked');+ await ev(`document.getElementById('furn').click(); document.getElementById('quality').value = 'draft'; document.getElementById('build').click()`);+ let st, sawEta = false, sawWord = false, sawStep = false;+ for (let i = 0; i < 400; i++) {+ st = await (await fetch(`${base}/api/jobs/${job}`)).json();+ if (['done', 'failed'].includes(st.stage)) break;+ sawEta ||= /left|almost done/.test(await ev(`document.getElementById('beta').textContent`));+ sawStep ||= /baking light|exporting model|building walls/.test(await ev(`document.getElementById('bmsg').textContent`));+ sawWord ||= /^\S.+…$/.test(await ev(`document.getElementById('bfun').hidden ? '' : document.getElementById('bword').textContent`));+ await sleep(1500);+ }+ assert.equal(st.stage, 'done', `build ${st.stage}: ${st.message}`);+ assert(sawEta, 'the build box should show the estimated time left');+ assert(sawWord, 'the build box should show a status word while building');+ assert(!sawStep, "the build box should not show Blender's step names");+ await sleep(2500);+ assert.equal(await ev(`document.getElementById('bfun').hidden`), true, 'status words should stop when the build is done');+ assert.match(await ev(`document.getElementById('bmsg').textContent`), /built in \d+ (s|min)/, 'the build box should say how long the build took');+ const plan = await (await fetch(`${base}/jobs/${job}/plan.json`)).json();+ assert.strictEqual(plan.furnish, false, 'plan.furnish should be false after unticking');+ // reopening the page must show the saved choice+ await cdp('Page.navigate', { url: `${base}/web/edit.html?job=${job}` });+ for (let i = 0; i < 150 && (await ev(`getComputedStyle(document.getElementById('wait')).display`)) !== 'none'; i++) await sleep(200);+ assert.equal(await ev(`document.getElementById('furn').checked`), false, 'Furniture box should stay unticked after reload');+ // walkthrough: screenshot (P) and recording (R) land in the downloads folder+ const dl = fs.mkdtempSync(path.join(os.tmpdir(), 'planto3d-'));+ const key = async (code, vk) => { for (const type of ['keyDown', 'keyUp']) await cdp('Input.dispatchKeyEvent', { type, code, key: code.slice(3).toLowerCase(), windowsVirtualKeyCode: vk }); };+ await cdp('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: dl });+ await cdp('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false });+ const meta = await (await fetch(`${base}/jobs/${job}/meta.json`)).json();+ const start = entrance(meta);+ await cdp('Page.navigate', { url: `${base}/web/view.html?job=${job}&pose=${start.x},${start.y},0,30,0` });+ for (let i = 0; i < 300 && !(await ev('!!window.__ready')); i++) await sleep(200);+ await sleep(1500);+ await key('KeyP', 80);+ await sleep(2500);+ await key('KeyR', 82);+ await cdp('Input.dispatchKeyEvent', { type: 'keyDown', code: 'KeyE', key: 'e', windowsVirtualKeyCode: 69 }); // turn: a still view compresses to almost nothing+ await sleep(3000);+ await cdp('Input.dispatchKeyEvent', { type: 'keyUp', code: 'KeyE', key: 'e', windowsVirtualKeyCode: 69 });+ assert.match(await ev(`document.getElementById('rec').textContent`), /^Stop 0:0\d$/, 'Record button should show the running time');+ await key('KeyR', 82);+ await sleep(2500);+ // the map: drawn, M enlarges it; leaving the top view (T, T) must not leave the mouse uncaptured with no start screen+ assert(await ev(`(() => { const c = document.getElementById('map'), d = c.getContext('2d').getImageData(0, 0, c.width, c.height).data;+ let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i]) n++; return n; })()`) > 1000, 'the map should be drawn');+ await key('KeyM', 77);+ assert.equal(await ev(`document.getElementById('map').classList.contains('big')`), true, 'M should enlarge the map');+ await key('KeyM', 77);+ await key('KeyT', 84);+ await sleep(400);+ await key('KeyT', 84);+ await sleep(600);+ assert.equal(await ev(`!!document.pointerLockElement || getComputedStyle(document.getElementById('overlay')).display !== 'none'`), true,+ 'leaving the top view should capture the mouse again or show the start screen');+ const files = fs.readdirSync(dl), png = files.find((f) => f.endsWith('.png')), vid = files.find((f) => /\.(mp4|webm)$/.test(f));+ assert(png && vid, `expected a screenshot and a video, got ${files}`);+ const ihdr = fs.readFileSync(path.join(dl, png));+ assert(ihdr.readUInt32BE(16) * ihdr.readUInt32BE(20) >= 0.95 * 3840 * 2160, 'screenshot should be about 4K');+ assert(fs.statSync(path.join(dl, vid)).size > 100e3, 'recording should not be empty');+ fs.rmSync(dl, { recursive: true });+ console.log('PASS upload page, furniture option, build box, screenshot, recording, map and top view');+} finally {+ ch.kill();+ if (job) fs.rmSync(new URL(`../jobs/${job}`, import.meta.url), { recursive: true, force: true }); // the test's own upload+}+process.exit(0);diff --git a/tests/test_walk.mjs b/tests/test_walk.mjsnew file mode 100644index 0000000..9562691--- /dev/null+++ b/tests/test_walk.mjs@@ -0,0 +1,60 @@+// Walk test on a generated house: climb every storey's stairs (flight -> landing -> flight) and check we arrive+// on the next floor; and check walls stop the walker. Run: node tests/test_walk.mjs jobs/<id>/meta.json+import fs from 'node:fs';+import * as walk from '../web/walk.js';++const meta = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));+let fails = 0;+const check = (ok, msg) => { console.log(`${ok ? 'ok ' : 'FAIL'} ${msg}`); if (!ok) fails++; };++function goTo(p, tx, ty, maxSteps = 2000) {+ for (let i = 0; i < maxSteps; i++) {+ const dx = tx - p.x, dy = ty - p.y, d = Math.hypot(dx, dy);+ if (d < 0.03) return true;+ const s = Math.min(0.04, d);+ const bx = p.x, by = p.y;+ walk.move(meta, p, dx / d * s, dy / d * s);+ if (p.x === bx && p.y === by) return false; // stuck+ }+ return false;+}++meta.floors.forEach((f, k) => {+ const flights = (f.stairs || []).filter((s) => !s.landing);+ if (!flights.length) return;+ if (meta.floors.length === 1) { // a single storey's stairs lead nowhere drawn: the walker must not get onto them+ const s0 = flights[0], mid = s0.axis === 'x' ? (s0.rect[2] + s0.rect[3]) / 2 : (s0.rect[0] + s0.rect[1]) / 2;+ const p = s0.axis === 'x' ? { x: s0.start - s0.dir * 0.6, y: mid, z: f.z } : { x: mid, y: s0.start - s0.dir * 0.6, z: f.z };+ const end = s0.start + s0.dir * 1.5;+ goTo(p, s0.axis === 'x' ? end : p.x, s0.axis === 'x' ? p.y : end);+ check(Math.abs(p.z - f.z) < 0.01 && !walk.inRect(s0.rect, p.x, p.y), `${f.name}: stairs to the roof are closed (stopped at ${p.x.toFixed(2)}, ${p.y.toFixed(2)})`);+ return;+ }+ const target = k + 1 < meta.floors.length ? meta.floors[k + 1].z : meta.roof_z;+ const s0 = flights[0];+ const mid = (r, ax) => (ax === 'x' ? (r[2] + r[3]) / 2 : (r[0] + r[1]) / 2);+ // stand on the floor just before the first step+ const p = s0.axis === 'x' ? { x: s0.start - s0.dir * 0.3, y: mid(s0.rect, 'x'), z: f.z } : { x: mid(s0.rect, 'y'), y: s0.start - s0.dir * 0.3, z: f.z };+ let ok = true;+ for (const s of flights) {+ const len = s.axis === 'x' ? s.rect[1] - s.rect[0] : s.rect[3] - s.rect[2];+ const end = s.start + s.dir * (len + 0.35);+ // line up with this flight (across the landing), then climb it+ ok = ok && goTo(p, s.axis === 'x' ? p.x : mid(s.rect, 'y'), s.axis === 'x' ? mid(s.rect, 'x') : p.y);+ ok = ok && goTo(p, s.axis === 'x' ? end : p.x, s.axis === 'x' ? p.y : end);+ }+ check(ok, `${f.name}: walked up all ${flights.length} flight(s) without getting stuck (at ${p.x.toFixed(2)}, ${p.y.toFixed(2)})`);+ check(Math.abs(p.z - target) < 0.05, `${f.name}: arrived at height ${p.z.toFixed(2)} m (next level ${target.toFixed(2)} m)`);+});++// walls block: walking straight at the first collider of the ground floor must stop before it+const w = meta.floors[0].colliders.find((r) => r[1] - r[0] > 2);+if (w) {+ const y = w[2] - 1.0, x = (w[0] + w[1]) / 2;+ const p = { x, y, z: meta.floors[0].z };+ if (walk.groundNear(meta, x, y, p.z) !== null && !walk.blockedAt(meta, 0, x, y)) {+ goTo(p, x, w[3] + 1.0);+ check(p.y < w[2], `wall at y=${w[2].toFixed(2)} stopped the walker at y=${p.y.toFixed(2)}`);+ }+}+process.exit(fails ? 1 : 0);