Skip to content

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

Python
6.3 KB
Raw Blame
"""plan JSON -> quantities: floor area per finish, wall paint, toilet wall tiles, doors and windows, furniture.
Pure Python, in feet. blender/gen.py takes FLOOR_MAT and opening_heights from here, so the sheet counts what is built.
Run: python3 quantities.py plan.json"""
import re
from collections import Counter

import furnish
import themes
from catalog import CATALOG

FLOOR_MAT = dict(dress="wood", bedroom="wood", toilet="bathtile", kitchen="marble", living="marble", dining="marble", puja="marble",
                 wash="concrete", store="concrete", study="wood", passage="tile", balcony="terracotta",
                 garden="turf", open="pebbles", parking="pavers", yard="pavers", stair="stair", room="tile",
                 duct="concrete")
PAINTED = furnish.INDOOR | {"stair"}
TILE_H = 7.0          # toilet walls are tiled to this height (gen.py builds them so), painted above
VENT_MAX = 2.6
LABELS = dict(shower2="Shower", geyser="Geyser", kitchen_run="Kitchen counter", chimney="Chimney", wall_cab2="Wall cabinet",
              rug="Rug", car="Car", outdoor_set="Outdoor table set", bathtub="Bathtub", round_rug="Round rug", **themes.SLOTS)


def zone_at(f, x, y):
    for z in f["rooms"]:
        for r in z["rects"]:
            if r[0] - 0.05 <= x <= r[1] + 0.05 and r[2] - 0.05 <= y <= r[3] + 0.05:
                return z
    return None


def opening_heights(f, o):
    """(sill, head) in feet above the floor; a door or bare opening starts below the floor"""
    r = o["rect"]
    if o["type"] != "window":
        return (-1, 7.0)
    cx, cy = (r[0] + r[1]) / 2, (r[2] + r[3]) / 2
    sides = [zone_at(f, cx, cy - 1.0), zone_at(f, cx, cy + 1.0)] if o["axis"] == "x" else \
            [zone_at(f, cx - 1.0, cy), zone_at(f, cx + 1.0, cy)]
    wet = any(z and z["type"] == "toilet" for z in sides)
    width = max(r[1] - r[0], r[3] - r[2])
    return (6.0, 7.5) if wet or width <= VENT_MAX else (3.0, 7.0)


def room_name(z):
    return " ".join(w for w in (z.get("label") or "").split() if not re.search(r"\d", w)).title() or z["type"].title()


def walls_of(f, z):
    """the room's wall faces: (length, openings in it as (width, sill, head)). Edges shared by two slices of the same
    room are not walls; an opening counts on a face when its band touches the face's line."""
    out = []
    for r in z["rects"]:
        x0, x1, y0, y1 = r
        others = [q for q in z["rects"] if q is not r]
        for ax, line, a, b in (("x", y0, x0, x1), ("x", y1, x0, x1), ("y", x0, y0, y1), ("y", x1, y0, y1)):
            lo, hi = (2, 3) if ax == "x" else (0, 1)       # across the face
            al, ah = (0, 1) if ax == "x" else (2, 3)       # along it
            ivs = [(a, b)]
            for q in others:
                if q[lo] - 0.1 <= line <= q[hi] + 0.1:
                    ivs = furnish.subtract_iv(ivs, q[al], q[ah])
            length = sum(q - p for p, q in ivs)
            if length < 0.05:
                continue
            ops = []
            for o in f["openings"]:
                c = o["rect"]
                w = sum(max(0.0, min(q, c[ah]) - max(p, c[al])) for p, q in ivs)
                if o["axis"] == ax and c[lo] - 0.5 <= line <= c[hi] + 0.5 and w > 0.05:
                    ops.append((w, *opening_heights(f, o)))
            out.append((length, ops))
    return out


def wall_area(faces, h0, h1):
    """wall between heights h0 and h1, less the openings in that band"""
    return sum(n * (h1 - h0) - sum(w * max(0.0, min(hd, h1) - max(s, h0)) for w, s, hd in ops) for n, ops in faces)


def quantities(plan):
    H = plan.get("floor_height", 10.0)
    floors, finishes, openings, items = [], Counter(), Counter(), Counter()
    T = themes.load(plan.get("theme"))
    for f in plan["floors"]:
        rooms = []
        for z in f["rooms"]:
            if z["type"] == "duct":
                continue
            area = sum((r[1] - r[0]) * (r[3] - r[2]) for r in z["rects"])
            fin = z.get("floor") or T["floors"].get(z["type"]) or FLOOR_MAT.get(z["type"], "tile")     # as gen.py builds it
            finishes[fin] += area
            row = dict(name=room_name(z), type=z["type"], finish=fin, area=area, paint=0.0, tiles=0.0, ceiling=0.0)
            if z["type"] in PAINTED:
                faces = walls_of(f, z)
                tiled = TILE_H if z["type"] == "toilet" else 0.0
                row.update(paint=wall_area(faces, tiled, H), tiles=wall_area(faces, 0.0, tiled), ceiling=area)
            rooms.append(row)
        for o in f["openings"]:
            r = o["rect"]
            s, hd = opening_heights(f, o)
            openings[(o["type"], round(max(r[1] - r[0], r[3] - r[2]) * 4) / 4, hd - max(s, 0))] += 1
        # a "model" item is a downloaded model: count it by its asset name ("potted_plant_01" -> "potted_plant");
        # a piece of the theme by the theme's name for it ("Carved four-poster bed")
        items.update(re.sub(r"_\d+$", "", str(it["args"][0])) if it["fn"] == "model" else
                     themes.label(T, it["fn"]) if it["fn"] in themes.SLOTS and not it["kw"].get("piece") and T["slots"][it["fn"]] in themes.LIBRARY
                     else it["fn"] for it in furnish.floor_items(plan, f))
        floors.append(dict(name=f.get("name", ""), rooms=rooms))
    return dict(
        floor_height=H, floors=floors, finishes=dict(finishes.most_common()),
        paint=sum(r["paint"] for f in floors for r in f["rooms"]), tiles=sum(r["tiles"] for f in floors for r in f["rooms"]),
        ceiling=sum(r["ceiling"] for f in floors for r in f["rooms"]),
        openings=[dict(type=t, width=w, height=h, count=n) for (t, w, h), n in sorted(openings.items())],
        furniture=[dict(name=CATALOG[fn][0] if fn in CATALOG else LABELS.get(fn, fn.replace("_", " ").capitalize()), count=n)
                   for fn, n in items.most_common()])


if __name__ == "__main__":
    import json, sys
    q = quantities(json.load(open(sys.argv[1])))
    for f in q["floors"]:
        for r in f["rooms"]:
            print(f'{f["name"]:14} {r["name"]:12} {r["finish"]:10} floor {r["area"]:7.1f}  paint {r["paint"]:7.1f}  tiles {r["tiles"]:6.1f} sq ft')
    print("finishes", {k: round(v, 1) for k, v in q["finishes"].items()})
    print("paint", round(q["paint"], 1), "tiles", round(q["tiles"], 1), "ceiling", round(q["ceiling"], 1))
    print("openings", q["openings"])
    print("furniture", q["furniture"])