#!/usr/bin/env python3 """Assemble a campus spec from per-building specs + a site manifest. Formalizes the spec-level merge proven on the 贝昂 case: every building's segments/footprints/caps are rotated+translated into campus-local meters, floor keys get building prefixes, site-context floors (from site_context_from_dump.py) are appended, and per-building roof_specs are re-keyed. Placement anchors follow the SKILL rules: WALL corners / coordinate callouts, never roof envelopes. Manifest (site_manifest.json) schema used here: { "campus_origin_surveying_m": [349505.372, 664163.589], "rotation_deg": 7.5711, # campus grid rotation (site vs building sheets) "buildings": { "1#厂房": {"spec": "work/building_spec.json", "prefix": "", "model_anchor_m": [7.3, 8.3], # point in the building spec (meters) "survey_anchor_m": [349582.714, 664188.492]}, # where it lands (surveying meters) "2#厂房": {"spec": "work/spec_2.json", "prefix": "2", ...} } } Buildings without a "spec" entry are skipped (e.g. "status": "待建模"). Checks performed (loud, not silent): pairwise wall-envelope overlap between buildings (negative gaps FAIL), and each building inside the site bounds if --site-bounds is given. Usage: python3 assemble_campus.py --manifest work/site_manifest.json \ [--site-floors work/site_floors.json] --out work/campus_spec.json \ [--project-name 厂区] [--roof-specs work/roof_specs.json] """ from __future__ import annotations import argparse import copy import json import math import sys from pathlib import Path def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--manifest", required=True) p.add_argument("--site-floors", default=None, help="site_context_from_dump.py output to merge") p.add_argument("--out", required=True) p.add_argument("--project-name", default=None) p.add_argument("--description", default=None) p.add_argument("--gap-warn", type=float, default=0.10, help="warn when two buildings' wall envelopes are closer than this (m); overlap always fails") p.add_argument("--allow-overlap", action="store_true", help="downgrade overlap FAIL to warning") return p.parse_args() def make_xf(anchor, survey_m, origin_m, cos_t, sin_t): ax, ay = anchor tx, ty = survey_m[0] - origin_m[0], survey_m[1] - origin_m[1] def xf(p): dx, dy = p[0] - ax, p[1] - ay return [round(dx * cos_t - dy * sin_t + tx, 6), round(dx * sin_t + dy * cos_t + ty, 6)] return xf def transform_floors(spec: dict, xf) -> dict: out = {} for fk, fl in spec.get("floors", {}).items(): nf = copy.deepcopy(fl) xs, ys = [], [] for segs in nf.get("segments", {}).values(): for s in segs: s["start"] = xf(s["start"]) s["end"] = xf(s["end"]) xs += [s["start"][0], s["end"][0]] ys += [s["start"][1], s["end"][1]] if "footprint" in nf: nf["footprint"]["polygons"] = [[xf(p) for p in poly] for poly in nf["footprint"]["polygons"]] for cap in nf.get("caps", []): cap["polygons"] = [[xf(p) for p in poly] for poly in cap["polygons"]] if xs: nf["bounds"] = [round(min(xs), 6), round(min(ys), 6), round(max(xs), 6), round(max(ys), 6)] out[fk] = nf return out def wall_envelope_axis(floors: dict, cos_t: float, sin_t: float): """Ground-floor wall envelope in the rotated building-axis frame. Uses the LOWEST floor with real walls: upper floors (roof machine rooms, parapet-level structures) legitimately overhang by 1-2 m and would turn a valid 0.19 m expansion joint into a false overlap alarm. """ ground = None for fl in floors.values(): if len(fl.get("segments", {}).get("walls", [])) < 10: continue z = float(fl.get("z", 0)) if z < -0.5: continue # basements are inset; the seam lives at ground level if ground is None or z < float(ground.get("z", 0)): ground = fl if ground is None: for fl in floors.values(): if len(fl.get("segments", {}).get("walls", [])) >= 10: if ground is None or float(fl.get("z", 0)) < float(ground.get("z", 0)): ground = fl if ground is None: return None pts = [] for s in ground["segments"]["walls"]: for p in (s["start"], s["end"]): pts.append((p[0] * cos_t + p[1] * sin_t, -p[0] * sin_t + p[1] * cos_t)) xs = [p[0] for p in pts] ys = [p[1] for p in pts] return (min(xs), min(ys), max(xs), max(ys)) def envelope_gap(a, b): """Positive = separation, negative = overlap (axis-aligned in building frame).""" dx = max(a[0] - b[2], b[0] - a[2]) dy = max(a[1] - b[3], b[1] - a[3]) if dx < 0 and dy < 0: return max(dx, dy) # overlapping in both axes -> negative depth return max(dx, dy) def main() -> int: args = parse_args() manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8")) origin = manifest.get("campus_origin_surveying_m") or manifest.get("campus_origin_surveying_mm") if origin is None: raise SystemExit("manifest needs campus_origin_surveying_m") if max(abs(origin[0]), abs(origin[1])) > 1e6: # mm legacy origin = [origin[0] / 1000.0, origin[1] / 1000.0] theta = math.radians(float(manifest.get("rotation_deg", 0.0))) cos_t, sin_t = math.cos(theta), math.sin(theta) base_spec = None placed: dict[str, dict] = {} envelopes: dict[str, tuple] = {} for name, b in manifest.get("buildings", {}).items(): if not isinstance(b, dict) or "spec" not in b: print(f"skip {name}: no spec (status: {b.get('status', '?') if isinstance(b, dict) else b})", file=sys.stderr) continue spec = json.loads(Path(b["spec"]).read_text(encoding="utf-8")) if base_spec is None: base_spec = spec anchor = b.get("model_anchor_m") or b.get("model_anchor_center_m") or b.get("model_anchor_SE_wall_corner_m") survey = b.get("survey_anchor_m") or b.get("survey_center_m") if not anchor or not survey: raise SystemExit(f"{name}: manifest entry needs model_anchor_m + survey_anchor_m") # Buildings on one campus can face different ways (27号: 4#楼 sits ~27° # off its siblings) — per-building rotation_deg overrides the global. b_theta = math.radians(float(b.get("rotation_deg", manifest.get("rotation_deg", 0.0)))) b_cos, b_sin = math.cos(b_theta), math.sin(b_theta) xf = make_xf(anchor, survey, origin, b_cos, b_sin) floors = transform_floors(spec, xf) prefix = str(b.get("prefix", "")) placed.update({prefix + fk: fl for fk, fl in floors.items()}) env = wall_envelope_axis(floors, cos_t, sin_t) if env: envelopes[name] = env # re-key this building's roof_specs into the campus config later b["_roof_specs"] = [ {**r, "floor_key": prefix + str(r.get("floor_key")), "footprint_from": [prefix + str(k) for k in r.get("footprint_from", [r.get("floor_key")])]} for r in spec.get("source", {}).get("config", {}).get("roof_specs", []) ] if base_spec is None: raise SystemExit("no buildings with specs in manifest") # gap audit names = list(envelopes) failures = [] for i in range(len(names)): for j in range(i + 1, len(names)): gap = envelope_gap(envelopes[names[i]], envelopes[names[j]]) tag = f"{names[i]} <-> {names[j]}" if gap < 0: failures.append(f"OVERLAP {tag}: {gap:.3f} m — placement bug (roof-envelope anchor? flip?)") elif gap < args.gap_warn: print(f"NOTE {tag}: gap {gap:.3f} m — 贴建/变形缝? corroborate per SKILL rules", file=sys.stderr) else: print(f"gap {tag}: {gap:.2f} m", file=sys.stderr) if failures and not args.allow_overlap: for f in failures: print("FAIL " + f, file=sys.stderr) return 3 for f in failures: print("WARN(allowed) " + f, file=sys.stderr) floors: dict = {} site_keys: list[str] = [] if args.site_floors: site = json.loads(Path(args.site_floors).read_text(encoding="utf-8")) wall_bounds = [fl["bounds"] for fl in placed.values() if len(fl.get("segments", {}).get("walls", [])) >= 10] for k, v in site.get("floors", {}).items(): if k.startswith("CTX"): w = v.get("segments", {}).get("walls", []) if w: xs = [q for s in w for q in (s["start"][0], s["end"][0])] ys = [q for s in w for q in (s["start"][1], s["end"][1])] cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2 if any(b[0] - 1 <= cx <= b[2] + 1 and b[1] - 1 <= cy <= b[3] + 1 for b in wall_bounds): continue # covered by a real model floors[k] = v site_keys.append(k) base_spec.setdefault("categories", {}).update(site.get("categories", {})) floors.update(placed) campus = base_spec campus["floors"] = floors campus["project"] = { "name": args.project_name or manifest.get("project_name", "厂区"), "description": args.description or manifest.get("description", "多栋建筑 + 场地(assemble_campus.py 合成)"), } cfg = campus.setdefault("source", {}).setdefault("config", {}) cfg["roof_specs"] = [r for b in manifest.get("buildings", {}).values() if isinstance(b, dict) for r in b.get("_roof_specs", [])] cfg["floor_order"] = site_keys + [k for k in placed] out = Path(args.out) out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(campus, ensure_ascii=False, indent=1), encoding="utf-8") print(json.dumps({"out": str(out), "floors": len(floors), "buildings": len(envelopes), "site_floors": len(site_keys)}, ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main())