Single place to convert your 2D floor plans to 3d model (no LLM)
Python
"""A plan's job folder and the work done on it: status, reading the drawing, the build queue (one Blender at a time),
the exports, the furniture list and its checks, and whether this machine is set up to build. No HTTP here: server.py."""
import importlib, json, math, os, posixpath, queue, re, shutil, subprocess, threading, time, traceback, zipfile
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 = os.environ.get("BLENDER") or shutil.which("blender") or "blender" # set BLENDER to its full path if it is not on PATH
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}$")
# raise ENGINE when a change to the build (blender/, furnish.py, themes.py) fixes or changes what a house looks like:
# houses built before it are then marked out of date in the review page and the walkthrough
ENGINE = 2
import catalog, detect, fetch_assets, furnish, themes # noqa: E402
os.makedirs(JOBS, exist_ok=True)
builds = queue.Queue()
lock = threading.RLock() # reentrant: request handlers hold it around status() to check and set a stage in one step
BUSY = ("uploaded", "detecting", "queued", "building")
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, site_lock = threading.Lock(), threading.Lock() # the site zip takes a second: it must not wait for a Blender pack
gpu = threading.Lock() # a house build and the themes' pictures both render on the GPU: one at a time
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"
def three_files():
"""the three.js files the viewer loads: what view.js and walk.js import from three, and what those import in turn"""
def deps(text, here):
for s in re.findall(r"\b(?:from|import)\s*['\"]([^'\"]+)['\"]", text):
if s == "three":
yield "build/three.module.js"
elif s.startswith("three/addons/"):
yield "examples/jsm/" + s[13:]
elif s.startswith(".") and here is not None:
yield posixpath.normpath(posixpath.join(here, s))
todo, seen = [f for w in ("view.js", "walk.js") for f in deps(open(os.path.join(WEB, w)).read(), None)], set()
while todo:
f = todo.pop()
if f not in seen and os.path.isfile(os.path.join(THREE, f)): # (an example in a doc comment may name a file that is not there)
seen.add(f)
todo += deps(open(os.path.join(THREE, f)).read(), posixpath.dirname(f))
# DRACOLoader fetches its decoder at run time (the WebAssembly one, as every browser with import maps has it)
return sorted(seen) + ["examples/jsm/libs/draco/draco_wasm_wrapper.js", "examples/jsm/libs/draco/draco_decoder.wasm"]
def export_site(jid):
"""jobs/<id>/house_site.zip: the walkthrough as a static website for any web host, without this server (made once
per build). Only the house itself leaves the job folder: never the client's PDF, the plan or the logs."""
d = jdir(jid)
glb, out = os.path.join(d, "house.glb"), os.path.join(d, "house_site.zip")
if not os.path.exists(glb):
raise ValueError("build the 3D house first")
srcs = [glb, os.path.join(d, "meta.json")] + [os.path.join(WEB, f) for f in ("view.html", "view.js", "walk.js", "style.css")]
with site_lock:
if not os.path.exists(out) or os.path.getmtime(out) < max(map(os.path.getmtime, srcs)): # a new build or a new viewer
meta = json.load(open(os.path.join(d, "meta.json")))
house = (["meta.json", "house.glb"] + [os.path.basename(f) for f in (meta.get("lightmaps") or {}).values()]
+ [f["file"] for f in (meta.get("finishes") or {}).values()])
# view.html with three.js next to it; view.js finds no ?job= and reads the house from ./house/
page = open(os.path.join(WEB, "view.html")).read().replace('"/three/', '"./three/')
with zipfile.ZipFile(out + ".part", "w", zipfile.ZIP_DEFLATED) as z:
z.writestr("index.html", page)
for f in ("view.js", "walk.js", "style.css"):
z.write(os.path.join(WEB, f), f)
for f in three_files():
z.write(os.path.join(THREE, f), "three/" + f)
for f in house: # already compressed (Draco, WebP)
z.write(os.path.join(d, f), "house/" + f, zipfile.ZIP_STORED)
z.writestr("README.txt", "3D walkthrough - made by PlanTo3D.\n\n"
"Put this folder on any static web host (Netlify, GitHub Pages, your own server) and open index.html.\n"
"To try it on your computer, run a web server in this folder, for example\n"
" python3 -m http.server 8000\n"
"and open http://localhost:8000/ . Opening index.html straight from the disk does not work:\n"
"browsers do not load the viewer's modules from file:// pages.\n\n"
"Viewer: three.js (MIT). Textures and models are CC0, from polyhaven.com.\n")
os.replace(out + ".part", out)
return f"/jobs/{jid}/house_site.zip"
def plan_items(jid):
"""the furniture each floor will get (the review page's own list if it edited that floor, else the rules' choice),
and what can be added, at the sizes of the plan's theme"""
plan = json.load(open(os.path.join(jdir(jid), "plan.json")))
T, cat = themes.load(plan.get("theme")), {}
for fn, (label, w, d, kw) in catalog.CATALOG.items():
m = themes.size(T, fn)
cat[fn] = [themes.label(T, fn), *((m[0], m[1] + (3.2 if fn == "dining_set" else 0)) if m else (w, d)), kw]
for fn in ("armchair", "corner", "bed_end"): # decor of the theme that stands on the floor
if themes.size(T, fn):
cat[fn] = [themes.label(T, fn), *themes.size(T, fn)[:2], {}]
return dict(floors=[furnish.floor_items(plan, f) for f in plan["floors"]], catalog=cat)
# items the browser may send: must match furniture.CALLS (blender/furniture.py runs inside Blender, so it cannot be imported here),
# minus "model", whose argument is an asset file name
ITEM_FNS = set(catalog.CATALOG) | {"shower2", "geyser", "kitchen_run", "chimney", "wall_cab2", "rug", "car",
"outdoor_set", "bathtub", "round_rug", "armchair", "art", "mirror", "decor", "corner", "bed_end"}
WORD = re.compile(r"@?[\w+-]{0,24}") # side names such as "-x", material names, "@style" pieces; nothing that can be a path
def check_items(plan):
"""furniture lists from the browser go to Blender as function arguments: only known items, plain values"""
num = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
plain = lambda v: v is None or isinstance(v, bool) or num(v) or (isinstance(v, str) and WORD.fullmatch(v))
for f in plan["floors"]:
if not isinstance(f, dict) or "items" not in f:
continue
items = f["items"]
if not isinstance(items, list) or len(items) > 400:
raise ValueError("invalid furniture list")
for it in items:
if not (isinstance(it, dict) and isinstance(it.get("fn"), str) and it["fn"] in ITEM_FNS
and isinstance(it.get("args"), list) and len(it["args"]) <= 8 and all(num(v) or isinstance(v, str) and WORD.fullmatch(v) for v in it["args"])
and isinstance(it.get("box"), list) and len(it["box"]) == 4 and all(map(num, it["box"]))
and isinstance(it.get("kw"), dict) and len(it["kw"]) <= 12
and all(WORD.fullmatch(k) and plain(v) for k, v in it["kw"].items())
and isinstance(it.get("solid", True), bool) and isinstance(it.get("room", ""), str)):
raise ValueError("invalid furniture item")
# ------------------------------------------------------------------ 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")
importlib.reload(detect) # pick up detector fixes without restarting the server
plan = detect.detect(pdf)
for k in sorted({f["page"] for f in plan["floors"]}): # 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)
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:
known = isinstance(e, detect.PlanError)
if not known: # a known one is the drawing's fault, already said in plain words
traceback.print_exc()
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 gpu, 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),
engine=ENGINE)
except Exception as e:
traceback.print_exc()
status(jid, stage="failed", message=str(e))
finally:
builds.task_done()