Skip to content

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

Python

Plan detector and furniture rules

23f2005639cbfe6e49a48e
diff --git a/detect.py b/detect.py
new file mode 100644
index 0000000..0f22d96
--- /dev/null
+++ b/detect.py
@@ -0,0 +1,1003 @@
+"""2D plan (CAD-exported PDF) -> plan JSON: floors with walls, doors, windows, openings, rooms, stairs.
+No machine learning: walls are pairs of parallel lines, openings are gaps between collinear walls,
+doors are swing arcs at a gap, windows are glass lines inside a gap, rooms are flood-filled regions
+named by the text inside them, and the scale comes from room size labels such as 14'x12'8".
+
+Usage: python3 detect.py plan.pdf [out.json] (python3 tools/dbg_plan.py draws the result over the page)
+Output units are FEET; per floor, origin = lower-left of the walls, +x right, +y up the page.
+"""
+import json, math, re, sys
+from collections import defaultdict
+
+import vector
+
+class PlanError(ValueError):
+ """the drawing cannot be read as a plan; the message is shown to the person who uploaded it"""
+
+
+# ------------------------------------------------------------------ room names
+ROOM_TYPES = [ # (type, keywords) - first match wins, checked against the label's words
+ ("toilet", ["TOI", "TOILET", "BATH", "W.C", "WC", "WASHROOM", "LAV", "POWDER"]),
+ ("bedroom", ["BED", "BEDROOM", "BEDRM", "B.R", "M.BED", "MASTER", "GUEST", "KIDS"]),
+ ("kitchen", ["KIT", "KITCHEN", "PANTRY"]),
+ ("dining", ["DIN", "DINING"]),
+ ("living", ["LIV", "LIVING", "DRG", "DRAWING", "LOUNGE", "HALL", "FAMILY", "SITTING"]),
+ ("puja", ["PUJA", "POOJA", "MANDIR", "PRAYER", "TEMPLE"]),
+ ("wash", ["WASH", "UTILITY", "LAUNDRY", "DRY"]),
+ ("dress", ["DRESS", "DRESSING", "WARDROBE", "W.I.C"]),
+ ("store", ["STORE", "STR", "STORAGE"]),
+ ("study", ["STUDY", "OFFICE", "LIBRARY"]),
+ ("passage", ["PASSAGE", "LOBBY", "CORRIDOR", "FOYER", "ENTRANCE", "PASS"]),
+ ("balcony", ["BALCONY", "SITOUT", "SIT-OUT", "VERANDAH", "VERANDA", "TERRACE", "DECK", "PORCH"]),
+ ("garden", ["LAWN", "GARDEN", "COURTYARD", "OTS"]),
+ ("open", ["OPEN", "SHAFT", "DUCT", "CUTOUT", "VOID"]),
+ ("parking", ["PARKING", "CAR", "GARAGE"]),
+ ("stair", ["STAIR", "STAIRCASE", "UP", "DN"]),
+]
+OUTDOOR = {"open", "garden", "parking", "balcony", "yard"}
+DIM = re.compile(r"""^(\d+)'?(?:-?(\d+)"?)?\s*[xX×]\s*(\d+)'?(?:-?(\d+)"?)?$""")
+FT = re.compile(r"""^(\d+)'(?:-?(\d+)"?)?$""")
+
+
+def room_type(words):
+ toks = [t.strip(".,:()").upper() for w in words for t in re.split(r"[\s/]+", w)]
+ for typ, keys in ROOM_TYPES:
+ for k in keys:
+ if any(t == k.strip(".") or t.startswith(k.strip(".")) and len(k) >= 3 for t in toks):
+ return typ
+ return None
+
+
+def parse_dims(s):
+ s = s.replace("’", "'").replace("”", '"').replace(" ", "")
+ m = DIM.match(s)
+ if not m:
+ return None
+ a = int(m.group(1)) + int(m.group(2) or 0) / 12
+ b = int(m.group(3)) + int(m.group(4) or 0) / 12
+ return (a, b) if a > 0 and b > 0 else None
+
+
+assert parse_dims("14'x12'8") == (14, 12 + 8 / 12) and parse_dims("5X6'8") == (5, 6 + 8 / 12)
+assert parse_dims("11'4X4'4") and parse_dims('10\'-6"x12\'') == (10.5, 12) and room_type(["DRESS/TOI."]) == "toilet"
+
+
+# ------------------------------------------------------------------ lines
+def join_dashes(lines, gap):
+ """join collinear pieces less than `gap` apart (dashed lines: ventilators, hidden edges)"""
+ out = {}
+ for o, ls in lines.items():
+ by = defaultdict(list)
+ for c, a0, a1 in ls:
+ by[c].append((a0, a1))
+ res = []
+ for c, iv in by.items():
+ iv.sort()
+ a0, a1 = iv[0]
+ for b0, b1 in iv[1:]:
+ if b0 <= a1 + gap:
+ a1 = max(a1, b1)
+ else:
+ res.append((c, a0, a1)); a0, a1 = b0, b1
+ res.append((c, a0, a1))
+ out[o] = res
+ return out
+
+
+def axis_lines(segs, min_len=1.0):
+ """merge collinear axis-aligned segments -> {'h': [(c, a0, a1)], 'v': [...]}: c = fixed coord."""
+ raw = {"h": defaultdict(list), "v": defaultdict(list)}
+ for x0, y0, x1, y1, *_ in segs:
+ if abs(y0 - y1) < 0.05 and abs(x1 - x0) > 0.05:
+ raw["h"][round((y0 + y1) / 2, 1)].append((min(x0, x1), max(x0, x1)))
+ elif abs(x0 - x1) < 0.05 and abs(y1 - y0) > 0.05:
+ raw["v"][round((x0 + x1) / 2, 1)].append((min(y0, y1), max(y0, y1)))
+ out = {}
+ for o, by in raw.items():
+ lines = []
+ for c, iv in by.items():
+ iv.sort()
+ a0, a1 = iv[0]
+ for b0, b1 in iv[1:]:
+ if b0 <= a1 + 0.3:
+ a1 = max(a1, b1)
+ else:
+ lines.append((c, a0, a1)); a0, a1 = b0, b1
+ lines.append((c, a0, a1))
+ out[o] = [l for l in lines if l[2] - l[1] >= min_len]
+ return out
+
+
+def nearest(lines, gmax):
+ """for each line i and side (+1 above / -1 below): pieces [(a0, a1, j, gap)] of its nearest
+ overlapping parallel line within gmax."""
+ by_c = sorted(range(len(lines)), key=lambda i: lines[i][0])
+ cs = [lines[i][0] for i in by_c]
+ import bisect
+ res = {}
+ for i, (c, a0, a1) in enumerate(lines):
+ for side in (1, -1):
+ if side > 0:
+ lo, hi = bisect.bisect_right(cs, c + 1e-6), bisect.bisect_right(cs, c + gmax)
+ cand = [by_c[k] for k in range(lo, hi)]
+ else:
+ lo, hi = bisect.bisect_left(cs, c - gmax), bisect.bisect_left(cs, c - 1e-6)
+ cand = [by_c[k] for k in range(lo, hi)][::-1]
+ free, pieces = [(a0, a1)], []
+ for j in cand:
+ cj, b0, b1 = lines[j]
+ nf = []
+ for f0, f1 in free:
+ o0, o1 = max(f0, b0), min(f1, b1)
+ if o1 - o0 > 0.05:
+ pieces.append((o0, o1, j, abs(cj - c)))
+ if o0 > f0: nf.append((f0, o0))
+ if o1 < f1: nf.append((o1, f1))
+ else:
+ nf.append((f0, f1))
+ free = nf
+ if not free:
+ break
+ res[i, side] = pieces
+ return res
+
+
+def wall_pairs(lines, gmax):
+ """mutual-nearest line pairs that are not part of an evenly spaced hatch (windows, stairs, tiles).
+ -> walls [(c0, c1, a0, a1)], hatch pieces [(c, a0, a1)]"""
+ nb = nearest(lines, gmax)
+
+ def at(i, side, a0, a1):
+ """partner pieces of line i on side overlapping [a0, a1]"""
+ return [(max(p0, a0), min(p1, a1), j, g) for p0, p1, j, g in nb[i, side] if min(p1, a1) - max(p0, a0) > 0.05]
+
+ walls, hatch = [], []
+ for i, (c, _, _) in enumerate(lines):
+ for p0, p1, j, g in nb[i, 1]:
+ for q0, q1, k, g2 in at(j, -1, p0, p1): # mutual: j's nearest below is i
+ if k != i:
+ continue
+ # hatch test: another line at a similar spacing just beyond either side
+ cut = [(r0, r1) for side, line in ((-1, i), (1, j))
+ for r0, r1, _, g3 in at(line, side, q0, q1) if abs(g3 - g) < 0.35 * g]
+ pieces = [(q0, q1)]
+ for r0, r1 in cut:
+ pieces = [x for a, b in pieces for x in ((a, min(b, r0)), (max(a, r1), b)) if x[1] - x[0] > 0.05]
+ for a, b in pieces:
+ walls.append((c, lines[j][0], a, b))
+ for r0, r1 in cut:
+ hatch.append((c, lines[j][0], max(q0, r0), min(q1, r1)))
+ return walls, hatch
+
+
+def boundary_lines(segs, s):
+ """single drawn lines that can separate rooms (door thresholds, open-kitchen edges, floor-finish edges):
+ axis lines >= 1.2 ft, minus evenly spaced families of the same pen (tile grids, hatches, treads, glass)."""
+ by_pen = defaultdict(list)
+ for g in segs:
+ by_pen[g[4], round(g[5], 2)].append(g)
+ out = {"h": [], "v": []}
+ for (col, _), gs in by_pen.items():
+ if 0.3 * col[0] + 0.59 * col[1] + 0.11 * col[2] > 190:
+ continue # pale pens: tile grids, outlines of colour fills
+ L = axis_lines(gs, min_len=0.5)
+ for o in ("h", "v"):
+ lines = L[o]
+ nb = nearest(lines, 5 * s)
+
+ def gap(i, side): # (gap, line) of the partner overlapping most of line i on this side
+ c, a0, a1 = lines[i]
+ best = max(nb[i, side], key=lambda p: p[1] - p[0], default=None)
+ return (best[3], best[2]) if best and best[1] - best[0] > 0.5 * (a1 - a0) else (None, None)
+ for i, (c, a0, a1) in enumerate(lines):
+ if a1 - a0 < 1.2 * s:
+ continue
+ (g1, j1), (g2, j2) = gap(i, 1), gap(i, -1)
+ # CAD grids / hatches are exactly evenly spaced; rooms only by chance, so a tight tolerance
+ eq = lambda a, b: a is not None and b is not None and abs(a - b) < 0.03 * max(a, b) + 0.3
+ if eq(g1, g2) or (g1 and eq(g1, gap(j1, 1)[0])) or (g2 and eq(g2, gap(j2, -1)[0])):
+ continue # one of >= 3 evenly spaced lines
+ out[o].append((c, a0, a1))
+ return out
+
+
+def fill_columns(fills, walls, T):
+ """solid-filled rectangles the size of a wall end (RCC columns), touching a wall -> wall rects.
+ Fills come as triangles: same-colour triangles that touch are joined; a rectangle's pieces fill its bbox."""
+ by_col = defaultdict(list)
+ for pts, col in fills:
+ xs, ys = [q[0] for q in pts], [q[1] for q in pts]
+ a = abs(sum(pts[i][0] * pts[i - 1][1] - pts[i - 1][0] * pts[i][1] for i in range(len(pts)))) / 2
+ by_col[col].append([min(xs), max(xs), min(ys), max(ys), a])
+ out = []
+ for tris in by_col.values():
+ groups = [t[:] for t in tris]
+ merged = True
+ while merged:
+ merged = False
+ for i in range(len(groups)):
+ for j in range(i + 1, len(groups)):
+ a, b = groups[i], groups[j]
+ if a[0] <= b[1] + 0.2 and b[0] <= a[1] + 0.2 and a[2] <= b[3] + 0.2 and b[2] <= a[3] + 0.2:
+ groups[i] = [min(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), max(a[3], b[3]), a[4] + b[4]]
+ groups.pop(j)
+ merged = True
+ break
+ if merged:
+ break
+ if len(groups) > 4000:
+ break
+ for x0, x1, y0, y1, a in groups:
+ w, h = x1 - x0, y1 - y0
+ if 0.8 * T <= min(w, h) and max(w, h) <= 6 * T and abs(a - w * h) < 0.08 * w * h and \
+ any(x0 <= r[1] + 0.5 * T and r[0] <= x1 + 0.5 * T and y0 <= r[3] + 0.5 * T and r[2] <= y1 + 0.5 * T
+ for r in walls):
+ out.append((x0, x1, y0, y1))
+ return out
+
+
+def thickness_mode(walls):
+ """length-weighted mode of the pair gaps (the main wall thickness, in points)."""
+ h = defaultdict(float)
+ for c0, c1, a0, a1 in walls:
+ h[round(c1 - c0, 1)] += a1 - a0
+ best = max(h, key=lambda g: sum(v for k, v in h.items() if abs(k - g) <= 0.3))
+ return best
+
+
+# ------------------------------------------------------------------ geometry in plan units
+def rect(o, w):
+ """wall/hatch tuple in its orientation -> (x0, x1, y0, y1) page points"""
+ c0, c1, a0, a1 = w
+ return (a0, a1, c0, c1) if o == "h" else (c0, c1, a0, a1)
+
+
+def merge_rects(rs, tol=0.2):
+ """join rects that share a full edge (same band, touching or overlapping along the axis)."""
+ rs = list(rs)
+ changed = True
+ while changed:
+ changed = False
+ out = []
+ for r in rs:
+ for k, q in enumerate(out):
+ same_y = abs(r[2] - q[2]) < tol and abs(r[3] - q[3]) < tol
+ same_x = abs(r[0] - q[0]) < tol and abs(r[1] - q[1]) < tol
+ if same_y and r[0] <= q[1] + tol and q[0] <= r[1] + tol:
+ out[k] = (min(r[0], q[0]), max(r[1], q[1]), min(r[2], q[2]), max(r[3], q[3])); changed = True; break
+ if same_x and r[2] <= q[3] + tol and q[2] <= r[3] + tol:
+ out[k] = (min(r[0], q[0]), max(r[1], q[1]), min(r[2], q[2]), max(r[3], q[3])); changed = True; break
+ else:
+ out.append(r)
+ rs = out
+ return rs
+
+
+def cut_windows(walls, lines, T, cuts):
+ """glass / frame lines (any pen) running inside a wall band mark a window: cut that span out of the wall
+ (the spans are appended to `cuts` as (rect, orientation))."""
+ out = []
+ for w in walls:
+ o = "h" if horiz(w) else "v"
+ lo, hi, b0, b1 = (w[0], w[1], w[2], w[3]) if o == "h" else (w[2], w[3], w[0], w[1])
+ spans = sorted((max(a0, lo), min(a1, hi)) for c, a0, a1 in lines[o]
+ if b0 + 0.12 * (b1 - b0) < c < b1 - 0.12 * (b1 - b0) and a1 - a0 >= 3 * T
+ and a0 >= lo - 0.5 and a1 <= hi + 0.5)
+ pieces = [(lo, hi)]
+ for a0, a1 in spans:
+ pieces = [x for p0, p1 in pieces for x in ((p0, min(p1, a0)), (max(p0, a1), p1)) if x[1] - x[0] > 0.3]
+ cuts.append(((a0, a1, b0, b1) if o == "h" else (b0, b1, a0, a1), o))
+ out += [(p0, p1, b0, b1) if o == "h" else (b0, b1, p0, p1) for p0, p1 in pieces]
+ return out
+
+
+def horiz(r):
+ return (r[1] - r[0]) >= (r[3] - r[2])
+
+
+def close_corners(walls, T):
+ """extend wall ends into a perpendicular wall that stops just short of them (L / T corners)."""
+ out = []
+ for r in walls:
+ x0, x1, y0, y1 = r
+ for q in walls:
+ if q is r or horiz(q) == horiz(r):
+ continue
+ if horiz(r):
+ if q[2] - 1.2 * T <= y1 and y0 <= q[3] + 1.2 * T: # q spans our band (or nearly)
+ if -0.2 <= q[1] - x0 and x0 - q[0] <= 1.6 * T + 0.2 and q[0] < x0: # left end
+ x0 = min(x0, q[0])
+ if -0.2 <= x1 - q[0] and q[1] - x1 <= 1.6 * T + 0.2 and q[1] > x1:
+ x1 = max(x1, q[1])
+ else:
+ if q[0] - 1.2 * T <= x1 and x0 <= q[1] + 1.2 * T:
+ if -0.2 <= q[3] - y0 and y0 - q[2] <= 1.6 * T + 0.2 and q[2] < y0:
+ y0 = min(y0, q[2])
+ if -0.2 <= y1 - q[2] and q[3] - y1 <= 1.6 * T + 0.2 and q[3] > y1:
+ y1 = max(y1, q[3])
+ out.append((x0, x1, y0, y1))
+ return out
+
+
+# ------------------------------------------------------------------ arcs (door swings)
+def arcs(curves):
+ """cubic bezier quarter-arcs -> (cx, cy, r, p0, p1): center from the end tangents' normals."""
+ out = []
+ for p0, p1, p2, p3, *_ in curves:
+ t0 = (p1[0] - p0[0], p1[1] - p0[1])
+ t1 = (p3[0] - p2[0], p3[1] - p2[1])
+ # center c: (c - p0).t0 = 0 and (c - p3).t1 = 0
+ det = t0[0] * t1[1] - t0[1] * t1[0]
+ if abs(det) < 1e-9:
+ continue
+ b0 = t0[0] * p0[0] + t0[1] * p0[1]
+ b1 = t1[0] * p3[0] + t1[1] * p3[1]
+ cx = (b0 * t1[1] - b1 * t0[1]) / det
+ cy = (t0[0] * b1 - t1[0] * b0) / det
+ r0, r1 = math.dist((cx, cy), p0), math.dist((cx, cy), p3)
+ if r0 < 1 or abs(r0 - r1) > 0.08 * r0:
+ continue
+ out.append((cx, cy, (r0 + r1) / 2, p0, p3))
+ # merge pieces of the same circle
+ merged = []
+ for a in out:
+ for k, b in enumerate(merged):
+ if math.dist(a[:2], b[0][:2]) < 0.05 * a[2] and abs(a[2] - b[0][2]) < 0.05 * a[2]:
+ b[1].extend([a[3], a[4]]); break
+ else:
+ merged.append([a, [a[3], a[4]]])
+ res = []
+ for a, pts in merged:
+ cx, cy, r = a[:3]
+ angs = sorted(math.atan2(p[1] - cy, p[0] - cx) for p in pts)
+ res.append((cx, cy, r, pts))
+ return res
+
+
+def wall_pens(segs):
+ """stroke styles that can draw walls: CAD draws walls with the heaviest pen. Styles carrying >= 5% of the
+ axis-aligned ink, and at least 60% as wide as the widest such style (thin tile grids / hatches drop out)."""
+ ink = defaultdict(float)
+ for x0, y0, x1, y1, col, w in segs:
+ if abs(x0 - x1) < 0.05 or abs(y0 - y1) < 0.05:
+ ink[col, round(w, 2)] += abs(x1 - x0) + abs(y1 - y0)
+ total = sum(ink.values()) or 1
+ big = {k: v for k, v in ink.items() if v >= 0.05 * total}
+ wmax = max(k[1] for k in big)
+ pens = {k for k in ink if k[1] >= 0.6 * wmax}
+ # walls are plotted in black / grey; coloured wide pens are window frames, columns, beams
+ grey = {k for k in pens if isinstance(k[0], tuple) and max(k[0]) - min(k[0]) < 30}
+ if sum(ink[k] for k in grey) >= 0.5 * sum(ink[k] for k in pens):
+ pens = grey
+ return pens
+
+
+# ------------------------------------------------------------------ text
+def phrases(words):
+ """join words into phrases (same line, small gap); vertical text is joined top-to-bottom."""
+ ws = sorted(words, key=lambda w: (round((w[1] + w[3]) / 2), w[0]))
+ out = []
+ for x0, y0, x1, y1, t in ws:
+ vert = (y1 - y0) > 1.6 * (x1 - x0) and len(t) > 2
+ for p in out:
+ if p["vert"] != vert:
+ continue
+ h = min(p["h"], (x1 - x0) if vert else (y1 - y0))
+ if not vert and abs((p["y0"] + p["y1"]) / 2 - (y0 + y1) / 2) < 0.4 * h and -0.5 * h < x0 - p["x1"] < 1.2 * h:
+ p.update(x1=x1, text=p["text"] + " " + t); break
+ if vert and abs((p["x0"] + p["x1"]) / 2 - (x0 + x1) / 2) < 0.4 * h and -0.5 * h < y0 - p["y1"] < 1.2 * h:
+ p.update(y1=y1, text=t + " " + p["text"]); break # CAD vertical text reads bottom-to-top
+ else:
+ out.append(dict(x0=x0, y0=y0, x1=x1, y1=y1, text=t, vert=vert, h=(x1 - x0) if vert else (y1 - y0)))
+ for p in out:
+ p["cx"], p["cy"] = (p["x0"] + p["x1"]) / 2, (p["y0"] + p["y1"]) / 2
+ p["dims"] = parse_dims(p["text"])
+ return out
+
+
+# ------------------------------------------------------------------ floors (one sheet can hold several plans)
+def clusters(walls, gap):
+ parent = list(range(len(walls)))
+
+ def find(i):
+ while parent[i] != i:
+ parent[i] = parent[parent[i]]
+ i = parent[i]
+ return i
+ for i, a in enumerate(walls):
+ for j in range(i + 1, len(walls)):
+ b = walls[j]
+ if a[0] - gap <= b[1] and b[0] - gap <= a[1] and a[2] - gap <= b[3] and b[2] - gap <= a[3]:
+ parent[find(i)] = find(j)
+ groups = defaultdict(list)
+ for i, w in enumerate(walls):
+ groups[find(i)].append(w)
+ return list(groups.values())
+
+
+def plan_groups(walls, T):
+ """touching walls form fragments; fragments whose bounding boxes overlap belong to the same plan."""
+ groups = [(bbox(c), c) for c in clusters(walls, 1.5 * T)]
+ merged = True
+ while merged:
+ merged = False
+ for i in range(len(groups)):
+ for j in range(i + 1, len(groups)):
+ a, b = groups[i][0], groups[j][0]
+ if a[0] < b[1] and b[0] < a[1] and a[2] < b[3] and b[2] < a[3]:
+ c = groups[i][1] + groups[j][1]
+ groups[i] = (bbox(c), c)
+ groups.pop(j)
+ merged = True
+ break
+ if merged:
+ break
+ return [g[1] for g in groups]
+
+
+def overlap_rect(a, b, m=0.0):
+ return a[0] < b[1] + m and b[0] < a[1] + m and a[2] < b[3] + m and b[2] < a[3] + m
+
+
+def bbox(rs):
+ return (min(r[0] for r in rs), max(r[1] for r in rs), min(r[2] for r in rs), max(r[3] for r in rs))
+
+
+def inside(p, b, m=0.0):
+ return b[0] - m <= p[0] <= b[1] + m and b[2] - m <= p[1] <= b[3] + m
+
+
+# ------------------------------------------------------------------ scale
+def scale_from_labels(walls, phr):
+ """points per foot: distance between the walls around a room label vs the size written in it."""
+ est = []
+ for p in phr:
+ if not p["dims"]:
+ continue
+ cx, cy = p["cx"], p["cy"]
+ L = max((w[1] for w in walls if w[2] <= cy <= w[3] and w[1] <= cx), default=None)
+ R = min((w[0] for w in walls if w[2] <= cy <= w[3] and w[0] >= cx), default=None)
+ U = max((w[3] for w in walls if w[0] <= cx <= w[1] and w[3] <= cy), default=None)
+ D = min((w[2] for w in walls if w[0] <= cx <= w[1] and w[2] >= cy), default=None)
+ if None in (L, R, U, D):
+ continue
+ w, h = R - L, D - U
+ a, b = p["dims"]
+ for r1, r2 in ((w / a, h / b), (w / b, h / a)):
+ if abs(r1 - r2) < 0.03 * max(r1, r2):
+ est.append((r1 + r2) / 2)
+ if len(est) < 2:
+ return None, est
+ # mode: the estimate with the most others within 2% (rays leaking through openings give scattered values)
+ best = max(est, key=lambda e: (sum(abs(f - e) < 0.02 * e for f in est), -e))
+ good = [e for e in est if abs(e - best) < 0.02 * best]
+ if len(good) < 2:
+ return None, est
+ return sum(good) / len(good), est
+
+
+# ------------------------------------------------------------------ openings
+def openings(walls, lines, arcs_, T, s, bl):
+ """gaps along a wall line -> doors / windows / plain openings. s = points per foot, bl = boundary lines."""
+ out = []
+ for o in ("h", "v"):
+ for a in (w for w in walls if horiz(w) == (o == "h") and not is_column(w, T)):
+ # in the wall's own frame: along = (lo, hi), band = (b0, b1)
+ lo, hi, b0, b1 = (a[0], a[1], a[2], a[3]) if o == "h" else (a[2], a[3], a[0], a[1])
+ for d in (1, -1): # the gap after the wall's high end, and before its low end
+ end, corner, skip = (hi if d > 0 else lo), False, {id(a)}
+ while True:
+ best, closer = None, None
+ for c in walls:
+ clo, chi, cb0, cb1 = (c[0], c[1], c[2], c[3]) if o == "h" else (c[2], c[3], c[0], c[1])
+ if id(c) in skip or cb0 >= b1 - 0.2 * T or cb1 <= b0 + 0.2 * T:
+ continue
+ if clo - 0.3 <= end <= chi + 0.3: # this end runs into another wall: closed
+ closer = (c, clo, chi)
+ break
+ g = clo - end if d > 0 else end - chi
+ if g > 0 and (best is None or g < best[0]):
+ best = (g, c, cb0, cb1)
+ if closer is None:
+ break
+ c, clo, chi = closer
+ # an L corner where our wall stops: the gap may continue straight past the corner
+ if horiz(c) != horiz(a) and not corner and (abs(chi - end) < 1.6 * T if d > 0 else abs(clo - end) < 1.6 * T):
+ end, corner = (chi if d > 0 else clo), True
+ skip.add(id(c))
+ continue
+ best = None
+ break
+ if not best or not 1.4 <= best[0] / s <= 12.5:
+ continue
+ g, c, cb0, cb1 = best
+ same_line = horiz(c) == horiz(a)
+ band = (max(b0, cb0), min(b1, cb1)) if same_line else (b0, b1)
+ g0 = end if d > 0 else end - g
+ r = (g0, g0 + g, *band) if o == "h" else (band[0], band[1], g0, g0 + g)
+ kind, info = classify(r, o, lines, arcs_, T, s)
+ if corner and not (info.get("glass") or info.get("leaves") or threshold(r, o, bl, T)):
+ continue # past a corner we need a drawn sill / threshold line as evidence
+ if kind == "opening":
+ # many drawings show doors as a bare gap: in a straight wall, or closed by a drawn line
+ # (a wall end facing a side wall with nothing drawn between is just a passage)
+ if g / s <= 4.6 and threshold(r, o, bl, T):
+ kind, info = "door", dict(leaves=[])
+ elif not (same_line and g / s <= 8):
+ continue
+ out.append(dict(type=kind, rect=r, axis=o, **info))
+ return out
+
+
+def is_column(w, T):
+ a, b = sorted((w[1] - w[0], w[3] - w[2]))
+ return b <= 3.2 * T and a >= 0.55 * b
+
+
+def threshold(r, o, lines, T):
+ """a line drawn along the wall band (on a face or inside) across most of the gap"""
+ lo, hi, b0, b1 = (r[0], r[1], r[2], r[3]) if o == "h" else (r[2], r[3], r[0], r[1])
+ return any(b0 - 0.3 * T <= c <= b1 + 0.3 * T and min(a1, hi) - max(a0, lo) > 0.7 * (hi - lo) for c, a0, a1 in lines[o])
+
+
+def classify(r, o, lines, arcs_, T, s):
+ lo, hi, b0, b1 = (r[0], r[1], r[2], r[3]) if o == "h" else (r[2], r[3], r[0], r[1])
+ g = hi - lo
+ # glass lines: parallel lines strictly inside the wall band covering most of the gap
+ # (glass ends at the jambs; floor-tile grid lines run on through; ventilators are drawn dashed)
+ cs = sorted(c for c, a0, a1 in lines[o] # (frame lines may sit on the faces)
+ if b0 - 0.1 * T < c < b1 + 0.1 * T and min(a1, hi) - max(a0, lo) > 0.5 * g
+ and a0 > lo - 2 * T and a1 < hi + 2 * T)
+ glass = sum(1 for k, c in enumerate(cs) if k == 0 or c - cs[k - 1] > 0.2 * T) # one per position (pens overlap)
+ # door swing arcs hinged at one end of the gap
+ leaves = []
+ for cx, cy, rad, pts in arcs_:
+ along, across = (cx, cy) if o == "h" else (cy, cx)
+ if not (b0 - 1.5 * T <= across <= b1 + 1.5 * T):
+ continue
+ for end in (lo, hi):
+ if abs(along - end) < 1.2 * T and (0.7 * g <= rad <= 1.2 * g or 0.38 * g <= rad <= 0.62 * g):
+ # swing side: where the arc points lie relative to the band
+ side = sum((p[1] if o == "h" else p[0]) - (b0 + b1) / 2 for p in pts)
+ leaves.append(dict(hinge=(cx, cy), radius=rad, side=1 if side > 0 else -1, at=end))
+ if leaves:
+ return "door", dict(leaves=leaves[:2])
+ if glass >= 2: # frame + glass lines stop at the jambs (wall faces and floor-tile joints run on through)
+ return "window", dict(glass=glass)
+ return "opening", {}
+
+
+# ------------------------------------------------------------------ rooms
+def flood_rooms(walls, blocks, box, cell):
+ """label the free cells enclosed by walls+openings. -> (grid of region ids, regions{id: cells}, outside id)"""
+ x0, x1, y0, y1 = box
+ nx, ny = int((x1 - x0) / cell) + 3, int((y1 - y0) / cell) + 3
+ ox, oy = x0 - cell, y0 - cell
+ grid = [bytearray(nx) for _ in range(ny)]
+ for r in walls + blocks:
+ i0, i1 = max(0, int((r[0] - ox) / cell)), min(nx - 1, int((r[1] - ox) / cell))
+ j0, j1 = max(0, int((r[2] - oy) / cell)), min(ny - 1, int((r[3] - oy) / cell))
+ for j in range(j0, j1 + 1):
+ grid[j][i0:i1 + 1] = b"\x01" * (i1 - i0 + 1)
+ lab = [[0] * nx for _ in range(ny)]
+ regions, nid = {}, 0
+ from collections import deque
+ for sj in range(ny):
+ for si in range(nx):
+ if grid[sj][si] or lab[sj][si]:
+ continue
+ nid += 1
+ q, cells = deque([(si, sj)]), []
+ lab[sj][si] = nid
+ while q:
+ i, j = q.popleft()
+ cells.append((i, j))
+ for a, b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
+ if 0 <= a < nx and 0 <= b < ny and not grid[b][a] and not lab[b][a]:
+ lab[b][a] = nid
+ q.append((a, b))
+ regions[nid] = cells
+ return dict(lab=lab, regions=regions, outside=lab[0][0], ox=ox, oy=oy, cell=cell, nx=nx, ny=ny)
+
+
+def region_rects(cells, F):
+ """cells of one region -> few axis-aligned rects (page points), rows merged greedily."""
+ rows = defaultdict(list)
+ for i, j in cells:
+ rows[j].append(i)
+ runs = {}
+ for j, xs in rows.items():
+ xs.sort()
+ rr, a = [], xs[0]
+ for k in range(1, len(xs)):
+ if xs[k] != xs[k - 1] + 1:
+ rr.append((a, xs[k - 1])); a = xs[k]
+ rr.append((a, xs[-1]))
+ runs[j] = rr
+ rects, open_ = [], {}
+ for j in sorted(runs):
+ cur = {}
+ for run in runs[j]:
+ if run in open_ and open_[run][1] == j - 1:
+ cur[run] = (open_[run][0], j)
+ else:
+ cur[run] = (j, j)
+ for run, (j0, j1) in open_.items():
+ if run not in cur or cur[run][0] != j0:
+ rects.append((run, j0, j1))
+ open_ = cur
+ rects += [(run, j0, j1) for run, (j0, j1) in open_.items()]
+ c, ox, oy = F["cell"], F["ox"], F["oy"]
+ return [(ox + a * c, ox + (b + 1) * c, oy + j0 * c, oy + (j1 + 1) * c) for (a, b), j0, j1 in rects]
+
+
+def line_cells(bl, C, ox, oy):
+ """grid cells under the boundary lines (each stretched one cell at both ends to close tiny gaps)"""
+ out = set()
+ for c, a0, a1 in bl["h"]:
+ j = int((c - oy) / C)
+ out.update((i, j) for i in range(int((a0 - ox) / C) - 1, int((a1 - ox) / C) + 2))
+ for c, a0, a1 in bl["v"]:
+ i = int((c - ox) / C)
+ out.update((i, j) for j in range(int((a0 - oy) / C) - 1, int((a1 - oy) / C) + 2))
+ return out
+
+
+def fine_parts(cells, seed_cells, line):
+ """split a walled region along drawn lines, then merge every unlabeled piece into the neighbour it shares the
+ longest line with (furniture outlines, tile edges...). -> [(cells, [seed indices])], each with a seed."""
+ from collections import deque
+ cellset, comp, parts = set(cells), {}, []
+ nbrs = lambda q: ((q[0] + 1, q[1]), (q[0] - 1, q[1]), (q[0], q[1] + 1), (q[0], q[1] - 1))
+ for q in cells:
+ if q in line or q in comp:
+ continue
+ comp[q], stack, part = len(parts), [q], []
+ while stack:
+ a = stack.pop()
+ part.append(a)
+ for b in nbrs(a):
+ if b in cellset and b not in line and b not in comp:
+ comp[b] = comp[q]
+ stack.append(b)
+ parts.append(part)
+ if not parts:
+ return [(cells, list(range(len(seed_cells))))]
+ fr = deque(comp) # line cells join the piece beside them
+ while fr:
+ a = fr.popleft()
+ for b in nbrs(a):
+ if b in cellset and b not in comp:
+ comp[b] = comp[a]
+ parts[comp[a]].append(b)
+ fr.append(b)
+ nb = defaultdict(lambda: defaultdict(int))
+ for a in cells:
+ for b in ((a[0] + 1, a[1]), (a[0], a[1] + 1)):
+ if b in comp and comp[b] != comp[a]:
+ nb[comp[a]][comp[b]] += 1
+ nb[comp[b]][comp[a]] += 1
+ lab = defaultdict(list)
+ for k, sc in enumerate(seed_cells):
+ lab[comp.get(sc, 0)].append(k)
+ alive = set(range(len(parts)))
+ while True:
+ un = [k for k in alive if not lab[k] and nb[k]]
+ if not un:
+ break
+ u = min(un, key=lambda k: len(parts[k]))
+ v = max(nb[u], key=nb[u].get)
+ for w, n in nb.pop(u).items():
+ del nb[w][u]
+ if w != v:
+ nb[v][w] += n
+ nb[w][v] += n
+ parts[v] += parts[u]
+ alive.remove(u)
+ return [(parts[k], lab[k]) for k in alive if lab[k]]
+
+
+def split_zones(cells, idx, seeds, lines, C, ox, oy, out):
+ """split an open-plan region between its name labels with straight cuts, preferring a drawn line
+ (floor-finish edge) between the labels, else the midpoint. Recursive; out[seed index] = cells."""
+ if len(idx) == 1:
+ out[idx[0]] = cells
+ return
+ xs = [ox + (i + 0.5) * C for i, j in cells]
+ ys = [oy + (j + 0.5) * C for i, j in cells]
+ ext = {"v": (min(ys), max(ys)), "h": (min(xs), max(xs))}
+ best = None
+ for o, k in (("v", 0), ("h", 1)): # 'v' line = cut at constant x
+ order = sorted(idx, key=lambda q: seeds[q][k])
+ for a, b in zip(order, order[1:]):
+ lo, hi = seeds[a][k], seeds[b][k]
+ if hi - lo < 2 * C:
+ continue
+ e0, e1 = ext[o]
+ cand = [(min(a1, e1) - max(a0, e0), c) for c, a0, a1 in lines[o] if lo < c < hi]
+ cov, c = max(cand, default=(0, (lo + hi) / 2))
+ frac = cov / max(e1 - e0, 1e-6)
+ if frac < 0.3:
+ c, frac = (lo + hi) / 2, 0
+ n_lo = sum(1 for q in idx if seeds[q][k] < c)
+ span = (max(xs) - min(xs)) if k == 0 else (max(ys) - min(ys))
+ score = frac + 0.3 * min(n_lo, len(idx) - n_lo) / len(idx) + 0.5 * (hi - lo) / max(span, 1e-6)
+ if not best or score > best[0]:
+ best = (score, k, c)
+ if not best:
+ # labels on top of each other: nearest label
+ for q in idx:
+ out[q] = []
+ for i, j in cells:
+ x, y = ox + (i + 0.5) * C, oy + (j + 0.5) * C
+ out[min(idx, key=lambda q: (x - seeds[q][0]) ** 2 + (y - seeds[q][1]) ** 2)].append((i, j))
+ return
+ _, k, c = best
+ lo_cells = [(i, j) for i, j in cells if (ox + (i + 0.5) * C if k == 0 else oy + (j + 0.5) * C) < c]
+ hi_cells = [(i, j) for i, j in cells if (ox + (i + 0.5) * C if k == 0 else oy + (j + 0.5) * C) >= c]
+ split_zones(lo_cells, [q for q in idx if seeds[q][k] < c], seeds, lines, C, ox, oy, out)
+ split_zones(hi_cells, [q for q in idx if seeds[q][k] >= c], seeds, lines, C, ox, oy, out)
+
+
+# ------------------------------------------------------------------ stairs
+def stair_flights(hatch, T, s, phr):
+ """runs of evenly spaced parallel treads (0.6-1.3 ft apart, 2.5-6 ft long) next to an UP / DN word."""
+ groups = []
+ for o in ("h", "v"):
+ # join dashed pieces of the same strip (hidden upper flights are drawn dashed)
+ strips = defaultdict(list)
+ for c0, c1, a0, a1 in hatch[o]:
+ strips[round(c0, 1), round(c1, 1)].append((a0, a1))
+ hs = []
+ for (c0, c1), iv in strips.items():
+ iv.sort()
+ a0, a1 = iv[0]
+ for b0, b1 in iv[1:]:
+ if b0 <= a1 + 2 * T:
+ a1 = max(a1, b1)
+ else:
+ hs.append((c0, c1, a0, a1)); a0, a1 = b0, b1
+ hs.append((c0, c1, a0, a1))
+ hs.sort(key=lambda h: h[0])
+ for c0, c1, a0, a1 in hs:
+ sp, ln = (c1 - c0) / s, (a1 - a0) / s
+ if not (0.55 <= sp <= 1.35 and 2.4 <= ln <= 7):
+ continue
+ for gr in groups:
+ if gr["o"] == o and abs(gr["a0"] - a0) < T and abs(gr["a1"] - a1) < T and abs(gr["c1"] - c0) < 0.5:
+ gr["c1"] = c1; gr["n"] += 1; break
+ else:
+ groups.append(dict(o=o, a0=a0, a1=a1, c0=c0, c1=c1, n=1))
+ words = [p for p in phr if p["text"].strip(".").upper() in ("UP", "DN", "DOWN")]
+ fl = []
+ for gr in groups:
+ if gr["n"] < 4:
+ continue
+ r = (gr["a0"], gr["a1"], gr["c0"], gr["c1"]) if gr["o"] == "h" else (gr["c0"], gr["c1"], gr["a0"], gr["a1"])
+ near = [p for p in words if inside((p["cx"], p["cy"]), r, 4 * s)]
+ if near:
+ fl.append(dict(rect=r, axis="y" if gr["o"] == "h" else "x", n=gr["n"] + 1,
+ up=any(p["text"].upper().startswith("UP") for p in near),
+ words=[(p["text"].upper(), p["cx"], p["cy"]) for p in near]))
+ return fl
+
+
+# ------------------------------------------------------------------ main
+def detect_page(page):
+ pens = wall_pens(page["segs"])
+ L = axis_lines([s for s in page["segs"] if (s[4], round(s[5], 2)) in pens])
+ ALL = axis_lines(page["segs"], min_len=0.5)
+ gmax = 0.025 * math.hypot(page["width"], page["height"])
+ walls, hatch = {}, {}
+ for o in ("h", "v"):
+ walls[o], hatch[o] = wall_pairs(L[o], gmax)
+ _, hatch_all = zip(*(wall_pairs(ALL[o], gmax) for o in ("h", "v")))
+ hatch_all = dict(h=hatch_all[0], v=hatch_all[1])
+ T = thickness_mode(walls["h"] + walls["v"])
+ by_pen = defaultdict(list) # lines per pen with dashes joined (a window frame drawn on a wall face stays its own line)
+ for g in page["segs"]:
+ by_pen[g[4], round(g[5], 2)].append(g)
+ PEN = {"h": [], "v": []}
+ for gs in by_pen.values():
+ for o, ls in join_dashes(axis_lines(gs, min_len=0.5), 0.8 * T).items():
+ PEN[o] += ls
+ W = [rect(o, w) for o in ("h", "v") for w in walls[o] if 0.45 * T <= w[1] - w[0] <= 2.6 * T and w[3] - w[2] >= 0.8 * T]
+ W = merge_rects(W)
+ W_solid = W # windows not cut yet: label rays stop at window walls
+ CUTS = []
+ W = [w for w in cut_windows(W, PEN, T, CUTS) if max(w[1] - w[0], w[3] - w[2]) >= 0.5 * T] # keep jambs beside windows
+ W += fill_columns(page["fills"], W, T)
+ phr = phrases(page["words"])
+ A = arcs(page["curves"])
+ # floors: wall clusters that contain at least two room names
+ floors = []
+ for cl in plan_groups(W, T):
+ b = bbox(cl)
+ names = [p for p in phr if inside((p["cx"], p["cy"]), b) and room_type([p["text"]])]
+ if len(names) >= 2:
+ floors.append(dict(walls=cl, bbox=b))
+ if not floors:
+ raise PlanError("no floor plan found (need double-line walls and room names)")
+ s, est = scale_from_labels([w for w in W_solid if any(inside(((w[0] + w[1]) / 2, (w[2] + w[3]) / 2), f["bbox"])
+ for f in floors)], phr)
+ scale_src = "labels"
+ if not s:
+ s, scale_src = T / 0.375, "assumed" # assume the main wall is 4.5" thick
+ BL = boundary_lines(page["segs"], s)
+ out = []
+ for f in floors:
+ f["walls"] = close_corners(f["walls"], T)
+ out.append(detect_floor(f, T, s, phr, PEN, hatch_all, A, BL, CUTS))
+ out.sort(key=lambda f: f["_x"])
+ return dict(T=T, scale=s, scale_source=scale_src, scale_estimates=est, floors=out)
+
+
+def detect_floor(f, T, s, phr, lines, hatch, A, zone_lines, cuts=()):
+ b, walls = f["bbox"], f["walls"]
+ ops = [o for o in openings(walls, lines, A, T, s, zone_lines) if inside(((o["rect"][0] + o["rect"][1]) / 2,
+ (o["rect"][2] + o["rect"][3]) / 2), b)]
+ # one opening per gap (found from both of its ends)
+ uniq = []
+ for o in ops:
+ if not any(abs(o["rect"][0] - u["rect"][0]) < T and abs(o["rect"][1] - u["rect"][1]) < T and
+ abs(o["rect"][2] - u["rect"][2]) < T and abs(o["rect"][3] - u["rect"][3]) < T for u in uniq):
+ uniq.append(o)
+ ops = uniq
+ # glass drawn inside an unbroken wall is a window even when the gap search finds no wall on both sides
+ for r, o in cuts:
+ c = ((r[0] + r[1]) / 2, (r[2] + r[3]) / 2)
+ if inside(c, b) and not any(overlap_rect(r, u["rect"], -0.5) for u in ops) \
+ and not any(inside(c, w) for w in walls): # (glass running on behind a column)
+ ops.append(dict(type="window", rect=r, axis=o, glass=1))
+ flights = [fl for fl in stair_flights(hatch, T, s, phr) if inside(((fl["rect"][0] + fl["rect"][1]) / 2,
+ (fl["rect"][2] + fl["rect"][3]) / 2), b)]
+ # walls drawn between / inside the flights are stair parts (mid wall, landing edge): make them low
+ stair_box = bbox([fl["rect"] for fl in flights]) if flights else None
+ if stair_box: # stair parts (landing edges, mid walls) are not doors
+ ax = flights[0]["axis"]
+ sb = (stair_box[0] - 4.5 * s, stair_box[1] + 4.5 * s, *stair_box[2:]) if ax == "x" else \
+ (*stair_box[:2], stair_box[2] - 4.5 * s, stair_box[3] + 4.5 * s)
+ ops = [o for o in ops if not inside(((o["rect"][0] + o["rect"][1]) / 2, (o["rect"][2] + o["rect"][3]) / 2), sb)]
+ border = [(b[0] - T, b[0], b[2] - T, b[3] + T), (b[1], b[1] + T, b[2] - T, b[3] + T),
+ (b[0] - T, b[1] + T, b[2] - T, b[2]), (b[0] - T, b[1] + T, b[3], b[3] + T)]
+ F = flood_rooms(walls, [o["rect"] for o in ops if o["type"] != "opening"] + border, (b[0] - T, b[1] + T, b[2] - T, b[3] + T), max(T / 3, 0.5))
+ names = [p for p in phr if inside((p["cx"], p["cy"]), b)]
+ rooms, zone_of = [], {} # zone_of[cell] = room index (open plans are split per name label)
+ C, ox, oy = F["cell"], F["ox"], F["oy"]
+ cell_of = lambda x, y: (int((x - ox) / C), int((y - oy) / C))
+ lcells = line_cells(zone_lines, C, ox, oy)
+ for rid, cells in F["regions"].items():
+ if rid == F["outside"]:
+ continue
+ area = len(cells) * (C / s) ** 2
+ if area < 2.0:
+ continue
+ cellset = set(cells)
+ inner = [p for p in names if cell_of(p["cx"], p["cy"]) in cellset]
+ seeds = [(p["cx"], p["cy"], room_type([p["text"]]), p) for p in inner if room_type([p["text"]])]
+ seeds = [sd for sd in seeds if sd[2] != "stair"]
+ for fl in flights: # (the middle of a dog-leg is its mid wall, so seed on a flight)
+ sc = ((fl["rect"][0] + fl["rect"][1]) / 2, (fl["rect"][2] + fl["rect"][3]) / 2)
+ if cell_of(*sc) in cellset:
+ seeds.append((*sc, "stair", None))
+ break
+ if not seeds:
+ xs = [ox + i * C for i, j in cells]
+ ys = [oy + j * C for i, j in cells]
+ edge = min(xs) <= b[0] + T or max(xs) >= b[1] - T or min(ys) <= b[2] + T or max(ys) >= b[3] - T
+ door = any(cell_of(x, y) in cellset for o in ops if o["type"] == "door"
+ for x, y in (((o["rect"][0] + o["rect"][1]) / 2, o["rect"][2] - 1.5 * C),
+ ((o["rect"][0] + o["rect"][1]) / 2, o["rect"][3] + 1.5 * C),
+ (o["rect"][0] - 1.5 * C, (o["rect"][2] + o["rect"][3]) / 2),
+ (o["rect"][1] + 1.5 * C, (o["rect"][2] + o["rect"][3]) / 2)))
+ # a door into it makes it a lobby; ducts are walled all round
+ seeds = [(0, 0, "yard" if edge else "passage" if door else "duct" if area < 12 else "room", None)]
+ groups = {}
+ for pc, idx in fine_parts(cells, [cell_of(sd[0], sd[1]) for sd in seeds], lcells) if seeds[0][3] or len(seeds) > 1 \
+ else [(cells, [0])]:
+ split_zones(pc, idx, seeds, zone_lines, C, ox, oy, groups)
+ for k, zc in groups.items():
+ p = seeds[k][3]
+ dims = None
+ if p: # the size label written just under / after the name
+ near = [q for q in inner if q["dims"] and abs(q["cx"] - p["cx"]) < 4 * p["h"] and 0 <= q["cy"] - p["cy"] < 3 * p["h"]]
+ dims = near[0] if near else None
+ for c in zc:
+ zone_of[c] = len(rooms)
+ rooms.append(dict(region=rid, type=seeds[k][2], area=round(len(zc) * (C / s) ** 2, 1),
+ label=" ".join(t["text"] for t in (p, dims) if t) if p else "",
+ dims=dims["dims"] if dims else None, rects=region_rects(zc, F)))
+ # walls with outdoor space (or nothing) on both sides are boundary / parapet walls -> low
+ def type_at(x, y):
+ k = zone_of.get(cell_of(x, y))
+ return rooms[k]["type"] if k is not None else None
+ # (sampled along the wall: a long outer wall can have a room on part of it; an open shaft keeps full walls)
+ out_walls = []
+ for w in walls:
+ sides = []
+ for t in (0.1, 0.3, 0.5, 0.7, 0.9):
+ if horiz(w):
+ m = w[0] + t * (w[1] - w[0])
+ sides += [type_at(m, w[2] - 1.5 * C), type_at(m, w[3] + 1.5 * C)]
+ else:
+ m = w[2] + t * (w[3] - w[2])
+ sides += [type_at(w[0] - 1.5 * C, m), type_at(w[1] + 1.5 * C, m)]
+ low = all(sd is None or (sd in OUTDOOR and sd != "open") for sd in sides)
+ if stair_box:
+ c = ((w[0] + w[1]) / 2, (w[2] + w[3]) / 2)
+ # between the flights and short across them (dashed pieces included): the mid wall, not an end wall
+ lo_, hi_, w0, w1 = (stair_box[2], stair_box[3], w[2], w[3]) if ax == "x" else (stair_box[0], stair_box[1], w[0], w[1])
+ mid = lo_ + T < (w0 + w1) / 2 < hi_ - T and w1 - w0 < 0.5 * (hi_ - lo_)
+ if inside(c, stair_box, -0.5 * T) or (mid and inside(c, sb)):
+ low = True # mid wall between the flights (it may run on across the landing)
+ elif inside(c, sb):
+ low = False # the stairwell's own walls rise with the stair
+ out_walls.append((w, low))
+ # page points -> feet: origin at the lower-left of the walls, +y up the page
+ X0, Y1 = b[0], b[3]
+ P = lambda x, y: (round((x - X0) / s, 3), round((Y1 - y) / s, 3))
+ R = lambda r: [round((r[0] - X0) / s, 3), round((r[1] - X0) / s, 3), round((Y1 - r[3]) / s, 3), round((Y1 - r[2]) / s, 3)]
+ title = next((p["text"] for p in phr if "FLOOR" in p["text"].upper() and b[0] <= p["cx"] <= b[1]
+ and 0 < p["cy"] - b[3] < 8 * s), None)
+ ops_out = []
+ for o in ops:
+ d = dict(type=o["type"], rect=R(o["rect"]), axis="x" if o["axis"] == "h" else "y")
+ if o["type"] == "door" and o["leaves"]:
+ lf = o["leaves"][0]
+ d["hinge"] = P(*lf["hinge"])
+ d["swing"] = -lf["side"] if o["axis"] == "h" else lf["side"] # +1: towards +y (or +x)
+ d["double"] = len(o["leaves"]) > 1 or lf["radius"] < 0.62 * ((o["rect"][1] - o["rect"][0]) if o["axis"] == "h" else (o["rect"][3] - o["rect"][2]))
+ ops_out.append(d)
+ return dict(
+ _x=b[0], title=title, origin_pt=[X0, Y1], size=[round((b[1] - b[0]) / s, 2), round((b[3] - b[2]) / s, 2)],
+ walls=[R(w) + [1 if low else 0] for w, low in out_walls],
+ openings=ops_out,
+ rooms=[dict(r, rects=[R(q) for q in r["rects"]]) for r in rooms],
+ stairs=[dict(rect=R(fl["rect"]), axis=fl["axis"], steps=fl["n"], up=fl["up"],
+ words=[(t, *P(x, y)) for t, x, y in fl["words"]]) for fl in flights],
+ labels=[dict(text=p["text"], at=P(p["cx"], p["cy"])) for p in names],
+ )
+
+
+def detect(pdf):
+ pages = []
+ for k in range(1, vector.page_count(pdf) + 1):
+ try:
+ pg = detect_page(vector.read_page(pdf, k))
+ except PlanError:
+ continue
+ for f in pg["floors"]:
+ f["page"] = k
+ pages.append(pg)
+ if not pages:
+ raise PlanError("No floor plan was found in this PDF. The drawing needs double-line walls and room names.")
+ floors = [f for p in pages for f in p["floors"]]
+ # order: by the title (ground, first, second...) else left-to-right, page order
+ order = ["BASEMENT", "STILT", "GROUND", "FIRST", "SECOND", "THIRD", "FOURTH", "TERRACE"]
+ def rank(f):
+ t = (f["title"] or "").upper()
+ return next((i for i, k in enumerate(order) if k in t), 99)
+ if all(rank(f) < 99 for f in floors):
+ floors.sort(key=rank)
+ for i, f in enumerate(floors):
+ f.pop("_x")
+ f["level"] = i
+ f["name"] = (f["title"] or f"Floor {i}").title().replace(" Plan", "")
+ p0 = pages[0]
+ return dict(version=1, source=pdf.rsplit("/", 1)[-1], units="ft", scale_pt_per_ft=round(p0["scale"], 4),
+ scale_source=p0["scale_source"], wall_pt=round(p0["T"], 2), floor_height=10.0, slab=0.5,
+ floors=floors)
+
+
+if __name__ == "__main__":
+ pdf = sys.argv[1]
+ plan = detect(pdf)
+ out = sys.argv[2] if len(sys.argv) > 2 and not sys.argv[2].startswith("--") else None
+ js = json.dumps(plan, indent=1)
+ if out:
+ open(out, "w").write(js)
+ for f in plan["floors"]:
+ print(f["name"], f["size"], "walls", len(f["walls"]), "openings",
+ {t: sum(o["type"] == t for o in f["openings"]) for t in ("door", "window", "opening")},
+ "rooms", len(f["rooms"]), "stairs", len(f["stairs"]))
+ print("scale", plan["scale_pt_per_ft"], plan["scale_source"])
diff --git a/furnish.py b/furnish.py
new file mode 100644
index 0000000..5ff97f2
--- /dev/null
+++ b/furnish.py
@@ -0,0 +1,628 @@
+"""Rule-based furniture layout (no ML): for each detected room zone pick items for its type and place them against
+real walls, away from doors, windows (for tall items), each other, and other rooms.
+Pure python so it can be tested without Blender. Units: feet. Output items are calls into blender/lib.py.
+
+Rotation (lib.py convention): 0 = item front faces -y (back to a wall on +y), 90 = +x, 180 = +y, 270 = -x.
+"""
+import math
+
+SIDES = { # side of the room rect -> (rot of an item backed onto it, axis along the wall)
+ "N": 0, "S": 180, "E": 270, "W": 90,
+}
+INDOOR = {"bedroom", "toilet", "kitchen", "living", "dining", "puja", "study", "store", "passage", "room", "wash", "dress"}
+
+
+def area(r):
+ return (r[1] - r[0]) * (r[3] - r[2])
+
+
+def overlap(a, b, m=0.0):
+ return a[0] < b[1] - m and b[0] < a[1] - m and a[2] < b[3] - m and b[2] < a[3] - m
+
+
+def inside(a, b, m=0.05):
+ return a[0] >= b[0] - m and a[1] <= b[1] + m and a[2] >= b[2] - m and a[3] <= b[3] + m
+
+
+def subtract_iv(ivs, a, b):
+ return [x for p, q in ivs for x in ((p, min(q, a)), (max(p, b), q)) if x[1] - x[0] > 0.05]
+
+
+def union_iv(ivs):
+ out = []
+ for a, b in sorted(ivs):
+ if out and a <= out[-1][1] + 0.3:
+ out[-1] = (out[-1][0], max(out[-1][1], b))
+ else:
+ out.append((a, b))
+ return out
+
+
+def max_rect(rects, exclude=None, g=0.25):
+ """largest axis-aligned rectangle inside the union of rects (minus `exclude`): rooms come as row slices"""
+ x0, y0 = min(r[0] for r in rects), min(r[2] for r in rects)
+ nx, ny = int(round((max(r[1] for r in rects) - x0) / g)), int(round((max(r[3] for r in rects) - y0) / g))
+ grid = [[False] * nx for _ in range(ny)]
+ for r in rects:
+ for j in range(int(round((r[2] - y0) / g)), int(round((r[3] - y0) / g))):
+ for i in range(int(round((r[0] - x0) / g)), int(round((r[1] - x0) / g))):
+ grid[j][i] = True
+ if exclude:
+ for j in range(ny):
+ for i in range(nx):
+ x, y = x0 + (i + 0.5) * g, y0 + (j + 0.5) * g
+ if exclude[0] < x < exclude[1] and exclude[2] < y < exclude[3]:
+ grid[j][i] = False
+ best, hts = (0, None), [0] * nx
+ for j in range(ny):
+ hts = [h + 1 if grid[j][i] else 0 for i, h in enumerate(hts)]
+ st = []
+ for i in range(nx + 1): # largest rectangle in a histogram
+ h = hts[i] if i < nx else 0
+ while st and hts[st[-1]] >= h:
+ top = st.pop()
+ left = st[-1] + 1 if st else 0
+ a = hts[top] * (i - left)
+ if a > best[0]:
+ best = (a, (x0 + left * g, x0 + i * g, y0 + (j + 1 - hts[top]) * g, y0 + (j + 1) * g))
+ st.append(i)
+ return best[1]
+
+
+class Room:
+ def __init__(self, zone, floor):
+ self.zone, self.type, self.floor = zone, zone["type"], floor
+ self.rect = max_rect(zone["rects"]) or max(zone["rects"], key=area)
+ x0, x1, y0, y1 = self.rect
+ self.w, self.d = x1 - x0, y1 - y0
+ self.items, self.keepout = [], []
+ walls = [w for w in floor["walls"]]
+ ops = floor["openings"]
+ self.free = {} # side -> {"low": intervals, "tall": intervals} (positions along the side)
+ for side in "NSEW":
+ along = (x0, x1) if side in "NS" else (y0, y1)
+ face = {"N": y1, "S": y0, "E": x1, "W": x0}[side]
+ # wall coverage along this side (open-plan boundaries have no wall)
+ cov = [] # walls, and windows (a counter or bed can stand under a sill; tall items are cut below)
+ for w in walls + [list(o["rect"]) + [0] for o in ops if o["type"] == "window"]:
+ if side in "NS":
+ near_ = (w[2] - 0.6 <= face <= w[3] + 0.6) and (w[2] >= face - 0.25 if side == "N" else w[3] <= face + 0.25)
+ if near_ and w[4] == 0:
+ cov.append((max(w[0], along[0]), min(w[1], along[1])))
+ else:
+ near_ = (w[0] - 0.6 <= face <= w[1] + 0.6) and (w[0] >= face - 0.25 if side == "E" else w[1] <= face + 0.25)
+ if near_ and w[4] == 0:
+ cov.append((max(w[2], along[0]), min(w[3], along[1])))
+ cov = union_iv([c for c in cov if c[1] - c[0] > 0.2])
+ low, tall = cov, cov
+ for o in ops:
+ r = o["rect"]
+ if side in "NS":
+ hit = r[2] - 0.8 <= face <= r[3] + 0.8 and r[1] > along[0] and r[0] < along[1]
+ a, b = r[0], r[1]
+ else:
+ hit = r[0] - 0.8 <= face <= r[1] + 0.8 and r[3] > along[0] and r[2] < along[1]
+ a, b = r[2], r[3]
+ if not hit:
+ continue
+ if o["type"] == "window":
+ tall = subtract_iv(tall, a - 0.2, b + 0.2)
+ else:
+ low = subtract_iv(low, a - 0.4, b + 0.4)
+ tall = subtract_iv(tall, a - 0.4, b + 0.4)
+ self.free[side] = {"low": low, "tall": tall}
+ # fridges and wardrobes must not stand in front of a window on a neighbouring wall either
+ self.win_front = []
+ for o in ops:
+ if o["type"] == "window":
+ r = o["rect"]
+ self.win_front.append((r[0] - 0.1, r[1] + 0.1, r[2] - 2.0, r[3] + 2.0) if o["axis"] == "x" else
+ (r[0] - 2.0, r[1] + 2.0, r[2] - 0.1, r[3] + 0.1))
+ # stair flights and their landing strip are walkways
+ for st in floor.get("stairs", []):
+ r = st["rect"]
+ self.keepout.append((r[0] - 0.1, r[1] + 0.1, r[2] - 0.1, r[3] + 0.1))
+ if floor.get("stairs"):
+ xs = [v for st in floor["stairs"] for v in st["rect"][:2]]
+ ys = [v for st in floor["stairs"] for v in st["rect"][2:]]
+ ax = floor["stairs"][0]["axis"]
+ pad = 4.0
+ self.keepout.append((min(xs) - (pad if ax == "x" else 0), max(xs) + (pad if ax == "x" else 0),
+ min(ys) - (pad if ax == "y" else 0), max(ys) + (pad if ax == "y" else 0)))
+ # door swing / walkway keep-out boxes (both sides of every door touching this room)
+ for o in ops:
+ if o["type"] == "window":
+ continue
+ r = o["rect"]
+ box = (r[0] - 0.2, r[1] + 0.2, r[2] - 3.0, r[3] + 3.0) if o["axis"] == "x" else \
+ (r[0] - 3.0, r[1] + 3.0, r[2] - 0.2, r[3] + 0.2)
+ if overlap(box, self.rect):
+ self.keepout.append(box)
+ # doors of this room: on its edge, with their middle inside the room's span (not a neighbour's door at a corner)
+ x0, x1, y0, y1 = self.rect
+ self.doors = [o for o in ops if o["type"] != "window" and overlap(
+ (o["rect"][0] - 0.8, o["rect"][1] + 0.8, o["rect"][2] - 0.8, o["rect"][3] + 0.8), self.rect)
+ and (x0 < (o["rect"][0] + o["rect"][1]) / 2 < x1 if o["axis"] == "x" else y0 < (o["rect"][2] + o["rect"][3]) / 2 < y1)]
+
+ # ---- placement against a side
+ def spot(self, side, w, d, tall=False, align="center", gap=0.0):
+ """best position (center) for an item of width w / depth d with its back on `side` -> (x, y, rot, box)"""
+ x0, x1, y0, y1 = self.rect
+ best = None
+ for a, b in self.free[side]["tall" if tall else "low"]:
+ if b - a < w + 2 * gap:
+ continue
+ if align == "start":
+ c = a + gap + w / 2
+ elif align == "end":
+ c = b - gap - w / 2
+ else:
+ c = (a + b) / 2
+ for c in (c, a + gap + w / 2, b - gap - w / 2):
+ if side == "N":
+ box, xy = (c - w / 2, c + w / 2, y1 - d, y1), (c, y1 - d / 2)
+ elif side == "S":
+ box, xy = (c - w / 2, c + w / 2, y0, y0 + d), (c, y0 + d / 2)
+ elif side == "E":
+ box, xy = (x1 - d, x1, c - w / 2, c + w / 2), (x1 - d / 2, c)
+ else:
+ box, xy = (x0, x0 + d, c - w / 2, c + w / 2), (x0 + d / 2, c)
+ if self.fits(box) and not (tall and 2 <= d <= 3 and any(overlap(box, k, 0.02) for k in self.win_front)):
+ score = b - a
+ if not best or score > best[0]:
+ best = (score, (*xy, SIDES[side], box))
+ break
+ return best[1] if best else None
+
+ def fits(self, box, ignore_keepout=False):
+ if not inside(box, self.rect):
+ return False
+ if any(overlap(box, it["box"], 0.02) for it in self.items if it.get("solid", True)):
+ return False
+ if not ignore_keepout and any(overlap(box, k, 0.02) for k in self.keepout):
+ return False
+ return True
+
+ def add(self, fn, box, *args, solid=True, **kw):
+ self.items.append(dict(fn=fn, args=list(args), kw=kw, box=box, solid=solid, room=self.zone.get("label") or self.type))
+
+ def sides_by(self, key, tall=False):
+ """sides sorted by their longest free run (desc)"""
+ lens = {s: max((b - a for a, b in self.free[s]["tall" if tall else "low"]), default=0) for s in "NSEW"}
+ return sorted("NSEW", key=lambda s: -lens[s] if key == "long" else lens[s])
+
+ def door_side(self):
+ """side of the rect nearest to the (first) door"""
+ if not self.doors:
+ return None
+ r = self.doors[0]["rect"]
+ cx, cy = (r[0] + r[1]) / 2, (r[2] + r[3]) / 2
+ x0, x1, y0, y1 = self.rect
+ return min({"W": abs(cx - x0), "E": abs(cx - x1), "S": abs(cy - y0), "N": abs(cy - y1)}.items(),
+ key=lambda kv: kv[1])[0]
+
+
+OPP = {"N": "S", "S": "N", "E": "W", "W": "E"}
+
+
+def front_offset(side, xy, dist):
+ """point `dist` feet in front of an item at xy backed onto `side`"""
+ dx, dy = {"N": (0, -1), "S": (0, 1), "E": (-1, 0), "W": (1, 0)}[side]
+ return xy[0] + dx * dist, xy[1] + dy * dist
+
+
+def rect_at(c, w, d, side):
+ """item box of width w (along wall) and depth d centred at c, for an item backed onto `side`"""
+ if side in "NS":
+ return (c[0] - w / 2, c[0] + w / 2, c[1] - d / 2, c[1] + d / 2)
+ return (c[0] - d / 2, c[0] + d / 2, c[1] - w / 2, c[1] + w / 2)
+
+
+# ------------------------------------------------------------------ rules per room type
+def bedroom(R):
+ double = min(R.w, R.d) >= 9.0
+ bw, bl = (5.0, 6.6) if double else (3.5, 6.5)
+ for side in R.sides_by("long", tall=True):
+ depth_room = R.d if side in "NS" else R.w
+ if depth_room < bl + 2.2:
+ continue
+ p = R.spot(side, bw + 2 * 1.6, bl, tall=True)
+ stands = p is not None
+ p = p or R.spot(side, bw, bl, tall=True)
+ if not p:
+ continue
+ x, y, rot, box = p
+ bb = rect_at((x, y), bw, bl, side)
+ # wood panel behind the bed: only as wide as the wall that is free there (never past a door or wall end)
+ c = x if side in "NS" else y
+ iv = next(((a, b) for a, b in R.free[side]["tall"] if a - 0.01 <= c <= b + 0.01), (c - bw / 2, c + bw / 2))
+ panel = max(0.0, min(bw + 3.2 if stands else bw + 1.0, 2 * min(c - iv[0], iv[1] - c) - 0.2))
+ R.add("bed", bb, x, y, rot, w=bw, l=bl, blanket="fabric_blanket", panel=round(panel, 2))
+ if stands:
+ for s in (-1, 1):
+ off = (bw / 2 + 0.8) * s
+ cx, cy = (x + off, y) if side in "NS" else (x, y + off)
+ cx, cy = front_offset(side, (cx, cy), -(bl / 2 - 0.8))
+ R.add("nightstand", rect_at((cx, cy), 1.5, 1.4, side), cx, cy, rot)
+ break
+ # wardrobe on another wall, towards a corner
+ for side in R.sides_by("long", tall=True):
+ for w in (6.0, 5.0, 4.0):
+ p = R.spot(side, w, 2.0, tall=True, align="end", gap=0.1)
+ if p:
+ x, y, rot, box = p
+ R.add("wardrobe", box, x, y, rot, w=w, d=2.0, h=7.0)
+ break
+ else:
+ continue
+ break
+ if R.w * R.d > 120:
+ p = None
+ for side in R.sides_by("long"):
+ p = R.spot(side, 3.5, 2.0)
+ if p:
+ R.add("desk", p[3], p[0], p[1], p[2])
+ break
+ # the bed's wall panel stops short of anything else standing against that wall (wardrobe, desk)
+ for bed in [i for i in R.items if i["fn"] == "bed"]:
+ bx, by, rot = bed["args"]
+ side = next(k for k, v in SIDES.items() if v == rot)
+ c, face = (bx, {"N": R.rect[3], "S": R.rect[2]}.get(side)) if side in "NS" else (by, {"E": R.rect[1], "W": R.rect[0]}[side])
+ half = bed["kw"]["panel"] / 2
+ for it in R.items:
+ if it is bed or it["fn"] == "nightstand":
+ continue
+ b = it["box"]
+ lo, hi, n0, n1 = (b[0], b[1], b[2], b[3]) if side in "NS" else (b[2], b[3], b[0], b[1])
+ if n0 - 0.3 <= face <= n1 + 0.3:
+ if hi <= c:
+ half = min(half, c - hi - 0.05)
+ elif lo >= c:
+ half = min(half, lo - c - 0.05)
+ bed["kw"]["panel"] = round(max(0.0, 2 * half), 2)
+
+
+def along(R, side, w, d, from_hi, tall=False, gap=0.0):
+ """first spot for a w x d item backed onto `side`, scanning along the wall from one end
+ (from_hi: start at the high-x / high-y end). gap: clear space kept on both sides of the item."""
+ x0, x1, y0, y1 = R.rect
+ lo, hi = (x0, x1) if side in "NS" else (y0, y1)
+ n = int((hi - lo - w) / 0.25) + 1
+ for k in range(max(n, 0)):
+ c = (hi - w / 2 - k * 0.25) if from_hi else (lo + w / 2 + k * 0.25)
+ if not any(a - 0.01 <= c - w / 2 and c + w / 2 <= b + 0.01 for a, b in R.free[side]["tall" if tall else "low"]):
+ continue
+ box = rect_at(((c, {"N": y1 - d / 2, "S": y0 + d / 2}[side]) if side in "NS" else
+ ({"E": x1 - d / 2, "W": x0 + d / 2}[side], c)), w, d, side)
+ roomy = rect_at(((box[0] + box[1]) / 2, (box[2] + box[3]) / 2), w + 2 * gap, d, side)
+ if R.fits(box) and not any(overlap(roomy, it["box"], 0.02) for it in R.items if it.get("solid", True)):
+ return ((box[0] + box[1]) / 2, (box[2] + box[3]) / 2, SIDES[side], box)
+ return None
+
+
+def toilet(R):
+ """basin by the door, then the WC, then the shower in the far corner - one wall if it is long enough,
+ so the WC never faces the basin across a small room"""
+ ds = R.door_side()
+ door = R.doors[0]["rect"] if R.doors else None
+ walls = [s for s in R.sides_by("long") if s != ds]
+ placed = False
+ for side in walls:
+ if door: # which end of this wall is nearer the door
+ dc = (door[0] + door[1]) / 2 if side in "NS" else (door[2] + door[3]) / 2
+ lo, hi = (R.rect[0], R.rect[1]) if side in "NS" else (R.rect[2], R.rect[3])
+ near_hi = abs(dc - hi) < abs(dc - lo)
+ else:
+ near_hi = False
+ v = along(R, side, 2.4, 1.7, near_hi, tall=True)
+ if not v:
+ continue
+ R.add("vanity", v[3], v[0], v[1], v[2], w=2.2)
+ wc = along(R, side, 1.6, 2.2, near_hi, gap=0.4)
+ if not wc: # WC beside the basin wall, at the far corner
+ R.items.pop()
+ continue
+ R.add("wc2", wc[3], wc[0], wc[1], wc[2])
+ placed = True
+ break
+ if not placed: # small room: WC facing the door, basin on a side wall next to the door
+ order = [OPP[ds]] + [s for s in "NSEW" if s not in (ds, OPP[ds])] if ds else list("NSEW")
+ for side in order:
+ p = R.spot(side, 1.6, 2.2, align="end", gap=0.3)
+ if p:
+ R.add("wc2", p[3], p[0], p[1], p[2])
+ break
+ for side in order[1:]:
+ p = R.spot(side, 2.4, 1.7, tall=True, align="start", gap=0.2)
+ if p:
+ R.add("vanity", p[3], p[0], p[1], p[2], w=2.2)
+ break
+ for side in [s for s in R.sides_by("long") if s != ds] + ([ds] if ds else []): # shower in a free corner
+ for from_hi in (True, False):
+ p = along(R, side, 2.6, 2.6, from_hi)
+ if p and (abs(p[3][0] - R.rect[0]) < 0.05 or abs(p[3][1] - R.rect[1]) < 0.05 or
+ abs(p[3][2] - R.rect[2]) < 0.05 or abs(p[3][3] - R.rect[3]) < 0.05) and \
+ sum(abs(v - e) < 0.05 for v, e in zip(p[3], R.rect)) >= 2:
+ x, y, rot, box = p
+ wx, wy = {"N": (x, box[3]), "S": (x, box[2]), "E": (box[1], y), "W": (box[0], y)}[side]
+ R.add("shower2", box, wx, wy, rot)
+ R.add("geyser", box, wx, wy, rot, solid=False)
+ return
+
+
+def kitchen(R):
+ """L-shaped platform: the main run on the window wall with the sink under the window, the return run (hob +
+ chimney) on the side wall away from the door; fridge on a free tall wall; nothing on the door's wall."""
+ ds = R.door_side()
+ x0, x1, y0, y1 = R.rect
+ FRONT = {"N": "-y", "S": "+y", "E": "-x", "W": "+x"}
+
+ def window_at(side): # centre of a window on this wall (a gap in the tall-free spans), or None
+ t = R.free[side]["tall"]
+ gaps = [((p + q) / 2, q - p) for p, q in zip([v[1] for v in t], [v[0] for v in t[1:]])]
+ if not t and R.free[side]["low"]:
+ a_, b_ = max(R.free[side]["low"], key=lambda iv: iv[1] - iv[0])
+ gaps = [((a_ + b_) / 2, b_ - a_)]
+ return max(gaps, key=lambda g: g[1])[0] if gaps else None
+
+ def box_on(side, a_, b_):
+ return {"N": (a_, b_, y1 - 2.0, y1), "S": (a_, b_, y0, y0 + 2.0), "E": (x1 - 2.0, x1, a_, b_),
+ "W": (x0, x0 + 2.0, a_, b_)}[side]
+
+ def fit_run(side, a_, b_, keep, min_len):
+ """shrink [a_, b_] from the end away from `keep` ('lo' / 'hi' / None) until it fits"""
+ while b_ - a_ >= min_len:
+ if R.fits(box_on(side, a_, b_)):
+ return a_, b_
+ if keep == "hi" or (keep is None and (b_ - a_) % 1.0 < 0.5):
+ a_ += 0.5
+ else:
+ b_ -= 0.5
+ return None
+
+ def score(side):
+ length = max((q - p for p, q in R.free[side]["low"]), default=0)
+ return length + 5 * (window_at(side) is not None) + 3 * (side == OPP.get(ds)) - 8 * (side == ds)
+
+ main = None
+ for side in sorted("NSEW", key=score, reverse=True):
+ if side == ds or not R.free[side]["low"]:
+ continue
+ a_, b_ = max(R.free[side]["low"], key=lambda iv: iv[1] - iv[0])
+ r = fit_run(side, a_, b_, None, 4.5)
+ if r:
+ main = (side, *r)
+ break
+ if not main:
+ return fridge(R)
+ side, a_, b_ = main
+ win = window_at(side)
+ sink = win if win is not None and a_ + 1.2 < win < b_ - 1.2 else None
+ # return run on a side wall, starting in the corner next to the main run, on the end away from the door
+ ret = None
+ cross = "EW" if side in "NS" else "NS"
+ face = {"N": y1, "S": y0, "E": x1, "W": x0}[side]
+ for s2 in sorted(cross, key=lambda q: q == ds):
+ if s2 == ds:
+ continue
+ corner_hi = face in (y1, x1) # the main run sits at the high end of this side wall
+ for p, q in R.free[s2]["low"]:
+ if corner_hi:
+ q2 = min(q, face - 2.0)
+ if abs(q - face) > 0.3 or q2 - p < 3.0:
+ continue
+ r = fit_run(s2, max(p, q2 - 6.0), q2, "hi", 3.0)
+ else:
+ p2 = max(p, face + 2.0)
+ if abs(p - face) > 0.3 or q - p2 < 3.0:
+ continue
+ r = fit_run(s2, p2, min(q, p2 + 6.0), "lo", 3.0)
+ if r:
+ ret = (s2, *r)
+ break
+ if ret:
+ break
+ # which end of the main run touches the return (the hob goes there if there is no return)
+ hob_main = None
+ if not ret:
+ hob_main = (b_ - 1.6) if sink is None or abs((b_ - 1.6) - sink) > 2.6 else (a_ + 1.6)
+ if sink is not None and abs(hob_main - sink) < 2.6:
+ hob_main = None
+ R.add("kitchen_run", box_on(side, a_, b_), *box_on(side, a_, b_), FRONT[side],
+ sink=sink if sink is not None else (a_ + 1.4 if ret is None else (a_ + b_) / 2), hob=hob_main)
+ runs = [(side, a_, b_, hob_main)]
+ if ret:
+ s2, p, q = ret
+ hob = (p + q) / 2
+ R.add("kitchen_run", box_on(s2, p, q), *box_on(s2, p, q), FRONT[s2], sink=None, hob=hob)
+ runs.append((s2, p, q, hob))
+ for sd, p, q, hob in runs:
+ if hob is not None:
+ hx, hy = {"N": (hob, y1), "S": (hob, y0), "E": (x1, hob), "W": (x0, hob)}[sd]
+ R.add("chimney", (0, 0, 0, 0), hx, hy, SIDES[sd], solid=False)
+ for u0, v0 in R.free[sd]["tall"]: # wall cabinets where the wall is solid, not over the hob
+ segs = [(max(u0, p), min(v0, q))]
+ if hob is not None:
+ segs = subtract_iv(segs, hob - 1.4, hob + 1.4)
+ for u, v in segs:
+ if v - u >= 1.5:
+ box = {"N": (u, v, y1 - 1.1, y1), "S": (u, v, y0, y0 + 1.1), "E": (x1 - 1.1, x1, u, v), "W": (x0, x0 + 1.1, u, v)}[sd]
+ R.add("wall_cab2", (0, 0, 0, 0), *box, FRONT[sd], solid=False)
+ fridge(R)
+
+
+def fridge(R):
+ ds = R.door_side()
+ for side in sorted(R.sides_by("long", tall=True), key=lambda q: q == ds):
+ p = R.spot(side, 2.4, 2.3, tall=True, align="end", gap=0.1)
+ if p:
+ R.add("fridge2", p[3], p[0], p[1], p[2])
+ return
+
+
+def living(R):
+ for side in R.sides_by("long"):
+ for w in (7.0, 6.0, 5.0):
+ p = R.spot(side, w, 3.0)
+ if not p:
+ continue
+ x, y, rot, box = p
+ ct = front_offset(side, (x, y), 3.0)
+ cbox = rect_at(ct, 3.6, 2.0, side)
+ if not R.fits(cbox):
+ continue
+ R.add("sofa", box, x, y, rot, w=w)
+ R.add("coffee_table", cbox, ct[0], ct[1], rot)
+ rbox = rect_at(ct, w + 0.5, 5.5, side)
+ R.add("rug", rbox, *rbox, solid=False)
+ # TV on the opposite wall if it is a wall
+ q = R.spot(OPP[side], 5.0, 1.4)
+ if q:
+ R.add("tv_unit", q[3], q[0], q[1], q[2])
+ return
+
+
+def dining(R):
+ if R.zone.get("area", R.w * R.d) >= 150: # a big "DRG./DIN." room is drawing + dining: sofa set first
+ living(R)
+ if not dining_table(R): # no room left beside the sofa: the table goes in the L's other arm
+ r = max_rect(R.zone["rects"], exclude=R.rect)
+ if r and min(r[1] - r[0], r[3] - r[2]) >= 6.0:
+ R2 = Room(dict(R.zone, rects=[r]), R.floor)
+ if dining_table(R2):
+ R.items += R2.items
+ return
+ dining_table(R)
+
+
+def dining_table(R):
+ long_x = R.w >= R.d
+ # (table w, l, seats, chair clearance); slide along the long axis from the centre outwards
+ for tw, tl, n, m in ((6.0, 3.2, 6, 2.2), (4.5, 3.0, 4, 2.2), (4.5, 3.0, 4, 1.8), (3.0, 3.0, 2, 1.8)):
+ for t, u in sorted(((k / 40, j / 40) for k in range(4, 37) for j in range(14, 27)),
+ key=lambda q: abs(q[0] - 0.5) + 2 * abs(q[1] - 0.5)):
+ cx = R.rect[0] + R.w * (t if long_x else u)
+ cy = R.rect[2] + R.d * (u if long_x else t)
+ a, b = (tw, tl) if long_x else (tl, tw)
+ box = (cx - a / 2 - m, cx + a / 2 + m, cy - b / 2 - m, cy + b / 2 + m)
+ if R.fits(box):
+ R.add("dining_set", (cx - a / 2 - 1.6, cx + a / 2 + 1.6, cy - b / 2 - 1.6, cy + b / 2 + 1.6),
+ cx, cy, 0 if long_x else 90, w=tw, d=tl, seats=n)
+ return True
+ return False
+
+
+def dress(R):
+ """walk-in dressing room: wardrobes along the free walls"""
+ for side in R.sides_by("long", tall=True)[:2]:
+ for w in (6.0, 5.0, 4.0, 3.0):
+ p = R.spot(side, w, 2.0, tall=True)
+ if p:
+ R.add("wardrobe", p[3], p[0], p[1], p[2], w=w, d=2.0, h=7.0)
+ break
+
+
+def puja(R):
+ ds = R.door_side()
+ for side in ([OPP[ds]] if ds else []) + list("NSEW"):
+ for w in (3.6, 3.0, 2.4):
+ p = R.spot(side, w, 1.6, tall=True)
+ if p:
+ R.add("puja_mandir", p[3], p[0], p[1], p[2], w=w)
+ return
+
+
+def wash(R):
+ for side in R.sides_by("long"):
+ p = R.spot(side, 2.1, 2.0, align="end", gap=0.2)
+ if p:
+ R.add("washer2", p[3], p[0], p[1], p[2])
+ return
+
+
+def parking(R):
+ cx, cy = (R.rect[0] + R.rect[1]) / 2, (R.rect[2] + R.rect[3]) / 2
+ along_y = R.d >= R.w
+ L, W = 14.5, 6.2
+ box = (cx - W / 2, cx + W / 2, cy - L / 2, cy + L / 2) if along_y else (cx - L / 2, cx + L / 2, cy - W / 2, cy + W / 2)
+ if R.fits(box):
+ R.add("car", box, cx, cy, 0 if along_y else 90)
+
+
+def balcony(R):
+ for side in R.sides_by("long"):
+ p = R.spot(side, 4.0, 3.5)
+ if p:
+ R.add("outdoor_set", p[3], p[0], p[1], p[2])
+ break
+ plants(R, 2)
+
+
+def garden(R):
+ plants(R, max(1, int(max(R.w, R.d) / 6)))
+
+
+def plants(R, n):
+ x0, x1, y0, y1 = R.rect
+ long_x = R.w >= R.d
+ for k in range(n):
+ t = (k + 0.5) / n
+ x, y = (x0 + (x1 - x0) * t, (y0 + y1) / 2) if long_x else ((x0 + x1) / 2, y0 + (y1 - y0) * t)
+ box = (x - 0.8, x + 0.8, y - 0.8, y + 0.8)
+ if R.fits(box):
+ R.add("plant", box, x, y, k * 70)
+
+
+RULES = dict(dress=dress, bedroom=bedroom, toilet=toilet, kitchen=kitchen, living=living, dining=dining, puja=puja, wash=wash,
+ parking=parking, balcony=balcony, garden=garden, study=lambda R: bedroom_study(R))
+
+
+def bedroom_study(R):
+ for side in R.sides_by("long"):
+ p = R.spot(side, 3.5, 2.0)
+ if p:
+ R.add("desk", p[3], p[0], p[1], p[2])
+ return
+
+
+def furnish_floor(floor):
+ """-> list of items {fn, args, kw, box, solid, room} for one floor"""
+ out = []
+ for z in floor["rooms"]:
+ if z["type"] not in RULES or not z["rects"]:
+ continue
+ R = Room(z, floor)
+ if R.w < 2.5 or R.d < 2.5:
+ continue
+ RULES[z["type"]](R)
+ out += R.items
+ return out
+
+
+def clashes(items, floor):
+ """sanity check: solid items overlapping each other, or blocking a doorway"""
+ bad = []
+ solid = [it for it in items if it["solid"] and it["box"][1] > it["box"][0]]
+ for i, a in enumerate(solid):
+ for b in solid[i + 1:]:
+ if overlap(a["box"], b["box"], 0.05) and a["fn"] != "rug" and b["fn"] != "rug":
+ bad.append(f'{a["fn"]} x {b["fn"]} in {a["room"]}')
+ for o in floor["openings"]:
+ if o["type"] == "window":
+ continue
+ r = o["rect"]
+ for it in solid:
+ if overlap(it["box"], (r[0] - 0.1, r[1] + 0.1, r[2] - 0.1, r[3] + 0.1)):
+ bad.append(f'{it["fn"]} blocks a doorway in {it["room"]}')
+ return bad
+
+
+if __name__ == "__main__":
+ import json, sys
+ P = json.load(open(sys.argv[1]))
+ for f in P["floors"]:
+ items = furnish_floor(f)
+ from collections import Counter
+ print(f["name"], len(items), dict(Counter(i["fn"] for i in items)))
+ for b in clashes(items, f):
+ print(" CLASH", b)
diff --git a/vector.py b/vector.py
new file mode 100644
index 0000000..10511ee
--- /dev/null
+++ b/vector.py
@@ -0,0 +1,114 @@
+"""Read the drawing primitives of a CAD-exported PDF page: line segments, curves, filled shapes and words.
+Coordinates are PDF points, y pointing down (page space). Needs poppler (pdftocairo, pdftotext)."""
+import html, re, subprocess, xml.etree.ElementTree as ET
+
+NUM = r"-?\d*\.?\d+(?:[eE][-+]?\d+)?"
+
+
+def _matrix(t):
+ if not t:
+ return (1, 0, 0, 1, 0, 0)
+ m = re.match(r"matrix\(([^)]*)\)", t)
+ if m:
+ return tuple(float(v) for v in re.split(r"[ ,]+", m.group(1).strip()))
+ m = re.match(r"translate\(([^)]*)\)", t)
+ if m:
+ v = [float(v) for v in re.split(r"[ ,]+", m.group(1).strip())] + [0]
+ return (1, 0, 0, 1, v[0], v[1])
+ raise ValueError(f"unsupported transform {t}")
+
+
+def _mul(m, n):
+ """m applied after n."""
+ a, b, c, d, e, f = m
+ A, B, C, D, E, F = n
+ return (a * A + c * B, b * A + d * B, a * C + c * D, b * C + d * D, a * E + c * F + e, b * E + d * F + f)
+
+
+def _rgb(s):
+ if not s or s == "none":
+ return None
+ m = re.findall(NUM, s)
+ return tuple(round(float(v) * (2.55 if "%" in s else 1)) for v in m[:3]) if m else s
+
+
+def page_count(pdf):
+ out = subprocess.run(["pdfinfo", pdf], capture_output=True, text=True, timeout=60).stdout
+ return int(re.search(r"Pages:\s+(\d+)", out).group(1))
+
+
+def read_page(pdf, page=1):
+ """-> dict(width, height, segs, curves, fills, words). segs: (x0,y0,x1,y1,stroke,width)."""
+ svg = subprocess.run(["pdftocairo", "-svg", "-f", str(page), "-l", str(page), pdf, "-"],
+ capture_output=True, check=True, timeout=120).stdout
+ root = ET.fromstring(svg)
+ ns = "{http://www.w3.org/2000/svg}"
+ vb = [float(v) for v in root.get("viewBox").split()]
+ segs, curves, fills = [], [], []
+
+ def walk(el, m):
+ tag = el.tag.replace(ns, "")
+ if tag in ("defs", "clipPath", "mask", "symbol", "pattern"):
+ return
+ m = _mul(m, _matrix(el.get("transform")))
+ if tag == "path":
+ path(el, m)
+ for ch in el:
+ walk(ch, m)
+
+ def path(el, m):
+ stroke, fill = _rgb(el.get("stroke")), _rgb(el.get("fill", "black"))
+ a, b, c, d, e, f = m
+ sw = float(el.get("stroke-width", 1)) * (abs(a * d - b * c) ** 0.5)
+ tf = lambda x, y: (a * x + c * y + e, b * x + d * y + f)
+ toks = re.findall(rf"[MLCZHVmlczhv]|{NUM}", el.get("d", ""))
+ i, cmd, cur, start, poly, polys = 0, None, (0, 0), (0, 0), [], []
+ while i < len(toks):
+ if toks[i].isalpha():
+ cmd = toks[i]
+ i += 1
+ if cmd in "Zz":
+ if stroke and cur != start:
+ segs.append((*tf(*cur), *tf(*start), stroke, sw))
+ cur = start
+ if poly:
+ polys.append(poly)
+ poly = []
+ continue
+ if cmd == "M":
+ cur = start = (float(toks[i]), float(toks[i + 1])); i += 2
+ if poly:
+ polys.append(poly)
+ poly = [tf(*cur)]
+ cmd = "L"
+ elif cmd == "L":
+ p = (float(toks[i]), float(toks[i + 1])); i += 2
+ if stroke:
+ segs.append((*tf(*cur), *tf(*p), stroke, sw))
+ cur = p
+ poly.append(tf(*p))
+ elif cmd == "C":
+ pts = [(float(toks[i + k]), float(toks[i + k + 1])) for k in (0, 2, 4)]; i += 6
+ if stroke:
+ curves.append((tf(*cur), *(tf(*q) for q in pts), stroke, sw))
+ cur = pts[2]
+ poly.append(tf(*cur))
+ else: # relative / H / V commands are not emitted by pdftocairo; skip their numbers
+ i += 1
+ if poly:
+ polys.append(poly)
+ if fill:
+ fills.extend((p, fill) for p in polys if len(p) >= 3)
+
+ walk(root, (1, 0, 0, 1, 0, 0))
+ return dict(width=vb[2], height=vb[3], segs=segs, curves=curves, fills=fills, words=read_words(pdf, page))
+
+
+def read_words(pdf, page=1):
+ out = subprocess.run(["pdftotext", "-bbox", "-f", str(page), "-l", str(page), pdf, "-"],
+ capture_output=True, text=True, check=True, timeout=120).stdout
+ words = []
+ for m in re.finditer(r'<word xMin="([\d.]+)" yMin="([\d.]+)" xMax="([\d.]+)" yMax="([\d.]+)">(.*?)</word>', out):
+ x0, y0, x1, y1 = (float(m.group(k)) for k in range(1, 5))
+ words.append((x0, y0, x1, y1, html.unescape(m.group(5))))
+ return words