Skip to content

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

Python

Furniture tool on the review page: move, turn, delete and add items

23f2005639c9323d06d809
diff --git a/AGENTS.md b/AGENTS.md
index 13f9192..7549168 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -35,6 +35,7 @@ Flow: upload -> `run_detect` -> `plan.json` -> review page edits it -> `POST …
- **Units.** Plan JSON and all furniture code are in feet. `meta.json` and the browser are in metres.
- **Rotation.** `rot` 0 = the item's front faces -y and its back is on +y; 90 = front +x; 180 = +y; 270 = -x.
+- **Furniture items** `{fn, args, kw, box, solid, room}`: a floor with an `items` list (written by the review page's Furniture tool) is built with exactly that list, `[]` = empty rooms; without the key the rules in `furnish.py` decide.
- **Rectangles** are `[x0, x1, y0, y1]`. A wall is `[x0, x1, y0, y1, low]` (`low` 1 = parapet height).
- **Stages** of a job: `uploaded`, `detecting`, `detected`, `queued`, `building`, `done`, `failed` (in `jobs/<id>/status.json`).
- Messages a person will read are raised as `detect.PlanError`. Anything else is logged and shown as a generic message.
@@ -55,7 +56,7 @@ If you change `examples/make_sample.py`, run it to rewrite the PDF and keep its
## How to change things
-- **A new furniture item:** write the builder in `blender/gen.py` (or `lib.py`), add it to `CALLS`, place it from a rule in `furnish.py` with its footprint `box`. Add it to `catalog.py` only if people should be able to replace it.
+- **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 `catalog.py` only if people should be able to replace it.
- **A new room type:** add its keywords to `ROOM_TYPES` in `detect.py`, a rule in `furnish.py`, a floor material in `gen.py` (`FLOOR_MAT`, `INDOOR`), and a colour in `web/edit.js` (`TYPES`, `ZCOL`).
- **A detector fix:** make it general, not a special case for one drawing. Check the sample still passes. The scores on real drawings need private fixtures (`PLANTO3D_FIXTURES`) that are not in the repository.
- **A new API call:** add it in `server.py` (`do_GET` / `do_POST` / `do_DELETE`), and to the table in `README.md`.
diff --git a/README.md b/README.md
index 876d035..39a0752 100644
--- a/README.md
+++ b/README.md
@@ -85,6 +85,7 @@ python server.py
|---|---|
| **Review before building** | Detected walls, doors, windows and rooms drawn over your PDF. Click to change or delete, draw walls, add doors and windows, set the scale |
| **Furniture on or off** | Untick **Furniture** for empty rooms |
+| **Move your furniture** | The **Furniture** tool on the review page shows each item: drag to move, turn it 90°, delete it, or add one from the list |
| **Time estimate** | The build box shows about how long is left, learned from earlier builds on the same machine |
| **Walkthrough** | W A S D and mouse on desktop, two thumbs on a phone. Starts at the entrance side of the plan |
| **Top view** (T) | The house from above, one storey at a time |
@@ -157,7 +158,8 @@ sequenceDiagram
| `POST /api/upload` | Body: the PDF. Header `X-Filename`. Returns `{ id }` and starts detection |
| `GET /api/jobs/{id}` | `{ stage, progress, message, floors, eta_left }`. Stages: `detecting`, `detected`, `queued`, `building`, `done`, `failed` |
| `GET /jobs/{id}/plan.json` | The detected plan (feet): walls, openings, rooms, stairs per storey |
-| `POST /api/jobs/{id}/plan` | Save an edited plan. `"furnish": false` builds empty rooms |
+| `POST /api/jobs/{id}/plan` | Save an edited plan. `"furnish": false` builds empty rooms. A floor's `items` list (furniture placed on the review page) replaces the rules for that floor |
+| `GET /api/jobs/{id}/furniture` | `{ floors, catalog }`: each floor's furniture items (its own `items`, else the rules' choice) and the items that can be added |
| `POST /api/jobs/{id}/build` | Body `{ "quality": "draft" \| "high" }`. Builds run one at a time |
| `POST /api/jobs/{id}/export` | Packs the Blender file. Returns `{ url }` of the zip |
| `GET /web/view.html?job={id}` | The walkthrough. `&embed` hides the link back to the upload page |
diff --git a/blender/gen.py b/blender/gen.py
index d2f9ca4..efcbdd5 100644
--- a/blender/gen.py
+++ b/blender/gen.py
@@ -523,8 +523,7 @@ for k, f in enumerate(floors):
stair_box_prev = bbox_of([b[:4] for b in sboxes])
else:
stair_box_prev = None
- # furniture: none if the review page's "Furniture" box was unticked; hand-placed items win over the rules
- items = [] if plan.get("furnish") is False else f.get("items") or furnish.furnish_floor(f)
+ items = furnish.floor_items(plan, f)
for it in items:
try:
custom(it) or CALLS[it["fn"]](*it["args"], **it["kw"])
diff --git a/furnish.py b/furnish.py
index eaad94d..d6ed756 100644
--- a/furnish.py
+++ b/furnish.py
@@ -599,6 +599,12 @@ def furnish_floor(floor):
return out
+def floor_items(plan, floor):
+ """what Blender builds on a floor: nothing if furnishing is off, the review page's own list if it edited this floor
+ (an empty one means empty rooms), else the rules' choice"""
+ return [] if plan.get("furnish") is False else floor["items"] if "items" in floor else furnish_floor(floor)
+
+
def clashes(items, floor):
"""sanity check: solid items overlapping each other, or blocking a doorway"""
bad = []
diff --git a/server.py b/server.py
index 6fd9918..4a97ca7 100644
--- a/server.py
+++ b/server.py
@@ -3,7 +3,7 @@ Standard library only. Run: python3 server.py [--port 8080] [--host 127.0.0.1] [
Builds run one at a time in Blender (GPU) in a background thread; progress is polled by the pages.
--cors lets pages on another site call the API from the browser (ORIGIN such as https://example.com, or *).
There is no login: run it on a trusted network, or behind your own backend or proxy."""
-import importlib, json, os, queue, re, shutil, subprocess, sys, threading, time, traceback, uuid, zipfile
+import importlib, json, math, os, queue, re, shutil, subprocess, sys, threading, time, traceback, uuid, zipfile
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, unquote
@@ -16,7 +16,7 @@ MAX_UPLOAD = 200 * 1024 * 1024 # plans are small; recordings sent for MP4
BUILD_TIMEOUT = 2 * 3600 # seconds; a high-quality build of a large house takes well under an hour
ID = re.compile(r"^[a-f0-9]{12}$")
sys.path.insert(0, HERE)
-import catalog, detect, fetch_assets # noqa: E402
+import catalog, detect, fetch_assets, furnish # noqa: E402
os.makedirs(JOBS, exist_ok=True)
builds = queue.Queue()
@@ -151,6 +151,39 @@ def furniture():
thumb=os.path.exists(os.path.join(THUMBS, f"{fn}.png"))) for fn, (label, *_) in catalog.CATALOG.items()])
+def plan_items(jid):
+ """the furniture each floor will get: the review page's own list if it edited that floor, else the rules' choice"""
+ plan = json.load(open(os.path.join(jdir(jid), "plan.json")))
+ return dict(floors=[furnish.floor_items(plan, f) for f in plan["floors"]], catalog={fn: [label, w, d, kw] for fn, (label, w, d, kw) in catalog.CATALOG.items()})
+
+
+# items the browser may send: must match gen.CALLS (gen.py runs inside Blender, so it cannot be imported here),
+# minus "model", whose argument is an asset file name
+ITEM_FNS = set(catalog.CATALOG) | {"shower2", "geyser", "kitchen_run", "chimney", "wall_cab2", "rug", "car",
+ "outdoor_set", "bathtub", "round_rug"}
+WORD = re.compile(r"[\w+-]{0,24}") # side names such as "-x" and material names; nothing that can be a path
+
+
+def check_items(plan):
+ """furniture lists from the browser go to Blender as function arguments: only known items, plain values"""
+ num = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
+ plain = lambda v: v is None or isinstance(v, bool) or num(v) or (isinstance(v, str) and WORD.fullmatch(v))
+ for f in plan["floors"]:
+ if not isinstance(f, dict) or "items" not in f:
+ continue
+ items = f["items"]
+ if not isinstance(items, list) or len(items) > 400:
+ raise ValueError("invalid furniture list")
+ for it in items:
+ if not (isinstance(it, dict) and isinstance(it.get("fn"), str) and it["fn"] in ITEM_FNS
+ and isinstance(it.get("args"), list) and len(it["args"]) <= 8 and all(num(v) or isinstance(v, str) and WORD.fullmatch(v) for v in it["args"])
+ and isinstance(it.get("box"), list) and len(it["box"]) == 4 and all(map(num, it["box"]))
+ and isinstance(it.get("kw"), dict) and len(it["kw"]) <= 12
+ and all(WORD.fullmatch(k) and plain(v) for k, v in it["kw"].items())
+ and isinstance(it.get("solid", True), bool) and isinstance(it.get("room", ""), str)):
+ raise ValueError("invalid furniture item")
+
+
# ------------------------------------------------------------------ pipeline steps
def run_detect(jid):
d = jdir(jid)
@@ -297,6 +330,15 @@ class H(BaseHTTPRequestHandler):
left = st["started"] + st["eta_total"] - time.time()
st["eta_left"] = max(0, round(min(left, 15) if st.get("progress", 0) >= 92 else left)) # 92 = exporting, the last step
return self.send(200 if st else 404, st or {"error": "no such job"})
+ m = re.match(r"^/api/jobs/([a-f0-9]{12})/furniture$", p)
+ if m:
+ if not os.path.exists(os.path.join(jdir(m.group(1)), "plan.json")):
+ return self.send(404, {"error": "no plan yet"})
+ try:
+ return self.send(200, plan_items(m.group(1)))
+ except Exception:
+ traceback.print_exc()
+ return self.send(500, {"error": "The furniture could not be worked out - see the server log."})
if p == "/api/system":
return self.send(200, system())
if p == "/api/jobs":
@@ -393,6 +435,7 @@ class H(BaseHTTPRequestHandler):
if what == "plan":
if not isinstance(req.get("floors"), list) or not req["floors"]:
return self.send(400, {"error": "invalid plan"})
+ 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})
diff --git a/tests/test_server.py b/tests/test_server.py
index 6b2d201..969384a 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -1,13 +1,13 @@
"""The server's guards, without Blender: files outside the web folders stay hidden, a plan that is being read or built
-cannot be changed or deleted, bad request bodies get an answer, and a cover sheet before the plan is not taken for a
-scan. python3 tests/test_server.py"""
+cannot be changed or deleted, bad request bodies get an answer, furniture from the review page reaches Blender only
+as known items with plain values, and a cover sheet before the plan is not taken for a scan. python3 tests/test_server.py"""
import json, os, shutil, subprocess, sys, tempfile, threading, urllib.error, urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path[:0] = [ROOT, os.path.join(ROOT, "examples")]
import make_sample as M # noqa: E402
-import server # noqa: E402
+import detect, server # noqa: E402
server.JOBS = tempfile.mkdtemp() # never touch the real jobs folder
httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), server.H)
@@ -46,6 +46,35 @@ try:
assert call("DELETE", f"/api/jobs/{done}")[0] == 200 and not os.path.exists(server.jdir(done))
print("ok server: hidden files, busy plans, bad bodies")
+ # furniture: the rules' list until the review page sends its own; an empty list is an empty floor
+ jid = job("detected")
+ assert call("GET", f"/api/jobs/{jid}/furniture")[0] == 404 # not read yet
+ plan = detect.detect(os.path.join(ROOT, "examples", "sample_plan.pdf"))
+ json.dump(plan, open(os.path.join(server.jdir(jid), "plan.json"), "w"))
+ code, out = call("GET", f"/api/jobs/{jid}/furniture")
+ out = json.loads(out)
+ assert code == 200 and len(out["floors"]) == len(plan["floors"]) and "bed" in out["catalog"], out
+ rules = out["floors"][0]
+ assert {"bed", "kitchen_run", "wall_cab2"} <= {it["fn"] for it in rules}
+ post = lambda p: call("POST", f"/api/jobs/{jid}/plan", json.dumps(p).encode())[0]
+ plan["floors"][0]["items"] = rules # the rules' own items pass as they are
+ assert post(plan) == 200
+ plan["floors"][0]["items"] = []
+ assert post(plan) == 200 and json.loads(call("GET", f"/api/jobs/{jid}/furniture")[1])["floors"][0] == []
+ bed = next(it for it in rules if it["fn"] == "bed")
+ for bad in (dict(bed, fn="model", args=["../../x", 1, 1, 0]), dict(bed, fn="nope"), dict(bed, args=[1, "../x", 0]),
+ dict(bed, args=[1, float("nan"), 0]), dict(bed, box=[0, 1, 2]), dict(bed, kw={"w": [5]}),
+ dict(bed, kw={"a/b": 1}), dict(bed, kw={"m": "rug\n"}), dict(bed, kw=None), dict(bed, fn=[]), "bed"):
+ plan["floors"][0]["items"] = [bad]
+ assert post(plan) == 400, bad
+ plan["floors"][0]["items"] = [bed] * 401
+ assert post(plan) == 400
+ plan["floors"][0]["items"] = [dict(bed, args=[1, 2, 90])]
+ assert post(plan) == 200
+ plan["furnish"] = False
+ assert post(plan) == 200 and json.loads(call("GET", f"/api/jobs/{jid}/furniture")[1])["floors"] == [[]] * len(plan["floors"])
+ print("ok server: furniture lists, item checks")
+
# a title sheet with no drawing before the plan: the plan on page 2 is found, and its page is the one drawn
cover = os.path.join(server.JOBS, "cover.pdf")
open(cover, "wb").write(M.pdf_page(b""))
diff --git a/web/edit.html b/web/edit.html
index 65e4bb4..89d2377 100644
--- a/web/edit.html
+++ b/web/edit.html
@@ -62,6 +62,7 @@
<button data-t="door">Add door</button>
<button data-t="window">Add window</button>
<button data-t="scale">Set scale</button>
+ <button data-t="furniture">Furniture</button>
<button id="undo">Undo</button>
</div>
<p class="muted" style="font-size:12px;margin:6px 0 0" id="hint">Click a wall, opening or room to edit it, or another floor plan to switch to it. Drag to pan, scroll to zoom.</p>
diff --git a/web/edit.js b/web/edit.js
index 6f75960..1c2f69f 100644
--- a/web/edit.js
+++ b/web/edit.js
@@ -100,6 +100,80 @@ function wallT() {
}
function snapshot() { history.push(JSON.stringify(plan)); if (history.length > 50) history.shift(); }
+// ---------------------------------------------------------------- furniture (feet; rot 0 = front faces -y, 90 = +x)
+let auto = null, cat = {}; // the rules' items per floor (from the server), the catalogue that can be added
+// nothing to show or edit until the rules' list is in, or while furnishing is off: an edit would freeze that empty list
+const ready = () => auto && $('furn').checked;
+const items = () => (ready() ? F().items || auto[fi] || [] : []);
+// the first edit on a floor copies the rules' list into the plan: from then on the build uses exactly that list
+function own() { snapshot(); return (F().items ??= structuredClone(auto[fi] || [])); }
+// kitchen runs, wall cabinets, rugs and the hood are placed from wall coordinates: they can only be deleted
+const movable = (it) => it.args.length === 3 && it.args.every((v) => typeof v === 'number') && it.box[1] > it.box[0];
+function itemRect(it) { // the wall cabinets and the hood have no footprint: drawn from their own coordinates
+ if (it.box[1] > it.box[0]) return it.box;
+ const a = it.args;
+ return typeof a[3] === 'number' ? a.slice(0, 4) : [a[0] - 0.6, a[0] + 0.6, a[1] - 0.6, a[1] + 0.6];
+}
+function pickItem(x, y) { // the smallest item under the pointer: a nightstand before the rug under it
+ let best = null, area = Infinity;
+ items().forEach((it, i) => {
+ const r = itemRect(it), a = (r[1] - r[0]) * (r[3] - r[2]);
+ if (inR(r, x, y) && a < area) { best = { kind: 'item', i }; area = a; }
+ });
+ return best;
+}
+function moveItem(it, dx, dy) {
+ it.args[0] += dx; it.args[1] += dy;
+ it.box = [it.box[0] + dx, it.box[1] + dx, it.box[2] + dy, it.box[3] + dy];
+}
+function rotateItem(it) { // a quarter turn anticlockwise about the item's point: (u, v) -> (-v, u)
+ const [x, y] = it.args, [x0, x1, y0, y1] = it.box;
+ it.box = [x - (y1 - y), x - (y0 - y), y + (x0 - x), y + (x1 - x)];
+ it.args[2] = (it.args[2] + 90) % 360;
+}
+async function loadFurniture() {
+ // saved first, so the rules see the room types as they are now (refused while a build runs: the saved plan is used)
+ auto = null; sel = null;
+ plan.furnish = $('furn').checked;
+ try {
+ await fetch(`/api/jobs/${job}/plan`, { method: 'POST', body: JSON.stringify(plan) });
+ const r = await fetch(`/api/jobs/${job}/furniture`);
+ if (r.ok) ({ floors: auto, catalog: cat } = await r.json());
+ } catch { /* shown below */ }
+ if (!auto) $('hint').textContent = 'The furniture could not be loaded. Choose the Furniture tool again to retry.';
+ ui();
+}
+function drawItems() {
+ items().forEach((it, i) => {
+ const B = itemRect(it), [X, Y, W, Hh] = rectC(B), on = sel?.kind === 'item' && sel.i === i;
+ g.fillStyle = on ? 'rgba(176,86,43,.45)' : 'rgba(40,40,40,.16)'; g.fillRect(X, Y, W, Hh);
+ g.strokeStyle = on ? '#b0562b' : '#333'; g.strokeRect(X, Y, W, Hh);
+ if (movable(it)) { // a thick line along the front edge, so a turn shows
+ const k = ((Math.round(it.args[2] / 90) % 4) + 4) % 4;
+ const e = [[B[0], B[2], B[1], B[2]], [B[1], B[2], B[1], B[3]], [B[0], B[3], B[1], B[3]], [B[0], B[2], B[0], B[3]]][k];
+ g.lineWidth = 3; g.beginPath(); g.moveTo(...toC(e[0], e[1])); g.lineTo(...toC(e[2], e[3])); g.stroke(); g.lineWidth = 1;
+ }
+ if (W > 30) { g.fillStyle = '#111'; g.font = '11px system-ui'; g.textAlign = 'center'; g.fillText(it.fn, X + W / 2, Y + Hh / 2 + 4); }
+ });
+}
+function addBox() { // a catalogue item in the middle of the view, its front facing -y; then drag it into place
+ const s = document.createElement('select');
+ s.style.width = '100%';
+ s.add(new Option('Add furniture…', ''));
+ for (const [fn, [label]] of Object.entries(cat)) s.add(new Option(label, fn));
+ s.onchange = () => {
+ const [, w, d, kw] = cat[s.value], [x, y] = toP(cv.clientWidth / 2, cv.clientHeight / 2);
+ own().push({ fn: s.value, args: [x, y, 0], kw: { ...kw }, box: [x - w / 2, x + w / 2, y - d / 2, y + d / 2], solid: true, room: '' });
+ sel = { kind: 'item', i: items().length - 1 }; ui();
+ };
+ return s;
+}
+function removeSel() {
+ if (sel.kind === 'item') own().splice(sel.i, 1);
+ else { snapshot(); F()[{ wall: 'walls', opening: 'openings', stair: 'stairs' }[sel.kind]].splice(sel.i, 1); }
+ sel = null; ui();
+}
+
// ---------------------------------------------------------------- drawing
function rectC(r) { const [a, b] = toC(r[0], r[3]), [c, d] = toC(r[1], r[2]); return [a, b, c - a, d - b]; }
// floor j's plan coordinates -> the current floor's (both are measured from their own lower-left corner)
@@ -153,6 +227,7 @@ function draw() {
// the other plans on this sheet stay visible (faded); click one to edit it
plan.floors.forEach((o, j) => { if (j !== fi && (o.page || 1) === (f.page || 1)) drawFloor(o, ...offsetOf(j), false); });
drawFloor(f, 0, 0, true);
+ if (tool === 'furniture') drawItems();
if (drag?.preview) { g.strokeStyle = '#000'; g.setLineDash([4, 3]); g.strokeRect(...rectC(drag.preview)); g.setLineDash([]); }
for (const p of scalePts) { const [x, y] = toC(...p); g.fillStyle = '#b0562b'; g.beginPath(); g.arc(x, y, 5, 0, 7); g.fill(); }
}
@@ -167,9 +242,14 @@ function ui() {
? 'read from room sizes' : src === 'user' ? 'set by you' : 'GUESSED - use Set scale'}`;
const P = $('props');
P.innerHTML = '';
+ if (!sel && tool === 'furniture') {
+ P.innerHTML = `<h3>Furniture</h3><p class="muted" style="font-size:13px">${!$('furn').checked
+ ? 'Furnish the rooms is off: the house is built empty' : auto ? `${items().length} items on this floor` : 'Loading…'}</p>`;
+ if (ready()) P.appendChild(addBox());
+ draw(); return;
+ }
if (!sel) { P.innerHTML = `<h3>Selection</h3><p class="muted" style="font-size:13px">${f.walls.length} walls, ${f.openings.length} openings, ${f.rooms.length} rooms</p>`; draw(); return; }
const h = document.createElement('div');
- const del = () => { snapshot(); f[{ wall: 'walls', opening: 'openings', stair: 'stairs' }[sel.kind]].splice(sel.i, 1); sel = null; ui(); };
if (sel.kind === 'wall') {
const w = f.walls[sel.i];
h.innerHTML = `<h3>Wall</h3><div class="row"><span>${(Math.max(w[1] - w[0], w[3] - w[2])).toFixed(1)} ft long</span>
@@ -193,12 +273,25 @@ function ui() {
} else if (sel.kind === 'stair') {
h.innerHTML = '<h3>Stair flight</h3>';
P.appendChild(h);
+ } else if (sel.kind === 'item') {
+ const it = items()[sel.i];
+ h.innerHTML = '<h3>Furniture</h3><p class="muted" style="font-size:13px"></p>';
+ h.querySelector('p').textContent = [cat[it.fn]?.[0] || it.fn, it.room, movable(it) ? '' : 'Fixed to the wall: delete only']
+ .filter(Boolean).join(' · ');
+ P.appendChild(h);
+ if (movable(it)) {
+ const b = document.createElement('button');
+ b.className = 'btn ghost'; b.textContent = 'Rotate 90°'; b.style.margin = '0 8px 0 0';
+ b.onclick = () => { rotateItem(own()[sel.i]); ui(); };
+ P.appendChild(b);
+ }
}
if (sel.kind !== 'room') {
const b = document.createElement('button');
- b.className = 'btn ghost'; b.textContent = 'Delete'; b.style.marginTop = '8px'; b.onclick = del;
+ b.className = 'btn ghost'; b.textContent = 'Delete'; b.style.marginTop = '8px'; b.onclick = removeSel;
P.appendChild(b);
}
+ if (tool === 'furniture' && ready()) P.appendChild(addBox());
draw();
}
$('fname').oninput = (e) => { F().name = e.target.value; document.querySelectorAll('#tabs button')[fi].textContent = e.target.value; };
@@ -211,20 +304,21 @@ const HINT = {
door: 'Click on a wall where the door should be (3 ft wide).',
window: 'Click on a wall where the window should be (4 ft wide).',
scale: 'Click two points a known distance apart, then type that distance.',
+ furniture: 'Drag furniture to move it, click it to turn or delete it, add more from the list. Drag elsewhere to pan.',
};
let scalePts = [];
document.querySelectorAll('#tools button[data-t]').forEach((b) => b.onclick = () => {
- tool = b.dataset.t; scalePts = [];
+ tool = b.dataset.t; scalePts = []; sel = null;
document.querySelectorAll('#tools button[data-t]').forEach((x) => x.classList.toggle('on', x === b));
$('hint').textContent = HINT[tool];
- draw();
+ if (tool === 'furniture') loadFurniture();
+ ui();
});
+$('furn').onchange = () => { if (tool === 'furniture') loadFurniture(); };
$('undo').onclick = () => { if (history.length) { plan = JSON.parse(history.pop()); sel = null; ui(); } };
addEventListener('keydown', (e) => {
if (e.target.tagName === 'INPUT') return;
- if ((e.key === 'Delete' || e.key === 'Backspace') && sel && sel.kind !== 'room') {
- snapshot(); F()[{ wall: 'walls', opening: 'openings', stair: 'stairs' }[sel.kind]].splice(sel.i, 1); sel = null; ui();
- }
+ if ((e.key === 'Delete' || e.key === 'Backspace') && sel && sel.kind !== 'room') removeSel();
if (e.key === 'z' && (e.ctrlKey || e.metaKey)) $('undo').onclick();
});
@@ -254,6 +348,7 @@ function rescale(k) {
(f.stairs || []).forEach((s) => { R(s.rect); s.words = s.words.map(([t, x, y]) => [t, x * k, y * k]); });
(f.labels || []).forEach((l) => { l.at = l.at.map((v) => v * k); });
f.size = f.size.map((v) => v * k);
+ delete f.items; // hand-placed furniture no longer matches the drawing: the rules place it again
f.scale_pt_per_ft = scaleOf(f) / k;
f.scale_source = 'user';
}
@@ -264,12 +359,24 @@ cv.addEventListener('pointerdown', (e) => {
cv.setPointerCapture(e.pointerId);
const [x, y] = toP(e.offsetX, e.offsetY);
drag = { X: e.offsetX, Y: e.offsetY, x, y, moved: false };
+ if (tool === 'furniture') {
+ sel = pickItem(x, y);
+ drag.item = sel && movable(items()[sel.i]);
+ ui();
+ }
});
cv.addEventListener('pointermove', (e) => {
if (!drag) return;
const dx = e.offsetX - drag.X, dy = e.offsetY - drag.Y;
if (Math.hypot(dx, dy) > 4) drag.moved = true;
- if (tool === 'select' && drag.moved) { view.ox += e.movementX; view.oy += e.movementY; draw(); }
+ if ((tool === 'select' || tool === 'furniture' && !drag.item) && drag.moved) { view.ox += e.movementX; view.oy += e.movementY; draw(); }
+ if (tool === 'furniture' && drag.item && drag.moved) {
+ const [x, y] = toP(e.offsetX, e.offsetY), list = drag.owned ? F().items : own(); // one undo step per drag
+ drag.owned = true;
+ moveItem(list[sel.i], x - drag.x, y - drag.y);
+ drag.x = x; drag.y = y;
+ draw();
+ }
if (tool === 'wall' && drag.moved) {
const [x, y] = toP(e.offsetX, e.offsetY), t = wallT() / 2;
drag.preview = Math.abs(x - drag.x) > Math.abs(y - drag.y)
@@ -307,7 +414,9 @@ cv.addEventListener('pointerup', (e) => {
const meas = Math.hypot(scalePts[1][0] - scalePts[0][0], scalePts[1][1] - scalePts[0][1]);
const real = parseFeet(prompt(`Measured ${meas.toFixed(2)} ft on the drawing. Real distance (e.g. 12'6")?`, meas.toFixed(1)));
scalePts = [];
- if (real > 0 && meas > 0) { rescale(real / meas); fit(); ui(); } else draw();
+ const ok = real > 0 && meas > 0 && (!plan.floors.some((o) => o.items)
+ || confirm('The furniture you placed will be placed again by the rules at the new scale. Go on?'));
+ if (ok) { rescale(real / meas); fit(); ui(); } else draw();
}
}
});