Skip to content

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

Python

Roof door never over the edge; server answers every request; failed theme pictures logged

23f200563973df49c5ef6c
diff --git a/blender/gen.py b/blender/gen.py
index d79e619..42c95fd 100644
--- a/blender/gen.py
+++ b/blender/gen.py
@@ -740,6 +740,10 @@ if stair_box_prev: # the top storey's stairs reach the roof: a small cabin ove
q = stair_top
end = q["start"] + q["dir"] * ((q["rect"][1] - q["rect"][0]) if q["axis"] == "x" else (q["rect"][3] - q["rect"][2]))
door = (end - 1, end + 1, *q["rect"][2:], -1, 7) if q["axis"] == "x" else (*q["rect"][:2], end - 1, end + 1, -1, 7)
+ ax = 0 if q["axis"] == "x" else 2
+ if not bb[ax] + t < end + q["dir"] * 1.5 < bb[ax + 1] - t: # it would open over the roof's edge: a side door
+ cx = (x0 + x1) / 2
+ door = (cx - 1.5, cx + 1.5, y1 - 1, y1 + 1, -1, 7)
walls_m = subtract_all(walls_m, [door])
roof_block += [b for b in walls_m if b[4] < 1] # (not the lintel over the door)
mesh_from_boxes("mumty", [(*b, "exterior") for b in walls_m] + [(x0 - t, x1 + t, y0 - t, y1 + t, 8, 8.5, "slab")])
diff --git a/server.py b/server.py
index 56dfb17..76583a6 100644
--- a/server.py
+++ b/server.py
@@ -183,10 +183,14 @@ def render_thumbs():
with open(os.path.join(out, "plan.json"), "w") as fh:
json.dump(catalog.preview_plan(tid), fh)
with gpu:
- subprocess.run([BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
- os.path.join(out, "plan.json"), out, "--no-bake"], capture_output=True, timeout=1800)
- subprocess.run([BLENDER, "-b", os.path.join(out, "house.blend"), "-P", os.path.join(HERE, "blender", "thumbs.py"),
- "--", out], capture_output=True, timeout=900)
+ for cmd, t, done in (([BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
+ os.path.join(out, "plan.json"), out, "--no-bake"], 1800, "GEN OK"),
+ ([BLENDER, "-b", os.path.join(out, "house.blend"), "-P", os.path.join(HERE, "blender", "thumbs.py"),
+ "--", out], 900, "THUMBS OK")):
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=t)
+ if done not in r.stdout: # (Blender exits 0 even when the script fails; say why in the server log)
+ print(f"theme pictures for {tid} failed:\n{(r.stdout + r.stderr)[-2000:]}", file=sys.stderr, flush=True)
+ break
if tid not in themes.THEMES and tid not in themes.custom_ids(): # deleted meanwhile
shutil.rmtree(out, ignore_errors=True)
except Exception:
@@ -405,6 +409,24 @@ class H(BaseHTTPRequestHandler):
shutil.copyfileobj(fh, self.wfile)
def do_GET(self):
+ self.guard(self.get)
+
+ def do_DELETE(self):
+ self.guard(self.delete)
+
+ def do_POST(self):
+ self.guard(self.post)
+
+ def guard(self, fn):
+ try:
+ fn()
+ except (ValueError, json.JSONDecodeError) as e:
+ self.send(400, {"error": str(e)})
+ except Exception: # anything else: still answer, so the page can say what failed
+ traceback.print_exc()
+ self.send(500, {"error": "The server could not do that - see its log."})
+
+ def get(self):
u = urlparse(self.path)
p = unquote(u.path)
if p in ("/", "/index.html"):
@@ -454,11 +476,14 @@ class H(BaseHTTPRequestHandler):
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
+ for jid in filter(ID.match, os.listdir(JOBS)):
+ try:
+ st = read_status(jid)
+ except (OSError, ValueError): # deleted (or being deleted) while we list
+ continue
if st:
out.append(dict(id=jid, **{k: st.get(k) for k in ("name", "stage", "updated", "floors")}))
- return self.send(200, out[:30])
+ return self.send(200, sorted(out, key=lambda j: -(j["updated"] or 0))[:30])
self.send(404, {"error": "not found"})
def body(self):
@@ -467,7 +492,7 @@ class H(BaseHTTPRequestHandler):
raise ValueError("file too large (200 MB max)")
return self.rfile.read(n)
- def do_DELETE(self):
+ def delete(self):
p = urlparse(self.path).path
m = re.match(r"^/api/jobs/([a-f0-9]{12})$", p)
if m and os.path.isdir(jdir(m.group(1))):
@@ -492,99 +517,93 @@ class H(BaseHTTPRequestHandler):
return self.send(200, {"ok": True})
self.send(404, {"error": "not found"})
- def do_POST(self):
+ def post(self):
p = urlparse(self.path).path
- try:
- m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})/model/(\w+)$", p)
- if m and m.group(1) in themes.custom_ids() and m.group(2) in themes.SLOTS: # your model for a piece (.glb)
- data = self.body()
- if not data.startswith(b"glTF"):
- return self.send(400, {"error": "Please upload a .glb file (binary glTF)."})
- os.makedirs(os.path.dirname(themes.upload_path(*m.groups())), exist_ok=True)
- with open(themes.upload_path(*m.groups()), "wb") as fh:
- fh.write(data)
- t = json.load(open(os.path.join(themes.DIR, m.group(1) + ".json")))
- t["slots"][m.group(2)] = "upload"
- save_theme(m.group(1), t)
- return self.send(200, {"ok": True})
- m = re.match(r"^/api/themes(?:/([a-z0-9][a-z0-9_-]{0,29}))?$", p)
- if m: # make (no id) or change one of your own themes
- return self.send(200, {"id": save_theme(m.group(1), json.loads(self.body() or b"{}"))})
- if p == "/api/mp4": # a WebM recording in, the same video as MP4 out
- if not shutil.which("ffmpeg"):
- return self.send(501, {"error": "ffmpeg is not installed on the server"})
- r = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", "pipe:0", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",
- "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-movflags", "frag_keyframe+empty_moov", "-f", "mp4", "pipe:1"],
- input=self.body(), capture_output=True, timeout=600)
- if r.returncode or not r.stdout:
- return self.send(500, {"error": "the recording could not be converted"})
- return self.send(200, r.stdout, "video/mp4")
- 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=[])
+ m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})/model/(\w+)$", p)
+ if m and m.group(1) in themes.custom_ids() and m.group(2) in themes.SLOTS: # your model for a piece (.glb)
+ data = self.body()
+ if not data.startswith(b"glTF"):
+ return self.send(400, {"error": "Please upload a .glb file (binary glTF)."})
+ os.makedirs(os.path.dirname(themes.upload_path(*m.groups())), exist_ok=True)
+ with open(themes.upload_path(*m.groups()), "wb") as fh:
+ fh.write(data)
+ t = json.load(open(os.path.join(themes.DIR, m.group(1) + ".json")))
+ t["slots"][m.group(2)] = "upload"
+ save_theme(m.group(1), t)
+ return self.send(200, {"ok": True})
+ m = re.match(r"^/api/themes(?:/([a-z0-9][a-z0-9_-]{0,29}))?$", p)
+ if m: # make (no id) or change one of your own themes
+ return self.send(200, {"id": save_theme(m.group(1), json.loads(self.body() or b"{}"))})
+ if p == "/api/mp4": # a WebM recording in, the same video as MP4 out
+ if not shutil.which("ffmpeg"):
+ return self.send(501, {"error": "ffmpeg is not installed on the server"})
+ r = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", "pipe:0", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",
+ "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-movflags", "frag_keyframe+empty_moov", "-f", "mp4", "pipe:1"],
+ input=self.body(), capture_output=True, timeout=600)
+ if r.returncode or not r.stdout:
+ return self.send(500, {"error": "the recording could not be converted"})
+ return self.send(200, r.stdout, "video/mp4")
+ if p == "/api/materials": # start the Poly Haven download (the home page's button)
+ with lock:
+ start = not assets_job["running"]
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|site)$", 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)})
- if what == "site":
- if (read_status(jid) or {}).get("stage") in BUSY: # half old, half new files: and it would be kept
- return self.send(409, {"error": "this plan is being read or built"})
- return self.send(200, {"url": export_site(jid)})
- req = json.loads(self.body() or b"{}")
- if not isinstance(req, dict):
- raise ValueError("expected a JSON object")
- with lock: # checked and set in one step: two quick clicks must not queue two builds
- if (read_status(jid) or {}).get("stage") in BUSY:
- return self.send(409, {"error": "this plan is being read or built"})
- if what == "plan":
- if not isinstance(req.get("floors"), list) or not req["floors"]:
- return self.send(400, {"error": "invalid plan"})
- # both go to Blender as material names / colours: only values it knows
- rooms = [z for f in req["floors"] if isinstance(f, dict) and isinstance(f.get("rooms"), list)
- for z in f["rooms"] if isinstance(z, dict)]
- if any("floor" in z and z["floor"] not in FINISHES for z in rooms):
- return self.send(400, {"error": "Unknown floor finish."})
- wall = req.get("wall_color")
- if "wall_color" in req and not (isinstance(wall, str) and re.fullmatch(r"#[0-9a-fA-F]{6}", wall)):
- return self.send(400, {"error": "Wall colour must look like #rrggbb."})
- th = req.get("theme")
- if "theme" in req and not (isinstance(th, str) and (th in themes.THEMES or th in themes.custom_ids())):
- return self.send(400, {"error": "Unknown interior theme."})
- check_items(req)
- with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
- json.dump(req, fh)
- return self.send(200, {"ok": True})
- q = req.get("quality") if req.get("quality") 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 Exception: # anything else: still answer, so the page can say what failed
- traceback.print_exc()
- self.send(500, {"error": "The server could not do that - see its log."})
+ 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|site)$", 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)})
+ if what == "site":
+ if (read_status(jid) or {}).get("stage") in BUSY: # half old, half new files: and it would be kept
+ return self.send(409, {"error": "this plan is being read or built"})
+ return self.send(200, {"url": export_site(jid)})
+ req = json.loads(self.body() or b"{}")
+ if not isinstance(req, dict):
+ raise ValueError("expected a JSON object")
+ with lock: # checked and set in one step: two quick clicks must not queue two builds
+ if (read_status(jid) or {}).get("stage") in BUSY:
+ return self.send(409, {"error": "this plan is being read or built"})
+ if what == "plan":
+ if not isinstance(req.get("floors"), list) or not req["floors"]:
+ return self.send(400, {"error": "invalid plan"})
+ # both go to Blender as material names / colours: only values it knows
+ rooms = [z for f in req["floors"] if isinstance(f, dict) and isinstance(f.get("rooms"), list)
+ for z in f["rooms"] if isinstance(z, dict)]
+ if any("floor" in z and z["floor"] not in FINISHES for z in rooms):
+ return self.send(400, {"error": "Unknown floor finish."})
+ wall = req.get("wall_color")
+ if "wall_color" in req and not (isinstance(wall, str) and re.fullmatch(r"#[0-9a-fA-F]{6}", wall)):
+ return self.send(400, {"error": "Wall colour must look like #rrggbb."})
+ th = req.get("theme")
+ if "theme" in req and not (isinstance(th, str) and (th in themes.THEMES or th in themes.custom_ids())):
+ return self.send(400, {"error": "Unknown interior theme."})
+ check_items(req)
+ with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
+ json.dump(req, fh)
+ return self.send(200, {"ok": True})
+ q = req.get("quality") if req.get("quality") 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"})
if __name__ == "__main__":