Initial commit: cad-building-showcase skill

Agent-led CAD-drawing → 3D web showcase pipeline. Inspects CAD reports,
maps layers/floors, extracts a normalized building spec (with block-probed
glazing and audit gates), builds Blender/trimesh GLB variants, and assembles
a Three.js web viewer. Includes XREF-shell detection and a regression test.

Large inputs/outputs (work/, outputs/, source_cad/, renders) are gitignored.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-12 16:16:04 +08:00
commit a6ac166049
26 changed files with 6228 additions and 0 deletions

392
scripts/build_ifc_poc.py Executable file
View File

@@ -0,0 +1,392 @@
#!/usr/bin/env python3
"""Create a semantic IFC proof-of-concept from building_spec.json."""
from __future__ import annotations
import argparse
import json
import math
import sys
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec", required=True, help="Path to building_spec.json")
parser.add_argument("--out-ifc", required=True, help="Output IFC file")
parser.add_argument("--out-report", help="Output validation report JSON")
parser.add_argument("--out-notes", help="Output Markdown notes")
parser.add_argument("--vendor-dir", default="work/vendor")
parser.add_argument("--project-name", default="CAD to IFC POC")
parser.add_argument("--max-walls-per-floor", type=int, default=0, help="0 means no limit")
parser.add_argument("--max-columns-per-floor", type=int, default=0, help="0 means no limit")
parser.add_argument("--max-beams-per-floor", type=int, default=0, help="0 means no limit")
parser.add_argument("--validate-geometry", action="store_true")
return parser.parse_args()
def import_deps(vendor_dir: Path):
if vendor_dir.exists():
sys.path.insert(0, str(vendor_dir.resolve()))
try:
import numpy as np # type: ignore
import ifcopenshell # type: ignore
import ifcopenshell.api.aggregate # type: ignore
import ifcopenshell.api.context # type: ignore
import ifcopenshell.api.geometry # type: ignore
import ifcopenshell.api.project # type: ignore
import ifcopenshell.api.pset # type: ignore
import ifcopenshell.api.root # type: ignore
import ifcopenshell.api.spatial # type: ignore
import ifcopenshell.api.unit # type: ignore
except ImportError as exc:
raise SystemExit(
"Missing dependency: ifcopenshell and/or numpy. Install locally with:\n"
f" python3 -m pip install --target {vendor_dir} ifcopenshell numpy"
) from exc
return np, ifcopenshell
def placement_matrix(np, x=0.0, y=0.0, z=0.0, angle=0.0):
c = math.cos(angle)
s = math.sin(angle)
return np.array(
[
[c, -s, 0.0, x],
[s, c, 0.0, y],
[0.0, 0.0, 1.0, z],
[0.0, 0.0, 0.0, 1.0],
]
)
def make_model(np, ifcopenshell, spec: dict, project_name: str):
model = ifcopenshell.api.project.create_file(version="IFC4")
project = ifcopenshell.api.root.create_entity(model, ifc_class="IfcProject", name=project_name)
ifcopenshell.api.unit.assign_unit(model, length={"is_metric": True, "raw": "METERS"})
model_context = ifcopenshell.api.context.add_context(model, context_type="Model")
body_context = ifcopenshell.api.context.add_context(
model,
context_type="Model",
context_identifier="Body",
target_view="MODEL_VIEW",
parent=model_context,
)
site = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSite", name="CAD Site")
building = ifcopenshell.api.root.create_entity(
model,
ifc_class="IfcBuilding",
name=spec.get("project", {}).get("name", "CAD Building"),
)
ifcopenshell.api.aggregate.assign_object(model, products=[site], relating_object=project)
ifcopenshell.api.aggregate.assign_object(model, products=[building], relating_object=site)
for obj in (project, site, building):
ifcopenshell.api.geometry.edit_object_placement(model, product=obj)
pset = ifcopenshell.api.pset.add_pset(model, product=project, name="CAD2BIM_Project")
ifcopenshell.api.pset.edit_pset(
model,
pset=pset,
properties={
"Source": json.dumps(spec.get("source", {}), ensure_ascii=False)[:1200],
"Method": "CAD/DXF -> building_spec.json -> IfcOpenShell",
"Purpose": "BIM replacement feasibility proof",
},
)
return model, body_context, building
def add_storey(np, ifcopenshell, model, building, floor_key: str, floor: dict):
storey = ifcopenshell.api.root.create_entity(
model,
ifc_class="IfcBuildingStorey",
name=floor.get("name", floor_key),
)
storey.Elevation = float(floor.get("z", 0.0))
ifcopenshell.api.aggregate.assign_object(model, products=[storey], relating_object=building)
ifcopenshell.api.geometry.edit_object_placement(
model,
product=storey,
matrix=placement_matrix(np, z=float(floor.get("z", 0.0))),
)
return storey
def segment_length(segment: dict) -> float:
sx, sy = segment["start"]
ex, ey = segment["end"]
return math.hypot(ex - sx, ey - sy)
def add_cad_pset(ifcopenshell, model, element, floor_key: str, category: str, segment: dict | None = None, source_index: int | None = None):
pset = ifcopenshell.api.pset.add_pset(model, product=element, name="CAD2BIM_Source")
props = {
"FloorKey": floor_key,
"Category": category,
"GeneratedFrom": "building_spec.json",
}
if segment:
props.update(
{
"SourceLayer": segment.get("layer", ""),
"SourceType": segment.get("source_type", ""),
"SourceIndex": int(source_index or 0),
"LengthMeters": round(segment_length(segment), 4),
}
)
ifcopenshell.api.pset.edit_pset(model, pset=pset, properties=props)
def add_slab(np, ifcopenshell, model, body_context, storey, floor_key: str, floor: dict):
min_x, min_y, max_x, max_y = floor["bounds"]
margin = float(floor.get("slab_margin", 1.2))
thickness = float(floor.get("slab_thickness", 0.25))
min_x -= margin
min_y -= margin
max_x += margin
max_y += margin
width = max_x - min_x
depth = max_y - min_y
polyline = [(0.0, 0.0), (width, 0.0), (width, depth), (0.0, depth), (0.0, 0.0)]
slab = ifcopenshell.api.root.create_entity(
model,
ifc_class="IfcSlab",
predefined_type="FLOOR",
name=f"{floor_key} Slab",
)
representation = ifcopenshell.api.geometry.add_slab_representation(
model,
context=body_context,
depth=thickness,
direction_sense="POSITIVE",
polyline=polyline,
)
ifcopenshell.api.geometry.assign_representation(model, product=slab, representation=representation)
ifcopenshell.api.geometry.edit_object_placement(
model,
product=slab,
matrix=placement_matrix(np, min_x, min_y, -thickness),
)
ifcopenshell.api.spatial.assign_container(model, products=[slab], relating_structure=storey)
add_cad_pset(ifcopenshell, model, slab, floor_key, "slab")
return slab
def add_segment_element(ifcopenshell, model, body_context, storey, floor_key: str, floor: dict, category: str, segment: dict, source_index: int):
length = segment_length(segment)
if length < 0.05:
return None
floor_height = float(floor.get("height", 4.2))
if category == "walls":
ifc_class = "IfcWall"
name = f"{floor_key} Wall {source_index:04d}"
height = max(0.5, floor_height - 0.1)
elevation = 0.0
thickness = max(0.08, min(0.45, float(segment.get("width", 0.20))))
elif category == "columns":
ifc_class = "IfcColumn"
name = f"{floor_key} Column {source_index:04d}"
height = max(0.5, floor_height)
elevation = 0.0
thickness = max(0.10, min(0.60, float(segment.get("width", 0.30))))
elif category == "beams":
ifc_class = "IfcBeam"
name = f"{floor_key} Beam {source_index:04d}"
height = min(0.65, max(0.25, floor_height * 0.10))
elevation = max(0.0, floor_height - height)
thickness = max(0.08, min(0.60, float(segment.get("width", 0.25))))
else:
return None
sx, sy = segment["start"]
ex, ey = segment["end"]
element = ifcopenshell.api.root.create_entity(model, ifc_class=ifc_class, name=name)
representation = ifcopenshell.api.geometry.create_2pt_wall(
model,
element=element,
context=body_context,
p1=(sx, sy),
p2=(ex, ey),
elevation=elevation,
height=height,
thickness=thickness,
is_si=True,
)
ifcopenshell.api.geometry.assign_representation(model, product=element, representation=representation)
ifcopenshell.api.spatial.assign_container(model, products=[element], relating_structure=storey)
add_cad_pset(ifcopenshell, model, element, floor_key, category, segment=segment, source_index=source_index)
return element
def select_segments(segments: list[dict], limit: int) -> list[tuple[int, dict]]:
if limit <= 0 or len(segments) <= limit:
return list(enumerate(segments, start=1))
step = len(segments) / limit
result = []
used: set[int] = set()
for i in range(limit):
idx = min(len(segments) - 1, int(i * step))
if idx in used:
continue
used.add(idx)
result.append((idx + 1, segments[idx]))
return result
def validate_ifc(ifcopenshell, path: Path, validate_geometry: bool) -> dict:
model = ifcopenshell.open(str(path))
counts = {
"IfcProject": len(model.by_type("IfcProject")),
"IfcSite": len(model.by_type("IfcSite")),
"IfcBuilding": len(model.by_type("IfcBuilding")),
"IfcBuildingStorey": len(model.by_type("IfcBuildingStorey")),
"IfcSlab": len(model.by_type("IfcSlab")),
"IfcWall": len(model.by_type("IfcWall")),
"IfcColumn": len(model.by_type("IfcColumn")),
"IfcBeam": len(model.by_type("IfcBeam")),
"IfcRelContainedInSpatialStructure": len(model.by_type("IfcRelContainedInSpatialStructure")),
"IfcPropertySet": len(model.by_type("IfcPropertySet")),
"IfcExtrudedAreaSolid": len(model.by_type("IfcExtrudedAreaSolid")),
}
storeys = []
for storey in model.by_type("IfcBuildingStorey"):
contained = []
for rel in storey.ContainsElements or []:
contained.extend(rel.RelatedElements or [])
storeys.append(
{
"name": storey.Name,
"elevation": storey.Elevation,
"contained_count": len(contained),
"contained_types": {
ifc_type: len([e for e in contained if e.is_a(ifc_type)])
for ifc_type in ("IfcSlab", "IfcWall", "IfcColumn", "IfcBeam")
},
}
)
geometry_failures = []
if validate_geometry:
import ifcopenshell.geom as geom # type: ignore
settings = geom.settings()
settings.set(settings.USE_WORLD_COORDS, True)
for ifc_type in ("IfcSlab", "IfcWall", "IfcColumn", "IfcBeam"):
for element in model.by_type(ifc_type):
try:
geom.create_shape(settings, element)
except Exception as exc:
geometry_failures.append(
{"ifc_type": ifc_type, "name": element.Name, "error": str(exc)}
)
return {
"ifc_path": str(path),
"schema": model.schema,
"entity_counts": counts,
"storeys": storeys,
"geometry_validation": {
"enabled": validate_geometry,
"failure_count": len(geometry_failures),
"failures": geometry_failures[:50],
},
"file_size_bytes": path.stat().st_size,
}
def make_notes(report: dict) -> str:
counts = report["entity_counts"]
lines = [
"# IFC BIM Proof Notes",
"",
"This IFC is a feasibility proof generated from CAD-derived linework. It contains semantic IFC entities, but it is not automatically a production BIM replacement.",
"",
"## IFC Output",
"",
f"- File: `{report['ifc_path']}`",
f"- Schema: `{report['schema']}`",
f"- Size: `{report['file_size_bytes']}` bytes",
"",
"## Entity Counts",
"",
]
for key in ("IfcBuildingStorey", "IfcSlab", "IfcWall", "IfcColumn", "IfcBeam", "IfcPropertySet", "IfcExtrudedAreaSolid"):
lines.append(f"- `{key}`: {counts.get(key, 0)}")
lines.extend(["", "## Storey Containment", ""])
for storey in report["storeys"]:
lines.append(f"- `{storey['name']}` at elevation `{storey['elevation']}`: {storey['contained_count']} elements")
for key, value in storey["contained_types"].items():
lines.append(f" - `{key}`: {value}")
gv = report["geometry_validation"]
lines.extend(
[
"",
"## Geometry Validation",
"",
f"- Enabled: `{gv['enabled']}`",
f"- Failures: `{gv['failure_count']}`",
"",
"## BIM Replacement Gaps",
"",
"- Add/validate openings, doors, windows, rooms/spaces, materials, quantities, classifications, georeferencing, discipline coordination, and object naming before calling this a BIM replacement.",
]
)
return "\n".join(lines)
def main() -> int:
args = parse_args()
np, ifcopenshell = import_deps(Path(args.vendor_dir))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
model, body_context, building = make_model(np, ifcopenshell, spec, args.project_name)
created = {"IfcSlab": 0, "IfcWall": 0, "IfcColumn": 0, "IfcBeam": 0}
limits = {
"walls": args.max_walls_per_floor,
"columns": args.max_columns_per_floor,
"beams": args.max_beams_per_floor,
}
source_counts = {}
for floor_key, floor in spec.get("floors", {}).items():
storey = add_storey(np, ifcopenshell, model, building, floor_key, floor)
add_slab(np, ifcopenshell, model, body_context, storey, floor_key, floor)
created["IfcSlab"] += 1
source_counts[floor_key] = {}
for category in ("walls", "columns", "beams"):
segments = floor.get("segments", {}).get(category, [])
source_counts[floor_key][category] = len(segments)
for source_index, segment in select_segments(segments, limits[category]):
element = add_segment_element(
ifcopenshell,
model,
body_context,
storey,
floor_key,
floor,
category,
segment,
source_index,
)
if element:
created[element.is_a()] += 1
out_ifc = Path(args.out_ifc)
out_ifc.parent.mkdir(parents=True, exist_ok=True)
model.write(str(out_ifc))
report = validate_ifc(ifcopenshell, out_ifc, args.validate_geometry)
report["created_from_script"] = created
report["source_segment_counts"] = source_counts
report["limits_per_floor"] = limits
out_report = Path(args.out_report) if args.out_report else out_ifc.with_suffix(".report.json")
out_notes = Path(args.out_notes) if args.out_notes else out_ifc.with_suffix(".notes.md")
out_report.parent.mkdir(parents=True, exist_ok=True)
out_notes.parent.mkdir(parents=True, exist_ok=True)
out_report.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
out_notes.write_text(make_notes(report), encoding="utf-8")
print(json.dumps({"ifc": str(out_ifc), "report": str(out_report), "notes": str(out_notes), "created": created}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())