"""Blender modelling script: contemporary structural-biology laboratory (illustrative scenery).

Run inside Blender (executed through the local Blender MCP connector):
    exec(compile(open(PATH).read(), PATH, "exec"))

Everything is built in an isolated scene named "PTP1B_Lab"; no other scene or datablock of
the running Blender session is modified. Geometry is accumulated per (group, material) so the
exported GLB needs few draw calls. Display surfaces are separate objects named SCREEN_<id>
(UV 0..1) so the browser can map live research content onto them, and PEDESTAL_<id> empties
mark where coordinate-derived molecular models are placed. No molecular geometry is made here.

Outputs (in scene/): ptp1b_research_lab.blend, ptp1b_laboratory.glb, lab_layout.json
"""
import bpy, bmesh, math, json, os, random
from mathutils import Matrix, Vector, Euler

OUT = globals().get("OUT_DIR") or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCN = "PTP1B_Lab"
RX, RY, RH = 6.0, 4.5, 3.2          # room half-extents (m) and height
rng = random.Random(7)

# ------------------------------------------------------------------ clean previous build
old = bpy.data.scenes.get(SCN)
if old:
    for ob in list(old.collection.all_objects):
        bpy.data.objects.remove(ob, do_unlink=True)
    for col in list(old.collection.children_recursive):
        bpy.data.collections.remove(col)
    bpy.data.scenes.remove(old)
for coll in (bpy.data.meshes, bpy.data.materials, bpy.data.lights, bpy.data.cameras):
    for d in list(coll):
        if d.name.startswith("LAB_") and d.users == 0:
            coll.remove(d)

scene = bpy.data.scenes.new(SCN)
scene.unit_settings.system = "METRIC"
root = bpy.data.collections.new("LAB_Room")
scene.collection.children.link(root)

# ------------------------------------------------------------------ materials (PBR)
MATS = {
    # name: (rgb, metallic, roughness, emission rgb, emission strength, alpha)
    "floor_epoxy":   ((0.62, 0.65, 0.67), 0.0, 0.35, None, 0, 1),
    "wall_paint":    ((0.90, 0.91, 0.90), 0.0, 0.85, None, 0, 1),
    "wall_accent":   ((0.16, 0.24, 0.30), 0.0, 0.70, None, 0, 1),
    "ceiling":       ((0.93, 0.93, 0.92), 0.0, 0.90, None, 0, 1),
    "skirting":      ((0.20, 0.22, 0.24), 0.0, 0.60, None, 0, 1),
    "led_panel":     ((1.0, 1.0, 1.0), 0.0, 0.4, (1.0, 0.97, 0.92), 6.0, 1),
    "led_strip":     ((1.0, 1.0, 1.0), 0.0, 0.4, (0.85, 0.93, 1.0), 3.0, 1),
    "bench_top":     ((0.07, 0.08, 0.09), 0.0, 0.42, None, 0, 1),
    "cabinet_white": ((0.86, 0.87, 0.88), 0.0, 0.50, None, 0, 1),
    "cabinet_blue":  ((0.20, 0.36, 0.50), 0.0, 0.50, None, 0, 1),
    "steel":         ((0.72, 0.73, 0.75), 1.0, 0.32, None, 0, 1),
    "steel_dark":    ((0.18, 0.19, 0.20), 1.0, 0.45, None, 0, 1),
    "plastic_black": ((0.03, 0.03, 0.035), 0.0, 0.45, None, 0, 1),
    "plastic_grey":  ((0.45, 0.47, 0.50), 0.0, 0.55, None, 0, 1),
    "plastic_white": ((0.88, 0.88, 0.86), 0.0, 0.45, None, 0, 1),
    "plastic_blue":  ((0.10, 0.32, 0.72), 0.0, 0.45, None, 0, 1),
    "plastic_orange": ((0.90, 0.42, 0.08), 0.0, 0.50, None, 0, 1),
    "plastic_yellow": ((0.92, 0.76, 0.12), 0.0, 0.50, None, 0, 1),
    "rubber":        ((0.02, 0.02, 0.02), 0.0, 0.90, None, 0, 1),
    "fabric_chair":  ((0.12, 0.15, 0.19), 0.0, 0.95, None, 0, 1),
    "glass_clear":   ((0.80, 0.90, 0.95), 0.0, 0.05, None, 0, 0.22),
    "glass_amber":   ((0.55, 0.28, 0.06), 0.0, 0.10, None, 0, 0.70),
    "glass_lead":    ((0.60, 0.72, 0.55), 0.0, 0.08, None, 0, 0.30),
    "liquid_blue":   ((0.10, 0.35, 0.85), 0.0, 0.15, None, 0, 0.80),
    "screen_off":    ((0.01, 0.012, 0.015), 0.0, 0.20, None, 0, 1),
    "indicator_green": ((0.1, 0.9, 0.3), 0.0, 0.4, (0.1, 1.0, 0.3), 4.0, 1),
    "indicator_amber": ((1.0, 0.6, 0.1), 0.0, 0.4, (1.0, 0.55, 0.05), 4.0, 1),
    "holo_ring":     ((0.2, 0.8, 1.0), 0.0, 0.3, (0.15, 0.75, 1.0), 5.0, 1),
    "pedestal":      ((0.10, 0.11, 0.13), 0.6, 0.35, None, 0, 1),
    "paper":         ((0.93, 0.92, 0.88), 0.0, 0.90, None, 0, 1),
    "binder_red":    ((0.55, 0.10, 0.10), 0.0, 0.60, None, 0, 1),
    "binder_green":  ((0.10, 0.36, 0.22), 0.0, 0.60, None, 0, 1),
    "binder_navy":   ((0.08, 0.14, 0.33), 0.0, 0.60, None, 0, 1),
    "door_wood":     ((0.50, 0.52, 0.55), 0.0, 0.55, None, 0, 1),
    "safety_red":    ((0.75, 0.05, 0.04), 0.0, 0.40, None, 0, 1),
}


