Sandbox round (Linux): - detect_sheet_frames.py: multi-frame sheet splitter (column AND row layouts), grid-vote per-floor offsets, section-elevation harvesting for storey heights - dwg_dump_json.mjs + dwgjson_to_dxf.py: WASM libredwg DWG->DXF fallback (blocks/INSERT preserved, ATTRIB->TEXT so axis labels survive) - assemble_campus.py: manifest-driven campus assembly with mandatory neighbour-gap gate (overlap = exit 3, 0.1-0.3m flagged as expansion joints) - site_context_from_dump.py: site-context floors (ground/roads/parking/ fence/trees/context massings) from site-plan dumps - write_offline_viewer.py + assets/offline-viewer-libs/: fully-offline single-file viewer (vendored three r147 + pako, gzip-embedded GLB) - audit: clip-scoped coverage figures; report: multi_frame_sheet warning; audit gate floors_aligned catches the diagonal-staircase failure mode Mac round: - build_blender_showcase.py now honors slab_bounds_fallback and prefers footprint polygons for generated roofs (bounds rects made roof plates jut past the facade and buried campuses under full-extent slabs); contract now matches spec_to_glb.py exactly - merge_wall_solids (default off) in BOTH backends: shapely union in spec_to_glb.py, native delaunay_2d_cdt union in Blender; endpoint-shared wall ends pre-extended w/2 so L-corners close seamlessly (flat caps leave a notch a union alone cannot fill) while openings stay flat - glazing_mullions (default off): curtain-wall panel grid (verticals every glazing_panel_w + floor-line transoms) as pseudo wall segments in the <floor>__walls node; glass pane kept - build_showcase_variants.py keeps source_file=="site" floors intact in all variants (roads/trees live on filtered categories) - web template: instanced low-poly trees from metadata site_trees, grade-level shadow catcher (was at basement depth), data-URI favicon - tools/compress.mjs deps pinned (package.json); 15MB campus GLB -> 0.57MB - tests: 24 -> 52 checks (wall union, mullions, byte-identical defaults) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
912 lines
34 KiB
Python
Executable File
912 lines
34 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Generate a Blender scene, GLB, preview PNG, and model metadata from building_spec.json."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import math
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
CATEGORY_DRAW_ORDER = (
|
|
"grid",
|
|
"floor_lines",
|
|
"detail_lines",
|
|
"doors",
|
|
"railings",
|
|
"roof",
|
|
"glazing",
|
|
"walls",
|
|
"columns",
|
|
"beams",
|
|
)
|
|
|
|
DEFAULT_CATEGORY_COLORS = {
|
|
"slab": "#c8ccc2",
|
|
"roof": "#b8ae98",
|
|
"walls": "#d4cbb8",
|
|
"glazing": "#79b8c9",
|
|
"columns": "#f58a1f",
|
|
"beams": "#1f66c2",
|
|
"railings": "#6f746d",
|
|
"doors": "#8a6a45",
|
|
"detail_lines": "#8c9088",
|
|
"floor_lines": "#18a058",
|
|
"grid": "#20242a",
|
|
}
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
argv = sys.argv
|
|
if "--" in argv:
|
|
argv = argv[argv.index("--") + 1 :]
|
|
else:
|
|
argv = []
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--spec", required=True, help="Path to building_spec.json")
|
|
parser.add_argument("--out-dir", required=True, help="Output folder")
|
|
parser.add_argument("--name", default="cad_building_showcase", help="Base output file name")
|
|
parser.add_argument("--render", action="store_true", default=True, help="Render preview PNG")
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def clear_scene(bpy):
|
|
bpy.ops.object.select_all(action="SELECT")
|
|
bpy.ops.object.delete()
|
|
for datablocks in (
|
|
bpy.data.meshes,
|
|
bpy.data.curves,
|
|
bpy.data.materials,
|
|
bpy.data.images,
|
|
bpy.data.lights,
|
|
bpy.data.cameras,
|
|
):
|
|
for item in list(datablocks):
|
|
if item.users == 0:
|
|
datablocks.remove(item)
|
|
|
|
|
|
def make_material(bpy, name: str, color_hex: str, alpha: float = 1.0, roughness: float = 0.75):
|
|
color_hex = color_hex.lstrip("#")
|
|
r = int(color_hex[0:2], 16) / 255.0
|
|
g = int(color_hex[2:4], 16) / 255.0
|
|
b = int(color_hex[4:6], 16) / 255.0
|
|
color = (r, g, b, alpha)
|
|
mat = bpy.data.materials.new(name)
|
|
mat.diffuse_color = color
|
|
mat.use_nodes = True
|
|
bsdf = mat.node_tree.nodes.get("Principled BSDF")
|
|
if bsdf:
|
|
bsdf.inputs["Base Color"].default_value = color
|
|
bsdf.inputs["Roughness"].default_value = roughness
|
|
if "Alpha" in bsdf.inputs:
|
|
bsdf.inputs["Alpha"].default_value = alpha
|
|
if alpha < 1.0:
|
|
mat.blend_method = "BLEND"
|
|
mat.show_transparent_back = True
|
|
return mat
|
|
|
|
|
|
def create_box_mesh(bpy, name: str, boxes: list[list[float]], material, floor_key: str, category: str):
|
|
verts = []
|
|
faces = []
|
|
for box in boxes:
|
|
x1, y1, x2, y2, z0, z1 = box
|
|
idx = len(verts)
|
|
verts.extend(
|
|
[
|
|
(x1, y1, z0),
|
|
(x2, y1, z0),
|
|
(x2, y2, z0),
|
|
(x1, y2, z0),
|
|
(x1, y1, z1),
|
|
(x2, y1, z1),
|
|
(x2, y2, z1),
|
|
(x1, y2, z1),
|
|
]
|
|
)
|
|
faces.extend(
|
|
[
|
|
(idx + 0, idx + 1, idx + 2, idx + 3),
|
|
(idx + 4, idx + 7, idx + 6, idx + 5),
|
|
(idx + 0, idx + 4, idx + 5, idx + 1),
|
|
(idx + 1, idx + 5, idx + 6, idx + 2),
|
|
(idx + 2, idx + 6, idx + 7, idx + 3),
|
|
(idx + 3, idx + 7, idx + 4, idx + 0),
|
|
]
|
|
)
|
|
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
|
mesh.from_pydata(verts, [], faces)
|
|
mesh.update()
|
|
mesh.validate(verbose=False) # drop degenerate faces so exported normals never become NaN
|
|
obj = bpy.data.objects.new(name, mesh)
|
|
bpy.context.collection.objects.link(obj)
|
|
obj.data.materials.append(material)
|
|
obj["floor"] = floor_key
|
|
obj["category"] = category
|
|
return obj
|
|
|
|
|
|
def clean_polygon_points(coords: list[list[float]]) -> list[tuple[float, float]]:
|
|
points = [(float(x), float(y)) for x, y in coords]
|
|
if len(points) > 1 and points[0] == points[-1]:
|
|
points = points[:-1]
|
|
cleaned = []
|
|
for point in points:
|
|
if not cleaned or point != cleaned[-1]:
|
|
cleaned.append(point)
|
|
return cleaned
|
|
|
|
|
|
def create_polygon_prism_mesh(
|
|
bpy,
|
|
name: str,
|
|
polygons: list[list[list[float]]],
|
|
z0: float,
|
|
z1: float,
|
|
material,
|
|
floor_key: str,
|
|
category: str,
|
|
):
|
|
from mathutils import Vector
|
|
from mathutils.geometry import tessellate_polygon
|
|
|
|
verts = []
|
|
faces = []
|
|
for coords in polygons:
|
|
points = clean_polygon_points(coords)
|
|
if len(points) < 3:
|
|
continue
|
|
base = len(verts)
|
|
verts.extend([(x, y, z0) for x, y in points])
|
|
verts.extend([(x, y, z1) for x, y in points])
|
|
n = len(points)
|
|
try:
|
|
triangles = tessellate_polygon([[Vector((x, y, 0.0)) for x, y in points]])
|
|
except Exception:
|
|
triangles = []
|
|
for triangle in triangles:
|
|
faces.append(tuple(base + n + index for index in triangle))
|
|
faces.append(tuple(base + index for index in reversed(triangle)))
|
|
for index in range(n):
|
|
next_index = (index + 1) % n
|
|
faces.append((base + index, base + next_index, base + n + next_index, base + n + index))
|
|
if not verts or not faces:
|
|
return None
|
|
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
|
mesh.from_pydata(verts, [], faces)
|
|
mesh.update()
|
|
mesh.validate(verbose=False) # drop degenerate faces so exported normals never become NaN
|
|
obj = bpy.data.objects.new(name, mesh)
|
|
bpy.context.collection.objects.link(obj)
|
|
obj.data.materials.append(material)
|
|
obj["floor"] = floor_key
|
|
obj["category"] = category
|
|
return obj
|
|
|
|
|
|
def segment_prism(segment: dict, z0: float, z1: float):
|
|
x1, y1 = segment["start"]
|
|
x2, y2 = segment["end"]
|
|
dx = x2 - x1
|
|
dy = y2 - y1
|
|
length = math.hypot(dx, dy)
|
|
if length <= 1e-7:
|
|
return None
|
|
half_width = max(float(segment.get("width", 0.1)), 0.005) / 2.0
|
|
nx = -dy / length * half_width
|
|
ny = dx / length * half_width
|
|
return [
|
|
(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),
|
|
]
|
|
|
|
|
|
def create_segment_mesh(bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str):
|
|
verts = []
|
|
faces = []
|
|
for segment in segments:
|
|
segment_z0 = float(segment.get("_z0", z0))
|
|
segment_z1 = float(segment.get("_z1", z1))
|
|
prism = segment_prism(segment, segment_z0, segment_z1)
|
|
if not prism:
|
|
continue
|
|
idx = len(verts)
|
|
verts.extend(prism)
|
|
faces.extend(
|
|
[
|
|
(idx + 0, idx + 1, idx + 2, idx + 3),
|
|
(idx + 4, idx + 7, idx + 6, idx + 5),
|
|
(idx + 0, idx + 4, idx + 5, idx + 1),
|
|
(idx + 1, idx + 5, idx + 6, idx + 2),
|
|
(idx + 2, idx + 6, idx + 7, idx + 3),
|
|
(idx + 3, idx + 7, idx + 4, idx + 0),
|
|
]
|
|
)
|
|
if not verts:
|
|
return None
|
|
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
|
mesh.from_pydata(verts, [], faces)
|
|
mesh.update()
|
|
mesh.validate(verbose=False) # drop degenerate faces so exported normals never become NaN
|
|
obj = bpy.data.objects.new(name, mesh)
|
|
bpy.context.collection.objects.link(obj)
|
|
obj.data.materials.append(material)
|
|
obj["floor"] = floor_key
|
|
obj["category"] = category
|
|
return obj
|
|
|
|
|
|
def extend_shared_wall_ends(segments: list[dict], tol: float = 1e-3) -> list[dict]:
|
|
"""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
|
|
closes the corner while free ends (door/window openings) stay flat.
|
|
Mirror of spec_to_glb.extend_shared_wall_ends.
|
|
"""
|
|
from collections import Counter
|
|
|
|
pts = []
|
|
for segment in segments:
|
|
pts.append((float(segment["start"][0]), float(segment["start"][1])))
|
|
pts.append((float(segment["end"][0]), float(segment["end"][1])))
|
|
scale = 1.0 / max(tol, 1e-9)
|
|
buckets = Counter((round(x * scale), round(y * scale)) for x, y in pts)
|
|
|
|
def shared(point):
|
|
cx, cy = round(point[0] * scale), round(point[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 segment in segments:
|
|
start = [float(segment["start"][0]), float(segment["start"][1])]
|
|
end = [float(segment["end"][0]), float(segment["end"][1])]
|
|
dx, dy = end[0] - start[0], end[1] - start[1]
|
|
length = math.hypot(dx, dy)
|
|
if length < 1e-7:
|
|
out.append(segment)
|
|
continue
|
|
ux, uy = dx / length, dy / length
|
|
half = max(float(segment.get("width", 0.1)), 0.005) / 2.0
|
|
item = dict(segment)
|
|
if shared((start[0], start[1])):
|
|
start = [start[0] - ux * half, start[1] - uy * half]
|
|
if shared((end[0], end[1])):
|
|
end = [end[0] + ux * half, end[1] + uy * half]
|
|
item["start"] = start
|
|
item["end"] = end
|
|
out.append(item)
|
|
return out
|
|
|
|
|
|
def create_merged_wall_mesh(bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str):
|
|
"""Union wall-segment rectangles into one continuous solid (config
|
|
{"merge_wall_solids": true}) — removes corner seams and z-fighting at
|
|
junctions. Blender-native: delaunay_2d_cdt (output_type=1) triangulates the
|
|
union of the overlapping rectangles; edges used by exactly one triangle are
|
|
the union outline and become the side faces. Same visual contract as
|
|
spec_to_glb.py's shapely union, without needing shapely in Blender python.
|
|
"""
|
|
from mathutils import Vector
|
|
from mathutils.geometry import delaunay_2d_cdt
|
|
|
|
points = []
|
|
rects = []
|
|
for segment in extend_shared_wall_ends(segments):
|
|
prism = segment_prism(segment, z0, z1)
|
|
if not prism:
|
|
continue
|
|
idx = len(points)
|
|
points.extend(Vector((vert[0], vert[1])) for vert in prism[:4])
|
|
rects.append((idx, idx + 1, idx + 2, idx + 3))
|
|
if not rects:
|
|
return None
|
|
verts2d, _edges, tris = delaunay_2d_cdt(points, [], rects, 1, 1e-5)[:3]
|
|
if not tris:
|
|
return None
|
|
count = len(verts2d)
|
|
verts = [(v.x, v.y, z0) for v in verts2d] + [(v.x, v.y, z1) for v in verts2d]
|
|
edge_use: dict[tuple[int, int], int] = {}
|
|
for tri in tris:
|
|
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
|
|
key = (min(a, b), max(a, b))
|
|
edge_use[key] = edge_use.get(key, 0) + 1
|
|
faces = [tuple(reversed(tri)) for tri in tris] # bottom, facing down
|
|
faces += [tuple(i + count for i in tri) for tri in tris] # top, facing up
|
|
for tri in tris:
|
|
# CCW triangles keep the interior left of a->b, so (a,b,b',a') faces outward.
|
|
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
|
|
if edge_use[(min(a, b), max(a, b))] == 1:
|
|
faces.append((a, b, b + count, a + count))
|
|
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
|
mesh.from_pydata(verts, [], faces)
|
|
mesh.update()
|
|
mesh.validate(verbose=False)
|
|
obj = bpy.data.objects.new(name, mesh)
|
|
bpy.context.collection.objects.link(obj)
|
|
obj.data.materials.append(material)
|
|
obj["floor"] = floor_key
|
|
obj["category"] = category
|
|
return obj
|
|
|
|
|
|
def glazing_mullion_segments(bands: list[dict], z0: float, z1: float, panel_w: float = 1.5, profile: float = 0.06, depth: float = 0.10) -> list[dict]:
|
|
"""Curtain-wall panel grid over glazing bands (mirror of spec_to_glb).
|
|
|
|
Emits pseudo wall segments (thin box profiles, rendered into the
|
|
<floor>__walls object): vertical mullions evenly spaced ~panel_w per band
|
|
plus a horizontal transom at the band's bottom and top floor lines
|
|
(via _z0/_z1). Config {"glazing_mullions": true, "glazing_panel_w": 1.5}.
|
|
"""
|
|
out = []
|
|
for segment in bands:
|
|
start = segment["start"]
|
|
end = segment["end"]
|
|
dx, dy = end[0] - start[0], end[1] - start[1]
|
|
length = math.hypot(dx, dy)
|
|
if length < max(profile * 2, 0.3):
|
|
continue
|
|
ux, uy = dx / length, dy / length
|
|
panels = max(1, round(length / max(panel_w, 0.2)))
|
|
step = length / panels
|
|
for i in range(panels + 1):
|
|
t = i * step
|
|
cx, cy = start[0] + ux * t, start[1] + uy * t
|
|
out.append({
|
|
"start": [cx - ux * profile / 2.0, cy - uy * profile / 2.0],
|
|
"end": [cx + ux * profile / 2.0, cy + uy * profile / 2.0],
|
|
"width": depth, "layer": segment.get("layer", ""), "source_type": "mullion",
|
|
})
|
|
thickness = 0.08
|
|
for tz0, tz1 in ((z0, z0 + thickness), (z1 - thickness, z1)):
|
|
out.append({
|
|
"start": [float(start[0]), float(start[1])], "end": [float(end[0]), float(end[1])],
|
|
"width": depth, "layer": segment.get("layer", ""), "source_type": "transom",
|
|
"_z0": tz0, "_z1": tz1,
|
|
})
|
|
return out
|
|
|
|
|
|
def create_label(bpy, name: str, body: str, location: tuple[float, float, float], size: float, material):
|
|
curve = bpy.data.curves.new(f"{name}Curve", "FONT")
|
|
curve.body = body
|
|
curve.align_x = "LEFT"
|
|
curve.align_y = "CENTER"
|
|
curve.size = size
|
|
curve.extrude = 0.02
|
|
obj = bpy.data.objects.new(name, curve)
|
|
obj.location = location
|
|
bpy.context.collection.objects.link(obj)
|
|
obj.data.materials.append(material)
|
|
return obj
|
|
|
|
|
|
def is_roof_floor(floor_key: str, floor: dict) -> bool:
|
|
text = f"{floor_key} {floor.get('name', '')}".upper()
|
|
return "RF" in text or "ROOF" in text or "屋顶" in text or "屋面" in text
|
|
|
|
|
|
def z_window_for_category(category: str, z: float, height: float, floor_key: str, floor: dict) -> tuple[float, float]:
|
|
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)
|
|
|
|
|
|
def union_bounds(bounds_list: list[list[float]]) -> list[float] | None:
|
|
bounds = [math.inf, math.inf, -math.inf, -math.inf]
|
|
for item in bounds_list:
|
|
if not item:
|
|
continue
|
|
bounds[0] = min(bounds[0], float(item[0]))
|
|
bounds[1] = min(bounds[1], float(item[1]))
|
|
bounds[2] = max(bounds[2], float(item[2]))
|
|
bounds[3] = max(bounds[3], float(item[3]))
|
|
if not math.isfinite(bounds[0]):
|
|
return None
|
|
return bounds
|
|
|
|
|
|
def bounds_from_floor_keys(spec: dict, floor_keys: list[str]) -> list[float] | None:
|
|
return union_bounds(
|
|
[
|
|
spec.get("floors", {}).get(str(key), {}).get("bounds")
|
|
for key in floor_keys
|
|
if spec.get("floors", {}).get(str(key), {}).get("bounds")
|
|
]
|
|
)
|
|
|
|
|
|
def footprint_polygons_from_floor_keys(spec: dict, floor_keys: list[str]) -> list[list[list[float]]]:
|
|
polygons = []
|
|
for key in floor_keys:
|
|
floor = spec.get("floors", {}).get(str(key))
|
|
if not floor:
|
|
continue
|
|
polygons.extend(floor.get("footprint", {}).get("polygons", []))
|
|
return polygons
|
|
|
|
|
|
def generated_roof_bounds(spec: dict) -> list[dict]:
|
|
config = spec.get("source", {}).get("config", {})
|
|
roofs = []
|
|
for index, roof in enumerate(config.get("roof_specs", []), start=1):
|
|
floor_key = str(roof.get("floor_key") or roof.get("key") or f"ROOF_{index}")
|
|
floor = spec.get("floors", {}).get(floor_key)
|
|
if not floor:
|
|
continue
|
|
bounds_from = list(roof.get("bounds_from", [floor_key]))
|
|
footprint_from = list(roof.get("footprint_from", bounds_from))
|
|
# Footprint polygons take priority over rectangular bounds whenever the
|
|
# source floors carry them (same contract as spec_to_glb.py); a bounds
|
|
# rect for e.g. a PH machine-room roof covers the whole building bbox
|
|
# and reads as a plate jutting past the facade.
|
|
footprint_polygons = footprint_polygons_from_floor_keys(spec, footprint_from)
|
|
bounds = roof.get("bounds") or bounds_from_floor_keys(spec, bounds_from)
|
|
if not bounds:
|
|
bounds = floor.get("bounds")
|
|
if not bounds:
|
|
continue
|
|
margin = float(roof.get("margin", 0.4))
|
|
roofs.append(
|
|
{
|
|
"floor_key": floor_key,
|
|
"z": float(roof.get("z", floor.get("z", 0.0))),
|
|
"bounds": [
|
|
float(bounds[0]) - margin,
|
|
float(bounds[1]) - margin,
|
|
float(bounds[2]) + margin,
|
|
float(bounds[3]) + margin,
|
|
],
|
|
"thickness": float(roof.get("thickness", 0.35)),
|
|
"polygons": footprint_polygons,
|
|
}
|
|
)
|
|
if roofs:
|
|
return roofs
|
|
|
|
for key, floor in spec.get("floors", {}).items():
|
|
if is_roof_floor(key, floor) and floor.get("bounds"):
|
|
roofs.append(
|
|
{
|
|
"floor_key": key,
|
|
"z": float(floor.get("z", 0.0)),
|
|
"bounds": floor["bounds"],
|
|
"thickness": 0.35,
|
|
"polygons": floor.get("footprint", {}).get("polygons", []),
|
|
}
|
|
)
|
|
return roofs
|
|
|
|
|
|
def point_in_bounds(point: tuple[float, float], bounds: list[float], margin: float) -> bool:
|
|
x, y = point
|
|
return bounds[0] - margin <= x <= bounds[2] + margin and bounds[1] - margin <= y <= bounds[3] + margin
|
|
|
|
|
|
def point_in_polygon(point: tuple[float, float], polygon: list[list[float]]) -> bool:
|
|
x, y = point
|
|
inside = False
|
|
if len(polygon) < 3:
|
|
return False
|
|
j = len(polygon) - 1
|
|
for i, current in enumerate(polygon):
|
|
xi, yi = float(current[0]), float(current[1])
|
|
xj, yj = float(polygon[j][0]), float(polygon[j][1])
|
|
crosses = (yi > y) != (yj > y)
|
|
if crosses:
|
|
x_at_y = (xj - xi) * (y - yi) / ((yj - yi) or 1e-12) + xi
|
|
if x < x_at_y:
|
|
inside = not inside
|
|
j = i
|
|
return inside
|
|
|
|
|
|
def point_in_or_near_polygons(point: tuple[float, float], polygons: list[list[list[float]]], margin: float) -> bool:
|
|
for polygon in polygons:
|
|
if point_in_polygon(point, polygon):
|
|
return True
|
|
points = clean_polygon_points(polygon)
|
|
for index, start in enumerate(points):
|
|
end = points[(index + 1) % len(points)]
|
|
if point_segment_distance(point, start, end) <= margin:
|
|
return True
|
|
return False
|
|
|
|
|
|
def floor_group(floor_key: str) -> str:
|
|
if floor_key.startswith("AUX_"):
|
|
return "AUX"
|
|
if floor_key in {"B1", "B1M"}:
|
|
return "BASE"
|
|
return "MAIN"
|
|
|
|
|
|
def point_segment_distance(point: tuple[float, float], start: tuple[float, float], end: tuple[float, float]) -> float:
|
|
px, py = point
|
|
ax, ay = start
|
|
bx, by = end
|
|
dx = bx - ax
|
|
dy = by - ay
|
|
length_sq = dx * dx + dy * dy
|
|
if length_sq <= 1e-12:
|
|
return math.hypot(px - ax, py - ay)
|
|
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / length_sq))
|
|
return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
|
|
|
|
|
|
def column_has_upper_support(point: tuple[float, float], floor_key: str, floor: dict, spec: dict, config: dict) -> bool:
|
|
floor_top = float(floor["z"]) + float(floor.get("height", 4.2))
|
|
support_distance = float(config.get("column_support_distance", 1.1))
|
|
z_tolerance = float(config.get("column_support_z_tolerance", 0.65))
|
|
structural_categories = set(config.get("column_support_categories", ["walls", "glazing", "columns", "beams"]))
|
|
require_upper_plate = bool(config.get("column_support_requires_upper_plate", True))
|
|
allow_plate_only = bool(config.get("column_support_allow_plate_only", False))
|
|
group = floor_group(floor_key)
|
|
|
|
for other_key, other in spec.get("floors", {}).items():
|
|
if floor_group(other_key) != group:
|
|
continue
|
|
other_z = float(other.get("z", 0.0))
|
|
if not (floor_top - 0.05 <= other_z <= floor_top + z_tolerance):
|
|
continue
|
|
upper_polygons = other.get("footprint", {}).get("polygons", [])
|
|
if upper_polygons:
|
|
has_upper_plate = point_in_or_near_polygons(point, upper_polygons, support_distance)
|
|
if has_upper_plate and allow_plate_only:
|
|
return True
|
|
if require_upper_plate and not has_upper_plate:
|
|
continue
|
|
for category in structural_categories:
|
|
for segment in other.get("segments", {}).get(category, []):
|
|
distance = point_segment_distance(point, tuple(segment["start"]), tuple(segment["end"]))
|
|
if distance <= support_distance:
|
|
return True
|
|
|
|
roof_z_tolerance = float(config.get("column_roof_support_z_tolerance", 0.65))
|
|
for roof in generated_roof_bounds(spec):
|
|
if floor_group(str(roof["floor_key"])) != group:
|
|
continue
|
|
if abs(float(roof["z"]) - floor_top) > roof_z_tolerance:
|
|
continue
|
|
roof_polygons = roof.get("polygons", [])
|
|
if roof_polygons and point_in_or_near_polygons(point, roof_polygons, support_distance):
|
|
return True
|
|
if not roof_polygons and point_in_bounds(point, roof["bounds"], support_distance):
|
|
return True
|
|
return False
|
|
|
|
|
|
def adjusted_column_segments(segments: list[dict], floor_key: str, floor: dict, spec: dict) -> list[dict]:
|
|
config = spec.get("source", {}).get("config", {})
|
|
if not config.get("shorten_unsupported_columns", False):
|
|
return segments
|
|
floor_filter = {str(key) for key in config.get("shorten_unsupported_columns_floor_keys", [])}
|
|
if floor_filter and floor_key not in floor_filter:
|
|
return segments
|
|
z = float(floor["z"])
|
|
height = float(floor.get("height", 4.2))
|
|
short_height = min(float(config.get("unsupported_column_height", 1.2)), height)
|
|
adjusted = []
|
|
for segment in segments:
|
|
start = segment["start"]
|
|
end = segment["end"]
|
|
midpoint = ((start[0] + end[0]) / 2.0, (start[1] + end[1]) / 2.0)
|
|
item = dict(segment)
|
|
if not column_has_upper_support(midpoint, floor_key, floor, spec, config):
|
|
item["_z0"] = z
|
|
item["_z1"] = z + short_height
|
|
adjusted.append(item)
|
|
return adjusted
|
|
|
|
|
|
def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], spec: dict):
|
|
z = float(floor["z"])
|
|
height = float(floor.get("height", 4.2))
|
|
config = spec.get("source", {}).get("config", {})
|
|
bounds = floor["bounds"]
|
|
margin = 1.2
|
|
slab_thickness = float(floor.get("slab_thickness", config.get("slab_thickness", 0.25)))
|
|
slab_box = [
|
|
bounds[0] - margin,
|
|
bounds[1] - margin,
|
|
bounds[2] + margin,
|
|
bounds[3] + margin,
|
|
z - slab_thickness,
|
|
z,
|
|
]
|
|
footprint = floor.get("footprint", {})
|
|
footprint_polygons = footprint.get("polygons", []) if config.get("use_footprint_slabs", False) else []
|
|
if footprint_polygons:
|
|
create_polygon_prism_mesh(
|
|
bpy,
|
|
f"{floor_key}__slab",
|
|
footprint_polygons,
|
|
z - slab_thickness,
|
|
z,
|
|
materials["slab"],
|
|
floor_key,
|
|
"slab",
|
|
)
|
|
elif config.get("slab_bounds_fallback", True):
|
|
# Rectangular fallback can fake a full-cover plate on floors like
|
|
# parapet-only roof plans or campus context floors (roads/fence/trees);
|
|
# disable via config {"slab_bounds_fallback": false} when footprints
|
|
# are trusted (same contract as spec_to_glb.py).
|
|
create_box_mesh(bpy, f"{floor_key}__slab", [slab_box], materials["slab"], floor_key, "slab")
|
|
# Cap slabs close the tops of columns at setbacks and over basement parking
|
|
# (computed by derive_showcase_spec.py and stored as floor["caps"]). They share
|
|
# the slab category; Blender de-dups the object name and the Web viewer strips the suffix.
|
|
for cap in floor.get("caps", []):
|
|
cap_polys = cap.get("polygons", [])
|
|
if not cap_polys:
|
|
continue
|
|
cap_z = float(cap.get("z", z + height))
|
|
create_polygon_prism_mesh(
|
|
bpy,
|
|
f"{floor_key}__slab",
|
|
cap_polys,
|
|
cap_z - slab_thickness,
|
|
cap_z,
|
|
materials["slab"],
|
|
floor_key,
|
|
"slab",
|
|
)
|
|
floor_segments = floor.get("segments", {})
|
|
mullion_segments: list[dict] = []
|
|
if config.get("glazing_mullions", False) and floor_segments.get("glazing"):
|
|
gz0, gz1 = z_window_for_category("glazing", z, height, floor_key, floor)
|
|
mullion_segments = glazing_mullion_segments(
|
|
floor_segments["glazing"], gz0, gz1, panel_w=float(config.get("glazing_panel_w", 1.5)),
|
|
)
|
|
known = [category for category in CATEGORY_DRAW_ORDER if floor_segments.get(category)]
|
|
extra = sorted(category for category in floor_segments if category not in CATEGORY_DRAW_ORDER and floor_segments.get(category))
|
|
if mullion_segments and "walls" not in known:
|
|
known.append("walls") # glazing-only floor still needs a walls object for the grid
|
|
for category in known + extra:
|
|
segments = floor.get("segments", {}).get(category, [])
|
|
if not segments and category != "walls":
|
|
continue
|
|
if category == "columns":
|
|
segments = adjusted_column_segments(segments, floor_key, floor, spec)
|
|
z0, z1 = z_window_for_category(category, z, height, floor_key, floor)
|
|
if category == "walls" and config.get("merge_wall_solids", False) and segments:
|
|
merged = create_merged_wall_mesh(
|
|
bpy, f"{floor_key}__walls", segments, z0, z1, materials[category], floor_key, category,
|
|
)
|
|
if merged is not None:
|
|
segments = [] # walls handled; mullions (if any) get their own pass below
|
|
if category == "walls":
|
|
segments = list(segments) + mullion_segments
|
|
mullion_segments = []
|
|
if not segments:
|
|
continue
|
|
create_segment_mesh(
|
|
bpy,
|
|
f"{floor_key}__{category}",
|
|
segments,
|
|
z0,
|
|
z1,
|
|
materials[category],
|
|
floor_key,
|
|
category,
|
|
)
|
|
if config.get("show_floor_labels", False):
|
|
create_label(
|
|
bpy,
|
|
f"{floor_key}__label",
|
|
floor.get("name", floor_key),
|
|
(bounds[0], bounds[3] + 2.0, z + 0.08),
|
|
1.8,
|
|
materials["text"],
|
|
)
|
|
|
|
|
|
def scene_bounds(spec: dict) -> tuple[list[float], float]:
|
|
bounds = [math.inf, math.inf, -math.inf, -math.inf]
|
|
max_z = 0.0
|
|
for floor in spec["floors"].values():
|
|
b = floor["bounds"]
|
|
bounds[0] = min(bounds[0], b[0])
|
|
bounds[1] = min(bounds[1], b[1])
|
|
bounds[2] = max(bounds[2], b[2])
|
|
bounds[3] = max(bounds[3], b[3])
|
|
max_z = max(max_z, float(floor["z"]) + float(floor.get("height", 4.2)))
|
|
if not math.isfinite(bounds[0]):
|
|
bounds = [0, 0, 1, 1]
|
|
return bounds, max_z
|
|
|
|
|
|
def add_generated_roofs(bpy, spec: dict, materials: dict[str, object]):
|
|
for roof in generated_roof_bounds(spec):
|
|
bounds = roof["bounds"]
|
|
z = float(roof["z"])
|
|
thickness = float(roof["thickness"])
|
|
polygons = roof.get("polygons", [])
|
|
if polygons:
|
|
create_polygon_prism_mesh(
|
|
bpy,
|
|
f"{roof['floor_key']}__roof",
|
|
polygons,
|
|
z - thickness,
|
|
z + 0.08,
|
|
materials["roof"],
|
|
str(roof["floor_key"]),
|
|
"roof",
|
|
)
|
|
else:
|
|
box = [bounds[0], bounds[1], bounds[2], bounds[3], z - thickness, z + 0.08]
|
|
create_box_mesh(
|
|
bpy,
|
|
f"{roof['floor_key']}__roof",
|
|
[box],
|
|
materials["roof"],
|
|
str(roof["floor_key"]),
|
|
"roof",
|
|
)
|
|
|
|
|
|
def setup_scene(bpy, spec: dict):
|
|
from mathutils import Vector
|
|
|
|
bpy.context.scene.unit_settings.system = "METRIC"
|
|
bpy.context.scene.unit_settings.scale_length = 1.0
|
|
try:
|
|
bpy.context.scene.render.engine = "BLENDER_EEVEE"
|
|
except TypeError:
|
|
pass
|
|
if bpy.context.scene.world:
|
|
bpy.context.scene.world.color = (0.78, 0.82, 0.86)
|
|
|
|
category_defs = dict(spec.get("categories", {}))
|
|
for floor in spec.get("floors", {}).values():
|
|
for key in floor.get("segments", {}):
|
|
category_defs.setdefault(key, {"color": DEFAULT_CATEGORY_COLORS.get(key, "#cccccc")})
|
|
for key, color in DEFAULT_CATEGORY_COLORS.items():
|
|
category_defs.setdefault(key, {"color": color})
|
|
|
|
alpha_by_category = {
|
|
"slab": 0.72,
|
|
"roof": 0.95,
|
|
"glazing": 0.38,
|
|
"floor_lines": 0.95,
|
|
"grid": 0.95,
|
|
"detail_lines": 0.82,
|
|
"doors": 0.90,
|
|
}
|
|
materials = {
|
|
key: make_material(
|
|
bpy,
|
|
key.replace("_", " "),
|
|
category_defs.get(key, {}).get("color", DEFAULT_CATEGORY_COLORS.get(key, "#cccccc")),
|
|
alpha_by_category.get(key, 1.0),
|
|
)
|
|
for key in category_defs
|
|
}
|
|
materials["text"] = make_material(bpy, "text", "#111111", 1.0)
|
|
|
|
for floor_key, floor in spec["floors"].items():
|
|
add_floor(bpy, floor_key, floor, materials, spec)
|
|
add_generated_roofs(bpy, spec, materials)
|
|
|
|
bounds, max_z = scene_bounds(spec)
|
|
cx = (bounds[0] + bounds[2]) / 2.0
|
|
cy = (bounds[1] + bounds[3]) / 2.0
|
|
sx = max(bounds[2] - bounds[0], 1.0)
|
|
sy = max(bounds[3] - bounds[1], 1.0)
|
|
|
|
bpy.ops.object.light_add(type="SUN", location=(0, 0, max_z + 30))
|
|
sun = bpy.context.object
|
|
sun.name = "Sun"
|
|
sun.data.energy = 2.2
|
|
sun.rotation_euler = (math.radians(45), 0, math.radians(35))
|
|
|
|
bpy.ops.object.light_add(type="AREA", location=(cx - sx * 0.25, cy - sy * 0.7, max_z + 40))
|
|
area = bpy.context.object
|
|
area.name = "Large softbox"
|
|
area.data.energy = 600
|
|
area.data.size = max(sx, sy) * 0.55
|
|
|
|
cam_distance = max(sx, sy, max_z) * 0.95
|
|
bpy.ops.object.camera_add(location=(cx - cam_distance, cy - cam_distance * 0.85, max_z + cam_distance * 0.65))
|
|
camera = bpy.context.object
|
|
camera.name = "Camera - showcase overview"
|
|
direction = Vector((cx, cy, max_z * 0.35)) - camera.location
|
|
camera.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
|
|
camera.data.type = "ORTHO"
|
|
camera.data.ortho_scale = max(sx, sy) * 1.18
|
|
bpy.context.scene.camera = camera
|
|
|
|
bpy.context.scene.render.resolution_x = 1800
|
|
bpy.context.scene.render.resolution_y = 1200
|
|
bpy.context.scene.view_settings.view_transform = "Standard"
|
|
bpy.context.scene.view_settings.look = "Medium High Contrast"
|
|
return bounds, max_z
|
|
|
|
|
|
def metadata(spec: dict, bounds: list[float], max_z: float, name: str) -> dict:
|
|
config = spec.get("source", {}).get("config", {})
|
|
return {
|
|
"project": spec.get("project", {"name": name}),
|
|
"floors": [
|
|
{"key": key, "name": floor.get("name", key), "z": floor.get("z", 0), "height": floor.get("height", 4.2)}
|
|
for key, floor in spec.get("floors", {}).items()
|
|
],
|
|
"categories": spec.get("categories", {}),
|
|
"viewer_defaults": {
|
|
"disabled_categories": list(config.get("default_disabled_categories", [])),
|
|
},
|
|
"bounds": {"xy": bounds, "max_z": max_z},
|
|
"files": {"glb": f"{name}.glb", "blend": f"{name}.blend", "preview": f"{name}.png"},
|
|
}
|
|
|
|
|
|
def main() -> int:
|
|
args = parse_args()
|
|
try:
|
|
import bpy # type: ignore
|
|
except ImportError as exc:
|
|
raise SystemExit("Run this script with Blender: blender -b --python build_blender_showcase.py -- --spec ...") from exc
|
|
|
|
spec_path = Path(args.spec)
|
|
out_dir = Path(args.out_dir)
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
|
clear_scene(bpy)
|
|
bounds, max_z = setup_scene(bpy, spec)
|
|
|
|
blend_path = out_dir / f"{args.name}.blend"
|
|
glb_path = out_dir / f"{args.name}.glb"
|
|
png_path = out_dir / f"{args.name}.png"
|
|
metadata_path = out_dir / "model_metadata.json"
|
|
bpy.ops.wm.save_as_mainfile(filepath=str(blend_path))
|
|
# Draco compression keeps the Web GLB lightweight (typically -85~92% size).
|
|
# The Web template registers a DRACOLoader to decode it; keep both in sync.
|
|
bpy.ops.export_scene.gltf(
|
|
filepath=str(glb_path),
|
|
export_format="GLB",
|
|
export_draco_mesh_compression_enable=True,
|
|
export_draco_mesh_compression_level=6,
|
|
export_draco_position_quantization=14,
|
|
export_draco_normal_quantization=10,
|
|
export_draco_generic_quantization=12,
|
|
)
|
|
if args.render:
|
|
bpy.context.scene.render.filepath = str(png_path)
|
|
bpy.ops.render.render(write_still=True)
|
|
metadata_path.write_text(json.dumps(metadata(spec, bounds, max_z, args.name), ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print(json.dumps({
|
|
"blend": str(blend_path),
|
|
"glb": str(glb_path),
|
|
"png": str(png_path),
|
|
"metadata": str(metadata_path),
|
|
"objects": len(bpy.data.objects),
|
|
}, ensure_ascii=False))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|