#!/usr/bin/env python3 """Extract IFC product geometry into a compact JSON mesh bundle for rendering.""" from __future__ import annotations import argparse import json import sys from pathlib import Path DEFAULT_TYPES = ("IfcSlab", "IfcWall", "IfcColumn", "IfcBeam") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--ifc", required=True, help="Source IFC") parser.add_argument("--out", required=True, help="Output mesh JSON") parser.add_argument("--vendor-dir", default="work/vendor") parser.add_argument("--types", nargs="*", default=list(DEFAULT_TYPES)) return parser.parse_args() def import_ifcopenshell(vendor_dir: Path): if vendor_dir.exists(): sys.path.insert(0, str(vendor_dir.resolve())) try: import ifcopenshell # type: ignore import ifcopenshell.geom as geom # type: ignore except ImportError as exc: raise SystemExit( "Missing dependency: ifcopenshell. Install locally with:\n" f" python3 -m pip install --target {vendor_dir} ifcopenshell" ) from exc return ifcopenshell, geom def append_shape(group: dict, shape): verts = list(shape.geometry.verts) faces = list(shape.geometry.faces) offset = len(group["vertices"]) for index in range(0, len(verts), 3): group["vertices"].append( [ round(float(verts[index]), 5), round(float(verts[index + 1]), 5), round(float(verts[index + 2]), 5), ] ) for index in range(0, len(faces), 3): group["faces"].append([faces[index] + offset, faces[index + 1] + offset, faces[index + 2] + offset]) def main() -> int: args = parse_args() ifcopenshell, geom = import_ifcopenshell(Path(args.vendor_dir)) model = ifcopenshell.open(str(Path(args.ifc))) settings = geom.settings() settings.set(settings.USE_WORLD_COORDS, True) groups = {ifc_type: {"ifc_type": ifc_type, "vertices": [], "faces": [], "elements": 0} for ifc_type in args.types} failures = [] for ifc_type in args.types: for element in model.by_type(ifc_type): try: shape = geom.create_shape(settings, element) append_shape(groups[ifc_type], shape) groups[ifc_type]["elements"] += 1 except Exception as exc: failures.append({"ifc_type": ifc_type, "name": element.Name, "error": str(exc)}) payload = { "source_ifc": str(args.ifc), "schema": model.schema, "groups": list(groups.values()), "failures": failures, "summary": { ifc_type: { "elements": groups[ifc_type]["elements"], "vertices": len(groups[ifc_type]["vertices"]), "faces": len(groups[ifc_type]["faces"]), } for ifc_type in args.types }, } out = Path(args.out) out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") print(json.dumps({"out": str(out), "summary": payload["summary"], "failures": len(failures)}, ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main())