#!/usr/bin/env python3 """Blender-free building_spec.json -> GLB exporter. Replicates the geometry rules of the skill's build_blender_showcase.py (segment prisms, z-windows, footprint slabs, generated roofs, floor__category naming) using trimesh, so the lightweight Web showcase can be produced without a Blender install. The Web viewer recolours meshes by category from model_metadata.json, so only correct node names + geometry are required. """ from __future__ import annotations import argparse, json, math, sys from pathlib import Path import numpy as np import trimesh from shapely.geometry import Polygon CATEGORY_DRAW_ORDER = ("grid","floor_lines","detail_lines","doors","railings", "roof","glazing","walls","columns","beams") def is_roof_floor(floor_key, floor): t = f"{floor_key} {floor.get('name','')}".upper() return any(k in t for k in ("RF","ROOF","屋顶","屋面")) def z_window(category, z, height, floor_key, floor): if category in {"walls","columns","glazing"}: if category == "columns" and is_roof_floor(floor_key, floor): return z, z + min(height, 1.15) return z, z + height if category == "beams": return z + max(height-0.55, 0.1), z + height if category == "roof": return z - 0.35, z + 0.08 if category == "railings":return z + 0.05, z + min(1.20, height) if category == "doors": return z + 0.02, z + min(2.30, height) if category in {"floor_lines","detail_lines"}: return z + 0.03, z + 0.09 if category == "grid": return z + 0.01, z + 0.04 return z + 0.03, z + min(0.12, height) # 12-triangle box from 8 corner verts _BOX_TRIS = np.array([ [0,1,2],[0,2,3], # bottom [4,6,5],[4,7,6], # top [0,4,5],[0,5,1], [1,5,6],[1,6,2], [2,6,7],[2,7,3], [3,7,4],[3,4,0], ], dtype=np.int64) def segment_box_verts(seg, z0, z1): x1,y1 = seg["start"]; x2,y2 = seg["end"] dx,dy = x2-x1, y2-y1 L = math.hypot(dx,dy) if L <= 1e-7: return None hw = max(float(seg.get("width",0.1)), 0.005)/2.0 nx,ny = -dy/L*hw, dx/L*hw z0 = float(seg.get("_z0", z0)); z1 = float(seg.get("_z1", z1)) return np.array([ (x1+nx,y1+ny,z0),(x2+nx,y2+ny,z0),(x2-nx,y2-ny,z0),(x1-nx,y1-ny,z0), (x1+nx,y1+ny,z1),(x2+nx,y2+ny,z1),(x2-nx,y2-ny,z1),(x1-nx,y1-ny,z1), ], dtype=np.float64) def mesh_from_segments(segments, z0, z1): V=[]; F=[]; base=0 for seg in segments: v = segment_box_verts(seg, z0, z1) if v is None: continue V.append(v); F.append(_BOX_TRIS+base); base+=8 if not V: return None return trimesh.Trimesh(vertices=np.vstack(V), faces=np.vstack(F), process=False) _POLY_FAILS = {"n": 0} def mesh_from_polygons(polygons, z0, z1): parts=[] for coords in polygons: pts=[(float(x),float(y)) for x,y in coords] if len(pts)>=2 and pts[0]==pts[-1]: pts=pts[:-1] if len(pts)<3: continue try: poly=Polygon(pts) if not poly.is_valid: poly=poly.buffer(0) if poly.is_empty or poly.area<=0: continue m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4)) m.apply_translation((0,0,z0)) parts.append(m) except Exception as exc: # Silent drops here erase slabs/caps/roofs wholesale (e.g. trimesh # cannot triangulate without mapbox_earcut/manifold3d installed). _POLY_FAILS["n"] += 1 if _POLY_FAILS["n"] <= 3: print(f"WARNING mesh_from_polygons failed ({exc}); slabs/caps/roofs may be " "missing - pip install mapbox_earcut", file=sys.stderr) continue if not parts: return None return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0] def hex_rgba(hex_color, alpha): h=hex_color.lstrip("#") return [int(h[0:2],16)/255, int(h[2:4],16)/255, int(h[4:6],16)/255, alpha] ALPHA={"slab":0.72,"roof":0.95,"glazing":0.38,"floor_lines":0.95,"grid":0.95, "detail_lines":0.82,"doors":0.90} def merge_collinear(segs, angle_tol_deg=6.0, offset_tol=0.30, gap_tol=3.6): """Merge collinear, near-touching segments into continuous spans (for glazing bands).""" groups={} keep=[] for s in segs: a=s["start"]; b=s["end"] dx=b[0]-a[0]; dy=b[1]-a[1]; L=math.hypot(dx,dy) if L<1e-6: keep.append(s); continue ang=math.atan2(dy,dx)%math.pi akey=round(ang/math.radians(angle_tol_deg)) nx,ny=-dy/L,dx/L off=a[0]*nx+a[1]*ny okey=round(off/offset_tol) groups.setdefault((akey,okey),[]).append((a,b,nx,ny,float(s.get("width",0.06)),s.get("layer",""),math.radians(angle_tol_deg)*akey)) out=list(keep) for (akey,okey),items in groups.items(): a0,b0,nx,ny,w,layer,_=items[0] dirx,diry=-ny,nx offv=a0[0]*nx+a0[1]*ny intervals=[] for (a,b,*_r) in items: t0=a[0]*dirx+a[1]*diry; t1=b[0]*dirx+b[1]*diry intervals.append([min(t0,t1),max(t0,t1)]) intervals.sort() merged=[intervals[0][:]] for lo,hi in intervals[1:]: if lo<=merged[-1][1]+gap_tol: merged[-1][1]=max(merged[-1][1],hi) else: merged.append([lo,hi]) for lo,hi in merged: p0=(offv*nx+lo*dirx, offv*ny+lo*diry) p1=(offv*nx+hi*dirx, offv*ny+hi*diry) out.append({"start":[p0[0],p0[1]],"end":[p1[0],p1[1]],"width":w,"layer":layer,"source_type":"merged"}) return out def extend_shared_wall_ends(segments, tol=1e-3): """Extend wall ends that meet another wall's endpoint by half their own width. Flat-capped rectangles stop exactly at the endpoint, so an L-corner leaves a w/2 x w/2 notch that even a union keeps open. Extending only SHARED ends makes the corner rectangles overlap (union -> clean square corner) while free ends (door/window openings) stay flat. T-joints need nothing: the ending wall already reaches the crossing wall's centerline. """ from collections import Counter pts=[] for s in segments: pts.append((float(s["start"][0]), float(s["start"][1]))) pts.append((float(s["end"][0]), float(s["end"][1]))) scale=1.0/max(tol,1e-9) buckets=Counter((round(x*scale), round(y*scale)) for x,y in pts) def shared(p): cx,cy=round(p[0]*scale), round(p[1]*scale) return sum(buckets.get((gx,gy),0) for gx in (cx-1,cx,cx+1) for gy in (cy-1,cy,cy+1))>=2 out=[] for s in segments: a=[float(s["start"][0]), float(s["start"][1])] b=[float(s["end"][0]), float(s["end"][1])] dx,dy=b[0]-a[0],b[1]-a[1]; L=math.hypot(dx,dy) if L<1e-7: out.append(s); continue ux,uy=dx/L,dy/L half=max(float(s.get("width",0.1)),0.005)/2.0 item=dict(s) if shared((a[0],a[1])): a=[a[0]-ux*half, a[1]-uy*half] if shared((b[0],b[1])): b=[b[0]+ux*half, b[1]+uy*half] item["start"]=a; item["end"]=b out.append(item) return out def merged_wall_polygons(segments): """Union per-segment wall rectangles into continuous solids (shapely). Shared endpoints are pre-extended (see extend_shared_wall_ends), then each segment becomes a flat-capped rectangle (LineString.buffer, cap_style=2, half its own width) and unary_union removes corner seams and z-fighting at junctions. Returns shapely Polygons (holes preserved for courtyard walls). Enabled via config {"merge_wall_solids": true}. """ from shapely.geometry import LineString from shapely.ops import unary_union rects=[] for s in extend_shared_wall_ends(segments): a=s["start"]; b=s["end"] if math.hypot(b[0]-a[0], b[1]-a[1])<1e-7: continue w=max(float(s.get("width",0.1)), 0.005) rects.append(LineString([tuple(a), tuple(b)]).buffer(w/2.0, cap_style=2)) if not rects: return [] union=unary_union(rects) geoms=[union] if union.geom_type=="Polygon" else list(getattr(union,"geoms",[])) # simplify(0) drops the collinear vertices GEOS noding leaves on straight edges return [g.simplify(0) for g in geoms if g.geom_type=="Polygon" and g.area>1e-6] def mesh_from_shapely(polys, z0, z1): """Extrude shapely Polygons directly (keeps interior holes, unlike mesh_from_polygons).""" parts=[] for poly in polys: try: m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4)) m.apply_translation((0,0,z0)) parts.append(m) except Exception as exc: _POLY_FAILS["n"] += 1 if _POLY_FAILS["n"] <= 3: print(f"WARNING mesh_from_polygons failed ({exc}); merged walls may be " "missing - pip install mapbox_earcut", file=sys.stderr) continue if not parts: return None return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0] def glazing_mullion_segments(bands, z0, z1, panel_w=1.5, profile=0.06, depth=0.10): """Curtain-wall panel grid over merged glazing bands. Emits pseudo wall segments (thin box profiles, walls material via the __walls node): vertical mullions evenly spaced ~panel_w along each band (posts at both ends included) plus a horizontal transom at the band's bottom and top floor lines (carrying _z0/_z1). The glass pane itself stays. Config {"glazing_mullions": true}, pitch {"glazing_panel_w": 1.5}. """ out=[] for s in bands: a=s["start"]; b=s["end"] dx,dy=b[0]-a[0],b[1]-a[1]; L=math.hypot(dx,dy) if L0: gs.append(g) except Exception: pass return unary_union(gs) if gs else None def _shapely_to_polys(geom, min_area=2.0): res=[] if geom is None or geom.is_empty: return res geoms=[geom] if geom.geom_type=="Polygon" else list(getattr(geom,"geoms",[])) for g in geoms: if g.geom_type!="Polygon" or g.area0.8: continue upper.extend(ot.get("footprint",{}).get("polygons",[])) own_u=_shapely_union(own_polys) cfg=spec.get("source",{}).get("config",{}) # 1.3 suits colonnade buildings (A208); ordinary facades want ~0.1 or the # cap ring reads as a slab overhanging every floor. Config: cap_buffer. buf=float(cfg.get("cap_buffer",1.3)) if not upper: # top of a basement stack -> cap the WHOLE footprint (ground / podium deck over parking) if grp=="BASE" and own_u is not None: return _shapely_to_polys(own_u.buffer(0.5), min_area=3.0) return [] # above-ground top handled by generated roof caps up_u=_shapely_union(upper) if own_u is None or up_u is None: return [] try: ring=own_u.buffer(buf).difference(up_u.buffer(0.05)) except Exception: return [] return _shapely_to_polys(ring, min_area=3.0) def floor_group(fk): if fk.startswith("AUX_"): return "AUX" if fk in {"B1","B1M"}: return "BASE" return "MAIN" def _pt_seg_dist(p, a, b): px,py=p; ax,ay=a; bx,by=b dx,dy=bx-ax,by-ay L=dx*dx+dy*dy if L<=1e-12: return math.hypot(px-ax,py-ay) t=max(0.0,min(1.0,((px-ax)*dx+(py-ay)*dy)/L)) return math.hypot(px-(ax+t*dx), py-(ay+t*dy)) def _pt_in_poly(p, poly): x,y=p; inside=False; n=len(poly) if n<3: return False j=n-1 for i in range(n): xi,yi=float(poly[i][0]),float(poly[i][1]) xj,yj=float(poly[j][0]),float(poly[j][1]) if (yi>y)!=(yj>y): xat=(xj-xi)*(y-yi)/((yj-yi) or 1e-12)+xi if xrtol: continue if r["polygons"] and _near_polys(pt,r["polygons"],sd): return True return False def adjust_columns(segs, fk, fl, spec, cfg, roofs): if not cfg.get("shorten_unsupported_columns",False): return segs flt={str(k) for k in cfg.get("shorten_unsupported_columns_floor_keys",[])} if flt and fk not in flt: return segs z=float(fl["z"]); h=float(fl.get("height",4.2)) sh=min(float(cfg.get("unsupported_column_height",1.2)),h) out=[] for s in segs: a=s["start"]; b=s["end"] mid=((a[0]+b[0])/2.0,(a[1]+b[1])/2.0) it=dict(s) if not column_supported(mid,fk,fl,spec,cfg,roofs): it["_z0"]=z; it["_z1"]=z+sh out.append(it) return out def roof_specs(spec): cfg=spec.get("source",{}).get("config",{}) floors=spec.get("floors",{}) out=[] for r in cfg.get("roof_specs",[]): fk=str(r.get("floor_key")) fl=floors.get(fk) if not fl: continue ffrom=list(r.get("footprint_from",[fk])) polys=[] for k in ffrom: polys.extend(floors.get(k,{}).get("footprint",{}).get("polygons",[])) out.append({"floor_key":fk,"z":float(r.get("z",fl.get("z",0.0))), "thickness":float(r.get("thickness",0.35)),"polygons":polys, "bounds":r.get("bounds") or fl.get("bounds")}) return out def build_scene(spec, categories): cfg=spec.get("source",{}).get("config",{}) use_fp_slab=cfg.get("use_footprint_slabs",False) slab_th=float(cfg.get("slab_thickness",0.25)) cat_defs=spec.get("categories",{}) scene=trimesh.Scene() mats={} def material(cat): if cat in mats: return mats[cat] color=cat_defs.get(cat,{}).get("color","#cccccc") m=trimesh.visual.material.PBRMaterial( name=cat, baseColorFactor=hex_rgba(color, ALPHA.get(cat,1.0)), metallicFactor=0.02, roughnessFactor=0.75, alphaMode=("BLEND" if ALPHA.get(cat,1.0)<1 else "OPAQUE")) mats[cat]=m; return m def add(name, mesh, cat): if mesh is None or mesh.faces.shape[0]==0: return # bake flat normals: unweld so each face has unique verts -> exported NORMAL is per-face tris = mesh.vertices[mesh.faces] v = tris.reshape(-1, 3) f = np.arange(len(v)).reshape(-1, 3) mesh = trimesh.Trimesh(vertices=v, faces=f, process=False) # drop degenerate (near-zero-area) faces so normals never become NaN tri=mesh.vertices[mesh.faces] area=np.linalg.norm(np.cross(tri[:,1]-tri[:,0], tri[:,2]-tri[:,0]), axis=1)*0.5 good=np.isfinite(area) & (area>1e-9) if not good.all(): mesh.update_faces(good); mesh.remove_unreferenced_vertices() if mesh.faces.shape[0]==0: return # convert Z-up -> glTF-standard Y-up: (x,y,z) -> (x, z, -y) mesh.apply_transform(np.array([[1,0,0,0],[0,0,1,0],[0,-1,0,0],[0,0,0,1.0]])) if not np.isfinite(mesh.vertices).all(): return vn=np.array(mesh.vertex_normals, dtype=np.float64) # force + sanitize badrows=~np.isfinite(vn).all(axis=1) if badrows.any(): vn[badrows]=[0.0,1.0,0.0] mesh.vertex_normals=vn try: mesh.visual=trimesh.visual.TextureVisuals(material=material(cat)) except Exception: pass scene.add_geometry(mesh, geom_name=name, node_name=name) want=None if categories in (None,"all") else set(categories) roofs=roof_specs(spec) for fk,fl in spec["floors"].items(): z=float(fl["z"]); h=float(fl.get("height",4.2)) # slab (bottom plate + setback cap ring at this floor's top to cap columns) if want is None or "slab" in want: polys=fl.get("footprint",{}).get("polygons",[]) if use_fp_slab else [] parts=[] if polys: parts.append(mesh_from_polygons(polys, z-slab_th, z)) cap_polys=setback_cap_polys(spec, fk, fl, polys) if cap_polys: parts.append(mesh_from_polygons(cap_polys, z+h-slab_th, z+h)) elif cfg.get("slab_bounds_fallback", True): # Rectangular fallback can fake a full-cover plate on floors # like parapet-only roof plans; disable via config # {"slab_bounds_fallback": false} when footprints are trusted. b=fl["bounds"]; mg=1.2 parts.append(mesh_from_polygons( [[[b[0]-mg,b[1]-mg],[b[2]+mg,b[1]-mg],[b[2]+mg,b[3]+mg],[b[0]-mg,b[3]+mg]]], z-slab_th, z)) parts=[p for p in parts if p is not None] if parts: add(f"{fk}__slab", parts[0] if len(parts)==1 else trimesh.util.concatenate(parts), "slab") segs=fl.get("segments",{}) mullion_mesh=None if cfg.get("glazing_mullions", False) and segs.get("glazing") and (want is None or "walls" in want): gz0,gz1=z_window("glazing",z,h,fk,fl) mullion_mesh=mesh_from_segments( glazing_mullion_segments(merge_collinear(segs["glazing"]), gz0, gz1, panel_w=float(cfg.get("glazing_panel_w",1.5))), gz0, gz1) present=[c for c in CATEGORY_DRAW_ORDER if segs.get(c)] extra=sorted(c for c in segs if c not in CATEGORY_DRAW_ORDER and segs.get(c)) for cat in present+extra: if want is not None and cat not in want: continue z0,z1=z_window(cat,z,h,fk,fl) seglist=segs[cat] if cat=="columns": seglist=adjust_columns(seglist, fk, fl, spec, cfg, roofs) if cat=="glazing": seglist=merge_collinear(seglist) if cat=="walls": wall_mesh=None if cfg.get("merge_wall_solids", False): wall_mesh=mesh_from_shapely(merged_wall_polygons(seglist), z0, z1) if wall_mesh is None: wall_mesh=mesh_from_segments(seglist, z0, z1) if mullion_mesh is not None: parts=[p for p in (wall_mesh, mullion_mesh) if p is not None] wall_mesh=trimesh.util.concatenate(parts) if len(parts)>1 else (parts[0] if parts else None) mullion_mesh=None add(f"{fk}__walls", wall_mesh, "walls") continue add(f"{fk}__{cat}", mesh_from_segments(seglist, z0, z1), cat) if mullion_mesh is not None: # glazing-only floor: the panel grid still needs a walls node add(f"{fk}__walls", mullion_mesh, "walls") # generated roofs if want is None or "roof" in want: for r in roof_specs(spec): z=r["z"]; th=r["thickness"] if r["polygons"]: add(f"{r['floor_key']}__roof", mesh_from_polygons(r["polygons"], z-th, z+0.08), "roof") elif r["bounds"]: b=r["bounds"] add(f"{r['floor_key']}__roof", mesh_from_polygons( [[[b[0],b[1]],[b[2],b[1]],[b[2],b[3]],[b[0],b[3]]]], z-th, z+0.08), "roof") return scene def scene_bounds(spec): bx=[math.inf,math.inf,-math.inf,-math.inf]; maxz=0.0 for fl in spec["floors"].values(): b=fl["bounds"] bx[0]=min(bx[0],b[0]); bx[1]=min(bx[1],b[1]) bx[2]=max(bx[2],b[2]); bx[3]=max(bx[3],b[3]) maxz=max(maxz,float(fl["z"])+float(fl.get("height",4.2))) return bx,maxz def write_metadata(spec, name, out): cfg=spec.get("source",{}).get("config",{}) bx,maxz=scene_bounds(spec) meta={ "project":spec.get("project",{"name":name}), "floors":[{"key":k,"name":f.get("name",k),"z":f.get("z",0),"height":f.get("height",4.2)} for k,f in spec["floors"].items()], "categories":spec.get("categories",{}), "viewer_defaults":{"disabled_categories":list(cfg.get("default_disabled_categories",[]))}, "bounds":{"xy":bx,"max_z":maxz}, "files":{"glb":f"{name}.glb"}, } Path(out).write_text(json.dumps(meta,ensure_ascii=False,indent=2),encoding="utf-8") def main(): ap=argparse.ArgumentParser() ap.add_argument("--spec",required=True) ap.add_argument("--out",required=True) ap.add_argument("--metadata-out") ap.add_argument("--name",default="model") ap.add_argument("--categories",default="all",help="'all' or comma list incl. slab") a=ap.parse_args() spec=json.loads(Path(a.spec).read_text(encoding="utf-8")) cats = None if a.categories=="all" else [c.strip() for c in a.categories.split(",") if c.strip()] scene=build_scene(spec,cats) Path(a.out).parent.mkdir(parents=True,exist_ok=True) scene.export(a.out) tris=sum(int(g.faces.shape[0]) for g in scene.geometry.values()) verts=sum(int(g.vertices.shape[0]) for g in scene.geometry.values()) if a.metadata_out: write_metadata(spec,a.name,a.metadata_out) print(json.dumps({"out":a.out,"nodes":len(scene.geometry),"triangles":tris, "vertices":verts,"bytes":Path(a.out).stat().st_size},ensure_ascii=False)) if __name__=="__main__": main()