Skip to content

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

Python

Same-house check: prove a refactor builds the same house

23f20056397c8e692ac1a0
diff --git a/AGENTS.md b/AGENTS.md
index 329a36a..10ec571 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -56,6 +56,16 @@ CHROME=/path/to/chromium node tests/test_site.mjs examples/sample_plan.pdf http:
Run it after any change to `web/`, `server.py` or `blender/`.
If you change `examples/make_sample.py`, run it to rewrite the PDF and keep its `EXPECT` in step.
+**Refactors (code moves, behaviour stays):** prove the house is the same. On `main`, then on your branch:
+
+```bash
+python3 tests/same_house.py snapshot before.json [jobs/<id>/plan.json] # the sample in every theme (+ a storeyed plan: stairs, roof)
+python3 tests/same_house.py snapshot after.json [jobs/<id>/plan.json]
+python3 tests/same_house.py compare before.json after.json # must print SAME HOUSE
+```
+
+It builds without baking (about 20 s a house) and compares every Blender object (name, box, vertices, materials) and `meta.json`.
+
## How to change things
- **A new furniture item:** write the builder in `blender/gen.py` (or `lib.py`), add it to `CALLS` and to `ITEM_FNS` in `server.py` (what the review page may send), place it from a rule in `furnish.py` with its footprint `box`. Add it to `themes.SLOTS` (and its size to `catalog.py`) if themes should be able to change it.
diff --git a/tests/same_house.py b/tests/same_house.py
new file mode 100644
index 0000000..8dfbd31
--- /dev/null
+++ b/tests/same_house.py
@@ -0,0 +1,102 @@
+"""Same-house check for refactors: build plans in Blender (no baking), record every object and meta.json, and compare
+two recordings. Code that only moves must build the same house before and after.
+ python3 tests/same_house.py snapshot before.json [plan.json ...] (the sample plan in every theme, then each plan given)
+ python3 tests/same_house.py compare before.json after.json
+Give a storeyed plan too (a copy of a job's plan.json): the sample has one storey, so no stairs or roof.
+Needs Blender (BLENDER or on PATH). Builds go to jobs/_same_house/ (snap Blender cannot write to /tmp)."""
+import collections, json, os, shutil, subprocess, sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+BLENDER = os.environ.get("BLENDER") or shutil.which("blender") or "blender"
+WORK = os.path.join(ROOT, "jobs", "_same_house")
+
+# run inside Blender on house.blend: one entry per object; Blender's .001 name suffixes depend on creation order, so
+# they are dropped and the comparison is of multisets
+DUMP = r"""
+import bpy, json, re, sys
+from mathutils import Vector
+bare = lambda n: re.sub(r"\.\d{3}$", "", n)
+out = []
+for o in bpy.data.objects:
+ pts = [o.matrix_world @ Vector(b) for b in o.bound_box]
+ d = dict(name=bare(o.name), type=o.type, parent=o.parent and bare(o.parent.name),
+ colls=sorted(bare(c.name) for c in o.users_collection),
+ box=[round(f(p[i] for p in pts), 3) for i in range(3) for f in (min, max)])
+ if o.type == "MESH":
+ d.update(verts=len(o.data.vertices), faces=len(o.data.polygons),
+ mats=sorted(bare(m.name) for m in o.data.materials if m))
+ if o.type == "LIGHT":
+ d.update(energy=round(o.data.energy, 3))
+ out.append(d)
+json.dump(out, open(sys.argv[-1], "w"))
+"""
+
+
+def build(label, plan_path):
+ out = os.path.join(WORK, label)
+ shutil.rmtree(out, ignore_errors=True)
+ os.makedirs(out)
+ r = subprocess.run([BLENDER, "-b", "--factory-startup", "-P", os.path.join(ROOT, "blender", "gen.py"), "--",
+ plan_path, out, "--quality", "draft", "--no-bake"], capture_output=True, text=True)
+ if "GEN OK" not in r.stdout: # Blender exits 0 even when the script failed
+ sys.exit(f"{label}: build failed\n{r.stdout[-3000:]}{r.stderr[-2000:]}")
+ dump = os.path.join(out, "objects.json")
+ r = subprocess.run([BLENDER, "-b", os.path.join(out, "house.blend"), "--python-expr", DUMP, "--", dump],
+ capture_output=True, text=True)
+ if not os.path.exists(dump):
+ sys.exit(f"{label}: could not read house.blend\n{r.stdout[-2000:]}{r.stderr[-2000:]}")
+ return dict(objects=json.load(open(dump)), meta=json.load(open(os.path.join(out, "meta.json"))))
+
+
+def snapshot(dest, plans):
+ os.makedirs(WORK, exist_ok=True)
+ import detect, themes
+ todo, base = [], detect.detect(os.path.join(ROOT, "examples", "sample_plan.pdf"))
+ for t in themes.THEMES:
+ todo.append((f"sample-{t}", os.path.join(WORK, f"sample-{t}.json")))
+ json.dump({**base, "theme": t}, open(todo[-1][1], "w"))
+ for k, p in enumerate(plans):
+ todo.append((f"plan{k}", os.path.join(WORK, f"plan{k}.json")))
+ shutil.copy(p, todo[-1][1])
+ res = {}
+ for label, p in todo:
+ print(f"building {label}", flush=True)
+ res[label] = build(label, p)
+ print(f" {len(res[label]['objects'])} objects", flush=True)
+ json.dump(res, open(dest, "w"))
+ print(f"wrote {dest}")
+
+
+def compare(a_path, b_path):
+ a, b = json.load(open(a_path)), json.load(open(b_path))
+ same = True
+ for label in sorted(set(a) | set(b)):
+ if label not in a or label not in b:
+ print(f"DIFF {label}: only in {'after' if label in b else 'before'}")
+ same = False
+ continue
+ ca = collections.Counter(json.dumps(o, sort_keys=True) for o in a[label]["objects"])
+ cb = collections.Counter(json.dumps(o, sort_keys=True) for o in b[label]["objects"])
+ gone, new = list((ca - cb).elements()), list((cb - ca).elements())
+ keys = [k for k in sorted(set(a[label]["meta"]) | set(b[label]["meta"]))
+ if json.dumps(a[label]["meta"].get(k), sort_keys=True) != json.dumps(b[label]["meta"].get(k), sort_keys=True)]
+ if not (gone or new or keys):
+ print(f"same {label}: {sum(ca.values())} objects, meta.json equal")
+ continue
+ same = False
+ print(f"DIFF {label}: {len(gone)} objects only before, {len(new)} only after, meta.json keys differ: {keys}")
+ for tag, xs in (("-", gone), ("+", new)):
+ for x in xs[:8]:
+ print(f" {tag} {x}")
+ print("SAME HOUSE" if same else "NOT THE SAME HOUSE")
+ return same
+
+
+if __name__ == "__main__":
+ if len(sys.argv) >= 3 and sys.argv[1] == "snapshot":
+ snapshot(sys.argv[2], sys.argv[3:])
+ elif len(sys.argv) == 4 and sys.argv[1] == "compare":
+ sys.exit(0 if compare(sys.argv[2], sys.argv[3]) else 1)
+ else:
+ sys.exit(__doc__)