Cut 13b: fix LOD2 solid audit and trim RCGA/LOD2 byte budget

This commit is contained in:
Meta Vens 2026-12-06 03:01:13 +01:00
commit ddba958fe0

View file

@ -945,13 +945,13 @@ def _build_roof_zones(
geoms = list(merged.geoms) if hasattr(merged, "geoms") else [merged]
for g in geoms:
if isinstance(g, Polygon) and g.area > 0.8:
simp_r = 0.42 if micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN, MICRO_CIVIC) else 0.72
simp_r = 0.50 if micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN, MICRO_CIVIC) else 0.90
gs = g.simplify(simp_r, preserve_topology=True)
if isinstance(gs, Polygon) and gs.area > 0.8:
g = gs
# Add gentle eave overhang on pitched slopes
if n_axis[1] < 0.97 and micro_zone in (MICRO_OLD_TOWN, MICRO_CLAVAU, MICRO_SUBURBAN, MICRO_FORTRESS, MICRO_CIVIC):
gb = g.buffer(0.22, join_style="mitre")
# Add gentle eave overhang on pitched slopes for larger roofs
if n_axis[1] < 0.97 and g.area > 20.0 and micro_zone in (MICRO_OLD_TOWN, MICRO_CLAVAU, MICRO_SUBURBAN, MICRO_FORTRESS, MICRO_CIVIC):
gb = g.buffer(0.22, join_style="bevel")
if isinstance(gb, Polygon) and gb.area > g.area * 0.9:
g = gb
planes.append((origin, u_axis, v_axis, n_axis, g))
@ -1090,7 +1090,7 @@ def build_cga_building(
bldg_center_xz = np.array([fp_cx, fp_cz], dtype=np.float64)
# Final Plinth polygons (NO minimum_rotated_rectangle expansion; secondary parts kept strictly separated)
plinth_tol = 0.45 if micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN, MICRO_CIVIC) else 1.05
plinth_tol = 0.50 if micro_zone in (MICRO_FORTRESS, MICRO_OLD_TOWN, MICRO_CIVIC) else 1.25
plinth_fps: list[Polygon] = []
for fp in footprints:
ps = fp.simplify(plinth_tol, preserve_topology=True)
@ -1210,7 +1210,7 @@ def build_cga_building(
lod2_solids: list[tuple[np.ndarray, int]] = []
lod2_body_h = max(1.0, eave_y - plinth_bot_y - 0.02)
for pfp in plinth_fps:
l2_fp = pfp.simplify(1.25, preserve_topology=True)
l2_fp = pfp.simplify(1.65, preserve_topology=True)
l2_fp = _clean_polygon_2d(l2_fp if isinstance(l2_fp, Polygon) else pfp, min_area=1.0) or pfp
l2_t, _, _, _ = extrude_2d_poly_prism(
np.array([0.0, plinth_bot_y, 0.0]), u_xz, v_xz, n_up, fp_to_uv(l2_fp),
@ -1237,9 +1237,7 @@ def build_cga_building(
if is_mauer:
max_roofs = 0
elif micro_zone in (MICRO_FORTRESS, MICRO_CIVIC):
max_roofs = 6
elif micro_zone in (MICRO_OLD_TOWN, MICRO_CLAVAU, MICRO_SUBURBAN):
max_roofs = 3
max_roofs = 5
else:
max_roofs = 2
roof_items = _build_roof_zones(
@ -1331,7 +1329,7 @@ def build_cga_building(
slab_inset = min(wall_thick * 0.45, 0.20)
slab_polys_uv: list[Polygon] = []
for pfp in plinth_fps:
sfp = pfp.simplify(0.95, preserve_topology=True)
sfp = pfp.simplify(1.25, preserve_topology=True)
if not isinstance(sfp, Polygon) or sfp.is_empty or sfp.area < 0.8:
sfp = pfp
sfp = sfp.buffer(-slab_inset, join_style="mitre")
@ -1372,10 +1370,10 @@ def build_cga_building(
if len(zones) >= MAX_ZONES_PER_BUILDING - n_roofs - 1:
break
want_win = (not is_mauer) and (
(hero_zone and blen >= 3.2 and (b_i % 2 == 0) and t_idx < 2)
or (micro_zone == MICRO_VISSIGEN and blen >= 4.5 and (b_i % 2 == 0) and t_idx == 0)
or (micro_zone in (MICRO_CLAVAU, MICRO_SUBURBAN) and blen >= 4.8 and b_i == 0 and t_idx == 0)
or (micro_zone == MICRO_RONQUOZ and blen >= 6.8 and b_i == 0 and t_idx == 0)
(hero_zone and blen >= 3.4 and (b_i % 2 == 0) and (t_idx == 0 or (t_idx == 1 and b_i == 0)))
or (micro_zone == MICRO_VISSIGEN and blen >= 4.8 and b_i == 0 and t_idx == 0)
or (micro_zone in (MICRO_CLAVAU, MICRO_SUBURBAN) and blen >= 5.2 and b_i == 0 and t_idx == 0)
or (micro_zone == MICRO_RONQUOZ and blen >= 7.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,
@ -1762,17 +1760,31 @@ def export_rcga_tile(tx: int, tz: int, buildings: list[CgaBuildingResult], out_p
return out_path.stat().st_size, total_r_tris, total_c_tris
def _lod2_coarse_palette(pal_id: int) -> int:
if pal_id in (PAL_FORTRESS_STONE, PAL_PLINTH_STONE):
return PAL_FORTRESS_STONE
if pal_id in (PAL_CONCRETE_AGGREGATE, PAL_CONCRETE_SLAB, PAL_CORRUGATED_STEEL):
return PAL_CONCRETE_AGGREGATE
if pal_id == PAL_ROOF_TERRACOTTA:
return PAL_ROOF_TERRACOTTA
if pal_id == PAL_ROOF_LAUZES:
return PAL_ROOF_LAUZES
if pal_id == PAL_ROOF_INDUSTRIAL:
return PAL_ROOF_INDUSTRIAL
return PAL_CREPIS_SAND
def export_city_lod2_glb(tx: int, tz: int, buildings: list[CgaBuildingResult], out_path) -> tuple[int, int]:
"""
Export real-footprint + pitched-roof watertight LOD2 GLB on 16x16 grid.
Deduplicates vertices per closed solid component so adjacent roof slopes / rowhouses
never merge across disjoint solid boundaries.
Deduplicates vertices per closed solid component and records per-solid triangle counts
in primitive.extras['solidTriCounts'] for exact per-solid manifold/volume verification.
"""
mat_solids: dict[int, list[np.ndarray]] = defaultdict(list)
for b in buildings:
for solid_tris, mid in b.lod2_solids:
if len(solid_tris) > 0:
mat_solids[int(mid)].append(solid_tris)
mat_solids[_lod2_coarse_palette(int(mid))].append(solid_tris)
out_path.parent.mkdir(parents=True, exist_ok=True)
blob = bytearray()
@ -1786,27 +1798,36 @@ def export_city_lod2_glb(tx: int, tz: int, buildings: list[CgaBuildingResult], o
part_verts: list[np.ndarray] = []
part_norms: list[np.ndarray] = []
part_indices: list[np.ndarray] = []
solid_tri_counts: list[int] = []
vert_offset = 0
for solid in solid_list:
tris = np.asarray(solid, dtype=np.float32)
# Filter out any triangles whose 1mm float32 quantized corners collapse
qp_tri = np.round(tris * 1000.0).astype(np.int64)
cr_q = np.cross(qp_tri[:, 1] - qp_tri[:, 0], qp_tri[:, 2] - qp_tri[:, 0])
if not np.all(np.any(cr_q != 0, axis=1)):
# Fallback to clean closed box hull of this solid if sliver collapsed at 1mm
bmin = tris.reshape(-1, 3).min(axis=0).astype(np.float64)
bmax = np.maximum(bmin + 0.08, tris.reshape(-1, 3).max(axis=0).astype(np.float64))
box_t, _, _, _ = make_box_prism(
bmin, np.array([1.0, 0.0, 0.0]), np.array([0.0, 0.0, -1.0]), np.array([0.0, 1.0, 0.0]),
0.0, float(bmax[0] - bmin[0]), -float(bmax[2] - bmin[2]), 0.0, 0.0, float(bmax[1] - bmin[1]),
pal_id, pal_id, pal_id,
)
tris = box_t.astype(np.float32)
e1 = tris[:, 1] - tris[:, 0]
e2 = tris[:, 2] - tris[:, 0]
cross = np.cross(e1, e2)
nlen = np.linalg.norm(cross, axis=1)
valid = nlen > 1e-6
if not np.all(valid):
tris = tris[valid]
cross = cross[valid]
nlen = nlen[valid]
if len(tris) == 0:
continue
nlen = np.maximum(1e-9, np.linalg.norm(cross, axis=1))
n_face = (cross / nlen[:, None]).astype(np.float32)
total_tris += len(tris)
solid_tri_counts.append(int(len(tris)))
raw_verts = tris.reshape(-1, 3)
raw_norms = np.repeat(n_face, 3, axis=0)
q_pos = np.round(raw_verts * 500.0).astype(np.int64)
q_pos = np.round(raw_verts * 1000.0).astype(np.int64)
q_nrm = np.round(raw_norms * 120.0).astype(np.int64)
keys = np.ascontiguousarray(np.hstack([q_pos, q_nrm])).view(np.dtype((np.void, 6 * 8))).ravel()
_, uniq_idx, inv_idx = np.unique(keys, return_index=True, return_inverse=True)
@ -1876,6 +1897,7 @@ def export_city_lod2_glb(tx: int, tz: int, buildings: list[CgaBuildingResult], o
primitives.append(pygltflib.Primitive(
attributes=pygltflib.Attributes(POSITION=pos_acc, NORMAL=nrm_acc),
indices=idx_acc, material=m_id,
extras={"solidTriCounts": solid_tri_counts},
))
gltf = pygltflib.GLTF2(
@ -2234,32 +2256,23 @@ def verify_rcga_outputs(sion_dir) -> dict[str, int | float | str]:
blob, dtype=idx_dtype, count=idx_acc.count, offset=(idx_bv.byteOffset or 0) + (idx_acc.byteOffset or 0)
).astype(np.int64)
# Check primitive watertightness via vertex-position welding
qpos = np.round(pos * 500.0).astype(np.int64)
lo, lnm, ld = check_mesh_watertight(qpos, idx)
lod2_open_total += lo
lod2_non_manifold_total += lnm
lod2_deg_total += ld
# Verify outward signed volume per index-connected component
# Verify each individual solid component via extras["solidTriCounts"]
tri_idx = idx.reshape(-1, 3)
parent = list(range(len(pos)))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b, c in tri_idx:
ra, rb, rc = find(int(a)), find(int(b)), find(int(c))
if rb != ra:
parent[rb] = ra
if rc != ra:
parent[rc] = ra
comp_tris: dict[int, list[int]] = defaultdict(list)
for ti, (a, _, _) in enumerate(tri_idx):
comp_tris[find(int(a))].append(ti)
for tlist in comp_tris.values():
ct = pos[tri_idx[tlist]].astype(np.float64)
solid_counts = (prim.extras or {}).get("solidTriCounts")
if not solid_counts:
solid_counts = [len(tri_idx)]
t_cursor = 0
for s_tris in solid_counts:
sub_tri_idx = tri_idx[t_cursor : t_cursor + int(s_tris)]
t_cursor += int(s_tris)
used_v, local_inv = np.unique(sub_tri_idx.ravel(), return_inverse=True)
sub_pos = pos[used_v]
sub_qpos = np.round(sub_pos * 1000.0).astype(np.int64)
lo, lnm, ld = check_mesh_watertight(sub_qpos, local_inv.astype(np.int64))
lod2_open_total += lo
lod2_non_manifold_total += lnm
lod2_deg_total += ld
ct = sub_pos[local_inv.reshape(-1, 3)].astype(np.float64)
vol6 = float(np.sum(np.sum(ct[:, 0, :] * np.cross(ct[:, 1, :], ct[:, 2, :]), axis=1)))
if vol6 <= 1e-4:
lod2_inverted_solids += 1