Skip to content

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

Python
4.7 KB
Raw Blame
"""People's own interior themes on disk, the list the Themes page shows, and the pictures of each theme's pieces
(rendered in Blender, one theme at a time, sharing the GPU with house builds)."""
import json, os, re, shutil, subprocess, sys, threading, traceback

import catalog, fetch_assets, themes
from jobs import BLENDER, HERE, gpu, lock, system


THUMBS = os.path.join(fetch_assets.ROOT, "thumbs")          # <theme>/<slot>.png
thumbs_job = dict(running=False, queue=[], tried=set())


def render_thumbs():
    """pictures of each queued theme's pieces as they will be built now: a small house with all of them in a row is
    built without baking, then photographed (a minute or so per theme)"""
    try:
        while True:
            with lock:
                if not thumbs_job["queue"]:
                    thumbs_job["running"] = False
                    return
                tid = thumbs_job["queue"].pop(0)
            out = os.path.join(THUMBS, tid)
            os.makedirs(out, exist_ok=True)
            with open(os.path.join(out, "plan.json"), "w") as fh:
                json.dump(catalog.preview_plan(tid), fh)
            with gpu:
                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:
        traceback.print_exc()
        with lock:
            thumbs_job["running"] = False


def refresh_thumbs(tid, again=True):
    """draw a theme's pictures (again: also if they were drawn before, after the theme changed)"""
    with lock:
        if not again and tid in thumbs_job["tried"]:
            return
        thumbs_job["tried"].add(tid)
        if tid not in thumbs_job["queue"]:
            thumbs_job["queue"].append(tid)
        if thumbs_job["running"]:
            return
        thumbs_job["running"] = True
    threading.Thread(target=render_thumbs, daemon=True).start()


def theme_list():
    out = []
    for tid in [*themes.THEMES, *themes.custom_ids()]:
        T = themes.load(tid)
        if T["id"] != tid:                       # a custom theme file that cannot be read
            continue
        pics = {s: os.path.getmtime(f) for s in themes.SLOTS if T["slots"][s]
                for f in [os.path.join(THUMBS, tid, s + ".png")] if os.path.exists(f)}
        if any(T["slots"][s] and s not in pics for s in themes.SLOTS) and system()["ready"]:
            refresh_thumbs(tid, again=False)     # drawn once on its own; a picture that fails must not loop
        out.append(dict(id=tid, label=T["label"], about=T["about"], builtin=T["builtin"], colours=T["colours"], tex=T.get("tex", {}),
                        floors=T["floors"], wall=T["wall"], tv=T["tv"], pictures={s: int(v) for s, v in pics.items()},
                        slots={s: dict(value=v, label=themes.label(T, s)) for s, v in T["slots"].items() if v}))
    return dict(themes=out, rendering=thumbs_job["running"], slots=themes.SLOTS, colours=themes.COLOURS, finishes=themes.FINISHES,
                choices={s: themes.choices(s) for s in themes.SLOTS})


def save_theme(tid, req):
    """a person's own theme from the Themes page: -> its id. tid None makes a new one, named after its label"""
    t = themes.check(req)
    if tid is None:
        base = re.sub(r"[^a-z0-9]+", "-", t["label"].lower()).strip("-")[:24] or "theme"
        tid, n = base, 2
        while tid in themes.THEMES or os.path.exists(os.path.join(themes.DIR, tid + ".json")):
            tid, n = f"{base}-{n}", n + 1
    elif tid in themes.THEMES or not os.path.exists(os.path.join(themes.DIR, tid + ".json")):
        raise ValueError("Only your own themes can be changed.")
    os.makedirs(themes.DIR, exist_ok=True)
    with open(os.path.join(themes.DIR, tid + ".json.part"), "w") as fh:
        json.dump(t, fh)
    os.replace(os.path.join(themes.DIR, tid + ".json.part"), os.path.join(themes.DIR, tid + ".json"))
    refresh_thumbs(tid)
    return tid