2108 lines
93 KiB
Python
2108 lines
93 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Offline Sion, Switzerland real-world map baker for RustToDust.
|
|
Fetches swissALTI3D DEM + swissBUILDINGS3D 3.0 LOD2 from Swisstopo STAC
|
|
(plus Swisstopo TLM WMS surface masks), caches raw downloads in $TEMP/sion-cache,
|
|
and bakes a 3072m x 3072m (6x6 grid of 512m tiles) playable arena:
|
|
- assets/maps/sion/heightmap.f32 (1025x1025 float32, 3.0m grid, 3072m x 3072m)
|
|
- assets/maps/sion/terrain_surface.png (2048x2048 RGB surface albedo)
|
|
- assets/maps/sion/metadata.json
|
|
- assets/maps/sion/buildings_manifest.json
|
|
- assets/maps/sion/tiles/lod2_<tx>_<tz>.glb (semantic LOD2 per non-empty tile)
|
|
- assets/maps/sion/tiles/lod1_<tx>_<tz>.glb (procedural LOD1 per non-empty tile)
|
|
- assets/maps/sion/tiles/col_<tx>_<tz>.bin (packed RCOL v1 collision trimesh)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import ctypes
|
|
import glob
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import struct
|
|
import urllib.parse
|
|
import urllib.request
|
|
import zipfile
|
|
from collections import Counter, defaultdict
|
|
from pathlib import Path
|
|
|
|
import imagecodecs
|
|
import numpy as np
|
|
import pygltflib
|
|
import pyogrio
|
|
import pyproj
|
|
import shapely
|
|
from scipy.ndimage import (
|
|
binary_closing,
|
|
binary_dilation,
|
|
binary_opening,
|
|
gaussian_filter,
|
|
map_coordinates,
|
|
maximum_filter1d,
|
|
zoom,
|
|
)
|
|
from shapely.geometry import Polygon, box
|
|
from shapely.ops import unary_union
|
|
import tifffile
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Arena & Swisstopo constants
|
|
# ---------------------------------------------------------------------------
|
|
ARENA_SIZE_M = 3072.0
|
|
HALF_EXTENT_M = 1536.0
|
|
GRID_RES = 1025
|
|
CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 3.0m exact
|
|
TILE_GRID = 6
|
|
TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 512.0m exact
|
|
|
|
SURFACE_TEX_RES = 2048
|
|
|
|
# Centered around Valere & Tourbillon twin citadels to frame:
|
|
# - Valere & Tourbillon fortress hills
|
|
# - Full Sion Old Town
|
|
# - Railway & industrial yards (south-west / central)
|
|
# - Rhone river corridor + highway bridges (south/east-to-west)
|
|
# - Terraced alpine hillsides & vineyards (north/east/south)
|
|
DEFAULT_CENTER_E = 2594150.0
|
|
DEFAULT_CENTER_N = 1120050.0
|
|
|
|
STAC_ALTI_URL = "https://data.geo.admin.ch/api/stac/v0.9/collections/ch.swisstopo.swissalti3d/items"
|
|
STAC_BLDG_URL = "https://data.geo.admin.ch/api/stac/v0.9/collections/ch.swisstopo.swissbuildings3d_3_0/items"
|
|
WMS_BASE_URL = "https://wms.geo.admin.ch/"
|
|
|
|
SKIRT_DEPTH_M = 4.0
|
|
MAX_LOD1_TRIS = 275_000
|
|
MAX_TILES_GLB_BYTES = 28_000_000
|
|
MAX_SURFACE_PNG_BYTES = 3_000_000
|
|
MAX_TOTAL_ASSETS_BYTES = 40_000_000
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GDAL / OGR ctypes wrapper (uses pyogrio's bundled GDAL 3.12+ DLL)
|
|
# ---------------------------------------------------------------------------
|
|
class OgrReader:
|
|
def __init__(self) -> None:
|
|
libs_dir = os.path.abspath(os.path.join(os.path.dirname(pyogrio.__file__), "..", "pyogrio.libs"))
|
|
os.add_dll_directory(libs_dir)
|
|
dlls = glob.glob(os.path.join(libs_dir, "gdal-*.dll"))
|
|
if not dlls:
|
|
raise RuntimeError(f"Could not locate gdal-*.dll in {libs_dir}")
|
|
g = ctypes.CDLL(dlls[0])
|
|
g.GDALAllRegister()
|
|
g.GDALOpenEx.argtypes = [ctypes.c_char_p, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
|
|
g.GDALOpenEx.restype = ctypes.c_void_p
|
|
g.GDALClose.argtypes = [ctypes.c_void_p]
|
|
g.GDALDatasetGetLayerByName.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
|
g.GDALDatasetGetLayerByName.restype = ctypes.c_void_p
|
|
g.OGR_L_SetSpatialFilterRect.argtypes = [
|
|
ctypes.c_void_p, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double
|
|
]
|
|
g.OGR_L_GetNextFeature.argtypes = [ctypes.c_void_p]
|
|
g.OGR_L_GetNextFeature.restype = ctypes.c_void_p
|
|
g.OGR_F_Destroy.argtypes = [ctypes.c_void_p]
|
|
g.OGR_F_GetFieldIndex.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
|
g.OGR_F_GetFieldIndex.restype = ctypes.c_int
|
|
g.OGR_F_GetFieldAsString.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
|
g.OGR_F_GetFieldAsString.restype = ctypes.c_char_p
|
|
g.OGR_F_GetFieldAsDouble.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
|
g.OGR_F_GetFieldAsDouble.restype = ctypes.c_double
|
|
g.OGR_F_GetGeometryRef.argtypes = [ctypes.c_void_p]
|
|
g.OGR_F_GetGeometryRef.restype = ctypes.c_void_p
|
|
g.OGR_G_WkbSize.argtypes = [ctypes.c_void_p]
|
|
g.OGR_G_WkbSize.restype = ctypes.c_int
|
|
g.OGR_G_ExportToIsoWkb.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p]
|
|
g.OGR_G_ExportToIsoWkb.restype = ctypes.c_int
|
|
self.g = g
|
|
|
|
def read_layer(
|
|
self,
|
|
gdb_path: str,
|
|
layer_name: str,
|
|
bbox: tuple[float, float, float, float],
|
|
fields: list[str],
|
|
) -> list[tuple[dict[str, str | float], list[np.ndarray]]]:
|
|
ds = self.g.GDALOpenEx(gdb_path.encode("utf-8"), 0x04, None, None, None)
|
|
if not ds:
|
|
raise RuntimeError(f"Failed to open GDB: {gdb_path}")
|
|
try:
|
|
lyr = self.g.GDALDatasetGetLayerByName(ds, layer_name.encode("utf-8"))
|
|
if not lyr:
|
|
raise RuntimeError(f"Layer {layer_name} not found in {gdb_path}")
|
|
self.g.OGR_L_SetSpatialFilterRect(lyr, *bbox)
|
|
out = []
|
|
field_indices: dict[str, int] | None = None
|
|
while True:
|
|
feat = self.g.OGR_L_GetNextFeature(lyr)
|
|
if not feat:
|
|
break
|
|
try:
|
|
if field_indices is None:
|
|
field_indices = {
|
|
fn: self.g.OGR_F_GetFieldIndex(feat, fn.encode("utf-8")) for fn in fields
|
|
}
|
|
attrs: dict[str, str | float] = {}
|
|
for fn, idx in field_indices.items():
|
|
if idx < 0:
|
|
attrs[fn] = ""
|
|
elif fn in ("DACH_MIN", "DACH_MAX", "GELAENDEPUNKT", "GESAMTHOEHE"):
|
|
attrs[fn] = float(self.g.OGR_F_GetFieldAsDouble(feat, idx))
|
|
else:
|
|
raw = self.g.OGR_F_GetFieldAsString(feat, idx)
|
|
attrs[fn] = raw.decode("utf-8", "replace") if raw else ""
|
|
geom = self.g.OGR_F_GetGeometryRef(feat)
|
|
if not geom:
|
|
continue
|
|
sz = self.g.OGR_G_WkbSize(geom)
|
|
if sz <= 0:
|
|
continue
|
|
buf = ctypes.create_string_buffer(sz)
|
|
self.g.OGR_G_ExportToIsoWkb(geom, 1, buf)
|
|
faces = parse_iso_wkb_outer_rings(buf.raw)
|
|
if faces:
|
|
out.append((attrs, faces))
|
|
finally:
|
|
self.g.OGR_F_Destroy(feat)
|
|
return out
|
|
finally:
|
|
self.g.GDALClose(ds)
|
|
|
|
|
|
def parse_iso_wkb_outer_rings(wkb: bytes) -> list[np.ndarray]:
|
|
"""Parse ISO WKB (TINZ / PolyhedralSurfaceZ / MultiPolygonZ / PolygonZ / TriangleZ) -> outer ring arrays (N,3)."""
|
|
faces: list[np.ndarray] = []
|
|
mv = memoryview(wkb)
|
|
|
|
def read_geom(p: int) -> int:
|
|
bo = wkb[p]
|
|
endian = "<" if bo == 1 else ">"
|
|
(wt,) = struct.unpack_from(endian + "I", wkb, p + 1)
|
|
p += 5
|
|
has_z = (wt // 1000) in (1, 3) or (wt & 0x80000000) != 0
|
|
base = wt % 1000 if wt < 4000 else (wt & 0xFF)
|
|
dims = 3 if has_z else 2
|
|
if base in (3, 17): # Polygon or Triangle
|
|
(nrings,) = struct.unpack_from(endian + "I", wkb, p)
|
|
p += 4
|
|
for ri in range(nrings):
|
|
(npts,) = struct.unpack_from(endian + "I", wkb, p)
|
|
p += 4
|
|
pts = np.frombuffer(mv[p : p + npts * dims * 8], dtype=endian + "f8").reshape(npts, dims)
|
|
p += npts * dims * 8
|
|
if ri == 0 and npts >= 3:
|
|
if dims == 2:
|
|
pts = np.column_stack([pts, np.zeros(npts, dtype=np.float64)])
|
|
# Strip closing duplicate point if present
|
|
if np.allclose(pts[0], pts[-1], atol=1e-7) and len(pts) > 3:
|
|
pts = pts[:-1]
|
|
if len(pts) >= 3:
|
|
faces.append(pts.copy())
|
|
elif base in (6, 7, 15, 16): # MultiPolygon, GeometryCollection, PolyhedralSurface, TIN
|
|
(ngeoms,) = struct.unpack_from(endian + "I", wkb, p)
|
|
p += 4
|
|
for _ in range(ngeoms):
|
|
p = read_geom(p)
|
|
else:
|
|
raise ValueError(f"Unsupported ISO WKB geometry type: {wt}")
|
|
return p
|
|
|
|
read_geom(0)
|
|
return faces
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# STAC query & download cache
|
|
# ---------------------------------------------------------------------------
|
|
def download_cached(url: str, dest: Path) -> Path:
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
if dest.exists() and dest.stat().st_size > 0:
|
|
return dest
|
|
tmp = dest.with_suffix(dest.suffix + ".part")
|
|
print(f" [STAC download] {url} -> {dest.name}")
|
|
urllib.request.urlretrieve(url, str(tmp))
|
|
tmp.replace(dest)
|
|
return dest
|
|
|
|
|
|
def fetch_stac_items(base_url: str, wgs84_bbox: tuple[float, float, float, float]) -> list[dict]:
|
|
bbox_str = ",".join(f"{v:.6f}" for v in wgs84_bbox)
|
|
items: list[dict] = []
|
|
url: str | None = f"{base_url}?bbox={bbox_str}&limit=100"
|
|
while url:
|
|
with urllib.request.urlopen(url, timeout=30) as resp:
|
|
data = json.loads(resp.read().decode("utf-8"))
|
|
items.extend(data.get("features", []))
|
|
url = None
|
|
for link in data.get("links", []):
|
|
if link.get("rel") == "next":
|
|
url = link.get("href")
|
|
break
|
|
return items
|
|
|
|
|
|
def acquire_swisstopo_data(
|
|
cache_dir: Path, e0: float, n0: float, e1: float, n1: float
|
|
) -> tuple[dict[tuple[int, int], Path], list[Path], list[str]]:
|
|
tr = pyproj.Transformer.from_crs("EPSG:2056", "EPSG:4326", always_xy=True)
|
|
lon0, lat0 = tr.transform(e0 - 20.0, n0 - 20.0)
|
|
lon1, lat1 = tr.transform(e1 + 20.0, n1 + 20.0)
|
|
wgs_bbox = (lon0, lat0, lon1, lat1)
|
|
|
|
# 1. swissALTI3D: pick latest year per 1km tile intersecting [e0, e1] x [n0, n1]
|
|
alti_items = fetch_stac_items(STAC_ALTI_URL, wgs_bbox)
|
|
req_ekm = range(int(math.floor(e0 / 1000.0)), int(math.floor((e1 - 1e-6) / 1000.0)) + 1)
|
|
req_nkm = range(int(math.floor(n0 / 1000.0)), int(math.floor((n1 - 1e-6) / 1000.0)) + 1)
|
|
needed_tiles = {(ek, nk) for ek in req_ekm for nk in req_nkm}
|
|
|
|
best_alti: dict[tuple[int, int], tuple[int, str, str, str]] = {}
|
|
for item in alti_items:
|
|
m = re.match(r"swissalti3d_(\d{4})_(\d{4})-(\d{4})$", item["id"])
|
|
if not m:
|
|
continue
|
|
yr, ek, nk = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
|
if (ek, nk) not in needed_tiles:
|
|
continue
|
|
for asset_name, asset in item.get("assets", {}).items():
|
|
if "_2_2056_5728.tif" in asset_name:
|
|
prev = best_alti.get((ek, nk))
|
|
if prev is None or yr > prev[0]:
|
|
best_alti[(ek, nk)] = (yr, item["id"], asset_name, asset["href"])
|
|
|
|
if len(best_alti) != len(needed_tiles):
|
|
missing = needed_tiles - set(best_alti.keys())
|
|
raise RuntimeError(f"Missing swissALTI3D tiles for bbox: {missing}")
|
|
|
|
tif_paths: dict[tuple[int, int], Path] = {}
|
|
stac_ids: list[str] = []
|
|
for key, (_, item_id, fname, href) in sorted(best_alti.items()):
|
|
tif_paths[key] = download_cached(href, cache_dir / fname)
|
|
stac_ids.append(item_id)
|
|
|
|
# 2. swissBUILDINGS3D 3.0: pick latest per-sheet tiled GDB (skip multi-GB whole-CH monoliths)
|
|
bldg_items = fetch_stac_items(STAC_BLDG_URL, wgs_bbox)
|
|
best_sheets: dict[str, tuple[int, str, str, str]] = {}
|
|
for item in bldg_items:
|
|
m = re.match(r"swissbuildings3d_3_0_(\d{4})_(\d{4}-\d{2})$", item["id"])
|
|
if not m:
|
|
continue
|
|
yr, sheet = int(m.group(1)), m.group(2)
|
|
for asset_name, asset in item.get("assets", {}).items():
|
|
if asset_name.endswith(".gdb.zip"):
|
|
prev = best_sheets.get(sheet)
|
|
if prev is None or yr > prev[0]:
|
|
best_sheets[sheet] = (yr, item["id"], asset_name, asset["href"])
|
|
|
|
if not best_sheets:
|
|
raise RuntimeError("No per-sheet swissBUILDINGS3D 3.0 GDB assets returned from STAC")
|
|
|
|
gdb_paths: list[Path] = []
|
|
for sheet, (_, item_id, fname, href) in sorted(best_sheets.items()):
|
|
zip_path = download_cached(href, cache_dir / fname)
|
|
stac_ids.append(item_id)
|
|
with zipfile.ZipFile(zip_path) as zf:
|
|
gdb_roots = {name.split("/")[0] for name in zf.namelist() if ".gdb/" in name}
|
|
for root in sorted(gdb_roots):
|
|
gdb_dir = cache_dir / root
|
|
if not gdb_dir.exists():
|
|
print(f" [Extract GDB] {fname} -> {root}")
|
|
zf.extractall(cache_dir)
|
|
gdb_paths.append(gdb_dir)
|
|
|
|
return tif_paths, gdb_paths, stac_ids
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# DEM stitching, heightmap resampling & surface albedo synthesis
|
|
# ---------------------------------------------------------------------------
|
|
def sample_mosaic_grid(
|
|
mosaic: np.ndarray, e_origin: float, n_top: float, center_e: float, center_n: float, res: int
|
|
) -> np.ndarray:
|
|
pixel_m = 2.0
|
|
step_m = ARENA_SIZE_M / (res - 1)
|
|
xs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m
|
|
zs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m
|
|
e_grid = center_e + xs
|
|
n_grid = center_n - zs
|
|
col_1d = (e_grid - e_origin) / pixel_m - 0.5
|
|
row_1d = (n_top - n_grid) / pixel_m - 0.5
|
|
row_coords, col_coords = np.meshgrid(row_1d, col_1d, indexing="ij")
|
|
return map_coordinates(mosaic, [row_coords, col_coords], order=1, mode="nearest").astype(np.float32)
|
|
|
|
|
|
def build_heightmap(
|
|
tif_paths: dict[tuple[int, int], Path], center_e: float, center_n: float
|
|
) -> tuple[np.ndarray, np.ndarray, float, float, float]:
|
|
ekms = sorted({k[0] for k in tif_paths})
|
|
nkms = sorted({k[1] for k in tif_paths}, reverse=True) # north-to-south rows
|
|
tile_px = 500
|
|
mosaic = np.zeros((len(nkms) * tile_px, len(ekms) * tile_px), dtype=np.float32)
|
|
|
|
for ni, nk in enumerate(nkms):
|
|
for ei, ek in enumerate(ekms):
|
|
arr = tifffile.imread(str(tif_paths[(ek, nk)]))
|
|
if arr.shape != (tile_px, tile_px):
|
|
raise RuntimeError(f"Unexpected DEM tile shape {arr.shape} in {tif_paths[(ek, nk)]}")
|
|
mosaic[ni * tile_px : (ni + 1) * tile_px, ei * tile_px : (ei + 1) * tile_px] = arr
|
|
|
|
e_origin = ekms[0] * 1000.0
|
|
n_top = (nkms[0] + 1) * 1000.0
|
|
|
|
# Grid coordinates in RustToDust:
|
|
# row iz (0..1024): Z = -1536 + iz * 3.0 (North -> South), N = center_n - Z
|
|
# col ix (0..1024): X = -1536 + ix * 3.0 (West -> East), E = center_e + X
|
|
hm_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, GRID_RES)
|
|
surf_dem_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, SURFACE_TEX_RES)
|
|
|
|
# Anchor valley floor near y = 0m using 5th percentile
|
|
base_elev = round(float(np.percentile(hm_asl, 5.0)), 2)
|
|
hm_rel = (hm_asl - base_elev).astype(np.float32)
|
|
return hm_rel, surf_dem_asl, base_elev, float(hm_rel.min()), float(hm_rel.max())
|
|
|
|
|
|
def acquire_wms_masks(
|
|
cache_dir: Path, e0: float, n0: float, e1: float, n1: float, res: int = SURFACE_TEX_RES
|
|
) -> dict[str, np.ndarray]:
|
|
"""Fetch and cache Swisstopo label-free TLM WMS layers for water, roads, rail, and forest."""
|
|
bbox_key = f"{int(round(e0))}_{int(round(n0))}_{int(round(e1))}_{int(round(n1))}_{res}"
|
|
specs = {
|
|
"tlm_color": ("ch.swisstopo.swisstlm3d-karte-farbe", "FALSE"),
|
|
"roads": ("ch.swisstopo.swisstlm3d-strassen", "TRUE"),
|
|
"rail": ("ch.swisstopo.swisstlm3d-eisenbahnnetz", "TRUE"),
|
|
"forest": ("ch.swisstopo.swisstlm3d-wald", "TRUE"),
|
|
}
|
|
out: dict[str, np.ndarray] = {}
|
|
for key, (layer, transparent) in specs.items():
|
|
dest = cache_dir / f"wms_{key}_{bbox_key}.png"
|
|
if not (dest.exists() and dest.stat().st_size > 0):
|
|
url = (
|
|
f"{WMS_BASE_URL}?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap"
|
|
f"&LAYERS={layer}&STYLES=default&CRS=EPSG:2056"
|
|
f"&BBOX={e0:.1f},{n0:.1f},{e1:.1f},{n1:.1f}"
|
|
f"&WIDTH={res}&HEIGHT={res}&FORMAT=image/png&TRANSPARENT={transparent}"
|
|
)
|
|
print(f" [WMS fetch] {layer} -> {dest.name}")
|
|
req = urllib.request.Request(url, headers={"User-Agent": "RustToDust-SionBaker/1.0"})
|
|
tmp = dest.with_suffix(".png.part")
|
|
with urllib.request.urlopen(req, timeout=45) as resp:
|
|
tmp.write_bytes(resp.read())
|
|
tmp.replace(dest)
|
|
out[key] = imagecodecs.png_decode(dest.read_bytes())
|
|
return out
|
|
|
|
|
|
def rasterize_triangles_xz(tris_list: list[np.ndarray], res: int) -> np.ndarray:
|
|
"""Rasterize 3D (N, 3, 3) triangles projected to (X, Z) onto a (res, res) boolean mask."""
|
|
mask = np.zeros((res, res), dtype=bool)
|
|
if not tris_list:
|
|
return mask
|
|
tris = np.asarray(tris_list, dtype=np.float64)
|
|
scale = (res - 1) / ARENA_SIZE_M
|
|
px = (tris[:, :, 0] + HALF_EXTENT_M) * scale
|
|
pz = (tris[:, :, 2] + HALF_EXTENT_M) * scale
|
|
|
|
for i in range(len(tris)):
|
|
x0, x1, x2 = px[i, 0], px[i, 1], px[i, 2]
|
|
y0, y1, y2 = pz[i, 0], pz[i, 1], pz[i, 2]
|
|
area = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)
|
|
if abs(area) < 0.25:
|
|
continue
|
|
if area < 0.0:
|
|
x1, x2 = x2, x1
|
|
y1, y2 = y2, y1
|
|
ix0 = max(0, int(math.floor(min(x0, x1, x2))))
|
|
ix1 = min(res - 1, int(math.ceil(max(x0, x1, x2))))
|
|
iy0 = max(0, int(math.floor(min(y0, y1, y2))))
|
|
iy1 = min(res - 1, int(math.ceil(max(y0, y1, y2))))
|
|
if ix1 < ix0 or iy1 < iy0:
|
|
continue
|
|
gx = np.arange(ix0, ix1 + 1, dtype=np.float64)[None, :] + 0.5
|
|
gy = np.arange(iy0, iy1 + 1, dtype=np.float64)[:, None] + 0.5
|
|
e0 = (x1 - x0) * (gy - y0) - (y1 - y0) * (gx - x0)
|
|
e1 = (x2 - x1) * (gy - y1) - (y2 - y1) * (gx - x1)
|
|
e2 = (x0 - x2) * (gy - y2) - (y0 - y2) * (gx - x2)
|
|
inside = (e0 >= -0.05) & (e1 >= -0.05) & (e2 >= -0.05)
|
|
mask[iy0 : iy1 + 1, ix0 : ix1 + 1] |= inside
|
|
return mask
|
|
|
|
|
|
def smooth_fbm_2d(res: int, seed: int = 42) -> np.ndarray:
|
|
"""Deterministic multi-octave smooth value noise in [0, 1] without high-frequency PNG-bloating grain."""
|
|
rng = np.random.default_rng(seed)
|
|
acc = np.zeros((res, res), dtype=np.float32)
|
|
weights = [(16, 0.45), (48, 0.30), (128, 0.17), (320, 0.08)]
|
|
for grid_n, w in weights:
|
|
coarse = rng.random((grid_n, grid_n), dtype=np.float32)
|
|
up = zoom(coarse, res / grid_n, order=1)[:res, :res]
|
|
if up.shape != (res, res):
|
|
pad = np.zeros((res, res), dtype=np.float32)
|
|
pad[: up.shape[0], : up.shape[1]] = up
|
|
up = pad
|
|
acc += up * w
|
|
acc = (acc - acc.min()) / max(1e-6, float(acc.max() - acc.min()))
|
|
return acc
|
|
|
|
|
|
def build_terrain_surface_texture(
|
|
dem_asl: np.ndarray,
|
|
base_elev: float,
|
|
wms_masks: dict[str, np.ndarray] | None,
|
|
fp_res_tris: list[np.ndarray],
|
|
fp_ind_tris: list[np.ndarray],
|
|
fp_fort_tris: list[np.ndarray],
|
|
) -> bytes:
|
|
"""
|
|
Synthesize 2048x2048 RGB surface albedo PNG (< 3 MB) combining:
|
|
- Grey alpine limestone cliffs (steep Valere / Tourbillon / hillside slopes)
|
|
- Valley meadows, terraced vineyards & alpine forest slopes
|
|
- Old Town stone plazas, industrial yards, rail ballast & road/bridge network
|
|
- Rhone river & canal glacial teal-blue water tint
|
|
"""
|
|
res = dem_asl.shape[0]
|
|
px_m = ARENA_SIZE_M / (res - 1) # 1.5m/px
|
|
elev_rel = dem_asl - base_elev
|
|
|
|
# DEM slope & aspect (row increases South, col increases East)
|
|
dem_smooth = gaussian_filter(dem_asl, sigma=0.75)
|
|
gy, gx = np.gradient(dem_smooth, px_m)
|
|
slope = np.hypot(gx, gy)
|
|
normal_y = 1.0 / np.sqrt(1.0 + slope * slope)
|
|
|
|
fbm = smooth_fbm_2d(res, seed=2056)
|
|
fbm2 = smooth_fbm_2d(res, seed=1120)
|
|
|
|
# 1. Base valley meadow & hillside terraced vineyards
|
|
# Valley grass -> warm terraced hillside olive/sage
|
|
hill_t = np.clip((elev_rel - 10.0) / 85.0, 0.0, 1.0)
|
|
valley_col = np.array([0.31, 0.36, 0.22], dtype=np.float32)
|
|
hill_col = np.array([0.25, 0.32, 0.17], dtype=np.float32)
|
|
rgb = valley_col * (1.0 - hill_t[..., None]) + hill_col * hill_t[..., None]
|
|
|
|
# Subtle meadow & hillside variation
|
|
rgb += (fbm[..., None] - 0.5) * np.array([0.07, 0.08, 0.05], dtype=np.float32)
|
|
|
|
# Sunny south-facing vineyard terrace contours (gy < 0 means elevation drops going South)
|
|
south_facing = np.clip((-gy - 0.05) / 0.35, 0.0, 1.0)
|
|
vine_band = np.clip((elev_rel - 14.0) / 18.0, 0.0, 1.0) * np.clip((260.0 - elev_rel) / 60.0, 0.0, 1.0)
|
|
vine_slope = np.clip((slope - 0.10) / 0.18, 0.0, 1.0) * np.clip((0.68 - slope) / 0.25, 0.0, 1.0)
|
|
terrace_wave = 0.5 + 0.5 * np.sin(dem_asl * 1.15 + fbm2 * 2.0)
|
|
vine_w = south_facing * vine_band * vine_slope * (0.25 + 0.55 * terrace_wave)
|
|
vine_col = np.array([0.33, 0.36, 0.20], dtype=np.float32)
|
|
rgb = rgb * (1.0 - vine_w[..., None] * 0.65) + vine_col * (vine_w[..., None] * 0.65)
|
|
|
|
# Forest canopy tint from Swisstopo Wald mask (darker alpine pine/oak green)
|
|
if wms_masks and "forest" in wms_masks:
|
|
f_rgba = wms_masks["forest"]
|
|
forest_mask = f_rgba[..., 3] > 60
|
|
forest_soft = gaussian_filter(forest_mask.astype(np.float32), sigma=2.2)
|
|
forest_col = np.array([0.16, 0.23, 0.13], dtype=np.float32) + (fbm2[..., None] - 0.5) * 0.04
|
|
rgb = rgb * (1.0 - forest_soft[..., None] * 0.72) + forest_col * (forest_soft[..., None] * 0.72)
|
|
|
|
# 2. Urban building footprint plazas & yards
|
|
mask_res = rasterize_triangles_xz(fp_res_tris, res)
|
|
mask_ind = rasterize_triangles_xz(fp_ind_tris, res)
|
|
mask_fort = rasterize_triangles_xz(fp_fort_tris, res)
|
|
|
|
# Local building density distinguishes dense Old Town stone plazas from suburban lawns
|
|
bldg_density = gaussian_filter((mask_res | mask_fort).astype(np.float32), sigma=22.0)
|
|
urban_core = np.clip(bldg_density * 5.5, 0.0, 1.0)
|
|
|
|
res_plaza = binary_dilation(mask_res, iterations=7) & (normal_y > 0.87)
|
|
res_soft = gaussian_filter(res_plaza.astype(np.float32), sigma=2.0) * (0.35 + 0.65 * urban_core)
|
|
plaza_col = np.array([0.45, 0.42, 0.37], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.05
|
|
rgb = rgb * (1.0 - res_soft[..., None] * 0.88) + plaza_col * (res_soft[..., None] * 0.88)
|
|
|
|
ind_yard = binary_dilation(mask_ind, iterations=10) & (normal_y > 0.90)
|
|
ind_soft = gaussian_filter(ind_yard.astype(np.float32), sigma=2.0)
|
|
ind_col = np.array([0.36, 0.36, 0.35], dtype=np.float32) + (fbm2[..., None] - 0.5) * 0.04
|
|
rgb = rgb * (1.0 - ind_soft[..., None] * 0.88) + ind_col * (ind_soft[..., None] * 0.88)
|
|
|
|
fort_court = binary_dilation(mask_fort, iterations=5) & (normal_y > 0.82)
|
|
fort_soft = gaussian_filter(fort_court.astype(np.float32), sigma=1.8)
|
|
fort_col = np.array([0.43, 0.40, 0.35], dtype=np.float32)
|
|
rgb = rgb * (1.0 - fort_soft[..., None] * 0.82) + fort_col * (fort_soft[..., None] * 0.82)
|
|
|
|
# 3. Railway yard ballast corridor
|
|
if wms_masks and "rail" in wms_masks:
|
|
rail_alpha = wms_masks["rail"][..., 3] > 50
|
|
rail_corridor = binary_dilation(rail_alpha, iterations=4)
|
|
rail_soft = gaussian_filter(rail_corridor.astype(np.float32), sigma=1.2)
|
|
rail_col = np.array([0.33, 0.30, 0.27], dtype=np.float32)
|
|
rgb = rgb * (1.0 - rail_soft[..., None] * 0.85) + rail_col * (rail_soft[..., None] * 0.85)
|
|
|
|
# 4. Steep alpine limestone cliff faces (Valere / Tourbillon / escarpments)
|
|
# Applied after ground lawns/plazas so sheer cliffs always expose limestone rock!
|
|
cliff_t = np.clip((0.88 - normal_y) / (0.88 - 0.72), 0.0, 1.0)
|
|
strata = 0.5 + 0.5 * np.sin(dem_asl * 0.85 + fbm * 3.0)
|
|
cliff_col = (
|
|
np.array([0.48, 0.46, 0.42], dtype=np.float32)
|
|
+ (strata[..., None] - 0.5) * np.array([0.07, 0.07, 0.06], dtype=np.float32)
|
|
+ (fbm2[..., None] - 0.5) * 0.05
|
|
)
|
|
rgb = rgb * (1.0 - cliff_t[..., None]) + cliff_col * cliff_t[..., None]
|
|
|
|
# 5. Rhone river, Borgne tributary & canals (gravel banks + glacial teal water)
|
|
water_mask = np.zeros((res, res), dtype=bool)
|
|
if wms_masks and "tlm_color" in wms_masks:
|
|
c_rgb = wms_masks["tlm_color"][..., :3].astype(np.int16)
|
|
cyan = (c_rgb[..., 2] - c_rgb[..., 0] > 55) & (c_rgb[..., 2] > 200) & (c_rgb[..., 1] > 170) & (c_rgb[..., 0] < 180)
|
|
# Heal blue river name text gaps inside the river polygon
|
|
water_mask = binary_closing(cyan, structure=np.ones((9, 9)))
|
|
water_mask &= elev_rel < 25.0
|
|
else:
|
|
# Pure-DEM fallback for leveed river channels
|
|
r_px = 60
|
|
n_max = maximum_filter1d(dem_asl, size=r_px, axis=0, origin=-(r_px // 2))
|
|
s_max = maximum_filter1d(dem_asl, size=r_px, axis=0, origin=(r_px // 2))
|
|
w_max = maximum_filter1d(dem_asl, size=r_px, axis=1, origin=-(r_px // 2))
|
|
e_max = maximum_filter1d(dem_asl, size=r_px, axis=1, origin=(r_px // 2))
|
|
trough = np.maximum(np.minimum(n_max, s_max) - dem_asl, np.minimum(w_max, e_max) - dem_asl)
|
|
water_mask = (trough > 3.2) & (slope < 0.03) & (elev_rel < 10.0)
|
|
water_mask = binary_closing(binary_opening(water_mask, structure=np.ones((3, 3))), structure=np.ones((7, 7)))
|
|
|
|
if np.any(water_mask):
|
|
bank_mask = binary_dilation(water_mask, iterations=4) & (~water_mask)
|
|
bank_soft = gaussian_filter(bank_mask.astype(np.float32), sigma=1.2)
|
|
bank_col = np.array([0.44, 0.42, 0.37], dtype=np.float32)
|
|
rgb = rgb * (1.0 - bank_soft[..., None] * 0.80) + bank_col * (bank_soft[..., None] * 0.80)
|
|
|
|
water_soft = gaussian_filter(water_mask.astype(np.float32), sigma=1.0)
|
|
water_col = np.array([0.13, 0.27, 0.34], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.03
|
|
rgb = rgb * (1.0 - water_soft[..., None] * 0.96) + water_col * (water_soft[..., None] * 0.96)
|
|
|
|
# 6. Roads, highway A9 & bridges (drawn after water so bridges span the Rhone!)
|
|
if wms_masks and "roads" in wms_masks:
|
|
r_rgba = wms_masks["roads"]
|
|
r_rgb = r_rgba[..., :3].astype(np.int16)
|
|
r_alpha = r_rgba[..., 3] > 80
|
|
# Major arterial / highway (orange/red/yellow in TLM roads) vs local streets
|
|
is_major = r_alpha & ((r_rgb[..., 0] - r_rgb[..., 2]) > 45)
|
|
is_minor = r_alpha & (~is_major)
|
|
minor_soft = gaussian_filter(is_minor.astype(np.float32), sigma=0.6)
|
|
major_soft = gaussian_filter(binary_dilation(is_major, iterations=1).astype(np.float32), sigma=0.7)
|
|
street_col = np.array([0.35, 0.34, 0.32], dtype=np.float32)
|
|
highway_col = np.array([0.25, 0.25, 0.26], dtype=np.float32)
|
|
rgb = rgb * (1.0 - minor_soft[..., None] * 0.72) + street_col * (minor_soft[..., None] * 0.72)
|
|
rgb = rgb * (1.0 - major_soft[..., None] * 0.88) + highway_col * (major_soft[..., None] * 0.88)
|
|
|
|
# Darken slightly under exact building footprints for subtle ambient grounding
|
|
bldg_under = (mask_res | mask_ind | mask_fort) & (normal_y > 0.75)
|
|
rgb[bldg_under] *= 0.88
|
|
|
|
rgb_u8 = np.clip(np.round(rgb * 255.0), 0, 255).astype(np.uint8)
|
|
png_bytes = imagecodecs.png_encode(rgb_u8, level=9)
|
|
if len(png_bytes) >= MAX_SURFACE_PNG_BYTES:
|
|
# Mild bit-depth quantization (7-bit per channel) preserves smooth gradients while halving PNG size
|
|
rgb_u8 = (rgb_u8 & 0xFE)
|
|
png_bytes = imagecodecs.png_encode(rgb_u8, level=9)
|
|
if len(png_bytes) >= MAX_SURFACE_PNG_BYTES:
|
|
rgb_u8 = (rgb_u8 & 0xFC)
|
|
png_bytes = imagecodecs.png_encode(rgb_u8, level=9)
|
|
return png_bytes
|
|
|
|
|
|
def sample_heightmap(hm: np.ndarray, x: np.ndarray | float, z: np.ndarray | float) -> np.ndarray | float:
|
|
fx = np.clip((np.asarray(x) + HALF_EXTENT_M) / CELL_SIZE_M, 0.0, GRID_RES - 1.00001)
|
|
fz = np.clip((np.asarray(z) + HALF_EXTENT_M) / CELL_SIZE_M, 0.0, GRID_RES - 1.00001)
|
|
ix = np.floor(fx).astype(np.int32)
|
|
iz = np.floor(fz).astype(np.int32)
|
|
tx = fx - ix
|
|
tz = fz - iz
|
|
h00 = hm[iz, ix]
|
|
h10 = hm[iz, ix + 1]
|
|
h01 = hm[iz + 1, ix]
|
|
h11 = hm[iz + 1, ix + 1]
|
|
return (h00 * (1.0 - tx) + h10 * tx) * (1.0 - tz) + (h01 * (1.0 - tx) + h11 * tx) * tz
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Coordinate conversion & geometry utilities
|
|
# ---------------------------------------------------------------------------
|
|
def enz_to_rtd(pts: np.ndarray, center_e: float, center_n: float, base_elev: float) -> np.ndarray:
|
|
"""EPSG:2056 (E, N, Z) -> RustToDust right-handed glTF (X=E-cE, Y=Z-base, Z=-(N-cN)). det=+1."""
|
|
out = np.empty_like(pts, dtype=np.float64)
|
|
out[:, 0] = pts[:, 0] - center_e
|
|
out[:, 1] = pts[:, 2] - base_elev
|
|
out[:, 2] = -(pts[:, 1] - center_n)
|
|
return out
|
|
|
|
|
|
def newell_normal(pts: np.ndarray) -> np.ndarray:
|
|
p0 = pts
|
|
p1 = np.roll(pts, -1, axis=0)
|
|
n = np.array(
|
|
[
|
|
np.sum((p0[:, 1] - p1[:, 1]) * (p0[:, 2] + p1[:, 2])),
|
|
np.sum((p0[:, 2] - p1[:, 2]) * (p0[:, 0] + p1[:, 0])),
|
|
np.sum((p0[:, 0] - p1[:, 0]) * (p0[:, 1] + p1[:, 1])),
|
|
],
|
|
dtype=np.float64,
|
|
)
|
|
length = float(np.linalg.norm(n))
|
|
return n / length if length > 1e-12 else np.array([0.0, 1.0, 0.0], dtype=np.float64)
|
|
|
|
|
|
def triangulate_polygon_3d(pts: np.ndarray) -> np.ndarray:
|
|
"""Triangulate a 3D simple polygon (N, 3) into (M, 3, 3) triangles preserving winding."""
|
|
n_pts = len(pts)
|
|
if n_pts == 3:
|
|
return pts[None, :, :]
|
|
if n_pts == 4:
|
|
# Check convexity via normal consistency, split along shorter diagonal
|
|
d02 = np.sum((pts[2] - pts[0]) ** 2)
|
|
d13 = np.sum((pts[3] - pts[1]) ** 2)
|
|
if d02 <= d13:
|
|
return np.stack([pts[[0, 1, 2]], pts[[0, 2, 3]]], axis=0)
|
|
return np.stack([pts[[1, 2, 3]], pts[[1, 3, 0]]], axis=0)
|
|
|
|
# Project onto dominant plane for ear-clipping
|
|
normal = newell_normal(pts)
|
|
ref = np.array([1.0, 0.0, 0.0]) if abs(normal[0]) < 0.8 else np.array([0.0, 1.0, 0.0])
|
|
u = np.cross(normal, ref)
|
|
u /= np.linalg.norm(u)
|
|
v = np.cross(normal, u)
|
|
pts2 = np.column_stack([pts @ u, pts @ v])
|
|
|
|
# Ensure CCW in 2D for ear-clipping test, track if flipped
|
|
area2 = 0.0
|
|
for i in range(n_pts):
|
|
j = (i + 1) % n_pts
|
|
area2 += pts2[i, 0] * pts2[j, 1] - pts2[j, 0] * pts2[i, 1]
|
|
order = list(range(n_pts))
|
|
if area2 < 0:
|
|
order.reverse()
|
|
|
|
tris_idx: list[tuple[int, int, int]] = []
|
|
idx = list(order)
|
|
guard = 0
|
|
while len(idx) > 3 and guard < n_pts * n_pts:
|
|
guard += 1
|
|
ear_found = False
|
|
m = len(idx)
|
|
for k in range(m):
|
|
ia, ib, ic = idx[(k - 1) % m], idx[k], idx[(k + 1) % m]
|
|
a, b, c = pts2[ia], pts2[ib], pts2[ic]
|
|
cross = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
|
|
if cross <= 1e-10:
|
|
continue
|
|
# Check if any other point lies inside triangle (a, b, c)
|
|
inside = False
|
|
for o in idx:
|
|
if o in (ia, ib, ic):
|
|
continue
|
|
p = pts2[o]
|
|
c1 = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
|
|
c2 = (c[0] - b[0]) * (p[1] - b[1]) - (c[1] - b[1]) * (p[0] - b[0])
|
|
c3 = (a[0] - c[0]) * (p[1] - c[1]) - (a[1] - c[1]) * (p[0] - c[0])
|
|
if c1 >= -1e-9 and c2 >= -1e-9 and c3 >= -1e-9:
|
|
inside = True
|
|
break
|
|
if not inside:
|
|
tris_idx.append((ia, ib, ic) if area2 >= 0 else (ia, ic, ib))
|
|
del idx[k]
|
|
ear_found = True
|
|
break
|
|
if not ear_found:
|
|
break
|
|
if len(idx) == 3:
|
|
ia, ib, ic = idx
|
|
tris_idx.append((ia, ib, ic) if area2 >= 0 else (ia, ic, ib))
|
|
if not tris_idx:
|
|
# Fallback fan
|
|
tris_idx = [(0, k, k + 1) for k in range(1, n_pts - 1)]
|
|
return pts[np.array(tris_idx, dtype=np.int32)]
|
|
|
|
|
|
def rays_inside_solid(
|
|
points: np.ndarray, normals: np.ndarray, solid_tris: np.ndarray, eps: float = 0.03
|
|
) -> np.ndarray:
|
|
"""
|
|
For each query (point + eps*normal), test 3 rays against closed solid_tris (K,3,3) via Moller-Trumbore.
|
|
Returns boolean mask: True if point+eps*normal is INSIDE solid (meaning normal points INWARD and must flip).
|
|
"""
|
|
if len(solid_tris) < 4 or len(points) == 0:
|
|
return np.zeros(len(points), dtype=bool)
|
|
v0 = solid_tris[:, 0, :] # (K, 3)
|
|
e1 = solid_tris[:, 1, :] - v0
|
|
e2 = solid_tris[:, 2, :] - v0
|
|
origins = points + normals * eps # (M, 3)
|
|
|
|
ray_dirs = np.array(
|
|
[
|
|
[0.37139068, 0.21899573, 0.90226797],
|
|
[-0.81239412, 0.41502134, 0.40984511],
|
|
[0.29510421, -0.88142173, 0.36901342],
|
|
],
|
|
dtype=np.float64,
|
|
)
|
|
|
|
votes = np.zeros(len(points), dtype=np.int32)
|
|
# Process in chunks to keep peak memory tiny even for Basilique de Valere
|
|
chunk = 256
|
|
for d in ray_dirs:
|
|
pvec = np.cross(d[None, :], e2) # (K, 3)
|
|
det = np.sum(e1 * pvec, axis=1) # (K,)
|
|
valid = np.abs(det) > 1e-10
|
|
inv_det = np.zeros_like(det)
|
|
inv_det[valid] = 1.0 / det[valid]
|
|
q_e1 = e1[valid]
|
|
q_e2 = e2[valid]
|
|
q_v0 = v0[valid]
|
|
q_pvec = pvec[valid]
|
|
q_inv = inv_det[valid]
|
|
if len(q_v0) == 0:
|
|
continue
|
|
for s in range(0, len(origins), chunk):
|
|
orig = origins[s : s + chunk] # (C, 3)
|
|
tvec = orig[:, None, :] - q_v0[None, :, :] # (C, K', 3)
|
|
u = np.sum(tvec * q_pvec[None, :, :], axis=2) * q_inv[None, :]
|
|
m = (u >= 0.0) & (u <= 1.0)
|
|
qvec = np.cross(tvec, q_e1[None, :, :])
|
|
v = np.sum(d[None, None, :] * qvec, axis=2) * q_inv[None, :]
|
|
m &= (v >= 0.0) & (u + v <= 1.0)
|
|
t = np.sum(q_e2[None, :, :] * qvec, axis=2) * q_inv[None, :]
|
|
m &= t > 1e-5
|
|
hits = m.sum(axis=1)
|
|
votes[s : s + chunk] += (hits % 2).astype(np.int32)
|
|
return votes >= 2
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Building extraction, classification, orientation & skirt generation
|
|
# ---------------------------------------------------------------------------
|
|
def classify_building(
|
|
objektart: str, name: str, pts_enz: np.ndarray, roof_faces_rtd: list[np.ndarray]
|
|
) -> str:
|
|
nl = name.lower()
|
|
if objektart in ("Sakrales Gebaeude", "Kapelle", "Sakraler Turm", "Mauer gross"):
|
|
return "fortress"
|
|
if any(k in nl for k in ("valère", "valere", "tourbillon", "basilique", "château", "chateau", "cathédral")):
|
|
return "fortress"
|
|
# Fortress hilltop zone (Valere & Tourbillon ridges)
|
|
ce = float(pts_enz[:, 0].mean())
|
|
cn = float(pts_enz[:, 1].mean())
|
|
min_z = float(pts_enz[:, 2].min())
|
|
if 2594180.0 <= ce <= 2594650.0 and 1120180.0 <= cn <= 1120660.0 and min_z > 545.0:
|
|
return "fortress"
|
|
|
|
if objektart in ("Hochhaus", "Offenes Gebaeude", "Flugdach", "Unterirdisches Gebaeude", "Im Bau", "Lagertank", "Treibhaus"):
|
|
return "industrial"
|
|
|
|
# Large flat-roofed industrial/commercial blocks in the valley flats
|
|
dx = float(pts_enz[:, 0].max() - pts_enz[:, 0].min())
|
|
dn = float(pts_enz[:, 1].max() - pts_enz[:, 1].min())
|
|
area_box = dx * dn
|
|
if area_box > 750.0 and min_z < 508.0 and roof_faces_rtd:
|
|
# Weighted average roof slope
|
|
flat_area = 0.0
|
|
total_area = 0.0
|
|
for rf in roof_faces_rtd:
|
|
n = newell_normal(rf)
|
|
a = 0.5 * float(np.linalg.norm(np.cross(rf[1] - rf[0], rf[-1] - rf[0])))
|
|
total_area += a
|
|
if abs(n[1]) > 0.985: # < ~10 deg
|
|
flat_area += a
|
|
if total_area > 1.0 and (flat_area / total_area) > 0.75:
|
|
return "industrial"
|
|
|
|
return "residential"
|
|
|
|
|
|
def orient_faces_outward(
|
|
faces_rtd: list[np.ndarray],
|
|
solid_tris_rtd: np.ndarray | None,
|
|
layer_kind: str,
|
|
bldg_center_rtd: np.ndarray,
|
|
) -> list[np.ndarray]:
|
|
if not faces_rtd:
|
|
return []
|
|
centers = np.array([f.mean(axis=0) for f in faces_rtd], dtype=np.float64)
|
|
normals = np.array([newell_normal(f) for f in faces_rtd], dtype=np.float64)
|
|
|
|
if layer_kind == "Roof":
|
|
# Roof shells are open surfaces: non-vertical roof slopes must face UP (+Y).
|
|
flip = normals[:, 1] < -0.05
|
|
# Near-vertical dormer cheeks/fascia: face away from building horizontal center
|
|
vert = np.abs(normals[:, 1]) <= 0.05
|
|
if np.any(vert):
|
|
d_xz = centers[vert][:, [0, 2]] - bldg_center_rtd[[0, 2]]
|
|
dot = np.sum(d_xz * normals[vert][:, [0, 2]], axis=1)
|
|
flip[vert] = dot < 0
|
|
elif layer_kind == "Floor":
|
|
# Floor caps face DOWN (-Y) unless steep step risers
|
|
flip = normals[:, 1] > 0.05
|
|
vert = np.abs(normals[:, 1]) <= 0.05
|
|
if np.any(vert) and solid_tris_rtd is not None and len(solid_tris_rtd) >= 4:
|
|
flip[vert] = rays_inside_solid(centers[vert], normals[vert], solid_tris_rtd, eps=0.025)
|
|
else:
|
|
# Wall faces: exact 3D solid parity against Building_solid when closed, else centroid fallback
|
|
if solid_tris_rtd is not None and len(solid_tris_rtd) >= 8:
|
|
flip = rays_inside_solid(centers, normals, solid_tris_rtd, eps=0.025)
|
|
else:
|
|
d_xz = centers[:, [0, 2]] - bldg_center_rtd[[0, 2]]
|
|
flip = np.sum(d_xz * normals[:, [0, 2]], axis=1) < 0
|
|
|
|
oriented = []
|
|
for i, f in enumerate(faces_rtd):
|
|
oriented.append(f[::-1].copy() if flip[i] else f)
|
|
return oriented
|
|
|
|
|
|
def build_foundation_skirt_tris(
|
|
wall_tris: np.ndarray,
|
|
floor_faces: list[np.ndarray],
|
|
hm: np.ndarray,
|
|
min_y: float,
|
|
simplify_tol: float = 0.0,
|
|
) -> np.ndarray:
|
|
"""
|
|
Build -4.0m downward perimeter skirt quads from the building's base footprint / bottom wall edges
|
|
so no building floats on steep terrain slopes.
|
|
"""
|
|
if len(wall_tris) == 0:
|
|
return np.zeros((0, 3, 3), dtype=np.float64)
|
|
|
|
# Sample terrain height across the building's XZ extent (corners + center)
|
|
pts_all = wall_tris.reshape(-1, 3)
|
|
x0, z0 = float(pts_all[:, 0].min()), float(pts_all[:, 2].min())
|
|
x1, z1 = float(pts_all[:, 0].max()), float(pts_all[:, 2].max())
|
|
gx = np.linspace(x0, x1, 5)
|
|
gz = np.linspace(z0, z1, 5)
|
|
mx, mz = np.meshgrid(gx, gz)
|
|
terrain_vals = sample_heightmap(hm, mx, mz)
|
|
terrain_min_y = float(np.min(terrain_vals))
|
|
# If building base already sits >= 0.45m below the lowest terrain sample across its footprint,
|
|
# no downward skirt is needed.
|
|
if min_y <= terrain_min_y - 0.45:
|
|
return np.zeros((0, 3, 3), dtype=np.float64)
|
|
skirt_bottom_y = min(min_y, terrain_min_y) - SKIRT_DEPTH_M
|
|
|
|
skirt_tris: list[np.ndarray] = []
|
|
|
|
# Primary method: extrude outer boundary of Floor polygons (projected to XZ, matching floor edge Y)
|
|
if floor_faces:
|
|
polys_2d = []
|
|
floor_verts = []
|
|
for ff in floor_faces:
|
|
floor_verts.append(ff)
|
|
p2 = Polygon(ff[:, [0, 2]])
|
|
if not p2.is_valid:
|
|
p2 = p2.buffer(0)
|
|
if not p2.is_empty and p2.area > 0.05:
|
|
polys_2d.append(p2)
|
|
if polys_2d:
|
|
fv = np.vstack(floor_verts)
|
|
merged = unary_union(polys_2d)
|
|
geoms = list(merged.geoms) if hasattr(merged, "geoms") else [merged]
|
|
for poly in geoms:
|
|
if not isinstance(poly, Polygon) or poly.is_empty:
|
|
continue
|
|
if simplify_tol > 0.0:
|
|
poly = poly.simplify(simplify_tol, preserve_topology=True)
|
|
if not isinstance(poly, Polygon) or poly.is_empty:
|
|
continue
|
|
# Ensure exterior ring is CCW in (X, Z) -> in right-handed (X, Y, Z),
|
|
# wait: for vertical wall from p0->p1 down to bottom, if cross(p1-p0, down) points OUTWARD:
|
|
# let tangent t = (dx, 0, dz), down = (0, -1, 0).
|
|
# t x down = (dz, 0, -dx). In (X, Z), (dz, -dx) is right-hand normal to (dx, dz)!
|
|
# A CCW polygon in (X, Z) has interior on LEFT and exterior on RIGHT (+dz, -dx)!
|
|
ring = shapely.geometry.polygon.orient(poly, sign=1.0).exterior.coords
|
|
coords = list(ring)
|
|
for k in range(len(coords) - 1):
|
|
ax, az = coords[k]
|
|
bx, bz = coords[k + 1]
|
|
if (ax - bx) ** 2 + (az - bz) ** 2 < 1e-4:
|
|
continue
|
|
# Nearest floor vertex Y so stepped hillside floors anchor seamlessly
|
|
da = (fv[:, 0] - ax) ** 2 + (fv[:, 2] - az) ** 2
|
|
db = (fv[:, 0] - bx) ** 2 + (fv[:, 2] - bz) ** 2
|
|
ya = float(fv[int(np.argmin(da)), 1]) + 0.05
|
|
yb = float(fv[int(np.argmin(db)), 1]) + 0.05
|
|
p0 = np.array([ax, ya, az])
|
|
p1 = np.array([bx, yb, bz])
|
|
p0b = np.array([ax, skirt_bottom_y, az])
|
|
p1b = np.array([bx, skirt_bottom_y, bz])
|
|
# Outward normal: cross(p1-p0, p0b-p0) = (dx, dy, dz) x (0, -H, 0) = (dz*H, 0, -dx*H)
|
|
skirt_tris.append(np.stack([p0, p1, p1b], axis=0))
|
|
skirt_tris.append(np.stack([p0, p1b, p0b], axis=0))
|
|
|
|
# Fallback for Floor-less structures (e.g. Mauer gross retaining walls):
|
|
# extrude lowest boundary edges of wall_tris straight down
|
|
if not skirt_tris:
|
|
# Quantize vertices to 2mm to match directed edges
|
|
def qkey(v: np.ndarray) -> tuple[int, int, int]:
|
|
return (int(round(v[0] * 500)), int(round(v[1] * 500)), int(round(v[2] * 500)))
|
|
|
|
directed: dict[tuple[tuple[int, int, int], tuple[int, int, int]], tuple[np.ndarray, np.ndarray]] = {}
|
|
for tri in wall_tris:
|
|
for e in ((0, 1), (1, 2), (2, 0)):
|
|
va, vb = tri[e[0]], tri[e[1]]
|
|
ka, kb = qkey(va), qkey(vb)
|
|
if (kb, ka) in directed:
|
|
del directed[(kb, ka)]
|
|
else:
|
|
directed[(ka, kb)] = (va, vb)
|
|
y_thresh = min_y + 1.5
|
|
for va, vb in directed.values():
|
|
if va[1] <= y_thresh and vb[1] <= y_thresh and ((va[0] - vb[0]) ** 2 + (va[2] - vb[2]) ** 2) > 0.04:
|
|
# Wall triangle has (va -> vb) on its boundary; in an outward-wound wall, bottom edge runs
|
|
# left-to-right when viewed from outside -> (va -> vb) x down points INWARD, so reverse!
|
|
p0, p1 = vb, va
|
|
p0b = np.array([p0[0], skirt_bottom_y, p0[2]])
|
|
p1b = np.array([p1[0], skirt_bottom_y, p1[2]])
|
|
skirt_tris.append(np.stack([p0, p1, p1b], axis=0))
|
|
skirt_tris.append(np.stack([p0, p1b, p0b], axis=0))
|
|
|
|
return np.array(skirt_tris, dtype=np.float64) if skirt_tris else np.zeros((0, 3, 3), dtype=np.float64)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Procedural LOD1 generator (from semantic LOD2 Wall & Roof faces)
|
|
# ---------------------------------------------------------------------------
|
|
def append_box_face_outward(
|
|
out_tris: list[np.ndarray],
|
|
origin: np.ndarray,
|
|
u_axis: np.ndarray,
|
|
v_axis: np.ndarray,
|
|
n_axis: np.ndarray,
|
|
u0: float,
|
|
u1: float,
|
|
v0: float,
|
|
v1: float,
|
|
d0: float,
|
|
d1: float,
|
|
include_back: bool = False,
|
|
) -> None:
|
|
"""Append an axis-aligned prism in local (u, v, n) frame with outward CCW triangles."""
|
|
def pt(u: float, v: float, d: float) -> np.ndarray:
|
|
return origin + u * u_axis + v * v_axis + d * n_axis
|
|
|
|
p000, p100, p110, p010 = pt(u0, v0, d0), pt(u1, v0, d0), pt(u1, v1, d0), pt(u0, v1, d0)
|
|
p001, p101, p111, p011 = pt(u0, v0, d1), pt(u1, v0, d1), pt(u1, v1, d1), pt(u0, v1, d1)
|
|
# Front (+n)
|
|
out_tris.append(np.stack([p001, p101, p111], axis=0))
|
|
out_tris.append(np.stack([p001, p111, p011], axis=0))
|
|
if include_back:
|
|
out_tris.append(np.stack([p000, p110, p100], axis=0))
|
|
out_tris.append(np.stack([p000, p010, p110], axis=0))
|
|
# Left (-u), Right (+u), Bottom (-v), Top (+v)
|
|
out_tris.append(np.stack([p000, p001, p011], axis=0))
|
|
out_tris.append(np.stack([p000, p011, p010], axis=0))
|
|
out_tris.append(np.stack([p101, p100, p110], axis=0))
|
|
out_tris.append(np.stack([p101, p110, p111], axis=0))
|
|
out_tris.append(np.stack([p000, p100, p101], axis=0))
|
|
out_tris.append(np.stack([p000, p101, p001], axis=0))
|
|
out_tris.append(np.stack([p011, p111, p110], axis=0))
|
|
out_tris.append(np.stack([p011, p110, p010], axis=0))
|
|
|
|
|
|
def append_lean_ledge(
|
|
out_tris: list[np.ndarray],
|
|
origin: np.ndarray,
|
|
u_axis: np.ndarray,
|
|
v_axis: np.ndarray,
|
|
n_axis: np.ndarray,
|
|
u0: float,
|
|
u1: float,
|
|
v0: float,
|
|
v1: float,
|
|
depth: float,
|
|
top_bevel: bool = True,
|
|
) -> None:
|
|
"""Append a lean 4-tri architectural ledge (front face + top or bottom bevel)."""
|
|
def pt(u: float, v: float, d: float) -> np.ndarray:
|
|
return origin + u * u_axis + v * v_axis + d * n_axis
|
|
|
|
f00, f10, f11, f01 = pt(u0, v0, depth), pt(u1, v0, depth), pt(u1, v1, depth), pt(u0, v1, depth)
|
|
out_tris.append(np.stack([f00, f10, f11], axis=0))
|
|
out_tris.append(np.stack([f00, f11, f01], axis=0))
|
|
if top_bevel:
|
|
b01, b11 = pt(u0, v1, 0.0), pt(u1, v1, 0.0)
|
|
out_tris.append(np.stack([f01, f11, b11], axis=0))
|
|
out_tris.append(np.stack([f01, b11, b01], axis=0))
|
|
else:
|
|
b00, b10 = pt(u0, v0, 0.0), pt(u1, v0, 0.0)
|
|
out_tris.append(np.stack([b00, b10, f10], axis=0))
|
|
out_tris.append(np.stack([b00, f10, f00], axis=0))
|
|
|
|
|
|
def append_quad_outward(
|
|
out_tris: list[np.ndarray],
|
|
origin: np.ndarray,
|
|
u_axis: np.ndarray,
|
|
v_axis: np.ndarray,
|
|
n_axis: np.ndarray,
|
|
u0: float,
|
|
u1: float,
|
|
v0: float,
|
|
v1: float,
|
|
d: float,
|
|
) -> None:
|
|
p00 = origin + u0 * u_axis + v0 * v_axis + d * n_axis
|
|
p10 = origin + u1 * u_axis + v0 * v_axis + d * n_axis
|
|
p11 = origin + u1 * u_axis + v1 * v_axis + d * n_axis
|
|
p01 = origin + u0 * u_axis + v1 * v_axis + d * n_axis
|
|
out_tris.append(np.stack([p00, p10, p11], axis=0))
|
|
out_tris.append(np.stack([p00, p11, p01], axis=0))
|
|
|
|
|
|
def merge_coplanar_faces(
|
|
faces: list[np.ndarray], n_quant: float = 40.0, d_quant: float = 5.0, min_area: float = 0.2
|
|
) -> list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Polygon]]:
|
|
"""
|
|
Merge coplanar connected faces into clean planar 2D shapely polygons with local (origin, u_axis, v_axis, n_axis).
|
|
Returns list of (origin, u_axis, v_axis, n_axis, poly_2d).
|
|
"""
|
|
if not faces:
|
|
return []
|
|
# Quantize plane key: normal rounded + plane offset d
|
|
groups: dict[tuple[int, int, int, int], list[tuple[np.ndarray, np.ndarray]]] = defaultdict(list)
|
|
for f in faces:
|
|
n = newell_normal(f)
|
|
d = float(np.dot(n, f[0]))
|
|
key = (
|
|
int(round(n[0] * n_quant)),
|
|
int(round(n[1] * n_quant)),
|
|
int(round(n[2] * n_quant)),
|
|
int(round(d * d_quant)),
|
|
)
|
|
groups[key].append((f, n))
|
|
|
|
merged_planes = []
|
|
up = np.array([0.0, 1.0, 0.0], dtype=np.float64)
|
|
for items in groups.values():
|
|
n_avg = np.mean([it[1] for it in items], axis=0)
|
|
ln = float(np.linalg.norm(n_avg))
|
|
if ln < 1e-8:
|
|
continue
|
|
n_axis = n_avg / ln
|
|
origin = items[0][0][0]
|
|
if abs(n_axis[1]) < 0.9:
|
|
u_axis = np.cross(up, n_axis)
|
|
u_axis /= np.linalg.norm(u_axis)
|
|
v_axis = np.cross(n_axis, u_axis)
|
|
else:
|
|
u_axis = np.cross(np.array([0.0, 0.0, -1.0]), n_axis)
|
|
u_axis /= np.linalg.norm(u_axis)
|
|
v_axis = np.cross(n_axis, u_axis)
|
|
|
|
polys = []
|
|
for f, _ in items:
|
|
rel = f - origin
|
|
pts2 = np.column_stack([rel @ u_axis, rel @ v_axis])
|
|
p = Polygon(pts2)
|
|
if not p.is_valid:
|
|
p = p.buffer(0)
|
|
if not p.is_empty and p.area > 0.02:
|
|
polys.append(p)
|
|
if not polys:
|
|
continue
|
|
u = unary_union(polys)
|
|
geoms = list(u.geoms) if hasattr(u, "geoms") else [u]
|
|
for g in geoms:
|
|
if isinstance(g, Polygon) and g.area > min_area:
|
|
merged_planes.append((origin, u_axis, v_axis, n_axis, g))
|
|
return merged_planes
|
|
|
|
|
|
def triangulate_planar_polygon(
|
|
origin: np.ndarray,
|
|
u_axis: np.ndarray,
|
|
v_axis: np.ndarray,
|
|
poly: Polygon,
|
|
simplify_tol: float = 0.08,
|
|
) -> list[np.ndarray]:
|
|
"""Triangulate a 2D shapely Polygon (with holes) in (u, v) and lift to 3D with +n_axis winding."""
|
|
use_tol = simplify_tol if (simplify_tol > 0.0 and poly.area >= 1.0 and len(poly.exterior.coords) > 4) else 0.0
|
|
p = poly.simplify(use_tol, preserve_topology=True) if use_tol > 0.0 else poly
|
|
if p.is_empty or p.area < 0.05:
|
|
p = poly
|
|
geoms = list(p.geoms) if hasattr(p, "geoms") else [p]
|
|
tris_3d: list[np.ndarray] = []
|
|
for g in geoms:
|
|
if not isinstance(g, Polygon) or g.is_empty or g.area < 0.02:
|
|
continue
|
|
cdt = shapely.constrained_delaunay_triangles(g)
|
|
for tri_poly in cdt.geoms:
|
|
coords = list(tri_poly.exterior.coords)
|
|
if len(coords) < 4:
|
|
continue
|
|
a, b, c = coords[0], coords[1], coords[2]
|
|
if (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) < 0.0:
|
|
b, c = c, b
|
|
p0 = origin + a[0] * u_axis + a[1] * v_axis
|
|
p1 = origin + b[0] * u_axis + b[1] * v_axis
|
|
p2 = origin + c[0] * u_axis + c[1] * v_axis
|
|
tris_3d.append(np.stack([p0, p1, p2], axis=0))
|
|
return tris_3d
|
|
|
|
|
|
def prepare_lod1_building(
|
|
bldg_uuid: str,
|
|
arch_style: str,
|
|
objektart: str,
|
|
in_core: bool,
|
|
wall_faces: list[np.ndarray],
|
|
roof_faces: list[np.ndarray],
|
|
wall_tris_raw: np.ndarray,
|
|
roof_tris_raw: np.ndarray,
|
|
skirt_tris_simp: np.ndarray,
|
|
) -> tuple:
|
|
"""Precompute simplified coplanar planes, clean LOD2/COL & LOD1 shells, and roof trim once per building."""
|
|
if arch_style == "fortress":
|
|
wall_planes = merge_coplanar_faces(wall_faces, n_quant=40.0, d_quant=5.0, min_area=0.2)
|
|
roof_planes = merge_coplanar_faces(roof_faces, n_quant=40.0, d_quant=5.0, min_area=0.2)
|
|
l1_wtol, l1_rtol = 0.08, 0.06
|
|
l2_wtol, l2_rtol, l2_min = 0.08, 0.06, 0.2
|
|
else:
|
|
wall_planes = merge_coplanar_faces(wall_faces, n_quant=14.0, d_quant=2.0, min_area=0.8)
|
|
roof_planes = merge_coplanar_faces(roof_faces, n_quant=20.0, d_quant=3.0, min_area=0.6)
|
|
l1_wtol, l1_rtol = 0.38, 0.28
|
|
l2_wtol, l2_rtol, l2_min = 0.78, 0.58, 1.6
|
|
|
|
lod1_wall_tris: list[np.ndarray] = []
|
|
lod2_wall_tris: list[np.ndarray] = []
|
|
if wall_planes:
|
|
for origin, u_axis, v_axis, _, poly in wall_planes:
|
|
lod1_wall_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l1_wtol))
|
|
if poly.area >= l2_min:
|
|
lod2_wall_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l2_wtol))
|
|
if not lod1_wall_tris and len(wall_tris_raw) > 0:
|
|
lod1_wall_tris = list(wall_tris_raw)
|
|
if not lod2_wall_tris:
|
|
lod2_wall_tris = lod1_wall_tris
|
|
|
|
lod1_roof_tris: list[np.ndarray] = []
|
|
lod2_roof_tris: list[np.ndarray] = []
|
|
if roof_planes:
|
|
for origin, u_axis, v_axis, _, poly in roof_planes:
|
|
lod1_roof_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l1_rtol))
|
|
if poly.area >= l2_min:
|
|
lod2_roof_tris.extend(triangulate_planar_polygon(origin, u_axis, v_axis, poly, simplify_tol=l2_rtol))
|
|
if not lod1_roof_tris and len(roof_tris_raw) > 0:
|
|
lod1_roof_tris = list(roof_tris_raw)
|
|
if not lod2_roof_tris:
|
|
lod2_roof_tris = lod1_roof_tris
|
|
|
|
# Precompute roof eaves overhang (~0.35m), ridge caps, and chimneys once
|
|
roof_mat = {"fortress": "roof_fortress", "industrial": "roof_industrial", "residential": "roof_terracotta"}[arch_style]
|
|
roof_detail_mats: dict[str, list[np.ndarray]] = defaultdict(list)
|
|
if roof_planes:
|
|
all_roof_xz = []
|
|
for origin, u_axis, v_axis, n_axis, poly in roof_planes:
|
|
pts2 = np.array(poly.exterior.coords)
|
|
pts3 = origin + pts2[:, 0:1] * u_axis + pts2[:, 1:2] * v_axis
|
|
pxz = Polygon(pts3[:, [0, 2]])
|
|
if not pxz.is_valid:
|
|
pxz = pxz.buffer(0)
|
|
if not pxz.is_empty:
|
|
all_roof_xz.append(pxz)
|
|
roof_union_xz = unary_union(all_roof_xz) if all_roof_xz else None
|
|
ext_boundary = roof_union_xz.boundary if roof_union_xz is not None else None
|
|
|
|
ridge_edges: list[tuple[np.ndarray, np.ndarray]] = []
|
|
pitched_planes: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Polygon]] = []
|
|
min_roof_area = 12.0 if arch_style == "fortress" else (24.0 if in_core else 42.0)
|
|
|
|
for origin, u_axis, v_axis, n_axis, poly in roof_planes:
|
|
slope_cos = float(abs(n_axis[1]))
|
|
if 0.15 < slope_cos < 0.993 and ext_boundary is not None and poly.area > min_roof_area:
|
|
pitched_planes.append((origin, u_axis, v_axis, n_axis, poly))
|
|
simp = shapely.geometry.polygon.orient(poly, sign=1.0).simplify(0.45, preserve_topology=True)
|
|
if isinstance(simp, Polygon) and not simp.is_empty:
|
|
c2 = np.array(simp.exterior.coords)
|
|
c3 = origin + c2[:, 0:1] * u_axis + c2[:, 1:2] * v_axis
|
|
for k in range(len(c2) - 1):
|
|
p0_3, p1_3 = c3[k], c3[k + 1]
|
|
elen = float(np.linalg.norm(p1_3 - p0_3))
|
|
if elen < 2.4:
|
|
continue
|
|
mid_xz = shapely.geometry.Point(0.5 * (p0_3[0] + p1_3[0]), 0.5 * (p0_3[2] + p1_3[2]))
|
|
if ext_boundary.distance(mid_xz) < 0.30:
|
|
du, dv = c2[k + 1, 0] - c2[k, 0], c2[k + 1, 1] - c2[k, 1]
|
|
out2 = np.array([dv, -du], dtype=np.float64)
|
|
ln2 = float(np.linalg.norm(out2))
|
|
if ln2 < 1e-6:
|
|
continue
|
|
out2 /= ln2
|
|
out3 = out2[0] * u_axis + out2[1] * v_axis
|
|
if out3[1] <= 0.15:
|
|
e0 = p0_3 + out3 * 0.35
|
|
e1 = p1_3 + out3 * 0.35
|
|
roof_detail_mats[roof_mat].append(np.stack([p0_3, e0, e1], axis=0))
|
|
roof_detail_mats[roof_mat].append(np.stack([p0_3, e1, p1_3], axis=0))
|
|
elif 0.5 * (p0_3[1] + p1_3[1]) > float(c3[:, 1].mean()) + 0.4 and elen > 3.2:
|
|
ridge_edges.append((p0_3, p1_3))
|
|
|
|
seen_ridges: list[tuple[np.ndarray, np.ndarray]] = []
|
|
for a, b in ridge_edges:
|
|
mid = 0.5 * (a + b)
|
|
if any(np.linalg.norm(mid - 0.5 * (sa + sb)) < 0.8 for sa, sb in seen_ridges):
|
|
continue
|
|
seen_ridges.append((a, b))
|
|
d_ab = b - a
|
|
rlen = float(np.linalg.norm(d_ab))
|
|
ru = d_ab / rlen
|
|
rn = np.cross(np.array([0.0, 1.0, 0.0]), ru)
|
|
ln = float(np.linalg.norm(rn))
|
|
if ln < 1e-4:
|
|
continue
|
|
rn /= ln
|
|
peak = np.array([0.0, 0.15, 0.0])
|
|
a_l, a_r = a - rn * 0.15, a + rn * 0.15
|
|
b_l, b_r = b - rn * 0.15, b + rn * 0.15
|
|
a_p, b_p = a + peak, b + peak
|
|
roof_detail_mats[roof_mat].append(np.stack([a_l, b_l, b_p], axis=0))
|
|
roof_detail_mats[roof_mat].append(np.stack([a_l, b_p, a_p], axis=0))
|
|
roof_detail_mats[roof_mat].append(np.stack([a_r, a_p, b_p], axis=0))
|
|
roof_detail_mats[roof_mat].append(np.stack([a_r, b_p, b_r], axis=0))
|
|
|
|
if arch_style == "residential" and pitched_planes:
|
|
h_byte = hashlib.blake2b(bldg_uuid.encode("utf-8"), digest_size=1).digest()[0]
|
|
if h_byte % 4 == 0:
|
|
origin, u_axis, v_axis, n_axis, poly = max(pitched_planes, key=lambda it: it[4].area)
|
|
if poly.area > 55.0:
|
|
rp = poly.representative_point()
|
|
c3 = origin + rp.x * u_axis + rp.y * v_axis
|
|
cy = float(c3[1])
|
|
up_v = np.array([0.0, 1.0, 0.0])
|
|
cu = np.array([1.0, 0.0, 0.0])
|
|
cz = np.array([0.0, 0.0, 1.0])
|
|
append_box_face_outward(
|
|
roof_detail_mats["stone_trim"], np.array([c3[0], cy - 0.4, c3[2]]),
|
|
cu, up_v, cz, -0.32, 0.32, 0.0, 1.45, -0.32, 0.32, include_back=False,
|
|
)
|
|
append_box_face_outward(
|
|
roof_detail_mats["stone_trim"], np.array([c3[0], cy + 1.05, c3[2]]),
|
|
cu, up_v, cz, -0.40, 0.40, 0.0, 0.14, -0.40, 0.40, include_back=False,
|
|
)
|
|
|
|
return (
|
|
bldg_uuid,
|
|
arch_style,
|
|
objektart,
|
|
in_core,
|
|
wall_planes,
|
|
lod1_wall_tris,
|
|
lod1_roof_tris,
|
|
lod2_wall_tris,
|
|
lod2_roof_tris,
|
|
list(skirt_tris_simp) if len(skirt_tris_simp) > 0 else [],
|
|
dict(roof_detail_mats),
|
|
)
|
|
|
|
|
|
def generate_lod1_building(
|
|
prepared: tuple,
|
|
bay_scale: float = 1.0,
|
|
) -> dict[str, list[np.ndarray]]:
|
|
"""
|
|
Derive procedural LOD1 architectural geometry from precomputed semantic Wall & Roof planes:
|
|
- Subdivides vertical walls (>3.5m tall, >3.0m wide) into realistic floor bays & architectural openings
|
|
- Attaches precomputed pitched roof eaves overhang (~0.35m), ridge caps, and chimneys
|
|
Returns dict mapping material key -> list of (3,3) triangle arrays.
|
|
"""
|
|
(
|
|
_bldg_uuid,
|
|
arch_style,
|
|
objektart,
|
|
in_core,
|
|
wall_planes,
|
|
lod1_wall_tris,
|
|
lod1_roof_tris,
|
|
_lod2_wall_tris,
|
|
_lod2_roof_tris,
|
|
skirt_tris,
|
|
roof_detail_mats,
|
|
) = prepared
|
|
out: dict[str, list[np.ndarray]] = defaultdict(list)
|
|
|
|
wall_mat = {
|
|
"fortress": "wall_fortress",
|
|
"industrial": "wall_industrial",
|
|
"residential": "wall_plaster",
|
|
}[arch_style]
|
|
roof_mat = {
|
|
"fortress": "roof_fortress",
|
|
"industrial": "roof_industrial",
|
|
"residential": "roof_terracotta",
|
|
}[arch_style]
|
|
trim_mat = "stone_trim" if arch_style != "industrial" else "concrete_trim"
|
|
|
|
if lod1_wall_tris:
|
|
out[wall_mat].extend(lod1_wall_tris)
|
|
if skirt_tris:
|
|
out["foundation_stone"].extend(skirt_tris)
|
|
|
|
# 1. Procedural facade detailing from merged vertical semantic Wall panels
|
|
# Prioritize Old Town core & fortress landmarks with rich window bays, while scaling outer suburbs cleanly
|
|
local_scale = (bay_scale * 0.72) if in_core else (bay_scale * 1.65)
|
|
area_thresh = (14.0 * (local_scale ** 1.15)) if in_core else (34.0 * (bay_scale ** 1.55))
|
|
eff_bay_scale = min(max(1.0, local_scale), 2.4)
|
|
for origin, u_axis, v_axis, n_axis, poly in wall_planes:
|
|
if abs(n_axis[1]) > 0.25:
|
|
continue # non-vertical wall slope
|
|
umin, vmin, umax, vmax = poly.bounds
|
|
w = umax - umin
|
|
h = vmax - vmin
|
|
# Always detail fortress hero walls (>14m2); prioritize larger facades first on residential/industrial
|
|
min_area = 14.0 if arch_style == "fortress" else area_thresh
|
|
if h <= 3.5 or w <= 3.2 or poly.area < min_area:
|
|
continue
|
|
|
|
if arch_style == "fortress":
|
|
if objektart == "Mauer gross":
|
|
if w >= 6.0:
|
|
n_but = max(2, min(7, int(w / (8.0 * eff_bay_scale)) + 1))
|
|
for bi in range(n_but):
|
|
bu = umin + 0.6 + (w - 1.2) * (bi / max(1, n_but - 1))
|
|
if poly.contains(box(bu - 0.25, vmin + 0.2, bu + 0.25, vmax - 0.2)):
|
|
append_lean_ledge(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
bu - 0.24, bu + 0.24, vmin, vmax - 0.1, 0.34, top_bevel=True,
|
|
)
|
|
if poly.contains(box(umin + 0.2, vmax - 0.35, umax - 0.2, vmax - 0.05)):
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
umin - 0.06, umax + 0.06, vmax - 0.24, vmax + 0.04, 0.18,
|
|
)
|
|
else:
|
|
if w >= 7.5:
|
|
n_but = max(2, min(7, int(w / (8.0 * eff_bay_scale)) + 1))
|
|
for bi in range(n_but):
|
|
bu = umin + 0.45 + (w - 0.9) * (bi / max(1, n_but - 1))
|
|
if poly.contains(box(bu - 0.25, vmin + 0.3, bu + 0.25, vmax - 0.3)):
|
|
append_lean_ledge(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
bu - 0.22, bu + 0.22, vmin, vmax - 0.15, 0.32, top_bevel=True,
|
|
)
|
|
bay_w = 3.2 * eff_bay_scale
|
|
story_h = 3.8
|
|
nx = max(1, int((w - 1.2) / bay_w))
|
|
ny = max(1, int((h - 1.0) / story_h))
|
|
step_u = (w - 1.2) / nx
|
|
step_v = (h - 1.0) / ny
|
|
for iy in range(ny):
|
|
vc = vmin + 0.6 + (iy + 0.52) * step_v
|
|
win_h = min(2.1, step_v * 0.56)
|
|
win_w = 0.58
|
|
for ix in range(nx):
|
|
uc = umin + 0.6 + (ix + 0.5) * step_u
|
|
if poly.contains(box(uc - 0.45, vc - win_h * 0.5 - 0.2, uc + 0.45, vc + win_h * 0.5 + 0.2)):
|
|
append_quad_outward(
|
|
out["window_glass"], origin, u_axis, v_axis, n_axis,
|
|
uc - win_w * 0.5, uc + win_w * 0.5, vc - win_h * 0.5, vc + win_h * 0.5, 0.03,
|
|
)
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
uc - win_w * 0.72, uc + win_w * 0.72, vc - win_h * 0.5 - 0.16, vc - win_h * 0.5, 0.14,
|
|
)
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
uc - win_w * 0.72, uc + win_w * 0.72, vc + win_h * 0.5, vc + win_h * 0.5 + 0.18, 0.14,
|
|
)
|
|
|
|
elif arch_style == "industrial":
|
|
story_h = 3.5
|
|
ny = max(1, int((h - 0.6) / story_h))
|
|
step_v = (h - 0.5) / ny
|
|
if w >= 6.0:
|
|
door_step = 6.2 * eff_bay_scale
|
|
nd = max(1, int((w - 1.4) / door_step))
|
|
du = (w - 1.4) / nd
|
|
for ix in range(nd):
|
|
uc = umin + 0.7 + (ix + 0.5) * du
|
|
dw = min(3.4, du * 0.62)
|
|
dh = min(3.0, step_v * 0.82)
|
|
if poly.contains(box(uc - dw * 0.5 - 0.15, vmin + 0.05, uc + dw * 0.5 + 0.15, vmin + dh + 0.2)):
|
|
append_quad_outward(
|
|
out["industrial_door"], origin, u_axis, v_axis, n_axis,
|
|
uc - dw * 0.5, uc + dw * 0.5, vmin + 0.05, vmin + dh, 0.03,
|
|
)
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
uc - dw * 0.54, uc + dw * 0.54, vmin + dh, vmin + dh + 0.18, 0.14,
|
|
)
|
|
for iy in range(1 if w >= 6.0 and ny > 1 else 0, ny):
|
|
vc = vmin + 0.3 + (iy + 0.62) * step_v
|
|
ch = min(0.95, step_v * 0.34)
|
|
cw = w - 1.2
|
|
if cw >= 2.2 and poly.contains(box(umin + 0.5, vc - ch * 0.5 - 0.1, umax - 0.5, vc + ch * 0.5 + 0.1)):
|
|
append_quad_outward(
|
|
out["window_glass"], origin, u_axis, v_axis, n_axis,
|
|
umin + 0.6, umax - 0.6, vc - ch * 0.5, vc + ch * 0.5, 0.03,
|
|
)
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
umin + 0.55, umax - 0.55, vc - ch * 0.5 - 0.11, vc - ch * 0.5, 0.12,
|
|
)
|
|
|
|
else:
|
|
# Residential / Old Town / Civic: ~3.1m stories, ~2.4m-3.4m multi-bay windows
|
|
story_h = 3.1
|
|
bay_w = 2.4 * eff_bay_scale
|
|
ny = max(1, int((h - 0.5) / story_h))
|
|
nx = max(1, int((w - 0.7) / bay_w))
|
|
step_v = (h - 0.4) / ny
|
|
step_u = (w - 0.6) / nx
|
|
|
|
# Subtle horizontal floor belt-courses on multi-story main facades
|
|
if ny >= 3 and w >= 7.0:
|
|
for iy in range(1, ny):
|
|
bv = vmin + 0.2 + iy * step_v
|
|
if poly.contains(box(umin + 0.25, bv - 0.08, umax - 0.25, bv + 0.08)):
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
umin + 0.05, umax - 0.05, bv - 0.07, bv + 0.07, 0.08,
|
|
)
|
|
|
|
win_w = min(1.15, step_u * 0.48)
|
|
win_h = min(1.48, step_v * 0.52)
|
|
has_lintel = w >= 7.0 and bay_scale <= 1.25
|
|
for iy in range(ny):
|
|
vc = vmin + 0.25 + (iy + 0.52) * step_v
|
|
for ix in range(nx):
|
|
uc = umin + 0.3 + (ix + 0.5) * step_u
|
|
if poly.contains(
|
|
box(uc - win_w * 0.62, vc - win_h * 0.55 - 0.14, uc + win_w * 0.62, vc + win_h * 0.55 + 0.14)
|
|
):
|
|
append_quad_outward(
|
|
out["window_glass"], origin, u_axis, v_axis, n_axis,
|
|
uc - win_w * 0.5, uc + win_w * 0.5, vc - win_h * 0.5, vc + win_h * 0.5, 0.03,
|
|
)
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
uc - win_w * 0.58, uc + win_w * 0.58, vc - win_h * 0.5 - 0.13, vc - win_h * 0.5, 0.13,
|
|
)
|
|
if has_lintel:
|
|
append_quad_outward(
|
|
out[trim_mat], origin, u_axis, v_axis, n_axis,
|
|
uc - win_w * 0.56, uc + win_w * 0.56, vc + win_h * 0.5, vc + win_h * 0.5 + 0.11, 0.09,
|
|
)
|
|
|
|
# 2. Precomputed Roof detailing: eaves overhang (~0.35m), ridge caps, chimneys
|
|
if lod1_roof_tris:
|
|
out[roof_mat].extend(lod1_roof_tris)
|
|
for mk, tlist in roof_detail_mats.items():
|
|
if tlist:
|
|
out[mk].extend(tlist)
|
|
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Fast GLB exporter (indexed flat-shaded per material)
|
|
# ---------------------------------------------------------------------------
|
|
MATERIAL_SPECS: dict[str, tuple[tuple[float, float, float, float], float, float]] = {
|
|
# name: ((r, g, b, a), metallic, roughness)
|
|
"roof_terracotta": ((0.50, 0.16, 0.09, 1.0), 0.02, 0.74),
|
|
"roof_fortress": ((0.19, 0.21, 0.24, 1.0), 0.05, 0.78),
|
|
"roof_industrial": ((0.29, 0.32, 0.35, 1.0), 0.12, 0.80),
|
|
"wall_plaster": ((0.76, 0.67, 0.55, 1.0), 0.00, 0.86),
|
|
"wall_fortress": ((0.35, 0.31, 0.26, 1.0), 0.02, 0.90),
|
|
"wall_industrial": ((0.48, 0.48, 0.46, 1.0), 0.08, 0.84),
|
|
"foundation_stone": ((0.22, 0.20, 0.18, 1.0), 0.02, 0.93),
|
|
"stone_trim": ((0.52, 0.48, 0.42, 1.0), 0.02, 0.86),
|
|
"concrete_trim": ((0.42, 0.43, 0.44, 1.0), 0.06, 0.85),
|
|
"window_glass": ((0.04, 0.07, 0.11, 1.0), 0.25, 0.12),
|
|
"industrial_door": ((0.16, 0.19, 0.22, 1.0), 0.45, 0.55),
|
|
}
|
|
|
|
|
|
def export_glb(mat_tris: dict[str, list[np.ndarray]], out_path: Path, mesh_name: str) -> tuple[int, int]:
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
blob = bytearray()
|
|
buffer_views = []
|
|
accessors = []
|
|
materials = []
|
|
primitives = []
|
|
|
|
total_tris = 0
|
|
for mat_idx, (mat_name, tri_list) in enumerate(sorted(mat_tris.items())):
|
|
if not tri_list:
|
|
continue
|
|
tris = np.asarray(tri_list, dtype=np.float32) # (N, 3, 3)
|
|
# Filter degenerate triangles
|
|
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
|
|
tris = tris[valid]
|
|
if len(tris) == 0:
|
|
continue
|
|
n_face = (cross[valid] / nlen[valid, None]).astype(np.float32)
|
|
|
|
total_tris += len(tris)
|
|
raw_verts = tris.reshape(-1, 3) # (N*3, 3)
|
|
raw_norms = np.repeat(n_face, 3, axis=0) # (N*3, 3)
|
|
|
|
# Deduplicate vertices sharing identical (position, hard-surface normal)
|
|
q_pos = np.round(raw_verts * 2000.0).astype(np.int64)
|
|
q_nrm = np.round(raw_norms * 250.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)
|
|
verts = np.ascontiguousarray(raw_verts[uniq_idx], dtype=np.float32)
|
|
norms = np.ascontiguousarray(raw_norms[uniq_idx], dtype=np.float32)
|
|
if len(verts) < 65535:
|
|
indices = inv_idx.astype(np.uint16)
|
|
idx_comp_type = pygltflib.UNSIGNED_SHORT
|
|
idx_elem_bytes = 2
|
|
else:
|
|
indices = inv_idx.astype(np.uint32)
|
|
idx_comp_type = pygltflib.UNSIGNED_INT
|
|
idx_elem_bytes = 4
|
|
|
|
# Position buffer view
|
|
while len(blob) % 4 != 0:
|
|
blob.append(0)
|
|
pos_off = len(blob)
|
|
blob.extend(verts.tobytes())
|
|
pos_bv = len(buffer_views)
|
|
buffer_views.append(pygltflib.BufferView(buffer=0, byteOffset=pos_off, byteLength=len(verts) * 12, target=pygltflib.ARRAY_BUFFER))
|
|
pos_acc = len(accessors)
|
|
accessors.append(
|
|
pygltflib.Accessor(
|
|
bufferView=pos_bv,
|
|
componentType=pygltflib.FLOAT,
|
|
count=len(verts),
|
|
type=pygltflib.VEC3,
|
|
min=verts.min(axis=0).tolist(),
|
|
max=verts.max(axis=0).tolist(),
|
|
)
|
|
)
|
|
|
|
# Normal buffer view
|
|
nrm_off = len(blob)
|
|
blob.extend(norms.tobytes())
|
|
nrm_bv = len(buffer_views)
|
|
buffer_views.append(pygltflib.BufferView(buffer=0, byteOffset=nrm_off, byteLength=len(norms) * 12, target=pygltflib.ARRAY_BUFFER))
|
|
nrm_acc = len(accessors)
|
|
accessors.append(
|
|
pygltflib.Accessor(
|
|
bufferView=nrm_bv,
|
|
componentType=pygltflib.FLOAT,
|
|
count=len(norms),
|
|
type=pygltflib.VEC3,
|
|
)
|
|
)
|
|
|
|
# Index buffer view
|
|
while len(blob) % 4 != 0:
|
|
blob.append(0)
|
|
idx_off = len(blob)
|
|
blob.extend(indices.tobytes())
|
|
idx_bv = len(buffer_views)
|
|
buffer_views.append(
|
|
pygltflib.BufferView(
|
|
buffer=0, byteOffset=idx_off, byteLength=len(indices) * idx_elem_bytes, target=pygltflib.ELEMENT_ARRAY_BUFFER
|
|
)
|
|
)
|
|
idx_acc = len(accessors)
|
|
accessors.append(
|
|
pygltflib.Accessor(
|
|
bufferView=idx_bv,
|
|
componentType=idx_comp_type,
|
|
count=len(indices),
|
|
type=pygltflib.SCALAR,
|
|
)
|
|
)
|
|
|
|
col, met, rough = MATERIAL_SPECS[mat_name]
|
|
m_id = len(materials)
|
|
materials.append(
|
|
pygltflib.Material(
|
|
name=mat_name,
|
|
pbrMetallicRoughness=pygltflib.PbrMetallicRoughness(
|
|
baseColorFactor=list(col),
|
|
metallicFactor=met,
|
|
roughnessFactor=rough,
|
|
),
|
|
)
|
|
)
|
|
primitives.append(
|
|
pygltflib.Primitive(
|
|
attributes=pygltflib.Attributes(POSITION=pos_acc, NORMAL=nrm_acc),
|
|
indices=idx_acc,
|
|
material=m_id,
|
|
)
|
|
)
|
|
|
|
gltf = pygltflib.GLTF2(
|
|
asset=pygltflib.Asset(version="2.0", generator="RustToDust Sion Map Baker"),
|
|
scene=0,
|
|
scenes=[pygltflib.Scene(nodes=[0])],
|
|
nodes=[pygltflib.Node(mesh=0, name=mesh_name)],
|
|
meshes=[pygltflib.Mesh(name=mesh_name, primitives=primitives)],
|
|
materials=materials,
|
|
buffers=[pygltflib.Buffer(byteLength=len(blob))],
|
|
bufferViews=buffer_views,
|
|
accessors=accessors,
|
|
)
|
|
gltf.set_binary_blob(bytes(blob))
|
|
gltf.save_binary(str(out_path))
|
|
return total_tris, out_path.stat().st_size
|
|
|
|
|
|
def export_collision_bin(
|
|
tris_list: list[np.ndarray], out_path: Path, tx: int, tz: int
|
|
) -> tuple[int, int, int, list[float], list[float]]:
|
|
"""
|
|
Export compact RCOL v1 binary static collision trimesh for Ymir.AddStaticMesh:
|
|
Header (48 bytes LE):
|
|
magic[4] = b"RCOL", uint32 version = 1, int32 tx, int32 tz,
|
|
uint32 vertexCount, uint32 indexCount,
|
|
float32[3] boundsMin, float32[3] boundsMax
|
|
Payload:
|
|
float32[vertexCount * 3] positions (X, Y, Z in arena glTF space)
|
|
int32[indexCount] triangle indices (CCW outward)
|
|
"""
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
if not tris_list:
|
|
raise RuntimeError(f"Cannot export empty collision bin for tile ({tx}, {tz})")
|
|
|
|
tris = np.asarray(tris_list, dtype=np.float32)
|
|
e1 = tris[:, 1] - tris[:, 0]
|
|
e2 = tris[:, 2] - tris[:, 0]
|
|
cross = np.cross(e1, e2)
|
|
valid = np.linalg.norm(cross, axis=1) > 1e-5
|
|
tris = tris[valid]
|
|
if len(tris) == 0:
|
|
raise RuntimeError(f"All collision triangles degenerate for tile ({tx}, {tz})")
|
|
|
|
raw_verts = tris.reshape(-1, 3)
|
|
# Position-only deduplication at 2mm grid (collision has no per-face normals)
|
|
q_pos = np.round(raw_verts * 500.0).astype(np.int64)
|
|
keys = np.ascontiguousarray(q_pos).view(np.dtype((np.void, 3 * 8))).ravel()
|
|
_, uniq_idx, inv_idx = np.unique(keys, return_index=True, return_inverse=True)
|
|
verts = np.ascontiguousarray(raw_verts[uniq_idx], dtype="<f4")
|
|
indices = np.ascontiguousarray(inv_idx, dtype="<i4")
|
|
|
|
# Drop degenerate indexed triangles after vertex snapping
|
|
tri_idx = indices.reshape(-1, 3)
|
|
non_deg = (tri_idx[:, 0] != tri_idx[:, 1]) & (tri_idx[:, 1] != tri_idx[:, 2]) & (tri_idx[:, 0] != tri_idx[:, 2])
|
|
indices = np.ascontiguousarray(tri_idx[non_deg].ravel(), dtype="<i4")
|
|
|
|
bmin = verts.min(axis=0).astype(float).tolist()
|
|
bmax = verts.max(axis=0).astype(float).tolist()
|
|
v_count = int(len(verts))
|
|
i_count = int(len(indices))
|
|
header = struct.pack(
|
|
"<4sIiiII3f3f",
|
|
b"RCOL",
|
|
1,
|
|
tx,
|
|
tz,
|
|
v_count,
|
|
i_count,
|
|
bmin[0], bmin[1], bmin[2],
|
|
bmax[0], bmax[1], bmax[2],
|
|
)
|
|
out_path.write_bytes(header + verts.tobytes() + indices.tobytes())
|
|
return v_count, i_count // 3, out_path.stat().st_size, [round(v, 3) for v in bmin], [round(v, 3) for v in bmax]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Main pipeline
|
|
# ---------------------------------------------------------------------------
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Bake Sion, Switzerland 3km tiled map assets for RustToDust.")
|
|
parser.add_argument("--repo-root", default=str(Path(__file__).resolve().parents[3]))
|
|
parser.add_argument("--cache-dir", default=os.path.join(os.environ.get("TEMP", "/tmp"), "sion-cache"))
|
|
parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E)
|
|
parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N)
|
|
args = parser.parse_args()
|
|
|
|
repo_root = Path(args.repo_root).resolve()
|
|
out_dir = repo_root / "assets" / "maps" / "sion"
|
|
tiles_dir = out_dir / "tiles"
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
tiles_dir.mkdir(parents=True, exist_ok=True)
|
|
cache_dir = Path(args.cache_dir)
|
|
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Cut obsolete single-monolith GLBs & any stale tile files before baking
|
|
for obsolete in ("sion_lod2.glb", "sion_lod1.glb"):
|
|
obs_path = out_dir / obsolete
|
|
if obs_path.exists():
|
|
obs_path.unlink()
|
|
print(f"[Sion Baker] Removed obsolete monolith {obs_path.name}")
|
|
for stale in tiles_dir.iterdir():
|
|
if stale.is_file():
|
|
stale.unlink()
|
|
|
|
cE, cN = args.center_e, args.center_n
|
|
e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M
|
|
|
|
print(
|
|
f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m ({TILE_GRID}x{TILE_GRID} tiles of {TILE_SIZE_M:.0f}m) "
|
|
f"EPSG:2056 center=({cE:.1f}, {cN:.1f}) bbox=[{e0:.1f}..{e1:.1f}, {n0:.1f}..{n1:.1f}]"
|
|
)
|
|
tif_paths, gdb_paths, stac_ids = acquire_swisstopo_data(cache_dir, e0, n0, e1, n1)
|
|
|
|
wms_masks: dict[str, np.ndarray] | None = None
|
|
try:
|
|
wms_masks = acquire_wms_masks(cache_dir, e0, n0, e1, n1, SURFACE_TEX_RES)
|
|
except Exception as exc:
|
|
print(f" [WMS warning] Falling back to DEM-only river/road synthesis ({exc})")
|
|
|
|
print(f"[Sion Baker] Stitching & resampling swissALTI3D to {GRID_RES}x{GRID_RES} float32...")
|
|
hm, surf_dem_asl, base_elev, min_y, max_y = build_heightmap(tif_paths, cE, cN)
|
|
hm_path = out_dir / "heightmap.f32"
|
|
hm.astype("<f4").tofile(str(hm_path))
|
|
print(
|
|
f" heightmap.f32: {hm.shape}, {hm_path.stat().st_size:,} bytes, "
|
|
f"baseElevationM={base_elev:.2f}m, Y=[{min_y:.2f}, {max_y:.2f}]m (relief={max_y - min_y:.2f}m)"
|
|
)
|
|
|
|
# Read semantic layers across intersecting GDB tiles
|
|
print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...")
|
|
reader = OgrReader()
|
|
bbox = (e0, n0, e1, n1)
|
|
fields = ["UUID", "OBJEKTART", "NAME_KOMPLETT", "DACH_MIN", "DACH_MAX", "GELAENDEPUNKT", "EGID"]
|
|
|
|
solids_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
|
|
walls_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
|
|
floors_by_uuid: dict[str, tuple[dict, list[np.ndarray]]] = {}
|
|
roofs_list: list[tuple[dict, list[np.ndarray]]] = []
|
|
|
|
for gdb in gdb_paths:
|
|
for attrs, faces in reader.read_layer(str(gdb), "Building_solid", bbox, fields):
|
|
u = str(attrs.get("UUID", ""))
|
|
if u and u not in solids_by_uuid:
|
|
solids_by_uuid[u] = (attrs, faces)
|
|
for attrs, faces in reader.read_layer(str(gdb), "Wall", bbox, fields):
|
|
u = str(attrs.get("UUID", ""))
|
|
if u and u not in walls_by_uuid:
|
|
walls_by_uuid[u] = (attrs, faces)
|
|
for attrs, faces in reader.read_layer(str(gdb), "Floor", bbox, fields):
|
|
u = str(attrs.get("UUID", ""))
|
|
if u and u not in floors_by_uuid:
|
|
floors_by_uuid[u] = (attrs, faces)
|
|
for attrs, faces in reader.read_layer(str(gdb), "Roof", bbox, fields):
|
|
roofs_list.append((attrs, faces))
|
|
|
|
# Index roofs by UUID, and attach orphan/empty-UUID roofs by EGID or 2D AABB overlap
|
|
roofs_by_uuid: dict[str, list[list[np.ndarray]]] = defaultdict(list)
|
|
bldg_egids: dict[str, str] = {}
|
|
bldg_boxes: list[tuple[str, float, float, float, float]] = []
|
|
for u, (attrs, faces) in walls_by_uuid.items():
|
|
pts = np.vstack(faces)
|
|
bldg_boxes.append((u, float(pts[:, 0].min()), float(pts[:, 1].min()), float(pts[:, 0].max()), float(pts[:, 1].max())))
|
|
egid = str(attrs.get("EGID", "")).strip()
|
|
if egid:
|
|
bldg_egids[egid] = u
|
|
|
|
standalone_roofs: list[tuple[str, dict, list[np.ndarray]]] = []
|
|
seen_roof_sigs: set[tuple[int, int, int]] = set()
|
|
for idx_r, (attrs, faces) in enumerate(roofs_list):
|
|
pts = np.vstack(faces)
|
|
sig = (int(round(pts[:, 0].mean() * 10)), int(round(pts[:, 1].mean() * 10)), len(faces))
|
|
if sig in seen_roof_sigs:
|
|
continue
|
|
seen_roof_sigs.add(sig)
|
|
u = str(attrs.get("UUID", "")).strip()
|
|
if u and u in walls_by_uuid:
|
|
roofs_by_uuid[u].append(faces)
|
|
continue
|
|
egid = str(attrs.get("EGID", "")).strip()
|
|
if egid and egid in bldg_egids:
|
|
roofs_by_uuid[bldg_egids[egid]].append(faces)
|
|
continue
|
|
rx, ry = float(pts[:, 0].mean()), float(pts[:, 1].mean())
|
|
matched_u = None
|
|
for bu, bx0, by0, bx1, by1 in bldg_boxes:
|
|
if bx0 - 0.5 <= rx <= bx1 + 0.5 and by0 - 0.5 <= ry <= by1 + 0.5:
|
|
matched_u = bu
|
|
break
|
|
if matched_u:
|
|
roofs_by_uuid[matched_u].append(faces)
|
|
else:
|
|
standalone_roofs.append((u or f"roof_{idx_r:04d}", attrs, faces))
|
|
|
|
print(
|
|
f" Raw extracted: {len(walls_by_uuid)} wall-buildings, "
|
|
f"{len(roofs_by_uuid)} matched roofs, {len(standalone_roofs)} roof-only structures"
|
|
)
|
|
|
|
# Spatial 6x6 tile buckets
|
|
tile_lod2_mats: dict[tuple[int, int], dict[str, list[np.ndarray]]] = defaultdict(lambda: defaultdict(list))
|
|
tile_col_tris: dict[tuple[int, int], list[np.ndarray]] = defaultdict(list)
|
|
tile_lod1_prepared: dict[tuple[int, int], list[tuple]] = defaultdict(list)
|
|
tile_bldg_counts: Counter[tuple[int, int]] = Counter()
|
|
|
|
fp_res_tris: list[np.ndarray] = []
|
|
fp_ind_tris: list[np.ndarray] = []
|
|
fp_fort_tris: list[np.ndarray] = []
|
|
|
|
manifest_entries: list[dict] = []
|
|
class_counts: Counter[str] = Counter()
|
|
|
|
all_records: list[tuple[str, dict, list[np.ndarray], list[np.ndarray], list[np.ndarray], list[np.ndarray]]] = []
|
|
for u, (attrs, w_faces) in walls_by_uuid.items():
|
|
r_faces = [f for grp in roofs_by_uuid.get(u, []) for f in grp]
|
|
fl_faces = floors_by_uuid[u][1] if u in floors_by_uuid else []
|
|
s_faces = solids_by_uuid[u][1] if u in solids_by_uuid else []
|
|
all_records.append((u, attrs, w_faces, r_faces, fl_faces, s_faces))
|
|
for u, attrs, r_faces in standalone_roofs:
|
|
all_records.append((u, attrs, [], r_faces, [], []))
|
|
|
|
bldg_seq = 0
|
|
for u, attrs, w_faces_enz, r_faces_enz, fl_faces_enz, s_faces_enz in all_records:
|
|
all_enz = np.vstack(w_faces_enz + r_faces_enz + fl_faces_enz)
|
|
cx_enz, cy_enz = float(all_enz[:, 0].mean()), float(all_enz[:, 1].mean())
|
|
# Keep buildings whose centroid falls inside the 3072x3072 arena (with 2m edge margin)
|
|
if not (e0 + 2.0 <= cx_enz <= e1 - 2.0 and n0 + 2.0 <= cy_enz <= n1 - 2.0):
|
|
continue
|
|
|
|
bldg_seq += 1
|
|
bid = f"sion_{bldg_seq:04d}"
|
|
objektart = str(attrs.get("OBJEKTART", "") or "Gebaeude Einzelhaus")
|
|
name = str(attrs.get("NAME_KOMPLETT", "") or "")
|
|
class_counts[objektart] += 1
|
|
|
|
w_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in w_faces_enz]
|
|
r_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in r_faces_enz]
|
|
fl_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in fl_faces_enz]
|
|
s_rtd = [enz_to_rtd(f, cE, cN, base_elev) for f in s_faces_enz]
|
|
|
|
solid_tris = np.concatenate([triangulate_polygon_3d(f) for f in s_rtd], axis=0) if s_rtd else None
|
|
all_rtd_pts = np.vstack(w_rtd + r_rtd + fl_rtd)
|
|
bldg_center = all_rtd_pts.mean(axis=0)
|
|
bmin = all_rtd_pts.min(axis=0)
|
|
bmax = all_rtd_pts.max(axis=0)
|
|
box_center = (bmin + bmax) * 0.5
|
|
|
|
tx = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / TILE_SIZE_M))))
|
|
tz = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / TILE_SIZE_M))))
|
|
tkey = (tx, tz)
|
|
tile_bldg_counts[tkey] += 1
|
|
|
|
w_oriented = orient_faces_outward(w_rtd, solid_tris, "Wall", bldg_center)
|
|
r_oriented = orient_faces_outward(r_rtd, solid_tris, "Roof", bldg_center)
|
|
fl_oriented = orient_faces_outward(fl_rtd, solid_tris, "Floor", bldg_center)
|
|
|
|
arch_style = classify_building(objektart, name, all_enz, r_oriented)
|
|
wall_mat = {"fortress": "wall_fortress", "industrial": "wall_industrial", "residential": "wall_plaster"}[arch_style]
|
|
roof_mat = {"fortress": "roof_fortress", "industrial": "roof_industrial", "residential": "roof_terracotta"}[arch_style]
|
|
|
|
wall_tris = np.concatenate([triangulate_polygon_3d(f) for f in w_oriented], axis=0) if w_oriented else np.zeros((0, 3, 3))
|
|
roof_tris = np.concatenate([triangulate_polygon_3d(f) for f in r_oriented], axis=0) if r_oriented else np.zeros((0, 3, 3))
|
|
|
|
min_bldg_y = float(all_rtd_pts[:, 1].min())
|
|
max_bldg_y = float(all_rtd_pts[:, 1].max())
|
|
skirt_tol = 0.35 if arch_style == "fortress" else 0.85
|
|
skirt_tris_simp = build_foundation_skirt_tris(wall_tris, fl_oriented, hm, min_bldg_y, simplify_tol=skirt_tol)
|
|
in_core = (arch_style == "fortress") or (math.hypot(float(box_center[0]), float(box_center[2])) < 680.0)
|
|
|
|
prep = prepare_lod1_building(u, arch_style, objektart, in_core, w_oriented, r_oriented, wall_tris, roof_tris, skirt_tris_simp)
|
|
tile_lod1_prepared[tkey].append(prep)
|
|
|
|
# Clean coplanar LOD2 hull (walls + roofs + simplified foundation skirt; omits buried downward floor caps)
|
|
clean_walls = prep[7]
|
|
clean_roofs = prep[8]
|
|
clean_skirts = prep[9]
|
|
|
|
# Footprint triangles for terrain_surface.png plaza masks
|
|
if clean_roofs:
|
|
if arch_style == "fortress":
|
|
fp_fort_tris.extend(clean_roofs)
|
|
elif arch_style == "industrial":
|
|
fp_ind_tris.extend(clean_roofs)
|
|
else:
|
|
fp_res_tris.extend(clean_roofs)
|
|
|
|
if clean_walls:
|
|
tile_lod2_mats[tkey][wall_mat].extend(clean_walls)
|
|
tile_col_tris[tkey].extend(clean_walls)
|
|
if clean_roofs:
|
|
tile_lod2_mats[tkey][roof_mat].extend(clean_roofs)
|
|
tile_col_tris[tkey].extend(clean_roofs)
|
|
if clean_skirts:
|
|
tile_lod2_mats[tkey]["foundation_stone"].extend(clean_skirts)
|
|
|
|
manifest_entries.append(
|
|
{
|
|
"id": bid,
|
|
"uuid": u,
|
|
"name": name,
|
|
"class": objektart,
|
|
"archStyle": arch_style,
|
|
"tile": [tx, tz],
|
|
"center": [round(float(v), 3) for v in box_center],
|
|
"size": [round(float(v), 3) for v in (bmax - bmin)],
|
|
"groundY": round(min_bldg_y, 3),
|
|
"roofY": round(max_bldg_y, 3),
|
|
"wallCount": int(len(clean_walls)),
|
|
"roofCount": int(len(clean_roofs)),
|
|
}
|
|
)
|
|
|
|
# Bake 2048x2048 terrain_surface.png albedo
|
|
print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png...")
|
|
surf_png = build_terrain_surface_texture(
|
|
surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris
|
|
)
|
|
surf_path = out_dir / "terrain_surface.png"
|
|
surf_path.write_bytes(surf_png)
|
|
print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)")
|
|
if len(surf_png) >= MAX_SURFACE_PNG_BYTES:
|
|
raise RuntimeError(f"terrain_surface.png exceeded 3 MB budget: {len(surf_png)} bytes")
|
|
|
|
# Export per-tile LOD2 GLBs & RCOL v1 collision bins
|
|
non_empty_tiles = sorted(tile_bldg_counts.keys())
|
|
tile_stats: dict[tuple[int, int], dict] = {}
|
|
total_lod2_tris = 0
|
|
total_lod2_bytes = 0
|
|
total_col_tris = 0
|
|
total_col_bytes = 0
|
|
|
|
for tkey in non_empty_tiles:
|
|
tx, tz = tkey
|
|
lod2_path = tiles_dir / f"lod2_{tx}_{tz}.glb"
|
|
col_path = tiles_dir / f"col_{tx}_{tz}.bin"
|
|
l2_tris, l2_bytes = export_glb(tile_lod2_mats[tkey], lod2_path, f"Sion_LOD2_{tx}_{tz}")
|
|
c_verts, c_tris, c_bytes, bmin, bmax = export_collision_bin(tile_col_tris[tkey], col_path, tx, tz)
|
|
total_lod2_tris += l2_tris
|
|
total_lod2_bytes += l2_bytes
|
|
total_col_tris += c_tris
|
|
total_col_bytes += c_bytes
|
|
tile_cx = -HALF_EXTENT_M + (tx + 0.5) * TILE_SIZE_M
|
|
tile_cz = -HALF_EXTENT_M + (tz + 0.5) * TILE_SIZE_M
|
|
tile_stats[tkey] = {
|
|
"tx": tx,
|
|
"tz": tz,
|
|
"lod2": f"tiles/lod2_{tx}_{tz}.glb",
|
|
"lod1": f"tiles/lod1_{tx}_{tz}.glb",
|
|
"collision": f"tiles/col_{tx}_{tz}.bin",
|
|
"buildingCount": int(tile_bldg_counts[tkey]),
|
|
"lod2Tris": int(l2_tris),
|
|
"lod2Bytes": int(l2_bytes),
|
|
"colVerts": int(c_verts),
|
|
"colTris": int(c_tris),
|
|
"colBytes": int(c_bytes),
|
|
"center": [round(tile_cx, 2), 0.0, round(tile_cz, 2)],
|
|
"boundsMin": bmin,
|
|
"boundsMax": bmax,
|
|
}
|
|
|
|
print(
|
|
f"[Sion Baker] Exported {len(non_empty_tiles)}/{TILE_GRID*TILE_GRID} non-empty LOD2+COL tiles: "
|
|
f"LOD2={total_lod2_tris:,} tris ({total_lod2_bytes/1e6:.2f} MB), "
|
|
f"COL={total_col_tris:,} tris ({total_col_bytes/1e6:.2f} MB)"
|
|
)
|
|
|
|
# Adaptive procedural LOD1 across all tiles so combined GLB footprint stays strictly < 28 MB
|
|
bay_scale = 1.0
|
|
all_preps = [p for tkey in non_empty_tiles for p in tile_lod1_prepared[tkey]]
|
|
for attempt in range(16):
|
|
est_tris = 0
|
|
for prep in all_preps:
|
|
per_mat = generate_lod1_building(prep, bay_scale=bay_scale)
|
|
est_tris += sum(len(v) for v in per_mat.values())
|
|
print(f" LOD1 global pass (bay_scale={bay_scale:.2f}): {est_tris:,} raw tris")
|
|
if est_tris <= MAX_LOD1_TRIS:
|
|
break
|
|
bay_scale *= max(1.16, math.sqrt(est_tris / (MAX_LOD1_TRIS * 0.90)))
|
|
|
|
total_lod1_tris = 0
|
|
total_lod1_bytes = 0
|
|
for tkey in non_empty_tiles:
|
|
tx, tz = tkey
|
|
t_mats: dict[str, list[np.ndarray]] = defaultdict(list)
|
|
for prep in tile_lod1_prepared[tkey]:
|
|
per_mat = generate_lod1_building(prep, bay_scale=bay_scale)
|
|
for mk, tlist in per_mat.items():
|
|
t_mats[mk].extend(tlist)
|
|
lod1_path = tiles_dir / f"lod1_{tx}_{tz}.glb"
|
|
l1_tris, l1_bytes = export_glb(t_mats, lod1_path, f"Sion_LOD1_{tx}_{tz}")
|
|
total_lod1_tris += l1_tris
|
|
total_lod1_bytes += l1_bytes
|
|
tile_stats[tkey]["lod1Tris"] = int(l1_tris)
|
|
tile_stats[tkey]["lod1Bytes"] = int(l1_bytes)
|
|
|
|
print(
|
|
f"[Sion Baker] Exported {len(non_empty_tiles)} LOD1 tiles (bay_scale={bay_scale:.2f}): "
|
|
f"{total_lod1_tris:,} tris ({total_lod1_bytes/1e6:.2f} MB)"
|
|
)
|
|
|
|
manifest = {
|
|
"map": "sion",
|
|
"coordinateSystem": "rusttodust_arena_gltf",
|
|
"attribution": "Federal Office of Topography swisstopo",
|
|
"sizeMeters": ARENA_SIZE_M,
|
|
"tileGrid": TILE_GRID,
|
|
"tileSizeMeters": TILE_SIZE_M,
|
|
"count": len(manifest_entries),
|
|
"classes": dict(class_counts.most_common()),
|
|
"buildings": manifest_entries,
|
|
}
|
|
manifest_path = out_dir / "buildings_manifest.json"
|
|
manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
|
|
|
meta = {
|
|
"name": "Sion, Valais, Switzerland",
|
|
"attribution": "Federal Office of Topography swisstopo",
|
|
"sources": [
|
|
"ch.swisstopo.swissalti3d (2m DTM, Open Government Data)",
|
|
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)",
|
|
],
|
|
"stacItems": stac_ids,
|
|
"crs": "EPSG:2056",
|
|
"originE": e0,
|
|
"originN": n0,
|
|
"centerE": cE,
|
|
"centerN": cN,
|
|
"baseElevationM": base_elev,
|
|
"minY": round(min_y, 3),
|
|
"maxY": round(max_y, 3),
|
|
"reliefM": round(max_y - min_y, 3),
|
|
"sizeMeters": ARENA_SIZE_M,
|
|
"tileGrid": TILE_GRID,
|
|
"tileSizeMeters": TILE_SIZE_M,
|
|
"gridRes": GRID_RES,
|
|
"cellSizeMeters": CELL_SIZE_M,
|
|
"heightmapFormat": "float32_le_row_major",
|
|
"surfaceTexture": "terrain_surface.png",
|
|
"surfaceTextureSize": SURFACE_TEX_RES,
|
|
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
|
|
"collisionFormat": {
|
|
"magic": "RCOL",
|
|
"version": 1,
|
|
"headerBytes": 48,
|
|
"headerLayout": "magic[4], uint32 version, int32 tx, int32 tz, uint32 vertexCount, uint32 indexCount, float32[3] boundsMin, float32[3] boundsMax",
|
|
"vertexLayout": "float32[vertexCount * 3] (X, Y, Z in arena glTF space)",
|
|
"indexLayout": "int32[indexCount] (CCW outward triangles)",
|
|
},
|
|
"rowOrder": "north_to_south_z_neg_to_pos",
|
|
"colOrder": "west_to_east_x_neg_to_pos",
|
|
"coordinateTransform": {
|
|
"X": "E - centerE (East = +X)",
|
|
"Y": "Z_asl - baseElevationM (Up = +Y)",
|
|
"Z": "-(N - centerN) (North = -Z)",
|
|
},
|
|
"tileCount": len(non_empty_tiles),
|
|
"tiles": [tile_stats[k] for k in non_empty_tiles],
|
|
}
|
|
meta_path = out_dir / "metadata.json"
|
|
meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
|
|
|
combined_glb_bytes = total_lod1_bytes + total_lod2_bytes
|
|
total_assets_bytes = sum(p.stat().st_size for p in out_dir.rglob("*") if p.is_file())
|
|
print(
|
|
f"[Sion Baker] Summary: {len(manifest_entries)} buildings across {len(non_empty_tiles)} tiles | "
|
|
f"LOD1+LOD2 GLBs = {combined_glb_bytes/1e6:.2f} MB (< 28 MB limit) | "
|
|
f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 40 MB limit)"
|
|
)
|
|
if combined_glb_bytes >= MAX_TILES_GLB_BYTES:
|
|
raise RuntimeError(f"Combined tile GLB budget exceeded: {combined_glb_bytes} bytes >= {MAX_TILES_GLB_BYTES}")
|
|
if total_assets_bytes >= MAX_TOTAL_ASSETS_BYTES:
|
|
raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|