Skip to content

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

Python

Blender build, light bake and tour renderer

23f200563975def0fdb158
diff --git a/blender/bake.py b/blender/bake.py
new file mode 100644
index 0000000..91e9cad
--- /dev/null
+++ b/blender/bake.py
@@ -0,0 +1,285 @@
+"""Bake lighting into lightmaps and export a light web model.
+Each group of objects (one storey, the site) is joined into one mesh, gets a second UV map ('lm') packed by
+Smart UV Project, and Cycles bakes direct + indirect diffuse light (no albedo) into it. The browser multiplies its
+normal textures by this light map, so it needs no real-time lights or shadows - cheap on any GPU.
+Light maps are stored as sRGB-encoded (light / max) WebP; meta.json carries max per map."""
+import math, os
+import bpy
+import numpy as np
+
+SRGB = lambda x: np.where(x <= 0.0031308, 12.92 * x, 1.055 * np.power(np.maximum(x, 0), 1 / 2.4) - 0.055)
+
+
+def _gpu(scene):
+ scene.render.engine = "CYCLES"
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ for dev in ("OPTIX", "CUDA", "HIP", "METAL", "ONEAPI"):
+ try:
+ prefs.compute_device_type = dev
+ prefs.get_devices()
+ if any(d.type == dev for d in prefs.devices):
+ for d in prefs.devices:
+ d.use = True
+ scene.cycles.device = "GPU"
+ return dev
+ except Exception:
+ continue
+ scene.cycles.device = "CPU"
+ return "CPU"
+
+
+def _transparent(ob):
+ for m in ob.data.materials if ob.type == "MESH" else []:
+ if m and m.use_nodes:
+ p = m.node_tree.nodes.get("Principled BSDF")
+ if p and p.inputs["Alpha"].default_value < 0.99:
+ return True
+ return False
+
+
+def _flatten(objs):
+ """bake modifiers into mesh data, make data single-user; -> list of mesh objects"""
+ dg = bpy.context.evaluated_depsgraph_get()
+ out = []
+ for ob in objs:
+ if ob.type != "MESH" or ob.name not in bpy.data.objects or not ob.users_collection:
+ continue # (imported model templates are kept outside the scene - not part of the house)
+ if ob.modifiers:
+ me = bpy.data.meshes.new_from_object(ob.evaluated_get(dg))
+ ob.modifiers.clear()
+ ob.data = me
+ elif ob.data.users > 1:
+ ob.data = ob.data.copy()
+ out.append(ob)
+ return out
+
+
+def _join(name, objs):
+ vl = bpy.context.view_layer
+ for o in vl.objects:
+ o.select_set(False)
+ target = objs[0]
+ coll = target.users_collection[0]
+ for o in objs:
+ o.select_set(True)
+ vl.objects.active = target
+ # keep world transforms: clear parents first
+ for o in objs:
+ if o.parent:
+ mw = o.matrix_world.copy()
+ o.parent = None
+ o.matrix_world = mw
+ with bpy.context.temp_override(active_object=target, selected_editable_objects=objs, selected_objects=objs):
+ bpy.ops.object.join()
+ target.name = name
+ return target
+
+
+def _surface_area(ob):
+ mw = ob.matrix_world
+ s = abs(mw.determinant()) ** (2 / 3)
+ return sum(p.area for p in ob.data.polygons) * s
+
+
+def _clean(ob):
+ """weld box pieces, drop back-to-back faces hidden inside walls, merge coplanar faces (fewer light map seams)"""
+ import bmesh
+ bm = bmesh.new()
+ bm.from_mesh(ob.data)
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0005)
+ bm.faces.ensure_lookup_table()
+ seen, dead = {}, set()
+ for f in bm.faces:
+ c = f.calc_center_median()
+ key = (round(c.x, 3), round(c.y, 3), round(c.z, 3), round(f.calc_area(), 4))
+ g = seen.get(key)
+ if g is not None and g.normal.dot(f.normal) < -0.99:
+ dead.update((g, f))
+ else:
+ seen[key] = f
+ bmesh.ops.delete(bm, geom=list(dead), context="FACES")
+ bmesh.ops.dissolve_limit(bm, angle_limit=math.radians(0.5), verts=bm.verts, edges=bm.edges, delimit={"MATERIAL"})
+ bm.to_mesh(ob.data)
+ bm.free()
+
+
+def _unwrap(ob):
+ _clean(ob)
+ me = ob.data
+ if "UVMap" not in me.uv_layers:
+ me.uv_layers.new(name="UVMap")
+ lm = me.uv_layers.new(name="lm")
+ me.uv_layers["UVMap"].active_render = True
+ me.uv_layers.active = lm
+ vl = bpy.context.view_layer
+ for o in vl.objects:
+ o.select_set(False)
+ ob.select_set(True)
+ vl.objects.active = ob
+ bpy.ops.object.mode_set(mode="EDIT")
+ bpy.ops.mesh.select_all(action="SELECT")
+ kw = dict(angle_limit=math.radians(66), island_margin=0.003, area_weight=0.0, correct_aspect=True, scale_to_bounds=False)
+ try:
+ bpy.ops.uv.smart_project(margin_method="FRACTION", **kw)
+ except TypeError:
+ bpy.ops.uv.smart_project(**kw)
+ bpy.ops.object.mode_set(mode="OBJECT")
+
+
+def _cool_down(progress, limit=78, resume=65):
+ """laptop GPUs overheat on long bakes: pause between bakes while the GPU is hot"""
+ import subprocess, time
+ def temp():
+ try:
+ out = subprocess.run(["nvidia-smi", "--query-gpu=temperature.gpu", "--format=csv,noheader"],
+ capture_output=True, text=True, timeout=5).stdout
+ return max(int(v) for v in out.split())
+ except Exception:
+ return 0
+ t = temp()
+ if t >= limit:
+ progress(None, f"GPU at {t}C - cooling down")
+ while temp() > resume:
+ time.sleep(5)
+
+
+def _texture_size(area_m2, texel_m):
+ px = math.sqrt(area_m2 / 0.55) / texel_m # ~55% of the atlas is covered by islands
+ for s in (512, 1024, 2048, 4096):
+ if px <= s:
+ return s
+ return 4096
+
+
+def _bake(ob, size, samples):
+ img = bpy.data.images.new(f"lm_{ob.name}", size, size, alpha=True, float_buffer=True)
+ nodes = []
+ for m in ob.data.materials:
+ if not m or not m.use_nodes:
+ continue
+ nt = m.node_tree
+ for n in nt.nodes:
+ n.select = False
+ n = nt.nodes.new("ShaderNodeTexImage")
+ n.image = img
+ n.select = True
+ nt.nodes.active = n
+ nodes.append((nt, n))
+ sc = bpy.context.scene
+ sc.cycles.samples = samples
+ sc.cycles.use_denoising = False
+ vl = bpy.context.view_layer
+ for o in vl.objects:
+ o.select_set(False)
+ ob.select_set(True)
+ vl.objects.active = ob
+ bpy.ops.object.bake(type="DIFFUSE", pass_filter={"DIRECT", "INDIRECT"}, margin=6, use_clear=True,
+ target="IMAGE_TEXTURES")
+ for nt, n in nodes:
+ nt.nodes.remove(n)
+ return img
+
+
+def _encode(img, path):
+ """denoise (masked blur inside islands), normalise, sRGB-encode, save WebP -> max light value"""
+ w, h = img.size
+ px = np.empty(w * h * 4, np.float32)
+ img.pixels.foreach_get(px)
+ px = px.reshape(h, w, 4)
+ rgb, a = px[..., :3], (px[..., 3] > 0.5).astype(np.float32)
+
+ def blur(x): # 5-tap separable binomial blur
+ k = np.array([1, 4, 6, 4, 1], np.float32) / 16
+ x = sum(np.roll(x, i - 2, axis=0) * k[i] for i in range(5))
+ return sum(np.roll(x, i - 2, axis=1) * k[i] for i in range(5))
+ # island-edge texels bake from inside the neighbouring geometry and come out dark (the faint seams):
+ # replace a 2-texel rim of every island with light grown outwards from its interior
+ shrink = lambda m: m * np.roll(m, 1, 0) * np.roll(m, -1, 0) * np.roll(m, 1, 1) * np.roll(m, -1, 1)
+ core = shrink(shrink(a))
+ for _ in range(3):
+ cn, cd = blur(rgb * core[..., None]), blur(core)[..., None]
+ rim = (a > 0.5) & (core < 0.5) & (cd[..., 0] > 0.02)
+ rgb = np.where(rim[..., None], cn / np.maximum(cd, 1e-6), rgb)
+ core = np.maximum(core, rim.astype(np.float32))
+ num = blur(rgb * a[..., None])
+ den = blur(a)[..., None]
+ sm = np.where(den > 0.05, num / np.maximum(den, 1e-6), rgb)
+ lum = sm[..., 0] * 0.2126 + sm[..., 1] * 0.7152 + sm[..., 2] * 0.0722
+ vals = lum[a > 0.5]
+ mx = float(np.percentile(vals, 99.5)) if vals.size else 1.0
+ mx = max(mx, 1e-3)
+ enc = SRGB(np.clip(sm / mx, 0, 1))
+ out = np.concatenate([enc, np.ones((h, w, 1), np.float32)], axis=2)
+ o = bpy.data.images.new(os.path.basename(path), w, h, alpha=False)
+ o.colorspace_settings.name = "Non-Color"
+ o.pixels.foreach_set(out.astype(np.float32).ravel())
+ o.filepath_raw = path
+ o.file_format = "WEBP"
+ try:
+ o.save(filepath=path, quality=90)
+ except TypeError:
+ o.save()
+ return mx
+
+
+def bake_and_export(groups, unbaked, out, quality="high", do_bake=True, progress=print):
+ scene = bpy.context.scene
+ dev = _gpu(scene)
+ print("bake device", dev, flush=True)
+ scene.cycles.max_bounces = 6
+ scene.cycles.diffuse_bounces = 4
+ texel = 0.02 if quality == "high" else 0.045
+ samples = 256 if quality == "high" else 64
+ baked, keep, lightmaps, lmax = [], [], {}, {}
+ n = len(groups)
+ for gi, (name, objs) in enumerate(groups.items()):
+ objs = [o for o in objs if o.name in bpy.data.objects]
+ meshes = _flatten(objs)
+ glass = [o for o in meshes if _transparent(o)]
+ solid = [o for o in meshes if o not in glass and len(o.data.polygons)]
+ keep += glass
+ if not solid:
+ continue
+ names = {o.name for o in objs if o.type == "EMPTY"}
+ ob = _join(f"bake_{name}", solid)
+ for nm in names: # parents / empties left behind
+ if nm in bpy.data.objects:
+ bpy.data.objects.remove(bpy.data.objects[nm])
+ baked.append(ob)
+ if not do_bake:
+ continue
+ _unwrap(ob)
+ size = _texture_size(_surface_area(ob), texel)
+ _cool_down(lambda p, m: progress(35 + 55 * gi / n, m))
+ progress(35 + 55 * gi / n, f"baking light for {name} ({size}px)")
+ img = _bake(ob, size, samples)
+ fn = f"lm_{name}.webp"
+ lmax[ob.name] = round(_encode(img, os.path.join(out, fn)), 4)
+ lightmaps[ob.name] = fn
+ bpy.data.images.remove(img)
+ progress(92, "exporting model")
+ vl = bpy.context.view_layer
+ for o in vl.objects:
+ o.select_set(False)
+ sel = baked + keep + [o for o in unbaked if o.name in bpy.data.objects]
+ for o in sel:
+ if o.name in vl.objects:
+ o.select_set(True)
+ for c in o.children_recursive:
+ c.select_set(True)
+ kw = dict(filepath=os.path.join(out, "house.glb"), export_format="GLB", use_selection=True, export_apply=True,
+ export_texcoords=True, export_normals=True, export_lights=False, export_cameras=False,
+ export_image_format="WEBP", export_draco_mesh_compression_enable=True,
+ export_draco_mesh_compression_level=6, export_draco_position_quantization=14,
+ export_draco_normal_quantization=10, export_draco_texcoord_quantization=14)
+ while True:
+ try:
+ bpy.ops.export_scene.gltf(**kw)
+ break
+ except TypeError as e: # option names differ between Blender versions: drop the unknown one
+ bad = next((k for k in kw if k in str(e) and k != "filepath"), None)
+ if not bad:
+ raise
+ kw.pop(bad)
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out, "house_baked.blend"))
+ return dict(lightmaps=lightmaps, lightmap_max=lmax, baked=bool(lightmaps))
diff --git a/blender/cinema.py b/blender/cinema.py
new file mode 100644
index 0000000..17c0abb
--- /dev/null
+++ b/blender/cinema.py
@@ -0,0 +1,383 @@
+"""Cinematic dusk tour of a built house (house.blend from gen.py): blue-hour sky, warm interior light with LED coves,
+garden uplights, one continuous camera glide through every room (route = tour.json), rendered frame by frame with
+heat locks on the GPU and CPU. Resumable: frames already on disk are skipped.
+
+blender -b JOB/house.blend -P blender/cinema.py -- TOUR.json OUTDIR [--stills t1,t2,..] [--shots SHOTS.json] [--save OUT.blend] [--frames] [--res 1920x1080]
+TOUR.json: {"fps": 30, "eye": 5.1, "speed": 1.9, "keys": [{"p": [x, y, z], "t": [x, y, z], "hold": s, "room": "..."}]}
+(feet; 'hold' = seconds spent turning from the previous target to this one without moving)"""
+import bmesh, bpy, glob, json, math, os, subprocess, sys, time
+from mathutils import Matrix, Vector
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+TOUR, OUT = json.load(open(argv[0])), argv[1]
+os.makedirs(OUT, exist_ok=True)
+F = 0.3048
+HERE = os.path.dirname(os.path.abspath(__file__))
+ASSETS = os.path.join(HERE, "..", "assets")
+sc = bpy.context.scene
+FPS = TOUR.get("fps", 30)
+opt = lambda k, d: type(d)(argv[argv.index(k) + 1]) if k in argv else d
+RES = [int(v) for v in (argv[argv.index("--res") + 1] if "--res" in argv else "1920x1080").split("x")]
+
+# ------------------------------------------------------------------ path: Catmull-Rom through the keys, timed by length
+keys = TOUR["keys"]
+times = [0.0]
+for a, b in zip(keys, keys[1:]):
+ d = (Vector(b["p"]) - Vector(a["p"])).length
+ da, db = Vector(a["t"]) - Vector(a["p"]), Vector(b["t"]) - Vector(b["p"])
+ ang = da.angle(db, 0.0) if da.length and db.length else 0.0
+ turn = max(0.5, ang / (math.pi / 2) * TOUR.get("turn_s", 1.6)) # seconds: slow, even pans
+ times.append(times[-1] + max(d / TOUR.get("speed", 1.6), b.get("hold", 0.0) * TOUR.get("hold_k", 1.4), turn))
+DUR = times[-1]
+
+
+def _cr(p0, p1, p2, p3, u):
+ return 0.5 * ((2 * p1) + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u * u + (-p0 + 3 * p1 - 3 * p2 + p3) * u ** 3)
+
+
+def at(t, field):
+ t = min(max(t, 0.0), DUR)
+ i = max(0, min(len(times) - 2, next((k for k in range(len(times) - 1) if times[k + 1] >= t), len(times) - 2)))
+ u = (t - times[i]) / max(times[i + 1] - times[i], 1e-6)
+ u = u * u * (3 - 2 * u) if keys[i].get("hold") or keys[i + 1].get("hold") else u # settle into turns
+ P = [Vector(keys[max(0, min(len(keys) - 1, j))][field]) for j in (i - 1, i, i + 1, i + 2)]
+ return _cr(*P, u)
+
+
+def room_at(t):
+ i = max(k for k in range(len(times)) if times[k] <= t + 1e-6)
+ return next((keys[k]["room"] for k in range(i, -1, -1) if keys[k].get("room")), "")
+
+
+# ------------------------------------------------------------------ look: dusk sky, warm interiors
+sky = os.path.join(ASSETS, "hdri", "qwantani_dusk_2_puresky.hdr")
+wn = sc.world.node_tree
+env = next(n for n in wn.nodes if n.type == "TEX_ENVIRONMENT")
+env.image = bpy.data.images.load(sky)
+wn.nodes["Background"].inputs["Strength"].default_value = TOUR.get("sky", 0.3)
+mp = wn.nodes.new("ShaderNodeMapping")
+tc = wn.nodes.new("ShaderNodeTexCoord")
+wn.links.new(tc.outputs["Generated"], mp.inputs["Vector"])
+wn.links.new(mp.outputs["Vector"], env.inputs["Vector"])
+mp.inputs["Rotation"].default_value[2] = math.radians(TOUR.get("sky_rot", 140))
+for o in list(sc.objects):
+ if o.type == "LIGHT": # the bake's sun and lamps: replaced below
+ bpy.data.objects.remove(o)
+
+
+def light(name, kind, loc, energy, color, size=None, rot=None, coll=sc.collection, **kw):
+ L = bpy.data.lights.new(name, kind)
+ L.energy, L.color = energy, color
+ if size is not None:
+ L.size = size
+ for k, v in kw.items():
+ setattr(L, k, v)
+ o = bpy.data.objects.new(name, L)
+ o.location = [v * F for v in loc]
+ if rot:
+ o.rotation_euler = [math.radians(a) for a in rot]
+ coll.objects.link(o)
+ return o
+
+
+WARM, LED = (1.0, 0.72, 0.47), (1.0, 0.66, 0.38)
+H = TOUR.get("ceiling", 10.0)
+plan = json.load(open(TOUR["plan"]))
+INDOOR = {"bedroom", "toilet", "kitchen", "living", "dining", "puja", "study", "store", "passage", "room", "wash", "dress"}
+led = bpy.data.materials.new("cove_led")
+led.use_nodes = True
+em = led.node_tree.nodes.new("ShaderNodeEmission")
+em.inputs["Color"].default_value = (*LED, 1)
+em.inputs["Strength"].default_value = TOUR.get("cove", 6.0)
+led.node_tree.links.new(em.outputs[0], led.node_tree.nodes["Material Output"].inputs["Surface"])
+COVES = []
+for f in plan["floors"]:
+ for z in f["rooms"]:
+ if z["type"] not in INDOOR:
+ continue
+ for x0, x1, y0, y1 in z["rects"]:
+ w, d = x1 - x0, y1 - y0
+ if w * d < 8:
+ continue
+ # soft ceiling glow + a warm fill: an area light the size of most of the room
+ toured = (y0 + y1) / 2 < TOUR.get("tour_y_max", 1e9) # the other unit is only seen from outside
+ Lo = light("room", "AREA", ((x0 + x1) / 2, (y0 + y1) / 2, H - 0.3), TOUR.get("room_w", 6.0) * w * d * F * F,
+ WARM, shape="RECTANGLE", size=w * 0.7 * F, size_y=d * 0.7 * F)
+ Lo.data.use_shadow = True # (without shadows it leaks through roofs and walls)
+ if toured: # LED cove wash: a long thin light along each wall pointing at the ceiling
+ for cx, cy, lx, ly in (((x0 + x1) / 2, y0 + 0.5, w, 0.15), ((x0 + x1) / 2, y1 - 0.5, w, 0.15),
+ (x0 + 0.5, (y0 + y1) / 2, 0.15, d), (x1 - 0.5, (y0 + y1) / 2, 0.15, d)):
+ c = light("cove", "AREA", (cx, cy, H - 0.55), TOUR.get("cove_w", 2.2) * max(lx, ly) * F, LED,
+ rot=(180, 0, 0), shape="RECTANGLE", size=lx * F, size_y=ly * F)
+ c.data.use_shadow = False
+ COVES.append(c)
+ # LED cove: a thin glowing strip just under the ceiling along every side
+ bm = bmesh.new()
+ for a, b, c, e in ((x0, x1, y0, y0 + 0.08), (x0, x1, y1 - 0.08, y1), (x0, x0 + 0.08, y0, y1), (x1 - 0.08, x1, y0, y1)):
+ bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Translation(((a + b) / 2 * F, (c + e) / 2 * F, (H - 0.45) * F))
+ @ Matrix.Diagonal(((b - a) * F, (e - c) * F, 0.05 * F)).to_4x4())
+ me = bpy.data.meshes.new("cove")
+ bm.to_mesh(me)
+ ob = bpy.data.objects.new("cove", me)
+ ob.data.materials.append(led)
+ sc.collection.objects.link(ob)
+# the coves have no shadows (cheap): keep them off the roof and parapet with light linking
+roofs = bpy.data.collections.new("cove_excluded")
+sc.collection.children.link(roofs)
+for o in sc.objects:
+ if o.type == "MESH" and o.name.startswith(("roof", "parapet")):
+ roofs.objects.link(o)
+try:
+ for co in roofs.collection_objects:
+ co.light_linking.link_state = "EXCLUDE"
+ for c in COVES:
+ c.light_linking.receiver_collection = roofs
+except Exception as e: # older Blender: shadows instead
+ print("light linking unavailable:", e)
+ for c in COVES:
+ c.data.use_shadow = True
+# garden: warm uplights at the trees / shrubs, wall washers on the courtyard faces
+for o in sc.objects:
+ n = o.name.split("_at_")[0]
+ if o.type == "EMPTY" and n in ("island_tree_01", "shrub_02", "shrub_03", "planter_box_01", "planter_pot_clay"):
+ x, y = o.location.x / F, o.location.y / F
+ if "tree" not in n:
+ up = light("uplight", "SPOT", (x + 0.8, y - 0.6, 0.4), 60, (1.0, 0.75, 0.5),
+ rot=(-20, 0, 0), spot_size=math.radians(70), spot_blend=0.8)
+ up.data.use_shadow = False
+
+# ------------------------------------------------------------------ restyle: warm neutrals like the reference
+def tint(name, rgb, rough=None):
+ m = bpy.data.materials.get(name)
+ if not m or not m.use_nodes:
+ return
+ for n in m.node_tree.nodes:
+ if n.type == "BSDF_PRINCIPLED":
+ bc = n.inputs["Base Color"]
+ if bc.is_linked: # textured: multiply the texture by the tint
+ mix = m.node_tree.nodes.new("ShaderNodeMix")
+ mix.data_type, mix.blend_type = "RGBA", "MULTIPLY"
+ mix.inputs[0].default_value = 1.0
+ col_a, col_b = [i for i in mix.inputs if i.type == "RGBA"][:2]
+ m.node_tree.links.new(bc.links[0].from_socket, col_a)
+ col_b.default_value = (*rgb, 1)
+ m.node_tree.links.new(next(o for o in mix.outputs if o.type == "RGBA"), bc)
+ else:
+ bc.default_value = (*rgb, 1)
+ if rough is not None:
+ n.inputs["Roughness"].default_value = rough
+def recolour(name, rgb, rough=None):
+ """replace a (textured) base colour by a flat one; bump / roughness maps stay"""
+ m = bpy.data.materials.get(name)
+ if not m:
+ return
+ for n in m.node_tree.nodes:
+ if n.type == "BSDF_PRINCIPLED":
+ for l in list(n.inputs["Base Color"].links):
+ m.node_tree.links.remove(l)
+ n.inputs["Base Color"].default_value = (*rgb, 1)
+ if rough is not None:
+ n.inputs["Roughness"].default_value = rough
+
+
+for name, rgb in (("cushion", (0.5, 0.45, 0.38)), ("sofa_fabric", (0.78, 0.75, 0.7)), ("rug_round", (0.62, 0.58, 0.52)),
+ ("rug", (0.55, 0.5, 0.44)), ("terrace", (0.82, 0.8, 0.77)), ("ceiling", (0.85, 0.83, 0.8))):
+ recolour(name, rgb)
+for name, rgb, rough in (("marble", (1.0, 0.97, 0.92), 0.12), ("sofa_fabric", (1.05, 1.02, 0.97), None),
+ ("marble", (1.0, 0.97, 0.92), 0.12),
+ ("tile", (1.0, 0.96, 0.9), 0.2)):
+ tint(name, rgb, rough)
+for o in sc.objects: # flat white roof like a modern villa
+ if o.type == "MESH" and o.name.startswith("roof") and bpy.data.materials.get("exterior"):
+ o.data.materials.clear()
+ o.data.materials.append(bpy.data.materials["exterior"])
+
+# procedural date palms instead of the broad-leaf tree (lighter and right for a courtyard)
+foliage = bpy.data.materials.get("foliage")
+bark = bpy.data.materials.get("bark") or foliage
+
+
+def palm(x, y, h=15.0, seed=0):
+ import random
+ rnd = random.Random(seed)
+ bm = bmesh.new()
+ lean = Vector((rnd.uniform(-0.6, 0.6), rnd.uniform(-0.6, 0.6), 0))
+ pts = [Vector((x, y, 0)) + lean * (k / 10) ** 2 + Vector((0, 0, h * k / 10)) for k in range(11)]
+ for k in range(10):
+ r0, r1 = 0.62 - 0.03 * k, 0.6 - 0.03 * (k + 1)
+ bmesh.ops.create_cone(bm, cap_ends=False, segments=12, radius1=r0 * F, radius2=r1 * F, depth=(h / 10) * F,
+ matrix=Matrix.Translation(((pts[k] + pts[k + 1]) / 2) * F))
+ trunk = bpy.data.meshes.new("palm_trunk")
+ bm.to_mesh(trunk)
+ ob = bpy.data.objects.new("palm_trunk", trunk)
+ ob.data.materials.append(bark)
+ sc.collection.objects.link(ob)
+ top = pts[-1]
+ bm = bmesh.new()
+ for i in range(16):
+ az = 2 * math.pi * i / 16 + rnd.uniform(-0.15, 0.15)
+ L = rnd.uniform(5.0, 6.3)
+ lift = rnd.uniform(0.25, 0.6)
+ dirv = Vector((math.cos(az), math.sin(az), 0))
+ side = Vector((-math.sin(az), math.cos(az), 0))
+ prev = None
+ for k in range(13):
+ sct = k / 12
+ c = top + dirv * (L * sct) + Vector((0, 0, L * (lift * math.sin(math.pi * sct * 0.8) - 0.55 * sct * sct)))
+ w = 1.3 * math.sin(math.pi * min(sct, 0.98)) ** 0.6 + 0.05
+ a = bm.verts.new((c - side * w) * F)
+ b = bm.verts.new((c + side * w) * F)
+ m = bm.verts.new((c + Vector((0, 0, 0.12 * w))) * F)
+ if prev:
+ bm.faces.new((prev[0], a, m, prev[2]))
+ bm.faces.new((prev[2], m, b, prev[1]))
+ prev = (a, b, m)
+ leaves = bpy.data.meshes.new("palm_leaves")
+ bm.to_mesh(leaves)
+ lo = bpy.data.objects.new("palm_leaves", leaves)
+ lo.data.materials.append(foliage)
+ sc.collection.objects.link(lo)
+ return top
+
+
+PALMS = []
+for o in list(sc.objects):
+ if o.type == "EMPTY" and o.name.startswith("island_tree_01"):
+ x, y = o.location.x / F, o.location.y / F
+ for c in o.children_recursive:
+ c.hide_render = c.hide_viewport = True
+ PALMS.append((x, y, palm(x, y, 15.5, seed=len(PALMS))))
+for x, y, top in PALMS:
+ light("palm_up", "SPOT", (x + 1.6, y - 1.2, 0.3), 420, (1.0, 0.74, 0.48), rot=(-14, 0, 0),
+ spot_size=math.radians(55), spot_blend=0.9)
+
+
+# ------------------------------------------------------------------ renderer
+eng = [e.identifier for e in bpy.types.RenderSettings.bl_rna.properties["engine"].enum_items]
+sc.render.engine = "BLENDER_EEVEE_NEXT" if "BLENDER_EEVEE_NEXT" in eng else "BLENDER_EEVEE"
+ee = sc.eevee
+for k, v in (("shadow_pool_size", "1024"), ("taa_render_samples", opt("--samples", TOUR.get("samples", 32))), ("use_raytracing", True), ("use_shadows", True),
+ ("shadow_ray_count", 2), ("shadow_step_count", 8), ("use_fast_gi", True), ("fast_gi_method", "GLOBAL_ILLUMINATION"),
+ ("ray_tracing_method", "SCREEN"), ("use_volumetric_shadows", False), ("gi_diffuse_bounces", 3)):
+ try:
+ setattr(ee, k, v)
+ except Exception as e:
+ print("eevee setting skipped", k, e)
+try:
+ ee.ray_tracing_options.resolution_scale = "2"
+ ee.ray_tracing_options.use_denoise = True
+except Exception:
+ pass
+sc.render.resolution_x, sc.render.resolution_y = RES
+sc.render.resolution_percentage = 100
+sc.render.fps = FPS
+sc.view_settings.view_transform = "AgX"
+sc.view_settings.look = "AgX - Medium High Contrast"
+sc.view_settings.exposure = TOUR.get("exposure", 0.9)
+sc.render.image_settings.file_format = "JPEG"
+sc.render.image_settings.quality = 94
+cam = bpy.data.objects.new("tourcam", bpy.data.cameras.new("tourcam"))
+sc.collection.objects.link(cam)
+cam.data.lens, cam.data.sensor_width = TOUR.get("lens", 18), 36
+cam.data.clip_start = 0.05
+sc.camera = cam
+
+
+def pose(t):
+ p, q = at(t, "p") * F, at(t, "t") * F
+ cam.location = p
+ cam.rotation_euler = (q - p).to_track_quat("-Z", "Y").to_euler()
+
+
+# ------------------------------------------------------------------ heat locks
+GPU_HOT, GPU_OK = TOUR.get("gpu_hot", 80), TOUR.get("gpu_ok", 70)
+CPU_HOT, CPU_OK = TOUR.get("cpu_hot", 92), TOUR.get("cpu_ok", 78)
+
+
+def temps():
+ g = c = 0
+ try:
+ g = int(subprocess.run(["nvidia-smi", "--query-gpu=temperature.gpu", "--format=csv,noheader"],
+ capture_output=True, text=True, timeout=5).stdout.split()[0])
+ except Exception:
+ pass
+ reads = [] # package temp spikes for a moment at each frame start:
+ for k in range(3): # lock on the lowest of 3 reads so only sustained heat counts
+ for z in glob.glob("/sys/class/thermal/thermal_zone*"):
+ try:
+ if open(z + "/type").read().strip() == "x86_pkg_temp":
+ reads.append(int(open(z + "/temp").read()) // 1000)
+ except Exception:
+ pass
+ time.sleep(0.25 * (k < 2))
+ return g, min(reads, default=c)
+
+
+def render_to(path):
+ g, c = temps()
+ if g >= GPU_HOT or c >= CPU_HOT:
+ print(f"HEAT LOCK gpu {g}C cpu {c}C - cooling to gpu {GPU_OK}C / cpu {CPU_OK}C", flush=True)
+ while g > GPU_OK or c > CPU_OK:
+ time.sleep(5)
+ g, c = temps()
+ print(f"resume gpu {g}C cpu {c}C", flush=True)
+ sc.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+ return g, c
+
+
+json.dump(dict(fps=FPS, duration=DUR, rooms=[(round(times[k], 2), keys[k]["room"]) for k in range(len(keys)) if keys[k].get("room")]),
+ open(os.path.join(OUT, "timeline.json"), "w"), indent=1)
+print(f"TOUR {DUR:.1f} s = {int(DUR * FPS)} frames at {FPS} fps, {RES[0]}x{RES[1]}, engine {sc.render.engine}", flush=True)
+
+if "--stills" in argv:
+ for t in [float(v) for v in argv[argv.index("--stills") + 1].split(",")]:
+ pose(t)
+ t0 = time.time()
+ g, c = render_to(os.path.join(OUT, f"still_{t:06.1f}.jpg"))
+ print(f"STILL {t:.1f}s {room_at(t)} {time.time() - t0:.1f}s gpu {g}C cpu {c}C", flush=True)
+
+if "--shots" in argv: # stills from fixed cameras: [{"name", "p": [x,y,z], "t": [x,y,z], "lens"}] (feet)
+ for sh in json.load(open(argv[argv.index("--shots") + 1])):
+ cam.location = Vector(sh["p"]) * F
+ cam.rotation_euler = ((Vector(sh["t"]) - Vector(sh["p"])) * F).to_track_quat("-Z", "Y").to_euler()
+ cam.data.lens = sh.get("lens", 18)
+ if "--save" in argv: # keep each view as a named camera in the saved scene
+ c = cam.copy(); c.data = cam.data.copy(); c.name = c.data.name = "view_" + sh["name"]
+ sc.collection.objects.link(c)
+ continue
+ t0 = time.time()
+ g, c = render_to(os.path.join(OUT, sh["name"] + ".jpg"))
+ print(f"SHOT {sh['name']} {time.time() - t0:.1f}s gpu {g}C cpu {c}C", flush=True)
+
+if "--save" in argv: # self-contained .blend: lights, cameras, every texture packed inside
+ bpy.ops.file.pack_all()
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.abspath(argv[argv.index("--save") + 1]), copy=True, compress=True)
+ print("SAVED", flush=True)
+
+if "--frames" in argv:
+ fd = os.path.join(OUT, "frames")
+ os.makedirs(fd, exist_ok=True)
+ n = int(DUR * FPS) + 1
+ for i in range(n): # bake the camera path into keyframes
+ pose(i / FPS)
+ cam.keyframe_insert("location", frame=i)
+ cam.keyframe_insert("rotation_euler", frame=i)
+ sc.frame_start, sc.frame_end, sc.frame_step = opt("--start", 0), n - 1, opt("--step", 1) # step 2: odd frames blended later
+ sc.render.filepath = os.path.join(fd, "f_#####")
+ sc.render.use_overwrite, sc.render.use_placeholder = False, True # resumable: done frames are skipped
+ stamp = [time.time()]
+
+ def heat_lock(scene, *_):
+ g, c = temps()
+ print(f"FRAME {scene.frame_current}/{n} {time.time() - stamp[0]:.1f}s gpu {g}C cpu {c}C", flush=True)
+ if g >= GPU_HOT or c >= CPU_HOT:
+ print(f"HEAT LOCK gpu {g}C cpu {c}C - cooling to gpu {GPU_OK}C / cpu {CPU_OK}C", flush=True)
+ while g > GPU_OK or c > CPU_OK:
+ time.sleep(5)
+ g, c = temps()
+ print(f"resume gpu {g}C cpu {c}C", flush=True)
+ stamp[0] = time.time()
+ bpy.app.handlers.render_pre.append(heat_lock)
+ bpy.ops.render.render(animation=True)
+ print("FRAMES OK", flush=True)
diff --git a/blender/gen.py b/blender/gen.py
new file mode 100644
index 0000000..ae11272
--- /dev/null
+++ b/blender/gen.py
@@ -0,0 +1,528 @@
+"""plan JSON -> furnished 3D house -> baked lighting -> web model (house.glb + lightmaps + meta.json).
+Run: blender -b --factory-startup -P planto3d/blender/gen.py -- plan.json OUTDIR [--quality draft|high] [--no-bake]
+Progress lines: 'PROGRESS <0-100> <message>' on stdout (read by the server)."""
+import json, math, os, sys, time
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path[:0] = [HERE, os.path.join(HERE, "..")]
+argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+PLAN, JOB = os.path.abspath(argv[0]), os.path.abspath(argv[1])
+QUALITY = argv[argv.index("--quality") + 1] if "--quality" in argv else "high"
+BAKE = "--no-bake" not in argv
+os.makedirs(JOB, exist_ok=True)
+
+import bpy # noqa: E402
+from lib import * # noqa: E402,F401
+import lib # noqa: E402
+import furnish # noqa: E402
+
+
+def progress(p, msg):
+ print(f"PROGRESS {int(p)} {msg}", flush=True)
+
+
+plan = json.load(open(PLAN))
+H, SLAB = plan.get("floor_height", 10.0), plan.get("slab", 0.5)
+FFH = H + SLAB
+lib.WALL_H = H
+floors = plan["floors"]
+NF = len(floors)
+progress(2, "building walls")
+
+mat("tile", tex="large_floor_tiles_02", tile=1.5)
+mat("pavers", tex="herringbone_pavement", tile=1.6)
+mat("asphalt", tex="asphalt_02", tile=4.0)
+mat("footpath", tex="square_concrete_pavers", tile=1.5)
+mat("pebbles", tex="dry_river_pebbles", tile=0.8)
+mat("terrace", tex="concrete_tiles", tile=1.5)
+mat("turf", tex="leafy_grass", tile=1.0, tint=(0.5, 0.75, 0.35))
+mat("exterior", (0.93, 0.91, 0.87), 0.9, tex="white_plaster_02", tile=2.5, albedo=False)
+mat("sofa_fabric", rough=0.95, tex="fabric_pattern_07", tile=0.6, tint=(0.75, 0.7, 0.62))
+mat("cushion", rough=0.95, tex="caban", tile=0.5, tint=(0.55, 0.45, 0.35))
+
+FLOOR_MAT = dict(dress="wood", bedroom="wood", toilet="bathtile", kitchen="marble", living="marble", dining="marble", puja="marble",
+ wash="concrete", store="concrete", study="wood", passage="tile", balcony="terracotta",
+ garden="turf", open="pebbles", parking="pavers", yard="pavers", stair="stair", room="tile",
+ duct="concrete")
+OPEN_SKY = {"open", "garden", "yard"} # no slab above these
+INDOOR = {"bedroom", "toilet", "kitchen", "living", "dining", "puja", "study", "store", "passage", "room", "wash", "dress"}
+
+
+# ------------------------------------------------------------------ helpers
+def window_parts(windows):
+ """frame + glass boxes for (x0,x1,y0,y1,sill,head) given at exact wall thickness."""
+ out = []
+ for x0, x1, y0, y1, s, h in windows:
+ fr = 0.18
+ if (x1 - x0) > (y1 - y0):
+ ym = (y0 + y1) / 2
+ t0, t1 = ym - 0.1, ym + 0.1
+ out += [(x0, x1, t0, t1, s, s + fr, "frame"), (x0, x1, t0, t1, h - fr, h, "frame"),
+ (x0, x0 + fr, t0, t1, s, h, "frame"), (x1 - fr, x1, t0, t1, s, h, "frame")]
+ n = max(1, round((x1 - x0) / 2.5))
+ out += [(x0 + (x1 - x0) * i / n - fr / 2, x0 + (x1 - x0) * i / n + fr / 2, t0, t1, s, h, "frame") for i in range(1, n)]
+ out.append((x0, x1, ym - 0.01, ym + 0.01, s, h, "glass"))
+ else:
+ xm = (x0 + x1) / 2
+ t0, t1 = xm - 0.1, xm + 0.1
+ out += [(t0, t1, y0, y1, s, s + fr, "frame"), (t0, t1, y0, y1, h - fr, h, "frame"),
+ (t0, t1, y0, y0 + fr, s, h, "frame"), (t0, t1, y1 - fr, y1, s, h, "frame")]
+ n = max(1, round((y1 - y0) / 2.5))
+ out += [(t0, t1, y0 + (y1 - y0) * i / n - fr / 2, y0 + (y1 - y0) * i / n + fr / 2, s, h, "frame") for i in range(1, n)]
+ out.append((xm - 0.01, xm + 0.01, y0, y1, s, h, "glass"))
+ return out
+
+
+def zone_at(f, x, y):
+ for z in f["rooms"]:
+ for r in z["rects"]:
+ if r[0] - 0.05 <= x <= r[1] + 0.05 and r[2] - 0.05 <= y <= r[3] + 0.05:
+ return z
+ return None
+
+
+def bbox_of(rs):
+ return (min(r[0] for r in rs), max(r[1] for r in rs), min(r[2] for r in rs), max(r[3] for r in rs))
+
+
+def boxes_minus(base, holes):
+ return disjoint(subtract_all([base], holes))
+
+
+VENT_MAX = 2.6
+
+
+def opening_heights(f, o):
+ r = o["rect"]
+ if o["type"] != "window":
+ return (-1, 7.0)
+ cx, cy = (r[0] + r[1]) / 2, (r[2] + r[3]) / 2
+ sides = [zone_at(f, cx, cy - 1.0), zone_at(f, cx, cy + 1.0)] if o["axis"] == "x" else \
+ [zone_at(f, cx - 1.0, cy), zone_at(f, cx + 1.0, cy)]
+ wet = any(z and z["type"] == "toilet" for z in sides)
+ width = max(r[1] - r[0], r[3] - r[2])
+ return (6.0, 7.5) if wet or width <= VENT_MAX else (3.0, 7.0)
+
+
+# ------------------------------------------------------------------ stairs
+def stair_parts(f, rise):
+ """flights + landing from the detected tread runs. The flight next to the UP word starts at floor level
+ at its UP end; the next flight starts where the previous one ended (dog-leg). -> (boxes, meta)"""
+ fl = [dict(s) for s in f["stairs"]]
+ if not fl:
+ return [], []
+ up = [s for s in fl if s["up"]] or fl[:1]
+ order = [up[0]] + [s for s in fl if s is not up[0]]
+ boxes, meta = [], []
+ z = 0.0
+ prev_end = None
+ per = rise / len(order)
+ for k, s in enumerate(order):
+ x0, x1, y0, y1 = s["rect"]
+ ax = 0 if s["axis"] == "x" else 1 # direction of travel along x or y
+ lo, hi = (x0, x1) if ax == 0 else (y0, y1)
+ if k == 0:
+ # start at the end nearest to the UP word
+ w = next((p for p in s["words"] if p[0].startswith("UP")), None)
+ pos = (w[1], w[2]) if w else ((x0 + x1) / 2, (y0 + y1) / 2)
+ start = lo if abs(pos[ax] - lo) < abs(pos[ax] - hi) else hi
+ else:
+ start = lo if abs(prev_end - lo) < abs(prev_end - hi) else hi
+ d = 1 if start == lo else -1
+ n = max(3, s["steps"])
+ run = (hi - lo) / n
+ for i in range(n):
+ a = start + d * i * run
+ b = a + d * run
+ a, b = min(a, b), max(a, b)
+ zt = z + per * (i + 1) / n
+ bx = (a, b, y0, y1, 0, zt) if ax == 0 else (x0, x1, a, b, 0, zt)
+ boxes.append((*bx, "stair"))
+ end = start + d * (hi - lo)
+ meta.append(dict(rect=[x0, x1, y0, y1], axis=s["axis"], start=start, dir=d, z0=z, z1=z + per))
+ z += per
+ prev_end = end
+ # landing beyond this flight's end, across the whole stair, if another flight follows
+ if k + 1 < len(order):
+ sb = bbox_of([q["rect"] for q in order])
+ depth = (y1 - y0) if ax == 0 else (x1 - x0)
+ if ax == 0:
+ L = (end, end + d * depth) if d > 0 else (end + d * depth, end)
+ lb = (max(L[0], sb[0] - depth), min(L[1], sb[1] + depth), sb[2], sb[3])
+ else:
+ L = (end, end + d * depth) if d > 0 else (end + d * depth, end)
+ lb = (sb[0], sb[1], max(L[0], sb[2] - depth), min(L[1], sb[3] + depth))
+ boxes.append((*lb, z - 0.5, z, "stair"))
+ meta.append(dict(rect=list(lb), landing=True, z0=z, z1=z))
+ return boxes, meta
+
+
+# ------------------------------------------------------------------ procedural furniture not in lib
+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)
+ 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):
+ hw = w / 2
+ group("sofa", [(-hw, hw, -1.5, 1.5, 0.3, 1.4, "sofa_fabric"), (-hw, hw, 0.8, 1.5, 1.4, 2.8, "sofa_fabric"),
+ (-hw, -hw + 0.6, -1.5, 1.5, 1.4, 2.2, "sofa_fabric"), (hw - 0.6, hw, -1.5, 1.5, 1.4, 2.2, "sofa_fabric"),
+ (-hw + 0.3, hw - 0.3, -1.5, 1.4, 0, 0.3, "black")], x, y, rot, bevel=0.1, seg=3)
+ n = max(2, round((w - 1.2) / 2.2))
+ cw = (w - 1.2) / n
+ cush = [(-hw + 0.6 + cw * i + 0.03, -hw + 0.6 + cw * (i + 1) - 0.03, -1.4, 0.8, 1.4, 1.95, "cushion") for i in range(n)]
+ cush += [(-hw + 0.6 + cw * i + 0.05, -hw + 0.6 + cw * (i + 1) - 0.05, 0.35, 0.85, 1.95, 3.0, "cushion") for i in range(n)]
+ group("sofa_cushions", cush, x, y, rot, bevel=0.18, seg=4, collide=False)
+
+
+def coffee_table(x, y, rot):
+ group("coffee_table", [(-1.8, 1.8, -1.0, 1.0, 1.25, 1.4, "teak"), (-1.6, 1.6, -0.8, 0.8, 0.0, 0.1, "black"),
+ (-0.1, 0.1, -0.1, 0.1, 0.1, 1.25, "steel")], x, y, rot, bevel=0.03)
+
+
+def tv_unit(x, y, rot):
+ group("tv_unit", [(-2.5, 2.5, -0.7, 0.7, 0.5, 1.9, "teak"), (-2.4, 2.4, -0.72, -0.7, 0.7, 1.7, "laminate_w")],
+ x, y, rot, bevel=0.02)
+ r = math.radians(rot) # the unit's back (local +y, 0.7 ft) is on the wall: hang the TV 0.1 ft off it
+ 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):
+ 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)
+ 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)
+ 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
+
+
+def chair(x, y, rot):
+ """at rot 0 the backrest ends up on +y (drawn on -y, turned 180 by the group call)"""
+ group("chair", [(-0.8, 0.8, -0.8, 0.8, 1.45, 1.6, "teak"), (-0.8, 0.8, -0.85, -0.7, 1.6, 3.2, "teak"),
+ *[(sx * 0.65 - 0.07, sx * 0.65 + 0.07, sy * 0.65 - 0.07, sy * 0.65 + 0.07, 0, 1.45, "teak")
+ for sx in (-1, 1) for sy in (-1, 1)],
+ (-0.7, 0.7, -0.7, 0.7, 1.6, 1.75, "cushion")], x, y, rot + 180, bevel=0.02, collide=False)
+
+
+def car(x, y, rot):
+ place("covered_car", x, y, rot, collide=False)
+
+
+import bmesh, random # noqa: E402
+
+mat("foliage", rough=0.9, tex="leafy_grass", tile=0.6, tint=(0.35, 0.55, 0.25))
+mat("bark", (0.25, 0.18, 0.12), 0.9)
+
+
+def blob(root, name, r, loc, mn="foliage", sub=2, jitter=0.18, seed=0):
+ """lumpy low-poly sphere (icosphere with random push) for foliage"""
+ rnd = random.Random(seed)
+ bm = bmesh.new()
+ bmesh.ops.create_icosphere(bm, subdivisions=sub, radius=r * lib.F)
+ for v in bm.verts:
+ v.co *= 1 + rnd.uniform(-jitter, jitter)
+ return lib._mesh_obj(name, bm, mn, root, loc, smooth=60)
+
+
+def tree(x, y, s=1.0, seed=0):
+ """light procedural tree: tapered trunk + clustered canopy (~3k triangles)"""
+ rnd = random.Random(seed)
+ r = item("tree", x, y, 0)
+ p_cyl(r, "trunk", 0.45 * s, 0.25 * s, 9 * s, "bark", segs=12)
+ for k in range(6):
+ a = rnd.uniform(0, 2 * math.pi)
+ d = rnd.uniform(1.0, 3.2) * s
+ blob(r, "canopy", rnd.uniform(2.6, 3.8) * s, (math.cos(a) * d, math.sin(a) * d, (9 + rnd.uniform(0, 4)) * s),
+ sub=3, seed=seed * 10 + k)
+ return done(r, collide=False)
+
+
+def plant(x, y, rot):
+ r = item("plant", x, y, rot)
+ p_cyl(r, "pot", 0.55, 0.75, 1.5, "terracotta", segs=24)
+ p_cyl(r, "soil", 0.68, 0.68, 0.05, "concrete", (0, 0, 1.4), segs=24)
+ for k, (dx, dy, dz, rr) in enumerate(((0, 0, 2.6, 0.9), (0.4, 0.2, 3.3, 0.7), (-0.35, -0.2, 3.1, 0.65), (0, 0.1, 3.9, 0.55))):
+ blob(r, "leaves", rr, (dx, dy, dz), sub=2, jitter=0.25, seed=int(rot) + k)
+ return done(r, collide=False)
+
+
+def outdoor_set(x, y, rot):
+ place("outdoor_table_chair_set_01", x, y, rot, collide=False)
+
+
+mat("rug_round", rough=1.0, tex="caban", tile=0.9, tint=(0.86, 0.83, 0.78))
+
+
+def bathtub(x, y, rot, l=5.4, w=2.6, h=1.8):
+ """built-in tub along a wall (long side on local x, back against +y)"""
+ t, hl, hw = 0.25, l / 2, w / 2
+ group("bathtub", [(-hl, hl, -hw, hw, 0, 0.35, "white_gloss"),
+ (-hl, hl, -hw, -hw + t, 0.35, h, "white_gloss"), (-hl, hl, hw - t, hw, 0.35, h, "white_gloss"),
+ (-hl, -hl + t, -hw + t, hw - t, 0.35, h, "white_gloss"), (hl - t, hl, -hw + t, hw - t, 0.35, h, "white_gloss"),
+ (-hl + 0.4, -hl + 0.55, hw - 0.5, hw - 0.3, h, h + 0.6, "chrome"),
+ (-hl + 0.4, -hl + 0.95, hw - 0.42, hw - 0.36, h + 0.5, h + 0.58, "chrome")], x, y, rot, bevel=0.04)
+
+
+def round_rug(x, y, r=4.0):
+ root = item("round_rug", x, y, 0)
+ p_cyl(root, "rug", r, r, 0.05, "rug_round", segs=72)
+ done(root, collide=False)
+
+
+def model(name, x, y, rot=0, z=0.0, scale=1.0):
+ place(name, x, y, rot, z=z, scale=scale, collide=False)
+
+
+CALLS = dict(bathtub=bathtub, round_rug=round_rug, model=model, bed=bed, nightstand=nightstand, wardrobe=wardrobe, desk=desk, wc2=wc2, vanity=vanity,
+ shower2=lambda x, y, rot: shower2(x, y, rot), geyser=lambda x, y, rot: geyser(x, y, rot),
+ 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)
+
+
+# ------------------------------------------------------------------ build each storey
+COLLIDERS, META_FLOORS, LAMPS = [], [], []
+by_floor = {}
+
+
+def new_objects(before):
+ return [o for o in bpy.data.objects if o not in before]
+
+
+bboxes = [bbox_of([w[:4] for w in f["walls"]]) for f in floors]
+stair_box_prev = None
+for k, f in enumerate(floors):
+ z = k * FFH
+ set_level(z)
+ before = set(bpy.data.objects)
+ low_h = 5.0 if k == 0 else 3.5
+ cuts, wins, door_list = [], [], []
+ for o in f["openings"]:
+ x0, x1, y0, y1 = o["rect"]
+ s, hd = opening_heights(f, o)
+ if o["axis"] == "x":
+ c = (x0, x1, y0 - 0.06, y1 + 0.06, s, hd)
+ else:
+ c = (x0 - 0.06, x1 + 0.06, y0, y1, s, hd)
+ cuts.append(c)
+ if o["type"] == "window":
+ wins.append((x0, x1, y0, y1, s, hd))
+ else:
+ door_list.append(o)
+ walls_f = [list(w) for w in f["walls"]]
+ if f["stairs"]:
+ fb = bbox_of([s["rect"] for s in f["stairs"]])
+ ax = f["stairs"][0]["axis"]
+ for w in walls_f: # low walls in the stair band (mid wall, landing edges) stop where the flights stop
+ cx, cy = (w[0] + w[1]) / 2, (w[2] + w[3]) / 2
+ in_band = (fb[2] - 0.2 <= cy <= fb[3] + 0.2 and fb[0] - 6 <= cx <= fb[1] + 6) if ax == "x" else \
+ (fb[0] - 0.2 <= cx <= fb[1] + 0.2 and fb[2] - 6 <= cy <= fb[3] + 6)
+ if w[4] and in_band:
+ if ax == "x":
+ w[0], w[1] = max(w[0], fb[0]), min(w[1], fb[1])
+ else:
+ w[2], w[3] = max(w[2], fb[2]), min(w[3], fb[3])
+ walls_f = [w for w in walls_f if w[1] - w[0] > 0.05 and w[3] - w[2] > 0.05]
+ # a mid wall drawn dashed comes in pieces: join low pieces on one line with small gaps
+ merged = True
+ while merged:
+ merged = False
+ for a in walls_f:
+ for b in walls_f:
+ if a is b or not (a[4] and b[4]):
+ continue
+ if ax == "x" and abs(a[2] - b[2]) < 0.1 and abs(a[3] - b[3]) < 0.1 and -0.05 < b[0] - a[1] < 1.0:
+ a[1] = b[1]; walls_f.remove(b); merged = True; break
+ if ax == "y" and abs(a[0] - b[0]) < 0.1 and abs(a[1] - b[1]) < 0.1 and -0.05 < b[2] - a[3] < 1.0:
+ a[3] = b[3]; walls_f.remove(b); merged = True; break
+ if merged:
+ break
+ f["walls"] = walls_f
+ wb = [(*w[:4], 0, (low_h if w[4] else H)) for w in f["walls"]]
+ # detected openings are gaps between walls: fill the wall below the sill and above the head (lintel)
+ for o, c in zip(f["openings"], cuts):
+ r = o["rect"]
+ touching = [w for w in f["walls"] if w[0] <= r[1] + 0.3 and r[0] <= w[1] + 0.3 and w[2] <= r[3] + 0.3 and r[2] <= w[3] + 0.3]
+ top = H if any(not w[4] for w in touching) or not touching else low_h
+ if c[4] > 0:
+ wb.append((*r, 0, c[4]))
+ if c[5] < top:
+ wb.append((*r, c[5], top))
+ wb = disjoint(subtract_all(wb, cuts))
+ mesh_from_boxes(f"walls_{k}", [(*b, "wall") for b in wb])
+ parts = window_parts(wins)
+ mesh_from_boxes(f"window_frames_{k}", [b for b in parts if b[6] == "frame"], bevel=0.005)
+ mesh_from_boxes(f"glass_{k}", [b for b in parts if b[6] == "glass"])
+ # door frames only: leaves of neighbouring doors swing into each other and hide side doors
+ frames = []
+ for o in door_list:
+ x0, x1, y0, y1 = o["rect"]
+ t = 0.25
+ if o["axis"] == "x":
+ frames += [(x0, x0 + t, y0, y1, 0, 7, "teak"), (x1 - t, x1, y0, y1, 0, 7, "teak"), (x0, x1, y0, y1, 7 - t, 7, "teak")]
+ else:
+ frames += [(x0, x1, y0, y0 + t, 0, 7, "teak"), (x0, x1, y1 - t, y1, 0, 7, "teak"), (x0, x1, y0, y1, 7 - t, 7, "teak")]
+ mesh_from_boxes(f"door_frames_{k}", frames, bevel=0.004)
+ # floors per zone (none over the stairwell coming up from below)
+ fl = {}
+ well = [(*stair_box_prev, -9, 99)] if stair_box_prev else []
+ for zn in f["rooms"]:
+ m = FLOOR_MAT.get(zn["type"], "tile")
+ fl.setdefault(m, []).extend((*b[:4], -0.02, 0.0, m) for r in zn["rects"] for b in subtract_all([(*r, -0.02, 0.0)], well))
+ for m, bs in fl.items():
+ mesh_from_boxes(f"floor_{k}_{m}", bs)
+ # wall tiles to 7 ft in toilets
+ # (the room's cells stop a little short of the wall face, so door holes are widened across for the tiles,
+ # and edges shared by two slices of the same room are not walls)
+ tiles = []
+ door_holes = [(c[0] - 0.6, c[1] + 0.6, c[2], c[3], c[4], c[5]) if o["axis"] == "y" else
+ (c[0], c[1], c[2] - 0.6, c[3] + 0.6, c[4], c[5]) for o, c in zip(f["openings"], cuts)]
+ for zn in f["rooms"]:
+ if zn["type"] != "toilet":
+ continue
+ for r in zn["rects"]:
+ x0, x1, y0, y1 = r
+ tt = 0.03
+ own = [(q[0] - 0.05, q[1] + 0.05, q[2] - 0.05, q[3] + 0.05, -1, 99) for q in zn["rects"] if q is not r]
+ tiles += subtract_all([(x0, x1, y0, y0 + tt, 0, 7), (x0, x1, y1 - tt, y1, 0, 7),
+ (x0, x0 + tt, y0, y1, 0, 7), (x1 - tt, x1, y0, y1, 0, 7)], own)
+ if tiles:
+ mesh_from_boxes(f"toilet_tiles_{k}", [(*b, "walltile") for b in disjoint(subtract_all(tiles, door_holes))])
+ # slab under this storey (k >= 1): the plan outline minus open-to-sky zones and the stairwell below
+ bb = bboxes[k]
+ holes = [(*r, -9, 99) for zn in f["rooms"] if zn["type"] in OPEN_SKY for r in zn["rects"]]
+ if k == 0:
+ mesh_from_boxes("plinth", [(bb[0] - 0.2, bb[1] + 0.2, bb[2] - 0.2, bb[3] + 0.2, -0.6, -0.02, "concrete")])
+ else:
+ prev = floors[k - 1]
+ holes += [(*r, -9, 99) for zn in prev["rooms"] if zn["type"] in OPEN_SKY for r in zn["rects"]]
+ sb = stair_box_prev
+ if sb:
+ holes.append((*sb, -9, 99))
+ mesh_from_boxes(f"slab_{k}", [(*b[:4], -SLAB, -0.02, "ceiling") for b in boxes_minus((*bb, -SLAB, -0.02), holes)])
+ # stairs rising from this storey
+ sboxes, smeta = stair_parts(f, FFH)
+ if sboxes:
+ mesh_from_boxes(f"stairs_{k}", sboxes)
+ stair_box_prev = bbox_of([b[:4] for b in sboxes])
+ else:
+ stair_box_prev = None
+ # furniture: none if the review page's "Furniture" box was unticked; hand-placed items win over the rules
+ items = [] if plan.get("furnish") is False else f.get("items") or furnish.furnish_floor(f)
+ for it in items:
+ try:
+ CALLS[it["fn"]](*it["args"], **it["kw"])
+ except Exception as e: # one bad item must not stop the build
+ print("ITEM FAILED", it["fn"], e, flush=True)
+ # lamps (emissive panel + area light for the bake) in roofed rooms
+ for zn in f["rooms"]:
+ if zn["type"] not in INDOOR and zn["type"] not in ("balcony", "parking", "stair"):
+ continue
+ x0, x1, y0, y1 = furnish.max_rect(zn["rects"]) or max(zn["rects"], key=lambda r: (r[1] - r[0]) * (r[3] - r[2]))
+ if (x1 - x0) * (y1 - y0) < 6:
+ continue
+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
+ 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
+ F_ = lib.F
+ m = lambda r: [round(v * F_, 3) for v in r[:4]]
+ META_FLOORS.append(dict(
+ name=f.get("name", f"Floor {k}"), z=round(z * F_, 3), height=round(H * F_, 3),
+ colliders=[m(b) for b in subtract_all([(*w[:4], 0, 1) for w in f["walls"]],
+ [(c[0], c[1], c[2], c[3], 0, 1) for c in cuts if c[4] < 1])],
+ rooms=[dict(label=zn.get("label") or zn["type"].title(), type=zn["type"], rects=[m(r) for r in zn["rects"]])
+ for zn in f["rooms"] if zn["type"] not in ("duct",)],
+ stairs=[dict(s, rect=m(s["rect"]), z0=round((z + s["z0"]) * F_, 3), z1=round((z + s["z1"]) * F_, 3),
+ **({"start": round(s["start"] * F_, 3)} if "start" in s else {})) for s in smeta],
+ ))
+ progress(5 + 25 * (k + 1) / NF, f"built {f.get('name', k)}")
+
+# ------------------------------------------------------------------ roof + parapet + stair cabin (mumty)
+top = NF * FFH
+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)])
+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),
+ (bb[0], bb[0] + t, bb[2], bb[3], 0, 3.5), (bb[1] - t, bb[1], bb[2], bb[3], 0, 3.5)],
+ [(h[0] - t, h[1] + t, h[2] - t, h[3] + t, -9, 99) for h in holes]))])
+if stair_box_prev: # the top storey's stairs reach the roof: a small cabin over them with a door
+ x0, x1, y0, y1 = stair_box_prev
+ walls_m = disjoint([(x0 - t, x1 + t, y0 - t, y0, 0, 8), (x0 - t, x1 + t, y1, y1 + t, 0, 8),
+ (x0 - t, x0, y0, y1, 0, 8), (x1, x1 + t, y0, y1, 0, 8)])
+ cx = (x0 + x1) / 2
+ walls_m = subtract_all(walls_m, [(cx - 1.5, cx + 1.5, y1 - 1, y1 + 1, -1, 7)])
+ mesh_from_boxes("mumty", [(*b, "exterior") for b in walls_m] + [(x0 - t, x1 + t, y0 - t, y1 + t, 8, 8.5, "slab")])
+by_floor[NF] = new_objects(before)
+
+# ------------------------------------------------------------------ site: ground, road, trees, lamps
+set_level(0)
+before = set(bpy.data.objects)
+X0, X1 = min(b[0] for b in bboxes), max(b[1] for b in bboxes)
+Y0, Y1 = min(b[2] for b in bboxes), max(b[3] for b in bboxes)
+mesh_from_boxes("ground", [(X0 - 60, X1 + 60, Y0 - 12, Y1 + 60, -0.65, -0.62, "turf")])
+mesh_from_boxes("road", [(X0 - 60, X1 + 60, Y0 - 34, Y0 - 12, -0.62, -0.6, "asphalt"),
+ (X0 - 60, X1 + 60, Y0 - 12, Y0 - 6, -0.62, -0.45, "footpath")])
+mesh_from_boxes("apron", [(X0 - 0.2, X1 + 0.2, Y0 - 6, Y0 - 0.2, -0.62, -0.58, "pavers")])
+site = new_objects(before)
+for k, (tx, ty, sz) in enumerate(((X0 - 16, Y0 - 8.5, 1.0), (X1 + 16, Y0 - 8.5, 0.85), (X0 - 20, Y1 - 10, 1.2),
+ (X1 + 22, Y1 - 4, 1.0), ((X0 + X1) / 2 + 20, Y0 - 40, 1.1), ((X0 + X1) / 2 - 25, Y0 - 42, 0.9))):
+ tree(tx, ty, sz, seed=k + 1)
+place("street_lamp_01", (X0 + X1) / 2 - 12, Y0 - 9.5, 90, collide=False)
+trees = [o for o in new_objects(before) if o not in site]
+progress(32, "lighting")
+
+# ------------------------------------------------------------------ lights + world
+world = bpy.data.worlds.new("sky")
+scene.world = world
+world.use_nodes = True
+wn = world.node_tree
+env = wn.nodes.new("ShaderNodeTexEnvironment")
+env.image = bpy.data.images.load(os.path.join(ASSETS, "hdri", "sky.hdr"))
+wn.links.new(env.outputs["Color"], wn.nodes["Background"].inputs["Color"])
+wn.nodes["Background"].inputs["Strength"].default_value = 1.0
+sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN"))
+sun.data.energy = 4.0
+sun.data.angle = math.radians(1.5)
+sun.rotation_euler = (math.radians(52), 0, math.radians(-28))
+collection("lights").objects.link(sun)
+for cx, cy, zz, a, typ in LAMPS:
+ L = bpy.data.lights.new("lamp", "AREA")
+ L.energy = (14 if typ in INDOOR else 8) * a * lib.F * lib.F
+ L.size, L.shape = 0.6, "SQUARE"
+ L.color = (1.0, 0.9, 0.78)
+ o = bpy.data.objects.new("lamp", L)
+ o.location = (cx * lib.F, cy * lib.F, zz * lib.F)
+ collection("lights").objects.link(o)
+
+bpy.ops.wm.save_as_mainfile(filepath=os.path.join(JOB, "house.blend"))
+progress(35, "model built")
+
+# ------------------------------------------------------------------ bake + export
+import bake # noqa: E402
+
+groups = {f"level_{k}": objs for k, objs in by_floor.items()}
+groups["site"] = site
+res = bake.bake_and_export(groups, unbaked=trees, out=JOB, quality=QUALITY, do_bake=BAKE, progress=progress)
+meta = dict(version=1, floors=META_FLOORS, roof_z=round(top * lib.F, 3), eye=1.6,
+ bounds=[round(v * lib.F, 3) for v in (X0, X1, Y0, Y1)], **res)
+with open(os.path.join(JOB, "meta.json"), "w") as fh:
+ json.dump(meta, fh)
+progress(100, "done")
+print("GEN OK", flush=True)
+os._exit(0)
diff --git a/blender/lib.py b/blender/lib.py
new file mode 100644
index 0000000..18c9491
--- /dev/null
+++ b/blender/lib.py
@@ -0,0 +1,690 @@
+"""Blender building blocks used by gen.py: materials, box meshes, furniture and fixtures (units: feet).
+Textures and models come from ../assets (python3 fetch_assets.py)."""
+import bpy, bmesh, json, math, os, sys
+from mathutils import Vector, Matrix
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+ASSETS = os.path.join(os.path.dirname(HERE), "assets")
+F = 0.3048 # feet -> metres
+WALL_H = 10.0 # floor-to-ceiling, feet
+LEVEL = 0.0 # z of the floor being furnished (feet); set with set_level() for upper storeys
+
+
+def set_level(z):
+ global LEVEL
+ LEVEL = z
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+scene = bpy.context.scene
+scene.unit_settings.system = "METRIC"
+
+# ---------------------------------------------------------------- materials
+MATS = {}
+
+
+def tex_node(nt, path, non_color=False):
+ n = nt.nodes.new("ShaderNodeTexImage")
+ n.image = bpy.data.images.load(path, check_existing=True)
+ if non_color:
+ n.image.colorspace_settings.name = "Non-Color"
+ return n
+
+
+def mat(name, color=(0.8, 0.8, 0.8), rough=0.5, metal=0.0, tex=None, tile=1.0, alpha=1.0,
+ emit=0.0, tint=None, albedo=True):
+ """tile = metres covered by one texture repeat (UVs are written in metres / tile)."""
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ nt = m.node_tree
+ p = nt.nodes["Principled BSDF"]
+ p.inputs["Base Color"].default_value = (*color, 1)
+ p.inputs["Roughness"].default_value = rough
+ p.inputs["Metallic"].default_value = metal
+ if tex:
+ d = os.path.join(ASSETS, "textures", tex)
+ if albedo and os.path.exists(os.path.join(d, "diff.jpg")): # albedo=False: bump only (smooth paint)
+ t = tex_node(nt, os.path.join(d, "diff.jpg"))
+ if tint: # multiply albedo by a tint colour
+ mix = nt.nodes.new("ShaderNodeMix")
+ mix.data_type = "RGBA"
+ mix.blend_type = "MULTIPLY"
+ mix.inputs["Factor"].default_value = 1.0
+ nt.links.new(t.outputs["Color"], mix.inputs[6])
+ mix.inputs[7].default_value = (*tint, 1)
+ nt.links.new(mix.outputs[2], p.inputs["Base Color"])
+ else:
+ nt.links.new(t.outputs["Color"], p.inputs["Base Color"])
+ if os.path.exists(os.path.join(d, "rough.jpg")):
+ r = tex_node(nt, os.path.join(d, "rough.jpg"), True)
+ nt.links.new(r.outputs["Color"], p.inputs["Roughness"])
+ if os.path.exists(os.path.join(d, "nor.jpg")):
+ n = tex_node(nt, os.path.join(d, "nor.jpg"), True)
+ nm = nt.nodes.new("ShaderNodeNormalMap")
+ nt.links.new(n.outputs["Color"], nm.inputs["Color"])
+ nt.links.new(nm.outputs["Normal"], p.inputs["Normal"])
+ if alpha < 1:
+ p.inputs["Alpha"].default_value = alpha
+ if hasattr(m, "surface_render_method"):
+ m.surface_render_method = "BLENDED"
+ if hasattr(m, "blend_method"):
+ try:
+ m.blend_method = "BLEND"
+ except Exception:
+ pass
+ if emit:
+ p.inputs["Emission Color"].default_value = (*color, 1)
+ p.inputs["Emission Strength"].default_value = emit
+ m["tile"] = tile
+ MATS[name] = m
+ return m
+
+
+mat("wall", (0.86, 0.80, 0.70), 0.9, tex="white_plaster_02", tile=1.5, albedo=False) # warm off-white paint
+mat("wall_accent", rough=0.5, tex="american_walnut_veneer", tile=1.2, tint=(0.62, 0.42, 0.28)) # wood panel behind beds
+mat("ceiling", (0.95, 0.94, 0.91), 0.95, tex="white_plaster_02", tile=2.0, albedo=False)
+mat("exterior", (0.88, 0.78, 0.62), 0.95, tex="white_plaster_02", tile=2.5, albedo=False)
+mat("slab", (0.6, 0.6, 0.58), 0.9)
+mat("marble", tex="marble_01", tile=1.2)
+mat("wood", tex="laminate_floor_02", tile=2.0)
+mat("bathtile", tex="anti_skid_tiles", tile=0.6)
+mat("walltile", tex="long_white_tiles", tile=0.9)
+mat("terracotta", tex="terracotta_floor_tiles", tile=1.2)
+mat("concrete", tex="concrete_floor", tile=2.0)
+mat("grass", tex="leafy_grass", tile=1.5, tint=(0.55, 0.8, 0.4))
+mat("granite", rough=0.15, tex="marble_01", tile=1.5, tint=(0.12, 0.11, 0.11)) # black marble slab
+mat("stair", (0.62, 0.58, 0.52), 0.4, tex="granite_tile", tile=1.0)
+mat("glass", (0.75, 0.85, 0.9), 0.05, alpha=0.18)
+mat("frame", (0.92, 0.92, 0.92), 0.4) # uPVC/powder-coated window frames
+mat("steel", (0.75, 0.75, 0.77), 0.25, 1.0)
+mat("teak", rough=0.4, tex="black_walnut_veneer_01", tile=1.0, tint=(0.5, 0.3, 0.18))
+mat("laminate_w", rough=0.4, tex="oak_veneer_01", tile=1.2)
+mat("white_gloss", (0.93, 0.93, 0.92), 0.15)
+mat("ceramic", (0.97, 0.97, 0.96), 0.08)
+mat("fabric_bed", rough=0.9, tex="cotton_jersey", tile=0.4, tint=(1.0, 0.98, 0.95))
+mat("fabric_blanket", rough=0.9, tex="floral_jacquard", tile=0.6, tint=(1.0, 0.75, 0.7))
+mat("fabric_blue", rough=0.9, tex="gingham_check", tile=0.5, tint=(0.6, 0.75, 1.0))
+mat("fabric_green", rough=0.95, tex="caban", tile=0.6, tint=(0.7, 0.85, 0.65))
+mat("rug", rough=1.0, tex="hessian_380", tile=0.8, tint=(0.9, 0.75, 0.6))
+mat("curtain", rough=0.7, tex="cotton_jersey", tile=0.5, tint=(0.88, 0.82, 0.72))
+mat("black", (0.02, 0.02, 0.02), 0.3)
+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)
+
+# ---------------------------------------------------------------- geometry helpers
+COLL = {}
+
+
+def collection(name):
+ if name not in COLL:
+ c = bpy.data.collections.new(name)
+ scene.collection.children.link(c)
+ COLL[name] = c
+ return COLL[name]
+
+
+def mesh_from_boxes(name, boxes, coll="arch", bevel=0.0, seg=2):
+ """boxes: list of (x0,x1,y0,y1,z0,z1,matname) in FEET (object-local). One object, multi-material."""
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ uv = bm.loops.layers.uv.new("UVMap")
+ mat_names = []
+ for b in boxes:
+ x0, x1, y0, y1, z0, z1, mn = b
+ if x1 - x0 < 1e-4 or y1 - y0 < 1e-4 or z1 - z0 < 1e-4:
+ continue
+ if mn not in mat_names:
+ mat_names.append(mn)
+ mi = mat_names.index(mn)
+ tile = MATS[mn]["tile"]
+ v = [bm.verts.new((x * F, y * F, z * F)) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)]
+ # v index = z*4 + y*2 + x
+ quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
+ for q in quads:
+ try:
+ f = bm.faces.new([v[i] for i in q])
+ except ValueError:
+ continue
+ f.material_index = mi
+ f.normal_update()
+ n = f.normal
+ ax = max(range(3), key=lambda i: abs(n[i]))
+ a, c = [(1, 2), (0, 2), (0, 1)][ax]
+ for lp in f.loops:
+ co = lp.vert.co
+ lp[uv].uv = (co[a] / tile, co[c] / tile)
+ bm.to_mesh(me)
+ bm.free()
+ for mn in mat_names:
+ me.materials.append(MATS[mn])
+ ob = bpy.data.objects.new(name, me)
+ ob.location.z = LEVEL * F
+ collection(coll).objects.link(ob)
+ if bevel:
+ md = ob.modifiers.new("bevel", "BEVEL")
+ md.width = bevel
+ md.segments = seg
+ md.limit_method = "ANGLE"
+ return ob
+
+
+def overlap(a, b):
+ return all(a[2 * i] < b[2 * i + 1] - 1e-6 and b[2 * i] < a[2 * i + 1] - 1e-6 for i in range(3))
+
+
+def subtract(a, b):
+ """axis-aligned box difference a - b -> list of boxes (6-tuples)."""
+ if not overlap(a, b):
+ return [a]
+ out, a = [], list(a)
+ for ax in range(3):
+ lo, hi = 2 * ax, 2 * ax + 1
+ if a[lo] < b[lo]:
+ p = a.copy(); p[hi] = b[lo]; out.append(tuple(p)); a[lo] = b[lo]
+ if a[hi] > b[hi]:
+ p = a.copy(); p[lo] = b[hi]; out.append(tuple(p)); a[hi] = b[hi]
+ return out
+
+
+def subtract_all(boxes, cutters):
+ for c in cutters:
+ boxes = [p for b in boxes for p in subtract(b, c)]
+ return boxes
+
+
+def disjoint(boxes):
+ """remove overlaps so no two boxes share coincident faces (avoids z-fighting / black Cycles faces)."""
+ out = []
+ for b in boxes:
+ out += subtract_all([b], list(out))
+ return out
+
+
+# self-check of the box difference
+_t = subtract((0, 4, 0, 1, 0, 10), (1, 2, -1, 2, 0, 7))
+_d = disjoint([(0, 2, 0, 1, 0, 1), (1, 3, 0, 1, 0, 1)])
+assert abs(sum((b[1]-b[0])*(b[3]-b[2])*(b[5]-b[4]) for b in _d) - 3) < 1e-9, _d
+assert abs(sum((b[1]-b[0])*(b[3]-b[2])*(b[5]-b[4]) for b in _t) - (40 - 7)) < 1e-9, _t
+
+COLLIDERS = [] # (x0,x1,y0,y1) feet, 2D footprint blocking the walker
+FURN = [] # (name, footprint) of furniture, for the doorway clearance check
+# ---------------------------------------------------------------- furniture
+PROTO = {}
+
+
+def load_model(name):
+ if name in PROTO:
+ return PROTO[name]
+ if not name.replace("_", "").isalnum():
+ raise ValueError(f"bad model name {name!r}")
+ path = os.path.join(ASSETS, "models", name, f"{name}_1k.gltf")
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=path)
+ 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)
+ PROTO[name] = new
+ return new
+
+
+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)
+ root = bpy.data.objects.new(f"{name}_at_{x:.1f}_{y:.1f}", None)
+ collection("furniture").objects.link(root)
+ mapping = {}
+ for o in objs:
+ c = o.copy() # shares mesh data -> glTF instancing
+ mapping[o] = c
+ collection("furniture").objects.link(c)
+ for o, c in mapping.items():
+ c.parent = mapping.get(o.parent, root)
+ root.location = (x * F, y * F, (z + LEVEL) * F)
+ root.rotation_euler = (0, 0, math.radians(rot))
+ root.scale = (scale,) * 3
+ if collide:
+ bpy.context.view_layer.update()
+ add_collider([c for c in mapping.values() if c.type == "MESH"])
+ return root
+
+
+def add_collider(objs):
+ pts = [o.matrix_world @ Vector(c) for o in objs for c in o.bound_box]
+ if not pts:
+ return
+ # furniture does not block the walker; footprints are only used for the doorway clearance check
+ FURN.append((objs[0].name, (min(p.x for p in pts) / F, max(p.x for p in pts) / F,
+ min(p.y for p in pts) / F, max(p.y for p in pts) / F)))
+
+
+def group(name, boxes, x, y, rot=0, bevel=0.0, collide=True, z=0.0, seg=2):
+ """procedural item: boxes in local feet, front faces -Y, origin at footprint centre."""
+ ob = mesh_from_boxes(name, boxes, coll="furniture", bevel=bevel * F, seg=seg)
+ ob.location = (x * F, y * F, (z + LEVEL) * F)
+ ob.rotation_euler = (0, 0, math.radians(rot))
+ if collide:
+ bpy.context.view_layer.update()
+ add_collider([ob])
+ return ob
+
+
+# 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="fabric_blanket", panel=None):
+ """panel: width of the wood panel on the wall behind the bed (default bed + 1.8 ft each side; 0 = none)"""
+ 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
+ if hp > 0:
+ group("accent_panel", [(-hp, hp, yb - 0.03, yb, 0, WALL_H - 0.01, "wall_accent")],
+ x, y, rot, collide=False) # panel sits flush on the wall behind the headboard
+ group("bed_frame", [(-hw, hw, yf, yb - 0.25, 0.25, 1.1, "teak"),
+ (-hw, hw, yb - 0.25, yb, 0, 3.6, "teak"),
+ (-hw + 0.1, hw - 0.1, yb - 0.45, yb - 0.25, 1.6, 3.3, "fabric_bed")],
+ x, y, rot, bevel=0.04)
+ group("mattress", [(-hw + 0.1, hw - 0.1, yf + 0.1, yb - 0.3, 1.1, 1.75, "fabric_bed")],
+ x, y, rot, bevel=0.12, seg=3, collide=False)
+ group("blanket", [(-hw + 0.02, hw - 0.02, yf + 0.02, yb - 2.2, 1.6, 1.82, blanket)],
+ x, y, rot, bevel=0.08, seg=3, collide=False)
+ group("pillows", [(-hw + 0.3, -0.15, yb - 1.8, yb - 0.5, 1.7, 2.15, "fabric_bed"),
+ (0.15, hw - 0.3, yb - 1.8, yb - 0.5, 1.7, 2.15, "fabric_bed")],
+ x, y, rot, bevel=0.15, seg=3, collide=False)
+
+
+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")]
+ n = max(2, round(w / 1.5))
+ 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"))
+ hx = x0 + (w / n - 0.25 if i % 2 == 0 else 0.25)
+ b.append((hx - 0.04, hx + 0.04, -d / 2 - 0.08, -d / 2, 3.0, 4.2, "steel"))
+ group("wardrobe", b, x, y, rot, bevel=0.01)
+
+
+def wall_cabinet(x0, x1, y0, y1):
+ mesh_from_boxes("wall_cabinet", [(x0, x1, y0, y1, 5.0, 7.2, "laminate_w")], coll="furniture",
+ bevel=0.01 * F)
+
+
+def fridge(x, y, rot):
+ group("fridge", [(-1.15, 1.15, -1.0, 1.1, 0, 5.8, "appliance"),
+ (0.9, 0.98, -1.1, -1.0, 2.5, 4.5, "steel"), (0.9, 0.98, -1.1, -1.0, 4.7, 5.5, "steel"),
+ (-1.14, 1.14, -1.02, -1.0, 4.55, 4.6, "black")], x, y, rot, bevel=0.06)
+
+
+def wc(x, y, rot):
+ group("wc", [(-0.6, 0.6, -1.0, 0.5, 0, 1.3, "ceramic"), (-0.7, 0.7, 0.5, 1.15, 0, 2.6, "ceramic"),
+ (-0.65, 0.65, -1.05, 0.5, 1.3, 1.38, "white_gloss")], x, y, rot, bevel=0.15, seg=3)
+
+
+def basin(x, y, rot):
+ group("basin", [(-0.9, 0.9, -0.7, 0.6, 2.4, 2.85, "ceramic"), (-0.15, 0.15, -0.2, 0.6, 0, 2.4, "ceramic"),
+ (-0.05, 0.05, 0.25, 0.4, 2.85, 3.3, "steel"),
+ (-1.0, 1.0, 0.58, 0.62, 3.6, 6.0, "glass"), (-1.05, 1.05, 0.62, 0.66, 3.55, 6.05, "steel")],
+ x, y, rot, bevel=0.05, collide=True)
+
+
+def shower(x, y):
+ group("shower", [(-0.04, 0.04, -0.04, 0.04, 0, 6.8, "steel"), (-0.35, 0.35, -0.35, 0.35, 6.7, 6.78, "steel")],
+ x, y, 0, bevel=0.01, collide=False)
+
+
+def tv(x, y, rot, z=3.2):
+ group("tv", [(-2.0, 2.0, -0.05, 0.1, z, z + 2.3, "black"), (-1.95, 1.95, -0.07, -0.05, z + 0.05, z + 2.25, "screen")],
+ x, y, rot, bevel=0.01, collide=False)
+
+
+def rug(x0, x1, y0, y1, m="rug"):
+ mesh_from_boxes("rug", [(x0, x1, y0, y1, 0, 0.04, m)], coll="furniture", bevel=0.01 * F)
+
+
+def desk(x, y, rot):
+ group("desk", [(-1.75, 1.75, -1.0, 1.0, 2.4, 2.55, "teak"), (-1.75, -1.6, -1.0, 1.0, 0, 2.4, "teak"),
+ (1.6, 1.75, -1.0, 1.0, 0, 2.4, "teak"), (0.3, 1.6, -0.9, 1.0, 1.4, 2.4, "teak")],
+ x, y, rot, bevel=0.02)
+
+
+def ceiling_light(x, y, s=0.9):
+ mesh_from_boxes("ceiling_light", [(x - s, x + s, y - s, y + s, WALL_H - 0.08, WALL_H, "light")],
+ coll="furniture")
+
+
+
+
+# ---------------------------------------------------------------- real fixtures: curved, bevelled meshes
+# (items are assembled from parts under an empty; local feet, front faces -y at rot 0, back against +y)
+mat("chrome", (0.92, 0.92, 0.94), 0.06, 1.0)
+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("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)
+mat("plastic_white", (0.9, 0.9, 0.88), 0.35)
+mat("water", (0.55, 0.7, 0.75), 0.02, alpha=0.5)
+mat("blue_accent", (0.1, 0.35, 0.75), 0.3)
+
+
+def _mesh_obj(name, bm, mn, parent, loc=(0, 0, 0), rot=(0, 0, 0), smooth=40, bevel=0.0, seg=3, solid=0.0):
+ me = bpy.data.meshes.new(name)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(MATS[mn])
+ if smooth:
+ me.shade_smooth()
+ me.set_sharp_from_angle(angle=math.radians(smooth))
+ ob = bpy.data.objects.new(name, me)
+ collection("furniture").objects.link(ob)
+ ob.parent = parent
+ ob.location = Vector(loc) * F
+ ob.rotation_euler = [math.radians(a) for a in rot]
+ if solid:
+ md = ob.modifiers.new("solid", "SOLIDIFY")
+ md.thickness = solid * F
+ if bevel:
+ md = ob.modifiers.new("bevel", "BEVEL")
+ md.width, md.segments, md.limit_method = bevel * F, seg, "ANGLE"
+ md.harden_normals = False
+ return ob
+
+
+def _bm_xform(bm, scale=(1, 1, 1), lift=0.0):
+ for v in bm.verts:
+ v.co = Vector((v.co.x * scale[0], v.co.y * scale[1], v.co.z * scale[2] + lift))
+ return bm
+
+
+def p_cyl(root, name, r1, r2, h, mn, loc=(0, 0, 0), rot=(0, 0, 0), sx=1.0, sy=1.0, segs=48, **kw):
+ """cone/cylinder, base at local z=0 before rotation; sx/sy squash the cross-section."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=segs, radius1=r1 * F, radius2=r2 * F,
+ depth=h * F)
+ return _mesh_obj(name, _bm_xform(bm, (sx, sy, 1), h * F / 2), mn, root, loc, rot, **kw)
+
+
+def p_box(root, name, sx, sy, sz, mn, loc=(0, 0, 0), rot=(0, 0, 0), bevel=0.02, seg=3, **kw):
+ """box centred on x/y, base at z=0 (feet)."""
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ return _mesh_obj(name, _bm_xform(bm, (sx * F, sy * F, sz * F), sz * F / 2), mn, root, loc, rot,
+ smooth=30, bevel=bevel, seg=seg, **kw)
+
+
+def p_frustum(root, name, w0, d0, w1, d1, h, mn, loc=(0, 0, 0), **kw):
+ """tapered box: bottom w0 x d0, top w1 x d1 (feet), base at z=0."""
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ for v in bm.verts:
+ top = v.co.z > 0
+ v.co = Vector((v.co.x * (w1 if top else w0) * F, v.co.y * (d1 if top else d0) * F, (v.co.z + 0.5) * h * F))
+ return _mesh_obj(name, bm, mn, root, loc, smooth=0, **kw)
+
+
+def p_bowl(root, name, r, depth, mn, loc=(0, 0, 0), sy=1.0, wall=0.04):
+ """open bowl (lower half sphere), rim at local z=0."""
+ bm = bmesh.new()
+ bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=r * F)
+ bmesh.ops.delete(bm, geom=[v for v in bm.verts if v.co.z > 1e-5], context="VERTS")
+ _bm_xform(bm, (1, sy, depth / r))
+ return _mesh_obj(name, bm, mn, root, loc, smooth=80, solid=wall)
+
+
+def p_torus(root, name, R, r, mn, loc=(0, 0, 0), rot=(0, 0, 0), sy=1.0, u=48, v=16):
+ bm = bmesh.new()
+ rings = []
+ for i in range(u):
+ a = 2 * math.pi * i / u
+ ring = []
+ for j in range(v):
+ b = 2 * math.pi * j / v
+ d = R + r * math.cos(b)
+ ring.append(bm.verts.new((d * math.cos(a) * F, d * math.sin(a) * sy * F, r * math.sin(b) * F)))
+ rings.append(ring)
+ for i in range(u):
+ for j in range(v):
+ a, b = rings[i], rings[(i + 1) % u]
+ bm.faces.new((a[j], b[j], b[(j + 1) % v], a[(j + 1) % v]))
+ return _mesh_obj(name, bm, mn, root, loc, rot, smooth=80)
+
+
+def p_tube(root, name, pts, radius, mn):
+ """swept round tube through local points (feet); used for taps, rails and hoses."""
+ cu = bpy.data.curves.new(name, "CURVE")
+ cu.dimensions = "3D"
+ cu.bevel_depth, cu.bevel_resolution, cu.use_fill_caps = radius * F, 4, True
+ sp = cu.splines.new("NURBS")
+ sp.points.add(len(pts) - 1)
+ for p, c in zip(sp.points, pts):
+ p.co = (c[0] * F, c[1] * F, c[2] * F, 1)
+ sp.use_endpoint_u, sp.order_u = True, min(4, len(pts))
+ tmp = bpy.data.objects.new(name + "_crv", cu)
+ scene.collection.objects.link(tmp)
+ bpy.context.view_layer.update()
+ me = bpy.data.meshes.new_from_object(tmp.evaluated_get(bpy.context.evaluated_depsgraph_get()))
+ bpy.data.objects.remove(tmp)
+ bpy.data.curves.remove(cu)
+ me.materials.clear()
+ me.materials.append(MATS[mn])
+ me.shade_smooth()
+ ob = bpy.data.objects.new(name, me)
+ collection("furniture").objects.link(ob)
+ ob.parent = root
+ return ob
+
+
+def item(name, x, y, rot=0, z=0.0):
+ root = bpy.data.objects.new(name, None)
+ collection("furniture").objects.link(root)
+ root.location = (x * F, y * F, (z + LEVEL) * F)
+ root.rotation_euler = (0, 0, math.radians(rot))
+ return root
+
+
+def done(root, collide=True):
+ if collide:
+ bpy.context.view_layer.update()
+ add_collider([c for c in root.children_recursive if c.type == "MESH"])
+ return root
+
+
+def arc(c, r, a0, a1, n=10, plane="yz"):
+ """points on a circular arc (degrees) around centre c in the given plane."""
+ pts = []
+ for i in range(n + 1):
+ a = math.radians(a0 + (a1 - a0) * i / n)
+ u, v = r * math.cos(a), r * math.sin(a)
+ pts.append((c[0], c[1] + u, c[2] + v) if plane == "yz" else (c[0] + u, c[1], c[2] + v))
+ return pts
+
+
+def wc2(x, y, rot):
+ """floor-mounted one-piece EWC with closed soft-close lid, cistern, chrome flush and health faucet."""
+ r = item("wc", x, y, rot)
+ p_cyl(r, "wc_body", 0.42, 0.6, 1.22, "ceramic", (0, -0.2, 0), sy=1.38, bevel=0.06, seg=4)
+ p_box(r, "wc_skirt", 1.05, 0.7, 1.22, "ceramic", (0, 0.5, 0), bevel=0.12, seg=4)
+ p_cyl(r, "wc_seat", 0.62, 0.62, 0.07, "white_gloss", (0, -0.2, 1.22), sy=1.38, bevel=0.03)
+ p_cyl(r, "wc_lid", 0.6, 0.6, 0.07, "white_gloss", (0, -0.17, 1.29), sy=1.36, bevel=0.03)
+ p_box(r, "wc_cistern", 1.32, 0.55, 1.15, "ceramic", (0, 0.78, 1.25), bevel=0.14, seg=5)
+ p_box(r, "wc_cistern_lid", 1.38, 0.6, 0.08, "ceramic", (0, 0.78, 2.4), bevel=0.03)
+ p_cyl(r, "wc_flush", 0.11, 0.11, 0.03, "chrome", (0, 0.78, 2.48))
+ # health faucet on the side wall-ish bracket with a coiled hose
+ p_box(r, "hf_holder", 0.12, 0.08, 0.2, "chrome", (0.95, 0.98, 2.0), bevel=0.02)
+ p_cyl(r, "hf_head", 0.05, 0.06, 0.45, "chrome", (0.95, 0.9, 1.95), rot=(15, 0, 0))
+ p_tube(r, "hf_hose", [(0.95, 0.95, 1.95), (1.0, 0.9, 1.2), (0.9, 0.85, 0.6), (0.85, 0.95, 1.6),
+ (0.9, 1.0, 2.3)], 0.025, "chrome")
+ return done(r)
+
+
+def vanity(x, y, rot, w=2.6):
+ """wall-hung vanity: laminate cabinet, quartz top, vessel basin, tall mixer, backlit mirror."""
+ r = item("vanity", x, y, rot)
+ d = 1.6
+ p_box(r, "vanity_cab", w, d, 1.5, "laminate_w", (0, 0.05, 1.05), bevel=0.02)
+ p_box(r, "vanity_groove", w - 0.1, 0.02, 0.04, "black", (0, 0.05 - d / 2 - 0.005, 2.25), bevel=0)
+ p_box(r, "vanity_top", w + 0.1, d + 0.1, 0.12, "quartz", (0, 0.05, 2.55), bevel=0.02)
+ p_bowl(r, "basin_bowl", 0.62, 0.5, "ceramic", (0, -0.1, 3.15), sy=0.82)
+ p_cyl(r, "basin_drain", 0.06, 0.06, 0.01, "chrome", (0, -0.1, 2.68))
+ p_cyl(r, "tap_base", 0.07, 0.07, 0.15, "chrome", (0, 0.55, 2.67))
+ p_tube(r, "tap_spout", [(0, 0.55, 2.7), (0, 0.55, 3.55)] + arc((0, 0.35, 3.55), 0.2, 0, 160, 8)[1:] +
+ [(0, 0.2, 3.35)], 0.045, "chrome")
+ p_box(r, "tap_lever", 0.06, 0.25, 0.05, "chrome", (0.1, 0.5, 3.2), rot=(-20, 0, 0), bevel=0.01)
+ p_box(r, "mirror_glow", w * 0.9 + 0.1, 0.03, 3.1, "led", (0, d / 2 + 0.02, 3.95), bevel=0)
+ p_box(r, "mirror", w * 0.9, 0.06, 3.0, "mirror", (0, d / 2 - 0.02, 4.0), bevel=0.05)
+ p_box(r, "soap_dish", 0.35, 0.25, 0.05, "black_glass", (w / 2 - 0.35, 0.4, 2.67), bevel=0.02)
+ return done(r)
+
+
+def shower2(x, y, rot, glass=None):
+ """rain shower on a wall arm + concealed mixer + floor drain; glass = (x0,x1,y0,y1) world screen."""
+ r = item("shower", x, y, rot)
+ p_tube(r, "shower_arm", [(0, 0.0, 7.4), (0, -0.4, 7.4), (0, -0.9, 7.3), (0, -1.1, 7.15)], 0.05, "chrome")
+ p_box(r, "shower_head", 0.85, 0.85, 0.05, "chrome", (0, -1.1, 7.05), bevel=0.02)
+ p_cyl(r, "mixer_plate", 0.28, 0.28, 0.04, "chrome", (0, 0.02, 3.8), rot=(90, 0, 0))
+ p_box(r, "mixer_lever", 0.06, 0.12, 0.4, "chrome", (0, -0.06, 3.75), bevel=0.02)
+ p_box(r, "floor_drain", 0.4, 0.4, 0.015, "steel", (0, -1.1, 0.0), bevel=0)
+ p_cyl(r, "hand_shower", 0.05, 0.07, 0.6, "chrome", (0.5, -0.05, 3.9), rot=(0, 0, 0))
+ p_tube(r, "hand_hose", [(0.5, -0.05, 3.9), (0.55, -0.15, 2.8), (0.4, -0.1, 2.2), (0.3, 0.0, 3.6)], 0.025,
+ "chrome")
+ done(r, collide=False)
+ if glass:
+ x0, x1, y0, y1 = glass
+ mesh_from_boxes("shower_glass", [(x0, x1, y0, y1, 0.05, 6.8, "glass")], coll="furniture")
+ mesh_from_boxes("shower_glass_trim", [(x0, x1, y0, y1, 6.8, 6.85, "chrome"),
+ (x0, x1, y0, y1, 0.0, 0.05, "chrome")], coll="furniture")
+ return r
+
+
+def geyser(x, y, rot, z=6.4):
+ r = item("geyser", x, y, rot, z=z)
+ p_cyl(r, "geyser_tank", 0.5, 0.5, 1.7, "plastic_white", (-0.85, -0.55, 0.5), rot=(0, 90, 0), bevel=0.12,
+ seg=4)
+ p_box(r, "geyser_panel", 0.5, 0.05, 0.25, "blue_accent", (0, -1.04, 0.35), bevel=0.02)
+ return done(r, collide=False)
+
+
+def _doors(r, length, depth, z0, z1, handle_at, front_y, n=None):
+ """shaker-ish door fronts with bar handles along local x; front_y = local y of the cabinet face."""
+ n = n or max(1, round(length / 1.5))
+ dw = length / n
+ for i in range(n):
+ cx = -length / 2 + dw * (i + 0.5)
+ p_box(r, "door", dw - 0.04, 0.06, z1 - z0 - 0.04, "laminate_w", (cx, front_y - 0.03, z0 + 0.02), bevel=0.01)
+ p_box(r, "door_panel", dw - 0.4, 0.02, z1 - z0 - 0.5, "laminate_w", (cx, front_y - 0.065, z0 + 0.25),
+ bevel=0.005)
+ hx = cx + (dw / 2 - 0.25 if i % 2 == 0 else -dw / 2 + 0.25)
+ p_box(r, "handle", 0.05, 0.08, 0.7, "chrome", (hx, front_y - 0.1, handle_at - 0.35), bevel=0.015)
+
+
+def kitchen_run(x0, x1, y0, y1, front, sink=None, hob=None, doors=True):
+ """base cabinets + granite top in world feet; front = side the cook stands ('-y','+y','+x','-x').
+ sink / hob = position along the run (world x for runs along x, world y for runs along y)."""
+ along_x = front in ("-y", "+y")
+ L, Dp = (x1 - x0, y1 - y0) if along_x else (y1 - y0, x1 - x0)
+ rot = {"-y": 0, "+x": 90, "+y": 180, "-x": 270}[front]
+ r = item("kitchen_run", (x0 + x1) / 2, (y0 + y1) / 2, rot)
+ flip = 1 if front in ("-y", "+x") else -1 # local x vs world axis direction after rotation
+ c = (x0 + x1) / 2 if along_x else (y0 + y1) / 2
+
+ def local(u): # world coordinate along the run -> local x
+ return (u - c) * flip
+
+ p_box(r, "plinth", L, Dp - 0.3, 0.33, "black", (0, 0.15, 0), bevel=0)
+ p_box(r, "carcass", L, Dp - 0.05, 2.42, "laminate_w", (0, 0.025, 0.33), bevel=0.005)
+ if doors:
+ _doors(r, L, Dp, 0.36, 2.72, 2.55, -Dp / 2 + 0.05)
+ # granite top with a hole for the sink bowl
+ top = [(-L / 2, L / 2, -Dp / 2 - 0.08, Dp / 2, 2.75, 2.9)]
+ holes = []
+ if sink is not None:
+ sx = local(sink)
+ holes.append((sx - 0.9, sx + 0.9, -0.55, 0.55, 2.0, 3.0))
+ top = subtract_all(top, holes)
+ for i, b in enumerate(top):
+ p_box(r, "counter_top", b[1] - b[0], b[3] - b[2], 0.15, "granite",
+ ((b[0] + b[1]) / 2, (b[2] + b[3]) / 2, 2.75), bevel=0.01)
+ p_box(r, "backsplash", L, 0.04, 2.0, "walltile", (0, Dp / 2 - 0.02, 2.9), bevel=0)
+ if sink is not None:
+ sx = local(sink)
+ for bx, by, w_, d_ in ((sx, -0.55, 1.8, 0.04), (sx, 0.55, 1.8, 0.04), (sx - 0.9, 0, 0.04, 1.1),
+ (sx + 0.9, 0, 0.04, 1.1)):
+ p_box(r, "sink_wall", w_, d_, 0.7, "steel", (bx, by, 2.2), bevel=0)
+ p_box(r, "sink_floor", 1.8, 1.1, 0.03, "steel", (sx, 0, 2.2), bevel=0)
+ p_cyl(r, "sink_drain", 0.12, 0.12, 0.01, "cast_iron", (sx, 0, 2.235))
+ p_box(r, "sink_rim", 1.95, 1.25, 0.02, "steel", (sx, 0, 2.9), bevel=0)
+ p_box(r, "sink_rim_cut", 1.8, 1.1, 0.03, "steel", (sx, 0, 2.9), bevel=0)
+ p_cyl(r, "faucet_base", 0.08, 0.08, 0.1, "chrome", (sx, 0.75, 2.9))
+ p_tube(r, "faucet", [(sx, 0.75, 2.95), (sx, 0.75, 3.9)] + arc((sx, 0.45, 3.9), 0.3, 0, 170, 10)[1:] +
+ [(sx, 0.15, 3.6)], 0.05, "chrome")
+ if hob is not None:
+ hx = local(hob)
+ p_box(r, "hob_glass", 2.4, 1.5, 0.08, "black_glass", (hx, 0.05, 2.9), bevel=0.02)
+ for k, bx in enumerate((-0.75, 0.0, 0.75)):
+ rb = 0.22 if k != 1 else 0.28
+ p_cyl(r, "burner", rb, rb * 0.9, 0.07, "brass", (hx + bx, 0.15, 2.98))
+ p_cyl(r, "burner_cap", rb * 0.6, rb * 0.5, 0.05, "cast_iron", (hx + bx, 0.15, 3.05))
+ for a in (0, 45, 90, 135):
+ p_box(r, "pan_support", 0.06, rb * 2 + 0.25, 0.08, "cast_iron", (hx + bx, 0.15, 3.0),
+ rot=(0, 0, a), bevel=0.01)
+ p_cyl(r, "knob", 0.07, 0.07, 0.07, "chrome", (hx + bx, -0.6, 2.98))
+ return done(r)
+
+
+def wall_cab2(x0, x1, y0, y1, front, z0=4.9, z1=7.2):
+ along_x = front in ("-y", "+y")
+ L, Dp = (x1 - x0, y1 - y0) if along_x else (y1 - y0, x1 - x0)
+ rot = {"-y": 0, "+x": 90, "+y": 180, "-x": 270}[front]
+ r = item("wall_cabinet", (x0 + x1) / 2, (y0 + y1) / 2, rot)
+ p_box(r, "wall_carcass", L, Dp - 0.05, z1 - z0, "laminate_w", (0, 0.025, z0), bevel=0.005)
+ _doors(r, L, Dp, z0, z1, z0 + 0.55, -Dp / 2 + 0.05)
+ p_box(r, "under_led", L - 0.2, 0.05, 0.02, "led", (0, -Dp / 2 + 0.3, z0 - 0.02), bevel=0)
+ return done(r, collide=False)
+
+
+def chimney(x, y, rot):
+ """kitchen hood: steel pyramid + black glass skirt + flue box up to the ceiling."""
+ r = item("chimney", x, y, rot)
+ p_frustum(r, "hood", 2.5, 1.5, 0.95, 0.85, 0.9, "steel", (0, -0.6, 5.05), bevel=0.01)
+ p_box(r, "hood_skirt", 2.5, 1.5, 0.2, "black_glass", (0, -0.6, 4.85), bevel=0.01)
+ p_box(r, "flue", 0.9, 0.8, WALL_H - 5.9, "steel", (0, -0.55, 5.9), bevel=0.01)
+ return done(r, collide=False)
+
+
+def fridge2(x, y, rot):
+ r = item("fridge", x, y, rot)
+ p_box(r, "fridge_body", 2.3, 2.1, 5.8, "appliance", (0, 0.05, 0), bevel=0.1, seg=4)
+ for s in (-1, 1):
+ p_box(r, "fridge_door", 1.12, 0.12, 5.6, "appliance", (s * 0.58, -1.03, 0.1), bevel=0.06, seg=3)
+ p_tube(r, "fridge_handle", [(s * 0.12, -1.22, 2.6), (s * 0.12, -1.22, 4.4)], 0.04, "chrome")
+ p_box(r, "fridge_display", 0.4, 0.02, 0.5, "black_glass", (-0.6, -1.1, 3.8), bevel=0.01)
+ return done(r)
+
+
+def washer2(x, y, rot):
+ r = item("washing_machine", x, y, rot)
+ p_box(r, "wm_body", 2.0, 1.9, 2.8, "white_gloss", (0, 0, 0), bevel=0.12, seg=4)
+ p_torus(r, "wm_ring", 0.55, 0.07, "chrome", (0, -0.97, 1.25), rot=(90, 0, 0))
+ p_cyl(r, "wm_glass", 0.5, 0.5, 0.05, "black_glass", (0, -0.93, 1.25), rot=(90, 0, 0))
+ p_box(r, "wm_panel", 1.9, 0.02, 0.4, "black_glass", (0, -0.96, 2.3), bevel=0.01)
+ p_cyl(r, "wm_knob", 0.12, 0.12, 0.05, "chrome", (0.6, -0.97, 2.5), rot=(90, 0, 0))
+ return done(r)
+
+
+def puja_mandir(x, y, rot, w=3.6):
+ """wooden mandir unit: storage base, back panel, pillars and a stepped shikhara canopy."""
+ r = item("mandir", x, y, rot)
+ p_box(r, "mandir_base", w, 1.5, 2.4, "teak", (0, 0, 0), bevel=0.03)
+ _doors(r, w, 1.5, 0.15, 2.3, 1.9, -0.75, n=2)
+ p_box(r, "mandir_back", w, 0.15, 4.2, "teak", (0, 0.68, 2.4), bevel=0.02)
+ p_box(r, "mandir_led", w - 0.4, 0.03, 3.6, "led", (0, 0.58, 2.6), bevel=0)
+ for s in (-1, 1):
+ p_cyl(r, "mandir_pillar", 0.1, 0.1, 3.6, "brass", (s * (w / 2 - 0.2), -0.55, 2.4))
+ p_box(r, "mandir_lintel", w + 0.1, 1.5, 0.25, "teak", (0, 0, 6.0), bevel=0.03)
+ for k, f in enumerate((0.88, 0.72, 0.55)):
+ p_box(r, "mandir_step", w * f, 1.2, 0.25, "teak", (0, 0.05, 6.25 + 0.25 * k), bevel=0.02)
+ p_cyl(r, "shikhara", w * 0.26, 0.08, 1.4, "brass", (0, 0.05, 7.0), segs=8)
+ return done(r)
+