Skip to content

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

Python

Interior themes: Minimalist, Royal and Rustic farmhouse, and your own

23f2005639bca97579114d
diff --git a/AGENTS.md b/AGENTS.md
index af4020e..329a36a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,7 +7,7 @@ There is no AI model in the pipeline: detection is geometry, furniture is rules,
```bash
./run.sh --port 8080 # npm install (three.js) + python3 server.py
-python3 fetch_assets.py # CC0 textures and models into assets/ (about 75 MB), once
+python3 fetch_assets.py # CC0 textures and models into assets/ (about 150 MB), once
```
Needs Python 3, Node 18+, Blender 4.2+ and poppler. If Blender is not on `PATH`, set `BLENDER` to its full path.
@@ -22,11 +22,12 @@ Needs Python 3, Node 18+, Blender 4.2+ and poppler. If Blender is not on `PATH`,
| `detect.py` | segments -> plan JSON: walls, openings, rooms, stairs, scale. Units: feet, y up |
| `furnish.py` | plan JSON -> furniture items `{fn, args, kw, box}`. Pure Python, no Blender |
| `quantities.py` | plan JSON -> areas, paint, tiles, doors, windows, furniture counts. Also holds `FLOOR_MAT` and `opening_heights`, which `gen.py` imports, so the sheet counts what is built |
-| `catalog.py` | furniture that people may replace with their own `.glb` (`assets/custom/<name>.glb`) |
+| `themes.py` | interior themes: `LIBRARY` (Poly Haven models with their measured sizes and turn), `STYLES` (pieces gen.py draws), `THEMES` (built-in), `check`/`load` for people's own (`assets/themes/<id>.json`, uploads in `assets/themes/<id>/<slot>.glb`) |
+| `catalog.py` | built-in pieces' default footprints, and `preview_plan(theme)`: the row of a theme's pieces that `blender/thumbs.py` photographs |
| `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 |
-| `web/` | `index.html` (upload), `edit.html` + `edit.js` (review), `view.html` + `view.js` (walkthrough), `walk.js` (collision, stairs, start point), `furniture.html` |
+| `web/` | `index.html` (upload), `edit.html` + `edit.js` (review), `view.html` + `view.js` (walkthrough), `walk.js` (collision, stairs, start point), `themes.html` |
| `examples/` | `sample_plan.pdf`, its generator `make_sample.py`, `embed.html` |
| `tools/` | video and debugging helpers, not used by the server |
@@ -46,7 +47,7 @@ Flow: upload -> `run_detect` -> `plan.json` -> review page edits it -> `POST …
## Tests: run them before you finish
```bash
-tests/run_all.sh # detector on the sample, server guards, furniture clashes, stair and wall walking
+tests/run_all.sh # detector on the sample, quantities, themes, server guards, furniture clashes, stair and wall walking
python3 tests/test_sample.py # the sample must be read exactly
CHROME=/path/to/chromium node tests/test_site.mjs examples/sample_plan.pdf http://127.0.0.1:8080
```
@@ -57,8 +58,11 @@ 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` 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 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.
+- **A model for the themes:** measure it as Blender imports it (feet, front facing -y after `turn`), add it to `themes.LIBRARY` with the slots it may fill; `fetch_assets.py` downloads every library model. Large ones: keep it under about 30k triangles.
+- **A new theme:** an entry in `themes.THEMES`. Furniture rules read only sizes from it (`Room.sizes`), so a model that does not fit falls back to the built-in piece in the theme's colours. Check it with `tests/test_themes.py` and look at a build: rules can be right and a room still look wrong.
+- **A new built-in piece style:** a `style=` branch in its builder, listed in `themes.STYLES`. New materials go in `lib.py`; a coloured one goes in `PAINT` in `gen.py` so themes repaint it.
+- **A new room type:** add its keywords to `ROOM_TYPES` in `detect.py`, a rule in `furnish.py`, a floor material in `quantities.py` (`FLOOR_MAT`, and `INDOOR` in `furnish.py`), 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`.
- **A new texture or model:** add its Poly Haven name to `fetch_assets.py`; never commit asset files.
diff --git a/README.md b/README.md
index e1a3364..89c568c 100644
--- a/README.md
+++ b/README.md
@@ -51,7 +51,7 @@ git clone <this repo> && cd planto3d
./run.sh # installs three.js, serves http://127.0.0.1:8080
```
-Open the page. It checks Blender, the PDF tools, the viewer library and the materials, and accepts a plan only when all four are in place. The textures and models (about 75 MB, CC0, from [Poly Haven](https://polyhaven.com)) are not in the repository: press **Download materials** on the page, or run `python3 fetch_assets.py`.
+Open the page. It checks Blender, the PDF tools, the viewer library and the materials, and accepts a plan only when all four are in place. The textures and models (about 150 MB, CC0, from [Poly Haven](https://polyhaven.com)) are not in the repository: press **Download materials** on the page, or run `python3 fetch_assets.py`.
Then press **Try the sample plan**, or drop your own PDF on the page.
@@ -86,7 +86,9 @@ 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 |
-| **Floor finish and wall paint** | Pick a room's floor (marble, wood, tiles, bathroom tiles, terracotta, concrete; Auto follows the room type) and one wall colour for the house. Saved in the plan as `room.floor` and `wall_color` (`#rrggbb`) |
+| **Interior themes** | Pick a theme on the review page: **Contemporary** (the look PlanTo3D always built), **Minimalist**, **Royal** (a European palace) or **Rustic farmhouse**. A theme sets the furniture, the decor (chandeliers, paintings, mirrors, an armchair, a clock or shelves, a bench at the foot of the bed), the colours of wood, fabrics, curtains, rugs and kitchen, and the floors and walls. Saved in the plan as `theme` |
+| **Your own themes** | **See and make themes** shows every theme's pieces as real renders. Make your own from any theme: choose each piece from the library of scanned models or the built-in ones, or use your own `.glb`, and set the colours and floors |
+| **Floor finish and wall paint** | Pick a room's floor (marble, wood, parquet, tiles, bathroom tiles, terracotta, concrete; Auto follows the theme, then the room type) and one wall colour for the house. Saved in the plan as `room.floor` and `wall_color` (`#rrggbb`); both win over the theme |
| **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 |
@@ -99,18 +101,22 @@ python server.py
| **Screenshot** (P) | PNG of about 4K size |
| **Record** (R) | Video of your walk as MP4 (browsers that record WebM are converted on the server; needs ffmpeg) |
| **Tour** (G) | Walks itself from the entrance through every room and up the stairs, looks around in each, and records it as one video. Any key or click stops it |
-| **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 |
| **Quantities** | A printable sheet from the review page or the walkthrough: floor area per finish, wall paint (less doors and windows), ceiling, toilet wall tiles, a door and window schedule with sizes, and a furniture count. In m² and sq ft |
| **Blender file** | The house as one `.blend` with every texture packed inside, in a zip |
| **Website** | The walkthrough as a static website in a zip, to share without this server (see below) |
-| **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
+### Interior themes
-| Furniture models page | A replaced sofa in a built house |
-|---|---|
-| ![Furniture page](docs/furniture.png) | ![Custom sofa](docs/custom_sofa.png) |
+![The same living room in Minimalist, Royal and Rustic farmhouse](docs/themes.jpg)
+
+<sub>The sample plan's living room in Minimalist, Royal and Rustic farmhouse, as the walkthrough shows it.</sub>
+
+| The Themes page |
+|---|
+| ![Themes page](docs/themes_page.jpg) |
+
+Most theme furniture is real scanned models from [Poly Haven](https://polyhaven.com) (CC0): the carved four-poster bed, chandeliers, gilded mirror and grandfather clock of Royal, the painted farmhouse cabinets and settee of Rustic, the oak side tables and globe lamps of Minimalist. Pieces Poly Haven does not have (the minimalist platform bed and wardrobe, the royal armoire and turned-leg table, the farmhouse bed and plank table) are drawn by `blender/gen.py` from photo textures. Where a model does not fit a room, the furniture rules use the built-in piece in the theme's colours instead.
**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.
@@ -177,7 +183,9 @@ sequenceDiagram
| `GET /web/edit.html?job={id}` | The review page |
| `GET /api/jobs` | The 30 most recent plans |
| `DELETE /api/jobs/{id}` | Delete a plan and its house |
-| `GET /api/furniture` | Replaceable items; `POST /api/furniture/{name}` (a `.glb`) replaces one, `DELETE` restores it |
+| `GET /api/themes` | The themes: built-in and your own, with their pieces, colours, floors and pictures, and what each piece may be |
+| `POST /api/themes` | Make your own theme: `{ label, slots, colours, floors, wall, tv }`; returns `{ id }`. `POST /api/themes/{id}` changes it, `DELETE` removes it |
+| `POST /api/themes/{id}/model/{slot}` | Your `.glb` for one piece of your own theme; `DELETE` goes back to the built-in piece |
To let people correct the plan first, show `/web/edit.html?job={id}` in the iframe instead of building straight away.
@@ -197,7 +205,8 @@ detect.py plan PDF -> plan JSON
vector.py PDF lines, curves, fills and words (poppler)
furnish.py furniture rules (pure Python)
quantities.py areas, paint, tiles, doors, windows and furniture counts (pure Python)
-catalog.py furniture that can be replaced by your own models
+themes.py interior themes: the model library, the built-in themes, checks for your own
+catalog.py the built-in pieces' sizes and the preview row the Themes page photographs
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)
web/ home, review and walkthrough pages
diff --git a/blender/gen.py b/blender/gen.py
index f7edc8f..9272bd0 100644
--- a/blender/gen.py
+++ b/blender/gen.py
@@ -16,7 +16,7 @@ from lib import * # noqa: E402,F401
import lib # noqa: E402
import furnish # noqa: E402
from quantities import FLOOR_MAT, TILE_H, opening_heights, zone_at # noqa: E402 (shared with the quantities sheet)
-from catalog import CATALOG # noqa: E402
+import themes # noqa: E402
from mathutils import Vector # noqa: E402
@@ -30,6 +30,7 @@ FFH = H + SLAB
lib.WALL_H = H
floors = plan["floors"]
NF = len(floors)
+T = themes.load(plan.get("theme")) # furniture, decor, colours and floors of the interior theme
progress(2, "building walls")
mat("tile", tex="large_floor_tiles_02", tile=1.5)
@@ -43,11 +44,16 @@ mat("exterior", (0.93, 0.91, 0.87), 0.9, tex="white_plaster_02", tile=2.5, albed
mat("cushion", rough=0.95, tex="caban", tile=0.5, tint=(0.55, 0.45, 0.35))
OPEN_SKY = {"open", "garden", "yard"} # no slab above these
-FINISHES = ("marble", "wood", "tile", "bathtile", "terracotta", "concrete") # as server.py FINISHES: the walkthrough can swap these
-wall_hex = plan.get("wall_color") # "#rrggbb" picked on the review page (sRGB); absent = lib's warm white
-if wall_hex: # Blender colour values are linear: undo the sRGB curve
- MATS["wall"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (*[
- v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 for v in (int(wall_hex[i:i + 2], 16) / 255 for i in (1, 3, 5))], 1)
+FINISHES = themes.FINISHES # the walkthrough can swap these
+
+
+def linear(hexc): # "#rrggbb" (sRGB) -> Blender's linear colour values
+ return tuple(v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 for v in (int(hexc[i:i + 2], 16) / 255 for i in (1, 3, 5)))
+
+
+wall_hex = plan.get("wall_color") or T["wall"] # picked on the review page, else the theme's; absent = lib's warm white
+if wall_hex:
+ MATS["wall"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (*linear(wall_hex), 1)
# ------------------------------------------------------------------ helpers
@@ -186,16 +192,38 @@ def stair_parts(f, rise):
def nightstand(x, y, rot):
group("nightstand", [(-0.75, 0.75, -0.7, 0.7, 0.2, 2.0, "teak"), (-0.7, 0.7, -0.75, -0.7, 1.15, 1.95, "laminate_w"),
(-0.2, 0.2, -0.82, -0.75, 1.5, 1.6, "brass")], x, y, rot, bevel=0.02)
- r = item("table_lamp", x, y, rot, z=2.0)
+ table_lamp(x, y, rot, 2.0)
+
+
+def table_lamp(x, y, rot, z):
+ r = item("table_lamp", x, y, rot, z=z)
p_cyl(r, "lamp_base", 0.18, 0.12, 0.7, "ceramic")
p_cyl(r, "lamp_shade", 0.45, 0.3, 0.6, "curtain", (0, 0, 0.7), solid=0.01)
done(r, collide=False)
-def sofa(x, y, rot, w=7.0):
- """velvet sofa: rounded arms and back, loose seat and back cushions, throw pillows, brass feet"""
+def sofa(x, y, rot, w=7.0, style="contemporary"):
+ """velvet sofa: rounded arms and back, loose seat and back cushions, throw pillows, brass feet.
+ style low: a low, square linen sofa on slim oak legs"""
hw = w / 2
r = item("sofa", x, y, rot)
+ if style == "low":
+ for sx in (-1, 1):
+ for sy in (-1, 1):
+ p_box(r, "sofa_leg", 0.12, 0.12, 0.4, "teak", (sx * (hw - 0.3), sy * 1.15, 0), bevel=0.01)
+ p_soft(r, "sofa_base", w, 3.0, 0.5, "linen_sofa", (0, 0, 0.4), r=0.06)
+ for s_ in (-1, 1):
+ p_soft(r, "sofa_arm", 0.45, 3.0, 1.15, "linen_sofa", (s_ * (hw - 0.22), 0, 0.4), r=0.08)
+ p_soft(r, "sofa_back", w - 0.9, 0.5, 1.6, "linen_sofa", (0, 1.25, 0.4), r=0.08)
+ n = max(2, round((w - 0.9) / 2.6))
+ cw = (w - 0.9) / n
+ for i in range(n):
+ cx = -hw + 0.45 + cw * (i + 0.5)
+ p_soft(r, "seat_cushion", cw - 0.03, 2.45, 0.42, "linen_sofa", (cx, -0.2, 0.9), r=0.1)
+ p_soft(r, "back_cushion", cw - 0.05, 0.5, 1.2, "linen_sofa", (cx, 0.78, 1.25), (-8, 0, 0), r=0.14)
+ for s_, m in ((-1, "boucle"), (1, "jacquard")):
+ p_soft(r, "throw_pillow", 1.25, 0.35, 1.25, m, (s_ * (hw - 1.3), 0.35, 1.38), (-18, 0, -s_ * 10), r=0.2)
+ return done(r)
for sx in (-1, 1):
for sy in (-1, 1):
p_cyl(r, "sofa_foot", 0.08, 0.05, 0.35, "brass", (sx * (hw - 0.35), sy * 1.2, 0), segs=16)
@@ -214,9 +242,22 @@ def sofa(x, y, rot, w=7.0):
return done(r)
-def coffee_table(x, y, rot):
- """tea table: oval white marble top on a walnut base with a shelf; books and a bowl on top"""
+def coffee_table(x, y, rot, style="contemporary"):
+ """tea table: oval white marble top on a walnut base with a shelf; books and a bowl on top.
+ style plank: a chunky reclaimed-plank table with a slatted shelf"""
r = item("coffee_table", x, y, rot)
+ if style == "plank":
+ for k in range(3):
+ p_box(r, "plank_top", 3.6, 0.64, 0.16, "raw_planks", (0, -0.66 + 0.66 * k, 1.29), bevel=0.02)
+ for sx in (-1, 1):
+ for sy in (-1, 1):
+ p_box(r, "plank_leg", 0.3, 0.3, 1.29, "raw_planks", (sx * 1.5, sy * 0.68, 0), bevel=0.02)
+ p_box(r, "plank_rail", 0.22, 1.6, 0.18, "raw_planks", (sx * 1.5, 0, 0.35), bevel=0.01)
+ for k in range(4):
+ p_box(r, "plank_shelf", 2.8, 0.34, 0.08, "raw_planks", (0, -0.6 + 0.4 * k, 0.45), bevel=0.01)
+ p_box(r, "book", 0.9, 0.65, 0.1, "blue_accent", (-0.8, 0.05, 1.45), (0, 0, 8), bevel=0.01)
+ p_bowl(r, "bowl", 0.4, 0.25, "ceramic", (0.7, 0.0, 1.7))
+ return done(r)
p_cyl(r, "table_top", 1.0, 1.0, 0.1, "marble_top", (0, 0, 1.35), sx=1.8, segs=64, bevel=0.03, seg=2)
p_cyl(r, "table_apron", 0.92, 0.92, 0.18, "teak", (0, 0, 1.17), sx=1.82, segs=64)
p_cyl(r, "table_shelf", 0.85, 0.85, 0.08, "teak", (0, 0, 0.35), sx=1.8, segs=64)
@@ -237,19 +278,66 @@ def tv_unit(x, y, rot):
tv(x - 0.5 * math.sin(r), y + 0.5 * math.cos(r), rot, z=3.4)
-def dining_set(x, y, rot, w=6.0, d=3.2, seats=6):
+def dining_set(x, y, rot, w=6.0, d=3.2, seats=6, style="contemporary", table=None, chairs=None):
+ """table (style oak: slim top on tapered legs; classic: walnut with an apron and turned legs; table: a model
+ piece fitted to w x d) and seats/2 chairs a side (chairs: the theme's chair piece)"""
hw, hd = w / 2, d / 2
- group("dining_table", [(-hw, hw, -hd, hd, 2.35, 2.5, "teak"),
- *[(sx * (hw - 0.4) - 0.12, sx * (hw - 0.4) + 0.12, sy * (hd - 0.4) - 0.12, sy * (hd - 0.4) + 0.12, 0, 2.35, "teak")
- for sx in (-1, 1) for sy in (-1, 1)]], x, y, rot, bevel=0.02)
+ a = math.radians(rot)
+ if table:
+ place_piece(table, (x - (hw if rot % 180 == 0 else hd), x + (hw if rot % 180 == 0 else hd),
+ y - (hd if rot % 180 == 0 else hw), y + (hd if rot % 180 == 0 else hw)), rot, "dining_set")
+ elif style == "oak":
+ r = item("dining_table", x, y, rot)
+ p_box(r, "table_top", w, d, 0.12, "teak", (0, 0, 2.4), bevel=0.03)
+ for sx in (-1, 1):
+ for sy in (-1, 1):
+ p_cyl(r, "table_leg", 0.06, 0.1, 2.4, "teak", (sx * (hw - 0.45), sy * (hd - 0.35), 0), segs=20)
+ done(r)
+ elif style == "classic":
+ r = item("dining_table", x, y, rot)
+ p_box(r, "table_top", w, d, 0.16, "teak", (0, 0, 2.36), bevel=0.04)
+ p_box(r, "table_apron", w - 0.5, d - 0.5, 0.35, "teak", (0, 0, 2.01), bevel=0.02)
+ for sx in (-1, 1):
+ for sy in (-1, 1): # turned legs: a vase on a column on a foot
+ lx, ly = sx * (hw - 0.4), sy * (hd - 0.4)
+ p_cyl(r, "leg_foot", 0.13, 0.1, 0.25, "teak", (lx, ly, 0), segs=24)
+ p_cyl(r, "leg_vase", 0.1, 0.19, 0.55, "teak", (lx, ly, 0.25), segs=24)
+ p_cyl(r, "leg_vase", 0.19, 0.08, 0.5, "teak", (lx, ly, 0.8), segs=24)
+ p_cyl(r, "leg_column", 0.08, 0.1, 0.71, "teak", (lx, ly, 1.3), segs=24)
+ p_box(r, "leg_block", 0.28, 0.28, 0.35, "teak", (lx, ly, 2.01), bevel=0.02)
+ done(r)
+ else:
+ group("dining_table", [(-hw, hw, -hd, hd, 2.35, 2.5, "teak"),
+ *[(sx * (hw - 0.4) - 0.12, sx * (hw - 0.4) + 0.12, sy * (hd - 0.4) - 0.12, sy * (hd - 0.4) + 0.12, 0, 2.35, "teak")
+ for sx in (-1, 1) for sy in (-1, 1)]], x, y, rot, bevel=0.02)
+ cw, cd = (themes.LIBRARY[chairs][1:3] if chairs in themes.LIBRARY else (1.6, 1.7))
per = seats // 2
for side in (-1, 1):
for i in range(per):
cx = -hw + w * (i + 0.5) / per
- cy = side * (hd + 0.6)
- a = math.radians(rot)
+ cy = side * (hd + (cd / 2 - 0.25 if chairs in themes.LIBRARY or chairs == "upload" else 0.6))
wx, wy = x + cx * math.cos(a) - cy * math.sin(a), y + cx * math.sin(a) + cy * math.cos(a)
- chair(wx, wy, rot + (180 if side < 0 else 0)) # backrest on the side away from the table
+ crot = rot + (180 if side < 0 else 0) # backrest on the side away from the table
+ if chairs in themes.LIBRARY or chairs == "upload":
+ place_piece(chairs, (wx - cw / 2, wx + cw / 2, wy - cd / 2, wy + cd / 2) if crot % 180 == 0 else
+ (wx - cd / 2, wx + cd / 2, wy - cw / 2, wy + cw / 2), crot, "dining_chair")
+ elif chairs == "@plain":
+ plain_chair(wx, wy, crot)
+ else:
+ chair(wx, wy, crot)
+
+
+def plain_chair(x, y, rot):
+ """oak frame, linen seat pad, a gently curved two-rail back (front faces -y at rot 0, back on +y)"""
+ r = item("chair", x, y, rot)
+ for sx in (-1, 1):
+ p_cyl(r, "chair_leg", 0.05, 0.065, 1.45, "teak", (sx * 0.62, -0.6, 0), segs=16)
+ p_box(r, "chair_back_leg", 0.12, 0.12, 2.95, "teak", (sx * 0.62, 0.62, 0), (-6, 0, 0), bevel=0.02)
+ p_box(r, "chair_seat", 1.5, 1.5, 0.12, "teak", (0, 0, 1.45), bevel=0.03)
+ p_soft(r, "chair_pad", 1.38, 1.38, 0.14, "linen_sofa", (0, -0.02, 1.57), r=0.05)
+ for z in (2.2, 2.65):
+ p_box(r, "chair_rail", 1.36, 0.08, 0.22, "teak", (0, 0.7, z), bevel=0.02)
+ return done(r, collide=False)
def chair(x, y, rot):
@@ -329,43 +417,99 @@ def model(name, x, y, rot=0, z=0.0, scale=1.0):
place(name, x, y, rot, z=z, scale=scale, collide=False)
-def custom(it):
- """the person's own model (assets/custom/<fn>.glb) in place of a built-in item, fitted to the item's footprint"""
- path = os.path.join(ASSETS, "custom", it["fn"] + ".glb")
- x0, x1, y0, y1 = it.get("box") or (0, 0, 0, 0)
- if it["fn"] not in CATALOG or not os.path.exists(path) or x1 - x0 < 0.1 or y1 - y0 < 0.1:
- return False
- before = set(bpy.data.objects)
- try:
- bpy.ops.import_scene.gltf(filepath=path) # shortcut: imported once per item, fine for a house; cache if plans grow huge
- except RuntimeError as e: # a broken file: the built-in item stands in for it
- print("CUSTOM MODEL FAILED", it["fn"], e, flush=True)
- for o in set(bpy.data.objects) - before:
- bpy.data.objects.remove(o)
- return False
- new = [o for o in bpy.data.objects if o not in before]
- bpy.context.view_layer.update()
- pts = [o.matrix_world @ Vector(c) for o in new if o.type == "MESH" for c in o.bound_box]
- if not pts:
- return False
- lo = Vector([min(p[i] for p in pts) for i in range(3)])
- hi = Vector([max(p[i] for p in pts) for i in range(3)])
- rot = it["args"][2]
- bw, bd = ((y1 - y0), (x1 - x0)) if round(rot) % 180 == 90 else ((x1 - x0), (y1 - y0))
- s = min(bw * lib.F / max(hi.x - lo.x, 1e-6), bd * lib.F / max(hi.y - lo.y, 1e-6))
- root = bpy.data.objects.new(f"custom_{it['fn']}", None)
+UPLOADS, BOUNDS = {}, {}
+
+
+def protos(piece, slot):
+ """the template objects of a theme piece (imported once, then copied per use: glTF instancing), or None"""
+ if piece in themes.LIBRARY:
+ return lib.load_model(piece)
+ key = themes.upload_path(T["id"], slot)
+ if key not in UPLOADS:
+ before = set(bpy.data.objects)
+ try:
+ bpy.ops.import_scene.gltf(filepath=key)
+ except RuntimeError as e: # a broken file: the built-in piece stands in for it
+ print("UPLOADED MODEL FAILED", slot, e, flush=True)
+ new = [o for o in bpy.data.objects if o not in before]
+ for o in new:
+ for c in list(o.users_collection):
+ c.objects.unlink(o)
+ for m in {sl.material for sl in o.material_slots if sl.material and sl.material.use_nodes} if o.type == "MESH" else ():
+ lib.glass_from_transmission(m)
+ UPLOADS[key] = new if any(o.type == "MESH" for o in new) else None
+ return UPLOADS[key]
+
+
+def place_piece(piece, box, rot, slot, z=0.0):
+ """a model piece fitted into box (feet; its front facing the way rot says), standing z ft above the floor.
+ -> its height in feet as placed, or None if there is no model to place"""
+ objs = protos(piece, slot)
+ if not objs:
+ return None
+ if id(objs) not in BOUNDS:
+ bpy.context.view_layer.update()
+ pts = [o.matrix_world @ Vector(c) for o in objs if o.type == "MESH" for c in o.bound_box]
+ BOUNDS[id(objs)] = (Vector([min(p[i] for p in pts) for i in range(3)]), Vector([max(p[i] for p in pts) for i in range(3)]))
+ lo, hi = BOUNDS[id(objs)]
+ turn = themes.LIBRARY[piece][4] if piece in themes.LIBRARY else 0
+ mw, md = (hi.y - lo.y, hi.x - lo.x) if turn % 180 == 90 else (hi.x - lo.x, hi.y - lo.y)
+ x0, x1, y0, y1 = box
+ bw, bd = (y1 - y0, x1 - x0) if round(rot) % 180 == 90 else (x1 - x0, y1 - y0)
+ s = min(bw * lib.F / max(mw, 1e-6), bd * lib.F / max(md, 1e-6))
+ root = bpy.data.objects.new(f"{slot}_{piece}", None)
collection("furniture").objects.link(root)
- for o in new:
- for c in list(o.users_collection):
- c.objects.unlink(o)
- collection("furniture").objects.link(o)
- if o.parent is None:
- o.location -= Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z)) # centred, standing on the floor
- o.parent = root
+ copies = {}
+ for o in objs:
+ c = o.copy() # shares the mesh
+ copies[o] = c
+ collection("furniture").objects.link(c)
+ for o, c in copies.items():
+ if o.parent in copies:
+ c.parent = copies[o.parent]
+ else:
+ c.parent = root
+ c.location = o.location - Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z)) # centred, standing on z
root.scale = (s, s, s)
- root.rotation_euler = (0, 0, math.radians(rot))
- root.location = ((x0 + x1) / 2 * lib.F, (y0 + y1) / 2 * lib.F, lib.LEVEL * lib.F)
- return True
+ root.rotation_euler = (0, 0, math.radians(rot + turn))
+ root.location = ((x0 + x1) / 2 * lib.F, (y0 + y1) / 2 * lib.F, (lib.LEVEL + z) * lib.F)
+ return (hi.z - lo.z) * s / lib.F
+
+
+def build(it):
+ """one furniture item in the theme's piece for its slot: a model fitted to the item's box, or a built-in piece"""
+ kw = dict(it["kw"])
+ fn, piece = it["fn"], kw.pop("piece", None) or T["slots"].get(it["fn"])
+ x, y, rot = it["args"][:3] if len(it["args"]) >= 3 else (0, 0, 0)
+ if fn == "dining_set":
+ chairs = T["slots"]["dining_chair"]
+ if piece in themes.LIBRARY or piece == "upload":
+ return dining_set(*it["args"], **{k: v for k, v in kw.items() if k in ("w", "d", "seats")}, table=piece, chairs=chairs)
+ return dining_set(*it["args"], **kw, chairs=chairs, **({"style": piece[1:]} if piece and piece != "@contemporary" else {}))
+ if piece in themes.LIBRARY or piece == "upload":
+ h = place_piece(piece, it["box"], rot, fn, z=kw.get("z", 0.0))
+ if h is not None:
+ if fn == "nightstand":
+ table_lamp(x, y, rot, h)
+ if fn == "tv_unit" and T["tv"]: # the TV on top, against the wall behind the unit
+ b, r = it["box"], math.radians(rot)
+ back = ((b[3] - b[2]) if round(rot) % 180 == 0 else (b[1] - b[0])) / 2
+ tv(x - (back - 0.2) * math.sin(r), y + (back - 0.2) * math.cos(r), rot, z=h + 0.4)
+ return
+ piece = None # (an upload that failed: the built-in piece)
+ if fn not in CALLS: # decor of a theme no longer chosen
+ return
+ if piece and piece.startswith("@") and piece != "@contemporary" and fn in STYLED:
+ kw["style"] = piece[1:]
+ kw.pop("z", None)
+ CALLS[fn](*it["args"], **kw)
+
+
+def hang_light(piece, cx, cy):
+ """a theme's ceiling light over (cx, cy): hung from the ceiling, its bottom no lower than 7.2 ft"""
+ w, d, h = themes.LIBRARY[piece][1:4] if piece in themes.LIBRARY else (2.0, 2.0, 2.5)
+ s = min(1.0, max(0.3, (H - 7.2) / h))
+ place_piece(piece, (cx - w * s / 2, cx + w * s / 2, cy - d * s / 2, cy + d * s / 2), 0, "light", z=H - h * s)
CALLS = dict(bathtub=bathtub, round_rug=round_rug, model=model, bed=bed, nightstand=nightstand, wardrobe=wardrobe, desk=desk, wc2=wc2, vanity=vanity,
@@ -373,6 +517,25 @@ CALLS = dict(bathtub=bathtub, round_rug=round_rug, model=model, bed=bed, nightst
kitchen_run=kitchen_run, chimney=chimney, wall_cab2=wall_cab2, fridge2=fridge2, washer2=washer2,
puja_mandir=puja_mandir, sofa=sofa, coffee_table=coffee_table, rug=rug, tv_unit=tv_unit,
dining_set=dining_set, car=car, plant=plant, outdoor_set=outdoor_set)
+CALLS.update(light=lambda x, y, rot, z=0.0: ceiling_light(x, y, 0.7), # (only the Themes page's preview row
+ dining_chair=lambda x, y, rot, style=None: (plain_chair if style == "plain" else chair)(x, y, rot)) # has these)
+STYLED = {"bed", "wardrobe", "sofa", "coffee_table", "dining_chair"} # builders that take style= (dining_set: see build)
+LIGHT_ROOMS = {"living", "dining", "bedroom", "study", "dress", "passage"} # where a theme hangs its own light
+
+
+# ------------------------------------------------------------------ the theme's colours on the built-in pieces
+PAINT = dict(wood=("teak", "wall_accent"), cabinet=("laminate_w", "painted_wood"), fabric=("velvet", "velvet_head", "cushion", "linen_sofa"),
+ curtain=("curtain",), rug=("rug", "rug_round"), accent=("jacquard", "throw", "quilt"))
+for key, names in PAINT.items():
+ if T["colours"].get(key):
+ rgb = linear(T["colours"][key])
+ for n in names: # made again in the theme's colour (and texture), keeping the weave or grain
+ sp = dict(lib.SPEC[n], **({"tex": T["tex"][key]} if key in T.get("tex", {}) else {}))
+ if sp["tex"] and sp["albedo"]:
+ sp.update(grey=True, tint=tuple(min(1.0, c / 0.8) for c in rgb)) # (the grey photo averages 0.8)
+ else:
+ sp["color"] = rgb
+ mat(n, **sp)
# ------------------------------------------------------------------ build each storey
@@ -462,7 +625,7 @@ for k, f in enumerate(floors):
fl = []
well = [(*stair_box_prev, -9, 99)] if stair_box_prev else []
for i, zn in enumerate(f["rooms"]):
- m = zn.get("floor") or FLOOR_MAT.get(zn["type"], "tile") # a finish chosen on the review page wins
+ m = zn.get("floor") or T["floors"].get(zn["type"]) or FLOOR_MAT.get(zn["type"], "tile") # review page, theme, type
if m in FINISHES: # the room's own copy, so the walkthrough can change this floor alone (it finds it by name)
MATS[f"floor_{k}_{i}"] = MATS[m].copy()
MATS[f"floor_{k}_{i}"].name = f"floor_{k}_{i}"
@@ -508,7 +671,7 @@ for k, f in enumerate(floors):
items = furnish.floor_items(plan, f)
for it in items:
try:
- custom(it) or CALLS[it["fn"]](*it["args"], **it["kw"])
+ build(it)
except Exception as e: # one bad item must not stop the build
print("ITEM FAILED", it["fn"], e, flush=True)
if items:
@@ -521,7 +684,10 @@ for k, f in enumerate(floors):
if (x1 - x0) * (y1 - y0) < 6:
continue
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
- ceiling_light(cx, cy, 0.7)
+ if themes.has(T, "light") and zn["type"] in LIGHT_ROOMS and (x1 - x0) * (y1 - y0) >= 40:
+ hang_light(T["slots"]["light"], cx, cy)
+ else:
+ ceiling_light(cx, cy, 0.7)
LAMPS.append((cx, cy, z + H - 0.25, (x1 - x0) * (y1 - y0), zn["type"]))
by_floor[k] = new_objects(before)
# walker data (metres): full-height and low walls block, openings do not
@@ -546,7 +712,9 @@ set_level(top)
before = set(bpy.data.objects)
bb = bboxes[-1]
holes = [(*r, -9, 99) for zn in floors[-1]["rooms"] if zn["type"] in OPEN_SKY for r in zn["rects"]]
-mesh_from_boxes("roof", [(*b[:4], -SLAB, 0.0, "terrace") for b in boxes_minus((*bb, -SLAB, 0.0), holes)])
+# the slab is plaster underneath (the top storey's ceiling) and tiled on top (the terrace)
+mesh_from_boxes("roof", [(*b[:4], z0, z1, m) for b in boxes_minus((*bb, -SLAB, 0.0), holes)
+ for z0, z1, m in ((-SLAB, -0.04, "ceiling"), (-0.04, 0.0, "terrace"))])
t = 0.33
mesh_from_boxes("parapet", [(*b, "exterior") for b in disjoint(subtract_all([ # (none along open courtyards)
(bb[0], bb[1], bb[2], bb[2] + t, 0, 3.5), (bb[0], bb[1], bb[3] - t, bb[3], 0, 3.5),
diff --git a/blender/lib.py b/blender/lib.py
index 9666d36..eb7f0fa 100644
--- a/blender/lib.py
+++ b/blender/lib.py
@@ -22,7 +22,7 @@ scene = bpy.context.scene
scene.unit_settings.system = "METRIC"
# ---------------------------------------------------------------- materials
-MATS = {}
+MATS, SPEC = {}, {}
def tex_node(nt, path, non_color=False):
@@ -69,6 +69,9 @@ def mat(name, color=(0.8, 0.8, 0.8), rough=0.5, metal=0.0, tex=None, tile=1.0, a
emit=0.0, tint=None, albedo=True, grey=False, image=None):
"""tile = metres covered by one texture repeat (UVs are written in metres / tile).
grey: drop the photo's own colour so tint is the colour; image: a generated image as the albedo."""
+ if image is None: # how it was made, so a theme can make it again in its own colour (gen.py repaint)
+ SPEC[name] = dict(color=color, rough=rough, metal=metal, tex=tex, tile=tile, alpha=alpha, emit=emit, tint=tint,
+ albedo=albedo, grey=grey)
m = bpy.data.materials.new(name)
m.use_nodes = True
nt = m.node_tree
@@ -163,6 +166,14 @@ mat("screen", (0.01, 0.01, 0.015), 0.05)
mat("light", (1.0, 0.95, 0.85), 0.5, emit=6.0)
mat("appliance", (0.8, 0.8, 0.82), 0.3, 0.8)
mat("steel_brushed", rough=0.3, metal=0.9, image=_brushed(), tile=0.6)
+# the themes' own pieces (blender/gen.py repaints the coloured ones in a theme's colours)
+mat("parquet", rough=0.35, tex="herringbone_parquet", tile=1.4) # floor finish
+mat("matte_white", (0.9, 0.89, 0.87), 0.55) # handleless doors
+mat("painted_wood", rough=0.7, tex="distressed_painted_planks", tile=1.6, grey=True, tint=(0.82, 0.86, 0.78))
+mat("painted_light", rough=0.7, tex="distressed_painted_planks", tile=1.6, grey=True, tint=(1.0, 0.98, 0.93))
+mat("raw_planks", rough=0.8, tex="dark_wooden_planks", tile=1.2)
+mat("linen_sofa", rough=0.95, tex="rough_linen", tile=0.5, grey=True, tint=(0.82, 0.8, 0.77))
+mat("quilt", rough=0.95, tex="gingham_check", tile=0.5, grey=True, tint=(0.75, 0.42, 0.36))
# ---------------------------------------------------------------- geometry helpers
COLL = {}
@@ -277,10 +288,26 @@ def load_model(name):
for o in new:
for c in list(o.users_collection):
c.objects.unlink(o)
+ for m in {sl.material for sl in o.material_slots if sl.material and sl.material.use_nodes} if o.type == "MESH" else ():
+ glass_from_transmission(m)
PROTO[name] = new
return new
+def glass_from_transmission(m):
+ """scanned glass uses transmission, which the web viewer cannot show, and the glTF exporter can drop its map and
+ break the whole file: make it plain see-through glass instead"""
+ p = m.node_tree.nodes.get("Principled BSDF")
+ t = p and p.inputs.get("Transmission Weight")
+ if t and (t.is_linked or t.default_value > 0.5):
+ for link in list(t.links):
+ m.node_tree.links.remove(link)
+ t.default_value = 0.0
+ p.inputs["Alpha"].default_value = 0.25
+ if hasattr(m, "surface_render_method"):
+ m.surface_render_method = "BLENDED"
+
+
def place(name, x, y, rot=0, z=0.0, scale=1.0, collide=True):
"""x,y,z in feet; rot = degrees, 0 = model's default facing."""
objs = load_model(name)
@@ -323,9 +350,10 @@ def group(name, boxes, x, y, rot=0, bevel=0.0, collide=True, z=0.0, seg=2):
# rot convention for procedural items: 0 -> front faces -y, 90 -> +x, 180 -> +y, 270 -> -x
-def bed(x, y, rot, w=5.0, l=6.6, blanket="throw", panel=None):
- """upholstered bed made up with sheet, duvet, a throw and pillows. blanket: material of the throw at the foot.
- panel: width of the wood panel on the wall behind the bed (default bed + 1.8 ft each side; 0 = none)"""
+def bed(x, y, rot, w=5.0, l=6.6, blanket="throw", panel=None, style="contemporary"):
+ """bed made up with sheet, duvet, a throw and pillows. blanket: material of the throw at the foot.
+ panel: width of the wood panel on the wall behind the bed (default bed + 1.8 ft each side; 0 = none)
+ style: contemporary (upholstered, tufted headboard), low (oak platform, slab headboard), farmhouse (painted planks)"""
hw = w / 2
yb, yf = l / 2, -l / 2 # head (back) at +y local
hp = hw + 1.8 if panel is None else panel / 2
@@ -336,32 +364,90 @@ def bed(x, y, rot, w=5.0, l=6.6, blanket="throw", panel=None):
blanket = "throw"
seed = round(x * 7 + y * 13)
r = item("bed", x, y, rot)
- p_box(r, "bed_plinth", w - 0.5, l - 0.8, 0.3, "black", (0, -0.2, 0), bevel=0.01)
- p_box(r, "bed_base", w, l - 0.35, 0.75, "teak", (0, -0.175, 0.3), bevel=0.05)
- p_box(r, "headboard_back", w + 0.3, 0.15, 3.9, "teak", (0, yb - 0.1, 0), bevel=0.03)
- n = max(3, round((w + 0.3) / 0.9)) # channel-tufted upholstered headboard
- cw = (w + 0.3) / n
- for i in range(n):
- p_soft(r, "headboard", cw - 0.02, 0.4, 2.9, "velvet_head", (-(w + 0.3) / 2 + cw * (i + 0.5), yb - 0.37, 0.95),
- r=0.17)
- p_soft(r, "mattress", w - 0.15, l - 0.55, 0.75, "sheet", (0, -0.225, 1.05), r=0.12)
- p_drape(r, "duvet", -hw + 0.08, hw - 0.08, yf + 0.1, yb - 2.1, 1.86, 0.85, "duvet", "xXy", thick=0.06, seed=seed)
- p_soft(r, "duvet_fold", w - 0.1, 0.55, 0.3, "duvet", (0, yb - 2.1, 1.72), r=0.14)
- p_drape(r, "throw", -hw, hw, yf + 0.3, yf + 1.7, 1.94, 1.0, blanket, "xX", thick=0.04, seed=seed)
+ dz = 0.0 # mattress height against the contemporary bed's
+ if style == "low": # oak platform on a recessed plinth, slab headboard
+ dz = -0.35
+ p_box(r, "bed_plinth", w - 0.8, l - 1.2, 0.18, "black", (0, -0.3, 0), bevel=0.01)
+ p_box(r, "bed_base", w + 0.5, l + 0.1, 0.52, "teak", (0, -0.05, 0.18), bevel=0.03)
+ p_box(r, "headboard", w + 0.5, 0.22, 3.0, "teak", (0, yb - 0.11, 0), bevel=0.03)
+ elif style == "farmhouse": # painted posts, plank head- and footboard, side rails
+ for sx in (-1, 1):
+ p_box(r, "bed_post", 0.32, 0.32, 4.3, "painted_light", (sx * (hw + 0.05), yb - 0.16, 0), bevel=0.04)
+ p_box(r, "bed_post", 0.32, 0.32, 2.7, "painted_light", (sx * (hw + 0.05), yf + 0.16, 0), bevel=0.04)
+ p_box(r, "bed_rail", 0.18, l - 0.6, 0.55, "painted_light", (sx * (hw - 0.02), -0.05, 0.6), bevel=0.02)
+ for yy, top in ((yb - 0.16, 3.9), (yf + 0.16, 2.3)):
+ n = max(4, round(w / 0.55))
+ for i in range(n): # vertical planks with a hairline gap
+ p_box(r, "bed_plank", w / n - 0.03, 0.12, top - 0.9, "painted_light", (-hw + w * (i + 0.5) / n, yy, 0.9), bevel=0.01)
+ p_box(r, "bed_cap", w + 0.6, 0.26, 0.16, "painted_light", (0, yy, top), bevel=0.03)
+ p_box(r, "bed_base", w - 0.1, l - 0.7, 0.45, "painted_light", (0, -0.05, 0.6), bevel=0.02)
+ if blanket == "throw":
+ blanket = "quilt"
+ else:
+ p_box(r, "bed_plinth", w - 0.5, l - 0.8, 0.3, "black", (0, -0.2, 0), bevel=0.01)
+ p_box(r, "bed_base", w, l - 0.35, 0.75, "teak", (0, -0.175, 0.3), bevel=0.05)
+ p_box(r, "headboard_back", w + 0.3, 0.15, 3.9, "teak", (0, yb - 0.1, 0), bevel=0.03)
+ n = max(3, round((w + 0.3) / 0.9)) # channel-tufted upholstered headboard
+ cw = (w + 0.3) / n
+ for i in range(n):
+ p_soft(r, "headboard", cw - 0.02, 0.4, 2.9, "velvet_head", (-(w + 0.3) / 2 + cw * (i + 0.5), yb - 0.37, 0.95),
+ r=0.17)
+ p_soft(r, "mattress", w - 0.15, l - 0.55, 0.75, "sheet", (0, -0.225, 1.05 + dz), r=0.12)
+ p_drape(r, "duvet", -hw + 0.08, hw - 0.08, yf + 0.1, yb - 2.1, 1.86 + dz, 0.85, "duvet", "xXy", thick=0.06, seed=seed)
+ p_soft(r, "duvet_fold", w - 0.1, 0.55, 0.3, "duvet", (0, yb - 2.1, 1.72 + dz), r=0.14)
+ p_drape(r, "throw", -hw, hw, yf + 0.3, yf + 1.7, 1.94 + dz, 1.0, blanket, "xX", thick=0.04, seed=seed)
pw, xs = (w - 0.6, (0,)) if w < 4 else (hw - 0.3, (-w / 4, w / 4))
for px in xs: # sleeping pillows leaning on the headboard
- p_soft(r, "pillow", pw, 0.55, 1.35, "sheet", (px, yb - 0.95, 1.75), (-18, 0, 0), r=0.26)
+ p_soft(r, "pillow", pw, 0.55, 1.35, "sheet", (px, yb - 0.95, 1.75 + dz), (-18, 0, 0), r=0.26)
if w >= 4: # cushions in front of them
for k, s in enumerate((-1, 1)):
- p_soft(r, "cushion", 1.25, 0.4, 1.25, "jacquard", (s * (w / 4 - 0.1), yb - 1.45, 1.8), (-22, 0, s * 6), r=0.2)
- p_soft(r, "cushion", 1.1, 0.35, 0.8, "boucle", (0, yb - 1.6, 1.8), (-15, 0, 0), r=0.16)
+ p_soft(r, "cushion", 1.25, 0.4, 1.25, "jacquard", (s * (w / 4 - 0.1), yb - 1.45, 1.8 + dz), (-22, 0, s * 6), r=0.2)
+ p_soft(r, "cushion", 1.1, 0.35, 0.8, "boucle", (0, yb - 1.6, 1.8 + dz), (-15, 0, 0), r=0.16)
return done(r)
-def wardrobe(x, y, rot, w=6.0, d=2.0, h=7.0):
- hw = w / 2
- b = [(-hw, hw, -d / 2 + 0.05, d / 2, 0, h, "laminate_w")]
+def wardrobe(x, y, rot, w=6.0, d=2.0, h=7.0, style="contemporary"):
+ """style: contemporary (oak, steel bar handles), flat (handleless white), classic (walnut armoire: plinth, cornice,
+ raised panels, brass knobs), farmhouse (painted plank doors, iron hinges and latches)"""
+ hw, f = w / 2, -d / 2 # f: the door face
n = max(2, round(w / 1.5))
+ if style == "flat":
+ b = [(-hw, hw, f + 0.05, d / 2, 0.25, h, "matte_white"), (-hw + 0.1, hw - 0.1, f + 0.12, d / 2, 0, 0.25, "black")]
+ for i in range(n):
+ x0 = -hw + w * i / n
+ b.append((x0 + 0.01, x0 + w / n - 0.01, f, f + 0.05, 0.27, h - 0.02, "matte_white"))
+ return group("wardrobe", b, x, y, rot, bevel=0.005)
+ if style == "classic":
+ b = [(-hw, hw, f + 0.1, d / 2, 0.5, h - 0.45, "teak"),
+ (-hw - 0.08, hw + 0.08, f - 0.02, d / 2, 0, 0.5, "teak"), # plinth
+ (-hw - 0.05, hw + 0.05, f, d / 2, h - 0.45, h - 0.25, "teak"), # cornice, stepping out
+ (-hw - 0.15, hw + 0.15, f - 0.12, d / 2, h - 0.25, h - 0.12, "teak"),
+ (-hw - 0.22, hw + 0.22, f - 0.18, d / 2, h - 0.12, h, "teak")]
+ for i in range(n):
+ x0, x1 = -hw + w * i / n + 0.03, -hw + w * (i + 1) / n - 0.03
+ b.append((x0, x1, f + 0.02, f + 0.1, 0.55, h - 0.5, "teak")) # door
+ for z0, z1 in ((0.85, 3.2), (3.55, h - 0.8)): # raised panels
+ b.append((x0 + 0.22, x1 - 0.22, f - 0.03, f + 0.02, z0, z1, "teak"))
+ kx = x1 - 0.2 if i % 2 == 0 else x0 + 0.2
+ b.append((kx - 0.06, kx + 0.06, f - 0.12, f - 0.03, 3.3, 3.42, "brass")) # knob
+ return group("wardrobe", b, x, y, rot, bevel=0.02)
+ if style == "farmhouse":
+ b = [(-hw, hw, f + 0.1, d / 2, 0.35, h - 0.3, "painted_wood"),
+ (-hw - 0.05, hw + 0.05, f + 0.02, d / 2, 0, 0.35, "painted_wood"),
+ (-hw - 0.12, hw + 0.12, f - 0.06, d / 2, h - 0.3, h, "painted_wood")]
+ for i in range(n):
+ x0, x1 = -hw + w * i / n + 0.03, -hw + w * (i + 1) / n - 0.03
+ k = max(2, round((x1 - x0) / 0.45))
+ for j in range(k): # tongue-and-groove planks
+ b.append((x0 + (x1 - x0) * j / k + 0.01, x0 + (x1 - x0) * (j + 1) / k - 0.01, f + 0.02, f + 0.1, 0.4, h - 0.35, "painted_wood"))
+ for z in (0.8, h - 1.0): # battens and iron strap hinges
+ b.append((x0 + 0.05, x1 - 0.05, f - 0.02, f + 0.02, z, z + 0.3, "painted_wood"))
+ hx0, hx1 = (x0, x0 + 0.7) if i % 2 == 0 else (x1 - 0.7, x1)
+ b.append((hx0, hx1, f - 0.05, f - 0.02, z + 0.1, z + 0.2, "iron"))
+ lx = x1 - 0.15 if i % 2 == 0 else x0 + 0.15
+ b.append((lx - 0.04, lx + 0.04, f - 0.14, f - 0.02, 3.2, 3.9, "iron")) # latch handle
+ return group("wardrobe", b, x, y, rot, bevel=0.01)
+ b = [(-hw, hw, -d / 2 + 0.05, d / 2, 0, h, "laminate_w")]
for i in range(n):
x0 = -hw + w * i / n
b.append((x0 + 0.03, x0 + w / n - 0.03, -d / 2, -d / 2 + 0.05, 0.3, h - 0.05, "laminate_w"))
@@ -427,6 +513,7 @@ mat("mirror", (0.96, 0.96, 0.96), 0.0, 1.0)
mat("black_glass", (0.01, 0.01, 0.012), 0.04)
mat("brass", (0.85, 0.62, 0.28), 0.25, 1.0)
mat("cast_iron", (0.03, 0.03, 0.03), 0.55, 0.6)
+mat("iron", (0.04, 0.04, 0.04), 0.5, 0.7)
mat("quartz", rough=0.12, tex="marble_01", tile=1.4, tint=(1.0, 0.98, 0.95))
mat("towel", rough=1.0, tex="cotton_jersey", tile=0.3, tint=(0.55, 0.62, 0.68))
mat("led", (1.0, 0.86, 0.66), 0.5, emit=8.0)
diff --git a/blender/thumbs.py b/blender/thumbs.py
index 2786cf5..97adba9 100644
--- a/blender/thumbs.py
+++ b/blender/thumbs.py
@@ -1,11 +1,11 @@
-"""Pictures of the furniture for the furniture page: blender -b PREVIEW/house.blend -P blender/thumbs.py -- OUT_DIR
-(house.blend = gen.py run on catalog.preview_plan(); one PNG per item, named after it)."""
-import bpy, os, sys
+"""Pictures of a theme's pieces for the Themes page: blender -b OUT/house.blend -P blender/thumbs.py -- OUT_DIR
+(OUT/house.blend = gen.py run on catalog.preview_plan(theme), saved as OUT/plan.json; one PNG per piece, named after
+its slot)."""
+import bpy, json, os, sys
from mathutils import Vector
-sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
-from catalog import CATALOG, CELL # noqa: E402
out, F = sys.argv[sys.argv.index("--") + 1], 0.3048
+plan = json.load(open(os.path.join(out, "plan.json")))
sc = bpy.context.scene
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bake # noqa: E402
@@ -19,11 +19,17 @@ cam = bpy.data.objects.new("thumb", bpy.data.cameras.new("thumb"))
sc.collection.objects.link(cam)
cam.data.lens = 26
sc.camera = cam
-for k, (fn, (_, w, d, _kw)) in enumerate(CATALOG.items()):
- c = Vector(((k + 0.5) * CELL, CELL / 2, 2.2)) * F
- back = max(w, d) * 0.7 + 4.5 # feet: far enough to fit the item
- cam.location = c + Vector((back * 0.55, -back, 3.2)) * F
+for it in plan["floors"][0]["items"]:
+ x0, x1, y0, y1 = it["box"]
+ z = it["kw"].get("z", 0.0)
+ wall, small = it["fn"] in ("art", "mirror"), max(x1 - x0, y1 - y0) < 1.5
+ c = Vector(((x0 + x1) / 2, (y0 + y1) / 2, z + (1.0 if it["fn"] == "light" else 0.8 if wall else 0.7 if small else 2.2))) * F
+ back = max(x1 - x0, y1 - y0) * 0.7 + (2.5 if small else 3.0 if wall or it["fn"] == "light" else 4.5) # feet: fits the piece
+ room = (y0 + y1) / 2 - 1.5 # the camera stays inside the preview room: a wider lens for big pieces
+ cam.data.lens = 26 * min(1.0, room / back)
+ back = min(back, room)
+ cam.location = c + Vector((back * 0.55, -back, 3.2 if not (wall or small) and it["fn"] != "light" else 0.4)) * F
cam.rotation_euler = (c - cam.location).to_track_quat("-Z", "Y").to_euler()
- sc.render.filepath = os.path.join(out, fn + ".png")
+ sc.render.filepath = os.path.join(out, it["fn"] + ".png")
bpy.ops.render.render(write_still=True)
print("THUMBS OK", flush=True)
diff --git a/catalog.py b/catalog.py
index a1363f1..cc4fc7a 100644
--- a/catalog.py
+++ b/catalog.py
@@ -1,6 +1,5 @@
-"""Furniture that can be replaced by your own model: name -> (label, width, depth in feet, extra arguments).
-A file assets/custom/<name>.glb takes the place of the built-in item in every later build: it is scaled to the item's
-footprint and stood on the floor. Model it with +Y up and its front facing +Z (the glTF standard)."""
+"""The built-in pieces' default footprints (name -> label, width, depth in feet, extra arguments), and the preview row
+of a theme's pieces that blender/thumbs.py photographs for the Themes page."""
CATALOG = {
"bed": ("Bed", 5.0, 6.6, {}), "nightstand": ("Nightstand", 1.6, 1.5, {}), "wardrobe": ("Wardrobe", 6.0, 2.0, {}),
"desk": ("Desk", 4.0, 2.0, {}), "sofa": ("Sofa", 7.0, 3.0, {}), "coffee_table": ("Coffee table", 3.6, 2.0, {}),
@@ -10,15 +9,36 @@ CATALOG = {
}
CELL = 20.0 # the preview scene: one item in the middle of each 20 ft cell of a long room
+import themes # noqa: E402
-def preview_plan():
- """a plan with every item standing in a row, used to render the pictures on the furniture page"""
- n, t = len(CATALOG), 0.75
- L = n * CELL
- items = [dict(fn=fn, args=[k * CELL + CELL / 2, CELL / 2, 0], kw=kw, solid=False, room="",
- box=[k * CELL + CELL / 2 - w / 2, k * CELL + CELL / 2 + w / 2, CELL / 2 - d / 2, CELL / 2 + d / 2])
- for k, (fn, (_, w, d, kw)) in enumerate(CATALOG.items())]
+
+def preview_plan(tid=None):
+ """a plan with every piece of a theme standing in a row (wall pieces on the back wall, the light hung from the
+ ceiling), built to render the pictures on the Themes page"""
+ T = themes.load(tid)
+ slots = [s for s in themes.SLOTS if T["slots"][s]]
+ t, L = 0.75, len(slots) * CELL
+ items = []
+ for k, s in enumerate(slots):
+ m = themes.size(T, s)
+ w, d, h = m or (*({**{fn: (w, d) for fn, (_, w, d, _) in CATALOG.items()}, **EXTRA}[s]), 0.0)
+ cx, cy, kw = k * CELL + CELL / 2, CELL / 2, {}
+ if s in ("art", "mirror"):
+ cy, kw = CELL - t - d / 2, dict(z=3.5)
+ elif s == "light":
+ kw = dict(z=round(10.0 - (h or 0.1), 2))
+ elif s == "bed":
+ kw = dict(w=w, l=d, **({"panel": 0.0} if themes.has(T, "art") else {})) # as the rules build it
+ elif s == "dining_set":
+ kw = dict(w=w, d=d, seats=6)
+ items.append(dict(fn=s, args=[cx, cy, 0], kw=kw, solid=False, room="", box=[cx - w / 2, cx + w / 2, cy - d / 2, cy + d / 2]))
walls = [[0, L, 0, t, 0], [0, L, CELL - t, CELL, 0], [0, t, 0, CELL, 0], [L - t, L, 0, CELL, 0]]
- return dict(version=1, units="ft", floor_height=10.0, slab=0.5, floors=[dict(
+ # an "open" room: no ceiling light of its own, and the sky lights the row evenly, as in a photo studio
+ return dict(version=1, units="ft", floor_height=10.0, slab=0.5, theme=T["id"], floors=[dict(
name="Preview", level=0, size=[L, CELL], walls=walls, openings=[], stairs=[], labels=[], items=items,
- rooms=[dict(type="living", label="", rects=[[t, L - t, t, CELL - t]], area=L * CELL)])])
+ rooms=[dict(type="open", label="", floor="wood", rects=[[t, L - t, t, CELL - t]], area=L * CELL)])])
+
+
+# sizes (w, d in feet) of the theme slots that are not in CATALOG, for the preview row
+EXTRA = dict(sofa=(7.0, 3.0), coffee_table=(3.6, 2.0), dining_set=(6.0, 3.2), dining_chair=(1.6, 1.7), armchair=(2.7, 3.0),
+ light=(1.8, 1.8), art=(2.0, 0.1), mirror=(1.6, 0.1), decor=(0.7, 0.7), corner=(2.0, 1.4), bed_end=(3.8, 1.6))
diff --git a/docs/custom_sofa.png b/docs/custom_sofa.png
deleted file mode 100644
index 17f6cf5..0000000
Binary files a/docs/custom_sofa.png and /dev/null differ
diff --git a/docs/furniture.png b/docs/furniture.png
deleted file mode 100644
index 5129f9e..0000000
Binary files a/docs/furniture.png and /dev/null differ
diff --git a/docs/themes.jpg b/docs/themes.jpg
new file mode 100644
index 0000000..26ea21d
Binary files /dev/null and b/docs/themes.jpg differ
diff --git a/docs/themes_page.jpg b/docs/themes_page.jpg
new file mode 100644
index 0000000..d260fa0
Binary files /dev/null and b/docs/themes_page.jpg differ
diff --git a/fetch_assets.py b/fetch_assets.py
index a6f02d0..0b6880d 100644
--- a/fetch_assets.py
+++ b/fetch_assets.py
@@ -1,16 +1,21 @@
-"""Download the CC0 textures, models and sky this project builds with, from Poly Haven, into ./assets (about 75 MB).
+"""Download the CC0 textures, models and sky this project builds with, from Poly Haven, into ./assets (about 150 MB,
+the interior themes' furniture models included).
python3 fetch_assets.py [--tour] files already present are skipped; --tour adds the dusk sky for blender/cinema.py
The server's home page runs the same download from its "Download materials" button."""
import json, os, sys, urllib.request
+import themes
+
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
-MODELS = ["covered_car", "outdoor_table_chair_set_01", "street_lamp_01"]
+MODELS = ["covered_car", "outdoor_table_chair_set_01", "street_lamp_01", *themes.LIBRARY]
TEXTURES = ["american_walnut_veneer", "anti_skid_tiles", "asphalt_02", "black_walnut_veneer_01", "caban", "concrete_floor",
"concrete_tiles", "cotton_jersey", "dry_river_pebbles", "floral_jacquard", "granite_tile",
"herringbone_pavement", "hessian_380", "knitted_fleece", "laminate_floor_02", "large_floor_tiles_02",
"leafy_grass", "long_white_tiles", "marble_01", "oak_veneer_01", "quatrefoil_jacquard_fabric",
"rough_linen", "square_concrete_pavers", "stretch_poplin", "terracotta_floor_tiles", "terrazzo_tiles",
- "velour_velvet", "waffle_pique_cotton", "white_plaster_02", "wool_boucle"]
+ "velour_velvet", "waffle_pique_cotton", "white_plaster_02", "wool_boucle",
+ # the interior themes' own pieces and the parquet floor
+ "ash_veneer", "dark_wooden_planks", "distressed_painted_planks", "gingham_check", "herringbone_parquet"]
SKY, TOUR_SKY = "kloofendal_48d_partly_cloudy_puresky", "qwantani_dusk_2_puresky"
UA = {"User-Agent": "planto3d-fetch/1.0"}
diff --git a/furnish.py b/furnish.py
index d6ed756..821a069 100644
--- a/furnish.py
+++ b/furnish.py
@@ -6,6 +6,7 @@ Rotation (lib.py convention): 0 = item front faces -y (back to a wall on +y), 90
"""
import math
+import themes
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,
}
@@ -70,8 +71,9 @@ def max_rect(rects, exclude=None, g=0.25):
class Room:
- def __init__(self, zone, floor):
+ def __init__(self, zone, floor, theme=None):
self.zone, self.type, self.floor = zone, zone["type"], floor
+ self.T = theme or themes.load(None)
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
@@ -186,6 +188,29 @@ class Room:
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 sizes(self, slot, defaults):
+ """footprints (w, d, kw) to try for a slot: a theme's model at its own size, a little smaller if need be, then
+ the built-in piece in the theme's colours (kw piece) where the model does not fit; without a model the defaults"""
+ m = themes.size(self.T, slot)
+ if not m:
+ return [(w, d, {}) for w, d in defaults]
+ return [(m[0] * k, m[1] * k, {}) for k in (1.0, 0.9, 0.8)] + [(w, d, dict(piece="@contemporary")) for w, d in defaults]
+
+ def height(self, slot, default):
+ m = themes.size(self.T, slot)
+ return m[2] if m else default
+
+ def hang(self, slot, side, c, z, ref=None):
+ """a theme's wall piece (art, mirror) on `side`, centred along it at c, its bottom z ft above the floor;
+ not solid, so it never blocks anything. ref: the item it hangs above (for the walkthrough's furniture tool)"""
+ m = themes.size(self.T, slot)
+ if not m or z + m[2] > self.floor.get("floor_height", 10.0) - 0.4:
+ return
+ face = {"N": self.rect[3], "S": self.rect[2], "E": self.rect[1], "W": self.rect[0]}[side]
+ xy = (c, face - m[1] / 2) if side == "N" else (c, face + m[1] / 2) if side == "S" else \
+ (face - m[1] / 2, c) if side == "E" else (face + m[1] / 2, c)
+ self.add(slot, rect_at(xy, m[0], m[1], side), *xy, SIDES[side], z=round(z, 2), solid=False)
+
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"}
@@ -222,11 +247,18 @@ def rect_at(c, w, d, side):
def bedroom(R):
double = min(R.w, R.d) >= 9.0
bw, bl = (5.0, 6.6) if double else (3.5, 6.5)
+ model = themes.size(R.T, "bed")
+ piece = {}
+ if model and double:
+ bw, bl = model[:2]
+ elif model: # a theme's bed is a double: a single room gets the built-in single bed
+ piece = dict(piece="@contemporary")
+ nw, nd, _ = R.sizes("nightstand", [(1.5, 1.4)])[0]
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)
+ p = R.spot(side, bw + 2 * (nw + 0.1), bl, tall=True)
stands = p is not None
p = p or R.spot(side, bw, bl, tall=True)
if not p:
@@ -237,13 +269,22 @@ def bedroom(R):
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, panel=round(panel, 2))
+ art = themes.has(R.T, "art") # a theme's picture over the bed instead of the wood panel
+ R.add("bed", bb, x, y, rot, w=bw, l=bl, panel=0.0 if art else round(panel, 2), **piece)
if stands:
for s in (-1, 1):
- off = (bw / 2 + 0.8) * s
+ off = (bw / 2 + nw / 2 + 0.05) * 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)
+ cx, cy = front_offset(side, (cx, cy), -(bl / 2 - nd / 2 - 0.1))
+ R.add("nightstand", rect_at((cx, cy), nw, nd, side), cx, cy, rot)
+ if art:
+ R.hang("art", side, c, max(4.6, (model[2] if model and not piece else 3.9) + 0.6))
+ if themes.has(R.T, "bed_end"): # a bench at the foot of the bed, if a walkway stays beyond it
+ m = R.sizes("bed_end", [])[0]
+ if m[0] <= bw:
+ c2 = front_offset(side, (x, y), bl / 2 + 0.25 + m[1] / 2)
+ if R.fits(rect_at(c2, m[0], m[1], side)) and inside(rect_at(front_offset(side, c2, 1.25), m[0], m[1] + 2.5, side), R.rect):
+ R.add("bed_end", rect_at(c2, m[0], m[1], side), *c2, rot)
break
# wardrobe on another wall, towards a corner
for side in R.sides_by("long", tall=True):
@@ -257,12 +298,7 @@ def bedroom(R):
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
+ desk(R)
# 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"]
@@ -270,7 +306,7 @@ def bedroom(R):
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":
+ if it is bed or it["fn"] in ("nightstand", "art"):
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])
@@ -462,26 +498,71 @@ def fridge(R):
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)
+ for w, sd, skw in R.sizes("sofa", [(7.0, 3.0), (6.0, 3.0), (5.0, 3.0)]):
+ p = R.spot(side, w, sd)
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):
+ for cw, cd, ckw in R.sizes("coffee_table", [(3.6, 2.0)]):
+ ct = front_offset(side, (x, y), sd / 2 + 0.5 + cd / 2)
+ cbox = rect_at(ct, cw, cd, side)
+ if R.fits(cbox):
+ break
+ else:
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("sofa", box, x, y, rot, w=w, **skw)
+ R.add("coffee_table", cbox, ct[0], ct[1], rot, **ckw)
+ rbox = rect_at(ct, w + 0.5, max(5.5, cd + 3.0), 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])
+ R.hang("art", side, x if side in "NS" else y, R.height("sofa", 3.0) + 0.7)
+ # an armchair at one end of the coffee table, facing it
+ if themes.has(R.T, "armchair"):
+ aw, ad, _ = R.sizes("armchair", [])[0]
+ for s in (1, -1):
+ along = cw / 2 + 0.6 + ad / 2
+ c = (ct[0] + s * along, ct[1]) if side in "NS" else (ct[0], ct[1] + s * along)
+ back = ("E" if s > 0 else "W") if side in "NS" else ("N" if s > 0 else "S")
+ if R.fits(rect_at(c, aw, ad, back)):
+ R.add("armchair", rect_at(c, aw, ad, back), *c, SIDES[back])
+ break
+ # TV (or a theme's commode with a mirror) on the opposite wall if it is a wall
+ for tw, td, tkw in R.sizes("tv_unit", [(5.0, 1.4)]):
+ q = R.spot(OPP[side], tw, td)
+ if q:
+ R.add("tv_unit", q[3], q[0], q[1], q[2], **tkw)
+ top, cq = 1.9 if tkw else R.height("tv_unit", 1.9), q[0] if side in "NS" else q[1]
+ if themes.has(R.T, "decor"): # on the unit: beside the TV, or in the middle with no TV
+ dw = themes.size(R.T, "decor")[0] if themes.size(R.T, "decor") else 0.7
+ off = (tw / 2 - dw / 2 - 0.2) * (1 if R.T["tv"] else 0)
+ dx, dy = (q[0] + off, q[1]) if side in "NS" else (q[0], q[1] + off)
+ R.add("decor", rect_at((dx, dy), dw, dw, OPP[side]), dx, dy, q[2], z=round(top, 2), solid=False)
+ if not R.T["tv"]:
+ R.hang("mirror", OPP[side], cq, top + 0.9)
+ break
+ corner(R)
return
+def corner(R):
+ """a theme's tall corner piece (clock, shelves) against a free wall, towards a corner"""
+ if themes.has(R.T, "corner"):
+ w, d, _ = R.sizes("corner", [])[0]
+ for side in R.sides_by("long", tall=True):
+ p = R.spot(side, w, d, tall=True, align="end", gap=0.3)
+ if p:
+ R.add("corner", p[3], p[0], p[1], p[2])
+ return
+
+
+def desk(R):
+ for side in R.sides_by("long"):
+ for w, d, kw in R.sizes("desk", [(3.5, 2.0)]):
+ p = R.spot(side, w, d)
+ if p:
+ R.add("desk", p[3], p[0], p[1], p[2], **kw)
+ 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)
@@ -498,7 +579,15 @@ def dining(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)):
+ sizes = ((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))
+ piece = {}
+ if themes.size(R.T, "dining_set"): # a theme's table: as many chairs a side as fit along it (at most three)
+ chair = (themes.size(R.T, "dining_chair") or (1.6,))[0]
+ sizes = [(w, d, 2 * max(1, min(3, int((w - 0.4) / (chair + 0.3)))), 2.2) for w, d, _ in R.sizes("dining_set", [])] + \
+ [(*q, "fallback") for q in sizes]
+ for tw, tl, n, m, *fb in sizes:
+ if fb: # the theme's table does not fit: the built-in one in the theme's colours
+ piece = dict(piece="@contemporary")
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)
@@ -507,7 +596,7 @@ def dining_table(R):
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)
+ cx, cy, 0 if long_x else 90, w=tw, d=tl, seats=n, **piece)
return True
return False
@@ -578,20 +667,16 @@ RULES = dict(dress=dress, bedroom=bedroom, toilet=toilet, kitchen=kitchen, livin
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
+ desk(R)
-def furnish_floor(floor):
- """-> list of items {fn, args, kw, box, solid, room} for one floor"""
+def furnish_floor(floor, theme=None):
+ """-> list of items {fn, args, kw, box, solid, room} for one floor, furnished in `theme` (themes.load result)"""
out = []
for z in floor["rooms"]:
if z["type"] not in RULES or not z["rects"]:
continue
- R = Room(z, floor)
+ R = Room(z, floor, theme)
if R.w < 2.5 or R.d < 2.5:
continue
RULES[z["type"]](R)
@@ -602,7 +687,8 @@ def furnish_floor(floor):
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)
+ return [] if plan.get("furnish") is False else floor["items"] if "items" in floor else \
+ furnish_floor(dict(floor, floor_height=plan.get("floor_height", 10.0)), themes.load(plan.get("theme")))
def clashes(items, floor):
diff --git a/quantities.py b/quantities.py
index 9a56aad..9431c23 100644
--- a/quantities.py
+++ b/quantities.py
@@ -5,6 +5,7 @@ import re
from collections import Counter
import furnish
+import themes
from catalog import CATALOG
FLOOR_MAT = dict(dress="wood", bedroom="wood", toilet="bathtile", kitchen="marble", living="marble", dining="marble", puja="marble",
@@ -15,7 +16,7 @@ PAINTED = furnish.INDOOR | {"stair"}
TILE_H = 7.0 # toilet walls are tiled to this height (gen.py builds them so), painted above
VENT_MAX = 2.6
LABELS = dict(shower2="Shower", geyser="Geyser", kitchen_run="Kitchen counter", chimney="Chimney", wall_cab2="Wall cabinet",
- rug="Rug", car="Car", outdoor_set="Outdoor table set", bathtub="Bathtub", round_rug="Round rug")
+ rug="Rug", car="Car", outdoor_set="Outdoor table set", bathtub="Bathtub", round_rug="Round rug", **themes.SLOTS)
def zone_at(f, x, y):
@@ -78,13 +79,14 @@ def wall_area(faces, h0, h1):
def quantities(plan):
H = plan.get("floor_height", 10.0)
floors, finishes, openings, items = [], Counter(), Counter(), Counter()
+ T = themes.load(plan.get("theme"))
for f in plan["floors"]:
rooms = []
for z in f["rooms"]:
if z["type"] == "duct":
continue
area = sum((r[1] - r[0]) * (r[3] - r[2]) for r in z["rects"])
- fin = z.get("floor") or FLOOR_MAT.get(z["type"], "tile")
+ fin = z.get("floor") or T["floors"].get(z["type"]) or FLOOR_MAT.get(z["type"], "tile") # as gen.py builds it
finishes[fin] += area
row = dict(name=room_name(z), type=z["type"], finish=fin, area=area, paint=0.0, tiles=0.0, ceiling=0.0)
if z["type"] in PAINTED:
@@ -96,8 +98,11 @@ def quantities(plan):
r = o["rect"]
s, hd = opening_heights(f, o)
openings[(o["type"], round(max(r[1] - r[0], r[3] - r[2]) * 4) / 4, hd - max(s, 0))] += 1
- # a "model" item is a downloaded model: count it by its asset name ("potted_plant_01" -> "potted_plant")
- items.update(re.sub(r"_\d+$", "", str(it["args"][0])) if it["fn"] == "model" else it["fn"] for it in furnish.floor_items(plan, f))
+ # a "model" item is a downloaded model: count it by its asset name ("potted_plant_01" -> "potted_plant");
+ # a piece of the theme by the theme's name for it ("Carved four-poster bed")
+ items.update(re.sub(r"_\d+$", "", str(it["args"][0])) if it["fn"] == "model" else
+ themes.label(T, it["fn"]) if it["fn"] in themes.SLOTS and not it["kw"].get("piece") and T["slots"][it["fn"]] in themes.LIBRARY
+ else it["fn"] for it in furnish.floor_items(plan, f))
floors.append(dict(name=f.get("name", ""), rooms=rooms))
return dict(
floor_height=H, floors=floors, finishes=dict(finishes.most_common()),
diff --git a/server.py b/server.py
index 8b4f1d9..1146905 100644
--- a/server.py
+++ b/server.py
@@ -16,13 +16,13 @@ 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, furnish, quantities # noqa: E402
+import catalog, detect, fetch_assets, furnish, quantities, themes # noqa: E402
os.makedirs(JOBS, exist_ok=True)
builds = queue.Queue()
lock = threading.RLock() # reentrant: request handlers hold it around status() to check and set a stage in one step
BUSY = ("uploaded", "detecting", "queued", "building")
-FINISHES = ("marble", "wood", "tile", "bathtile", "terracotta", "concrete") # room.floor: blender/lib.py materials, as in edit.js FINISH
+FINISHES = themes.FINISHES # room.floor: blender/lib.py materials, as in edit.js FINISH
TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json",
".png": "image/png", ".jpg": "image/jpeg", ".webp": "image/webp", ".glb": "model/gltf-binary",
".wasm": "application/wasm", ".svg": "image/svg+xml", ".pdf": "application/pdf", ".hdr": "application/octet-stream",
@@ -84,7 +84,7 @@ def fetch_materials():
assets_job["failed"] = [str(e)]
finally:
assets_job["running"] = False
- thumbs_job["tried"] = False # the furniture pictures can be drawn now
+ thumbs_job["tried"].clear() # the themes' pictures can be drawn now
def export_blend(jid):
@@ -162,61 +162,105 @@ def export_site(jid):
return f"/jobs/{jid}/house_site.zip"
-# ------------------------------------------------------------------ your own furniture models
-CUSTOM, THUMBS = os.path.join(fetch_assets.ROOT, "custom"), os.path.join(fetch_assets.ROOT, "thumbs")
-thumbs_job = dict(running=False, again=False, tried=False)
+# ------------------------------------------------------------------ interior themes and their pictures
+THUMBS = os.path.join(fetch_assets.ROOT, "thumbs") # <theme>/<slot>.png
+thumbs_job = dict(running=False, queue=[], tried=set())
def render_thumbs():
- """pictures of every replaceable item as it will be built now (built-in or your model): a small house with all of
- them in a row is built without baking, then photographed. Runs again if a model changed meanwhile."""
+ """pictures of each queued theme's pieces as they will be built now: a small house with all of them in a row is
+ built without baking, then photographed (a minute or so per theme)"""
try:
while True:
- thumbs_job["again"] = False
- os.makedirs(THUMBS, exist_ok=True)
- with open(os.path.join(THUMBS, "plan.json"), "w") as fh:
- json.dump(catalog.preview_plan(), fh)
+ with lock:
+ if not thumbs_job["queue"]:
+ thumbs_job["running"] = False
+ return
+ tid = thumbs_job["queue"].pop(0)
+ out = os.path.join(THUMBS, tid)
+ os.makedirs(out, exist_ok=True)
+ with open(os.path.join(out, "plan.json"), "w") as fh:
+ json.dump(catalog.preview_plan(tid), fh)
subprocess.run([BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
- os.path.join(THUMBS, "plan.json"), THUMBS, "--no-bake"], capture_output=True, timeout=1800)
- subprocess.run([BLENDER, "-b", os.path.join(THUMBS, "house.blend"), "-P", os.path.join(HERE, "blender", "thumbs.py"),
- "--", THUMBS], capture_output=True, timeout=600)
- if not thumbs_job["again"]:
- break
+ os.path.join(out, "plan.json"), out, "--no-bake"], capture_output=True, timeout=1800)
+ subprocess.run([BLENDER, "-b", os.path.join(out, "house.blend"), "-P", os.path.join(HERE, "blender", "thumbs.py"),
+ "--", out], capture_output=True, timeout=900)
+ if tid not in themes.THEMES and tid not in themes.custom_ids(): # deleted meanwhile
+ shutil.rmtree(out, ignore_errors=True)
except Exception:
traceback.print_exc()
- finally:
- thumbs_job["running"] = False
+ with lock:
+ thumbs_job["running"] = False
-def refresh_thumbs():
+def refresh_thumbs(tid, again=True):
+ """draw a theme's pictures (again: also if they were drawn before, after the theme changed)"""
with lock:
+ if not again and tid in thumbs_job["tried"]:
+ return
+ thumbs_job["tried"].add(tid)
+ if tid not in thumbs_job["queue"]:
+ thumbs_job["queue"].append(tid)
if thumbs_job["running"]:
- thumbs_job["again"] = True
return
- thumbs_job.update(running=True, tried=True)
+ thumbs_job["running"] = True
threading.Thread(target=render_thumbs, daemon=True).start()
-def furniture():
- # drawn once on its own; after that only a new or removed model draws them again (a render that fails must not loop)
- if not thumbs_job["tried"] and not all(os.path.exists(os.path.join(THUMBS, f"{fn}.png")) for fn in catalog.CATALOG):
- refresh_thumbs()
- return dict(rendering=thumbs_job["running"], items=[
- dict(fn=fn, label=label, custom=os.path.exists(os.path.join(CUSTOM, f"{fn}.glb")),
- thumb=os.path.exists(os.path.join(THUMBS, f"{fn}.png"))) for fn, (label, *_) in catalog.CATALOG.items()])
+def theme_list():
+ out = []
+ for tid in [*themes.THEMES, *themes.custom_ids()]:
+ T = themes.load(tid)
+ if T["id"] != tid: # a custom theme file that cannot be read
+ continue
+ pics = {s: os.path.getmtime(f) for s in themes.SLOTS if T["slots"][s]
+ for f in [os.path.join(THUMBS, tid, s + ".png")] if os.path.exists(f)}
+ if any(T["slots"][s] and s not in pics for s in themes.SLOTS) and system()["ready"]:
+ refresh_thumbs(tid, again=False) # drawn once on its own; a picture that fails must not loop
+ out.append(dict(id=tid, label=T["label"], about=T["about"], builtin=T["builtin"], colours=T["colours"], tex=T.get("tex", {}),
+ floors=T["floors"], wall=T["wall"], tv=T["tv"], pictures={s: int(v) for s, v in pics.items()},
+ slots={s: dict(value=v, label=themes.label(T, s)) for s, v in T["slots"].items() if v}))
+ return dict(themes=out, rendering=thumbs_job["running"], slots=themes.SLOTS, colours=themes.COLOURS, finishes=FINISHES,
+ choices={s: themes.choices(s) for s in themes.SLOTS})
+
+
+def save_theme(tid, req):
+ """a person's own theme from the Themes page: -> its id. tid None makes a new one, named after its label"""
+ t = themes.check(req)
+ if tid is None:
+ base = re.sub(r"[^a-z0-9]+", "-", t["label"].lower()).strip("-")[:24] or "theme"
+ tid, n = base, 2
+ while tid in themes.THEMES or os.path.exists(os.path.join(themes.DIR, tid + ".json")):
+ tid, n = f"{base}-{n}", n + 1
+ elif tid in themes.THEMES or not os.path.exists(os.path.join(themes.DIR, tid + ".json")):
+ raise ValueError("Only your own themes can be changed.")
+ os.makedirs(themes.DIR, exist_ok=True)
+ with open(os.path.join(themes.DIR, tid + ".json.part"), "w") as fh:
+ json.dump(t, fh)
+ os.replace(os.path.join(themes.DIR, tid + ".json.part"), os.path.join(themes.DIR, tid + ".json"))
+ refresh_thumbs(tid)
+ return tid
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"""
+ """the furniture each floor will get (the review page's own list if it edited that floor, else the rules' choice),
+ and what can be added, at the sizes of the plan's theme"""
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()})
+ T, cat = themes.load(plan.get("theme")), {}
+ for fn, (label, w, d, kw) in catalog.CATALOG.items():
+ m = themes.size(T, fn)
+ cat[fn] = [themes.label(T, fn), *((m[0], m[1] + (3.2 if fn == "dining_set" else 0)) if m else (w, d)), kw]
+ for fn in ("armchair", "corner", "bed_end"): # decor of the theme that stands on the floor
+ if themes.size(T, fn):
+ cat[fn] = [themes.label(T, fn), *themes.size(T, fn)[:2], {}]
+ return dict(floors=[furnish.floor_items(plan, f) for f in plan["floors"]], catalog=cat)
# 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
+ "outdoor_set", "bathtub", "round_rug", "armchair", "art", "mirror", "decor", "corner", "bed_end"}
+WORD = re.compile(r"@?[\w+-]{0,24}") # side names such as "-x", material names, "@style" pieces; nothing that can be a path
def check_items(plan):
@@ -369,8 +413,8 @@ class H(BaseHTTPRequestHandler):
return self.file(os.path.join(HERE, "examples", p[10:]), os.path.join(HERE, "examples"))
if p.startswith("/thumbs/"):
return self.file(os.path.join(THUMBS, p[8:]), THUMBS)
- if p == "/api/furniture":
- return self.send(200, furniture())
+ if p == "/api/themes":
+ return self.send(200, theme_list())
if p.startswith("/three/"):
return self.file(os.path.join(THREE, p[7:]), THREE)
if p.startswith("/jobs/"):
@@ -430,30 +474,40 @@ class H(BaseHTTPRequestHandler):
return self.send(409, {"error": "This plan is being read or built. Delete it when that has finished."})
shutil.rmtree(jdir(m.group(1)))
return self.send(200, {"ok": True})
- m = re.match(r"^/api/furniture/(\w+)$", p)
- if m and m.group(1) in catalog.CATALOG: # back to the built-in item
- for f in (os.path.join(CUSTOM, m.group(1) + ".glb"), os.path.join(THUMBS, m.group(1) + ".png")):
- if os.path.exists(f):
- os.remove(f)
- refresh_thumbs()
+ m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})$", p)
+ if m and m.group(1) in themes.custom_ids(): # a person's own theme (plans built with it get contemporary)
+ for f in (os.path.join(themes.DIR, m.group(1)), os.path.join(THUMBS, m.group(1))):
+ shutil.rmtree(f, ignore_errors=True)
+ os.remove(os.path.join(themes.DIR, m.group(1) + ".json"))
+ return self.send(200, {"ok": True})
+ m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})/model/(\w+)$", p)
+ if m and m.group(1) in themes.custom_ids() and m.group(2) in themes.SLOTS: # back to the built-in piece
+ t = json.load(open(os.path.join(themes.DIR, m.group(1) + ".json")))
+ t["slots"].pop(m.group(2), None)
+ if os.path.exists(themes.upload_path(*m.groups())):
+ os.remove(themes.upload_path(*m.groups()))
+ save_theme(m.group(1), t)
return self.send(200, {"ok": True})
self.send(404, {"error": "not found"})
def do_POST(self):
p = urlparse(self.path).path
try:
- m = re.match(r"^/api/furniture/(\w+)$", p)
- if m and m.group(1) in catalog.CATALOG: # your model for this item, as a .glb file
+ m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})/model/(\w+)$", p)
+ if m and m.group(1) in themes.custom_ids() and m.group(2) in themes.SLOTS: # your model for a piece (.glb)
data = self.body()
if not data.startswith(b"glTF"):
return self.send(400, {"error": "Please upload a .glb file (binary glTF)."})
- os.makedirs(CUSTOM, exist_ok=True)
- with open(os.path.join(CUSTOM, m.group(1) + ".glb"), "wb") as fh:
+ os.makedirs(os.path.dirname(themes.upload_path(*m.groups())), exist_ok=True)
+ with open(themes.upload_path(*m.groups()), "wb") as fh:
fh.write(data)
- if os.path.exists(os.path.join(THUMBS, m.group(1) + ".png")):
- os.remove(os.path.join(THUMBS, m.group(1) + ".png"))
- refresh_thumbs()
+ t = json.load(open(os.path.join(themes.DIR, m.group(1) + ".json")))
+ t["slots"][m.group(2)] = "upload"
+ save_theme(m.group(1), t)
return self.send(200, {"ok": True})
+ m = re.match(r"^/api/themes(?:/([a-z0-9][a-z0-9_-]{0,29}))?$", p)
+ if m: # make (no id) or change one of your own themes
+ return self.send(200, {"id": save_theme(m.group(1), json.loads(self.body() or b"{}"))})
if p == "/api/mp4": # a WebM recording in, the same video as MP4 out
if not shutil.which("ffmpeg"):
return self.send(501, {"error": "ffmpeg is not installed on the server"})
@@ -512,6 +566,9 @@ class H(BaseHTTPRequestHandler):
wall = req.get("wall_color")
if "wall_color" in req and not (isinstance(wall, str) and re.fullmatch(r"#[0-9a-fA-F]{6}", wall)):
return self.send(400, {"error": "Wall colour must look like #rrggbb."})
+ th = req.get("theme")
+ if "theme" in req and not (isinstance(th, str) and (th in themes.THEMES or th in themes.custom_ids())):
+ return self.send(400, {"error": "Unknown interior theme."})
check_items(req)
with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
json.dump(req, fh)
diff --git a/tests/run_all.sh b/tests/run_all.sh
index 204aa70..224f0c2 100755
--- a/tests/run_all.sh
+++ b/tests/run_all.sh
@@ -7,6 +7,7 @@ python3 tests/test_sample.py
python3 tests/test_detect.py
python3 tests/test_server.py
python3 tests/test_quantities.py
+python3 tests/test_themes.py
python3 detect.py examples/sample_plan.pdf /tmp/planto3d_sample.json > /dev/null
for p in /tmp/planto3d_sample.json jobs/*/plan.json; do
[ -f "$p" ] || continue
diff --git a/tests/test_server.py b/tests/test_server.py
index 17b4b5a..de75976 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -8,9 +8,11 @@ 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 detect, server # noqa: E402
+import detect, server, themes # noqa: E402
server.JOBS = tempfile.mkdtemp() # never touch the real jobs folder
+themes.DIR, server.THUMBS = tempfile.mkdtemp(), tempfile.mkdtemp() # nor the real themes and their pictures
+server.refresh_thumbs = lambda tid, again=True: None # (pictures need Blender)
httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), server.H)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
URL = f"http://127.0.0.1:{httpd.server_port}"
@@ -113,6 +115,32 @@ try:
server.run_detect(jid)
assert "scan" in server.read_status(jid)["message"]
print("ok server: a cover sheet before the plan, a PDF without lines")
+
+ # interior themes: the built-in ones are listed and fixed; own ones are checked, take .glb models, and can be chosen
+ code, out = call("GET", "/api/themes")
+ out = json.loads(out)
+ assert code == 200 and {"contemporary", "minimalist", "royal", "rustic"} <= {t["id"] for t in out["themes"]}, out
+ assert "GothicBed_01" in out["choices"]["bed"]
+ for bad in (b"[]", b"{}", b'{"label": "x", "slots": {"bed": "../x"}}', b'{"label": "x", "colours": {"wood": "red"}}'):
+ assert call("POST", "/api/themes", bad)[0] == 400, bad
+ assert call("POST", "/api/themes/royal", b'{"label": "Mine"}')[0] == 400 # built-in: not changed
+ code, out = call("POST", "/api/themes", b'{"label": "My Royal", "slots": {"bed": "GothicBed_01"}}')
+ tid = json.loads(out)["id"]
+ assert code == 200 and tid == "my-royal" and os.path.exists(os.path.join(themes.DIR, tid + ".json"))
+ assert json.loads(call("POST", "/api/themes", b'{"label": "My Royal"}')[1])["id"] == "my-royal-2"
+ assert call("POST", f"/api/themes/{tid}/model/sofa", b"not a glb")[0] == 400
+ assert call("POST", f"/api/themes/{tid}/model/sink", b"glTF")[0] == 404 # not a slot
+ assert call("POST", "/api/themes/royal/model/sofa", b"glTF")[0] == 404 # not your own theme
+ assert call("POST", f"/api/themes/{tid}/model/sofa", b"glTF\x02")[0] == 200
+ assert themes.load(tid)["slots"]["sofa"] == "upload" and os.path.exists(themes.upload_path(tid, "sofa"))
+ assert call("DELETE", f"/api/themes/{tid}/model/sofa")[0] == 200 and themes.load(tid)["slots"]["sofa"] == "@contemporary"
+ jid = job("detected")
+ for bad in (b'{"floors": [{}], "theme": "nope"}', b'{"floors": [{}], "theme": ["royal"]}', b'{"floors": [{}], "theme": "../x"}'):
+ assert call("POST", f"/api/jobs/{jid}/plan", bad)[0] == 400, bad
+ assert call("POST", f"/api/jobs/{jid}/plan", json.dumps({"floors": [{}], "theme": tid}).encode())[0] == 200
+ assert call("DELETE", "/api/themes/royal")[0] == 404
+ assert call("DELETE", f"/api/themes/{tid}")[0] == 200 and tid not in themes.custom_ids()
+ print("ok server: interior themes")
finally:
httpd.shutdown()
shutil.rmtree(server.JOBS)
diff --git a/tests/test_site.mjs b/tests/test_site.mjs
index 902c8f5..8a89a49 100644
--- a/tests/test_site.mjs
+++ b/tests/test_site.mjs
@@ -1,5 +1,5 @@
// End-to-end check of the site in a real (headless) browser, against a running server:
-// the upload page rejects a non-PDF and accepts a PDF; the review page's "Furniture" box, unticked, gives a draft build
+// the upload page rejects a non-PDF and accepts a PDF; the review page's "Furniture" box, unticked, with the Royal theme, gives a draft build
// whose saved plan has furnish=false, and the build box shows status words and the time left; in the walkthrough, P saves a 4K-size PNG, R records a video, M enlarges the map, N measures and T-T returns to walking; F changes a floor and the wall colour and saves them; the Website zip loads on its own.
// Takes about 2 min (one draft build); removes its own job.
// CHROME=/path/to/chromium node tests/test_site.mjs <plan.pdf> [http://127.0.0.1:8080]
@@ -39,6 +39,8 @@ try {
assert(job, 'a PDF should open the review page');
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`), true, 'Furniture box should start ticked');
+ for (let i = 0; i < 50 && (await ev(`document.getElementById('theme').options.length`)) < 4; i++) await sleep(100);
+ await ev(`(() => { const t = document.getElementById('theme'); t.value = 'royal'; t.dispatchEvent(new Event('change')); })()`);
await ev(`document.getElementById('furn').click(); document.getElementById('quality').value = 'draft'; document.getElementById('build').click()`);
let st, sawEta = false, sawWord = false, sawStep = false;
for (let i = 0; i < 400; i++) {
@@ -58,15 +60,26 @@ try {
assert.match(await ev(`document.getElementById('bmsg').textContent`), /built in \d+ (s|min)/, 'the build box should say how long the build took');
const plan = await (await fetch(`${base}/jobs/${job}/plan.json`)).json();
assert.strictEqual(plan.furnish, false, 'plan.furnish should be false after unticking');
+ assert.strictEqual(plan.theme, 'royal', 'the chosen interior theme should be saved in the plan');
// reopening the page must show the saved choice
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
+ assert.equal(await ev(`document.getElementById('theme').value`), 'royal', 'the Theme box should show the saved theme after reload');
+ // a plan whose theme is gone (deleted on the Themes page) can still be saved: the page drops it
+ await (await fetch(`${base}/api/jobs/${job}/plan`, { method: 'POST', body: JSON.stringify({ ...plan, theme: 'royal' }) })).json();
+ fs.writeFileSync(new URL(`../jobs/${job}/plan.json`, import.meta.url), JSON.stringify({ ...plan, theme: 'gone-theme' }));
+ 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);
+ await ev(`document.querySelector('[data-t=furniture]').click()`); // (saves the plan)
+ await sleep(1500);
+ assert.equal((await (await fetch(`${base}/jobs/${job}/plan.json`)).json()).theme, undefined, 'a deleted theme should be dropped, not block saving');
+ await ev(`(() => { const t = document.getElementById('theme'); t.value = 'royal'; t.dispatchEvent(new Event('change')); document.querySelector('[data-t=select]').click(); })()`);
+ // the themes 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');
+ for (let i = 0; i < 50 && !cards; i++) { await sleep(200); cards = await ev(`document.getElementById('modelsframe').contentDocument?.querySelectorAll('#list .theme').length || 0`); }
+ assert(cards >= 4 && await ev(`document.getElementById('modelsdlg').open`), 'See and make themes should show the themes 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
@@ -139,7 +152,7 @@ try {
for (let i = 0; i < 150 && !(await ev('!!window.__ready')); i++) await sleep(200);
assert.equal(await ev('!!window.__ready'), true, 'the downloaded website should load the walkthrough');
} finally { web.kill(); fs.rmSync(sd, { recursive: true }); }
- console.log('PASS upload page, furniture option, furniture models dialog, build box, screenshot, recording, map, measure, top view, finishes and website');
+ console.log('PASS upload page, furniture option, theme, themes dialog, build box, screenshot, recording, map, measure, top view, finishes and website');
} 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/tests/test_themes.py b/tests/test_themes.py
new file mode 100644
index 0000000..d22324d
--- /dev/null
+++ b/tests/test_themes.py
@@ -0,0 +1,49 @@
+"""Interior themes without Blender: the built-in themes only name pieces that exist, every library model is downloaded
+by fetch_assets.py, the furniture rules furnish the sample in every theme without clashes (decor where a theme has it),
+and people's own themes are checked before they are stored. python3 tests/test_themes.py"""
+import json, os, sys, tempfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.dirname(HERE))
+import detect, fetch_assets, furnish, themes # noqa: E402
+
+for tid, t in themes.THEMES.items():
+ assert themes.check(t)["slots"] == t["slots"], tid # every piece is one the slot may hold
+for m, (label, w, d, h, turn, slots) in themes.LIBRARY.items():
+ assert m in fetch_assets.MODELS and min(w, d, h) > 0 and turn in (0, 90, 180, 270), m
+ assert set(slots) <= set(themes.SLOTS), m
+assert themes.load(None)["id"] == themes.load("nope")["id"] == themes.load("../royal")["id"] == "contemporary"
+print("ok themes: built-in pieces exist, library models are downloaded")
+
+plan = detect.detect(os.path.join(HERE, "..", "examples", "sample_plan.pdf"))
+f = plan["floors"][0]
+items = {tid: furnish.furnish_floor(f, themes.load(tid)) for tid in themes.THEMES}
+for tid, its in items.items():
+ assert not furnish.clashes(its, f), (tid, furnish.clashes(its, f))
+fns = {tid: {it["fn"] for it in its} for tid, its in items.items()}
+assert not fns["contemporary"] & {"art", "mirror", "decor", "corner", "armchair", "bed_end"}, fns["contemporary"]
+assert not any("piece" in it["kw"] for it in items["contemporary"])
+assert {"art", "mirror", "decor", "corner", "armchair"} <= fns["royal"], fns["royal"]
+assert {"bed_end", "corner", "armchair"} <= fns["rustic"], fns["rustic"]
+bed = next(it for it in items["royal"] if it["fn"] == "bed")
+dims = sorted((bed["box"][1] - bed["box"][0], bed["box"][3] - bed["box"][2]))
+assert abs(dims[0] - 4.9) < 0.01 and abs(dims[1] - 6.69) < 0.01, bed["box"] # the model at its own size
+print("ok themes: the sample furnished in every theme, decor where the theme has it")
+
+themes.DIR = tempfile.mkdtemp()
+for bad in ([], {}, {"label": ""}, {"label": "x" * 41}, {"label": "a", "slots": {"bed": "../../etc"}},
+ {"label": "a", "slots": {"sink": "@contemporary"}}, {"label": "a", "slots": {"bed": "sofa_03"}},
+ {"label": "a", "colours": {"wood": "brown"}}, {"label": "a", "colours": {"lava": "#123456"}},
+ {"label": "a", "floors": {"living": "lava"}}, {"label": "a", "wall": "#12345"}):
+ try:
+ themes.check(bad)
+ raise AssertionError(bad)
+ except ValueError:
+ pass
+t = themes.check({"label": " Mine ", "slots": {"bed": "upload", "sofa": "sofa_03"}, "colours": {"wood": "#112233"}, "evil": 1})
+assert t["label"] == "Mine" and "evil" not in t
+json.dump(t, open(os.path.join(themes.DIR, "mine.json"), "w"))
+m = themes.load("mine")
+assert m["id"] == "mine" and m["slots"]["sofa"] == "sofa_03" and m["slots"]["bed"] == "@contemporary" # (no upload on disk)
+assert themes.custom_ids() == ["mine"]
+print("ok themes: own themes are checked, stored and loaded")
diff --git a/themes.py b/themes.py
new file mode 100644
index 0000000..4928b02
--- /dev/null
+++ b/themes.py
@@ -0,0 +1,208 @@
+"""Interior themes: which furniture, decor, colours and floors a house is built with. Pure Python: the server lists and
+checks them, furnish.py sizes the furniture by them, blender/gen.py builds them.
+Built-in themes are below. People's own themes are JSON files in assets/themes/<id>.json (made on the Themes page),
+with their uploaded models next to them in assets/themes/<id>/<slot>.glb.
+
+A slot is filled by one of
+ "@<style>" a piece blender/gen.py draws itself ("@contemporary" is the look PlanTo3D always built)
+ "<model>" a Poly Haven model from LIBRARY (downloaded by fetch_assets.py into assets/models/)
+ "upload" the person's own .glb (custom themes only)"""
+import json, os, re
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+DIR = os.path.join(HERE, "assets", "themes")
+
+# slot -> label: the furniture rules' items (named as in their furniture lists), the dining chairs, the ceiling light,
+# and the decor the rules add only when a theme has something for it
+SLOTS = dict(bed="Bed", nightstand="Nightstand", wardrobe="Wardrobe", desk="Desk", sofa="Sofa", coffee_table="Coffee table",
+ tv_unit="TV unit", dining_set="Dining table", dining_chair="Dining chair", armchair="Armchair",
+ light="Ceiling light", art="Wall art", mirror="Mirror", decor="Decor piece", corner="Corner piece",
+ bed_end="Bed bench", fridge2="Fridge", washer2="Washing machine", wc2="WC", vanity="Basin",
+ puja_mandir="Mandir", plant="Plant")
+
+# built-in pieces per slot ("@contemporary" everywhere it exists; a slot missing here has no built-in piece: empty)
+STYLES = dict(
+ bed={"@contemporary": "Upholstered bed", "@low": "Low platform bed", "@farmhouse": "Farmhouse plank bed"},
+ nightstand={"@contemporary": "Nightstand with a drawer"},
+ wardrobe={"@contemporary": "Wardrobe with bar handles", "@flat": "Handleless white wardrobe", "@classic": "Carved walnut armoire",
+ "@farmhouse": "Painted plank wardrobe"},
+ desk={"@contemporary": "Writing desk"},
+ sofa={"@contemporary": "Cushioned velvet sofa", "@low": "Low linen sofa"},
+ coffee_table={"@contemporary": "Marble tea table", "@plank": "Reclaimed plank table"},
+ tv_unit={"@contemporary": "Low TV unit"},
+ dining_set={"@contemporary": "Four-leg dining table", "@oak": "Slim oak table", "@classic": "Turned-leg walnut table"},
+ dining_chair={"@contemporary": "Cushioned dining chair", "@plain": "Oak and linen chair"},
+ light={"@contemporary": "Flush ceiling light"},
+ fridge2={"@contemporary": "Steel fridge"}, washer2={"@contemporary": "Front-loading washer"}, wc2={"@contemporary": "Wall-hung WC"},
+ vanity={"@contemporary": "Basin on a vanity"}, puja_mandir={"@contemporary": "Wooden mandir"}, plant={"@contemporary": "Potted plant"},
+)
+
+# Poly Haven models (CC0): label, size in feet as built (w across the front, d front to back, h) after turning by
+# `turn` degrees so the front faces -y, and the slots that may use it. Sizes measured from the imported models.
+LIBRARY = {
+ # minimalist
+ "side_table_01": ("Oak side table", 1.8, 1.48, 1.81, 0, ("nightstand", "decor")),
+ "coffee_table_round_01": ("Round stone coffee table", 4.27, 4.27, 1.61, 0, ("coffee_table",)),
+ "modern_coffee_table_01": ("Stone and oak coffee table", 3.94, 1.97, 1.28, 90, ("coffee_table",)),
+ "modern_wooden_cabinet": ("Slatted walnut sideboard", 8.01, 1.71, 2.23, 0, ("tv_unit",)),
+ "modern_arm_chair_01": ("Leather and oak armchair", 2.69, 3.24, 3.36, 0, ("armchair",)),
+ "mid_century_lounge_chair": ("Mid-century lounge chair", 3.31, 3.91, 3.84, 0, ("armchair",)),
+ "modern_ceiling_lamp_01": ("Globe pendant lamp", 1.42, 1.42, 3.12, 0, ("light",)),
+ "hanging_picture_frame_01": ("Black frame print", 1.95, 0.05, 2.76, 180, ("art",)),
+ "ceramic_vase_01": ("White ceramic vase", 0.67, 0.67, 1.31, 0, ("decor",)),
+ "ceramic_vase_02": ("Stoneware vase", 0.72, 0.72, 1.01, 0, ("decor",)),
+ "wooden_display_shelves_01": ("Cube shelves", 3.54, 1.22, 5.11, 90, ("corner",)),
+ "Ottoman_01": ("Leather ottoman", 2.9, 2.04, 2.05, 0, ("bed_end",)),
+ # royal
+ "GothicBed_01": ("Carved four-poster bed", 4.9, 6.69, 5.03, 0, ("bed",)),
+ "ClassicNightstand_01": ("Carved nightstand", 1.86, 1.39, 2.3, 0, ("nightstand",)),
+ "GothicCommode_01": ("Carved commode", 3.94, 1.91, 3.98, 0, ("tv_unit",)),
+ "ClassicConsole_01": ("Carved console table", 5.06, 1.93, 3.11, 0, ("desk", "tv_unit")),
+ "sofa_03": ("Rolled-arm manor sofa", 8.96, 3.04, 3.67, 0, ("sofa",)),
+ "Sofa_01": ("Carved camelback sofa", 5.16, 2.16, 2.61, 0, ("sofa",)),
+ "ArmChair_01": ("Carved bergère armchair", 2.78, 2.51, 3.49, 0, ("armchair",)),
+ "GreenChair_01": ("Carved green armchair", 2.21, 2.18, 3.47, 0, ("dining_chair", "armchair")),
+ "gothic_coffee_table": ("Carved square coffee table", 4.73, 4.73, 1.83, 0, ("coffee_table",)),
+ "Chandelier_01": ("Brass chandelier", 2.45, 2.68, 2.62, 0, ("light",)),
+ "Chandelier_02": ("Small brass chandelier", 2.23, 2.03, 2.78, 0, ("light",)),
+ "fancy_picture_frame_01": ("Gilded oil painting", 1.98, 0.07, 1.52, 0, ("art",)),
+ "ornate_mirror_01": ("Gilded mirror", 1.6, 0.09, 2.44, 0, ("mirror", "art")),
+ "brass_vase_02": ("Brass vase", 0.69, 0.69, 1.73, 0, ("decor",)),
+ "marble_bust_01": ("Marble bust", 0.89, 0.98, 1.69, 0, ("decor",)),
+ "vintage_grandfather_clock_01": ("Grandfather clock", 2.05, 1.4, 7.19, 0, ("corner",)),
+ # rustic farmhouse
+ "painted_wooden_nightstand": ("Painted nightstand", 1.66, 1.67, 2.02, 0, ("nightstand",)),
+ "painted_wooden_cabinet": ("Distressed white cabinet", 3.92, 2.02, 3.88, 0, ("tv_unit",)),
+ "painted_wooden_sofa": ("Painted wooden settee", 8.04, 2.58, 4.2, 0, ("sofa",)),
+ "Rockingchair_01": ("Rocking chair", 2.32, 2.73, 3.26, 0, ("armchair",)),
+ "painted_wooden_table": ("Painted trestle table", 7.89, 3.73, 3.15, 0, ("dining_set",)),
+ "painted_wooden_chair_01": ("White painted chair", 1.42, 1.77, 3.14, 0, ("dining_chair",)),
+ "painted_wooden_chair_02": ("Blue ladder-back chair", 2.1, 2.17, 4.15, 0, ("dining_chair",)),
+ "lantern_chandelier_01": ("Iron lantern chandelier", 1.9, 1.89, 2.88, 0, ("light",)),
+ "hanging_picture_frame_02": ("Landscape in white frame", 2.47, 0.11, 1.64, 180, ("art",)),
+ "wicker_basket_02": ("Wicker basket", 1.23, 0.89, 0.72, 0, ("decor",)),
+ "metal_jug": ("Milk churn", 0.65, 0.64, 0.94, 0, ("decor",)),
+ "painted_wooden_bench": ("Painted bench", 3.82, 1.63, 2.92, 0, ("bed_end",)),
+ "painted_wooden_shelves": ("Painted wall shelf", 1.68, 1.2, 3.69, 0, ("corner",)),
+}
+
+# colours (sRGB "#rrggbb") of the built-in pieces' materials: wood, kitchen and wardrobe cabinets, upholstery,
+# curtains, rugs, cushions and throws. A missing one keeps the contemporary material. Built-in themes may also name
+# a texture per colour (tex), whose grain or weave is kept under the colour.
+COLOURS = ("wood", "cabinet", "fabric", "curtain", "rug", "accent")
+FINISHES = ("marble", "wood", "parquet", "tile", "bathtile", "terracotta", "concrete") # as server.py FINISHES
+
+THEMES = {
+ "contemporary": dict(label="Contemporary", about="Warm modern: walnut, velvet and marble. The look PlanTo3D has always built.",
+ slots={}, colours={}, floors={}, wall=None, tv=True),
+ "minimalist": dict(
+ label="Minimalist", about="Pale oak, white and grey linen, stone, and nothing more than a room needs.",
+ slots=dict(bed="@low", nightstand="side_table_01", wardrobe="@flat", sofa="@low", coffee_table="coffee_table_round_01",
+ tv_unit="modern_wooden_cabinet", dining_set="@oak", dining_chair="@plain", armchair="modern_arm_chair_01",
+ light="modern_ceiling_lamp_01", art="hanging_picture_frame_01", decor="ceramic_vase_01"),
+ colours=dict(wood="#d9bf9c", cabinet="#f1efea", fabric="#c9c6bf", curtain="#f3f0ea", rug="#d8d3ca", accent="#8c8a85"),
+ floors=dict(living="tile", dining="tile", kitchen="tile", passage="tile", bedroom="wood", study="wood", dress="wood"),
+ wall="#f4f2ee", tv=True, tex=dict(wood="ash_veneer")),
+ "royal": dict(
+ label="Royal", about="A European palace: carved dark wood, curved sofas, brass chandeliers, gilded mirrors and oil paintings.",
+ slots=dict(bed="GothicBed_01", nightstand="ClassicNightstand_01", wardrobe="@classic", desk="ClassicConsole_01",
+ sofa="sofa_03", coffee_table="gothic_coffee_table", tv_unit="GothicCommode_01", dining_set="@classic",
+ dining_chair="GreenChair_01", armchair="ArmChair_01", light="Chandelier_01", art="fancy_picture_frame_01",
+ mirror="ornate_mirror_01", decor="brass_vase_02", corner="vintage_grandfather_clock_01"),
+ colours=dict(wood="#4a2c1d", cabinet="#efe4cc", fabric="#6f1d2a", curtain="#7a2333", rug="#8c3b2e", accent="#c9a24a"),
+ floors=dict(living="marble", dining="marble", passage="marble", kitchen="marble", bedroom="parquet", study="parquet",
+ dress="parquet"),
+ wall="#ece0c8", tv=False, tex=dict(curtain="velour_velvet", rug="floral_jacquard")),
+ "rustic": dict(
+ label="Rustic farmhouse", about="Painted and weathered wood, a trestle table, gingham and linen, iron lanterns.",
+ slots=dict(bed="@farmhouse", nightstand="painted_wooden_nightstand", wardrobe="@farmhouse", sofa="painted_wooden_sofa",
+ coffee_table="@plank", tv_unit="painted_wooden_cabinet", dining_set="painted_wooden_table",
+ dining_chair="painted_wooden_chair_02", armchair="Rockingchair_01", light="lantern_chandelier_01",
+ art="hanging_picture_frame_02", decor="wicker_basket_02", corner="painted_wooden_shelves",
+ bed_end="painted_wooden_bench"),
+ colours=dict(wood="#8b6a48", cabinet="#8fa386", fabric="#bfae90", curtain="#e4dccb", rug="#b89c78", accent="#7d4b3a"),
+ floors=dict(living="terracotta", dining="terracotta", kitchen="terracotta", passage="terracotta", bedroom="wood",
+ study="wood", dress="wood"),
+ wall="#efe6d6", tv=True, tex=dict(curtain="gingham_check")),
+}
+DEFAULT = "contemporary"
+TEXTURES = {v for t in THEMES.values() for v in t.get("tex", {}).values()}
+ID = re.compile(r"^[a-z0-9][a-z0-9_-]{0,29}$")
+HEX = re.compile(r"^#[0-9a-fA-F]{6}$")
+
+
+def choices(slot):
+ """what a slot may hold: built-in pieces and library models (value -> label)"""
+ return {**STYLES.get(slot, {}), **{m: v[0] for m, v in LIBRARY.items() if slot in v[5]}}
+
+
+def check(t):
+ """a theme from a browser, made safe to store: -> clean dict, or ValueError with a message a person can read"""
+ if not isinstance(t, dict):
+ raise ValueError("A theme must be a JSON object.")
+ label = t.get("label")
+ if not (isinstance(label, str) and 0 < len(label.strip()) <= 40):
+ raise ValueError("Give the theme a name of up to 40 characters.")
+ slots = t.get("slots") or {}
+ if not isinstance(slots, dict) or any(s not in SLOTS or not isinstance(v, str) or (v != "upload" and v not in choices(s))
+ for s, v in slots.items()):
+ raise ValueError("Unknown furniture in the theme.")
+ colours = t.get("colours") or {}
+ if not isinstance(colours, dict) or any(k not in COLOURS or not (isinstance(v, str) and HEX.match(v)) for k, v in colours.items()):
+ raise ValueError("Colours must look like #rrggbb.")
+ floors = t.get("floors") or {}
+ if not isinstance(floors, dict) or any(not (isinstance(k, str) and re.fullmatch(r"[a-z]{1,12}", k)) or v not in FINISHES
+ for k, v in floors.items()):
+ raise ValueError("Unknown floor finish in the theme.")
+ wall = t.get("wall")
+ if wall is not None and not (isinstance(wall, str) and HEX.match(wall)):
+ raise ValueError("Wall colour must look like #rrggbb.")
+ tex = t.get("tex") or {} # (kept from the built-in theme a copy was made from)
+ if not isinstance(tex, dict) or any(k not in COLOURS or v not in TEXTURES for k, v in tex.items()):
+ raise ValueError("Unknown texture in the theme.")
+ return dict(label=label.strip(), about=str(t.get("about") or "")[:200], slots=slots, colours=colours, floors=floors,
+ wall=wall, tv=t.get("tv") is not False, tex=tex)
+
+
+def custom_ids():
+ return sorted(f[:-5] for f in os.listdir(DIR) if f.endswith(".json") and ID.match(f[:-5])) if os.path.isdir(DIR) else []
+
+
+def load(tid):
+ """the theme to build with, every slot filled: a missing or unknown id is the contemporary theme"""
+ tid = tid if isinstance(tid, str) else DEFAULT
+ if tid in THEMES:
+ t = dict(THEMES[tid], builtin=True)
+ elif ID.match(tid) and os.path.exists(os.path.join(DIR, tid + ".json")):
+ try:
+ t = dict(check(json.load(open(os.path.join(DIR, tid + ".json")))), builtin=False)
+ except (ValueError, json.JSONDecodeError):
+ tid, t = DEFAULT, dict(THEMES[DEFAULT], builtin=True)
+ else:
+ tid, t = DEFAULT, dict(THEMES[DEFAULT], builtin=True)
+ slots = {s: "@contemporary" if "@contemporary" in STYLES.get(s, {}) else None for s in SLOTS}
+ slots.update(t["slots"])
+ for s, v in slots.items(): # an upload whose file is gone falls back to the built-in piece
+ if v == "upload" and not os.path.exists(upload_path(tid, s)):
+ slots[s] = "@contemporary" if "@contemporary" in STYLES.get(s, {}) else None
+ return dict(t, id=tid, slots=slots)
+
+
+def upload_path(tid, slot):
+ return os.path.join(DIR, tid, slot + ".glb")
+
+
+def size(theme, slot):
+ """(w, d, h) in feet of a slot filled by a library model, else None (built-in pieces and uploads take the rules' sizes)"""
+ v = theme["slots"].get(slot)
+ return LIBRARY[v][1:4] if v in LIBRARY else None
+
+
+def has(theme, slot):
+ """the theme puts something in this decor slot (contemporary has none of them)"""
+ return theme["slots"].get(slot) not in (None, "@contemporary")
+
+
+def label(theme, slot):
+ v = theme["slots"].get(slot)
+ return LIBRARY[v][0] if v in LIBRARY else STYLES.get(slot, {}).get(v) or SLOTS[slot]
diff --git a/web/edit.html b/web/edit.html
index 10a02e2..13b7e35 100644
--- a/web/edit.html
+++ b/web/edit.html
@@ -74,7 +74,8 @@
<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 class="row" style="margin-top:8px"><span>Theme</span><select id="theme" style="width:170px" title="The furniture, decor, colours and floors the house is built with"></select></div>
+ <button class="btn ghost" id="models" type="button" style="margin-top:8px;width:100%">See and make themes</button>
<button class="btn ghost" id="qty" type="button" style="margin-top:8px;width:100%" title="Floor areas, wall paint and tiles, doors, windows and furniture">Quantities</button>
</div>
<div>
@@ -109,7 +110,7 @@
</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>
+ <iframe id="modelsframe" title="Interior themes" style="width:100%;height:100%;border:0"></iframe>
</dialog>
<script type="module" src="/web/edit.js"></script>
</body>
diff --git a/web/edit.js b/web/edit.js
index fc14d35..ef3a036 100644
--- a/web/edit.js
+++ b/web/edit.js
@@ -8,9 +8,12 @@ const ZCOL = { bedroom: '#c8a2c8', toilet: '#8fc7e8', kitchen: '#f2c48d', living
wash: '#a8d5c2', store: '#bbb', study: '#b8c9a0', passage: '#d9d2c3', balcony: '#b6dfa0', garden: '#7fc97f', open: '#9fd8d0',
parking: '#c9c9d6', yard: '#cfe6b8', stair: '#c49a6c', room: '#dcdcdc', duct: '#999', dress: '#e3d2b8' };
// room.floor: material names in blender/lib.py (server.py FINISHES checks them); no value = by room type
-const FINISH = { '': 'Auto (by room type)', marble: 'Marble', wood: 'Wood', tile: 'Tiles', bathtile: 'Bathroom tiles',
- terracotta: 'Terracotta', concrete: 'Concrete' };
-const WALL = '#efe7da'; // lib.py's warm white in sRGB: choosing it drops plan.wall_color, so the build is as before
+const FINISH = { '': 'Auto (theme, room type)', marble: 'Marble', wood: 'Wood', parquet: 'Parquet', tile: 'Tiles',
+ bathtile: 'Bathroom tiles', terracotta: 'Terracotta', concrete: 'Concrete' };
+const WALL = '#efe7da'; // lib.py's warm white in sRGB
+let themes = []; // from /api/themes: the theme's own wall colour is the default one
+// the wall colour the build uses without plan.wall_color: choosing it drops wall_color, so the build is as before
+const wall0 = () => themes.find((t) => t.id === (plan.theme || 'contemporary'))?.wall || WALL;
const D = 100 / 72; // page image px per PDF point
let plan, fi = 0, sel = null, tool = 'select', img = {}, history = [];
let view = { k: 10, ox: 40, oy: 600 };
@@ -47,8 +50,25 @@ async function load() {
}
$('fh').value = plan.floor_height;
$('furn').checked = plan.furnish !== false;
+ await loadThemes();
fit(); ui();
}
+async function loadThemes() {
+ themes = (await fetch('/api/themes').then((r) => r.json())).themes;
+ if (plan.theme && !themes.some((t) => t.id === plan.theme)) delete plan.theme; // deleted: the server would refuse the plan
+ $('theme').replaceChildren(...themes.map((t) => new Option(t.label, t.id)));
+ $('theme').value = themes.some((t) => t.id === plan.theme) ? plan.theme : 'contemporary';
+}
+$('theme').onchange = (e) => {
+ const edited = plan.floors.filter((f) => f.items).length;
+ // furniture moved on the review page was sized for the old theme: start again from the new one's, if wanted
+ if (edited && confirm(`You changed the furniture on ${edited} floor${edited > 1 ? 's' : ''}. Start again from the new theme's furniture there?`)) {
+ snapshot();
+ plan.floors.forEach((f) => delete f.items);
+ }
+ if (e.target.value === 'contemporary') delete plan.theme; else plan.theme = e.target.value;
+ if (tool === 'furniture') loadFurniture(); else { auto = null; ui(); }
+};
// playful words while Blender works, with the time left beside them
const WORDS = ['Raising walls', 'Laying bricks', 'Squaring corners', 'Hanging doors', 'Polishing windows', 'Pouring floors',
'Mixing paint', 'Tiling bathrooms', 'Measuring twice', 'Switching on lamps', 'Chasing shadows', 'Baking sunlight', 'Sweeping up'];
@@ -112,7 +132,8 @@ 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];
+// (a theme's wall pieces and the decor on a unit hang or stand at a height that belongs to their place: delete only)
+const movable = (it) => it.args.length === 3 && it.args.every((v) => typeof v === 'number') && it.box[1] > it.box[0] && !('z' in it.kw);
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;
@@ -241,7 +262,8 @@ function ui() {
document.querySelectorAll('#tabs button').forEach((b, i) => b.classList.toggle('on', i === fi));
const f = F();
$('fname').value = f.name;
- $('wc').value = plan.wall_color || WALL;
+ $('wc').value = plan.wall_color || wall0();
+ $('theme').value = themes.some((t) => t.id === plan.theme) ? plan.theme : 'contemporary'; // (also after an undo)
document.querySelectorAll('#paint .sw').forEach((b) => b.classList.toggle('on', b.dataset.c === $('wc').value));
const src = f.scale_source || plan.scale_source;
$('scale').textContent = `${plan.floors.length} floor${plan.floors.length > 1 ? 's' : ''} · scale ${src === 'labels'
@@ -304,7 +326,7 @@ function ui() {
draw();
}
$('fname').oninput = (e) => { F().name = e.target.value; document.querySelectorAll('#tabs button')[fi].textContent = e.target.value; };
-function paint(c) { if ((plan.wall_color || WALL) === c) return; snapshot(); if (c === WALL) delete plan.wall_color; else plan.wall_color = c; ui(); }
+function paint(c) { if ((plan.wall_color || wall0()) === c) return; snapshot(); if (c === wall0()) delete plan.wall_color; else plan.wall_color = c; ui(); }
document.querySelectorAll('#paint .sw').forEach((b) => { b.style.background = b.dataset.c; b.onclick = () => paint(b.dataset.c); });
$('wc').onchange = (e) => paint(e.target.value);
$('fh').onchange = (e) => { plan.floor_height = Math.max(8, Math.min(14, +e.target.value || 10)); };
@@ -459,6 +481,10 @@ $('qty').onclick = async () => { // saved first: the sheet is worked out
if (w) w.location = `/web/quantities.html?job=${job}`;
};
$('models').onclick = () => { // the furniture page, inside this one: replace a model, then build
- $('modelsframe').src = '/web/furniture.html?embed';
+ $('modelsframe').src = '/web/themes.html?embed';
$('modelsdlg').showModal();
};
+$('modelsdlg').onclose = async () => { // a theme made or changed there shows up in the list
+ await loadThemes();
+ if (tool === 'furniture') loadFurniture();
+};
diff --git a/web/furniture.html b/web/furniture.html
deleted file mode 100644
index a113ecc..0000000
--- a/web/furniture.html
+++ /dev/null
@@ -1,57 +0,0 @@
-<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Furniture models</title>
-<link rel="stylesheet" href="/web/style.css?v=2">
-</head>
-<body class="home">
-<main class="wrap" style="max-width:960px">
- <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
- front facing +Z. Houses already built keep their furniture until you build them again.</p>
- <p id="state" class="muted" role="status"></p>
- <div class="furn" id="list"></div>
- <input type="file" id="file" accept=".glb,model/gltf-binary" hidden>
-</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() {
- const f = await fetch('/api/furniture').then((r) => r.json());
- $('state').textContent = f.rendering ? 'Drawing the pictures… (about a minute)' : '';
- $('list').replaceChildren(...f.items.map((it) => {
- const fig = document.createElement('figure');
- if (it.thumb) { const im = new Image(); im.src = `/thumbs/${it.fn}.png?${Date.now()}`; im.alt = it.label; fig.append(im); }
- else fig.append(el('div', 'wait', 'Drawing…'));
- const cap = document.createElement('figcaption');
- const pick = el('button', 'more', it.custom ? 'Change model' : 'Use my model');
- pick.onclick = () => { target = it.fn; $('file').click(); };
- cap.append(el('b', '', it.label), el('span', 'chip' + (it.custom ? ' ok' : ''), it.custom ? 'Your model' : 'Built-in'), pick);
- if (it.custom) {
- const back = el('button', 'more', 'Back to built-in');
- back.onclick = async () => { await fetch(`/api/furniture/${it.fn}`, { method: 'DELETE' }); load(); };
- cap.append(back);
- }
- fig.append(cap);
- return fig;
- }));
- if (f.rendering) setTimeout(load, 3000);
-}
-$('file').onchange = async (e) => {
- const file = e.target.files[0];
- e.target.value = '';
- if (!file) return;
- const r = await fetch(`/api/furniture/${target}`, { method: 'POST', body: file });
- if (!r.ok) alert((await r.json()).error);
- load();
-};
-load();
-</script>
-</body>
-</html>
diff --git a/web/index.html b/web/index.html
index 9c1f4b2..3c594b5 100644
--- a/web/index.html
+++ b/web/index.html
@@ -20,7 +20,7 @@
<span>or click to choose · CAD-exported PDF</span>
</label>
<p id="msg" role="status"></p>
- <p class="links"><button class="more" id="sample">Try the sample plan</button> · <a href="/web/furniture.html">Furniture models</a></p>
+ <p class="links"><button class="more" id="sample">Try the sample plan</button> · <a href="/web/themes.html">Interior themes</a></p>
<p class="steps" id="steps">Detect → Review → Build → Walk</p>
<section class="setup" id="setup" hidden>
diff --git a/web/themes.html b/web/themes.html
new file mode 100644
index 0000000..803f367
--- /dev/null
+++ b/web/themes.html
@@ -0,0 +1,194 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Interior themes</title>
+<link rel="stylesheet" href="/web/style.css?v=2">
+<style>
+ .theme { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px 18px; margin-top: 18px; }
+ .theme h2 { margin: 0; font-size: 19px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
+ .theme > p { margin: 4px 0 10px; }
+ .pics { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
+ .pics figure { margin: 0; }
+ .pics img, .pics .wait { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: 8px; background: var(--bg); }
+ .pics .wait { display: grid; place-items: center; color: var(--muted); font-size: 12px; }
+ .pics figcaption { font-size: 12px; margin-top: 4px; line-height: 1.3; }
+ .pics figcaption b { display: block; font-size: 13px; }
+ .dots { display: flex; gap: 6px; align-items: center; font-size: 13px; color: var(--muted); margin: 10px 0 0; flex-wrap: wrap; }
+ .dots i { width: 18px; height: 18px; border-radius: 50%; border: 1px solid var(--line); display: inline-block; }
+ .acts { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
+ #ed { width: min(760px, 94vw); max-height: 90vh; border: 1px solid var(--line); border-radius: 12px; background: var(--panel); color: var(--ink); padding: 18px 20px; }
+ #ed h3 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 18px 0 6px; }
+ .grid { display: grid; grid-template-columns: 150px 1fr auto; gap: 6px 10px; align-items: center; font-size: 14px; }
+ .grid select { width: 100%; }
+ .grid .more { margin: 0; font-size: 13px; }
+ input[type=color] { width: 40px; height: 28px; padding: 0; border: 1px solid var(--line); border-radius: 6px; background: none; }
+</style>
+</head>
+<body class="home">
+<main class="wrap" style="max-width:1040px">
+ <p class="brand" id="brand"><a href="/" style="color:inherit;text-decoration:none">PlanTo3D</a> · <a href="/">Home</a></p>
+ <h1>Interior themes</h1>
+ <p class="muted">A theme decides the furniture, decor, colours and floors a house is built with. Pick one for a plan on its
+ review page. Make your own from any theme: choose each piece from the library or use your own <code>.glb</code> model
+ (modelled with +Y up and its front facing +Z; it is scaled to the piece's place and stood on the floor).</p>
+ <p id="state" class="muted" role="status"></p>
+ <div id="list"></div>
+</main>
+<dialog id="ed">
+ <form id="edf" method="dialog">
+ <h2 id="edh" style="margin:0 0 4px">New theme</h2>
+ <div class="grid" style="margin-top:12px"><span>Name</span><input type="text" id="edname" maxlength="40" required><span></span></div>
+ <h3>Furniture and decor</h3>
+ <div class="grid" id="edslots"></div>
+ <label style="display:block;margin-top:8px;font-size:14px"><input type="checkbox" id="edtv"> A TV on the TV unit (off: a mirror above it)</label>
+ <h3>Colours</h3>
+ <div class="grid" id="edcolours"></div>
+ <h3>Floors</h3>
+ <div class="grid" id="edfloors"></div>
+ <p id="edmsg" class="muted" style="font-size:13px"></p>
+ <div class="acts"><button class="btn" id="edsave" value="save">Save theme</button><button class="btn ghost" value="cancel" formnovalidate>Close</button></div>
+ </form>
+</dialog>
+<input type="file" id="file" accept=".glb,model/gltf-binary" hidden>
+<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); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+const NAMES = { wood: 'Wood', cabinet: 'Kitchen and cabinets', fabric: 'Sofa and upholstery', curtain: 'Curtains', rug: 'Rugs', accent: 'Cushions and throws' };
+const ROOMS = ['living', 'dining', 'bedroom', 'kitchen', 'study', 'passage'];
+const FIN = { marble: 'Marble', wood: 'Wood', parquet: 'Parquet', tile: 'Tiles', bathtile: 'Bathroom tiles', terracotta: 'Terracotta', concrete: 'Concrete' };
+let data, editing = null, uploadSlot = null, tex = {};
+
+async function load() {
+ data = await fetch('/api/themes').then((r) => r.json());
+ $('state').textContent = data.rendering ? 'Drawing the pictures… (about a minute per theme)' : '';
+ $('list').replaceChildren(...data.themes.map(card));
+ if (data.rendering) setTimeout(load, 4000);
+}
+function card(t) {
+ const c = el('section', 'theme');
+ const h = el('h2', '', t.label);
+ h.append(el('span', 'chip' + (t.builtin ? '' : ' ok'), t.builtin ? 'Built-in' : 'Yours'));
+ c.append(h, el('p', 'muted', t.about || ''));
+ const pics = el('div', 'pics');
+ for (const [s, v] of Object.entries(t.slots)) {
+ if (!(s in t.pictures) && !data.rendering) continue;
+ const f = el('figure');
+ if (s in t.pictures) { const im = new Image(); im.src = `/thumbs/${t.id}/${s}.png?v=${t.pictures[s]}`; im.alt = v.label; im.loading = 'lazy'; f.append(im); }
+ else f.append(el('div', 'wait', 'Drawing…'));
+ const cap = el('figcaption', '', v.label);
+ cap.prepend(el('b', '', data.slots[s]));
+ f.append(cap);
+ pics.append(f);
+ }
+ c.append(pics);
+ const dots = el('p', 'dots');
+ for (const [k, hex] of [['Walls', t.wall], ...Object.entries(t.colours).map(([k, v]) => [NAMES[k], v])]) {
+ if (!hex) continue;
+ const i = el('i'); i.style.background = hex; i.title = k;
+ dots.append(i);
+ }
+ if (dots.children.length) { dots.prepend(el('span', '', 'Colours')); c.append(dots); }
+ const acts = el('div', 'acts');
+ const copy = el('button', 'btn ghost', t.builtin ? 'Make my own from this' : 'Copy');
+ copy.onclick = () => edit(t, true);
+ acts.append(copy);
+ if (!t.builtin) {
+ const e = el('button', 'btn ghost', 'Edit'); e.onclick = () => edit(t, false);
+ const d = el('button', 'btn ghost', 'Delete'); d.style.color = 'var(--bad)';
+ d.onclick = async () => { if (confirm(`Delete the theme "${t.label}"? Plans that use it are built in Contemporary.`)) { await fetch(`/api/themes/${t.id}`, { method: 'DELETE' }); load(); } };
+ acts.append(e, d);
+ }
+ c.append(acts);
+ return c;
+}
+// the editor: a copy of a theme (new) or one of your own
+function edit(t, copy) {
+ editing = copy ? null : t.id;
+ tex = t.tex || {}; // the built-in theme's textures stay with its copies
+ $('edh').textContent = copy ? `New theme from ${t.label}` : `Edit ${t.label}`;
+ $('edname').value = copy ? `My ${t.label.toLowerCase()}` : t.label;
+ $('edtv').checked = t.tv;
+ $('edmsg').textContent = copy ? 'Save the theme first to use your own models in it.' : '';
+ const rows = [];
+ for (const [s, label] of Object.entries(data.slots)) {
+ const sel = el('select'); sel.dataset.slot = s;
+ if (!data.choices[s]['@contemporary']) sel.add(new Option('None', ''));
+ for (const [v, l] of Object.entries(data.choices[s])) sel.add(new Option(l, v));
+ const cur = t.slots[s]?.value || '';
+ if (cur === 'upload') sel.add(new Option('Your own model', 'upload'));
+ sel.value = cur;
+ const side = el('span');
+ if (!copy) {
+ const up = el('button', 'more', cur === 'upload' ? 'Replace your model' : 'Use my model');
+ up.type = 'button';
+ up.onclick = () => { uploadSlot = s; $('file').click(); };
+ side.append(up);
+ if (cur === 'upload') {
+ const back = el('button', 'more', 'Remove'); back.type = 'button';
+ back.onclick = async () => { await fetch(`/api/themes/${editing}/model/${s}`, { method: 'DELETE' }); await reopen(); };
+ side.append(' · ', back);
+ }
+ }
+ rows.push(el('span', '', label), sel, side);
+ }
+ $('edslots').replaceChildren(...rows);
+ const crow = [];
+ for (const [k, l] of [['wall', 'Walls'], ...data.colours.map((k) => [k, NAMES[k]])]) {
+ const v = k === 'wall' ? t.wall : t.colours[k];
+ const on = el('input'); on.type = 'checkbox'; on.checked = !!v; on.title = 'Use this colour (off: as Contemporary)';
+ const c = el('input'); c.type = 'color'; c.value = v || '#d8d0c4'; c.dataset.key = k;
+ c.oninput = () => { on.checked = true; };
+ on.dataset.key = k;
+ crow.push(el('span', '', l), c, on);
+ }
+ $('edcolours').replaceChildren(...crow);
+ const frow = [];
+ for (const r of ROOMS) {
+ const sel = el('select'); sel.dataset.room = r;
+ sel.add(new Option('Auto (by room type)', ''));
+ for (const f of data.finishes) sel.add(new Option(FIN[f] || f, f));
+ sel.value = t.floors[r] || '';
+ frow.push(el('span', '', r[0].toUpperCase() + r.slice(1)), sel, el('span'));
+ }
+ $('edfloors').replaceChildren(...frow);
+ if (!$('ed').open) $('ed').showModal();
+}
+async function reopen() { await load(); const t = data.themes.find((q) => q.id === editing); if (t) edit(t, false); }
+function collect() {
+ const slots = {}, colours = {}, floors = {};
+ let wall = null;
+ for (const s of $('edslots').querySelectorAll('select')) if (s.value) slots[s.dataset.slot] = s.value;
+ for (const c of $('edcolours').querySelectorAll('input[type=color]')) {
+ if (!$('edcolours').querySelector(`input[type=checkbox][data-key="${c.dataset.key}"]`).checked) continue;
+ if (c.dataset.key === 'wall') wall = c.value; else colours[c.dataset.key] = c.value;
+ }
+ for (const s of $('edfloors').querySelectorAll('select')) if (s.value) floors[s.dataset.room] = s.value;
+ return { label: $('edname').value, slots, colours, floors, wall, tv: $('edtv').checked, tex };
+}
+$('edf').onsubmit = async (e) => {
+ if (e.submitter?.value !== 'save') return;
+ e.preventDefault();
+ const r = await fetch(editing ? `/api/themes/${editing}` : '/api/themes', { method: 'POST', body: JSON.stringify(collect()) });
+ const j = await r.json();
+ if (!r.ok) { $('edmsg').textContent = j.error; return; }
+ editing = j.id;
+ await reopen();
+ $('edmsg').textContent = 'Saved. Its pictures are drawn again in a minute.';
+};
+$('file').onchange = async (e) => {
+ const file = e.target.files[0];
+ e.target.value = '';
+ if (!file || !editing) return;
+ $('edmsg').textContent = 'Uploading…';
+ const r = await fetch(`/api/themes/${editing}/model/${uploadSlot}`, { method: 'POST', body: file });
+ if (!r.ok) { $('edmsg').textContent = (await r.json()).error; return; }
+ await reopen();
+ $('edmsg').textContent = 'Your model is in the theme. Its picture is drawn in a minute.';
+};
+load();
+</script>
+</body>
+</html>
diff --git a/web/view.js b/web/view.js
index 7ae83ff..4768dff 100644
--- a/web/view.js
+++ b/web/view.js
@@ -324,7 +324,7 @@ function drawMap(lv) {
// ---- finishes (F): another wall colour, or another floor for the room you stand in, tried on at once. The light stays
// as it was baked for the old finish until the next build; Save puts the choice in the plan for that build.
-const FIN = { marble: 'Marble', wood: 'Wood', tile: 'Tiles', bathtile: 'Bathroom tiles', terracotta: 'Terracotta', concrete: 'Concrete' };
+const FIN = { marble: 'Marble', wood: 'Wood', parquet: 'Parquet', tile: 'Tiles', bathtile: 'Bathroom tiles', terracotta: 'Terracotta', concrete: 'Concrete' };
const WALL0 = '#efe7da'; // edit.js WALL: the build's own white, saved as no wall_color
const finTex = {}, chosen = { floors: {} }; // floors: '<level>_<room index in the plan>' -> finish
let finRoom;