def make_mat(name, spec):
    rgb, metal, rough, em, es, alpha = spec
    m = bpy.data.materials.new("LAB_" + name)
    m.use_nodes = True
    b = next(n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
    def setv(keys, v):
        for k in keys:
            if k in b.inputs:
                b.inputs[k].default_value = v
                return
    setv(["Base Color"], (*rgb, 1.0))
    setv(["Metallic"], metal)
    setv(["Roughness"], rough)
    if em:
        setv(["Emission Color", "Emission"], (*em, 1.0))
        setv(["Emission Strength"], es)
    if alpha < 1:
        setv(["Alpha"], alpha)
        for attr, val in (("surface_render_method", "BLENDED"), ("blend_method", "BLEND")):
            try:
                setattr(m, attr, val)
            except Exception:
                pass
    m.diffuse_color = (*rgb, alpha)
    return m


M = {k: make_mat(k, v) for k, v in MATS.items()}
ACC, COLLIDERS, STATIONS, STATS = {}, [], {}, {"primitives": 0}


def acc(group, mat):
    key = (group, mat)
    if key not in ACC:
        ACC[key] = bmesh.new()
    return ACC[key]


def _merge(bm, group, mat, mtx):
    bmesh.ops.transform(bm, matrix=mtx, verts=bm.verts)
    tmp = bpy.data.meshes.new("LAB_tmp")
    bm.to_mesh(tmp)
    bm.free()
    acc(group, mat).from_mesh(tmp)
    bpy.data.meshes.remove(tmp)
    STATS["primitives"] += 1


def _mtx(loc, rot):
    return Matrix.Translation(Vector(loc)) @ Euler(rot, "XYZ").to_matrix().to_4x4()


def box(group, mat, size, loc, rot=(0, 0, 0), bevel=0.0, collide=False, name=None):
    bm = bmesh.new()
    bmesh.ops.create_cube(bm, size=1.0)
    bmesh.ops.scale(bm, vec=Vector(size), verts=bm.verts)
    if bevel > 0:
        bmesh.ops.bevel(bm, geom=list(bm.edges), offset=min(bevel, min(size) * 0.45), segments=1, affect="EDGES")
    _merge(bm, group, mat, _mtx(loc, rot))
    if collide:
        COLLIDERS.append(dict(name=name or f"{group}_{len(COLLIDERS)}", min=[loc[0] - size[0] / 2, loc[1] - size[1] / 2],
                              max=[loc[0] + size[0] / 2, loc[1] + size[1] / 2], top=loc[2] + size[2] / 2))


def cyl(group, mat, r, h, loc, rot=(0, 0, 0), seg=20, r2=None, smooth=True):
    bm = bmesh.new()
    bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=seg, radius1=r, radius2=r if r2 is None else r2, depth=h)
    if smooth:
        for f in bm.faces:
            if len(f.verts) == 4:
                f.smooth = True
    _merge(bm, group, mat, _mtx(loc, rot))


