Cut 13b: fix multi-edge WallBay enclosure, wall_h<1.2 pancakes, and LOD2 pitched roofs

This commit is contained in:
Meta Vens 2026-12-06 06:08:34 +01:00
commit b279b6d54c

View file

@ -22,7 +22,7 @@ import zlib
import numpy as np
import pygltflib
import shapely
from shapely.geometry import MultiPolygon, Polygon, box
from shapely.geometry import LineString, MultiPolygon, Polygon, box
from shapely.ops import unary_union
@ -676,62 +676,130 @@ def _extract_footprint_polygons(
return [p for p in out[:4] if p.area >= 3.0] or out[:1]
def _merge_short_ring_edges(coords: list[tuple[float, float]], min_edge_len: float = 1.2) -> list[tuple[float, float]]:
"""Collapse tiny jagged edge steps so wall bays don't fragment into micro-slivers."""
pts = list(coords[:-1]) # open ring
if len(pts) <= 3:
return pts
changed = True
while changed and len(pts) > 3:
changed = False
new_pts: list[tuple[float, float]] = []
i = 0
while i < len(pts):
a = pts[i]
b = pts[(i + 1) % len(pts)]
if math.hypot(b[0] - a[0], b[1] - a[1]) < min_edge_len and len(pts) - (1 if new_pts else 0) > 3:
if i + 1 < len(pts):
new_pts.append((0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1])))
i += 2
changed = True
continue
new_pts.append(a)
i += 1
pts = new_pts
return pts
def _partition_ring_into_wall_chains(
plinth_fp: Polygon,
max_bays: int,
base_bay_len: float,
) -> list[list[tuple[float, float]]]:
"""
Partition 100% of plinth_fp's outer perimeter ring into <= max_bays contiguous edge chains
(never dropping or truncating edges).
Each returned chain is [p_0, p_1, ..., p_k] (k >= 1 edges) in CCW ring traversal order.
"""
raw_pts = list(plinth_fp.exterior.coords[:-1])
pts: list[tuple[float, float]] = []
for p in raw_pts:
if not pts or math.hypot(p[0] - pts[-1][0], p[1] - pts[-1][1]) >= 0.05:
pts.append((float(p[0]), float(p[1])))
while len(pts) > 3 and math.hypot(pts[0][0] - pts[-1][0], pts[0][1] - pts[-1][1]) < 0.05:
pts.pop()
if len(pts) < 3:
minx, minz, maxx, maxz = plinth_fp.bounds
pts = [(minx, minz), (maxx, minz), (maxx, maxz), (minx, maxz)]
m = len(pts)
elens = [math.hypot(pts[(k + 1) % m][0] - pts[k][0], pts[(k + 1) % m][1] - pts[k][1]) for k in range(m)]
if m <= max_bays:
# Subdivide unusually long single edges only within remaining bay slack
slack = max(0, max_bays - m)
chains: list[list[tuple[float, float]]] = []
for k in range(m):
ax, az = pts[k]
bx, bz = pts[(k + 1) % m]
elen = elens[k]
n_sub = 1
if slack > 0 and elen > base_bay_len * 1.15:
want_sub = min(slack + 1, max(1, int(math.ceil(elen / base_bay_len))))
n_sub = want_sub
slack -= (n_sub - 1)
for s in range(n_sub):
t0 = s / n_sub
t1 = (s + 1) / n_sub
p0 = (ax + (bx - ax) * t0, az + (bz - az) * t0)
p1 = (ax + (bx - ax) * t1, az + (bz - az) * t1)
chains.append([p0, p1])
return chains
# M > max_bays: partition all M consecutive edges evenly by arc length into max_bays chains
cum = [0.0]
for elen in elens:
cum.append(cum[-1] + elen)
total_perim = cum[-1]
splits = [0]
cur = 0
for b in range(1, max_bays):
target = total_perim * (b / max_bays)
lo = cur + 1
hi = m - (max_bays - b)
best = min(range(lo, hi + 1), key=lambda idx: abs(cum[idx] - target))
splits.append(best)
cur = best
splits.append(m)
chains = []
for b in range(max_bays):
a, c = splits[b], splits[b + 1]
chains.append([pts[idx % m] for idx in range(a, c + 1)])
return chains
def _split_ring_into_wall_bays(
ring_pts: list[tuple[float, float]],
max_bay_len: float,
is_hole: bool = False,
) -> list[tuple[np.ndarray, np.ndarray, float]]:
def _build_multi_edge_wall_bay_geometry(
chain_pts: list[tuple[float, float]],
plinth_fp: Polygon,
y_bot: float,
y_top: float,
wall_thick: float,
pal: dict[str, int],
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""
Return list of (p_start_xz (2,), p_end_xz (2,), length) oriented so
outward normal points AWAY from the building solid.
For CCW outer ring in (X, Z): interior is on LEFT in (X, Z) math -> outward is RIGHT = (dz, -dx).
For CW hole ring: interior of building is STILL on LEFT of ring traversal -> outward into courtyard is STILL RIGHT!
Extrude a contiguous multi-edge perimeter chain into a closed, watertight 2-manifold WallBay
volume spanning [y_bot, y_top] and lying inward from the outer perimeter inside plinth_fp.
"""
bays: list[tuple[np.ndarray, np.ndarray, float]] = []
n = len(ring_pts)
for k in range(n):
ax, az = ring_pts[k]
bx, bz = ring_pts[(k + 1) % n]
elen = math.hypot(bx - ax, bz - az)
if elen < 0.75:
continue
n_sub = max(1, int(math.ceil(elen / max_bay_len)))
pa = np.array([ax, az], dtype=np.float64)
pb = np.array([bx, bz], dtype=np.float64)
for s in range(n_sub):
t0 = s / n_sub
t1 = (s + 1) / n_sub
sa = pa + (pb - pa) * t0
sb = pa + (pb - pa) * t1
slen = float(np.linalg.norm(sb - sa))
if slen >= 0.75:
bays.append((sa, sb, slen))
return bays
ls = LineString(chain_pts)
band = ls.buffer(wall_thick, single_sided=True, join_style="mitre", mitre_limit=2.0)
w2d = band.intersection(plinth_fp)
if w2d.is_empty:
w2d = band
if isinstance(w2d, Polygon):
raw_polys = [w2d] if w2d.area >= 0.02 else []
else:
raw_polys = [g for g in getattr(w2d, "geoms", []) if isinstance(g, Polygon) and g.area >= 0.02]
if not raw_polys:
fallback = ls.buffer(wall_thick, single_sided=True, join_style="bevel")
raw_polys = [fallback] if isinstance(fallback, Polygon) and not fallback.is_empty else [
g for g in getattr(fallback, "geoms", []) if isinstance(g, Polygon) and g.area >= 0.02
]
raw_polys.sort(key=lambda p: p.area, reverse=True)
kept: list[Polygon] = []
for rp in raw_polys:
cleaned = _clean_polygon_2d(rp, min_area=0.02)
if cleaned is not None and (not kept or all(cleaned.distance(k) > 0.05 for k in kept)):
kept.append(cleaned)
if not kept:
kept = [_clean_polygon_2d(band, min_area=0.01) or box(*ls.buffer(wall_thick * 0.5).bounds)]
u_xz = np.array([1.0, 0.0, 0.0], dtype=np.float64)
v_xz = np.array([0.0, 0.0, -1.0], dtype=np.float64)
n_up = np.array([0.0, 1.0, 0.0], dtype=np.float64)
origin = np.array([0.0, y_bot, 0.0], dtype=np.float64)
h = y_top - y_bot
parts = []
for kp in kept:
ext = [(x, -z) for x, z in kp.exterior.coords]
holes = [[(x, -z) for x, z in hole.coords] for hole in kp.interiors]
uv_poly = Polygon(ext, holes)
parts.append(extrude_2d_poly_prism(
origin, u_xz, v_xz, n_up, uv_poly,
0.0, h,
mat_top=pal["wall"], mat_bot=pal["wall"], mat_side=pal["wall"],
ao_top=225, ao_bot=185, ao_side=215,
))
return _concat_parts(parts) if len(parts) > 1 else parts[0]
def _build_wall_bay_geometry(
@ -1224,7 +1292,7 @@ def build_cga_building(
# Build real-footprint + pitched-roof watertight LOD2 solids
lod2_solids: list[tuple[np.ndarray, int]] = []
lod2_body_h = max(1.0, eave_y - plinth_bot_y - 0.02)
l2_simp = 2.2 if micro_zone in (MICRO_FORTRESS, MICRO_CIVIC, MICRO_OLD_TOWN) else 3.2
l2_simp = 2.2 if micro_zone in (MICRO_FORTRESS, MICRO_CIVIC, MICRO_OLD_TOWN) else 3.6
l2_wings = plinth_fps if micro_zone in (MICRO_FORTRESS, MICRO_CIVIC) else plinth_fps[:1]
for pfp in l2_wings:
l2_fp = pfp.simplify(l2_simp, preserve_topology=True)
@ -1262,8 +1330,8 @@ def build_cga_building(
)
n_roofs = len(roof_items)
# 3. Canopy / Open Shed without walls (columns/core + roof)
if is_canopy_only or (wall_h < 1.2 and len(w_rtd) == 0):
# 3. Canopy / Open Shed / zero-wall underground structures without walls (columns/core + roof)
if is_canopy_only or wall_h < 1.2:
# Add 1 InteriorCore pier supporting the roof
minx, minz, maxx, maxz = plinth_fp.bounds
cw = max(0.6, min(2.4, (maxx - minx) * 0.22))
@ -1295,9 +1363,7 @@ def build_cga_building(
n_stories = max(1, int(round(wall_h / story_h_target)))
hero_zone = micro_zone in (MICRO_OLD_TOWN, MICRO_FORTRESS, MICRO_CIVIC)
min_edge = 3.6 if hero_zone else 4.6
ext_pts = _merge_short_ring_edges(list(plinth_fp.exterior.coords), min_edge_len=min_edge)
raw_bays_len = max(3, len(ext_pts))
raw_bays_len = max(3, len(plinth_fp.exterior.coords) - 1)
# Cap structural tiers cleanly so total city RCGA + LOD2 fits well <= 16 MiB (and total sion <= 85 MiB)
avail_for_stories = MAX_ZONES_PER_BUILDING - (2 + n_roofs)
@ -1309,25 +1375,7 @@ def build_cga_building(
perim = float(plinth_fp.exterior.length)
base_bay_len = 15.0 if hero_zone else (22.0 if (is_mauer or micro_zone == MICRO_RONQUOZ or perim > 70.0) else 20.0)
bays_2d: list[tuple[np.ndarray, np.ndarray, float]] = []
for mult in (1.0, 1.4, 2.0, 3.0, 5.0, 10.0):
cand = _split_ring_into_wall_bays(ext_pts, base_bay_len * mult)
if len(cand) <= max_bays_per_tier:
bays_2d = cand
break
if not bays_2d:
# Simplify plinth_fp progressively until edge count fits max_bays_per_tier (never OBB-expand!)
for simp_f in (0.04, 0.08, 0.14):
sfp = plinth_fp.simplify(max(0.8, perim * simp_f), preserve_topology=True)
if isinstance(sfp, Polygon) and not sfp.is_empty:
spts = _merge_short_ring_edges(list(sfp.exterior.coords), min_edge_len=3.2)
cand = _split_ring_into_wall_bays(spts, max(base_bay_len, perim / max(3, max_bays_per_tier)))
if len(cand) <= max_bays_per_tier:
bays_2d = cand
break
if not bays_2d:
cand = _split_ring_into_wall_bays(ext_pts, perim + 1.0)
bays_2d = cand[:max_bays_per_tier] if len(cand) > max_bays_per_tier else cand
bay_chains = _partition_ring_into_wall_chains(plinth_fp, max_bays_per_tier, base_bay_len)
# 4a. InteriorCore zone (spans full height plinth_top_y .. eave_y - 0.15)
minx, minz, maxx, maxz = plinth_fp.bounds
@ -1384,18 +1432,31 @@ def build_cga_building(
cur_bay_indices: list[int] = []
cur_bay_mids: list[np.ndarray] = []
for b_i, (sa, sb, blen) in enumerate(bays_2d):
for b_i, chain_pts in enumerate(bay_chains):
if len(zones) >= MAX_ZONES_PER_BUILDING - n_roofs - 1:
break
want_win = (not is_mauer) and (
(hero_zone and blen >= 5.2 and t_idx == 0 and (b_i == 0 or (micro_zone in (MICRO_FORTRESS, MICRO_CIVIC) and b_i == 2 and blen >= 6.5)))
or (micro_zone in (MICRO_VISSIGEN, MICRO_CLAVAU, MICRO_SUBURBAN) and blen >= 8.2 and b_i == 0 and t_idx == 0)
or (micro_zone == MICRO_RONQUOZ and blen >= 11.0 and b_i == 0 and t_idx == 0)
)
r_parts, c_parts, has_win = _build_wall_bay_geometry(
sa, sb, blen, y0, bay_y_top, wall_thick, pal, micro_zone,
allow_details=want_win,
)
if len(chain_pts) == 2:
sa = np.array(chain_pts[0], dtype=np.float64)
sb = np.array(chain_pts[1], dtype=np.float64)
blen = float(np.linalg.norm(sb - sa))
want_win = (not is_mauer) and (
(hero_zone and blen >= 5.2 and t_idx == 0 and (b_i == 0 or (micro_zone in (MICRO_FORTRESS, MICRO_CIVIC) and b_i == 2 and blen >= 6.5)))
or (micro_zone in (MICRO_VISSIGEN, MICRO_CLAVAU, MICRO_SUBURBAN) and blen >= 10.5 and b_i == 0 and t_idx == 0)
or (micro_zone == MICRO_RONQUOZ and blen >= 14.0 and b_i == 0 and t_idx == 0)
)
r_parts, c_parts, has_win = _build_wall_bay_geometry(
sa, sb, blen, y0, bay_y_top, wall_thick, pal, micro_zone,
allow_details=want_win,
)
bay_mid = 0.5 * (sa + sb)
else:
r_parts = _build_multi_edge_wall_bay_geometry(
chain_pts, plinth_fp, y0, bay_y_top, wall_thick, pal
)
c_parts = r_parts
has_win = False
mp = LineString(chain_pts).interpolate(0.5, normalized=True)
bay_mid = np.array([mp.x, mp.y], dtype=np.float64)
if t_idx == 0:
sup_mask = plinth_bit
else:
@ -1405,7 +1466,7 @@ def build_cga_building(
z_flags = ZONE_FLAG_EXTERIOR | (ZONE_FLAG_HAS_WINDOWS if has_win else 0)
bz_idx = add_zone(ZONE_WALL_BAY, pal["wall_class"], z_flags, sup_mask, r_parts, c_parts)
cur_bay_indices.append(bz_idx)
cur_bay_mids.append(0.5 * (sa + sb))
cur_bay_mids.append(bay_mid)
# Horizontal FloorSlab at top of tier t_idx (strictly inset inside plinth_fps, 0 overhang)
tier_wall_mask = 0
@ -1423,7 +1484,7 @@ def build_cga_building(
)
for suv in slab_polys_uv
])
slab_sup = (tier_wall_mask if tier_wall_mask else plinth_bit) | core_bit
slab_sup = tier_wall_mask if tier_wall_mask else (plinth_bit | core_bit)
slab_idx = add_zone(ZONE_FLOOR_SLAB, MAT_CLASS_CONCRETE, 0, slab_sup, slab_parts, slab_parts)
all_tier_supports_mask = tier_wall_mask | core_bit | (1 << slab_idx)
else:
@ -1434,7 +1495,7 @@ def build_cga_building(
prev_bay_mids = cur_bay_mids
# 5. Roof Zones anchored to top-tier perimeter WallBays (never floating solely on 0.8m core)
lod2_roof_cap = 2 if micro_zone in (MICRO_FORTRESS, MICRO_CIVIC) else 1
lod2_roof_cap = 3 if micro_zone in (MICRO_FORTRESS, MICRO_CIVIC) else 2
for r_i, (r_render, r_col, r_c3) in enumerate(roof_items):
if len(zones) >= MAX_ZONES_PER_BUILDING:
break
@ -2181,6 +2242,10 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]:
lod2_inverted_solids = 0
grounding_violations = 0
floorslab_overhangs = 0
floorslab_outside_wallbay = 0
open_perimeter_gaps = 0
wallbay_pancakes = 0
min_wallbay_height = float("inf")
verified_buildings = 0
total_render_tris = 0
total_col_tris = 0
@ -2218,6 +2283,10 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]:
verified_buildings += 1
plinth_verts_xz: np.ndarray | None = None
plinth_min_y = 0.0
plinth_top_polys: list[Polygon] = []
wall_top_polys: list[Polygon] = []
wall_boxes_xz: list[tuple[float, float, float, float]] = []
slab_boxes_xz: list[tuple[float, float, float, float]] = []
for zi in range(z_cnt):
rv_cnt, ri_cnt, cv_cnt, ci_cnt = slice_hdrs[s_ptr]
@ -2250,6 +2319,30 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]:
t_vals = _sample_hm_verify(hm, plinth_verts_xz[:, 0], plinth_verts_xz[:, 1])
if plinth_min_y > float(np.min(t_vals)) - 3.90:
grounding_violations += 1
tri_p = c_pos[ci_arr.reshape(-1, 3)]
cr = np.cross(tri_p[:, 1] - tri_p[:, 0], tri_p[:, 2] - tri_p[:, 0])
ny_u = cr[:, 1] / np.maximum(1e-9, np.linalg.norm(cr, axis=1))
for t2 in tri_p[ny_u > 0.7][:, :, [0, 2]]:
tp = Polygon(t2)
if tp.is_valid and tp.area > 1e-4:
plinth_top_polys.append(tp)
elif z_kind == ZONE_WALL_BAY:
wb_h = float(c_pos[:, 1].max() - c_pos[:, 1].min())
if wb_h < min_wallbay_height:
min_wallbay_height = wb_h
if wb_h < 0.35:
wallbay_pancakes += 1
wall_boxes_xz.append((
float(c_pos[:, 0].min()), float(c_pos[:, 2].min()),
float(c_pos[:, 0].max()), float(c_pos[:, 2].max()),
))
tri_p = c_pos[ci_arr.reshape(-1, 3)]
cr = np.cross(tri_p[:, 1] - tri_p[:, 0], tri_p[:, 2] - tri_p[:, 0])
ny_u = cr[:, 1] / np.maximum(1e-9, np.linalg.norm(cr, axis=1))
for t2 in tri_p[ny_u > 0.7][:, :, [0, 2]]:
tp = Polygon(t2)
if tp.is_valid and tp.area > 1e-4:
wall_top_polys.append(tp)
elif z_kind == ZONE_FLOOR_SLAB and plinth_verts_xz is not None:
p_x0, p_z0 = float(plinth_verts_xz[:, 0].min()), float(plinth_verts_xz[:, 1].min())
p_x1, p_z1 = float(plinth_verts_xz[:, 0].max()), float(plinth_verts_xz[:, 1].max())
@ -2257,6 +2350,22 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]:
s_x1, s_z1 = float(c_pos[:, 0].max()), float(c_pos[:, 2].max())
if s_x0 < p_x0 - 0.08 or s_x1 > p_x1 + 0.08 or s_z0 < p_z0 - 0.08 or s_z1 > p_z1 + 0.08:
floorslab_overhangs += 1
slab_boxes_xz.append((s_x0, s_z0, s_x1, s_z1))
if wall_boxes_xz and slab_boxes_xz:
wx0 = min(b[0] for b in wall_boxes_xz)
wz0 = min(b[1] for b in wall_boxes_xz)
wx1 = max(b[2] for b in wall_boxes_xz)
wz1 = max(b[3] for b in wall_boxes_xz)
if any(sx0 < wx0 - 1.0 or sx1 > wx1 + 1.0 or sz0 < wz0 - 1.0 or sz1 > wz1 + 1.0 for sx0, sz0, sx1, sz1 in slab_boxes_xz):
floorslab_outside_wallbay += 1
if plinth_top_polys and wall_top_polys:
pu = unary_union(plinth_top_polys)
primary_plinth = max(pu.geoms, key=lambda g: g.area) if hasattr(pu, "geoms") else pu
wu = unary_union(wall_top_polys).buffer(0.30)
if float(primary_plinth.exterior.difference(wu).length) > 0.50:
open_perimeter_gaps += 1
# Verify every city_lod2_*.glb primitive & connected solid component
for lpath in lod2_files:
@ -2322,6 +2431,10 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]:
"lod2_inverted_solids": lod2_inverted_solids,
"grounding_violations": grounding_violations,
"floorslab_overhangs": floorslab_overhangs,
"floorslab_outside_wallbay": floorslab_outside_wallbay,
"open_perimeter_gaps": open_perimeter_gaps,
"wallbay_pancakes": wallbay_pancakes,
"min_wallbay_height": round(min_wallbay_height, 4) if min_wallbay_height != float("inf") else 0.0,
"tile_drift_count": tile_drift_count,
"support_dag_cycles": dag_cycles,
"ground_unreachable": ground_unreachable,
@ -2342,9 +2455,11 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]:
raise RuntimeError(
f"LOD2 GLB watertight audit FAILED: open={lod2_open_total}, nm={lod2_non_manifold_total}, deg={lod2_deg_total}, inv={lod2_inverted_solids}"
)
if grounding_violations != 0 or floorslab_overhangs != 0 or tile_drift_count != 0:
if grounding_violations != 0 or floorslab_overhangs != 0 or floorslab_outside_wallbay != 0 or open_perimeter_gaps != 0 or wallbay_pancakes != 0 or tile_drift_count != 0:
raise RuntimeError(
f"Spatial audit FAILED: grounding={grounding_violations}, floorslab_overhang={floorslab_overhangs}, tile_drift={tile_drift_count}"
f"Spatial audit FAILED: grounding={grounding_violations}, floorslab_overhang={floorslab_overhangs}, "
f"floorslab_outside_wallbay={floorslab_outside_wallbay}, open_perimeter_gaps={open_perimeter_gaps}, "
f"wallbay_pancakes={wallbay_pancakes}, tile_drift={tile_drift_count}"
)
if dag_cycles != 0 or ground_unreachable != 0:
raise RuntimeError(f"Support DAG audit FAILED: cycles={dag_cycles}, unreachable={ground_unreachable}")