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>
This commit is contained in:
2026-07-02 17:44:41 +08:00
parent 74cc7168f7
commit 6ace84ffba
27 changed files with 8515 additions and 85 deletions

View File

@@ -46,21 +46,48 @@ def parse_args() -> argparse.Namespace:
return parser.parse_args()
def iter_block_contents(entity, max_depth: int, depth: int = 0):
"""Yield every leaf entity inside an INSERT, regardless of extraction config."""
if depth >= max_depth:
return
try:
from ezdxf import explode as ezdxf_explode
_BLOCK_LENGTHS_CACHE: dict[tuple[int, str], dict[str, float]] = {}
virtual_entities = list(ezdxf_explode.virtual_block_reference_entities(entity))
def block_layer_unit_lengths(doc, name: str, max_chord: float, max_depth: int, depth: int = 0) -> dict[str, float]:
"""Per-layer supported length inside a block DEFINITION (unit scale).
Exploding every INSERT for accounting is O(inserts x block size) and times
out on real Chinese sheet sets (hundreds of identical axis/door/window
blocks). Walking the definition once per block name and multiplying by the
insert scale gives the same length totals (rotation preserves length;
non-uniform scales are approximated by the mean of |sx|,|sy|).
"""
key = (id(doc), name)
cached = _BLOCK_LENGTHS_CACHE.get(key)
if cached is not None:
return cached
totals: dict[str, float] = defaultdict(float)
try:
block = doc.blocks.get(name)
except Exception:
return
for virtual_entity in virtual_entities:
if virtual_entity.dxftype() == "INSERT":
yield from iter_block_contents(virtual_entity, max_depth, depth + 1)
else:
yield virtual_entity
block = None
if block is not None:
for inner in block:
if inner.dxftype() == "INSERT" and depth < max_depth:
inner_name = str(inner.dxf.name) if inner.dxf.hasattr("name") else ""
if not inner_name:
continue
sx = abs(float(inner.dxf.get("xscale", 1.0) or 1.0))
sy = abs(float(inner.dxf.get("yscale", 1.0) or 1.0))
factor = (sx + sy) / 2.0
for layer, length in block_layer_unit_lengths(doc, inner_name, max_chord, max_depth, depth + 1).items():
totals[layer] += length * factor
else:
length = sum(
segment_length_source(segment)
for segment in derive.entity_segments(inner, max_chord)
)
if length > 0:
totals[derive.entity_layer(inner)] += length
result = dict(totals)
_BLOCK_LENGTHS_CACHE[key] = result
return result
def output_paths(output: Path) -> tuple[Path, Path]:
@@ -94,17 +121,34 @@ def inspect_entity(
)
segments = derive.entity_segments(entity, max_chord)
supported_length = sum(segment_length_source(segment) for segment in segments)
sample = None
if segments:
(sx, sy), (ex, ey) = segments[0]
sample = ((sx + ex) / 2.0, (sy + ey) / 2.0)
return {
"layer": layer,
"type": dxftype,
"category": category,
"segment_count": len(segments),
"supported_length": supported_length,
"sample": sample,
"high_risk": dxftype in HIGH_RISK_TYPES,
"insert_name": block_name or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
}
def config_clips(config: dict[str, Any]) -> list[list[float]]:
clips = []
for drawing in config.get("drawings", []) or []:
base = drawing.get("clip")
for floor in drawing.get("floors", []) or []:
clip = floor.get("clip", base)
if clip:
x0, y0, x1, y1 = clip
clips.append([min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)])
return clips
def source_files_from_config(dxf_dir: Path, config: dict[str, Any]) -> list[Path]:
drawings = config.get("drawings")
if drawings:
@@ -147,6 +191,9 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
total_supported = 0.0
classified_supported = 0.0
captured_from_blocks = 0.0
clips = config_clips(config)
clipped_total = 0.0
clipped_classified = 0.0
excludes = derive.exclude_layer_patterns(config)
max_block_depth = int(config.get("expand_blocks_max_depth", 2))
block_layer_lengths: dict[str, dict[str, Any]] = defaultdict(
@@ -172,19 +219,22 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
file_insert_names[insert_name] += 1
# Config-independent accounting of geometry locked inside blocks,
# so missing block expansion cannot hide behind a high coverage number.
for inner in iter_block_contents(source_entity, max_block_depth):
inner_length = sum(
segment_length_source(segment)
for segment in derive.entity_segments(inner, max_chord)
if insert_name:
sx = abs(float(source_entity.dxf.get("xscale", 1.0) or 1.0))
sy = abs(float(source_entity.dxf.get("yscale", 1.0) or 1.0))
factor = (sx + sy) / 2.0
unit_lengths = block_layer_unit_lengths(
doc, insert_name, max_chord, max_block_depth
)
if inner_length <= 0:
continue
inner_layer = derive.entity_layer(inner)
record = block_layer_lengths[inner_layer]
record["supported_length_source"] += inner_length
record["entity_count"] += 1
if record["category"] is None:
record["category"] = derive.match_category(inner_layer, patterns, excludes) or ""
for inner_layer, unit_length in unit_lengths.items():
inner_length = unit_length * factor
if inner_length <= 0:
continue
record = block_layer_lengths[inner_layer]
record["supported_length_source"] += inner_length
record["entity_count"] += 1
if record["category"] is None:
record["category"] = derive.match_category(inner_layer, patterns, excludes) or ""
for entity, fallback_layer, block_name in derive.iter_model_entities(source_entity, config):
item = inspect_entity(entity, patterns, config, max_chord, fallback_layer, block_name)
layer = item["layer"]
@@ -209,6 +259,12 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
captured_from_blocks += length
total_supported += length
file_total_supported += length
if clips and item["sample"] is not None:
px, py = item["sample"]
if any(c[0] <= px <= c[2] and c[1] <= py <= c[3] for c in clips):
clipped_total += length
if category:
clipped_classified += length
if item["high_risk"]:
# Top-level INSERTs were already counted above.
@@ -284,6 +340,12 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"block_locked_length_meters": round(block_locked_total * scale, 3),
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
# Clip-scoped view: with multi-frame clips, elevations/sections/details
# inflate the file-global denominator; judge extraction quality by THIS.
"clipped_supported_length_meters": round(clipped_total * scale, 3) if clips else None,
"clipped_supported_length_coverage": round(clipped_classified / clipped_total, 4)
if clips and clipped_total
else None,
},
"spec_counts": spec_counts(spec),
"files": file_reports,
@@ -296,21 +358,64 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"top_layers": dict(global_layer_counts.most_common(50)),
"agent_questions": agent_questions(unclassified_layers, global_high_risk, global_insert_names),
}
report["gates"] = evaluate_gates(report)
report["gates"] = evaluate_gates(report, spec, config)
return report
GATE_GLAZING_MIN_METERS = 5.0
GATE_ALIGN_CENTER_FACTOR = 0.35
def evaluate_gates(report: dict[str, Any]) -> list[dict[str, Any]]:
def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""FAIL when floors of one stack are horizontally scattered.
The classic multi-frame failure mode:每层保留了图框在图纸墙上的位置,
模型里楼层沿图框间距斜着排开. Wall-bbox centers of floors in the same
cap-group must agree to within GATE_ALIGN_CENTER_FACTOR x plan size.
"""
groups: dict[str, list[tuple[str, float, float, float]]] = defaultdict(list)
for fk, floor in spec.get("floors", {}).items():
walls = floor.get("segments", {}).get("walls") or []
if len(walls) < 10:
continue
xs = [v for s in walls for v in (s["start"][0], s["end"][0])]
ys = [v for s in walls for v in (s["start"][1], s["end"][1])]
size = max(max(xs) - min(xs), max(ys) - min(ys))
groups[derive._cap_floor_group(fk, config)].append(
(fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size)
)
worst: tuple[float, str] | None = None
for grp, items in groups.items():
if len(items) < 2:
continue
limit = GATE_ALIGN_CENTER_FACTOR * max(item[3] for item in items)
for i in range(len(items)):
for j in range(i + 1, len(items)):
dist = math.hypot(items[i][1] - items[j][1], items[i][2] - items[j][2])
if dist > limit and (worst is None or dist > worst[0]):
worst = (dist, f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})")
if worst:
return {
"name": "floors_aligned",
"status": "FAIL",
"detail": worst[1] + ". Floors are not stacked — per-frame offsets are missing or wrong; "
"run detect_sheet_frames.py and use its clip/offset config.",
}
return {
"name": "floors_aligned",
"status": "PASS",
"detail": "Wall-bbox centers of same-stack floors coincide.",
}
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any]) -> list[dict[str, Any]]:
"""Hard checks that must pass before 3D generation.
A gate FAIL means the extraction is known-incomplete in a way that high
coverage numbers cannot excuse; fix the config (block expansion, layer
mapping, source re-export) and re-run instead of accepting the model.
"""
gates: list[dict[str, Any]] = []
gates: list[dict[str, Any]] = [floors_alignment_gate(spec, config)]
spec_glazing_segments = sum(
counts.get("glazing", 0) for counts in report["spec_counts"].values()
@@ -428,6 +533,11 @@ def markdown(report: dict[str, Any]) -> str:
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
"(modelspace linework only — block-locked geometry is NOT in this denominator)",
*([
f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over "
f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — "
"on multi-frame sheets judge extraction by THIS number, not the file-global one"
] if coverage.get("clipped_supported_length_coverage") is not None else []),
f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",