def sphere(group, mat, r, loc, seg=14, scale=(1, 1, 1)):
    bm = bmesh.new()
    bmesh.ops.create_uvsphere(bm, u_segments=seg, v_segments=max(6, seg // 2), radius=r)
    bmesh.ops.scale(bm, vec=Vector(scale), verts=bm.verts)
    for f in bm.faces:
        f.smooth = True
    _merge(bm, group, mat, _mtx(loc, (0, 0, 0)))


def collider(name, x0, x1, y0, y1, top=3.0):
    COLLIDERS.append(dict(name=name, min=[min(x0, x1), min(y0, y1)], max=[max(x0, x1), max(y0, y1)], top=top))


def link(ob):
    root.objects.link(ob)
    return ob


def screen(sid, w, h, center, normal, title, kind):
    """Separate UV-mapped quad the browser textures with live content; faces `normal`."""
    n = Vector(normal).normalized()
    u = Vector((0, 0, 1))
    r = u.cross(n)
    c = Vector(center)
    me = bpy.data.meshes.new(f"LAB_SCREEN_{sid}")
    bm = bmesh.new()
    uvl = bm.loops.layers.uv.new("UVMap")
    pts = [(c - r * w / 2 - u * h / 2, (0, 0)), (c + r * w / 2 - u * h / 2, (1, 0)), (c + r * w / 2 + u * h / 2, (1, 1)), (c - r * w / 2 + u * h / 2, (0, 1))]
    vs = [bm.verts.new(p) for p, _ in pts]
    f = bm.faces.new(vs)
    for loop, (_, uv) in zip(f.loops, pts):
        loop[uvl].uv = uv
    bm.normal_update()
    bm.to_mesh(me)
    bm.free()
    mat = make_mat(f"SCREEN_{sid}", ((0.02, 0.05, 0.08), 0.0, 0.25, (0.10, 0.30, 0.45), 1.2, 1))
    me.materials.append(mat)
    ob = link(bpy.data.objects.new(f"SCREEN_{sid}", me))
    ob["station"] = sid
    ob["content_kind"] = kind
    STATIONS[sid] = dict(id=sid, title=title, kind=kind, screen=f"SCREEN_{sid}", center=[round(x, 4) for x in c], normal=[round(x, 4) for x in n],
                         width=w, height=h)
    return ob


def marker(name, loc, **props):
    e = link(bpy.data.objects.new(name, None))
    e.empty_display_type = "SPHERE"
    e.empty_display_size = 0.15
    e.location = loc
    for k, v in props.items():
        e[k] = v
    return e


# ================================================================== architecture
G = "Architecture"
T = 0.12
box(G, "wall_paint", (2 * RX + 2 * T, T, RH), (0, RY + T / 2, RH / 2))                       # north
box(G, "wall_paint", (T, 2 * RY, RH), (-RX - T / 2, 0, RH / 2))                             # west
box(G, "wall_paint", (T, 2 * RY, RH), (RX + T / 2, 0, RH / 2))                              # east
DW, DH = 1.10, 2.15                                                                          # door opening in the south wall
seg = RX + T - DW / 2
box(G, "wall_paint", (seg, T, RH), (-(DW / 2 + seg / 2), -RY - T / 2, RH / 2))
box(G, "wall_paint", (seg, T, RH), ((DW / 2 + seg / 2), -RY - T / 2, RH / 2))
box(G, "wall_paint", (DW, T, RH - DH), (0, -RY - T / 2, DH + (RH - DH) / 2))
box(G, "door_wood", (DW - 0.04, 0.05, DH - 0.02), (0, -RY - 0.03, DH / 2), bevel=0.004)      # door leaf (closed)
box(G, "glass_clear", (0.32, 0.055, 0.85), (0.22, -RY - 0.03, 1.50))                         # vision panel
box(G, "steel", (0.035, 0.05, 0.22), (-0.42, -RY + 0.02, 1.05), bevel=0.004)                 # handle
for sx in (-1, 1):
    box(G, "steel_dark", (0.05, T + 0.04, DH), (sx * (DW / 2 + 0.025), -RY - T / 2, DH / 2))
box(G, "steel_dark", (DW + 0.10, T + 0.04, 0.05), (0, -RY - T / 2, DH + 0.025))
box(G, "ceiling", (2 * RX + 2 * T, 2 * RY + 2 * T, 0.10), (0, 0, RH + 0.05))
# dark accent bands behind the wall displays
box(G, "wall_accent", (2 * RX, 0.012, 1.9), (0, RY - 0.006, 1.75))
box(G, "wall_accent", (4.2, 0.012, 1.9), (-3.4, -RY + 0.006, 1.75))
box(G, "wall_accent", (4.2, 0.012, 1.9), (3.4, -RY + 0.006, 1.75))
# skirting
box(G, "skirting", (2 * RX, 0.02, 0.10), (0, RY - 0.01, 0.05))
box(G, "skirting", (0.02, 2 * RY, 0.10), (-RX + 0.01, 0, 0.05))
box(G, "skirting", (0.02, 2 * RY, 0.10), (RX - 0.01, 0, 0.05))
for sx in (-1, 1):
    box(G, "skirting", (RX - DW / 2 - 0.05, 0.02, 0.10), (sx * (DW / 2 + 0.05 + (RX - DW / 2 - 0.05) / 2), -RY + 0.01, 0.05))
# floor: own object with UVs in metres so the browser can apply a tiled finish
me = bpy.data.meshes.new("LAB_Floor")
bm = bmesh.new()
uvl = bm.loops.layers.uv.new("UVMap")
vs = [bm.verts.new(p) for p in ((-RX, -RY, 0), (RX, -RY, 0), (RX, RY, 0), (-RX, RY, 0))]
f = bm.faces.new(vs)
for loop, uv in zip(f.loops, ((0, 0), (2 * RX, 0), (2 * RX, 2 * RY), (0, 2 * RY))):
    loop[uvl].uv = uv
bm.normal_update(); bm.to_mesh(me); bm.free()
me.materials.append(M["floor_epoxy"])
link(bpy.data.objects.new("LAB_Floor", me))

# ceiling services
G = "Lighting"
PANELS = []
for px in (-4.0, 0.0, 4.0):
    for py in (-2.4, 0.6, 3.2):
        box(G, "led_panel", (1.2, 0.6, 0.015), (px, py, RH - 0.012))
        box(G, "steel", (1.26, 0.66, 0.03), (px, py, RH - 0.004))
        PANELS.append([px, py, RH - 0.03])
G = "Architecture"
for px in (-2.0, 2.0):                                                                       # supply-air diffusers
    box(G, "plastic_white", (0.6, 0.6, 0.03), (px, -0.9, RH - 0.015))
    for k in range(4):
        box(G, "plastic_grey", (0.5 - k * 0.11, 0.5 - k * 0.11, 0.008), (px, -0.9, RH - 0.034 - k * 0.003))
box(G, "steel", (0.30, 2 * RY - 0.4, 0.06), (5.2, 0, RH - 0.25))                             # cable tray above the equipment wall
for py in (-3.5, -1.2, 1.2, 3.5):
    box(G, "steel", (0.02, 0.02, 0.22), (5.2, py, RH - 0.11))
cyl(G, "steel", 0.11, 2 * RX - 0.6, (0, 2.05, RH - 0.20), rot=(0, math.pi / 2, 0), seg=16)   # exhaust duct
for px in (-4.5, -1.5, 1.5, 4.5):
    box(G, "steel_dark", (0.03, 0.26, 0.03), (px, 2.05, RH - 0.07))


# ================================================================== furniture helpers
def bottle(group, x, y, z, kind):
    if kind == 0:      # amber reagent bottle
        r, h = 0.045, 0.16
        cyl(group, "glass_amber", r, h, (x, y, z + h / 2), seg=12)
        cyl(group, "plastic_black", r * 0.55, 0.03, (x, y, z + h + 0.015), seg=10)
    elif kind == 1:    # clear media bottle with blue cap and liquid
        r, h = 0.05, 0.19
        cyl(group, "glass_clear", r, h, (x, y, z + h / 2), seg=12)
        cyl(group, "liquid_blue", r * 0.9, h * 0.55, (x, y, z + h * 0.29), seg=12)
        cyl(group, "plastic_blue", r * 0.6, 0.035, (x, y, z + h + 0.017), seg=10)
    elif kind == 2:    # white plastic jar
        r, h = 0.055, 0.13
        cyl(group, "plastic_white", r, h, (x, y, z + h / 2), seg=12)
        cyl(group, "plastic_orange", r * 0.9, 0.025, (x, y, z + h + 0.012), seg=12)
    else:              # squeeze / wash bottle
        r, h = 0.035, 0.17
        cyl(group, "plastic_white", r, h, (x, y, z + h / 2), seg=10)
        cyl(group, "plastic_yellow", r * 0.5, 0.05, (x, y, z + h + 0.025), seg=8, r2=r * 0.15)


def tube_rack(group, x, y, z, nx=6, ny=4, rot=0.0):
    w, d = 0.022 * nx + 0.02, 0.022 * ny + 0.02
    box(group, "plastic_blue", (w, d, 0.045), (x, y, z + 0.0225), rot=(0, 0, rot), bevel=0.003)
    c, s = math.cos(rot), math.sin(rot)
    for i in range(nx):
        for j in range(ny):
            if rng.random() < 0.25:
                continue
            lx, ly = (i - (nx - 1) / 2) * 0.022, (j - (ny - 1) / 2) * 0.022
            px, py = x + lx * c - ly * s, y + lx * s + ly * c
            cyl(group, "glass_clear", 0.0075, 0.05, (px, py, z + 0.055), seg=6, smooth=False)
            cyl(group, rng.choice(["plastic_orange", "plastic_blue", "plastic_yellow", "plastic_white"]), 0.0085, 0.008, (px, py, z + 0.084), seg=6, smooth=False)


def stool(x, y):
    g = "Benches"
    cyl(g, "fabric_chair", 0.17, 0.05, (x, y, 0.64), seg=18)
    cyl(g, "steel", 0.022, 0.5, (x, y, 0.37), seg=10)
    cyl(g, "steel", 0.16, 0.012, (x, y, 0.30), seg=18)
    for k in range(5):
        a = k * 2 * math.pi / 5
        box(g, "steel_dark", (0.26, 0.035, 0.025), (x + 0.13 * math.cos(a), y + 0.13 * math.sin(a), 0.085), rot=(0, 0, a))
        cyl(g, "rubber", 0.025, 0.02, (x + 0.26 * math.cos(a), y + 0.26 * math.sin(a), 0.03), rot=(math.pi / 2, 0, a), seg=8)
    collider("stool", x - 0.2, x + 0.2, y - 0.2, y + 0.2, top=0.7)


def office_chair(x, y, face):
    g = "Workstations"
    cyl(g, "fabric_chair", 0.24, 0.07, (x, y, 0.47), seg=18)
    box(g, "fabric_chair", (0.06, 0.44, 0.50), (x - 0.22 * face, y, 0.80), bevel=0.02)
    cyl(g, "steel_dark", 0.025, 0.36, (x, y, 0.27), seg=10)
    for k in range(5):
        a = k * 2 * math.pi / 5 + 0.3
        box(g, "plastic_black", (0.30, 0.04, 0.03), (x + 0.15 * math.cos(a), y + 0.15 * math.sin(a), 0.085), rot=(0, 0, a))
        cyl(g, "rubber", 0.028, 0.025, (x + 0.30 * math.cos(a), y + 0.30 * math.sin(a), 0.03), rot=(math.pi / 2, 0, a), seg=8)
    collider("chair", x - 0.28, x + 0.28, y - 0.28, y + 0.28, top=1.0)


def monitor(group, x, y, z, w, h, facing, sid=None, title="", kind=""):
    """Monitor standing on a surface at height z; `facing` is +1 (faces +X) or -1."""
    box(group, "plastic_black", (0.03, w + 0.024, h + 0.024), (x, y, z + 0.13 + h / 2), bevel=0.004)
    box(group, "plastic_black", (0.05, 0.10, 0.16), (x - 0.03 * facing, y, z + 0.11))
    box(group, "steel_dark", (0.20, 0.26, 0.012), (x - 0.02 * facing, y, z + 0.006), bevel=0.003)
    if sid:
        screen(sid, w, h, (x + 0.0165 * facing, y, z + 0.13 + h / 2), (facing, 0, 0), title, kind)
    else:
        box(group, "screen_off", (0.004, w, h), (x + 0.0155 * facing, y, z + 0.13 + h / 2))


def keyboard(group, x, y, z, facing):
    box(group, "plastic_black", (0.14, 0.44, 0.016), (x, y, z + 0.008), bevel=0.003)
    for r in range(4):
        for c in range(14):
            box(group, "plastic_grey", (0.022, 0.024, 0.006), (x - 0.045 + r * 0.03, y - 0.195 + c * 0.03, z + 0.019))
    box(group, "plastic_black", (0.10, 0.06, 0.03), (x, y + 0.34 * facing, z + 0.015), bevel=0.012)   # mouse


def desk(cy, width, n_mon, sid, title, kind, sid2=None, title2="", kind2=""):
    g = "Workstations"
    x0 = -RX + 0.45
    box(g, "cabinet_white", (0.80, width, 0.035), (x0, cy, 0.735), bevel=0.006)
    for sy in (-1, 1):
        box(g, "steel_dark", (0.70, 0.04, 0.72), (x0, cy + sy * (width / 2 - 0.05), 0.36))
    box(g, "steel_dark", (0.03, width - 0.14, 0.30), (x0 - 0.33, cy, 0.52))
    collider(f"desk_{sid}", -RX, x0 + 0.42, cy - width / 2, cy + width / 2, top=0.76)
    zt = 0.7525
    if n_mon == 2:
        monitor(g, x0 - 0.22, cy - 0.36, zt, 0.62, 0.36, 1, sid, title, kind)
        monitor(g, x0 - 0.22, cy + 0.36, zt, 0.62, 0.36, 1, sid2, title2, kind2)
    else:
        monitor(g, x0 - 0.22, cy, zt, 0.86, 0.37, 1, sid, title, kind)
    keyboard(g, x0 + 0.12, cy, zt, 1)
    box(g, "plastic_black", (0.42, 0.19, 0.44), (x0 - 0.05, cy - width / 2 + 0.22, 0.24), bevel=0.008)   # workstation tower
    box(g, "indicator_green", (0.004, 0.012, 0.012), (x0 + 0.161, cy - width / 2 + 0.22, 0.40))
    office_chair(x0 + 0.75, cy, 1)


def island(cx, cy, tag):
    g = "Benches"
    L, W, Hh = 3.4, 1.5, 0.92
    box(g, "bench_top", (W, L, 0.04), (cx, cy, Hh - 0.02), bevel=0.006)
    collider(f"bench_{tag}", cx - W / 2, cx + W / 2, cy - L / 2, cy + L / 2, top=Hh)
    for sx in (-1, 1):                                    # under-bench cabinets with drawers on both long sides
        for k, yy in enumerate((-1.25, -0.42, 0.42, 1.25)):
            if k in (1,) and sx == 1:
                continue                                  # knee space
            box(g, "cabinet_white", (0.58, 0.78, 0.80), (cx + sx * 0.44, cy + yy, 0.48), bevel=0.004)
            for dz in (0.24, 0.50, 0.74):
                box(g, "cabinet_blue", (0.012, 0.74, 0.22), (cx + sx * 0.736, cy + yy, dz + 0.08))
                box(g, "steel", (0.02, 0.22, 0.012), (cx + sx * 0.752, cy + yy, dz + 0.14))
    box(g, "steel_dark", (W - 0.1, L - 0.1, 0.08), (cx, cy, 0.04))                                  # plinth
    shelf_levels = (0.08,) if cx < 0 else (0.42, 0.76)
    spine_height = shelf_levels[-1] + 0.02
    for yy in (-L / 2 + 0.06, 0, L / 2 - 0.06):
        box(g, "steel", (0.04, 0.04, spine_height), (cx, cy + yy, Hh + spine_height / 2))
    for level in shelf_levels:
        zz = Hh + level
        box(g, "cabinet_white", (0.34, L - 0.1, 0.022), (cx, cy, zz), bevel=0.004)
        box(g, "led_strip", (0.03, L - 0.3, 0.008), (cx, cy, zz - 0.016))
        yy = -L / 2 + 0.22
        while yy < L / 2 - 0.2:
            for sx in (-0.09, 0.09):
                if rng.random() < 0.8:
                    bottle(g, cx + sx, cy + yy, zz + 0.011, rng.choice([0, 0, 1, 1, 2, 3]))
            yy += rng.uniform(0.13, 0.2)
    for sx in (-1, 1):                                    # service sockets
        box(g, "plastic_white", (0.01, 0.16, 0.08), (cx + sx * 0.022, cy - 0.8, Hh + 0.12))
        box(g, "plastic_white", (0.01, 0.16, 0.08), (cx + sx * 0.022, cy + 0.8, Hh + 0.12))
    return Hh


def compound_microscope(x, y, z, rot=0.0):
    g = "Equipment"
    R = (0, 0, rot)
    c, s = math.cos(rot), math.sin(rot)
    def P(dx, dy, dz):
        return (x + dx * c - dy * s, y + dx * s + dy * c, z + dz)
    box(g, "plastic_white", (0.20, 0.26, 0.04), P(0, 0, 0.02), R, bevel=0.01)
    box(g, "plastic_white", (0.07, 0.07, 0.30), P(0, 0.085, 0.19), R, bevel=0.01)
    box(g, "plastic_white", (0.08, 0.20, 0.06), P(0, 0.0, 0.345), R, bevel=0.012)
    box(g, "plastic_black", (0.15, 0.15, 0.012), P(0, -0.02, 0.165), R)                                 # stage
    cyl(g, "steel_dark", 0.035, 0.03, P(0, -0.04, 0.30), seg=14)                                     # nosepiece
    for a in (-0.6, 0.0, 0.6):
        cyl(g, "steel", 0.011, 0.055, P(0.022 * math.sin(a), -0.04 - 0.012 * math.cos(a), 0.262), seg=8)
    for sx in (-0.03, 0.03):                                                                           # binocular eyepieces
        cyl(g, "plastic_black", 0.015, 0.10, P(sx, -0.115, 0.405), rot=(math.radians(-55), 0, rot), seg=10)
    cyl(g, "plastic_black", 0.028, 0.05, P(0, 0.09, 0.10), rot=(0, math.pi / 2, rot), seg=12)        # focus knobs
    cyl(g, "plastic_black", 0.020, 0.26, P(0, 0.09, 0.10), rot=(0, math.pi / 2, rot), seg=10)
    cyl(g, "led_strip", 0.022, 0.006, P(0, -0.02, 0.045), seg=12)                                   # illuminator


def stereo_microscope(x, y, z):
    g = "Equipment"
    box(g, "plastic_white", (0.26, 0.30, 0.025), (x, y, z + 0.0125), bevel=0.008)
    cyl(g, "glass_clear", 0.07, 0.004, (x, y - 0.03, z + 0.027), seg=18)
    cyl(g, "steel", 0.016, 0.42, (x, y + 0.11, z + 0.235), seg=10)
    box(g, "plastic_grey", (0.07, 0.11, 0.07), (x, y + 0.07, z + 0.30), bevel=0.008)
    cyl(g, "plastic_white", 0.05, 0.12, (x, y - 0.03, z + 0.30), seg=14)
    cyl(g, "steel_dark", 0.035, 0.04, (x, y - 0.03, z + 0.225), seg=14)
    for sx in (-0.03, 0.03):
        cyl(g, "plastic_black", 0.016, 0.11, (x + sx, y - 0.075, z + 0.40), rot=(math.radians(-45), 0, 0), seg=10)
    # 96-well crystallisation plate under the objective
    box(g, "glass_clear", (0.127, 0.085, 0.014), (x, y - 0.03, z + 0.036))


def centrifuge(x, y, z):
    g = "Equipment"
    box(g, "plastic_white", (0.36, 0.44, 0.22), (x, y, z + 0.11), bevel=0.02)
    cyl(g, "plastic_grey", 0.15, 0.03, (x, y + 0.03, z + 0.235), seg=20)
    cyl(g, "glass_lead", 0.09, 0.006, (x, y + 0.03, z + 0.253), seg=18)
    box(g, "plastic_black", (0.20, 0.008, 0.07), (x, y - 0.221, z + 0.13))
    box(g, "indicator_green", (0.06, 0.004, 0.02), (x - 0.04, y - 0.226, z + 0.14))


def pipette_stand(x, y, z):
    g = "Equipment"
    cyl(g, "plastic_grey", 0.09, 0.015, (x, y, z + 0.0075), seg=16)
    cyl(g, "steel", 0.008, 0.30, (x, y, z + 0.16), seg=8)
    cyl(g, "plastic_grey", 0.085, 0.012, (x, y, z + 0.30), seg=16)
    cols = ["plastic_yellow", "plastic_blue", "plastic_orange", "plastic_white"]
    for k in range(4):
        a = k * math.pi / 2 + 0.4
        px, py = x + 0.075 * math.cos(a), y + 0.075 * math.sin(a)
        cyl(g, "plastic_grey", 0.012, 0.16, (px, py, z + 0.22), seg=8)
        cyl(g, cols[k], 0.014, 0.03, (px, py, z + 0.315), seg=8)
        cyl(g, "plastic_white", 0.004, 0.07, (px, py, z + 0.105), seg=6, r2=0.0015)


def plate_stack(x, y, z, n):
    for k in range(n):
        box("Equipment", "glass_clear", (0.127, 0.085, 0.016), (x + rng.uniform(-0.004, 0.004), y + rng.uniform(-0.004, 0.004), z + 0.008 + k * 0.0175))


def pedestal(sid, x, y, title):
    g = "Displays"
    cyl(g, "pedestal", 0.46, 0.06, (x, y, 0.03), seg=32)
    cyl(g, "pedestal", 0.36, 0.84, (x, y, 0.48), seg=32, r2=0.30)
    cyl(g, "pedestal", 0.44, 0.05, (x, y, 0.925), seg=32)
    cyl(g, "holo_ring", 0.40, 0.012, (x, y, 0.956), seg=32)
    cyl(g, "pedestal", 0.34, 0.016, (x, y, 0.958), seg=32)
    collider(f"pedestal_{sid}", x - 0.42, x + 0.42, y - 0.42, y + 0.42, top=0.96)
    marker(f"PEDESTAL_{sid}", (x, y, 1.55), station=sid, role="coordinate-derived molecular model is placed here by the browser")
    STATIONS.setdefault(sid, {})["pedestal"] = [x, y, 1.55]


def wall_display(sid, x, y, w, h, z, normal, title, kind):
    g = "Displays"
    ny = normal[1]
    box(g, "plastic_black", (w + 0.06, 0.05, h + 0.06), (x, y - ny * 0.03, z), bevel=0.006)
    screen(sid, w, h, (x, y + ny * 0.0005 - ny * 0.004, z), normal, title, kind)
    box(g, "steel_dark", (w * 0.5, 0.10, 0.03), (x, y - ny * 0.03, z - h / 2 - 0.10))            # sound-bar / sensor strip


# ================================================================== island benches and bench equipment
zA = island(-2.6, 1.0, "A")
zB = island(2.6, 1.0, "B")
compound_microscope(-3.05, 2.25, zA, rot=math.pi / 2)
compound_microscope(-3.05, 1.55, zA, rot=math.pi / 2)
centrifuge(-2.15, 2.1, zA)
pipette_stand(-3.05, 0.55, zA)
pipette_stand(-2.15, 0.25, zA)
tube_rack("Equipment", -3.0, 0.15, zA, rot=0.2)
tube_rack("Equipment", -3.05, -0.25, zA, rot=-0.1)
tube_rack("Equipment", -2.15, 1.25, zA, nx=8, ny=3, rot=1.57)
box("Equipment", "plastic_blue", (0.26, 0.20, 0.16), (-2.2, -0.35, zA + 0.08), bevel=0.02)       # ice bucket
box("Equipment", "plastic_grey", (0.16, 0.20, 0.12), (-2.15, 0.75, zA + 0.06), bevel=0.02)       # vortex mixer
cyl("Equipment", "rubber", 0.035, 0.03, (-2.15, 0.75, zA + 0.135), seg=12)
box("Equipment", "plastic_white", (0.30, 0.22, 0.012), (-3.0, -0.6, zA + 0.006))               # lab notebook (closed)
box("Equipment", "binder_navy", (0.30, 0.22, 0.004), (-3.0, -0.6, zA + 0.014))
stereo_microscope(3.05, 2.15, zB)
stereo_microscope(3.05, 1.35, zB)
plate_stack(2.15, 2.25, zB, 6)
plate_stack(2.15, 2.05, zB, 4)
plate_stack(3.05, 0.75, zB, 3)
# drop-setting robot (illustrative)
box("Equipment", "plastic_white", (0.55, 0.70, 0.06), (2.2, 1.15, zB + 0.03), bevel=0.01)
for sy in (-0.32, 0.32):
    box("Equipment", "steel", (0.05, 0.04, 0.34), (1.97, 1.15 + sy, zB + 0.23))
box("Equipment", "plastic_grey", (0.07, 0.72, 0.07), (1.97, 1.15, zB + 0.40), bevel=0.01)
box("Equipment", "plastic_orange", (0.22, 0.10, 0.10), (2.08, 1.05, zB + 0.33), bevel=0.01)
box("Equipment", "glass_clear", (0.127, 0.085, 0.016), (2.28, 1.0, zB + 0.068))
box("Equipment", "glass_clear", (0.127, 0.085, 0.016), (2.28, 1.3, zB + 0.068))
cyl("Equipment", "steel", 0.11, 0.26, (3.05, 0.15, zB + 0.13), seg=18)                          # bench-top transfer dewar
cyl("Equipment", "steel_dark", 0.06, 0.05, (3.05, 0.15, zB + 0.285), seg=14)
tube_rack("Equipment", 2.2, 0.35, zB, nx=5, ny=5)
tube_rack("Equipment", 2.2, -0.1, zB, nx=6, ny=4, rot=0.3)
pipette_stand(3.0, -0.35, zB)
for (sx_, sy_) in ((-3.7, 1.8), (-1.5, 0.3), (3.7, 1.8), (1.5, 1.6)):
    stool(sx_, sy_)

# ================================================================== workstations (west wall)
desk(2.3, 1.9, 2, "analysis", "Analysis workstation", "scripts, notebook cells, result tables, figures",
     "analysis_b", "Analysis workstation (second monitor)", "figure preview")
desk(-1.3, 1.7, 1, "verify", "Verification terminal", "verification tests, reviewer findings, limitations")
box("Workstations", "cabinet_white", (0.5, 0.9, 1.1), (-RX + 0.27, 0.45, 0.55), bevel=0.006)        # filing cabinet between desks
for dz in (0.22, 0.55, 0.88):
    box("Workstations", "steel", (0.012, 0.3, 0.02), (-RX + 0.525, 0.45, dz))
collider("filing", -RX, -RX + 0.54, 0.0, 0.9, top=1.1)
box("Workstations", "plastic_grey", (0.36, 0.46, 0.20), (-RX + 0.27, 0.45, 1.20), bevel=0.02)       # printer
box("Workstations", "paper", (0.21, 0.30, 0.012), (-RX + 0.36, 0.45, 1.306))

# ================================================================== wall displays, stations and pedestals
# Both wall-mounted displays share a mounting line and frame.
back_display = (2.60, 1.46, 1.75)  # width, height, centre above the floor (metres)
wall_display("timeline", -3.3, RY - 0.03, *back_display, (0, -1, 0), "Research timeline", "provenance timeline from recorded events")
wall_display("literature", 3.3, RY - 0.03, *back_display, (0, -1, 0), "Literature viewer", "references and how each source was used")
wall_display("compare", -3.4, -RY + 0.03, 2.6, 1.46, 1.75, (0, 1, 0), "Open / closed comparison", "5K9W vs 5K9V superposition and RMSD")
wall_display("pocket", 3.4, -RY + 0.03, 2.6, 1.46, 1.75, (0, 1, 0), "Allosteric site station", "ligand 892 neighbourhood in 1T49")
# freestanding molecular display between the benches
g = "Displays"
box(g, "steel_dark", (0.9, 0.5, 0.03), (0, 3.35, 0.015), bevel=0.006)
for sx in (-0.5, 0.5):
    box(g, "steel", (0.06, 0.06, 1.45), (sx, 3.38, 0.75))
box(g, "plastic_black", (2.46, 0.05, 1.41), (0, 3.40, 1.78), bevel=0.006)
screen("viewer", 2.4, 1.35, (0, 3.372, 1.78), (0, -1, 0), "Molecular structure viewer", "experimental PTP1B coordinates")
collider("viewer_display", -1.25, 1.25, 3.2, 3.6, top=2.5)
pedestal("viewer", 0.0, 2.1, "Structure")
pedestal("compare", -3.4, -3.15, "Open vs closed")
pedestal("pocket", 3.4, -3.15, "Allosteric site")
# reading shelf under the literature display (scenery)
g = "Storage"
box(g, "cabinet_white", (2.6, 0.34, 0.03), (3.3, RY - 0.19, 0.86), bevel=0.005)
box(g, "cabinet_white", (2.6, 0.34, 0.03), (3.3, RY - 0.19, 0.46), bevel=0.005)
for sx in (-1.28, 0, 1.28):
    box(g, "cabinet_white", (0.03, 0.34, 0.86), (3.3 + sx, RY - 0.19, 0.43))
xx = 2.08
while xx < 4.5:
    w_ = rng.uniform(0.035, 0.07)
    if abs(xx - 3.3) > 0.05:
        box(g, rng.choice(["binder_red", "binder_green", "binder_navy", "paper", "plastic_grey"]), (w_, 0.24, rng.uniform(0.26, 0.32)), (xx, RY - 0.19, 0.475 + 0.15))
    xx += w_ + 0.006
collider("lit_shelf", 2.0, 4.6, RY - 0.4, RY, top=0.9)

# ================================================================== equipment wall (east)
g = "Storage"
# -80 C freezer
box(g, "plastic_white", (0.85, 0.90, 1.95), (RX - 0.45, 3.45, 0.975), bevel=0.012, collide=True, name="freezer")
box(g, "cabinet_white", (0.02, 0.86, 1.60), (RX - 0.885, 3.45, 0.95), bevel=0.006)
box(g, "steel", (0.05, 0.04, 0.60), (RX - 0.92, 3.08, 1.05), bevel=0.006)
box(g, "plastic_black", (0.012, 0.36, 0.16), (RX - 0.88, 3.45, 1.84))
box(g, "indicator_green", (0.004, 0.16, 0.05), (RX - 0.888, 3.40, 1.85))
# crystal incubator with glass door and plate shelves
box(g, "plastic_white", (0.70, 0.75, 1.85), (RX - 0.38, 2.4, 0.925), bevel=0.012, collide=True, name="incubator")
box(g, "plastic_black", (0.01, 0.62, 1.30), (RX - 0.735, 2.4, 1.02))
box(g, "glass_clear", (0.012, 0.60, 1.28), (RX - 0.745, 2.4, 1.02))
for k in range(5):
    box(g, "steel", (0.006, 0.56, 0.008), (RX - 0.737, 2.4, 0.50 + k * 0.26))
    for j in range(3):
        box(g, "glass_clear", (0.01, 0.127, 0.05), (RX - 0.739, 2.2 + j * 0.2, 0.535 + k * 0.26))
box(g, "indicator_amber", (0.004, 0.10, 0.03), (RX - 0.735, 2.4, 1.76))
# open shelving with cryo boxes
box(g, "steel", (0.45, 1.3, 0.03), (RX - 0.26, -3.55, 0.015))
for sy in (-0.63, 0.63):
    for sx in (-0.2, 0.2):
        box(g, "steel", (0.03, 0.03, 1.9), (RX - 0.26 + sx, -3.55 + sy, 0.95))
for k in range(5):
    zz = 0.25 + k * 0.38
    box(g, "steel", (0.45, 1.3, 0.02), (RX - 0.26, -3.55, zz))
    yy = -4.12
    while yy < -3.0:
        if rng.random() < 0.85:
            box(g, rng.choice(["plastic_white", "plastic_blue", "plastic_orange", "paper", "plastic_yellow"]), (0.30, 0.134, 0.055 + 0.05 * (k % 2)),
                (RX - 0.27, yy, zz + 0.045 + 0.025 * (k % 2)), bevel=0.004)
        yy += 0.15
collider("shelving", RX - 0.5, RX, -4.2, -2.9)
# liquid-nitrogen dewars
g = "Equipment"
for (dx, dy, r, h) in ((RX - 0.55, -2.15, 0.27, 0.72), (RX - 0.50, -1.45, 0.20, 0.55)):
    cyl(g, "steel", r, h, (dx, dy, 0.12 + h / 2), seg=28)
    cyl(g, "steel", r * 0.45, 0.14, (dx, dy, 0.12 + h + 0.07), seg=20, r2=r * 0.35)
    cyl(g, "plastic_blue", r * 0.36, 0.05, (dx, dy, 0.12 + h + 0.165), seg=16)
    cyl(g, "steel_dark", r * 1.05, 0.04, (dx, dy, 0.10), seg=28)
    for k in range(5):
        a = k * 2 * math.pi / 5
        cyl(g, "rubber", 0.035, 0.03, (dx + r * 0.9 * math.cos(a), dy + r * 0.9 * math.sin(a), 0.04), rot=(math.pi / 2, 0, a), seg=8)
    collider("dewar", dx - r, dx + r, dy - r, dy + r, top=1.0)
# X-ray diffractometer enclosure (illustrative)
ex, ey = RX - 0.85, 0.25
box(g, "cabinet_white", (1.5, 2.0, 0.90), (ex, ey, 0.45), bevel=0.01, collide=True, name="diffractometer")
box(g, "steel_dark", (1.5, 2.0, 0.05), (ex, ey, 0.925))
for sx in (-0.72, 0.72):
    for sy in (-0.97, 0.97):
        box(g, "plastic_white", (0.06, 0.06, 1.10), (ex + sx, ey + sy, 1.50))
box(g, "plastic_white", (1.5, 2.0, 0.10), (ex, ey, 2.10), bevel=0.01)
box(g, "glass_lead", (0.012, 1.86, 1.08), (ex - 0.735, ey, 1.50))
box(g, "glass_lead", (1.36, 0.012, 1.08), (ex, ey - 0.985, 1.50))
box(g, "glass_lead", (1.36, 0.012, 1.08), (ex, ey + 0.985, 1.50))
box(g, "steel", (0.03, 0.05, 0.30), (ex - 0.76, ey - 0.4, 1.45), bevel=0.005)
cyl(g, "steel_dark", 0.16, 0.10, (ex, ey, 1.00), seg=24)                                       # goniometer base
cyl(g, "steel", 0.05, 0.36, (ex, ey, 1.20), seg=16)
box(g, "steel_dark", (0.05, 0.30, 0.05), (ex, ey + 0.11, 1.40))
cyl(g, "steel", 0.012, 0.10, (ex, ey + 0.02, 1.47), rot=(math.pi / 2, 0, 0), seg=8)            # goniometer head and pin
cyl(g, "plastic_orange", 0.004, 0.05, (ex, ey - 0.05, 1.47), rot=(math.pi / 2, 0, 0), seg=6)
box(g, "plastic_black", (0.34, 0.14, 0.34), (ex, ey - 0.62, 1.47), bevel=0.01)                 # detector
box(g, "steel_dark", (0.30, 0.012, 0.30), (ex, ey - 0.545, 1.47))
cyl(g, "steel", 0.05, 0.50, (ex, ey + 0.55, 1.47), rot=(math.pi / 2, 0, 0), seg=14)            # source / optics
cyl(g, "steel_dark", 0.02, 0.16, (ex, ey + 0.24, 1.47), rot=(math.pi / 2, 0, 0), seg=10, r2=0.006)
cyl(g, "steel", 0.03, 0.34, (ex + 0.28, ey + 0.1, 1.52), rot=(0, math.radians(60), 0), seg=10)  # cryostream nozzle
cyl(g, "indicator_amber", 0.05, 0.10, (ex - 0.5, ey - 0.8, 2.20), seg=14)                      # status beacon
box(g, "plastic_black", (0.01, 0.40, 0.26), (ex - 0.755, ey + 0.55, 0.62))
box(g, "indicator_green", (0.004, 0.06, 0.02), (ex - 0.761, ey + 0.45, 0.70))
# safety fixtures by the door
g = "Architecture"
cyl(g, "safety_red", 0.07, 0.42, (1.15, -RY + 0.13, 0.75), seg=16)
cyl(g, "plastic_black", 0.03, 0.08, (1.15, -RY + 0.13, 1.00), seg=10)
box(g, "plastic_yellow", (0.30, 0.10, 0.20), (-1.2, -RY + 0.06, 1.25), bevel=0.02)             # eyewash station
box(g, "plastic_white", (0.12, 0.012, 0.16), (0.85, -RY + 0.012, 1.25))                        # light switch plate
cyl("Storage", "plastic_grey", 0.19, 0.55, (-1.7, -RY + 0.3, 0.275), seg=18, r2=0.22)          # waste bins
cyl("Storage", "plastic_yellow", 0.19, 0.55, (-2.2, -RY + 0.3, 0.275), seg=18, r2=0.22)
collider("bins", -2.45, -1.45, -RY, -RY + 0.55, top=0.6)

# ================================================================== flush accumulators into objects
for (group, mat), bm in sorted(ACC.items()):
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)
    me = bpy.data.meshes.new(f"LAB_{group}_{mat}")
    bm.normal_update()
    bm.to_mesh(me)
    bm.free()
    me.materials.append(M[mat])
    ob = link(bpy.data.objects.new(f"LAB_{group}_{mat}", me))
    ob["group"] = group
    ob["scenery"] = "illustrative laboratory scenery; carries no scientific data"

# lights and camera for renders of the .blend (the browser builds its own real-time lights)
for i, (px, py, pz) in enumerate(PANELS):
    L = bpy.data.lights.new(f"LAB_PanelLight_{i}", "AREA")
    L.shape = "RECTANGLE"; L.size = 1.2; L.size_y = 0.6; L.energy = 260; L.color = (1.0, 0.97, 0.92)
    lo = link(bpy.data.objects.new(f"LAB_PanelLight_{i}", L))
    lo.location = (px, py, pz)
cam = bpy.data.cameras.new("LAB_Camera")
cam.lens = 20
co = link(bpy.data.objects.new("LAB_Camera", cam))
co.location = (0.0, -4.1, 1.65)
co.rotation_euler = (math.radians(86), 0, 0)
scene.camera = co
marker("PLAYER_START", (0.0, -3.4, 0.0), heading_deg=0)
world = bpy.data.worlds.new("LAB_World")
scene.world = world
try:
    world.use_nodes = True
    world.node_tree.nodes["Background"].inputs[0].default_value = (0.02, 0.025, 0.03, 1)
except Exception:
    pass
try:
    scene.render.engine = "BLENDER_EEVEE"
except Exception:
    pass
scene.render.resolution_x, scene.render.resolution_y = 1600, 900

tris = sum(sum(len(p.vertices) - 2 for p in o.data.polygons) for o in root.objects if o.type == "MESH")
layout = dict(units="metres; Blender Z-up (GLB is exported Y-up: x_gl = x, y_gl = z, z_gl = -y)", room=dict(half_x=RX, half_y=RY, height=RH),
              player_start=[0.0, -3.4], stations=STATIONS, colliders=COLLIDERS, ceiling_panels=PANELS,
              stats=dict(mesh_objects=sum(o.type == "MESH" for o in root.objects), triangles=int(tris), materials=len({o.data.materials[0].name for o in root.objects if o.type == "MESH"}),
                         primitives=STATS["primitives"]),
              note="All geometry in this file is illustrative laboratory scenery. Molecular models shown in the browser are built from validated PDB coordinates, not from Blender geometry.")
with open(os.path.join(OUT, "lab_layout.json"), "w") as fh:
    json.dump(layout, fh, indent=1)
print("BUILD_OK", json.dumps(layout["stats"]), "stations", sorted(STATIONS), "colliders", len(COLLIDERS))
