Skip to content

Single place to convert your 2D floor plans to 3d model (no LLM)

Python

Web server, pages and asset downloader

23f2005639c5a3529285cf
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6304509
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+# built houses, downloaded materials, dependencies
+/jobs/
+/assets
+/node_modules/
+__pycache__/
+*.pyc
diff --git a/fetch_assets.py b/fetch_assets.py
new file mode 100644
index 0000000..247d05e
--- /dev/null
+++ b/fetch_assets.py
@@ -0,0 +1,78 @@
+"""Download the CC0 textures, models and sky this project builds with, from Poly Haven, into ./assets (about 60 MB).
+python3 fetch_assets.py [--tour] files already present are skipped; --tour adds the dusk sky for blender/cinema.py
+The server's home page runs the same download from its "Download materials" button."""
+import json, os, sys, urllib.request
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
+MODELS = ["covered_car", "outdoor_table_chair_set_01", "street_lamp_01"]
+TEXTURES = ["american_walnut_veneer", "anti_skid_tiles", "asphalt_02", "black_walnut_veneer_01", "caban", "concrete_floor",
+ "concrete_tiles", "cotton_jersey", "dry_river_pebbles", "fabric_pattern_07", "floral_jacquard", "gingham_check",
+ "granite_tile", "herringbone_pavement", "hessian_380", "laminate_floor_02", "large_floor_tiles_02", "leafy_grass",
+ "long_white_tiles", "marble_01", "oak_veneer_01", "square_concrete_pavers", "terracotta_floor_tiles",
+ "white_plaster_02"]
+SKY, TOUR_SKY = "kloofendal_48d_partly_cloudy_puresky", "qwantani_dusk_2_puresky"
+UA = {"User-Agent": "planto3d-fetch/1.0"}
+
+
+def get(url):
+ return urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60).read()
+
+
+def save(url, path):
+ if os.path.exists(path):
+ return
+ if not os.path.realpath(path).startswith(os.path.realpath(ROOT) + os.sep): # (file names come from the web reply)
+ raise ValueError(f"refusing to write outside the assets folder: {path}")
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ data = get(url)
+ with open(path + ".part", "wb") as f:
+ f.write(data)
+ os.replace(path + ".part", path) # a download cut short never leaves a half-written file under the real name
+
+
+def files(asset):
+ return json.loads(get(f"https://api.polyhaven.com/files/{asset}"))
+
+
+def missing():
+ """names of the assets that are not on disk yet (the server's system check reports these)"""
+ out = [m for m in MODELS if not os.path.exists(os.path.join(ROOT, "models", m, f"{m}_1k.gltf"))]
+ out += [t for t in TEXTURES if not os.path.isdir(os.path.join(ROOT, "textures", t))] # (some have no colour map, only bump)
+ return out + ([] if os.path.exists(os.path.join(ROOT, "hdri", "sky.hdr")) else ["sky"])
+
+
+def fetch(progress=lambda done, total, name: None, tour=False):
+ """download whatever is missing; progress(done, total, name) is called before each asset. -> names that failed"""
+ todo = [("model", m) for m in MODELS] + [("texture", t) for t in TEXTURES] + [("sky", SKY)] + ([("sky", TOUR_SKY)] if tour else [])
+ failed, need = [], missing()
+ for k, (kind, name) in enumerate(todo):
+ progress(k, len(todo), name)
+ have = os.path.exists(os.path.join(ROOT, "hdri", f"{name}.hdr")) if name == TOUR_SKY else ("sky" if kind == "sky" else name) not in need
+ if have:
+ continue
+ try:
+ f = files(name)
+ if kind == "model":
+ g = f["gltf"]["1k"]["gltf"]
+ d = os.path.join(ROOT, "models", name)
+ save(g["url"], os.path.join(d, os.path.basename(g["url"])))
+ for rel, inc in g["include"].items():
+ save(inc["url"], os.path.join(d, rel))
+ elif kind == "texture":
+ for key, short in (("Diffuse", "diff"), ("nor_gl", "nor"), ("Rough", "rough")):
+ if key in f:
+ save(f[key]["1k"]["jpg"]["url"], os.path.join(ROOT, "textures", name, f"{short}.jpg"))
+ elif name == SKY:
+ save(f["hdri"]["1k"]["hdr"]["url"], os.path.join(ROOT, "hdri", "sky.hdr"))
+ else:
+ save(f["hdri"]["2k"]["hdr"]["url"], os.path.join(ROOT, "hdri", f"{name}.hdr"))
+ except Exception as e: # one asset failing (network, renamed on Poly Haven) must not stop the rest
+ failed.append(name)
+ print("FAILED", name, e, flush=True)
+ progress(len(todo), len(todo), "")
+ return failed
+
+
+if __name__ == "__main__":
+ bad = fetch(lambda k, n, name: print(f"[{k}/{n}] {name}", flush=True), tour="--tour" in sys.argv)
+ sys.exit(f"could not download: {', '.join(bad)}" if bad else 0)
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..f89bef5
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,20 @@
+{
+ "name": "planto3d",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "planto3d",
+ "version": "1.0.0",
+ "dependencies": {
+ "three": "0.170.0"
+ }
+ },
+ "node_modules/three": {
+ "version": "0.170.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz",
+ "integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ=="
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..ce2e68a
--- /dev/null
+++ b/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "planto3d",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Floor plan PDF in, furnished walkable 3D house out. No AI model: geometry, rules and Blender.",
+ "scripts": {
+ "start": "./run.sh",
+ "test": "tests/run_all.sh"
+ },
+ "dependencies": {
+ "three": "0.170.0"
+ }
+}
diff --git a/run.sh b/run.sh
new file mode 100755
index 0000000..f8c1b8a
--- /dev/null
+++ b/run.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+# Start PlanTo3D: http://127.0.0.1:8080 (pass --port / --host / --cors to change). The home page reports anything missing.
+cd "$(dirname "$0")"
+command -v python3 >/dev/null || { echo "install Python 3.9 or newer"; exit 1; }
+[ -d node_modules/three ] || npm install || echo "npm install failed: the 3D viewer needs node_modules/three"
+exec python3 server.py "$@"
diff --git a/server.py b/server.py
new file mode 100644
index 0000000..acdde82
--- /dev/null
+++ b/server.py
@@ -0,0 +1,331 @@
+"""PlanTo3D web app: upload a CAD-exported PDF floor plan -> review the detected plan -> build a walkable 3D house.
+Standard library only. Run: python3 server.py [--port 8080] [--host 127.0.0.1] [--cors ORIGIN]
+Builds run one at a time in Blender (GPU) in a background thread; progress is polled by the pages.
+--cors lets pages on another site call the API from the browser (ORIGIN such as https://example.com, or *).
+There is no login: run it on a trusted network, or behind your own backend or proxy."""
+import importlib, json, os, queue, re, shutil, subprocess, sys, threading, time, traceback, uuid, zipfile
+from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
+from urllib.parse import urlparse, unquote
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+JOBS = os.path.join(HERE, "jobs")
+WEB = os.path.join(HERE, "web")
+THREE = os.path.join(HERE, "node_modules", "three")
+BLENDER = shutil.which("blender") or "blender"
+MAX_UPLOAD = 60 * 1024 * 1024
+BUILD_TIMEOUT = 2 * 3600 # seconds; a high-quality build of a large house takes well under an hour
+ID = re.compile(r"^[a-f0-9]{12}$")
+sys.path.insert(0, HERE)
+import detect, fetch_assets, vector # noqa: E402
+
+os.makedirs(JOBS, exist_ok=True)
+builds = queue.Queue()
+lock = threading.Lock()
+TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json",
+ ".png": "image/png", ".jpg": "image/jpeg", ".webp": "image/webp", ".glb": "model/gltf-binary",
+ ".wasm": "application/wasm", ".svg": "image/svg+xml", ".pdf": "application/pdf", ".hdr": "application/octet-stream",
+ ".zip": "application/zip"}
+CORS = sys.argv[sys.argv.index("--cors") + 1] if "--cors" in sys.argv else None
+
+
+def jdir(jid):
+ return os.path.join(JOBS, jid)
+
+
+def status(jid, **kw):
+ p = os.path.join(jdir(jid), "status.json")
+ with lock:
+ st = json.load(open(p)) if os.path.exists(p) else {}
+ st.update(kw, updated=time.time())
+ tmp = p + ".tmp"
+ with open(tmp, "w") as fh:
+ json.dump(st, fh)
+ os.replace(tmp, p)
+ return st
+
+
+def read_status(jid):
+ p = os.path.join(jdir(jid), "status.json")
+ return json.load(open(p)) if os.path.exists(p) else None
+
+
+# ------------------------------------------------------------------ system check and the materials download
+_blender = None # Blender's version, read once ("" = not found)
+assets_job = dict(running=False, done=0, total=0, failed=[])
+export_lock = threading.Lock()
+
+
+def system():
+ """what must be in place before a plan is accepted (shown on the home page, enforced on upload and build)"""
+ global _blender
+ if _blender is None:
+ try:
+ out = subprocess.run([BLENDER, "--version"], capture_output=True, text=True, timeout=60).stdout
+ _blender = (re.search(r"Blender (\d+\.\d+)", out) or [None, ""])[1]
+ except (OSError, subprocess.TimeoutExpired):
+ _blender = ""
+ checks = dict(
+ blender=dict(ok=bool(_blender) and tuple(map(int, _blender.split("."))) >= (4, 2), version=_blender),
+ pdf_tools=dict(ok=all(shutil.which(c) for c in ("pdftocairo", "pdftotext", "pdfinfo"))),
+ viewer=dict(ok=os.path.isfile(os.path.join(THREE, "build", "three.module.js"))),
+ materials=dict(ok=not fetch_assets.missing(), **assets_job))
+ return dict(ready=all(c["ok"] for c in checks.values()), **checks)
+
+
+def fetch_materials():
+ def progress(done, total, name):
+ assets_job.update(done=done, total=total)
+ try:
+ assets_job["failed"] = fetch_assets.fetch(progress)
+ except Exception as e:
+ traceback.print_exc()
+ assets_job["failed"] = [str(e)]
+ finally:
+ assets_job["running"] = False
+
+
+def export_blend(jid):
+ """jobs/<id>/house_blender.zip: the built house as one .blend with every texture packed inside (made once per build)"""
+ d = jdir(jid)
+ src, out = os.path.join(d, "house_baked.blend"), os.path.join(d, "house_blender.zip")
+ if not os.path.exists(src):
+ raise ValueError("build the 3D house first")
+ with export_lock:
+ if not os.path.exists(out) or os.path.getmtime(out) < os.path.getmtime(src):
+ tmp = os.path.join(d, "export.blend")
+ expr = f"import bpy; bpy.ops.file.pack_all(); bpy.ops.wm.save_as_mainfile(filepath={tmp!r}, copy=True, compress=True)"
+ subprocess.run([BLENDER, "-b", src, "--python-expr", expr], check=True, timeout=900, capture_output=True)
+ with zipfile.ZipFile(out + ".part", "w", zipfile.ZIP_STORED) as z: # the .blend is already compressed
+ z.write(tmp, "house.blend")
+ z.writestr("README.txt", "house.blend - made by PlanTo3D. Open it in Blender 4.2 or newer.\n"
+ "Every texture is packed inside the file. Each storey is one mesh (bake_level_N) with its lamps;\n"
+ "the render engine is Cycles. Textures and models are CC0, from polyhaven.com.\n")
+ os.remove(tmp)
+ os.replace(out + ".part", out)
+ return f"/jobs/{jid}/house_blender.zip"
+
+
+# ------------------------------------------------------------------ pipeline steps
+def run_detect(jid):
+ d = jdir(jid)
+ pdf = os.path.join(d, "source.pdf")
+ try:
+ status(jid, stage="detecting", progress=5, message="Reading the drawing")
+ n = vector.page_count(pdf)
+ for k in range(1, min(n, 6) + 1): # page images for the review screen (100 dpi = 100/72 px per pt)
+ subprocess.run(["pdftocairo", "-png", "-r", "100", "-f", str(k), "-l", str(k), "-singlefile", pdf,
+ os.path.join(d, f"page-{k}")], check=True, timeout=120)
+ p1 = vector.read_page(pdf, 1)
+ if len(p1["segs"]) < 150:
+ raise detect.PlanError("This PDF has almost no vector lines - it looks like a scan or photo. "
+ "Please export the plan from AutoCAD / your CAD tool as a PDF.")
+ importlib.reload(detect) # pick up detector fixes without restarting the server
+ plan = detect.detect(pdf)
+ with open(os.path.join(d, "plan.json"), "w") as fh:
+ json.dump(plan, fh)
+ status(jid, stage="detected", progress=100, message="Plan detected - please review",
+ floors=[f["name"] for f in plan["floors"]], scale_source=plan["scale_source"])
+ except Exception as e:
+ traceback.print_exc()
+ known = isinstance(e, detect.PlanError)
+ status(jid, stage="failed", message=str(e) if known else "This drawing could not be read. Is it a floor plan exported from a CAD tool?")
+
+
+def estimate(jid, quality):
+ """seconds this build should take: the latest finished build of the same quality on this machine, scaled by the
+ number of light maps (one per storey + the site); README timings until a build has been measured"""
+ n = len((read_status(jid) or {}).get("floors") or [1]) + 1
+ past = [st for st in (read_status(j) for j in os.listdir(JOBS) if ID.match(j))
+ if st and st.get("build_seconds") and st.get("quality") == quality]
+ if not past:
+ return {"draft": 45, "high": 240}[quality] * n
+ st = max(past, key=lambda s: s["updated"])
+ return st["build_seconds"] * n / (len(st.get("floors") or [1]) + 1)
+
+
+def builder():
+ while True:
+ jid, quality = builds.get()
+ d = jdir(jid)
+ try:
+ t0 = time.time()
+ status(jid, stage="building", progress=1, message="Starting Blender", started=t0, eta_total=estimate(jid, quality))
+ cmd = [BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
+ os.path.join(d, "plan.json"), d, "--quality", quality]
+ with open(os.path.join(d, "build.log"), "w") as log:
+ pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
+ watchdog = threading.Timer(BUILD_TIMEOUT, pr.kill) # a hung Blender must not block every later build
+ watchdog.start()
+ ok = False
+ for line in pr.stdout:
+ log.write(line)
+ m = re.match(r"PROGRESS (\d+) (.*)", line)
+ if m:
+ status(jid, progress=int(m.group(1)), message=m.group(2).strip())
+ ok = ok or line.startswith("GEN OK")
+ pr.wait()
+ watchdog.cancel()
+ if not ok or not os.path.exists(os.path.join(d, "house.glb")):
+ raise RuntimeError("3D build failed - see build.log")
+ for f in ("house.blend", "house.blend1", "house_baked.blend1"): # keep house_baked.blend only
+ if os.path.exists(os.path.join(d, f)):
+ os.remove(os.path.join(d, f))
+ status(jid, stage="done", progress=100, message="Ready", quality=quality, build_seconds=round(time.time() - t0))
+ except Exception as e:
+ traceback.print_exc()
+ status(jid, stage="failed", message=str(e))
+ finally:
+ builds.task_done()
+
+
+# ------------------------------------------------------------------ http
+class H(BaseHTTPRequestHandler):
+ server_version = "PlanTo3D/1"
+
+ def log_message(self, fmt, *a):
+ if not self.path.startswith("/api/jobs/") or "status" not in self.path:
+ sys.stderr.write("%s %s\n" % (self.address_string(), fmt % a))
+
+ def send(self, code, body, ctype="application/json"):
+ if isinstance(body, (dict, list)):
+ body = json.dumps(body).encode()
+ elif isinstance(body, str):
+ body = body.encode()
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Cache-Control", "no-cache")
+ self.cors()
+ self.end_headers()
+ self.wfile.write(body)
+
+ def cors(self):
+ if CORS:
+ self.send_header("Access-Control-Allow-Origin", CORS)
+ self.send_header("Access-Control-Allow-Headers", "Content-Type, X-Filename")
+
+ def do_OPTIONS(self): # the browser's question before a cross-site POST
+ self.send_response(204)
+ self.cors()
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ def file(self, path, root):
+ path = os.path.realpath(path)
+ if not path.startswith(os.path.realpath(root) + os.sep) or not os.path.isfile(path):
+ return self.send(404, {"error": "not found"})
+ ext = os.path.splitext(path)[1].lower()
+ size = os.path.getsize(path)
+ self.send_response(200)
+ self.send_header("Content-Type", TYPES.get(ext, "application/octet-stream"))
+ self.send_header("Content-Length", str(size))
+ # job outputs change on every rebuild: never let the browser show a stale house
+ fresh = ext in (".json", ".html", ".js", ".css") or "/jobs/" in path.replace(os.sep, "/")
+ self.send_header("Cache-Control", "no-cache" if fresh else "max-age=3600")
+ self.cors()
+ self.end_headers()
+ with open(path, "rb") as fh:
+ shutil.copyfileobj(fh, self.wfile)
+
+ def do_GET(self):
+ u = urlparse(self.path)
+ p = unquote(u.path)
+ if p in ("/", "/index.html"):
+ return self.file(os.path.join(WEB, "index.html"), WEB)
+ if p.startswith("/web/"):
+ return self.file(os.path.join(WEB, p[5:]), WEB)
+ if p.startswith("/three/"):
+ return self.file(os.path.join(THREE, p[7:]), THREE)
+ if p.startswith("/jobs/"):
+ parts = p[6:].split("/", 1)
+ if len(parts) == 2 and ID.match(parts[0]):
+ return self.file(os.path.join(jdir(parts[0]), parts[1]), jdir(parts[0]))
+ return self.send(404, {"error": "not found"})
+ m = re.match(r"^/api/jobs/([a-f0-9]{12})$", p)
+ if m:
+ st = read_status(m.group(1))
+ if st and st.get("stage") == "building" and st.get("started"): # counted here: the viewer's clock may differ
+ left = st["started"] + st["eta_total"] - time.time()
+ st["eta_left"] = max(0, round(min(left, 15) if st.get("progress", 0) >= 92 else left)) # 92 = exporting, the last step
+ return self.send(200 if st else 404, st or {"error": "no such job"})
+ if p == "/api/system":
+ return self.send(200, system())
+ if p == "/api/jobs":
+ out = []
+ for jid in sorted(os.listdir(JOBS), key=lambda j: -os.path.getmtime(jdir(j))):
+ st = read_status(jid) if ID.match(jid) else None
+ if st:
+ out.append(dict(id=jid, **{k: st.get(k) for k in ("name", "stage", "updated", "floors")}))
+ return self.send(200, out[:30])
+ self.send(404, {"error": "not found"})
+
+ def body(self):
+ n = int(self.headers.get("Content-Length") or 0)
+ if not 0 <= n <= MAX_UPLOAD:
+ raise ValueError("file too large (60 MB max)")
+ return self.rfile.read(n)
+
+ def do_POST(self):
+ p = urlparse(self.path).path
+ try:
+ if p == "/api/materials": # start the Poly Haven download (the home page's button)
+ with lock:
+ start = not assets_job["running"]
+ if start:
+ assets_job.update(running=True, done=0, total=0, failed=[])
+ if start:
+ threading.Thread(target=fetch_materials, daemon=True).start()
+ return self.send(200, {"ok": True})
+ if (p == "/api/upload" or p.endswith("/build")) and not system()["ready"]:
+ return self.send(503, {"error": "The server is not set up yet: open its home page to see what is missing."})
+ if p == "/api/upload":
+ data = self.body()
+ name = os.path.basename(unquote(self.headers.get("X-Filename") or "plan.pdf"))[:120]
+ if not data.startswith(b"%PDF"):
+ return self.send(400, {"error": "Please upload a PDF exported from your CAD tool "
+ "(images and DWG are not supported yet)."})
+ jid = uuid.uuid4().hex[:12]
+ os.makedirs(jdir(jid))
+ with open(os.path.join(jdir(jid), "source.pdf"), "wb") as fh:
+ fh.write(data)
+ status(jid, name=name, stage="uploaded", progress=0, message="Uploaded", created=time.time())
+ threading.Thread(target=run_detect, args=(jid,), daemon=True).start()
+ return self.send(200, {"id": jid})
+ m = re.match(r"^/api/jobs/([a-f0-9]{12})/(plan|build|export)$", p)
+ if m and os.path.isdir(jdir(m.group(1))):
+ jid, what = m.groups()
+ if what == "export":
+ return self.send(200, {"url": export_blend(jid)})
+ st = read_status(jid) or {}
+ if st.get("stage") in ("building", "queued"):
+ return self.send(409, {"error": "a build is already running"})
+ if what == "plan":
+ plan = json.loads(self.body())
+ if not isinstance(plan, dict) or not isinstance(plan.get("floors"), list) or not plan["floors"]:
+ return self.send(400, {"error": "invalid plan"})
+ with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
+ json.dump(plan, fh)
+ return self.send(200, {"ok": True})
+ q = json.loads(self.body() or b"{}").get("quality", "high")
+ q = q if q in ("draft", "high") else "high"
+ status(jid, stage="queued", progress=0, message=f"Waiting for the 3D builder ({builds.qsize()} ahead)")
+ builds.put((jid, q))
+ return self.send(200, {"ok": True})
+ self.send(404, {"error": "not found"})
+ except (ValueError, json.JSONDecodeError) as e:
+ self.send(400, {"error": str(e)})
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
+ traceback.print_exc()
+ self.send(500, {"error": "Blender could not write the file"})
+
+
+if __name__ == "__main__":
+ port = int(sys.argv[sys.argv.index("--port") + 1]) if "--port" in sys.argv else 8080
+ host = sys.argv[sys.argv.index("--host") + 1] if "--host" in sys.argv else "127.0.0.1"
+ for jid in os.listdir(JOBS): # builds interrupted by a restart
+ st = read_status(jid) if ID.match(jid) else None
+ if st and st.get("stage") in ("building", "queued", "detecting"):
+ status(jid, stage="failed", message="interrupted by a server restart - press Build again")
+ threading.Thread(target=builder, daemon=True).start()
+ print(f"PlanTo3D on http://{host}:{port}", flush=True)
+ ThreadingHTTPServer((host, port), H).serve_forever()
diff --git a/web/edit.html b/web/edit.html
new file mode 100644
index 0000000..ec5bacd
--- /dev/null
+++ b/web/edit.html
@@ -0,0 +1,91 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Review Plan</title>
+<link rel="stylesheet" href="/web/style.css?v=2">
+<style>
+ body { height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
+ header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid var(--line); background: var(--panel); flex-wrap: wrap; }
+ header h2 { font-size: 17px; margin: 0 10px 0 0; }
+ .tabs button { border: 1px solid var(--line); background: transparent; color: var(--ink); border-radius: 6px; padding: 5px 10px; cursor: pointer; }
+ .tabs button.on { background: var(--ink); color: var(--bg); }
+ main { flex: 1; display: flex; min-height: 0; }
+ #stage { flex: 1; position: relative; background: #fff; overflow: hidden; cursor: crosshair; touch-action: none; }
+ #cv { position: absolute; inset: 0; width: 100%; height: 100%; }
+ aside { width: 300px; border-left: 1px solid var(--line); background: var(--panel); padding: 14px; overflow: auto; display: flex; flex-direction: column; gap: 14px; }
+ aside h3 { margin: 0; font-size: 14px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
+ .tools { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
+ .tools button { border: 1px solid var(--line); background: transparent; color: var(--ink); border-radius: 6px; padding: 6px; cursor: pointer; font-size: 13px; }
+ .tools button.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 15%, transparent); }
+ .row { display: flex; gap: 8px; align-items: center; justify-content: space-between; }
+ select, input[type=text], input[type=number] { background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 5px 7px; }
+ .legend span { display: inline-flex; align-items: center; gap: 4px; margin-right: 10px; font-size: 12px; }
+ .legend i { width: 12px; height: 8px; display: inline-block; border-radius: 2px; }
+ #bfun { color: var(--accent); font-weight: 600; margin: 10px 0 0; display: flex; align-items: center; }
+ #bfun[hidden] { display: none; }
+ #bhead { display: flex; justify-content: space-between; align-items: baseline; }
+ #beta { font-weight: 400; font-size: 13px; text-transform: none; letter-spacing: 0; }
+ #bspin { width: 18px; height: 18px; flex: none; margin-right: 8px; fill: none; stroke: currentColor; stroke-width: 2;
+ stroke-linecap: round; stroke-linejoin: round; }
+ #bspin path { stroke-dasharray: 100; animation: drawhouse 2.6s ease-in-out infinite; } /* drawn, held, wiped away */
+ @keyframes drawhouse { 0% { stroke-dashoffset: 100; } 55%, 72% { stroke-dashoffset: 0; } 100% { stroke-dashoffset: -100; } }
+ @media (prefers-reduced-motion: reduce) { #bspin path { animation: none; } }
+ #wait { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: var(--bg); flex-direction: column; gap: 10px; padding: 16px; text-align: center; }
+ @media (max-width: 760px) { main { flex-direction: column; } aside { width: auto; max-height: 45vh; border-left: 0; border-top: 1px solid var(--line); } }
+</style>
+</head>
+<body>
+<header>
+ <h2 id="title">Review</h2>
+ <div class="tabs" id="tabs"></div>
+ <span class="muted" id="scale"></span>
+ <span style="flex:1"></span>
+ <label title="Untick to build empty rooms: walls, floors, doors, windows and lights only"><input type="checkbox" id="furn" checked> Furniture</label>
+ <select id="quality" title="Quality">
+ <option value="draft">Draft (fast)</option>
+ <option value="high" selected>High quality</option>
+ </select>
+ <button class="btn" id="build">Build 3D</button>
+</header>
+<main>
+ <div id="stage"><canvas id="cv"></canvas>
+ <div id="wait"><b id="wmsg">Reading the drawing…</b><div class="bar" style="width:260px"><i id="wbar"></i></div><a href="/" id="back" hidden>Upload another file</a></div>
+ </div>
+ <aside>
+ <div>
+ <h3>Tools</h3>
+ <div class="tools" id="tools">
+ <button data-t="select" class="on">Select / pan</button>
+ <button data-t="wall">Draw wall</button>
+ <button data-t="door">Add door</button>
+ <button data-t="window">Add window</button>
+ <button data-t="scale">Set scale</button>
+ <button id="undo">Undo</button>
+ </div>
+ <p class="muted" style="font-size:12px;margin:6px 0 0" id="hint">Click a wall, opening or room to edit it, or another floor plan to switch to it. Drag to pan, scroll to zoom.</p>
+ </div>
+ <div id="props"></div>
+ <div>
+ <h3>Floor</h3>
+ <div class="row"><span>Name</span><input type="text" id="fname" style="width:150px"></div>
+ <div class="row" style="margin-top:6px"><span>Ceiling height (ft)</span><input type="number" id="fh" min="8" max="14" step="0.5" style="width:70px"></div>
+ </div>
+ <div class="legend">
+ <span><i style="background:#e53935"></i>wall</span><span><i style="background:#d81bd8"></i>low wall</span>
+ <span><i style="background:#2e9d3a"></i>door</span><span><i style="background:#1e6fe0"></i>window</span>
+ <span><i style="background:#f2b400"></i>opening</span><span><i style="background:#8a5a2b"></i>stairs</span>
+ </div>
+ <div id="buildbox" hidden>
+ <h3 id="bhead">3D build<span id="beta"></span></h3>
+ <div class="bar"><i id="bbar"></i></div>
+ <p id="bfun" hidden><svg id="bspin" viewBox="0 0 24 24" aria-hidden="true"><path pathLength="100" d="M3 11 12 3l9 8M5 9.5V21h14V9.5M10 21v-6h4v6"/></svg><span id="bword"></span></p>
+ <p id="bmsg" class="muted" style="font-size:13px;margin-top:4px"></p>
+ <a class="btn" id="open" hidden>Open walkthrough</a>
+ </div>
+ </aside>
+</main>
+<script type="module" src="/web/edit.js"></script>
+</body>
+</html>
diff --git a/web/edit.js b/web/edit.js
new file mode 100644
index 0000000..7856aa4
--- /dev/null
+++ b/web/edit.js
@@ -0,0 +1,330 @@
+// Review screen: the detected plan drawn over the PDF page; fix walls / openings / room types, then build.
+const $ = (id) => document.getElementById(id);
+const job = new URLSearchParams(location.search).get('job');
+const cv = $('cv'), g = cv.getContext('2d');
+const TYPES = ['bedroom', 'toilet', 'kitchen', 'living', 'dining', 'puja', 'wash', 'store', 'study', 'passage',
+ 'balcony', 'garden', 'open', 'parking', 'yard', 'stair', 'room', 'duct', 'dress'];
+const ZCOL = { bedroom: '#c8a2c8', toilet: '#8fc7e8', kitchen: '#f2c48d', living: '#e9d48a', dining: '#e7b7a0', puja: '#f0a0a0',
+ wash: '#a8d5c2', store: '#bbb', study: '#b8c9a0', passage: '#d9d2c3', balcony: '#b6dfa0', garden: '#7fc97f', open: '#9fd8d0',
+ parking: '#c9c9d6', yard: '#cfe6b8', stair: '#c49a6c', room: '#dcdcdc', duct: '#999', dress: '#e3d2b8' };
+const D = 100 / 72; // page image px per PDF point
+let plan, fi = 0, sel = null, tool = 'select', img = {}, history = [];
+let view = { k: 10, ox: 40, oy: 600 };
+
+// ---------------------------------------------------------------- loading / polling
+async function poll() {
+ const st = await fetch(`/api/jobs/${job}`).then((r) => r.json());
+ $('title').textContent = st.name || 'Review';
+ if (['uploaded', 'detecting'].includes(st.stage)) {
+ $('wmsg').textContent = st.message || 'Reading the drawing…';
+ $('wbar').style.width = (st.progress || 5) + '%';
+ return setTimeout(poll, 700);
+ }
+ if (st.stage === 'failed' && !plan) {
+ $('wmsg').textContent = st.message; $('wmsg').className = 'err'; $('back').hidden = false; return;
+ }
+ if (!plan) await load();
+ buildStatus(st);
+}
+async function load() {
+ plan = await fetch(`/jobs/${job}/plan.json`).then((r) => r.json());
+ $('wait').style.display = 'none';
+ plan.floors.forEach((f, i) => {
+ const b = document.createElement('button');
+ b.textContent = f.name;
+ b.onclick = () => { fi = i; sel = null; fit(); ui(); };
+ $('tabs').appendChild(b);
+ });
+ for (const p of new Set(plan.floors.map((f) => f.page || 1))) {
+ const im = new Image();
+ im.src = `/jobs/${job}/page-${p}.png`;
+ im.onload = draw;
+ img[p] = im;
+ }
+ $('fh').value = plan.floor_height;
+ $('furn').checked = plan.furnish !== false;
+ fit(); ui();
+}
+// playful words while Blender works, with the time left beside them
+const WORDS = ['Raising walls', 'Laying bricks', 'Squaring corners', 'Hanging doors', 'Polishing windows', 'Pouring floors',
+ 'Mixing paint', 'Tiling bathrooms', 'Measuring twice', 'Switching on lamps', 'Chasing shadows', 'Baking sunlight', 'Sweeping up'];
+const FURNISHED = ['Fluffing pillows', 'Arranging furniture', 'Watering plants', 'Making the beds'];
+let fun = null;
+function funWords(on) {
+ $('bfun').hidden = !on;
+ if (on === !!fun) return;
+ if (!on) { clearInterval(fun); fun = null; return; }
+ const words = $('furn').checked ? WORDS.concat(FURNISHED) : WORDS;
+ const next = () => { // never the same word twice in a row
+ let w;
+ do w = words[Math.floor(Math.random() * words.length)] + '…'; while (w === $('bword').textContent);
+ $('bword').textContent = w;
+ };
+ next();
+ fun = setInterval(next, 2800);
+}
+const secs = (s) => (s >= 90 ? `${Math.round(s / 60)} min` : `${s} s`);
+function buildStatus(st) {
+ if (!['queued', 'building', 'done', 'failed'].includes(st.stage)) return;
+ $('buildbox').hidden = false;
+ $('bbar').style.width = (st.progress || 0) + '%';
+ funWords(['queued', 'building'].includes(st.stage));
+ const left = st.stage === 'building' ? st.eta_left : null; // seconds, estimated from earlier builds on this machine
+ $('beta').textContent = left == null ? '' : left > 8 ? `about ${secs(left >= 90 ? left : Math.ceil(left / 5) * 5)} left` : 'almost done';
+ const took = st.stage === 'done' && st.build_seconds ? `built in ${secs(st.build_seconds)}` : '';
+ const step = st.stage === 'building' && !/cooling/.test(st.message) ? '' : st.message; // Blender's step names stay out of sight
+ $('bmsg').textContent = st.stage === 'failed' ? `Failed: ${st.message}` : [step, took].filter(Boolean).join(' · ');
+ $('bmsg').className = st.stage === 'failed' ? 'err' : 'muted';
+ $('open').hidden = st.stage !== 'done';
+ $('open').href = `/web/view.html?job=${job}`;
+ $('build').disabled = ['queued', 'building'].includes(st.stage);
+ if (['queued', 'building'].includes(st.stage)) setTimeout(() => fetch(`/api/jobs/${job}`).then((r) => r.json()).then(buildStatus), 1500);
+}
+
+// ---------------------------------------------------------------- geometry helpers
+const F = () => plan.floors[fi];
+const toC = (x, y) => [view.ox + x * view.k, view.oy - y * view.k];
+const toP = (X, Y) => [(X - view.ox) / view.k, (view.oy - Y) / view.k];
+const inR = (r, x, y, m = 0) => x >= r[0] - m && x <= r[1] + m && y >= r[2] - m && y <= r[3] + m;
+function fit() {
+ const f = F(), [w, h] = f.size, W = cv.clientWidth, H = cv.clientHeight;
+ view.k = Math.min((W - 60) / w, (H - 60) / h);
+ view.ox = (W - w * view.k) / 2;
+ view.oy = (H + h * view.k) / 2;
+ draw();
+}
+function wallT() {
+ const t = F().walls.map((w) => Math.min(w[1] - w[0], w[3] - w[2])).sort((a, b) => a - b);
+ return t[Math.floor(t.length / 2)] || 0.375;
+}
+function snapshot() { history.push(JSON.stringify(plan)); if (history.length > 50) history.shift(); }
+
+// ---------------------------------------------------------------- drawing
+function rectC(r) { const [a, b] = toC(r[0], r[3]), [c, d] = toC(r[1], r[2]); return [a, b, c - a, d - b]; }
+// floor j's plan coordinates -> the current floor's (both are measured from their own lower-left corner)
+function offsetOf(j) {
+ const s = plan.scale_pt_per_ft, a = F().origin_pt, b = plan.floors[j].origin_pt;
+ return [(b[0] - a[0]) / s, (a[1] - b[1]) / s];
+}
+function drawFloor(f, dx, dy, active) {
+ const fade = active ? 1 : 0.4, mv = (r) => [r[0] + dx, r[1] + dx, r[2] + dy, r[3] + dy];
+ const isSel = (kind, i) => active && sel?.kind === kind && sel.i === i;
+ f.rooms.forEach((z, i) => {
+ g.fillStyle = ZCOL[z.type] || '#ddd';
+ g.globalAlpha = (isSel('room', i) ? 0.75 : 0.38) * fade;
+ z.rects.forEach((r) => g.fillRect(...rectC(mv(r))));
+ });
+ g.globalAlpha = fade;
+ for (const st of f.stairs || []) { g.fillStyle = 'rgba(138,90,43,.55)'; g.fillRect(...rectC(mv(st.rect))); }
+ f.walls.forEach((w, i) => {
+ g.fillStyle = isSel('wall', i) ? '#000' : w[4] ? '#d81bd8' : '#e53935';
+ g.fillRect(...rectC(mv(w)));
+ });
+ const OC = { door: '#2e9d3a', window: '#1e6fe0', opening: '#f2b400' };
+ f.openings.forEach((o, i) => {
+ g.fillStyle = isSel('opening', i) ? '#000' : OC[o.type];
+ const [x, y, w, h] = rectC(mv(o.rect));
+ g.fillRect(x - 1, y - 1, w + 2, h + 2);
+ });
+ g.font = '12px system-ui'; g.textAlign = 'center';
+ f.rooms.forEach((z) => {
+ const r = mv(z.rects.reduce((a, b) => ((b[1] - b[0]) * (b[3] - b[2]) > (a[1] - a[0]) * (a[3] - a[2]) ? b : a)));
+ if ((r[1] - r[0]) * view.k < 30) return;
+ const [x, y] = toC((r[0] + r[1]) / 2, (r[2] + r[3]) / 2);
+ g.fillStyle = '#111';
+ g.fillText(z.type, x, y);
+ });
+ g.globalAlpha = 1;
+}
+function draw() {
+ if (!plan) return;
+ const dpr = devicePixelRatio || 1;
+ cv.width = cv.clientWidth * dpr; cv.height = cv.clientHeight * dpr;
+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
+ g.clearRect(0, 0, cv.clientWidth, cv.clientHeight);
+ const f = F(), s = plan.scale_pt_per_ft, im = img[f.page || 1];
+ if (im?.complete) {
+ const sc = view.k / (s * D);
+ g.globalAlpha = 0.45;
+ g.drawImage(im, view.ox - f.origin_pt[0] * view.k / s, view.oy - f.origin_pt[1] * view.k / s, im.width * sc, im.height * sc);
+ g.globalAlpha = 1;
+ }
+ // the other plans on this sheet stay visible (faded); click one to edit it
+ plan.floors.forEach((o, j) => { if (j !== fi && (o.page || 1) === (f.page || 1)) drawFloor(o, ...offsetOf(j), false); });
+ drawFloor(f, 0, 0, true);
+ if (drag?.preview) { g.strokeStyle = '#000'; g.setLineDash([4, 3]); g.strokeRect(...rectC(drag.preview)); g.setLineDash([]); }
+ for (const p of scalePts) { const [x, y] = toC(...p); g.fillStyle = '#b0562b'; g.beginPath(); g.arc(x, y, 5, 0, 7); g.fill(); }
+}
+
+// ---------------------------------------------------------------- side panel
+function ui() {
+ document.querySelectorAll('#tabs button').forEach((b, i) => b.classList.toggle('on', i === fi));
+ const f = F();
+ $('fname').value = f.name;
+ $('scale').textContent = `${plan.floors.length} floor${plan.floors.length > 1 ? 's' : ''} · scale ${plan.scale_source === 'labels'
+ ? 'read from room sizes' : 'GUESSED - use Set scale'}`;
+ const P = $('props');
+ P.innerHTML = '';
+ if (!sel) { P.innerHTML = `<h3>Selection</h3><p class="muted" style="font-size:13px">${f.walls.length} walls, ${f.openings.length} openings, ${f.rooms.length} rooms</p>`; draw(); return; }
+ const h = document.createElement('div');
+ const del = () => { snapshot(); f[{ wall: 'walls', opening: 'openings', stair: 'stairs' }[sel.kind]].splice(sel.i, 1); sel = null; ui(); };
+ if (sel.kind === 'wall') {
+ const w = f.walls[sel.i];
+ h.innerHTML = `<h3>Wall</h3><div class="row"><span>${(Math.max(w[1] - w[0], w[3] - w[2])).toFixed(1)} ft long</span>
+ <select id="wl"><option value="0">Full height</option><option value="1">Low / parapet</option></select></div>`;
+ P.appendChild(h);
+ $('wl').value = w[4]; $('wl').onchange = (e) => { snapshot(); w[4] = +e.target.value; draw(); };
+ } else if (sel.kind === 'opening') {
+ const o = f.openings[sel.i];
+ h.innerHTML = `<h3>Opening</h3><div class="row"><span>${(Math.max(o.rect[1] - o.rect[0], o.rect[3] - o.rect[2])).toFixed(1)} ft wide</span>
+ <select id="ot"><option>door</option><option>window</option><option>opening</option></select></div>`;
+ P.appendChild(h);
+ $('ot').value = o.type; $('ot').onchange = (e) => { snapshot(); o.type = e.target.value; draw(); };
+ } else if (sel.kind === 'room') {
+ const z = f.rooms[sel.i];
+ h.innerHTML = `<h3>Room</h3><div class="row"><span>Type</span><select id="rt">${TYPES.map((t) => `<option>${t}</option>`).join('')}</select></div>
+ <div class="row" style="margin-top:6px"><span>Label</span><input type="text" id="rl" style="width:160px"></div>
+ <p class="muted" style="font-size:12px">${+z.area} sq ft. Furniture follows the type.</p>`;
+ P.appendChild(h);
+ $('rt').value = z.type; $('rt').onchange = (e) => { snapshot(); z.type = e.target.value; draw(); };
+ $('rl').value = z.label || ''; $('rl').oninput = (e) => { z.label = e.target.value; };
+ } else if (sel.kind === 'stair') {
+ h.innerHTML = '<h3>Stair flight</h3>';
+ P.appendChild(h);
+ }
+ if (sel.kind !== 'room') {
+ const b = document.createElement('button');
+ b.className = 'btn ghost'; b.textContent = 'Delete'; b.style.marginTop = '8px'; b.onclick = del;
+ P.appendChild(b);
+ }
+ draw();
+}
+$('fname').oninput = (e) => { F().name = e.target.value; document.querySelectorAll('#tabs button')[fi].textContent = e.target.value; };
+$('fh').onchange = (e) => { plan.floor_height = Math.max(8, Math.min(14, +e.target.value || 10)); };
+
+// ---------------------------------------------------------------- tools
+const HINT = {
+ select: 'Click a wall, opening or room to edit it, or another floor plan to switch to it. Drag to pan, scroll to zoom.',
+ wall: 'Drag along the line of the new wall.',
+ door: 'Click on a wall where the door should be (3 ft wide).',
+ window: 'Click on a wall where the window should be (4 ft wide).',
+ scale: 'Click two points a known distance apart, then type that distance.',
+};
+let scalePts = [];
+document.querySelectorAll('#tools button[data-t]').forEach((b) => b.onclick = () => {
+ tool = b.dataset.t; scalePts = [];
+ document.querySelectorAll('#tools button[data-t]').forEach((x) => x.classList.toggle('on', x === b));
+ $('hint').textContent = HINT[tool];
+ draw();
+});
+$('undo').onclick = () => { if (history.length) { plan = JSON.parse(history.pop()); sel = null; ui(); } };
+addEventListener('keydown', (e) => {
+ if (e.target.tagName === 'INPUT') return;
+ if ((e.key === 'Delete' || e.key === 'Backspace') && sel && sel.kind !== 'room') {
+ snapshot(); F()[{ wall: 'walls', opening: 'openings', stair: 'stairs' }[sel.kind]].splice(sel.i, 1); sel = null; ui();
+ }
+ if (e.key === 'z' && (e.ctrlKey || e.metaKey)) $('undo').onclick();
+});
+
+function pick(x, y) {
+ const f = F(), m = 4 / view.k;
+ let i = f.openings.findIndex((o) => inR(o.rect, x, y, m));
+ if (i >= 0) return { kind: 'opening', i };
+ i = f.walls.findIndex((w) => inR(w, x, y, m));
+ if (i >= 0) return { kind: 'wall', i };
+ i = (f.stairs || []).findIndex((s) => inR(s.rect, x, y));
+ if (i >= 0) return { kind: 'stair', i };
+ i = f.rooms.findIndex((z) => z.rects.some((r) => inR(r, x, y)));
+ if (i >= 0) return { kind: 'room', i };
+ return null;
+}
+function parseFeet(s) {
+ const m = /^\s*(\d+(?:\.\d+)?)\s*'?\s*(?:-?\s*(\d+(?:\.\d+)?)\s*"?)?\s*$/.exec(s || '');
+ return m ? +m[1] + (m[2] ? +m[2] / 12 : 0) : NaN;
+}
+function rescale(k) {
+ snapshot();
+ const R = (r) => { for (let i = 0; i < 4; i++) r[i] *= k; };
+ for (const f of plan.floors) {
+ f.walls.forEach(R); f.openings.forEach((o) => { R(o.rect); if (o.hinge) o.hinge = o.hinge.map((v) => v * k); });
+ f.rooms.forEach((z) => { z.rects.forEach(R); z.area = +(z.area * k * k).toFixed(1); });
+ (f.stairs || []).forEach((s) => { R(s.rect); s.words = s.words.map(([t, x, y]) => [t, x * k, y * k]); });
+ (f.labels || []).forEach((l) => { l.at = l.at.map((v) => v * k); });
+ f.size = f.size.map((v) => v * k);
+ }
+ plan.scale_pt_per_ft /= k;
+ plan.scale_source = 'user';
+}
+
+let drag = null;
+cv.addEventListener('pointerdown', (e) => {
+ cv.setPointerCapture(e.pointerId);
+ const [x, y] = toP(e.offsetX, e.offsetY);
+ drag = { X: e.offsetX, Y: e.offsetY, x, y, moved: false };
+});
+cv.addEventListener('pointermove', (e) => {
+ if (!drag) return;
+ const dx = e.offsetX - drag.X, dy = e.offsetY - drag.Y;
+ if (Math.hypot(dx, dy) > 4) drag.moved = true;
+ if (tool === 'select' && drag.moved) { view.ox += e.movementX; view.oy += e.movementY; draw(); }
+ if (tool === 'wall' && drag.moved) {
+ const [x, y] = toP(e.offsetX, e.offsetY), t = wallT() / 2;
+ drag.preview = Math.abs(x - drag.x) > Math.abs(y - drag.y)
+ ? [Math.min(x, drag.x), Math.max(x, drag.x), drag.y - t, drag.y + t]
+ : [drag.x - t, drag.x + t, Math.min(y, drag.y), Math.max(y, drag.y)];
+ draw();
+ }
+});
+cv.addEventListener('pointerup', (e) => {
+ const d = drag; drag = null;
+ if (!d) return;
+ const f = F(), [x, y] = toP(e.offsetX, e.offsetY);
+ if (tool === 'select' && !d.moved) {
+ sel = pick(x, y);
+ const j = sel ? -1 : plan.floors.findIndex((o, j) => { // clicked on another plan of the sheet: edit that one
+ if (j === fi || (o.page || 1) !== (f.page || 1)) return false;
+ const [dx, dy] = offsetOf(j);
+ return x >= dx && x <= dx + o.size[0] && y >= dy && y <= dy + o.size[1];
+ });
+ if (j >= 0) { const [dx, dy] = offsetOf(j); fi = j; view.ox += dx * view.k; view.oy -= dy * view.k; }
+ ui(); draw();
+ }
+ else if (tool === 'wall' && d.preview) { snapshot(); f.walls.push([...d.preview.map((v) => +v.toFixed(3)), 0]); draw(); }
+ else if ((tool === 'door' || tool === 'window') && !d.moved) {
+ const w = f.walls.find((q) => inR(q, x, y, 6 / view.k));
+ if (!w) { $('hint').textContent = 'Click exactly on a wall.'; return; }
+ const half = tool === 'door' ? 1.5 : 2, horiz = w[1] - w[0] >= w[3] - w[2];
+ snapshot();
+ f.openings.push({ type: tool, axis: horiz ? 'x' : 'y',
+ rect: horiz ? [x - half, x + half, w[2], w[3]] : [w[0], w[1], y - half, y + half] });
+ draw();
+ } else if (tool === 'scale' && !d.moved) {
+ scalePts.push([x, y]); draw();
+ if (scalePts.length === 2) {
+ const meas = Math.hypot(scalePts[1][0] - scalePts[0][0], scalePts[1][1] - scalePts[0][1]);
+ const real = parseFeet(prompt(`Measured ${meas.toFixed(2)} ft on the drawing. Real distance (e.g. 12'6")?`, meas.toFixed(1)));
+ scalePts = [];
+ if (real > 0 && meas > 0) { rescale(real / meas); fit(); ui(); } else draw();
+ }
+ }
+});
+cv.addEventListener('wheel', (e) => {
+ e.preventDefault();
+ const z = Math.exp(-e.deltaY * 0.0015);
+ view.ox = e.offsetX - (e.offsetX - view.ox) * z;
+ view.oy = e.offsetY - (e.offsetY - view.oy) * z;
+ view.k *= z;
+ draw();
+}, { passive: false });
+addEventListener('resize', draw);
+
+$('build').onclick = async () => {
+ $('build').disabled = true;
+ plan.furnish = $('furn').checked;
+ let r = await fetch(`/api/jobs/${job}/plan`, { method: 'POST', body: JSON.stringify(plan) });
+ if (r.ok) r = await fetch(`/api/jobs/${job}/build`, { method: 'POST', body: JSON.stringify({ quality: $('quality').value }) });
+ const j = await r.json();
+ if (!r.ok) { alert(j.error); $('build').disabled = false; return; }
+ buildStatus({ stage: 'queued', progress: 0, message: 'Queued' });
+};
+poll();
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..8a54ab7
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,153 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>PlanTo3D</title>
+<link rel="stylesheet" href="/web/style.css?v=2">
+</head>
+<body class="home">
+<pre id="ascii" aria-hidden="true"></pre>
+<main class="wrap">
+ <p class="brand">PlanTo3D</p>
+ <h1>Floor plan in. Walkable 3D house out.</h1>
+
+ <label class="drop" id="drop">
+ <input type="file" id="file" class="sr" accept="application/pdf,.pdf">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5M4 16v2.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V16"/></svg>
+ <b>Drop your plan PDF</b>
+ <span>or click to choose · CAD-exported PDF</span>
+ </label>
+ <p id="msg" role="status"></p>
+
+ <p class="steps" id="steps">Detect → Review → Build → Walk</p>
+ <section class="setup" id="setup" hidden>
+ <h2>Finish the setup</h2>
+ <ul id="checks"></ul>
+ <button class="btn" id="getmat" hidden>Download materials</button>
+ <p class="muted" id="matmsg"></p>
+ </section>
+
+ <section class="recent" id="recent" hidden>
+ <h2>Recent plans</h2>
+ <div class="jobs" id="jobs"></div>
+ <button class="more" id="more" hidden></button>
+ </section>
+</main>
+<script>
+const $ = (id) => document.getElementById(id);
+const el = (tag, cls, text) => { const e = document.createElement(tag); e.className = cls; e.textContent = text; return e; };
+const drop = $('drop');
+async function upload(f) {
+ if (!f) return;
+ $('msg').textContent = `Uploading ${f.name}…`;
+ $('msg').className = '';
+ drop.classList.add('busy');
+ try {
+ const r = await fetch('/api/upload', { method: 'POST', body: f, headers: { 'X-Filename': encodeURIComponent(f.name) } });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error);
+ location.href = `/web/edit.html?job=${j.id}`;
+ } catch (e) {
+ $('msg').textContent = e.message || 'Upload failed. Is the server still running?';
+ $('msg').className = 'err';
+ drop.classList.remove('busy');
+ $('file').value = '';
+ }
+}
+$('file').onchange = (e) => upload(e.target.files[0]);
+['dragenter', 'dragover'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('over'); }));
+['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('over'); }));
+drop.addEventListener('drop', (e) => upload(e.dataTransfer.files[0]));
+
+// ---- system check: plans are accepted only when Blender, the PDF tools, the viewer and the materials are in place
+const FIX = {
+ blender: (c) => (c.version ? `Blender ${c.version} found, but 4.2 or newer is needed.` : 'Blender 4.2 or newer was not found. Install it from blender.org (or: snap install blender --classic), then restart the server.'),
+ pdf_tools: () => 'The PDF tools were not found. Install poppler (apt install poppler-utils, or brew install poppler).',
+ viewer: () => 'The 3D viewer library is missing. Run "npm install" in the project folder.',
+ materials: () => 'Textures and models are not downloaded yet (about 60 MB, free CC0 files from Poly Haven).',
+};
+async function checkSystem() {
+ const s = await fetch('/api/system').then((r) => r.json()), m = s.materials;
+ drop.classList.toggle('busy', !s.ready);
+ $('file').disabled = !s.ready;
+ $('setup').hidden = s.ready;
+ $('steps').textContent = s.ready ? `Detect → Review → Build → Walk · Blender ${s.blender.version} ready` : '';
+ $('checks').replaceChildren(...Object.keys(FIX).filter((k) => !s[k].ok).map((k) => el('li', '', FIX[k](s[k]))));
+ $('getmat').hidden = m.ok || m.running;
+ $('matmsg').textContent = m.running ? `Downloading… ${m.done} of ${m.total || '?'}`
+ : m.failed.length && !m.ok ? `Could not download ${m.failed.length} file${m.failed.length > 1 ? 's' : ''}. Check the connection and try again.` : '';
+ if (m.running) setTimeout(checkSystem, 1000);
+}
+$('getmat').onclick = async () => { $('getmat').hidden = true; await fetch('/api/materials', { method: 'POST' }); checkSystem(); };
+
+// ---- background: a slow field of ASCII characters (one static frame if the system asks for reduced motion)
+const pre = $('ascii'), RAMP = ' ..::--==++**##';
+let cols = 0, rows = 0, last = 0;
+function grid() {
+ const probe = document.createElement('span');
+ probe.textContent = 'M'.repeat(50);
+ pre.textContent = '';
+ pre.append(probe);
+ const cw = probe.getBoundingClientRect().width / 50;
+ cols = Math.ceil(innerWidth / cw) + 1;
+ rows = Math.ceil(innerHeight / parseFloat(getComputedStyle(pre).lineHeight)) + 1;
+}
+function frame(ms) {
+ const t = ms / 1000, cx = cols / 2, cy = rows / 2, out = [];
+ for (let y = 0; y < rows; y++) {
+ let line = '';
+ const yy = y * 1.9; // characters are about 1.9 times taller than wide
+ for (let x = 0; x < cols; x++) {
+ const v = Math.sin(x * 0.11 + t * 0.6) + Math.sin(yy * 0.1 - t * 0.5) + Math.sin((x + yy) * 0.06 + t * 0.4)
+ + Math.sin(Math.hypot(x - cx, yy - cy * 1.9) * 0.09 - t * 0.7);
+ line += RAMP[Math.floor((v + 4) / 8.001 * RAMP.length)];
+ }
+ out.push(line);
+ }
+ pre.textContent = out.join('\n');
+}
+function loop(ms) {
+ if (ms - last >= 90) { last = ms; frame(ms); } // about 11 frames a second is plenty for text
+ requestAnimationFrame(loop);
+}
+grid();
+frame(0);
+if (!matchMedia('(prefers-reduced-motion: reduce)').matches) requestAnimationFrame(loop);
+addEventListener('resize', () => { grid(); frame(last); });
+
+const STAGE = { done: ['Ready', 'ok'], failed: ['Failed', 'bad'], detected: ['Needs review', ''], building: ['Building…', ''],
+ queued: ['Queued', ''], detecting: ['Reading…', ''], uploaded: ['Reading…', ''] };
+const rtf = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
+function ago(t) { // seconds since 1970 -> "3 hours ago"; hand-made jobs have no time
+ if (!t) return '';
+ const s = t - Date.now() / 1000;
+ if (-s > 7 * 86400) return new Date(t * 1000).toLocaleDateString();
+ for (const [unit, n] of [['day', 86400], ['hour', 3600], ['minute', 60]]) if (-s >= n) return rtf.format(Math.round(s / n), unit);
+ return 'just now';
+}
+checkSystem();
+fetch('/api/jobs').then((r) => r.json()).then((jobs) => {
+ if (!jobs.length) return;
+ $('recent').hidden = false;
+ for (const j of jobs) {
+ const done = j.stage === 'done', row = el('div', 'job', '');
+ const a = el('a', 'main', '');
+ a.href = done ? `/web/view.html?job=${j.id}` : `/web/edit.html?job=${j.id}`;
+ const n = j.floors?.length;
+ a.append(el('span', 'name', j.name || j.id), el('span', 'sub', [n && `${n} floor${n > 1 ? 's' : ''}`, ago(j.updated)].filter(Boolean).join(' · ')));
+ const [label, cls] = STAGE[j.stage] || [j.stage, ''];
+ row.append(a, el('span', `chip ${cls}`, label));
+ if (done) { const e = el('a', 'edit', 'Edit'); e.href = `/web/edit.html?job=${j.id}`; row.append(e); }
+ $('jobs').append(row);
+ }
+ if (jobs.length > 5) {
+ $('more').hidden = false;
+ $('more').textContent = `Show all ${jobs.length}`;
+ $('more').onclick = () => { $('more').textContent = $('jobs').classList.toggle('all') ? 'Show fewer' : `Show all ${jobs.length}`; };
+ }
+});
+</script>
+</body>
+</html>
diff --git a/web/package.json b/web/package.json
new file mode 100644
index 0000000..089153b
--- /dev/null
+++ b/web/package.json
@@ -0,0 +1 @@
+{"type":"module"}
diff --git a/web/style.css b/web/style.css
new file mode 100644
index 0000000..62ad890
--- /dev/null
+++ b/web/style.css
@@ -0,0 +1,61 @@
+:root {
+ --bg: #f4f1ea; --panel: #ffffff; --ink: #1f2326; --muted: #6b7076; --line: #ddd6c8; --accent: #b0562b; --accent-ink: #fff;
+ --ok: #2f7d4a; --bad: #b3261e;
+}
+@media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) { --bg: #16181b; --panel: #1f2226; --ink: #ecebe7; --muted: #9aa0a6; --line: #34383d; --accent: #e07a48;
+ --ok: #6cc08a; --bad: #f28b82; }
+}
+* { box-sizing: border-box; }
+body { margin: 0; font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; background: var(--bg); color: var(--ink); }
+a { color: var(--accent); }
+button, select, input { font: inherit; }
+.btn { background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 8px; padding: 9px 16px; cursor: pointer; font-weight: 600; }
+.btn.ghost { background: transparent; color: var(--ink); border: 1px solid var(--line); font-weight: 500; }
+.btn:disabled { opacity: .5; cursor: default; }
+h1 { font-size: 28px; margin: 0 0 6px; }
+.muted { color: var(--muted); }
+/* ---- home page */
+.wrap { max-width: 720px; margin: 0 auto; padding: 56px 20px 64px; }
+.brand { font-weight: 700; letter-spacing: .02em; color: var(--accent); margin: 0 0 28px; }
+.home h1 { font-size: clamp(28px, 5vw, 40px); line-height: 1.15; letter-spacing: -.01em; margin: 0; text-wrap: balance; }
+#ascii { position: fixed; inset: 0; z-index: -1; margin: 0; overflow: hidden; pointer-events: none; user-select: none; white-space: pre;
+ font: 14px/16px ui-monospace, "DejaVu Sans Mono", Menlo, Consolas, monospace; color: var(--accent); opacity: .38;
+ /* dimmer behind the page's centre column so the text stays easy to read */
+ mask-image: linear-gradient(90deg, #000 0, #000 calc(50% - 440px), rgba(0, 0, 0, .3) calc(50% - 340px), rgba(0, 0, 0, .3) calc(50% + 340px), #000 calc(50% + 440px), #000 100%); }
+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
+.drop { display: block; border: 2px dashed var(--line); border-radius: 16px; padding: 44px 20px; text-align: center; background: var(--panel);
+ margin: 32px 0 10px; cursor: pointer; transition: border-color .15s, background .15s; }
+.drop:hover, .drop.over, .drop:focus-within { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 6%, var(--panel)); }
+.drop svg { width: 40px; height: 40px; color: var(--accent); display: block; margin: 0 auto 12px; }
+.drop b { font-size: 18px; display: block; }
+.drop span { color: var(--muted); font-size: 14px; }
+.drop.busy { pointer-events: none; opacity: .7; }
+#msg { min-height: 22px; margin: 0; font-size: 14px; text-align: center; }
+.steps { text-align: center; color: var(--muted); font-size: 13px; letter-spacing: .04em; margin: 14px 0 0; }
+.setup { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px 18px; margin-top: 8px; }
+.setup h2 { font-size: 16px; margin: 0 0 8px; }
+.setup ul { margin: 0 0 12px; padding-left: 18px; }
+.setup li { margin: 4px 0; }
+.setup .muted { margin: 8px 0 0; font-size: 14px; }
+.recent { margin-top: 48px; }
+.recent h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 0 0 10px; }
+.jobs { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
+.job { display: flex; align-items: center; gap: 12px; padding: 0 14px; border-top: 1px solid var(--line); }
+.job:first-child { border-top: 0; }
+.jobs:not(.all) .job:nth-child(n+6) { display: none; }
+.job .main { flex: 1; min-width: 0; padding: 11px 0; text-decoration: none; color: var(--ink); }
+.job .main:hover .name { color: var(--accent); }
+.job .name { display: block; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.job .sub { display: block; font-size: 13px; color: var(--muted); }
+.job .edit { font-size: 13px; white-space: nowrap; }
+.chip { font-size: 12px; font-weight: 600; padding: 2px 9px; border-radius: 999px; white-space: nowrap; color: var(--muted);
+ background: color-mix(in srgb, var(--muted) 14%, transparent); }
+.chip.ok { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }
+.chip.bad { color: var(--bad); background: color-mix(in srgb, var(--bad) 12%, transparent); }
+.more { margin-top: 10px; background: none; border: 0; color: var(--accent); cursor: pointer; padding: 4px 0; font-size: 14px; }
+.empty { padding: 16px 14px; color: var(--muted); font-size: 14px; }
+@media (max-width: 560px) { .wrap { padding-top: 32px; } }
+.bar { height: 8px; background: var(--line); border-radius: 4px; overflow: hidden; }
+.bar > i { display: block; height: 100%; background: var(--accent); width: 0; transition: width .4s; }
+.err { color: var(--bad); }
diff --git a/web/view.html b/web/view.html
new file mode 100644
index 0000000..084e011
--- /dev/null
+++ b/web/view.html
@@ -0,0 +1,54 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
+<title>3D Walkthrough</title>
+<link rel="stylesheet" href="/web/style.css?v=2">
+<style>
+ html, body { margin: 0; height: 100%; overflow: hidden; background: #111; touch-action: none; }
+ canvas { display: block; }
+ #overlay { position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;
+ background: rgba(10, 12, 16, .7); color: #f2efe8; text-align: center; cursor: pointer; padding: 16px; }
+ #overlay h1 { font-weight: 600; margin: 0 0 8px; font-size: 24px; }
+ #overlay p { margin: 4px; opacity: .85; }
+ kbd { background: #2b2f36; border-radius: 4px; padding: 1px 7px; font-family: inherit; }
+ #room { position: fixed; top: 14px; left: 50%; transform: translateX(-50%); color: #fff; background: rgba(0,0,0,.45);
+ padding: 6px 14px; border-radius: 18px; font-size: 14px; pointer-events: none; white-space: nowrap; }
+ #room:empty { display: none; }
+ #cross { position: fixed; left: 50%; top: 50%; width: 6px; height: 6px; margin: -3px; border-radius: 50%;
+ background: rgba(255,255,255,.7); pointer-events: none; }
+ #bar { position: fixed; bottom: 12px; left: 12px; right: 12px; display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
+ #bar button { background: rgba(20,22,26,.75); color: #eee; border: 1px solid #444; border-radius: 6px; padding: 7px 11px; font-size: 13px; }
+ #bar button.on { background: #e8e1d3; color: #111; }
+ #bar button.live { background: #b3261e; border-color: #b3261e; color: #fff; }
+ #fps { color: #bbb; font-size: 12px; margin-left: auto; background: rgba(0,0,0,.4); padding: 4px 8px; border-radius: 6px; }
+ #floors { display: contents; }
+ #map { position: fixed; right: 12px; bottom: 58px; width: 220px; height: 220px; border-radius: 12px; cursor: pointer;
+ background: rgba(14, 16, 20, .78); border: 1px solid rgba(255, 255, 255, .18); }
+ #map.big { right: 50%; bottom: 50%; transform: translate(50%, 50%); width: min(88vw, 88vh, 900px); height: min(88vw, 88vh, 900px);
+ background: rgba(14, 16, 20, .92); }
+ .mapbig #room, .mapbig #cross { visibility: hidden; } /* the large map shows the room itself */
+ @media (max-width: 600px) { #map:not(.big) { width: 130px; height: 130px; bottom: 100px; } }
+ @media (pointer: coarse) { .desk { display: none; } }
+ @media (pointer: fine) { .touch { display: none; } }
+</style>
+<script type="importmap">
+{ "imports": { "three": "/three/build/three.module.js", "three/addons/": "/three/examples/jsm/" } }
+</script>
+</head>
+<body>
+<canvas id="map" title="Map: click or press M to enlarge"></canvas>
+<div id="overlay">
+ <h1>3D walkthrough</h1>
+ <p id="status">Loading…</p>
+ <p class="desk"><kbd>W A S D</kbd> walk · <kbd>Mouse</kbd> look · <kbd>Shift</kbd> run · <kbd>T</kbd> top view · <kbd>Esc</kbd> pause</p>
+ <p class="desk"><kbd>P</kbd> screenshot · <kbd>R</kbd> start / stop recording · <kbd>M</kbd> map</p>
+ <p class="touch">Left thumb: move · right thumb: look</p>
+</div>
+<div id="room"></div>
+<div id="cross"></div>
+<div id="bar"><button id="topbtn">Top view</button><span id="floors"></span><button id="shot" title="Save a picture of this view (P)">Screenshot</button><button id="rec" title="Record a video of your walk (R)">Record</button><button id="blend" title="Download this house as a Blender file (.zip)">Blender file</button><a href="/" id="newplan" style="color:#ccc;font-size:13px">New plan</a><span id="fps"></span></div>
+<script type="module" src="/web/view.js"></script>
+</body>
+</html>
diff --git a/web/view.js b/web/view.js
new file mode 100644
index 0000000..57f96d3
--- /dev/null
+++ b/web/view.js
@@ -0,0 +1,371 @@
+// Walkthrough of a generated house: baked lighting (light maps) on unlit materials, so it runs on any GPU.
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import * as walk from '/web/walk.js';
+
+const $ = (id) => document.getElementById(id);
+const job = new URLSearchParams(location.search).get('job');
+const base = `/jobs/${job}/`;
+const WALK = 1.5, RUN = 3.0;
+
+const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
+renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5));
+renderer.setSize(innerWidth, innerHeight);
+renderer.toneMapping = THREE.AgXToneMapping;
+renderer.toneMappingExposure = 1.0;
+document.body.appendChild(renderer.domElement);
+
+const scene = new THREE.Scene();
+scene.background = new THREE.Color(0xbfd6ea);
+scene.fog = new THREE.Fog(0xbfd6ea, 60, 160);
+const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 0.05, 400);
+const env = new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(), 0.04).texture;
+
+const meta = await fetch(base + 'meta.json').then((r) => r.json());
+const draco = new DRACOLoader().setDecoderPath('/three/examples/jsm/libs/draco/');
+const gltf = await new GLTFLoader().setDRACOLoader(draco).loadAsync(base + 'house.glb', (e) => {
+ if (e.total) $('status').textContent = `Loading model… ${Math.round(100 * e.loaded / e.total)}%`;
+});
+const texLoader = new THREE.TextureLoader();
+const lightmaps = {};
+await Promise.all(Object.entries(meta.lightmaps || {}).map(async ([name, file]) => {
+ const t = await texLoader.loadAsync(base + file);
+ t.channel = 1; // second UV set (TEXCOORD_1)
+ t.colorSpace = THREE.SRGBColorSpace; // stored sRGB-encoded for precision in the shadows
+ t.flipY = false;
+ lightmaps[name] = t;
+}));
+
+// ---- materials: unlit * baked light; real-time light only for objects without a light map (trees)
+const baked = !!meta.baked;
+if (!baked) {
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x8a7a66, 1.6));
+ const sun = new THREE.DirectionalLight(0xfff1d6, 2.2);
+ sun.position.set(-8, 14, 6);
+ scene.add(sun);
+} else {
+ scene.add(new THREE.HemisphereLight(0xdfefff, 0x6d6450, 1.2));
+ const sun = new THREE.DirectionalLight(0xfff1d6, 1.6);
+ sun.position.set(-8, 14, 6);
+ scene.add(sun);
+}
+const levels = []; // level index -> objects (hidden above the current level in top view)
+gltf.scene.traverse((o) => {
+ if (!o.isMesh) return;
+ let root = o;
+ while (root.parent && root.parent !== gltf.scene) root = root.parent;
+ const lm = lightmaps[root.name] || lightmaps[o.name];
+ const lmax = (meta.lightmap_max || {})[root.name] ?? (meta.lightmap_max || {})[o.name] ?? 1;
+ const conv = (m) => {
+ const emissive = m.emissive && (m.emissive.r + m.emissive.g + m.emissive.b) > 0.01;
+ const opts = { map: m.map, color: m.color, transparent: m.transparent, opacity: m.opacity, side: m.side,
+ alphaTest: m.alphaTest, depthWrite: !m.transparent };
+ if (emissive) return new THREE.MeshBasicMaterial({ color: m.emissive.clone().multiplyScalar(Math.max(1, m.emissiveIntensity || 1)) });
+ if (m.transparent) return new THREE.MeshBasicMaterial({ ...opts, envMap: env, reflectivity: 0.12, combine: THREE.MixOperation });
+ // mirrors are pure metal: the baked (diffuse) light is black there, so show only the reflection
+ if (m.metalness > 0.9 && m.roughness < 0.1) return new THREE.MeshBasicMaterial({ color: 0xe8ecef, envMap: env, reflectivity: 0.9, combine: THREE.MixOperation });
+ if (lm) {
+ const shiny = m.metalness > 0.5 ? 0.55 : m.roughness < 0.25 ? 0.12 : 0;
+ return new THREE.MeshBasicMaterial({ ...opts, lightMap: lm, lightMapIntensity: Math.PI * lmax,
+ envMap: shiny ? env : null, reflectivity: shiny, combine: THREE.MixOperation });
+ }
+ return new THREE.MeshLambertMaterial(opts);
+ };
+ o.material = Array.isArray(o.material) ? o.material.map(conv) : conv(o.material);
+ const m = /^bake_level_(\d+)/.exec(root.name) || /_(\d+)$/.exec(root.name);
+ if (m && /^(bake_level|glass)/.test(root.name)) (levels[+m[1]] ||= []).push(o);
+});
+scene.add(gltf.scene);
+
+// ---- plan (x, y metres, z up) -> three (x, z, -y)
+const W = (x, y, z) => new THREE.Vector3(x, z, -y);
+const floors = meta.floors;
+function roomAt(lv, x, y) {
+ for (const r of floors[lv]?.rooms || []) for (const q of r.rects) if (walk.inRect(q, x, y)) return r.label;
+ return '';
+}
+
+// ---- player
+const p = { ...walk.entrance(meta), z: floors[0].z, yaw: 0, pitch: 0 };
+const keys = {};
+let locked = false, topView = false;
+addEventListener('keydown', (e) => {
+ keys[e.code] = true;
+ if (e.code === 'KeyT') toggleTop();
+ if (e.code === 'KeyP' && !e.repeat) screenshot();
+ if (e.code === 'KeyR' && !e.repeat) toggleRec();
+ if (e.code === 'KeyM' && !e.repeat) toggleMap();
+});
+addEventListener('keyup', (e) => { keys[e.code] = false; });
+const canvas = renderer.domElement;
+$('overlay').addEventListener('click', () => {
+ if (matchMedia('(pointer: coarse)').matches) { $('overlay').style.display = 'none'; return; }
+ canvas.requestPointerLock();
+});
+document.addEventListener('pointerlockchange', () => {
+ locked = document.pointerLockElement === canvas;
+ $('overlay').style.display = locked || topView ? 'none' : 'flex';
+});
+// the browser refused to capture the mouse: show the start screen, whose click captures it
+document.addEventListener('pointerlockerror', () => { if (!topView) $('overlay').style.display = 'flex'; });
+addEventListener('mousemove', (e) => {
+ if (!locked) return;
+ p.yaw -= e.movementX * 0.0022;
+ p.pitch = Math.max(-1.4, Math.min(1.4, p.pitch - e.movementY * 0.0022));
+});
+// touch: left half = move stick, right half = look
+const touch = { move: null, look: null, mx: 0, my: 0 };
+canvas.addEventListener('touchstart', (e) => {
+ for (const t of e.changedTouches) {
+ if (t.clientX < innerWidth / 2 && !touch.move) touch.move = { id: t.identifier, x: t.clientX, y: t.clientY };
+ else if (!touch.look) touch.look = { id: t.identifier, x: t.clientX, y: t.clientY };
+ }
+}, { passive: true });
+canvas.addEventListener('touchmove', (e) => {
+ if (topView) return;
+ for (const t of e.changedTouches) {
+ if (touch.move && t.identifier === touch.move.id) {
+ touch.mx = Math.max(-1, Math.min(1, (t.clientX - touch.move.x) / 60));
+ touch.my = Math.max(-1, Math.min(1, (t.clientY - touch.move.y) / 60));
+ } else if (touch.look && t.identifier === touch.look.id) {
+ p.yaw -= (t.clientX - touch.look.x) * 0.005;
+ p.pitch = Math.max(-1.4, Math.min(1.4, p.pitch - (t.clientY - touch.look.y) * 0.005));
+ touch.look.x = t.clientX; touch.look.y = t.clientY;
+ }
+ }
+}, { passive: true });
+canvas.addEventListener('touchend', (e) => {
+ for (const t of e.changedTouches) {
+ if (touch.move && t.identifier === touch.move.id) { touch.move = null; touch.mx = touch.my = 0; }
+ if (touch.look && t.identifier === touch.look.id) touch.look = null;
+ }
+});
+
+// ---- top view (dollhouse): storeys above the chosen one are hidden
+const orbit = new OrbitControls(camera, canvas);
+orbit.enabled = false;
+let showLevel = 0;
+function showLevels(n) {
+ showLevel = n;
+ levels.forEach((objs, i) => objs?.forEach((o) => { o.visible = !topView || i <= n; }));
+ document.querySelectorAll('#floors button').forEach((b, i) => b.classList.toggle('on', topView && i === n));
+}
+function toggleTop() {
+ topView = !topView;
+ if (topView) {
+ document.exitPointerLock?.();
+ $('overlay').style.display = 'none';
+ const b = meta.bounds, cx = (b[0] + b[1]) / 2, cy = (b[2] + b[3]) / 2, size = Math.max(b[1] - b[0], b[3] - b[2]);
+ const z0 = floors[walk.levelOf(meta, p.z)].z;
+ orbit.target.copy(W(cx, cy, z0));
+ camera.position.copy(W(cx, cy - size * 0.75, z0 + size * 1.05));
+ orbit.enabled = true;
+ orbit.update();
+ showLevels(walk.levelOf(meta, p.z));
+ } else {
+ orbit.enabled = false;
+ showLevels(levels.length);
+ // back to walking: capture the mouse again, or looking around stays dead with nothing to click
+ if (!matchMedia('(pointer: coarse)').matches) canvas.requestPointerLock()?.catch?.(() => { $('overlay').style.display = 'flex'; });
+ }
+ map.style.display = topView ? 'none' : 'block';
+ $('cross').style.display = topView ? 'none' : 'block';
+ $('topbtn').textContent = topView ? 'Walk' : 'Top view';
+}
+$('topbtn').onclick = toggleTop;
+floors.forEach((f, i) => {
+ const b = document.createElement('button');
+ b.textContent = f.name;
+ b.onclick = () => {
+ if (topView) { showLevels(i); orbit.target.y = f.z; return; }
+ // walk mode: jump to a free spot in the biggest room of that floor
+ const r = (f.rooms.filter((q) => !['open', 'garden', 'yard', 'stair'].includes(q.type))
+ .flatMap((q) => q.rects).sort((a, c) => (c[1] - c[0]) * (c[3] - c[2]) - (a[1] - a[0]) * (a[3] - a[2])))[0];
+ if (r) { p.x = (r[0] + r[1]) / 2; p.y = (r[2] + r[3]) / 2; p.z = f.z; }
+ };
+ $('floors').appendChild(b);
+});
+
+// ---- map (M): the storey you are on from above, with room names, stairs, and where you stand and look
+const map = $('map'), mg = map.getContext('2d');
+const OUTSIDE = new Set(['open', 'garden', 'yard', 'balcony', 'parking']);
+const roomName = (r) => (r.label || r.type).split(/\s+/).filter((w) => !/\d/.test(w)).join(' ').toUpperCase() || r.type.toUpperCase(); // without the size
+let mapBig = false;
+function toggleMap() { mapBig = !mapBig; map.classList.toggle('big', mapBig); document.body.classList.toggle('mapbig', mapBig); }
+map.onclick = toggleMap;
+function drawMap(lv) {
+ const dpr = devicePixelRatio || 1, w = map.clientWidth, h = map.clientHeight;
+ if (map.width !== Math.round(w * dpr) || map.height !== Math.round(h * dpr)) { map.width = Math.round(w * dpr); map.height = Math.round(h * dpr); }
+ mg.setTransform(dpr, 0, 0, dpr, 0, 0);
+ mg.clearRect(0, 0, w, h);
+ const f = floors[lv], pad = mapBig ? 46 : 10, rs = [...f.colliders, ...f.rooms.flatMap((r) => r.rects)];
+ const x0 = Math.min(...rs.map((r) => r[0])), x1 = Math.max(...rs.map((r) => r[1]));
+ const y0 = Math.min(...rs.map((r) => r[2])), y1 = Math.max(...rs.map((r) => r[3]));
+ const k = Math.min((w - 2 * pad) / (x1 - x0), (h - 2 * pad) / (y1 - y0));
+ const X = (x) => (w - (x1 - x0) * k) / 2 + (x - x0) * k, Y = (y) => (h + (y1 - y0) * k) / 2 - (y - y0) * k; // plan +y is up
+ const box = (r) => mg.fillRect(X(r[0]), Y(r[3]), (r[1] - r[0]) * k, (r[3] - r[2]) * k);
+ const here = f.rooms.find((r) => r.rects.some((q) => walk.inRect(q, p.x, p.y)));
+ for (const r of f.rooms) {
+ mg.fillStyle = r === here ? 'rgba(224, 122, 72, .5)' : OUTSIDE.has(r.type) ? 'rgba(120, 170, 110, .22)' : 'rgba(255, 255, 255, .13)';
+ r.rects.forEach(box);
+ }
+ mg.fillStyle = 'rgba(196, 154, 108, .85)';
+ (f.stairs || []).forEach((s) => box(s.rect));
+ mg.fillStyle = 'rgba(255, 255, 255, .85)';
+ f.colliders.forEach(box);
+ const size = mapBig ? 13 : 9;
+ mg.font = `600 ${size}px system-ui, sans-serif`;
+ mg.textAlign = 'center';
+ mg.textBaseline = 'middle';
+ mg.fillStyle = '#fff';
+ for (const r of f.rooms) { // a name is drawn only where it fits inside its room
+ const q = r.rects.reduce((a, b) => ((b[1] - b[0]) * (b[3] - b[2]) > (a[1] - a[0]) * (a[3] - a[2]) ? b : a));
+ const name = roomName(r);
+ if (mg.measureText(name).width < (q[1] - q[0]) * k - 2 && size < (q[3] - q[2]) * k - 2) mg.fillText(name, X((q[0] + q[1]) / 2), Y((q[2] + q[3]) / 2));
+ }
+ // you: a view cone and a dot (yaw 0 looks along plan +y, turning left is positive)
+ const px = X(p.x), py = Y(p.y), a = -Math.PI / 2 - p.yaw, len = mapBig ? 70 : 30;
+ const cone = mg.createRadialGradient(px, py, 0, px, py, len);
+ cone.addColorStop(0, 'rgba(255, 220, 190, .75)');
+ cone.addColorStop(1, 'rgba(255, 220, 190, 0)');
+ mg.fillStyle = cone;
+ mg.beginPath(); mg.moveTo(px, py); mg.arc(px, py, len, a - 0.6, a + 0.6); mg.closePath(); mg.fill();
+ mg.fillStyle = '#e07a48'; mg.strokeStyle = '#fff'; mg.lineWidth = 1.5;
+ mg.beginPath(); mg.arc(px, py, mapBig ? 6 : 4, 0, 7); mg.fill(); mg.stroke();
+ if (mapBig) {
+ mg.fillStyle = '#fff';
+ mg.textAlign = 'left';
+ mg.font = '600 15px system-ui, sans-serif';
+ mg.fillText([f.name, here && roomName(here)].filter(Boolean).join(' · '), 18, 22);
+ mg.textAlign = 'right';
+ mg.font = '13px system-ui, sans-serif';
+ mg.fillStyle = 'rgba(255, 255, 255, .6)';
+ mg.fillText('M to close', w - 18, 22);
+ }
+}
+
+// ---- screenshot (P) and video recording (R): the 3D view only, without the buttons and labels
+function save(blob, ext) {
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ const now = new Date(Date.now() - new Date().getTimezoneOffset() * 60000); // local time in the file name
+ a.download = `walkthrough-${now.toISOString().slice(0, 19).replace(/[T:]/g, '-')}.${ext}`;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(a.href), 10000);
+}
+let rec = null;
+function screenshot() {
+ const pr = renderer.getPixelRatio();
+ // about 4K worth of pixels, whatever the window size (not while recording: the video must keep one size)
+ if (!rec) renderer.setPixelRatio(Math.max(pr, Math.sqrt(3840 * 2160 / (innerWidth * innerHeight))));
+ renderer.render(scene, camera); // the picture can only be read right after a render
+ canvas.toBlob((b) => save(b, 'png'), 'image/png');
+ renderer.setPixelRatio(pr);
+}
+const REC_TYPE = window.MediaRecorder && ['video/mp4;codecs=avc1.42E01E', 'video/webm;codecs=vp9', 'video/webm']
+ .find((t) => MediaRecorder.isTypeSupported(t));
+function toggleRec() {
+ if (!REC_TYPE) return;
+ if (rec) return rec.stop();
+ const chunks = [], t0 = performance.now();
+ const label = () => {
+ const s = Math.floor((performance.now() - t0) / 1000);
+ $('rec').textContent = `Stop ${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+ };
+ rec = new MediaRecorder(canvas.captureStream(30), { mimeType: REC_TYPE, videoBitsPerSecond: 12e6 });
+ rec.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); };
+ const tick = setInterval(label, 500);
+ rec.onstop = () => {
+ clearInterval(tick);
+ rec = null;
+ $('rec').textContent = 'Record';
+ $('rec').classList.remove('live');
+ save(new Blob(chunks, { type: REC_TYPE }), REC_TYPE.includes('mp4') ? 'mp4' : 'webm');
+ };
+ rec.start(1000);
+ $('rec').classList.add('live');
+ label();
+}
+$('blend').onclick = async () => { // the server packs the textures into one .blend (a few seconds, once per build)
+ const b = $('blend');
+ b.disabled = true;
+ b.textContent = 'Preparing…';
+ try {
+ const r = await fetch(`/api/jobs/${job}/export`, { method: 'POST' }), j = await r.json();
+ if (!r.ok) throw new Error(j.error);
+ const a = document.createElement('a');
+ a.href = j.url;
+ a.download = 'house-blender.zip';
+ a.click();
+ } catch (e) { alert(e.message || 'Could not prepare the Blender file.'); }
+ b.disabled = false;
+ b.textContent = 'Blender file';
+};
+$('shot').onclick = screenshot;
+$('rec').onclick = toggleRec;
+$('rec').hidden = !REC_TYPE; // this browser cannot record video
+
+// ---- loop
+const clock = new THREE.Clock();
+let frames = 0, fpsT = 0;
+renderer.setAnimationLoop(() => {
+ const raw = clock.getDelta(), dt = Math.min(raw, 0.05);
+ frames++; fpsT += raw;
+ if (fpsT > 0.5) { $('fps').textContent = `${Math.round(frames / fpsT)} fps`; frames = 0; fpsT = 0; }
+ if (!topView) {
+ const sp = (keys.ShiftLeft || keys.ShiftRight ? RUN : WALK) * dt;
+ let f = 0, s = 0;
+ if (keys.KeyW || keys.ArrowUp) f += 1;
+ if (keys.KeyS || keys.ArrowDown) f -= 1;
+ if (keys.KeyD || keys.ArrowRight) s += 1;
+ if (keys.KeyA || keys.ArrowLeft) s -= 1;
+ f -= touch.my; s += touch.mx;
+ if (keys.KeyQ) p.yaw += 1.8 * dt;
+ if (keys.KeyE) p.yaw -= 1.8 * dt;
+ const len = Math.hypot(f, s);
+ if (len > 0.01) {
+ const k = sp / Math.max(1, len);
+ // plan axes: yaw 0 looks along +y (three -z)
+ const dx = (-Math.sin(p.yaw) * f + Math.cos(p.yaw) * s) * k;
+ const dy = (Math.cos(p.yaw) * f + Math.sin(p.yaw) * s) * k;
+ walk.move(meta, p, dx, dy);
+ }
+ camera.position.copy(W(p.x, p.y, p.z + meta.eye));
+ camera.rotation.set(0, 0, 0);
+ camera.rotation.order = 'YXZ';
+ camera.rotation.y = p.yaw;
+ camera.rotation.x = p.pitch;
+ const lv = walk.levelOf(meta, p.z);
+ $('room').textContent = [floors[lv].name, roomAt(lv, p.x, p.y)].filter(Boolean).join(' · ');
+ drawMap(lv);
+ } else orbit.update();
+ renderer.render(scene, camera);
+});
+$('status').textContent = matchMedia('(pointer: coarse)').matches ? 'Tap to start' : 'Click to walk in';
+// ?pose=x,y,level,yawDeg,pitchDeg (metres) and ?top=level : fixed views for previews / tests
+const q = new URLSearchParams(location.search);
+if (q.get('pose')) {
+ const [x, y, lv, yaw, pitch] = q.get('pose').split(',').map(Number);
+ Object.assign(p, { x, y, z: floors[lv || 0].z, yaw: (yaw || 0) * Math.PI / 180, pitch: (pitch || 0) * Math.PI / 180 });
+ $('overlay').style.display = 'none';
+}
+if (q.get('top') !== null) { toggleTop(); showLevels(+q.get('top') || 0); }
+if (q.get('embed') !== null) $('newplan').remove(); // inside another site's page there is no "new plan" to go to
+// recording hook: draw one frame at a pose (metres, radians) and return it as a JPEG data URL
+window.__frame = (x, y, z, yaw, pitch) => {
+ renderer.setAnimationLoop(null);
+ camera.position.copy(W(x, y, z + meta.eye));
+ camera.rotation.order = 'YXZ';
+ camera.rotation.set(pitch, yaw, 0);
+ renderer.render(scene, camera);
+ return renderer.domElement.toDataURL('image/jpeg', 0.92);
+};
+window.__ready = true;
+addEventListener('resize', () => {
+ camera.aspect = innerWidth / innerHeight;
+ camera.updateProjectionMatrix();
+ renderer.setSize(innerWidth, innerHeight);
+});
diff --git a/web/walk.js b/web/walk.js
new file mode 100644
index 0000000..9cd1fe2
--- /dev/null
+++ b/web/walk.js
@@ -0,0 +1,80 @@
+// Walking rules shared by the viewer and its test: plan metres (x right, y forward, z up).
+export const RADIUS = 0.22, STEP = 0.45;
+// a single-storey plan's stairs lead to a floor that is not drawn: keep them closed. With 2+ storeys the
+// top storey's stairs go up to the roof terrace and stay walkable.
+const closed = (meta) => (meta.floors.length === 1 ? 0 : -1);
+export const inRect = (r, x, y, m = 0) => x >= r[0] - m && x <= r[1] + m && y >= r[2] - m && y <= r[3] + m;
+
+/** where a visit starts: the middle of the bottom-most room of the lowest storey (the entrance side of the plan).
+ * Voids and stairs do not count; of rooms equally low, the bigger one wins. Yaw 0 then looks up the plan, into the house. */
+export function entrance(meta) {
+ const area = (q) => (q[1] - q[0]) * (q[3] - q[2]);
+ const rooms = meta.floors[0].rooms.filter((r) => !['open', 'stair', 'duct'].includes(r.type) && r.rects.length)
+ .map((r) => ({ low: Math.min(...r.rects.map((q) => q[2])), big: r.rects.reduce((a, b) => (area(b) > area(a) ? b : a)) }));
+ if (!rooms.length) { const b = meta.bounds; return { x: (b[0] + b[1]) / 2, y: (b[2] + b[3]) / 2 }; }
+ const low = Math.min(...rooms.map((r) => r.low));
+ const q = rooms.filter((r) => r.low < low + 0.3).sort((a, b) => area(b.big) - area(a.big))[0].big;
+ return { x: (q[0] + q[1]) / 2, y: (q[2] + q[3]) / 2 };
+}
+
+export function levelOf(meta, z) {
+ let lv = 0;
+ meta.floors.forEach((f, i) => { if (z >= f.z - 0.3) lv = i; });
+ return lv;
+}
+
+export function blockedAt(meta, lv, x, y) {
+ const f = meta.floors[lv];
+ if (!f) return false;
+ for (const r of f.colliders) {
+ const cx = Math.max(r[0], Math.min(x, r[1])), cy = Math.max(r[2], Math.min(y, r[3]));
+ if ((x - cx) ** 2 + (y - cy) ** 2 < RADIUS * RADIUS) return true;
+ }
+ if (lv === closed(meta))
+ for (const s of f.stairs || []) if (inRect(s.rect, x, y)) return true; // (not where we come up)
+ return false;
+}
+
+/** every walkable height under (x, y): storey floors, the roof, stair flights (a ramp) and landings */
+export function heights(meta, x, y) {
+ const planes = [...meta.floors.map((f) => f.z), meta.roof_z];
+ const out = [];
+ const shut = closed(meta);
+ meta.floors.forEach((f, k) => {
+ if (k === shut) return;
+ for (const s of f.stairs || []) {
+ if (!inRect(s.rect, x, y, 0.05)) continue;
+ planes[k] = planes[k + 1] = null; // steps cover this floor; the slab above has the stairwell hole
+ }
+ });
+ out.push(...planes.filter((z) => z !== null));
+ for (const f of meta.floors.filter((_, k) => k !== shut)) for (const s of f.stairs || []) {
+ if (!inRect(s.rect, x, y, 0.05)) continue;
+ if (s.landing) { out.push(s.z0); continue; }
+ const a = s.axis === 'x' ? x : y;
+ const len = s.axis === 'x' ? s.rect[1] - s.rect[0] : s.rect[3] - s.rect[2];
+ const t = Math.min(1, Math.max(0, (a - s.start) * s.dir / len));
+ out.push(s.z0 + (s.z1 - s.z0) * t);
+ }
+ return out;
+}
+
+/** the height closest to z that is within one step, or null (a drop / wall) */
+export function groundNear(meta, x, y, z) {
+ let best = null;
+ for (const h of heights(meta, x, y)) if (Math.abs(h - z) <= STEP && (best === null || Math.abs(h - z) < Math.abs(best - z))) best = h;
+ return best;
+}
+
+/** move the player p {x, y, z} by (dx, dy), sliding along walls; returns p */
+export function move(meta, p, dx, dy) {
+ for (const [ddx, ddy] of [[dx, 0], [0, dy]]) { // one axis at a time: slide along walls
+ if (!ddx && !ddy) continue;
+ const nx = p.x + ddx, ny = p.y + ddy;
+ const g = groundNear(meta, nx, ny, p.z);
+ if (g === null) continue;
+ if (blockedAt(meta, levelOf(meta, Math.max(g, p.z) - 0.05), nx, ny)) continue;
+ p.x = nx; p.y = ny; p.z = g;
+ }
+ return p;
+}