#!/usr/bin/env python3 """Create overview/standard/detail showcase variants from a building spec. The script writes filtered spec files for each variant and can optionally call Blender to produce GLBs. Its manifest is consumed by write_web_showcase.py. """ from __future__ import annotations import argparse import sys import glob import shutil import os import copy import json import subprocess from pathlib import Path from typing import Any import showcase_schema VARIANTS = [ { "key": "overview", "label": "总览轻量版", "description": "Walls, glazing, roofs, columns, beams, and generated slabs.", "categories": ["walls", "glazing", "roof", "columns", "beams"], }, { "key": "standard", "label": "展示标准版", "description": "Default Web presentation model with railings and doors.", "categories": ["walls", "glazing", "roof", "columns", "beams", "railings", "doors"], }, { "key": "detail", "label": "完整审图版", "description": "Full extracted linework for audit and review.", "categories": None, }, ] def default_blender() -> str: """Blender executable: env BLENDER > PATH > platform install defaults.""" override = os.environ.get("BLENDER") if override: return override found = shutil.which("blender") if found: return found if sys.platform == "win32": hits = sorted(glob.glob(r"C:/Program Files/Blender Foundation/Blender */blender.exe")) if hits: return hits[-1] return "/Applications/Blender.app/Contents/MacOS/Blender" def default_build_script() -> Path: return Path(__file__).resolve().with_name("build_blender_showcase.py") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--spec", required=True, help="Source building_spec.json") parser.add_argument("--out-dir", required=True, help="Output folder for variant specs/manifest/artifacts") parser.add_argument("--name", default="cad_building_showcase", help="Project/model base name") parser.add_argument("--build", action="store_true", help="Run Blender for each generated variant") parser.add_argument("--blender", default=default_blender(), help="Blender executable path") parser.add_argument("--build-script", default=str(default_build_script()), help="build_blender_showcase.py path") return parser.parse_args() def filtered_spec(source: dict[str, Any], variant: dict[str, Any]) -> dict[str, Any]: spec = copy.deepcopy(source) keep = variant.get("categories") config = spec.setdefault("source", {}).setdefault("config", {}) disabled = [key for key in config.get("default_disabled_categories", []) if key != "slab"] config["default_disabled_categories"] = disabled config["showcase_variant"] = variant["key"] config["showcase_variant_categories"] = keep or "all" if keep is None: return spec keep_set = set(keep) for floor in spec.get("floors", {}).values(): # Campus site-context floors (roads/parking/fence/trees emitted by # site_context_from_dump.py with source_file="site") are presentation # content: their roads live on detail_lines/grid and trees on a custom # category, so category filtering would strip the whole site. Keep them # intact in every variant. if floor.get("source_file") == "site": continue segments = floor.get("segments", {}) for category in list(segments): if category not in keep_set: segments[category] = [] return spec def write_variant_specs(spec: dict[str, Any], out_dir: Path) -> list[dict[str, Any]]: spec_dir = out_dir / "variant_specs" spec_dir.mkdir(parents=True, exist_ok=True) entries = [] for variant in VARIANTS: key = variant["key"] variant_spec = filtered_spec(spec, variant) spec_path = spec_dir / f"{key}.json" spec_path.write_text(json.dumps(variant_spec, ensure_ascii=False, indent=2), encoding="utf-8") entries.append({**variant, "spec_path": spec_path}) return entries def run_blender(entries: list[dict[str, Any]], out_dir: Path, blender: str, build_script: Path): if not build_script.exists(): raise SystemExit(f"Blender build script not found: {build_script}") for entry in entries: key = entry["key"] variant_dir = out_dir / "variants" / key variant_dir.mkdir(parents=True, exist_ok=True) subprocess.run( [ blender, "-b", "--python", str(build_script), "--", "--spec", str(entry["spec_path"]), "--out-dir", str(variant_dir), "--name", key, ], check=True, ) def relative_to_out(path: Path, out_dir: Path) -> str: try: return str(path.relative_to(out_dir)) except ValueError: return str(path) def write_manifest(entries: list[dict[str, Any]], out_dir: Path, name: str) -> Path: variants = [] for entry in entries: key = entry["key"] variant_dir = out_dir / "variants" / key variants.append( { "key": key, "label": entry["label"], "description": entry["description"], "file": f"{key}.glb", "source_glb": relative_to_out(variant_dir / f"{key}.glb", out_dir), "metadata": relative_to_out(variant_dir / "model_metadata.json", out_dir), "spec": relative_to_out(entry["spec_path"], out_dir), } ) manifest = { "manifest_version": showcase_schema.MANIFEST_VERSION, "name": name, "default_key": "standard", "variants": variants, } showcase_schema.validate_manifest(manifest) manifest_path = out_dir / "variants_manifest.json" manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8") return manifest_path def main() -> int: args = parse_args() spec_path = Path(args.spec) out_dir = Path(args.out_dir) out_dir.mkdir(parents=True, exist_ok=True) spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8"))) try: showcase_schema.validate_spec(spec) except showcase_schema.ValidationFailure as exc: print(str(exc), file=sys.stderr) return 3 entries = write_variant_specs(spec, out_dir) if args.build: run_blender(entries, out_dir, args.blender, Path(args.build_script)) manifest_path = write_manifest(entries, out_dir, args.name) print(json.dumps({"manifest": str(manifest_path)}, ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main())