Skip to content

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

Python

Realistic room photos rendered with Cycles; furniture models in the review page

23f2005639d623c63c7612
diff --git a/AGENTS.md b/AGENTS.md
index 5f0f9f7..fc58956 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,11 +25,13 @@ Needs Python 3, Node 18+, Blender 4.2+ and poppler. If Blender is not on `PATH`,
| `blender/gen.py` | plan JSON -> house (run inside Blender). `CALLS` maps item `fn` to the function that builds it |
| `blender/lib.py` | materials, box meshes, furniture parts. Feet in, metres out (`F = 0.3048`) |
| `blender/bake.py` | light maps (Cycles) and `house.glb` export |
+| `blender/photos.py` | optional realistic room photos (Cycles) from `house_baked.blend`, run by the server after the build |
| `web/` | `index.html` (upload), `edit.html` + `edit.js` (review), `view.html` + `view.js` (walkthrough), `walk.js` (collision, stairs, start point), `furniture.html` |
| `examples/` | `sample_plan.pdf`, its generator `make_sample.py`, `embed.html` |
| `tools/` | video and debugging helpers, not used by the server |
Flow: upload -> `run_detect` -> `plan.json` -> review page edits it -> `POST …/build` -> `gen.py` -> `bake.py` -> `house.glb`, `meta.json`, light maps -> `view.js`.
+With `"photos": true` the server then runs `photos.py`, which writes `photos/*.jpg` and the job's `photos` list.
## Conventions
diff --git a/README.md b/README.md
index cba1739..6bebe3d 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,7 @@ flowchart LR
| 3D | `blender/gen.py` | Walls with openings cut, sills and lintels, frames and glass, floors per room type, stairs, roof with parapet, site with road and trees |
| Lighting | `blender/bake.py` | Cycles bakes direct and bounced light into one light map per storey. The browser multiplies textures by it: no real-time lights, so it runs on any GPU |
| Viewer | `web/view.js` | three.js, unlit materials, wall collision, stairs between storeys |
+| Photos | `blender/photos.py` | Optional: Cycles renders each room from the corner that best shows its main piece of furniture |
## Quick start
@@ -92,6 +93,8 @@ python server.py
| **Your own furniture** | The Furniture models page shows each item and lets you replace it with your `.glb` model |
| **Sample plan, delete** | "Try the sample plan" on the home page; every plan in the list has Delete |
| **Blender file** | The house as one `.blend` with every texture packed inside, in a zip |
+| **Realistic photos** | Tick **Realistic photos** on the review page: after the build, Blender's Cycles engine renders a photo of every room (about 40 s per room on an RTX 3050). **Photos** in the walkthrough shows them |
+| **Furniture models in the review page** | **Change furniture models** opens the furniture page in a window, so you can swap a model and then build |
### Your own furniture
@@ -99,6 +102,8 @@ python server.py
|---|---|
| ![Furniture page](docs/furniture.png) | ![Custom sofa](docs/custom_sofa.png) |
+**Which renderer does what.** The walkthrough runs in the browser with three.js. Its light and shadows are computed once by Blender's Cycles engine and baked into light maps, so walking is smooth on any GPU but reflections and glossy highlights are not shown. Realistic photos are full Cycles renders: real reflections, soft shadows and bounced light, at the cost of extra build time. EEVEE is only used for the small pictures on the furniture page.
+
## Build time and accuracy
Measured on a laptop with an RTX 3050 (4 GB).
@@ -153,7 +158,7 @@ sequenceDiagram
| `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}/build` | Body `{ "quality": "draft" \| "high" }`. Builds run one at a time |
+| `POST /api/jobs/{id}/build` | Body `{ "quality": "draft" \| "high", "photos": true }`. Builds run one at a time. With `photos`, the job's `photos` list names the files in `/jobs/{id}/photos/` |
| `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 |
| `GET /web/edit.html?job={id}` | The review page |
@@ -172,7 +177,7 @@ vector.py PDF lines, curves, fills and words (poppler)
furnish.py furniture rules (pure Python)
catalog.py furniture that can be replaced by your own models
fetch_assets.py downloads the CC0 textures, models and sky
-blender/ gen.py (build), bake.py (light maps), lib.py (parts), cinema.py (video renderer)
+blender/ gen.py (build), bake.py (light maps), lib.py (parts), photos.py (Cycles room photos), cinema.py (video)
web/ home, review and walkthrough pages
examples/ sample_plan.pdf, its generator, embed.html
tests/ detector, furniture, walking and browser tests
diff --git a/blender/photos.py b/blender/photos.py
new file mode 100644
index 0000000..b8b563d
--- /dev/null
+++ b/blender/photos.py
@@ -0,0 +1,111 @@
+"""Realistic photos of a built house, rendered with Cycles (path tracing: real light, reflections, soft shadows).
+blender -b JOB/house_baked.blend -P blender/photos.py -- JOB [--samples 128] [--res 1920x1080]
+One JPEG per room in JOB/photos/, taken from the spot in the room with the clearest view of it.
+Progress lines: 'PROGRESS <0-100> <message>'; 'PHOTO <file> <room label>' for each picture; 'PHOTOS OK' at the end."""
+import json, math, os, re, sys
+import bpy
+from mathutils import Vector
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import bake # noqa: E402
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+JOB = os.path.abspath(argv[0])
+SAMPLES = int(argv[argv.index("--samples") + 1]) if "--samples" in argv else 128
+RES = [int(v) for v in argv[argv.index("--res") + 1].split("x")] if "--res" in argv else [1920, 1080]
+ROOMS = {"bedroom", "living", "dining", "kitchen", "toilet", "study", "puja", "room", "dress", "balcony"}
+EYE = 1.5 # metres above the floor
+
+meta = json.load(open(os.path.join(JOB, "meta.json")))
+out = os.path.join(JOB, "photos")
+os.makedirs(out, exist_ok=True)
+for f in os.listdir(out): # a rebuild replaces the old set
+ os.remove(os.path.join(out, f))
+
+sc = bpy.context.scene
+bake._gpu(sc)
+sc.cycles.samples, sc.cycles.use_adaptive_sampling, sc.cycles.use_denoising = SAMPLES, True, True
+sc.cycles.max_bounces, sc.cycles.diffuse_bounces = 8, 4
+sc.render.resolution_x, sc.render.resolution_y, sc.render.resolution_percentage = *RES, 100
+sc.render.image_settings.file_format, sc.render.image_settings.quality = "JPEG", 92
+sc.view_settings.exposure = 0.6 # rooms are lit for the light maps, which are normalised; photos are not
+cam = bpy.data.objects.new("photo_cam", bpy.data.cameras.new("photo_cam"))
+sc.collection.objects.link(cam)
+sc.camera = cam
+dg = bpy.context.evaluated_depsgraph_get()
+
+
+def ray(o, d, far):
+ hit, loc, *_ = sc.ray_cast(dg, o, d.normalized(), distance=far)
+ return (loc - o).length if hit else far
+
+
+def best_view(r, z, hero):
+ """camera spot in the room rectangle r (x0, x1, y0, y1): corners and wall middles, inset 0.35 m, whose eye is not
+ inside furniture. With a main piece of furniture (hero, its centre) the spot that sees it unblocked from about
+ 4 m wins and the camera looks between it and the room centre; otherwise the spot that sees farthest.
+ -> (position, target) or None"""
+ x0, x1, y0, y1 = r
+ c = Vector(((x0 + x1) / 2, (y0 + y1) / 2, z + 1.0))
+ t = c if hero is None else Vector((hero[0], hero[1], z + 0.8)).lerp(c, 0.35)
+ i = 0.35
+ spots = [(x, y) for x in (x0 + i, x1 - i) for y in (y0 + i, y1 - i)] + \
+ [((x0 + x1) / 2, y0 + i), ((x0 + x1) / 2, y1 - i), (x0 + i, (y0 + y1) / 2), (x1 - i, (y0 + y1) / 2)]
+ best, score = None, -1e9
+ for x, y in spots:
+ p = Vector((x, y, z + EYE))
+ if ray(p, Vector((0, 0, -1)), EYE + 0.1) < EYE - 0.05: # standing on a bed or a counter
+ continue
+ d = t - p
+ a0 = math.atan2(d.y, d.x)
+ s = sum(ray(p, Vector((math.cos(a0 + math.radians(a)), math.sin(a0 + math.radians(a)), -0.15)), 30)
+ for a in (-40, -20, 0, 20, 40)) / 5
+ if hero is not None:
+ h = Vector((hero[0], hero[1], z + 0.8))
+ seen = ray(p, h - p, 30) >= (h - p).length - 1.2 # nothing in the way but the item itself
+ s = (10 if seen else 0) - abs((h - p).length - 4.0) + 0.1 * s
+ if s > score:
+ best, score = (p, t), s
+ return best
+
+
+def heroes():
+ """centre (m) and floor area of the largest piece of furniture in each storey, from the same rules the build used"""
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+ import furnish
+ plan = json.load(open(os.path.join(JOB, "plan.json")))
+ out = []
+ for f in plan["floors"]:
+ items = [] if plan.get("furnish") is False else f.get("items") or furnish.furnish_floor(f)
+ out.append([((b[0] + b[1]) / 2 * 0.3048, (b[2] + b[3]) / 2 * 0.3048, (b[1] - b[0]) * (b[3] - b[2]))
+ for b in (it.get("box") for it in items if it["fn"] not in SMALL) if b])
+ return out
+
+
+SMALL = {"rug", "round_rug", "wall_cab2", "chimney", "geyser", "model", "plant", "nightstand"}
+HEROES = heroes()
+
+
+photos = []
+todo = [(f, rm) for f in meta["floors"] for rm in f["rooms"] if rm["type"] in ROOMS]
+for k, (f, rm) in enumerate(todo):
+ r = max(rm["rects"], key=lambda q: (q[1] - q[0]) * (q[3] - q[2]))
+ if (r[1] - r[0]) * (r[3] - r[2]) < 2.5: # m²: cupboards and ducts
+ continue
+ fi = meta["floors"].index(f)
+ inside = [h for h in (HEROES[fi] if fi < len(HEROES) else []) if r[0] <= h[0] <= r[1] and r[2] <= h[1] <= r[3]]
+ view = best_view(r, f["z"], max(inside, key=lambda h: h[2])[:2] if inside else None)
+ if not view:
+ continue
+ print(f"PROGRESS {int(100 * k / len(todo))} photographing {rm['label']} ({k + 1} of {len(todo)})", flush=True)
+ p, t = view
+ cam.location = p
+ cam.rotation_euler = (t - p).to_track_quat("-Z", "Y").to_euler()
+ cam.data.lens = 14 if min(r[1] - r[0], r[3] - r[2]) < 2.5 else 18 # narrow rooms need a wider lens
+ name = f"{len(photos) + 1:02d}_{re.sub(r'[^a-z0-9]+', '_', rm['label'].lower()).strip('_') or rm['type']}.jpg"
+ sc.render.filepath = os.path.join(out, name)
+ bpy.ops.render.render(write_still=True)
+ photos.append(name)
+ print(f"PHOTO {name} {f['name']} · {rm['label']}", flush=True)
+print("PROGRESS 100 photos done", flush=True)
+print("PHOTOS OK", flush=True)
diff --git a/server.py b/server.py
index f1f887a..ba78b38 100644
--- a/server.py
+++ b/server.py
@@ -186,34 +186,76 @@ def estimate(jid, quality):
return st["build_seconds"] * n / (len(st.get("floors") or [1]) + 1)
+def photo_estimate(jid):
+ """seconds for the realistic photos: one per room, timed on the last house that had them (40 s each until then)"""
+ rooms = sum(1 for f in (json.load(open(os.path.join(jdir(jid), "plan.json")))["floors"]) for r in f["rooms"]
+ if r["type"] in PHOTO_ROOMS)
+ past = [st for st in (read_status(j) for j in os.listdir(JOBS) if ID.match(j)) if st and st.get("photo_seconds")]
+ if not past:
+ return rooms * 40
+ st = max(past, key=lambda s: s["updated"])
+ return rooms * st["photo_seconds"] / max(1, len(st.get("photos") or []))
+
+
+PHOTO_ROOMS = {"bedroom", "living", "dining", "kitchen", "toilet", "study", "puja", "room", "dress", "balcony"} # as in blender/photos.py
+
+
+def run_blender(cmd, log, on_line):
+ """run Blender, copy its output to log, hand every line to on_line; killed after BUILD_TIMEOUT"""
+ pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
+ watchdog = threading.Timer(BUILD_TIMEOUT, pr.kill) # a hung Blender must not block every later build
+ watchdog.start()
+ try:
+ for line in pr.stdout:
+ log.write(line)
+ on_line(line)
+ pr.wait()
+ finally:
+ watchdog.cancel()
+
+
def builder():
while True:
- jid, quality = builds.get()
+ jid, quality, photos = builds.get()
d = jdir(jid)
try:
t0 = time.time()
- status(jid, stage="building", progress=1, message="Starting Blender", started=t0, eta_total=estimate(jid, quality))
+ shutil.rmtree(os.path.join(d, "photos"), ignore_errors=True) # photos of the old build would not match
+ share = 60 if photos else 100 # % of the progress bar for the build; the photos get the rest
+ status(jid, stage="building", progress=1, message="Starting Blender", started=t0, photos=None, want_photos=photos,
+ eta_total=estimate(jid, quality) + (photo_estimate(jid) if photos else 0))
cmd = [BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
os.path.join(d, "plan.json"), d, "--quality", quality]
+ ok = []
+
+ def gen_line(line):
+ m = re.match(r"PROGRESS (\d+) (.*)", line)
+ if m:
+ status(jid, progress=int(m.group(1)) * share // 100, message=m.group(2).strip())
+ if line.startswith("GEN OK"):
+ ok.append(1)
with open(os.path.join(d, "build.log"), "w") as log:
- pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
- watchdog = threading.Timer(BUILD_TIMEOUT, pr.kill) # a hung Blender must not block every later build
- watchdog.start()
- ok = False
- for line in pr.stdout:
- log.write(line)
- m = re.match(r"PROGRESS (\d+) (.*)", line)
- if m:
- status(jid, progress=int(m.group(1)), message=m.group(2).strip())
- ok = ok or line.startswith("GEN OK")
- pr.wait()
- watchdog.cancel()
+ run_blender(cmd, log, gen_line)
if not ok or not os.path.exists(os.path.join(d, "house.glb")):
raise RuntimeError("3D build failed - see build.log")
for f in ("house.blend", "house.blend1", "house_baked.blend1"): # keep house_baked.blend only
if os.path.exists(os.path.join(d, f)):
os.remove(os.path.join(d, f))
- status(jid, stage="done", progress=100, message="Ready", quality=quality, build_seconds=round(time.time() - t0))
+ done = dict(quality=quality, build_seconds=round(time.time() - t0))
+ if photos:
+ t1, names = time.time(), []
+
+ def photo_line(line):
+ m = re.match(r"PROGRESS (\d+) (.*)", line)
+ if m:
+ status(jid, progress=share + int(m.group(1)) * (100 - share) // 100, message=m.group(2).strip())
+ if line.startswith("PHOTO "):
+ names.append(line.split()[1])
+ with open(os.path.join(d, "photos.log"), "w") as log: # a failed photo still leaves a usable house
+ run_blender([BLENDER, "-b", os.path.join(d, "house_baked.blend"), "-P",
+ os.path.join(HERE, "blender", "photos.py"), "--", d], log, photo_line)
+ done.update(photos=names, photo_seconds=round(time.time() - t1))
+ status(jid, stage="done", progress=100, message="Ready", **done)
except Exception as e:
traceback.print_exc()
status(jid, stage="failed", message=str(e))
@@ -296,7 +338,7 @@ class H(BaseHTTPRequestHandler):
st = read_status(m.group(1))
if st and st.get("stage") == "building" and st.get("started"): # counted here: the viewer's clock may differ
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
+ st["eta_left"] = max(0, round(min(left, 15) if st.get("message") == "exporting model" and not st.get("want_photos") else left)) # the build's last step
return self.send(200 if st else 404, st or {"error": "no such job"})
if p == "/api/system":
return self.send(200, system())
@@ -394,10 +436,10 @@ class H(BaseHTTPRequestHandler):
with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
json.dump(plan, fh)
return self.send(200, {"ok": True})
- q = json.loads(self.body() or b"{}").get("quality", "high")
- q = q if q in ("draft", "high") else "high"
+ req = json.loads(self.body() or b"{}")
+ q = req.get("quality") if req.get("quality") in ("draft", "high") else "high"
status(jid, stage="queued", progress=0, message=f"Waiting for the 3D builder ({builds.qsize()} ahead)")
- builds.put((jid, q))
+ builds.put((jid, q, req.get("photos") is True))
return self.send(200, {"ok": True})
self.send(404, {"error": "not found"})
except (ValueError, json.JSONDecodeError) as e:
diff --git a/tests/test_site.mjs b/tests/test_site.mjs
index 1c40bf1..c56e600 100644
--- a/tests/test_site.mjs
+++ b/tests/test_site.mjs
@@ -62,6 +62,13 @@ try {
await cdp('Page.navigate', { url: `${base}/web/edit.html?job=${job}` });
for (let i = 0; i < 150 && (await ev(`getComputedStyle(document.getElementById('wait')).display`)) !== 'none'; i++) await sleep(200);
assert.equal(await ev(`document.getElementById('furn').checked`), false, 'Furniture box should stay unticked after reload');
+ // the furniture models page opens inside the review page
+ await ev(`document.getElementById('models').click()`);
+ let cards = 0;
+ for (let i = 0; i < 50 && !cards; i++) { await sleep(200); cards = await ev(`document.getElementById('modelsframe').contentDocument?.querySelectorAll('#list figure').length || 0`); }
+ assert(cards >= 10 && await ev(`document.getElementById('modelsdlg').open`), 'Change furniture models should show the models in a dialog');
+ assert.equal(await ev(`!!document.getElementById('modelsframe').contentDocument.getElementById('brand')`), false, 'no Home link inside the dialog');
+ await ev(`document.getElementById('modelsdlg').close()`);
// walkthrough: screenshot (P) and recording (R) land in the downloads folder
const dl = fs.mkdtempSync(path.join(os.tmpdir(), 'planto3d-'));
const key = async (code, vk) => { for (const type of ['keyDown', 'keyUp']) await cdp('Input.dispatchKeyEvent', { type, code, key: code.slice(3).toLowerCase(), windowsVirtualKeyCode: vk }); };
@@ -99,7 +106,7 @@ try {
assert(ihdr.readUInt32BE(16) * ihdr.readUInt32BE(20) >= 0.95 * 3840 * 2160, 'screenshot should be about 4K');
assert(fs.statSync(path.join(dl, vid)).size > 100e3, 'recording should not be empty');
fs.rmSync(dl, { recursive: true });
- console.log('PASS upload page, furniture option, build box, screenshot, recording, map and top view');
+ console.log('PASS upload page, furniture option, furniture models dialog, build box, screenshot, recording, map and top view');
} finally {
ch.kill();
if (job) fs.rmSync(new URL(`../jobs/${job}`, import.meta.url), { recursive: true, force: true }); // the test's own upload
diff --git a/web/edit.html b/web/edit.html
index ab91c19..3ac0fe6 100644
--- a/web/edit.html
+++ b/web/edit.html
@@ -43,7 +43,7 @@
<div class="tabs" id="tabs"></div>
<span class="muted" id="scale"></span>
<span style="flex:1"></span>
- <label title="Untick to build empty rooms: walls, floors, doors, windows and lights only"><input type="checkbox" id="furn" checked> Furniture</label>
+ <label title="After the 3D build, Blender's Cycles engine renders a realistic photo of every room. About a minute more per room."><input type="checkbox" id="photos"> Realistic photos</label>
<select id="quality" title="Quality">
<option value="draft">Draft (fast)</option>
<option value="high" selected>High quality</option>
@@ -68,6 +68,11 @@
<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>
</div>
<div id="props"></div>
+ <div>
+ <h3>Furniture</h3>
+ <label title="Untick to build empty rooms: walls, floors, doors, windows and lights only"><input type="checkbox" id="furn" checked> Furnish the rooms</label>
+ <button class="btn ghost" id="models" type="button" style="margin-top:8px;width:100%">Change furniture models</button>
+ </div>
<div>
<h3>Floor</h3>
<div class="row"><span>Name</span><input type="text" id="fname" style="width:150px"></div>
@@ -84,9 +89,14 @@
<p id="bfun" hidden><svg id="bspin" viewBox="0 0 24 24" aria-hidden="true"><path pathLength="100" d="M3 11 12 3l9 8M5 9.5V21h14V9.5M10 21v-6h4v6"/></svg><span id="bword"></span></p>
<p id="bmsg" class="muted" style="font-size:13px;margin-top:4px"></p>
<a class="btn" id="open" hidden>Open walkthrough</a>
+ <a class="btn ghost" id="openphotos" hidden style="margin-left:6px">Photos</a>
</div>
</aside>
</main>
+<dialog id="modelsdlg" style="width:min(1000px,94vw);height:86vh;padding:0;border:1px solid var(--line);border-radius:12px;background:var(--bg)">
+ <form method="dialog" style="position:absolute;right:10px;top:8px"><button class="btn ghost">Close</button></form>
+ <iframe id="modelsframe" title="Furniture models" style="width:100%;height:100%;border:0"></iframe>
+</dialog>
<script type="module" src="/web/edit.js"></script>
</body>
</html>
diff --git a/web/edit.js b/web/edit.js
index 7856aa4..14f2345 100644
--- a/web/edit.js
+++ b/web/edit.js
@@ -72,11 +72,13 @@ function buildStatus(st) {
const left = st.stage === 'building' ? st.eta_left : null; // seconds, estimated from earlier builds on this machine
$('beta').textContent = left == null ? '' : left > 8 ? `about ${secs(left >= 90 ? left : Math.ceil(left / 5) * 5)} left` : 'almost done';
const took = st.stage === 'done' && st.build_seconds ? `built in ${secs(st.build_seconds)}` : '';
- const step = st.stage === 'building' && !/cooling/.test(st.message) ? '' : st.message; // Blender's step names stay out of sight
+ const step = st.stage === 'building' && !/cooling|photographing/.test(st.message) ? '' : st.message; // Blender's step names stay out of sight
$('bmsg').textContent = st.stage === 'failed' ? `Failed: ${st.message}` : [step, took].filter(Boolean).join(' · ');
$('bmsg').className = st.stage === 'failed' ? 'err' : 'muted';
$('open').hidden = st.stage !== 'done';
$('open').href = `/web/view.html?job=${job}`;
+ $('openphotos').hidden = !(st.stage === 'done' && st.photos?.length);
+ $('openphotos').href = `/web/view.html?job=${job}&photos`;
$('build').disabled = ['queued', 'building'].includes(st.stage);
if (['queued', 'building'].includes(st.stage)) setTimeout(() => fetch(`/api/jobs/${job}`).then((r) => r.json()).then(buildStatus), 1500);
}
@@ -322,9 +324,13 @@ $('build').onclick = async () => {
$('build').disabled = true;
plan.furnish = $('furn').checked;
let r = await fetch(`/api/jobs/${job}/plan`, { method: 'POST', body: JSON.stringify(plan) });
- if (r.ok) r = await fetch(`/api/jobs/${job}/build`, { method: 'POST', body: JSON.stringify({ quality: $('quality').value }) });
+ if (r.ok) r = await fetch(`/api/jobs/${job}/build`, { method: 'POST', body: JSON.stringify({ quality: $('quality').value, photos: $('photos').checked }) });
const j = await r.json();
if (!r.ok) { alert(j.error); $('build').disabled = false; return; }
buildStatus({ stage: 'queued', progress: 0, message: 'Queued' });
};
poll();
+$('models').onclick = () => { // the furniture page, inside this one: replace a model, then build
+ $('modelsframe').src = '/web/furniture.html?embed';
+ $('modelsdlg').showModal();
+};
diff --git a/web/furniture.html b/web/furniture.html
index 16d2acf..a113ecc 100644
--- a/web/furniture.html
+++ b/web/furniture.html
@@ -8,7 +8,7 @@
</head>
<body class="home">
<main class="wrap" style="max-width:960px">
- <p class="brand"><a href="/" style="color:inherit;text-decoration:none">PlanTo3D</a> · <a href="/">Home</a></p>
+ <p class="brand" id="brand"><a href="/" style="color:inherit;text-decoration:none">PlanTo3D</a> · <a href="/">Home</a></p>
<h1>Furniture models</h1>
<p class="muted">Each picture shows the item as houses are built with it now. Replace any of them with your own
<code>.glb</code> model: it is scaled to the item's footprint and stood on the floor. Model it with +Y up and its
@@ -19,6 +19,7 @@
</main>
<script>
const $ = (id) => document.getElementById(id);
+if (new URLSearchParams(location.search).has('embed')) $('brand').remove(); // shown inside the review page
const el = (tag, cls, text) => { const e = document.createElement(tag); e.className = cls; e.textContent = text; return e; };
let target = null;
async function load() {
diff --git a/web/view.html b/web/view.html
index b477759..6653de8 100644
--- a/web/view.html
+++ b/web/view.html
@@ -24,6 +24,13 @@
#bar button.live { background: #b3261e; border-color: #b3261e; color: #fff; }
#fps { color: #bbb; font-size: 12px; margin-left: auto; background: rgba(0,0,0,.4); padding: 4px 8px; border-radius: 6px; }
#floors { display: contents; }
+ #gallery { position: fixed; inset: 0; z-index: 20; background: rgba(12,13,15,.94); overflow: auto; padding: 56px 16px 24px; }
+ #gallery[hidden] { display: none; }
+ #gallery .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 420px), 1fr)); gap: 14px; max-width: 1500px; margin: auto; }
+ #gallery figure { margin: 0; color: #ddd; font-size: 13px; }
+ #gallery img { width: 100%; border-radius: 8px; display: block; }
+ #gallery figcaption { margin-top: 5px; text-transform: capitalize; }
+ #gallery button { position: fixed; top: 12px; right: 16px; background: #e8e1d3; color: #111; border: 0; border-radius: 6px; padding: 7px 12px; font-size: 13px; }
#map { position: fixed; right: 12px; bottom: 58px; width: 220px; height: 220px; border-radius: 12px; cursor: pointer;
background: rgba(14, 16, 20, .78); border: 1px solid rgba(255, 255, 255, .18); }
#map.big { right: 50%; bottom: 50%; transform: translate(50%, 50%); width: min(88vw, 88vh, 900px); height: min(88vw, 88vh, 900px);
@@ -46,9 +53,10 @@
<p class="desk"><kbd>P</kbd> screenshot · <kbd>R</kbd> start / stop recording · <kbd>M</kbd> map</p>
<p class="touch">Left thumb: move · right thumb: look</p>
</div>
+<div id="gallery" hidden><button id="closephotos">Close</button><div class="grid" id="photogrid"></div></div>
<div id="room"></div>
<div id="cross"></div>
-<div id="bar"><button id="topbtn">Top view</button><span id="floors"></span><button id="shot" title="Save a picture of this view (P)">Screenshot</button><button id="rec" title="Record a video of your walk (R)">Record</button><button id="blend" title="Download this house as a Blender file (.zip)">Blender file</button><a href="/" id="newplan" style="color:#ccc;font-size:13px">Home</a><span id="fps"></span></div>
+<div id="bar"><button id="topbtn">Top view</button><span id="floors"></span><button id="shot" title="Save a picture of this view (P)">Screenshot</button><button id="rec" title="Record a video of your walk (R)">Record</button><button id="blend" title="Download this house as a Blender file (.zip)">Blender file</button><button id="photosbtn" hidden title="Realistic photos of each room, rendered with Blender's Cycles engine">Photos</button><a href="/" id="newplan" style="color:#ccc;font-size:13px">Home</a><span id="fps"></span></div>
<script type="module" src="/web/view.js"></script>
</body>
</html>
diff --git a/web/view.js b/web/view.js
index 25ef7fc..1f0fecc 100644
--- a/web/view.js
+++ b/web/view.js
@@ -294,6 +294,27 @@ function toggleRec() {
$('rec').classList.add('live');
label();
}
+// realistic photos (Cycles), when the house was built with them: a gallery over the walkthrough
+fetch(`/api/jobs/${job}`).then((r) => r.json()).then((st) => {
+ const names = (st.photos || []).filter((n) => /^[\w.-]+\.jpg$/.test(n));
+ if (!names.length) return;
+ $('photogrid').replaceChildren(...names.map((n) => {
+ const fig = document.createElement('figure'), a = document.createElement('a'), im = new Image(), cap = document.createElement('figcaption');
+ a.href = im.src = `${base}photos/${n}`;
+ a.target = '_blank';
+ im.alt = cap.textContent = n.slice(3, -4).replace(/_/g, ' ');
+ im.loading = 'lazy';
+ a.append(im);
+ fig.append(a, cap);
+ return fig;
+ }));
+ $('photosbtn').hidden = false;
+ if (q.has('photos')) showPhotos();
+});
+function showPhotos() { document.exitPointerLock?.(); $('gallery').hidden = false; }
+$('photosbtn').onclick = showPhotos;
+$('closephotos').onclick = () => { $('gallery').hidden = true; };
+addEventListener('keydown', (e) => { if (e.code === 'Escape') $('gallery').hidden = true; });
$('blend').onclick = async () => { // the server packs the textures into one .blend (a few seconds, once per build)
const b = $('blend');
b.disabled = true;