Files
cad-building-showcase/scripts/dwgjson_to_dxf.py
zhengwr 6ace84ffba Campus pipeline hardening: backend parity, wall union, mullion grids, Draco tooling
Sandbox round (Linux):
- detect_sheet_frames.py: multi-frame sheet splitter (column AND row layouts),
  grid-vote per-floor offsets, section-elevation harvesting for storey heights
- dwg_dump_json.mjs + dwgjson_to_dxf.py: WASM libredwg DWG->DXF fallback
  (blocks/INSERT preserved, ATTRIB->TEXT so axis labels survive)
- assemble_campus.py: manifest-driven campus assembly with mandatory
  neighbour-gap gate (overlap = exit 3, 0.1-0.3m flagged as expansion joints)
- site_context_from_dump.py: site-context floors (ground/roads/parking/
  fence/trees/context massings) from site-plan dumps
- write_offline_viewer.py + assets/offline-viewer-libs/: fully-offline
  single-file viewer (vendored three r147 + pako, gzip-embedded GLB)
- audit: clip-scoped coverage figures; report: multi_frame_sheet warning;
  audit gate floors_aligned catches the diagonal-staircase failure mode

Mac round:
- build_blender_showcase.py now honors slab_bounds_fallback and prefers
  footprint polygons for generated roofs (bounds rects made roof plates jut
  past the facade and buried campuses under full-extent slabs); contract now
  matches spec_to_glb.py exactly
- merge_wall_solids (default off) in BOTH backends: shapely union in
  spec_to_glb.py, native delaunay_2d_cdt union in Blender; endpoint-shared
  wall ends pre-extended w/2 so L-corners close seamlessly (flat caps leave
  a notch a union alone cannot fill) while openings stay flat
- glazing_mullions (default off): curtain-wall panel grid (verticals every
  glazing_panel_w + floor-line transoms) as pseudo wall segments in the
  <floor>__walls node; glass pane kept
- build_showcase_variants.py keeps source_file=="site" floors intact in all
  variants (roads/trees live on filtered categories)
- web template: instanced low-poly trees from metadata site_trees,
  grade-level shadow catcher (was at basement depth), data-URI favicon
- tools/compress.mjs deps pinned (package.json); 15MB campus GLB -> 0.57MB
- tests: 24 -> 52 checks (wall union, mullions, byte-identical defaults)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 17:44:41 +08:00

144 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Rebuild an ezdxf DXF from a dwg_dump_json.mjs entity dump.
Fallback DWG->DXF path when native dwg2dxf / ODA File Converter is not
available. Preserves layers, block definitions, and INSERT transforms so the
extraction pipeline (derive_showcase_spec.py block probing included) works
unchanged.
Usage:
python3 dwgjson_to_dxf.py --json work/dump.json --out work/dxf_raw/file.dxf
"""
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("--json", required=True)
parser.add_argument("--out", required=True)
parser.add_argument("--vendor-dir", default="work/vendor")
return parser.parse_args()
def import_ezdxf(vendor_dir: Path):
if vendor_dir.exists():
sys.path.insert(0, str(vendor_dir.resolve()))
try:
import ezdxf # type: ignore
except ImportError as exc:
raise SystemExit(
f"Missing ezdxf. Install with: python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
return ezdxf
def add_entity(space, ent: dict) -> None:
kind = ent["t"]
attribs = {"layer": ent.get("layer", "0")}
if kind == "LINE":
space.add_line(ent["a"], ent["b"], dxfattribs=attribs)
elif kind in {"LWPOLYLINE", "POLYLINE"}:
points = [(v[0], v[1], 0.0, 0.0, v[2] if len(v) > 2 else 0.0) for v in ent["v"]]
space.add_lwpolyline(points, format="xyseb", close=bool(ent.get("closed")), dxfattribs=attribs)
elif kind == "ARC":
start = math.degrees(ent["sa"]) if abs(ent["sa"]) <= math.tau + 0.01 else ent["sa"]
end = math.degrees(ent["ea"]) if abs(ent["ea"]) <= math.tau + 0.01 else ent["ea"]
if ent.get("r", 0) > 0:
space.add_arc(ent["c"], ent["r"], start, end, dxfattribs=attribs)
elif kind == "CIRCLE":
if ent.get("r", 0) > 0:
space.add_circle(ent["c"], ent["r"], dxfattribs=attribs)
elif kind == "ELLIPSE":
major = (ent["mj"][0], ent["mj"][1], 0.0)
if math.hypot(major[0], major[1]) > 0:
space.add_ellipse(
ent["c"], major_axis=major, ratio=max(min(ent.get("ratio", 1.0), 1.0), 1e-6),
start_param=ent.get("sa", 0.0), end_param=ent.get("ea", math.tau), dxfattribs=attribs,
)
elif kind == "SPLINE":
space.add_lwpolyline([(v[0], v[1]) for v in ent["v"]], dxfattribs=attribs)
elif kind in {"TEXT", "MTEXT"}:
text = ent.get("text", "")
if text:
space.add_text(
text, height=max(float(ent.get("h", 250.0) or 250.0), 1e-3), dxfattribs=attribs,
).set_placement(ent["p"])
elif kind == "INSERT":
rotation = ent.get("rot", 0.0)
rotation = math.degrees(rotation) if abs(rotation) <= math.tau + 0.01 else rotation
space.add_blockref(
ent["name"], ent["p"],
dxfattribs={
**attribs,
"xscale": ent.get("sx", 1.0) or 1.0,
"yscale": ent.get("sy", 1.0) or 1.0,
"rotation": rotation,
},
)
def main() -> int:
args = parse_args()
ezdxf = import_ezdxf(Path(args.vendor_dir))
payload = json.loads(Path(args.json).read_text(encoding="utf-8"))
doc = ezdxf.new("R2010", setup=False)
doc.header["$INSUNITS"] = int(payload.get("insunits", 4) or 4)
for layer in payload.get("layers", []):
name = layer.get("name") or "0"
if name != "0" and name not in doc.layers:
try:
doc.layers.add(name, color=max(int(layer.get("color", 7)) or 7, 1))
except Exception:
pass
block_defs: dict = payload.get("blocks", {})
for name in block_defs:
if name in doc.blocks:
continue
try:
doc.blocks.new(name=name)
except Exception:
continue
for name, ents in block_defs.items():
try:
block = doc.blocks.get(name)
except Exception:
continue
for ent in ents:
if ent["t"] == "INSERT" and ent.get("name") not in doc.blocks:
continue
try:
add_entity(block, ent)
except Exception:
pass
msp = doc.modelspace()
added = skipped = 0
for ent in payload.get("entities", []):
if ent["t"] == "INSERT" and ent.get("name") not in doc.blocks:
skipped += 1
continue
try:
add_entity(msp, ent)
added += 1
except Exception:
skipped += 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
doc.saveas(out)
print(json.dumps({"out": str(out), "added": added, "skipped": skipped, "blocks": len(block_defs)}))
return 0
if __name__ == "__main__":
raise SystemExit(main())