feat: harden CAD showcase skill and delivery pipeline

This commit is contained in:
2026-07-10 09:21:13 +08:00
parent a6856f903d
commit 8b1b1d5e89
53 changed files with 5405 additions and 1327 deletions

View File

@@ -40,6 +40,8 @@ import math
import sys
from pathlib import Path
import showcase_schema
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
@@ -48,8 +50,12 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--out", required=True)
p.add_argument("--project-name", default=None)
p.add_argument("--description", default=None)
p.add_argument("--gap-warn", type=float, default=0.10,
help="warn when two buildings' wall envelopes are closer than this (m); overlap always fails")
p.add_argument(
"--gap-warn",
type=float,
default=0.10,
help="warn when two buildings' wall envelopes are closer than this (m); overlap always fails",
)
p.add_argument("--allow-overlap", action="store_true", help="downgrade overlap FAIL to warning")
return p.parse_args()
@@ -61,6 +67,7 @@ def make_xf(anchor, survey_m, origin_m, cos_t, sin_t):
def xf(p):
dx, dy = p[0] - ax, p[1] - ay
return [round(dx * cos_t - dy * sin_t + tx, 6), round(dx * sin_t + dy * cos_t + ty, 6)]
return xf
@@ -142,9 +149,15 @@ def main() -> int:
envelopes: dict[str, tuple] = {}
for name, b in manifest.get("buildings", {}).items():
if not isinstance(b, dict) or "spec" not in b:
print(f"skip {name}: no spec (status: {b.get('status', '?') if isinstance(b, dict) else b})", file=sys.stderr)
print(
f"skip {name}: no spec (status: {b.get('status', '?') if isinstance(b, dict) else b})", file=sys.stderr
)
continue
spec = json.loads(Path(b["spec"]).read_text(encoding="utf-8"))
spec = showcase_schema.normalize_spec(json.loads(Path(b["spec"]).read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(f"{name}: {exc}") from exc
if base_spec is None:
base_spec = spec
anchor = b.get("model_anchor_m") or b.get("model_anchor_center_m") or b.get("model_anchor_SE_wall_corner_m")
@@ -164,8 +177,11 @@ def main() -> int:
envelopes[name] = env
# re-key this building's roof_specs into the campus config later
b["_roof_specs"] = [
{**r, "floor_key": prefix + str(r.get("floor_key")),
"footprint_from": [prefix + str(k) for k in r.get("footprint_from", [r.get("floor_key")])]}
{
**r,
"floor_key": prefix + str(r.get("floor_key")),
"footprint_from": [prefix + str(k) for k in r.get("footprint_from", [r.get("floor_key")])],
}
for r in spec.get("source", {}).get("config", {}).get("roof_specs", [])
]
@@ -212,20 +228,31 @@ def main() -> int:
floors.update(placed)
campus = base_spec
campus["schema_version"] = showcase_schema.SCHEMA_VERSION
campus["floors"] = floors
campus["project"] = {
"name": args.project_name or manifest.get("project_name", "厂区"),
"description": args.description or manifest.get("description", "多栋建筑 + 场地(assemble_campus.py 合成)"),
}
cfg = campus.setdefault("source", {}).setdefault("config", {})
cfg["roof_specs"] = [r for b in manifest.get("buildings", {}).values()
if isinstance(b, dict) for r in b.get("_roof_specs", [])]
cfg["config_version"] = showcase_schema.CONFIG_VERSION
cfg["roof_specs"] = [
r for b in manifest.get("buildings", {}).values() if isinstance(b, dict) for r in b.get("_roof_specs", [])
]
cfg["floor_order"] = site_keys + [k for k in placed]
out = Path(args.out)
try:
showcase_schema.validate_spec(campus)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(campus, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"out": str(out), "floors": len(floors), "buildings": len(envelopes),
"site_floors": len(site_keys)}, ensure_ascii=False))
print(
json.dumps(
{"out": str(out), "floors": len(floors), "buildings": len(envelopes), "site_floors": len(site_keys)},
ensure_ascii=False,
)
)
return 0

View File

@@ -14,6 +14,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import derive_showcase_spec as derive # noqa: E402
import showcase_schema # noqa: E402
HIGH_RISK_TYPES = {
@@ -48,8 +49,8 @@ def parse_args() -> argparse.Namespace:
nargs="*",
default=None,
help="detect_sheet_frames out-config JSON(s): enables the frame-ledger gate "
"(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)",
"(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)",
)
return parser.parse_args()
@@ -87,10 +88,7 @@ def block_layer_unit_lengths(doc, name: str, max_chord: float, max_depth: int, d
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)
)
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)
@@ -141,7 +139,8 @@ def inspect_entity(
"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 ""),
"insert_name": block_name
or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
}
@@ -168,15 +167,17 @@ def spec_counts(spec: dict[str, Any]) -> dict[str, dict[str, int]]:
categories = [key for key in spec.get("categories", {}) if key != "slab"]
result = {}
for floor_key, floor in spec.get("floors", {}).items():
result[floor_key] = {
category: len(floor.get("segments", {}).get(category, []))
for category in categories
}
result[floor_key] = {category: len(floor.get("segments", {}).get(category, [])) for category in categories}
return result
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path,
frames: list[dict[str, Any]] | None = None) -> dict[str, Any]:
def audit(
dxf_dir: Path,
config: dict[str, Any],
spec: dict[str, Any],
vendor_dir: Path,
frames: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -232,9 +233,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
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
)
unit_lengths = block_layer_unit_lengths(doc, insert_name, max_chord, max_block_depth)
for inner_layer, unit_length in unit_lengths.items():
inner_length = unit_length * factor
if inner_length <= 0:
@@ -343,9 +342,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"coverage": {
"supported_length_meters": round(total_supported * scale, 3),
"classified_supported_length_meters": round(classified_supported * scale, 3),
"supported_length_coverage": round(classified_supported / total_supported, 4)
if total_supported
else None,
"supported_length_coverage": round(classified_supported / total_supported, 4) if total_supported else None,
"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),
@@ -390,9 +387,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
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)
)
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:
@@ -402,7 +397,10 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
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)})")
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",
@@ -432,16 +430,15 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for grp, keys in by_group.items():
if len(keys) < 2:
continue
ref_key = max(keys, key=lambda k: sum(
math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_key = max(keys, key=lambda k: sum(math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4)
ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4)
def zero_cov(ref_prof, prof, tol: float = 0.25) -> float:
total = sum(w for _, w in prof)
if total <= 0:
return 0.0
matched = sum(w for p, w in prof
if any(abs(p - rp) <= tol for rp, _ in ref_prof))
matched = sum(w for p, w in prof if any(abs(p - rp) <= tol for rp, _ in ref_prof))
return matched / total
for fk in keys:
@@ -455,8 +452,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
# let any small profile "match" somewhere: 27号 1#A PH)
if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov:
continue
if (shift is not None and cov >= 0.45 and ratio >= 1.5
and abs(shift) > 1.0):
if shift is not None and cov >= 0.45 and ratio >= 1.5 and abs(shift) > 1.0:
return {
"name": "floors_aligned",
"status": "FAIL",
@@ -475,28 +471,40 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
}
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any],
frames: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]:
def evaluate_gates(
report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any], frames: list[dict[str, Any]] | None = None
) -> 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]] = [floors_alignment_gate(spec, config)]
gates: list[dict[str, Any]] = [
{
"name": "all_config_drawings_present",
"status": "PASS",
"detail": "Every configured source drawing exists and passed config validation.",
},
{
"name": "unique_floor_keys",
"status": "PASS",
"detail": "Configured floor keys are unique.",
},
{
"name": "every_floor_nonempty",
"status": "PASS",
"detail": "Every floor contains segments, footprint polygons, or caps.",
},
floors_alignment_gate(spec, config),
]
spec_glazing_segments = sum(
counts.get("glazing", 0) for counts in report["spec_counts"].values()
)
spec_glazing_segments = sum(counts.get("glazing", 0) for counts in report["spec_counts"].values())
locked_glazing_meters = sum(
item["supported_length_meters"]
for item in report["block_locked_layers"]
if item["category"] == "glazing"
item["supported_length_meters"] for item in report["block_locked_layers"] if item["category"] == "glazing"
)
glazing_named_blocks = [
name
for name in report["top_insert_names"]
if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
name for name in report["top_insert_names"] if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
]
glazing_evidence = locked_glazing_meters >= GATE_GLAZING_MIN_METERS or bool(glazing_named_blocks)
if not glazing_evidence:
@@ -524,7 +532,7 @@ def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[st
gates.append(
{
"name": "no_annotation_layers_classified",
"status": "WARN" if annotation_classified else "PASS",
"status": "FAIL" if annotation_classified else "PASS",
"detail": (
f"Annotation/identification layers classified as geometry: {', '.join(annotation_classified[:5])}. "
"These are tags, not elements; exclude them."
@@ -586,8 +594,7 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
`"discarded_frames": [{"name": ..., "reason": ...}]`.
"""
if not frames:
return {"name": "frame_ledger", "status": "SKIP",
"detail": "No --frames given; frame ledger not checked."}
return {"name": "frame_ledger", "status": "SKIP", "detail": "No --frames given; frame ledger not checked."}
discarded = {str(d.get("name", "")) for d in config.get("discarded_frames", [])}
cfg_by_file: dict[str, list[dict[str, Any]]] = {}
for drawing in config.get("drawings", []) or []:
@@ -604,10 +611,7 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
clip = frame.get("clip")
if name in discarded:
continue
if clip and any(
fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3
for fl in cfg_floors
):
if clip and any(fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3 for fl in cfg_floors):
continue
unaccounted.append(f"{file}: {frame.get('key', '?')} {name}")
if unaccounted:
@@ -621,8 +625,11 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
"floors/wings vanish — use them or discard them WITH a reason."
),
}
return {"name": "frame_ledger", "status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded."}
return {
"name": "frame_ledger",
"status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded.",
}
def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -635,8 +642,11 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
"""
declared = config.get("declared_areas_m2")
if not declared:
return {"name": "area_declared", "status": "SKIP",
"detail": "No declared_areas_m2 in config; area cross-check not requested."}
return {
"name": "area_declared",
"status": "SKIP",
"detail": "No declared_areas_m2 in config; area cross-check not requested.",
}
tol = float(config.get("declared_area_tolerance", 0.15))
problems = []
for key, want in declared.items():
@@ -649,19 +659,26 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
if got <= 0:
problems.append(f"{key}: no footprint area in spec")
elif abs(got - want) / want > tol:
problems.append(f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)")
problems.append(
f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)"
)
if problems:
return {
"name": "area_declared",
"status": "FAIL",
"detail": ("Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."),
"detail": (
"Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."
),
}
return {"name": "area_declared", "status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values."}
return {
"name": "area_declared",
"status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values.",
}
def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -672,20 +689,29 @@ def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str,
"""
expected = config.get("expected_storeys_above_ground")
if expected is None:
return {"name": "storey_count", "status": "SKIP",
"detail": "No expected_storeys_above_ground in config; count cross-check not requested."}
return {
"name": "storey_count",
"status": "SKIP",
"detail": "No expected_storeys_above_ground in config; count cross-check not requested.",
}
import re as _re
actual = sum(1 for k in spec.get("floors", {}) if _re.fullmatch(r"F\d+", str(k)))
if actual != int(expected):
return {
"name": "storey_count",
"status": "FAIL",
"detail": (f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."),
"detail": (
f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."
),
}
return {"name": "storey_count", "status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count."}
return {
"name": "storey_count",
"status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count.",
}
def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]:
@@ -727,11 +753,15 @@ 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"- 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",
@@ -765,14 +795,12 @@ def markdown(report: dict[str, Any]) -> str:
lines.extend(["", "## Classified Layers", ""])
for layer in report["classified_layers"][:30]:
lines.append(
f"- `{layer['layer']}`: `{layer['categories']}`, "
f"classified length `{layer['classified_length_meters']}` m"
f"- `{layer['layer']}`: `{layer['categories']}`, classified length `{layer['classified_length_meters']}` m"
)
lines.extend(["", "## Files", ""])
for item in report["files"]:
lines.append(
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, "
f"high-risk `{item['high_risk_types']}`"
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, high-risk `{item['high_risk_types']}`"
)
return "\n".join(lines)
@@ -781,6 +809,12 @@ def main() -> int:
args = parse_args()
config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
try:
config = showcase_schema.validate_config(config, Path(args.dxf_dir))
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
frames = None
if args.frames:
frames = [json.loads(Path(p).read_text(encoding="utf-8")) for p in args.frames]

View File

@@ -9,6 +9,8 @@ import math
import sys
from pathlib import Path
import showcase_schema
CATEGORY_DRAW_ORDER = (
"grid",
@@ -43,7 +45,7 @@ def parse_args() -> argparse.Namespace:
if "--" in argv:
argv = argv[argv.index("--") + 1 :]
else:
argv = []
argv = argv[1:]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec", required=True, help="Path to building_spec.json")
parser.add_argument("--out-dir", required=True, help="Output folder")
@@ -210,7 +212,9 @@ def segment_prism(segment: dict, z0: float, z1: float):
]
def create_segment_mesh(bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str):
def create_segment_mesh(
bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str
):
verts = []
faces = []
for segment in segments:
@@ -288,7 +292,9 @@ def extend_shared_wall_ends(segments: list[dict], tol: float = 1e-3) -> list[dic
return out
def create_merged_wall_mesh(bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str):
def create_merged_wall_mesh(
bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str
):
"""Union wall-segment rectangles into one continuous solid (config
{"merge_wall_solids": true}) — removes corner seams and z-fighting at
junctions. Blender-native: delaunay_2d_cdt (output_type=1) triangulates the
@@ -339,7 +345,9 @@ def create_merged_wall_mesh(bpy, name: str, segments: list[dict], z0: float, z1:
return obj
def glazing_mullion_segments(bands: list[dict], z0: float, z1: float, panel_w: float = 1.5, profile: float = 0.06, depth: float = 0.10) -> list[dict]:
def glazing_mullion_segments(
bands: list[dict], z0: float, z1: float, panel_w: float = 1.5, profile: float = 0.06, depth: float = 0.10
) -> list[dict]:
"""Curtain-wall panel grid over glazing bands (mirror of spec_to_glb).
Emits pseudo wall segments (thin box profiles, rendered into the
@@ -361,18 +369,28 @@ def glazing_mullion_segments(bands: list[dict], z0: float, z1: float, panel_w: f
for i in range(panels + 1):
t = i * step
cx, cy = start[0] + ux * t, start[1] + uy * t
out.append({
"start": [cx - ux * profile / 2.0, cy - uy * profile / 2.0],
"end": [cx + ux * profile / 2.0, cy + uy * profile / 2.0],
"width": depth, "layer": segment.get("layer", ""), "source_type": "mullion",
})
out.append(
{
"start": [cx - ux * profile / 2.0, cy - uy * profile / 2.0],
"end": [cx + ux * profile / 2.0, cy + uy * profile / 2.0],
"width": depth,
"layer": segment.get("layer", ""),
"source_type": "mullion",
}
)
thickness = 0.08
for tz0, tz1 in ((z0, z0 + thickness), (z1 - thickness, z1)):
out.append({
"start": [float(start[0]), float(start[1])], "end": [float(end[0]), float(end[1])],
"width": depth, "layer": segment.get("layer", ""), "source_type": "transom",
"_z0": tz0, "_z1": tz1,
})
out.append(
{
"start": [float(start[0]), float(start[1])],
"end": [float(end[0]), float(end[1])],
"width": depth,
"layer": segment.get("layer", ""),
"source_type": "transom",
"_z0": tz0,
"_z1": tz1,
}
)
return out
@@ -536,12 +554,8 @@ def point_in_or_near_polygons(point: tuple[float, float], polygons: list[list[li
return False
def floor_group(floor_key: str) -> str:
if floor_key.startswith("AUX_"):
return "AUX"
if floor_key in {"B1", "B1M"}:
return "BASE"
return "MAIN"
def floor_group(floor_key: str, config: dict | None = None) -> str:
return showcase_schema.floor_group(floor_key, config)
def point_segment_distance(point: tuple[float, float], start: tuple[float, float], end: tuple[float, float]) -> float:
@@ -564,10 +578,10 @@ def column_has_upper_support(point: tuple[float, float], floor_key: str, floor:
structural_categories = set(config.get("column_support_categories", ["walls", "glazing", "columns", "beams"]))
require_upper_plate = bool(config.get("column_support_requires_upper_plate", True))
allow_plate_only = bool(config.get("column_support_allow_plate_only", False))
group = floor_group(floor_key)
group = floor_group(floor_key, config)
for other_key, other in spec.get("floors", {}).items():
if floor_group(other_key) != group:
if floor_group(other_key, config) != group:
continue
other_z = float(other.get("z", 0.0))
if not (floor_top - 0.05 <= other_z <= floor_top + z_tolerance):
@@ -587,7 +601,7 @@ def column_has_upper_support(point: tuple[float, float], floor_key: str, floor:
roof_z_tolerance = float(config.get("column_roof_support_z_tolerance", 0.65))
for roof in generated_roof_bounds(spec):
if floor_group(str(roof["floor_key"])) != group:
if floor_group(str(roof["floor_key"]), config) != group:
continue
if abs(float(roof["z"]) - floor_top) > roof_z_tolerance:
continue
@@ -679,10 +693,15 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
if config.get("glazing_mullions", False) and floor_segments.get("glazing"):
gz0, gz1 = z_window_for_category("glazing", z, height, floor_key, floor)
mullion_segments = glazing_mullion_segments(
floor_segments["glazing"], gz0, gz1, panel_w=float(config.get("glazing_panel_w", 1.5)),
floor_segments["glazing"],
gz0,
gz1,
panel_w=float(config.get("glazing_panel_w", 1.5)),
)
known = [category for category in CATEGORY_DRAW_ORDER if floor_segments.get(category)]
extra = sorted(category for category in floor_segments if category not in CATEGORY_DRAW_ORDER and floor_segments.get(category))
extra = sorted(
category for category in floor_segments if category not in CATEGORY_DRAW_ORDER and floor_segments.get(category)
)
if mullion_segments and "walls" not in known:
known.append("walls") # glazing-only floor still needs a walls object for the grid
for category in known + extra:
@@ -694,7 +713,14 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
z0, z1 = z_window_for_category(category, z, height, floor_key, floor)
if category == "walls" and config.get("merge_wall_solids", False) and segments:
merged = create_merged_wall_mesh(
bpy, f"{floor_key}__walls", segments, z0, z1, materials[category], floor_key, category,
bpy,
f"{floor_key}__walls",
segments,
z0,
z1,
materials[category],
floor_key,
category,
)
if merged is not None:
segments = [] # walls handled; mullions (if any) get their own pass below
@@ -849,6 +875,8 @@ def setup_scene(bpy, spec: dict):
def metadata(spec: dict, bounds: list[float], max_z: float, name: str) -> dict:
config = spec.get("source", {}).get("config", {})
return {
"metadata_version": 1,
"schema_version": spec.get("schema_version"),
"project": spec.get("project", {"name": name}),
"floors": [
{"key": key, "name": floor.get("name", key), "z": floor.get("z", 0), "height": floor.get("height", 4.2)}
@@ -868,12 +896,19 @@ def main() -> int:
try:
import bpy # type: ignore
except ImportError as exc:
raise SystemExit("Run this script with Blender: blender -b --python build_blender_showcase.py -- --spec ...") from exc
raise SystemExit(
"Run this script with Blender: blender -b --python build_blender_showcase.py -- --spec ..."
) from exc
spec_path = Path(args.spec)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
spec = json.loads(spec_path.read_text(encoding="utf-8"))
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
clear_scene(bpy)
bounds, max_z = setup_scene(bpy, spec)
@@ -896,14 +931,21 @@ def main() -> int:
if args.render:
bpy.context.scene.render.filepath = str(png_path)
bpy.ops.render.render(write_still=True)
metadata_path.write_text(json.dumps(metadata(spec, bounds, max_z, args.name), ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({
"blend": str(blend_path),
"glb": str(glb_path),
"png": str(png_path),
"metadata": str(metadata_path),
"objects": len(bpy.data.objects),
}, ensure_ascii=False))
metadata_path.write_text(
json.dumps(metadata(spec, bounds, max_z, args.name), ensure_ascii=False, indent=2), encoding="utf-8"
)
print(
json.dumps(
{
"blend": str(blend_path),
"glb": str(glb_path),
"png": str(png_path),
"metadata": str(metadata_path),
"objects": len(bpy.data.objects),
},
ensure_ascii=False,
)
)
return 0

View File

@@ -9,6 +9,8 @@ import math
import sys
from pathlib import Path
import showcase_schema
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
@@ -118,7 +120,15 @@ def segment_length(segment: dict) -> float:
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):
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,
@@ -172,7 +182,17 @@ def add_slab(np, ifcopenshell, model, body_context, storey, floor_key: str, floo
return slab
def add_segment_element(ifcopenshell, model, body_context, storey, floor_key: str, floor: dict, category: str, segment: dict, source_index: int):
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
@@ -276,9 +296,7 @@ def validate_ifc(ifcopenshell, path: Path, validate_geometry: bool) -> dict:
try:
geom.create_shape(settings, element)
except Exception as exc:
geometry_failures.append(
{"ifc_type": ifc_type, "name": element.Name, "error": str(exc)}
)
geometry_failures.append({"ifc_type": ifc_type, "name": element.Name, "error": str(exc)})
return {
"ifc_path": str(path),
@@ -310,7 +328,15 @@ def make_notes(report: dict) -> str:
"## Entity Counts",
"",
]
for key in ("IfcBuildingStorey", "IfcSlab", "IfcWall", "IfcColumn", "IfcBeam", "IfcPropertySet", "IfcExtrudedAreaSolid"):
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"]:
@@ -337,7 +363,11 @@ def make_notes(report: dict) -> str:
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"))
spec = showcase_schema.normalize_spec(json.loads(Path(args.spec).read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
model, body_context, building = make_model(np, ifcopenshell, spec, args.project_name)
created = {"IfcSlab": 0, "IfcWall": 0, "IfcColumn": 0, "IfcBeam": 0}
limits = {
@@ -384,7 +414,12 @@ def main() -> int:
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))
print(
json.dumps(
{"ifc": str(out_ifc), "report": str(out_report), "notes": str(out_notes), "created": created},
ensure_ascii=False,
)
)
return 0

View File

@@ -18,6 +18,8 @@ import subprocess
from pathlib import Path
from typing import Any
import showcase_schema
VARIANTS = [
{
@@ -160,10 +162,12 @@ def write_manifest(entries: list[dict[str, Any]], out_dir: Path, name: str) -> P
}
)
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
@@ -174,7 +178,12 @@ def main() -> int:
spec_path = Path(args.spec)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
spec = json.loads(spec_path.read_text(encoding="utf-8"))
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))

View File

@@ -8,6 +8,7 @@ import glob
import fnmatch
import json
import os
import re
import shutil
import subprocess
import sys
@@ -24,7 +25,17 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--work", default="work/cad_showcase", help="Intermediate work folder")
parser.add_argument("--output", default="outputs/cad_read_report", help="Output path stem or folder")
parser.add_argument("--vendor-dir", default="work/vendor", help="Optional Python vendor dir containing ezdxf")
parser.add_argument("--no-convert", action="store_true", help="Skip DWG conversion and only read existing DXF files")
parser.add_argument(
"--no-convert", action="store_true", help="Skip DWG conversion and only read existing DXF files"
)
parser.add_argument(
"--converter",
choices=("auto", "libredwg", "oda"),
default="auto",
help="auto=libredwg then ODA fallback; choose oda explicitly for 3DSOLID/ACIS drawings",
)
parser.add_argument("--allow-partial", action="store_true", help="Write a partial report instead of failing")
parser.add_argument("--partial-reason", help="Required justification when --allow-partial is used")
return parser.parse_args()
@@ -36,8 +47,7 @@ def import_ezdxf(vendor_dir: Path):
from ezdxf import bbox, recover # type: ignore
except ImportError as exc:
raise SystemExit(
"Missing dependency: ezdxf. Install locally with:\n"
f" python3 -m pip install --target {vendor_dir} ezdxf"
f"Missing dependency: ezdxf. Install locally with:\n python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
return ezdxf, bbox, recover
@@ -54,10 +64,7 @@ def safe_name(path: Path, used: set[str]) -> str:
def find_cad_files(input_dir: Path) -> list[Path]:
return sorted(
path for path in input_dir.rglob("*")
if path.is_file() and path.suffix.lower() in CAD_SUFFIXES
)
return sorted(path for path in input_dir.rglob("*") if path.is_file() and path.suffix.lower() in CAD_SUFFIXES)
def run_dwg2dxf(source: Path, dest: Path) -> dict:
@@ -129,7 +136,8 @@ def run_oda_batch(sources: list[Path], work_dir: Path) -> dict[Path, Path]:
try:
subprocess.run(
[exe, str(in_dir.resolve()), str(out_dir.resolve()), "ACAD2018", "DXF", "0", "1", "*.dwg"],
capture_output=True, timeout=1800,
capture_output=True,
timeout=1800,
)
except (subprocess.TimeoutExpired, OSError):
return {}
@@ -240,15 +248,13 @@ def xref_definitions(doc) -> list[dict]:
return xrefs
import re as _re
PLAN_TITLE_RE = _re.compile(r"平面图$")
PLAN_TITLE_EXCLUDE_RE = _re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
PLAN_TITLE_RE = re.compile(r"平面图$")
PLAN_TITLE_EXCLUDE_RE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
# AutoCAD MIF escapes (\M+5XXXX): CJK text in pre-Unicode DWGs survives
# DXF conversion as literal escape sequences, so title matching must decode
# them first. The digit selects the codepage; XXXX is the hex byte pair.
MIF_RE = _re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})")
MIF_RE = re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})")
MIF_CODEPAGES = {"1": "cp932", "2": "big5", "3": "cp949", "4": "johab", "5": "gbk"}
@@ -256,7 +262,7 @@ def decode_mif(text: str) -> str:
if "\\M+" not in text:
return text
def repl(match: "_re.Match[str]") -> str:
def repl(match: "re.Match[str]") -> str:
value = int(match.group(2), 16)
raw = value.to_bytes(2, "big") if value > 0xFF else value.to_bytes(1, "big")
try:
@@ -330,11 +336,14 @@ def file_warnings(item: dict) -> list[str]:
# pipeline has never seen — the layer mapping must be built consciously,
# or extraction silently captures nothing (patterns age, invariants don't).
wall_dialects = ("*WALL*", "*墙*", "*QIANG*")
layer_names = [l["name"] for l in item.get("layers", []) if l.get("entity_count", 0) > 0]
if (plan_titles >= 1 and (entities or 0) >= 400
and layer_names
and not any(fnmatch.fnmatch(n.upper(), p.upper()) for n in layer_names for p in wall_dialects)):
tops = ", ".join(l["name"] for l in item.get("top_layers", [])[:8])
layer_names = [layer["name"] for layer in item.get("layers", []) if layer.get("entity_count", 0) > 0]
if (
plan_titles >= 1
and (entities or 0) >= 400
and layer_names
and not any(fnmatch.fnmatch(n.upper(), p.upper()) for n in layer_names for p in wall_dialects)
):
tops = ", ".join(layer["name"] for layer in item.get("top_layers", [])[:8])
warnings.append(
f"unknown_layer_dialect: {plan_titles} plan title(s) but no wall-like layer "
f"(*WALL*/*墙*) among {len(layer_names)} populated layers — an unfamiliar design-institute "
@@ -380,11 +389,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
msp = doc.modelspace()
entities = list(msp)
type_counts = Counter(entity.dxftype() for entity in entities)
layer_counts = Counter(
str(entity.dxf.layer)
for entity in entities
if entity.dxf.hasattr("layer")
)
layer_counts = Counter(str(entity.dxf.layer) for entity in entities if entity.dxf.hasattr("layer"))
try:
geometry_bbox = bbox_tuple(bbox.extents(entities, fast=True))
except Exception as exc: # bbox can fail on unsupported proxy geometry.
@@ -415,10 +420,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
"modelspace_entities": len(entities),
"plan_title_count": count_plan_titles(entities),
"entity_types": dict(type_counts.most_common()),
"top_layers": [
{"name": name, "entity_count": count}
for name, count in layer_counts.most_common(30)
],
"top_layers": [{"name": name, "entity_count": count} for name, count in layer_counts.most_common(30)],
"layer_count": len(layers),
"layers": sorted(layers, key=lambda item: (-item["entity_count"], item["name"])),
"bbox": geometry_bbox,
@@ -445,12 +447,14 @@ def markdown_report(results: list[dict], conversions: list[dict], input_dir: Pat
for file_name, warning in all_warnings:
lines.append(f"- `{file_name}`: {warning}")
lines.append("")
lines.extend([
"## Files",
"",
"| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |",
"| --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
])
lines.extend(
[
"## Files",
"",
"| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |",
"| --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
]
)
for item in results:
bbox_data = item.get("bbox") or {}
size = bbox_data.get("size", ["", "", ""])
@@ -516,21 +520,43 @@ def main() -> int:
if not input_dir.exists():
raise SystemExit(f"Input folder not found: {input_dir}")
if args.allow_partial and not (args.partial_reason or "").strip():
raise SystemExit("--allow-partial requires --partial-reason")
# These folders are generated intermediates. Recreate them so a source
# removed between runs cannot survive as a stale DXF and enter modeling.
shutil.rmtree(raw_dir, ignore_errors=True)
shutil.rmtree(clean_dir, ignore_errors=True)
raw_dir.mkdir(parents=True, exist_ok=True)
clean_dir.mkdir(parents=True, exist_ok=True)
cad_files = find_cad_files(input_dir)
used_names: set[str] = set()
conversions: list[dict] = []
raw_dxfs: list[Path] = []
for source in find_cad_files(input_dir):
dest = raw_dir / safe_name(source, used_names)
assigned = [(source, raw_dir / safe_name(source, used_names)) for source in cad_files]
oda_outputs: dict[Path, Path] = {}
if args.converter == "oda" and not args.no_convert:
oda_outputs = run_oda_batch(
[source for source, _dest in assigned if source.suffix.lower() == ".dwg"],
work_dir,
)
for source, dest in assigned:
if source.suffix.lower() == ".dwg":
if args.no_convert:
continue
conversion = run_dwg2dxf(source, dest)
if args.converter == "oda":
produced = oda_outputs.get(source)
if produced:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(produced, dest)
conversion = {"source": str(source), "dest": str(dest), "status": "oda_ok"}
else:
conversion = {"source": str(source), "dest": str(dest), "status": "oda_failed"}
else:
conversion = run_dwg2dxf(source, dest)
conversions.append(conversion)
if conversion["status"] == "ok":
if conversion["status"] in {"ok", "oda_ok"}:
raw_dxfs.append(dest)
else:
if source.resolve() != dest.resolve():
@@ -565,7 +591,7 @@ def main() -> int:
if c.get("status") in {"failed", "missing_dwg2dxf"} and str(c.get("source", "")).lower().endswith(".dwg"):
name = Path(c["dest"]).name if c.get("dest") else Path(c["source"]).with_suffix(".dxf").name
retry.setdefault(name, Path(c["source"]))
if retry:
if retry and args.converter == "auto":
produced = run_oda_batch(list(retry.values()), work_dir)
for name, src in retry.items():
out = produced.get(src)
@@ -592,17 +618,58 @@ def main() -> int:
json_path.parent.mkdir(parents=True, exist_ok=True)
md_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"input": str(input_dir),
"work": str(work_dir),
"dxf_sanitized": str(clean_dir),
"report_version": 1,
"input": str(input_dir.resolve()),
"work": str(work_dir.resolve()),
"dxf_sanitized": str(clean_dir.resolve()),
"conversions": conversions,
"files": results,
}
# --no-convert is a diagnostic convenience, not permission to silently
# exclude DWGs from the source ledger. A mixed folder therefore fails the
# hard gate until every DWG is converted or the run is explicitly partial.
dwg_sources = {str(path) for path in cad_files if path.suffix.lower() == ".dwg"}
successful_dwg_sources = {
str(item.get("source")) for item in conversions if item.get("status") in {"ok", "oda_ok", "oda_fallback_ok"}
}
unresolved_dwgs = sorted(dwg_sources - successful_dwg_sources)
failed_files = [item.get("file", "?") for item in results if item.get("status") != "ok"]
empty_files = [
item.get("file", "?") for item in results if item.get("status") == "ok" and item.get("modelspace_entities") == 0
]
issues = []
if not cad_files:
issues.append("input contains no DWG/DXF files")
if unresolved_dwgs:
issues.append("unconverted DWG files: " + ", ".join(Path(path).name for path in unresolved_dwgs))
if failed_files:
issues.append("unreadable DXF files: " + ", ".join(failed_files))
if empty_files:
issues.append("zero-entity DXF files: " + ", ".join(empty_files))
if not results:
issues.append("no readable DXF files were produced")
payload["gate"] = {
"name": "all_sources_converted_and_readable",
"status": "WARN" if issues and args.allow_partial else ("FAIL" if issues else "PASS"),
"detail": "; ".join(issues) if issues else f"{len(results)} DXF file(s) readable",
"partial_reason": args.partial_reason if issues and args.allow_partial else None,
}
payload = scrub_surrogates(payload)
results = payload["files"]
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
md_path.write_text(markdown_report(results, conversions, input_dir), encoding="utf-8")
gate = payload["gate"]
gate_md = (
"## Source Gate\n\n"
f"- **{gate['status']}** `{gate['name']}`: {gate['detail']}"
+ (f"\n- Partial reason: {gate['partial_reason']}" if gate.get("partial_reason") else "")
+ "\n\n"
)
md_path.write_text(gate_md + markdown_report(results, conversions, input_dir), encoding="utf-8")
print(json.dumps({"json": str(json_path), "markdown": str(md_path), "files": len(results)}, ensure_ascii=False))
if issues and not args.allow_partial:
for issue in issues:
print(f"GATE FAIL [all_sources_converted_and_readable]: {issue}", file=sys.stderr)
return 3
return 0

419
scripts/cad_showcase.py Normal file
View File

@@ -0,0 +1,419 @@
#!/usr/bin/env python3
"""Resumable command-line orchestrator for the deterministic showcase pipeline."""
from __future__ import annotations
import argparse
import hashlib
import importlib.metadata
import json
import shutil
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import showcase_schema
from build_showcase_variants import default_blender
from cad_dxf_report import oda_converter
ROOT = Path(__file__).resolve().parent.parent
SCRIPTS = ROOT / "scripts"
def now() -> str:
return datetime.now(timezone.utc).isoformat()
def fingerprint(config: Path, source_report: Path, dxf_dir: Path) -> str:
"""Hash source data and pipeline code so resume cannot reuse stale work."""
digest = hashlib.sha256()
tracked = [config, source_report, *sorted(dxf_dir.glob("*.dxf"))]
tracked.extend(sorted(SCRIPTS.glob("*.py")))
tracked.extend(sorted((ROOT / "schemas").glob("*.json")))
tracked.extend(sorted((ROOT / "assets" / "web-showcase-template").glob("*")))
for path in tracked:
if not path.is_file():
continue
digest.update(str(path.relative_to(ROOT) if path.is_relative_to(ROOT) else path).encode("utf-8"))
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def output_ready(path: Path) -> bool:
if not path.exists():
return False
if path.is_file():
return path.stat().st_size > 0
return any(path.iterdir())
class Pipeline:
def __init__(self, state_path: Path, input_fingerprint: str, resume: bool):
self.path = state_path
self.resume = resume
if state_path.exists():
try:
current = json.loads(state_path.read_text(encoding="utf-8"))
except Exception:
current = {}
else:
current = {}
if current.get("input_fingerprint") != input_fingerprint:
current = {}
self.state: dict[str, Any] = {
"state_version": 1,
"input_fingerprint": input_fingerprint,
"started_at": current.get("started_at", now()),
"updated_at": now(),
"steps": current.get("steps", {}),
}
self.save()
def save(self) -> None:
self.state["updated_at"] = now()
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(self.state, ensure_ascii=False, indent=2), encoding="utf-8")
def run(
self,
name: str,
command: list[str],
outputs: list[Path],
forbidden_stderr: tuple[str, ...] = (),
) -> None:
old = self.state["steps"].get(name, {})
if (
self.resume
and old.get("status") == "PASS"
and old.get("command") == command
and all(output_ready(path) for path in outputs)
):
print(json.dumps({"step": name, "status": "SKIP", "reason": "resume"}, ensure_ascii=False))
return
started = now()
proc = subprocess.run(command, cwd=ROOT, text=True, capture_output=True)
forbidden_hits = [pattern for pattern in forbidden_stderr if pattern in proc.stderr]
effective_code = proc.returncode or (3 if forbidden_hits else 0)
entry = {
"status": "PASS" if effective_code == 0 else "FAIL",
"started_at": started,
"finished_at": now(),
"returncode": effective_code,
"command": command,
"outputs": [str(path) for path in outputs],
"stdout_tail": proc.stdout[-4000:],
"stderr_tail": proc.stderr[-4000:],
"forbidden_stderr_hits": forbidden_hits,
}
self.state["steps"][name] = entry
self.save()
if proc.stdout:
print(proc.stdout, end="")
if proc.stderr:
print(proc.stderr, file=sys.stderr, end="")
if forbidden_hits:
print(f"GATE FAIL [{name}]: forbidden warning(s): {', '.join(forbidden_hits)}", file=sys.stderr)
if effective_code != 0:
raise SystemExit(effective_code)
missing = [str(path) for path in outputs if not output_ready(path)]
if missing:
entry["status"] = "FAIL"
entry["stderr_tail"] += "\nMissing expected outputs: " + ", ".join(missing)
self.save()
raise SystemExit(f"Step {name} did not create expected outputs: {missing}")
def python_script(name: str, *args: str) -> list[str]:
return [sys.executable, str(SCRIPTS / name), *args]
def doctor() -> int:
modules = ["ezdxf", "jsonschema", "numpy", "shapely", "trimesh", "matplotlib", "PIL", "pygltflib"]
checks = []
failed = False
for module in modules:
try:
version = importlib.metadata.version("pillow" if module == "PIL" else module)
checks.append({"name": module, "status": "PASS", "version": version})
except Exception as exc:
checks.append({"name": module, "status": "FAIL", "detail": str(exc)})
failed = True
for executable in ("node", "npm", "dwg2dxf"):
path = shutil.which(executable)
checks.append({"name": executable, "status": "PASS" if path else "OPTIONAL", "path": path})
for executable, resolver in (("ODAFileConverter", oda_converter), ("blender", default_blender)):
candidate = resolver()
path = candidate if candidate and Path(candidate).exists() else None
checks.append({"name": executable, "status": "PASS" if path else "OPTIONAL", "path": path})
print(json.dumps({"status": "FAIL" if failed else "PASS", "checks": checks}, ensure_ascii=False, indent=2))
return 3 if failed else 0
def inspect_command(args: argparse.Namespace) -> int:
command = python_script(
"cad_dxf_report.py",
"--input",
args.input,
"--work",
args.work,
"--output",
args.output,
"--vendor-dir",
args.vendor_dir,
"--converter",
args.converter,
)
return subprocess.run(command, cwd=ROOT).returncode
def build_with_trimesh(pipeline: Pipeline, bundle: Path) -> list[Path]:
glbs = []
for key in ("overview", "standard", "detail"):
spec = bundle / "variant_specs" / f"{key}.json"
out_dir = bundle / "variants" / key
glb = out_dir / f"{key}.glb"
metadata = out_dir / "model_metadata.json"
pipeline.run(
f"glb_{key}",
python_script(
"spec_to_glb.py",
"--spec",
str(spec),
"--out",
str(glb),
"--metadata-out",
str(metadata),
"--name",
key,
),
[glb, metadata],
forbidden_stderr=("WARNING mesh_from_polygons",),
)
glbs.append(glb)
return glbs
def run_pipeline(args: argparse.Namespace) -> int:
dxf_dir = Path(args.dxf_dir).resolve()
config = Path(args.config).resolve()
source_report = Path(args.source_report).resolve()
try:
report = json.loads(source_report.read_text(encoding="utf-8"))
showcase_schema.validate_source_report(report, dxf_dir)
except (OSError, json.JSONDecodeError, showcase_schema.ValidationFailure) as exc:
print(f"GATE FAIL [source_report]: {exc}", file=sys.stderr)
return 3
out_dir = Path(args.out_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
pipeline = Pipeline(out_dir / "pipeline_state.json", fingerprint(config, source_report, dxf_dir), args.resume)
spec = out_dir / "building_spec.json"
audit = out_dir / "extraction_audit.json"
audit_md = out_dir / "extraction_audit.md"
overlays = out_dir / "overlays"
pipeline.run(
"derive",
python_script(
"derive_showcase_spec.py",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config),
"--out",
str(spec),
"--vendor-dir",
args.vendor_dir,
),
[spec],
forbidden_stderr=("WARNING topless_group",),
)
audit_cmd = python_script(
"audit_showcase_extraction.py",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config),
"--spec",
str(spec),
"--out",
str(audit),
"--vendor-dir",
args.vendor_dir,
)
if args.frames:
audit_cmd.extend(["--frames", *args.frames])
pipeline.run("audit", audit_cmd, [audit, audit_md])
pipeline.run(
"overlays",
python_script(
"draw_coverage_overlay.py",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config),
"--spec",
str(spec),
"--out-dir",
str(overlays),
"--vendor-dir",
args.vendor_dir,
),
[overlays],
)
bundle = out_dir / "delivery"
manifest = bundle / "variants_manifest.json"
variant_cmd = python_script(
"build_showcase_variants.py",
"--spec",
str(spec),
"--out-dir",
str(bundle),
"--name",
args.name,
)
if args.backend == "blender":
variant_cmd.append("--build")
if args.blender:
variant_cmd.extend(["--blender", args.blender])
pipeline.run("variants", variant_cmd, [manifest, bundle / "variant_specs" / "standard.json"])
if args.backend == "trimesh":
glbs = build_with_trimesh(pipeline, bundle)
else:
glbs = [bundle / "variants" / key / f"{key}.glb" for key in ("overview", "standard", "detail")]
web_dir = out_dir / "web"
if args.web:
pipeline.run(
"web",
python_script(
"write_web_showcase.py",
"--variants-manifest",
str(manifest),
"--out-dir",
str(web_dir),
"--title",
args.name,
),
[web_dir / "index.html", web_dir / "model.glb", web_dir / "model_metadata.json"],
)
if not args.skip_web_deps:
pipeline.run(
"web_dependencies",
["npm", "install", "--prefix", str(web_dir), "--ignore-scripts"],
[web_dir / "node_modules" / "three" / "build" / "three.module.js"],
)
standard = bundle / "variants" / "standard" / "standard.glb"
offline = out_dir / "viewer.html"
if args.offline:
pipeline.run(
"offline",
python_script(
"write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(standard),
"--out",
str(offline),
"--title",
args.name,
),
[offline],
)
preview = out_dir / "verify_previews.png"
pipeline.run(
"preview",
python_script(
"verify_showcase.py",
"--spec",
str(spec),
"--glb",
*[str(path) for path in glbs],
"--out",
str(preview),
"--budget-mb",
str(args.budget_mb),
"--strict",
),
[preview],
)
evidence = out_dir / "evidence_manifest.json"
verify_cmd = python_script(
"verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--variants-manifest",
str(manifest),
"--render",
str(preview),
"--budget-mb",
str(args.budget_mb),
"--evidence-out",
str(evidence),
)
if args.web:
verify_cmd.extend(["--web-dir", str(web_dir)])
if args.offline:
verify_cmd.extend(["--offline-viewer", str(offline)])
if args.browser_report:
verify_cmd.extend(["--browser-report", args.browser_report])
if args.require_browser_report:
verify_cmd.append("--require-browser-report")
pipeline.run("delivery_verification", verify_cmd, [evidence])
pipeline.state["status"] = "PASS"
pipeline.state["finished_at"] = now()
pipeline.save()
print(json.dumps({"status": "PASS", "out_dir": str(out_dir), "evidence": str(evidence)}, ensure_ascii=False))
return 0
def parser() -> argparse.ArgumentParser:
root = argparse.ArgumentParser(description=__doc__)
sub = root.add_subparsers(dest="command", required=True)
sub.add_parser("doctor", help="Check Python, Node, CAD converter, and Blender prerequisites")
inspect = sub.add_parser("inspect", help="Convert/read a CAD folder and enforce the source gate")
inspect.add_argument("--input", required=True)
inspect.add_argument("--work", required=True)
inspect.add_argument("--output", required=True)
inspect.add_argument("--vendor-dir", default="work/vendor")
inspect.add_argument("--converter", choices=("auto", "libredwg", "oda"), default="auto")
run = sub.add_parser("run", help="Run extract -> audit -> overlays -> variants -> verify from an approved config")
run.add_argument("--dxf-dir", required=True)
run.add_argument("--config", required=True)
run.add_argument("--source-report", required=True, help="Passing cad_read_report.json for this sanitized DXF dir")
run.add_argument("--out-dir", required=True)
run.add_argument("--name", default="cad_building_showcase")
run.add_argument("--vendor-dir", default="work/vendor")
run.add_argument("--frames", nargs="*", default=[])
run.add_argument("--backend", choices=("trimesh", "blender"), default="trimesh")
run.add_argument("--blender")
run.add_argument("--web", action="store_true")
run.add_argument("--skip-web-deps", action="store_true")
run.add_argument("--offline", action="store_true")
run.add_argument("--browser-report")
run.add_argument("--require-browser-report", action="store_true")
run.add_argument("--budget-mb", type=float, default=25.0)
run.add_argument("--resume", action="store_true")
return root
def main() -> int:
args = parser().parse_args()
if args.command == "doctor":
return doctor()
if args.command == "inspect":
return inspect_command(args)
return run_pipeline(args)
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -13,6 +13,8 @@ from collections import defaultdict
from pathlib import Path
from typing import Any
import showcase_schema
DEFAULT_CATEGORIES = {
"walls": {"label": "墙体", "color": "#d4cbb8", "width": 0.20},
@@ -78,16 +80,15 @@ def import_ezdxf(vendor_dir: Path):
from ezdxf import recover # type: ignore
except ImportError as exc:
raise SystemExit(
"Missing dependency: ezdxf. Install locally with:\n"
f" python3 -m pip install --target {vendor_dir} ezdxf"
f"Missing dependency: ezdxf. Install locally with:\n python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
return ezdxf, recover
def read_json(path: Path | None) -> dict[str, Any]:
if not path:
return {}
return json.loads(path.read_text(encoding="utf-8"))
return showcase_schema.normalize_config({})
return showcase_schema.normalize_config(json.loads(path.read_text(encoding="utf-8")))
def read_doc(path: Path, ezdxf, recover):
@@ -405,10 +406,7 @@ def polyline_points(entity) -> list[tuple[float, float]]:
if entity.dxftype() == "LWPOLYLINE":
return [(float(x), float(y)) for x, y in entity.get_points("xy")]
if entity.dxftype() == "POLYLINE":
return [
(float(vertex.dxf.location.x), float(vertex.dxf.location.y))
for vertex in entity.vertices
]
return [(float(vertex.dxf.location.x), float(vertex.dxf.location.y)) for vertex in entity.vertices]
return []
@@ -489,10 +487,7 @@ def collect_raw_segments(
recover,
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
patterns = layer_patterns(config)
default_widths = {
key: float(value.get("width", 0.1))
for key, value in DEFAULT_CATEGORIES.items()
}
default_widths = {key: float(value.get("width", 0.1)) for key, value in DEFAULT_CATEGORIES.items()}
default_widths.update({key: float(value) for key, value in config.get("default_widths", {}).items()})
scale = float(config.get("scale", config.get("scale_to_meters", 0.001)))
min_source_length = float(config.get("min_source_length", 1.0))
@@ -731,7 +726,9 @@ def generated_footprint(segments: dict[str, list[dict[str, Any]]], config: dict[
}
def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offset_tol: float = 0.30, gap_tol: float = 3.6) -> list[dict[str, Any]]:
def merge_collinear(
segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offset_tol: float = 0.30, gap_tol: float = 3.6
) -> list[dict[str, Any]]:
"""Merge collinear, near-touching segments into continuous spans.
CAD curtain walls are often drawn as sparse panel/mullion segments with gaps;
@@ -742,10 +739,14 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
groups: dict[tuple, list] = {}
keep: list[dict[str, Any]] = []
for s in segs:
a = s["start"]; b = s["end"]
dx = b[0] - a[0]; dy = b[1] - a[1]; length = math.hypot(dx, dy)
a = s["start"]
b = s["end"]
dx = b[0] - a[0]
dy = b[1] - a[1]
length = math.hypot(dx, dy)
if length < 1e-6:
keep.append(s); continue
keep.append(s)
continue
ang = math.atan2(dy, dx) % math.pi
akey = round(ang / math.radians(angle_tol_deg))
nx, ny = -dy / length, dx / length
@@ -757,8 +758,9 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
dirx, diry = -ny, nx
offv = a0[0] * nx + a0[1] * ny
intervals = []
for (a, b, *_rest) in items:
t0 = a[0] * dirx + a[1] * diry; t1 = b[0] * dirx + b[1] * diry
for a, b, *_rest in items:
t0 = a[0] * dirx + a[1] * diry
t1 = b[0] * dirx + b[1] * diry
intervals.append([min(t0, t1), max(t0, t1)])
intervals.sort()
merged = [intervals[0][:]]
@@ -768,11 +770,15 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
else:
merged.append([lo, hi])
for lo, hi in merged:
out.append({
"start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
"end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
"width": width, "layer": layer, "source_type": "merged",
})
out.append(
{
"start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
"end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
"width": width,
"layer": layer,
"source_type": "merged",
}
)
return out
@@ -783,14 +789,7 @@ def _cap_floor_group(fk: str, config: dict[str, Any] | None = None) -> str:
(fnmatch patterns, first match wins). Defaults reproduce the A208 case:
AUX_* prefix = annex tower, B1/B1M = basement, everything else = main.
"""
for pattern, group in (config or {}).get("cap_groups", []):
if fnmatch.fnmatch(fk.upper(), str(pattern).upper()):
return str(group)
if fk.startswith("AUX_"):
return "AUX"
if fk in {"B1", "B1M"}:
return "BASE"
return "MAIN"
return showcase_schema.floor_group(fk, config)
def _shapely_union(polys: list):
@@ -862,7 +861,9 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
fl.setdefault("caps", []).append({"z": round(ftop, 6), "polygons": polys})
def drop_isolated_clusters(segments: dict[str, list[dict[str, Any]]], config: dict[str, Any], floor_key: str) -> dict[str, list[dict[str, Any]]]:
def drop_isolated_clusters(
segments: dict[str, list[dict[str, Any]]], config: dict[str, Any], floor_key: str
) -> dict[str, list[dict[str, Any]]]:
"""Drop tiny segment clusters far away from the floor's main mass.
Sheet legends and title blocks draw window/door symbols with REAL geometry
@@ -925,8 +926,10 @@ def drop_isolated_clusters(segments: dict[str, list[dict[str, Any]]], config: di
seg = items[idx][2]
(x1, y1), (x2, y2) = seg["start"], seg["end"]
total += math.hypot(x2 - x1, y2 - y1)
bx[0] = min(bx[0], x1, x2); bx[1] = min(bx[1], y1, y2)
bx[2] = max(bx[2], x1, x2); bx[3] = max(bx[3], y1, y2)
bx[0] = min(bx[0], x1, x2)
bx[1] = min(bx[1], y1, y2)
bx[2] = max(bx[2], x1, x2)
bx[3] = max(bx[3], y1, y2)
return total, bx
stats = {root: cluster_stats(idx_list) for root, idx_list in clusters.items()}
@@ -1051,7 +1054,9 @@ def finalize_spec(
if key not in floor_data:
continue
floor = floor_data[key]
segments: dict[str, list[dict[str, Any]]] = {category: [] for category in DEFAULT_CATEGORIES if category != "slab"}
segments: dict[str, list[dict[str, Any]]] = {
category: [] for category in DEFAULT_CATEGORIES if category != "slab"
}
xs: list[float] = []
ys: list[float] = []
for category, raw_segments in floor["segments_source"].items():
@@ -1131,14 +1136,12 @@ def finalize_spec(
file=sys.stderr,
)
categories = {
key: {"label": value["label"], "color": value["color"]}
for key, value in DEFAULT_CATEGORIES.items()
}
categories = {key: {"label": value["label"], "color": value["color"]} for key, value in DEFAULT_CATEGORIES.items()}
for key, value in config.get("categories", {}).items():
categories.setdefault(key, {}).update(value)
return {
"schema_version": showcase_schema.SCHEMA_VERSION,
"project": {
"name": config.get("project_name", "CAD Building Showcase"),
"description": config.get("description", "建筑 CAD 生成的 Web 展示模型"),
@@ -1164,9 +1167,19 @@ def main() -> int:
if not dxf_dir.exists():
raise SystemExit(f"DXF folder not found: {dxf_dir}")
config = read_json(Path(args.config) if args.config else None)
try:
config = showcase_schema.validate_config(config, dxf_dir)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
floor_data, extraction_report = collect_raw_segments(dxf_dir, config, ezdxf, recover)
spec = finalize_spec(floor_data, config, extraction_report, dxf_dir)
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")

View File

@@ -30,13 +30,14 @@ from __future__ import annotations
import argparse
import fnmatch
import json
import math
import re
import statistics
import sys
from collections import Counter, defaultdict
from pathlib import Path
import showcase_schema
PLAN_TITLE = re.compile(r"平面图$")
PLAN_EXCLUDE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
@@ -60,6 +61,8 @@ def decode_mif(text: str) -> str:
return match.group(0)
return MIF_RE.sub(repl, text)
CN_NUM = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10}
FLOOR_NAME_KEY = [
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"B{_cn(m.group('n'))}M"),
@@ -124,22 +127,30 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--out-config", default="work/frames_config.json")
parser.add_argument("--out-report", default="work/frames_report.md")
parser.add_argument("--vendor-dir", default="work/vendor")
parser.add_argument("--title-regex", default=r"平面图$",
help="Plan-frame title pattern; e.g. '(?i)(FLOOR )?PLAN$' for English sets")
parser.add_argument(
"--title-regex", default=r"平面图$", help="Plan-frame title pattern; e.g. '(?i)(FLOOR )?PLAN$' for English sets"
)
parser.add_argument("--title-exclude-regex", default=r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
parser.add_argument("--title-exclude-layers", default="*图签*,*PUB_TAB*,*TK*,*图框*,*目录*")
# Wildcards matter: design institutes prefix layers (13号地块: A_DOTE/A_AXIS),
# and an exact "DOTE" token silently zeroes the grid-correlation votes.
parser.add_argument("--axis-layers", default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*",
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs")
parser.add_argument(
"--axis-layers",
default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*",
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs",
)
parser.add_argument("--wall-layers", default="WALL,*WALL*,*墙*")
parser.add_argument("--refine-fallback-layers",
default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*",
help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)")
parser.add_argument("--frame-aspect", type=float, default=1.5,
help="Initial clip width = pitch * aspect (A1 landscape + margin)")
parser.add_argument("--grid-bin", type=float, default=60.0,
help="Cluster tolerance (source units) for axis positions and vote bins")
parser.add_argument(
"--refine-fallback-layers",
default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*",
help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)",
)
parser.add_argument(
"--frame-aspect", type=float, default=1.5, help="Initial clip width = pitch * aspect (A1 landscape + margin)"
)
parser.add_argument(
"--grid-bin", type=float, default=60.0, help="Cluster tolerance (source units) for axis positions and vote bins"
)
return parser.parse_args()
@@ -304,8 +315,7 @@ def correlate_shift(ref_pos, src_pos, coarse: float = 500.0, fine: float = 50.0)
if not fine_votes:
return None, 0.0, 0.0
fb = max(fine_votes, key=lambda k: fine_votes[k])
sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos
if abs((rp - sp) - fb * fine) <= fine]
sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos if abs((rp - sp) - fb * fine) <= fine]
mass = sum(w for _, w in sel)
shift = sum(d * w for d, w in sel) / mass if mass else center
return shift, coverage, ratio
@@ -425,10 +435,12 @@ def main() -> int:
vk = ve.dxftype()
if vk == "LINE":
for p in (ve.dxf.start, ve.dxf.end):
xs_fb.append(float(p.x)); ys_fb.append(float(p.y))
xs_fb.append(float(p.x))
ys_fb.append(float(p.y))
elif vk == "LWPOLYLINE":
for px, py in ve.get_points("xy"):
xs_fb.append(float(px)); ys_fb.append(float(py))
xs_fb.append(float(px))
ys_fb.append(float(py))
except Exception:
continue
if not xs_fb:
@@ -501,19 +513,23 @@ def main() -> int:
notes = []
refine_groups = [wall_layers] + [
[p.strip() for p in group.split(",") if p.strip()]
for group in args.refine_fallback_layers.split("|") if group.strip()
for group in args.refine_fallback_layers.split("|")
if group.strip()
]
for t in titles:
rough = [t["x"] - clip_w * 0.55, t["y"] - pitch * 0.06, t["x"] + clip_w * 0.55, t["y"] + clip_h]
if pitch_x and not pitch_y:
# row layout: title x may sit anywhere under its frame; centre on it
rough = [t["x"] - clip_w * 0.6, t["y"] - clip_h * 0.04, t["x"] + clip_w * 0.6, t["y"] + clip_h]
frame_rect = next((r for r in frame_rects
if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
frame_rect = next((r for r in frame_rects if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
if frame_rect is not None:
fw, fh = frame_rect[2] - frame_rect[0], frame_rect[3] - frame_rect[1]
rough = [frame_rect[0] + fw * 0.01, frame_rect[1] + fh * 0.01,
frame_rect[2] - fw * 0.01, frame_rect[3] - fh * 0.01]
rough = [
frame_rect[0] + fw * 0.01,
frame_rect[1] + fh * 0.01,
frame_rect[2] - fw * 0.01,
frame_rect[3] - fh * 0.01,
]
notes.append(f"{t['name']}: frame-block rect used for clip window ({fw / 1000:.1f}x{fh / 1000:.1f} m)")
clip = None
for group in refine_groups:
@@ -524,8 +540,12 @@ def main() -> int:
margin = pitch * 0.06
clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin]
if frame_rect is not None: # never swallow the neighbour sheet
clip = [max(clip[0], rough[0]), max(clip[1], rough[1]),
min(clip[2], rough[2]), min(clip[3], rough[3])]
clip = [
max(clip[0], rough[0]),
max(clip[1], rough[1]),
min(clip[2], rough[2]),
min(clip[3], rough[3]),
]
break
if clip is None:
clip = rough
@@ -554,21 +574,24 @@ def main() -> int:
f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a "
"separate structure or revision sheet; excluded from reference candidacy"
)
floors.append({
"key": floor_key_for(t["name"], used_keys),
"name": t["name"],
"clip": [round(c, 1) for c in clip],
"_vx": cluster_positions(vert, args.grid_bin),
"_hy": cluster_positions(horiz, args.grid_bin),
"_walls": segments_in(lines, clip, wall_layers),
"_aux": bool(qualifier),
})
floors.append(
{
"key": floor_key_for(t["name"], used_keys),
"name": t["name"],
"clip": [round(c, 1) for c in clip],
"_vx": cluster_positions(vert, args.grid_bin),
"_hy": cluster_positions(horiz, args.grid_bin),
"_walls": segments_in(lines, clip, wall_layers),
"_aux": bool(qualifier),
}
)
def ref_rank(f):
# never anchor on auxiliary structures (bike ramps, 人防 revisions...);
# prefer a pure ground-floor plan, then the richest grid
f1_family = 0 if re.match(r"^F1(_\d+)?$", f["key"]) else 1
return (1 if f["_aux"] else 0, f1_family, -(len(f["_vx"]) + len(f["_hy"])))
reference = sorted(floors, key=ref_rank)[0]
alignment = []
@@ -587,12 +610,9 @@ def main() -> int:
# Grid voting failed (no axis geometry in this frame). Try wall-profile
# correlation before surrendering to the clip-corner anchor, which is
# off by whole bays whenever wall bboxes differ between floors.
wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0),
wall_profile(f["_walls"], 0))
wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1),
wall_profile(f["_walls"], 1))
if (wdx is not None and wdy is not None
and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5):
wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0), wall_profile(f["_walls"], 0))
wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1), wall_profile(f["_walls"], 1))
if wdx is not None and wdy is not None and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5:
f["offset"] = [round(wdx, 1), round(wdy, 1)]
alignment.append(
f"{f['key']}: wall-correlated (votes x={vx} y={vy}; coverage x={covx:.2f} "
@@ -600,8 +620,7 @@ def main() -> int:
f"offset={f['offset']}{aux_tag} — verify overlay!"
)
continue
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1),
round(reference["clip"][1] - f["clip"][1], 1)]
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1), round(reference["clip"][1] - f["clip"][1], 1)]
alignment.append(
f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']}{aux_tag} — verify overlay!"
)
@@ -626,34 +645,49 @@ def main() -> int:
covers = covered_floor_numbers(f["name"])
if covers:
for n in covers:
config_floors.append({"key": _unique_key(f"F{n}"), "name": f"{n}层({f['name']})",
"clip": f["clip"], "offset": f["offset"]})
notes.append(f"{f['name']}: multi-floor title expanded to "
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)")
config_floors.append(
{
"key": _unique_key(f"F{n}"),
"name": f"{n}层({f['name']})",
"clip": f["clip"],
"offset": f["offset"],
}
)
notes.append(
f"{f['name']}: multi-floor title expanded to "
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)"
)
else:
config_floors.append({"key": _unique_key(f["key"]), "name": f["name"],
"clip": f["clip"], "offset": f["offset"]})
config_floors.append(
{"key": _unique_key(f["key"]), "name": f["name"], "clip": f["clip"], "offset": f["offset"]}
)
config = {
"config_version": showcase_schema.CONFIG_VERSION,
"project_name": path.stem,
"scale": 0.001,
"floor_height": 4.2,
"_comment": "Review floor order/keys/z/heights (use elevation/section frames). offset stacks each frame onto the reference frame; origin_strategy normalizes globally.",
"origin_strategy": "min",
"drawings": [{
"file": path.name,
"floors": config_floors,
}],
"drawings": [
{
"file": path.name,
"floors": config_floors,
}
],
}
out_config = Path(args.out_config)
out_config.parent.mkdir(parents=True, exist_ok=True)
out_config.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
report = [
f"# Sheet Frame Detection: {path.name}", "",
f"# Sheet Frame Detection: {path.name}",
"",
f"- plan frames: {len(floors)} (sheet pitch ≈ {round(pitch, 1)})",
f"- reference frame: {reference['key']} ({reference['name']})", "",
"## Floors", "",
f"- reference frame: {reference['key']} ({reference['name']})",
"",
"## Floors",
"",
]
for f in floors:
report.append(f"- `{f['key']}` {f['name']} clip={f['clip']} offset={f['offset']}")
@@ -674,8 +708,10 @@ def main() -> int:
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
votes: Counter = Counter()
ladders: dict[str, set] = {o["name"]: set() for o in frames_e}
boxes = [(o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06,
o["x"] + clip_w * 0.6, o["y"] + clip_h) for o in frames_e]
boxes = [
(o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
for o in frames_e
]
for entity in msp:
if entity.dxftype() != "TEXT":
continue
@@ -701,10 +737,16 @@ def main() -> int:
report.append(line)
levels = sorted(v for v, n in votes.items() if n >= 2 or (votes[v] >= 1 and -20 < v < 150))
if levels:
report.extend(["", "## Suggested storey elevations (from 剖面/立面 标高 texts)", "",
"- " + ", ".join(f"{v:+.3f}" for v in levels),
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
"storey z = consecutive major levels, height = difference."])
report.extend(
[
"",
"## Suggested storey elevations (from 剖面/立面 标高 texts)",
"",
"- " + ", ".join(f"{v:+.3f}" for v in levels),
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
"storey z = consecutive major levels, height = difference.",
]
)
# Uniform-step suggestion: the dominant consecutive difference and
# its longest chain. A SUGGESTION for the Agent to verify against
# the 剖面 — stair sections beat at half-storey rhythm (2.25 for a
@@ -732,12 +774,20 @@ def main() -> int:
report.append(
f"- suggested storey table: uniform step {step} m x {len(best_chain) - 1} "
f"storeys, z {best_chain[0]:+.3f} → {best_chain[-1]:+.3f} — verify against "
"剖面/立面 per-frame ladders (podium and machine floors may differ)")
"剖面/立面 per-frame ladders (podium and machine floors may differ)"
)
Path(args.out_report).write_text("\n".join(report) + "\n", encoding="utf-8")
print(json.dumps({
"config": str(out_config), "report": args.out_report,
"floors": [f["key"] for f in floors], "pitch": round(pitch, 1),
}, ensure_ascii=False))
print(
json.dumps(
{
"config": str(out_config),
"report": args.out_report,
"floors": [f["key"] for f in floors],
"pitch": round(pitch, 1),
},
ensure_ascii=False,
)
)
return 0

View File

@@ -15,6 +15,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import derive_showcase_spec as derive # noqa: E402
import showcase_schema # noqa: E402
CATEGORY_COLORS = {
@@ -41,7 +42,9 @@ def parse_args() -> argparse.Namespace:
return parser.parse_args()
def source_to_meters(point: tuple[float, float], offset: tuple[float, float], origin: tuple[float, float], scale: float) -> tuple[float, float]:
def source_to_meters(
point: tuple[float, float], offset: tuple[float, float], origin: tuple[float, float], scale: float
) -> tuple[float, float]:
return (
(point[0] + offset[0] - origin[0]) * scale,
(point[1] + offset[1] - origin[1]) * scale,
@@ -53,7 +56,9 @@ def line_length(segment: tuple[tuple[float, float], tuple[float, float]]) -> flo
return math.hypot(ex - sx, ey - sy)
def collect_source_segments(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path) -> dict[str, list[dict[str, Any]]]:
def collect_source_segments(
dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path
) -> dict[str, list[dict[str, Any]]]:
ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -139,8 +144,7 @@ def draw_floor_svg(floor_key: str, floor: dict[str, Any], source_segments: list[
extracted_segments.append({**segment, "category": category, "source_type": "extracted"})
lines = [
'<svg xmlns="http://www.w3.org/2000/svg" width="1800" height="1200" '
f'viewBox="{view_box}">',
f'<svg xmlns="http://www.w3.org/2000/svg" width="1800" height="1200" viewBox="{view_box}">',
"<style>",
"text{font-family:Arial,sans-serif;font-size:1.2px;fill:#111}",
".legend text{font-size:1.1px}",
@@ -177,6 +181,12 @@ def main() -> int:
dxf_dir = Path(args.dxf_dir)
config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
try:
config = showcase_schema.validate_config(config, dxf_dir)
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
source_by_floor = collect_source_segments(dxf_dir, config, spec, Path(args.vendor_dir))
@@ -187,7 +197,9 @@ def main() -> int:
outputs.append(str(out_path))
index = out_dir / "index.html"
links = "\n".join(f'<li><a href="{Path(path).name}">{html.escape(Path(path).name)}</a></li>' for path in outputs)
index.write_text(f"<!doctype html><meta charset='utf-8'><title>CAD Overlay</title><ul>{links}</ul>", encoding="utf-8")
index.write_text(
f"<!doctype html><meta charset='utf-8'><title>CAD Overlay</title><ul>{links}</ul>", encoding="utf-8"
)
print(json.dumps({"out_dir": str(out_dir), "files": outputs}, ensure_ascii=False))
return 0

View File

@@ -33,9 +33,7 @@ def import_ezdxf(vendor_dir: Path):
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
raise SystemExit(f"Missing ezdxf. Install with: python3 -m pip install --target {vendor_dir} ezdxf") from exc
return ezdxf
@@ -59,8 +57,12 @@ def add_entity(space, ent: dict) -> None:
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,
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)
@@ -68,13 +70,16 @@ def add_entity(space, ent: dict) -> None:
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,
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"],
ent["name"],
ent["p"],
dxfattribs={
**attribs,
"xscale": ent.get("sx", 1.0) or 1.0,

View File

@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Extract flat ACIS 3DSOLID faces and DXF MESH entities to Y-up OBJ/GLB."""
from __future__ import annotations
import argparse
import json
import sys
from collections import Counter
from pathlib import Path
CURVED_RECORDS = (
"cone-surface",
"sphere-surface",
"spline-surface",
"torus-surface",
"cylinder-surface",
"swept-surface",
"revolution-surface",
)
def import_dependencies(vendor_dir: Path):
if vendor_dir.exists():
sys.path.insert(0, str(vendor_dir.resolve()))
try:
import ezdxf
import numpy as np
import trimesh
from ezdxf.acis import api as acis
except ImportError as exc:
raise SystemExit("Install requirements-core.txt (ezdxf, numpy, trimesh) before extracting solids") from exc
return ezdxf, np, trimesh, acis
def triangles_from_face_vertices(faces) -> list[list[tuple[float, float, float]]]:
triangles = []
for face in faces:
points = [(float(point.x), float(point.y), float(point.z)) for point in face]
if len(points) == 3:
triangles.append(points)
elif len(points) > 3:
for index in range(1, len(points) - 1):
triangles.append([points[0], points[index], points[index + 1]])
return triangles
def mesh_entity_triangles(entity) -> list[list[tuple[float, float, float]]]:
vertices = [
(
float(point.x if hasattr(point, "x") else point[0]),
float(point.y if hasattr(point, "y") else point[1]),
float(point.z if hasattr(point, "z") else point[2]),
)
for point in entity.vertices
]
triangles = []
for face in entity.faces:
indices = [int(index) for index in face]
if len(indices) < 3:
continue
for index in range(1, len(indices) - 1):
triangles.append([vertices[indices[0]], vertices[indices[index]], vertices[indices[index + 1]]])
return triangles
def trimesh_from_triangles(triangles, np, trimesh):
if not triangles:
return None
vertices = np.asarray(triangles, dtype=np.float64).reshape(-1, 3)
faces = np.arange(len(vertices), dtype=np.int64).reshape(-1, 3)
finite = np.isfinite(vertices).all(axis=1)
if not finite.all():
good_faces = finite.reshape(-1, 3).all(axis=1)
faces = faces[good_faces]
if len(faces) == 0:
return None
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
tri = mesh.vertices[mesh.faces]
areas = np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1) * 0.5
mesh.update_faces(np.isfinite(areas) & (areas > 1e-9))
mesh.remove_unreferenced_vertices()
if len(mesh.faces) == 0:
return None
# DXF/OBJ is Z-up; glTF is Y-up.
mesh.apply_transform(np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1.0]]))
return mesh
def acis_text(entity) -> str:
sat = getattr(entity, "sat", None)
if sat:
return "\n".join(str(item) for item in sat)
sab = getattr(entity, "sab", None)
return bytes(sab or b"").decode("latin1", errors="ignore")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dxf", required=True, help="ODA-converted R2000+ DXF containing 3DSOLID/MESH")
parser.add_argument("--out-glb", required=True)
parser.add_argument("--out-obj")
parser.add_argument("--report", required=True)
parser.add_argument("--vendor-dir", default="work/vendor")
args = parser.parse_args()
ezdxf, np, trimesh, acis = import_dependencies(Path(args.vendor_dir))
doc = ezdxf.readfile(args.dxf)
scene = trimesh.Scene()
report = {
"report_version": 1,
"source": str(Path(args.dxf)),
"entities": Counter(),
"acis_bodies": 0,
"captured_meshes": 0,
"captured_triangles": 0,
"curved_records": Counter(),
"failures": [],
}
index = 0
for entity in doc.modelspace():
kind = entity.dxftype()
if kind not in {"3DSOLID", "BODY", "REGION", "MESH"}:
continue
report["entities"][kind] += 1
if kind == "MESH":
candidates = [mesh_entity_triangles(entity)]
else:
text = acis_text(entity).lower()
for record in CURVED_RECORDS:
report["curved_records"][record] += text.count(record)
candidates = []
try:
bodies = acis.load_dxf(entity)
report["acis_bodies"] += len(bodies)
for body in bodies:
for mesh in acis.mesh_from_body(body, merge_lumps=False):
candidates.append(triangles_from_face_vertices(mesh.tessellation(max_vertex_count=3)))
except Exception as exc:
report["failures"].append({"handle": entity.dxf.handle, "type": kind, "error": str(exc)})
for triangles in candidates:
mesh = trimesh_from_triangles(triangles, np, trimesh)
if mesh is None:
continue
index += 1
scene.add_geometry(mesh, node_name=f"SOLID_{index:03d}__mesh", geom_name=f"SOLID_{index:03d}__mesh")
report["captured_meshes"] += 1
report["captured_triangles"] += int(len(mesh.faces))
report["entities"] = dict(report["entities"])
report["curved_records"] = {key: value for key, value in report["curved_records"].items() if value}
curved_total = sum(report["curved_records"].values())
report["status"] = "PASS" if report["captured_meshes"] else "FAIL"
report["limitations"] = (
f"{curved_total} curved ACIS surface record(s) require a full CAD kernel and were not tessellated."
if curved_total
else "Only flat polygonal ACIS faces and DXF MESH entities are supported."
)
report_path = Path(args.report)
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
if not report["captured_meshes"]:
print("GATE FAIL [solid_mesh_captured]: no flat ACIS/MESH geometry could be extracted", file=sys.stderr)
return 3
glb = Path(args.out_glb)
glb.parent.mkdir(parents=True, exist_ok=True)
scene.export(glb)
if args.out_obj:
obj = Path(args.out_obj)
obj.parent.mkdir(parents=True, exist_ok=True)
scene.export(obj)
print(json.dumps({"glb": str(glb), "meshes": index, "report": str(report_path)}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -57,10 +57,7 @@ def main() -> int:
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
}
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):

View File

@@ -23,10 +23,11 @@ import argparse
import json
from pathlib import Path
import showcase_schema
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--outline", required=True, help="JSON [[x,y],...] site meters")
parser.add_argument("--storeys", type=int, required=True)
parser.add_argument("--height", type=float, default=3.0, help="storey height (m)")
@@ -53,13 +54,16 @@ def main() -> int:
floors = {}
for i in range(1, args.storeys + 1):
walls = [{"start": a, "end": b, "width": args.wall_width, "layer": "MASSING"}
for a, b in zip(poly, poly[1:] + poly[:1])]
walls = [
{"start": a, "end": b, "width": args.wall_width, "layer": "MASSING", "source_type": "site_outline"}
for a, b in zip(poly, poly[1:] + poly[:1])
]
floors[f"F{i}"] = {
"name": f"{i}层(总图轮廓体量)",
"z": round((i - 1) * args.height, 3),
"height": args.height,
"bounds": bounds,
"source_file": "site_outline",
"segments": {"walls": walls},
"footprint": {"source": "site_outline", "polygons": [poly]},
"caps": [{"z": top_z, "polygons": [poly]}] if i == args.storeys else [],
@@ -67,30 +71,51 @@ def main() -> int:
label = args.label or args.name
spec = {
"project": args.name,
"description": (f"{label}:无交付图纸,按总平面轮廓×{args.storeys}层×{args.height}m "
"出体量(诚实标注,非详图模型)"),
"units": {"scale": 0.001, "origin_source": [ox, oy]},
"schema_version": showcase_schema.SCHEMA_VERSION,
"project": {
"name": args.name,
"description": (
f"{label}:无交付图纸,按总平面轮廓×{args.storeys}层×{args.height}m 出体量(诚实标注,非详图模型)"
),
},
"units": {"source": "meters", "scale_to_meters": 1.0, "origin_source": [ox, oy]},
"categories": {
"walls": {"label": "墙体(体量)", "color": "#d4cbb8", "width": args.wall_width},
"slab": {"label": "楼板", "color": "#c8ccc2", "width": 0.0},
},
"source": {"config": {"use_footprint_slabs": True, "generate_caps": True,
"roof_specs": [], "project_name": args.name}},
"source": {
"config": {
"config_version": showcase_schema.CONFIG_VERSION,
"use_footprint_slabs": True,
"generate_caps": True,
"roof_specs": [],
"project_name": args.name,
}
},
"floors": floors,
}
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(spec, ensure_ascii=False), encoding="utf-8")
ctr = [round(sum(p[0] for p in poly) / len(poly), 3),
round(sum(p[1] for p in poly) / len(poly), 3)]
print(json.dumps({
"out": str(out), "floors": args.storeys, "top_z": top_z,
"model_anchor_m": ctr,
"survey_anchor_m": [round(ctr[0] + ox, 3), round(ctr[1] + oy, 3)],
"rotation_deg": 0.0,
}, ensure_ascii=False))
ctr = [round(sum(p[0] for p in poly) / len(poly), 3), round(sum(p[1] for p in poly) / len(poly), 3)]
print(
json.dumps(
{
"out": str(out),
"floors": args.storeys,
"top_z": top_z,
"model_anchor_m": ctr,
"survey_anchor_m": [round(ctr[0] + ox, 3), round(ctr[1] + oy, 3)],
"rotation_deg": 0.0,
},
ensure_ascii=False,
)
)
return 0

View File

@@ -39,6 +39,8 @@ import math
import sys
from pathlib import Path
import showcase_schema
def dist_pt_seg(p, a, b) -> float:
ax, ay = a
@@ -66,8 +68,7 @@ def rot(p, th, c):
return (x * ct - y * st, x * st + y * ct)
def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
trim=0.9):
def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05, trim=0.9):
"""Best (theta_deg, translation, score) overlaying model polygons on points.
score = trimmed mean distance from each site point to the nearest
@@ -80,9 +81,10 @@ def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
def score_at(th_deg, t):
th = math.radians(th_deg)
edges = [((rot(a, th, mc)[0] + t[0], rot(a, th, mc)[1] + t[1]),
(rot(b, th, mc)[0] + t[0], rot(b, th, mc)[1] + t[1]))
for a, b in edges_m]
edges = [
((rot(a, th, mc)[0] + t[0], rot(a, th, mc)[1] + t[1]), (rot(b, th, mc)[0] + t[0], rot(b, th, mc)[1] + t[1]))
for a, b in edges_m
]
ds = sorted(min(dist_pt_seg(p, a, b) for a, b in edges) for p in site_pts)
k = max(1, int(len(ds) * trim))
return sum(ds[:k]) / k
@@ -99,9 +101,13 @@ def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
t = list(best[1])
for _ in range(4):
thr = math.radians(th0)
edges = [((rot(a, thr, mc)[0] + t[0], rot(a, thr, mc)[1] + t[1]),
(rot(b, thr, mc)[0] + t[0], rot(b, thr, mc)[1] + t[1]))
for a, b in edges_m]
edges = [
(
(rot(a, thr, mc)[0] + t[0], rot(a, thr, mc)[1] + t[1]),
(rot(b, thr, mc)[0] + t[0], rot(b, thr, mc)[1] + t[1]),
)
for a, b in edges_m
]
vecs = []
for p in site_pts:
dmin, q = 1e9, None
@@ -134,20 +140,26 @@ def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--spec", required=True, help="building_spec.json")
parser.add_argument("--floors", nargs="+", required=True,
help="floor keys whose footprints form the registration target")
parser.add_argument("--site-points", required=True,
help="JSON: [[x,y],...] site outline vertices / corner callouts (m)")
parser.add_argument("--angle-window", nargs=2, type=float, default=None,
metavar=("LO", "HI"), help="restrict rotation search (deg)")
parser.add_argument(
"--floors", nargs="+", required=True, help="floor keys whose footprints form the registration target"
)
parser.add_argument(
"--site-points", required=True, help="JSON: [[x,y],...] site outline vertices / corner callouts (m)"
)
parser.add_argument(
"--angle-window", nargs=2, type=float, default=None, metavar=("LO", "HI"), help="restrict rotation search (deg)"
)
parser.add_argument("--out", required=True)
parser.add_argument("--prefix", default="", help="building prefix for the manifest entry")
args = parser.parse_args()
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
spec = showcase_schema.normalize_spec(json.loads(Path(args.spec).read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
polys = []
for fk in args.floors:
floor = spec.get("floors", {}).get(fk)
@@ -155,8 +167,9 @@ def main() -> int:
raise SystemExit(f"floor {fk!r} not in spec")
polys.extend((floor.get("footprint") or {}).get("polygons") or [])
if not polys:
raise SystemExit("no footprint polygons on the requested floors — "
"enable generate_footprints or pick other floors")
raise SystemExit(
"no footprint polygons on the requested floors — enable generate_footprints or pick other floors"
)
raw = json.loads(Path(args.site_points).read_text(encoding="utf-8"))
site_pts = raw.get("points") if isinstance(raw, dict) else raw
site_pts = [(float(p[0]), float(p[1])) for p in site_pts]
@@ -185,12 +198,19 @@ def main() -> int:
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"out": str(out), "rotation_deg": result["rotation_deg"],
"residual_m": result["residual_m"]}, ensure_ascii=False))
print(
json.dumps(
{"out": str(out), "rotation_deg": result["rotation_deg"], "residual_m": result["residual_m"]},
ensure_ascii=False,
)
)
if score > 2.0:
print(f"WARNING residual {score:.2f} m is high — wrong outline, wrong floors, "
"or the site points include strays (garage outline / fire pads); "
"plot the overlay before trusting this placement.", file=sys.stderr)
print(
f"WARNING residual {score:.2f} m is high — wrong outline, wrong floors, "
"or the site points include strays (garage outline / fire pads); "
"plot the overlay before trusting this placement.",
file=sys.stderr,
)
return 0

View File

@@ -23,7 +23,7 @@ def parse_args() -> argparse.Namespace:
if "--" in argv:
argv = argv[argv.index("--") + 1 :]
else:
argv = []
argv = argv[1:]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--meshes", required=True, help="Mesh JSON from extract_ifc_meshes.py")
parser.add_argument("--out-dir", required=True)
@@ -149,7 +149,9 @@ def main() -> int:
try:
import bpy # type: ignore
except ImportError as exc:
raise SystemExit("Run this script with Blender: blender -b --python render_ifc_meshes_blender.py -- --meshes ...") from exc
raise SystemExit(
"Run this script with Blender: blender -b --python render_ifc_meshes_blender.py -- --meshes ..."
) from exc
payload = json.loads(Path(args.meshes).read_text(encoding="utf-8"))
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
@@ -171,7 +173,17 @@ def main() -> int:
bpy.ops.export_scene.gltf(filepath=str(glb_path), export_format="GLB")
bpy.context.scene.render.filepath = str(png_path)
bpy.ops.render.render(write_still=True)
print(json.dumps({"blend": str(blend_path), "glb": str(glb_path), "png": str(png_path), "mesh_objects": [obj.name for obj in objects]}, ensure_ascii=False))
print(
json.dumps(
{
"blend": str(blend_path),
"glb": str(glb_path),
"png": str(png_path),
"mesh_objects": [obj.name for obj in objects],
},
ensure_ascii=False,
)
)
return 0

268
scripts/showcase_schema.py Normal file
View File

@@ -0,0 +1,268 @@
#!/usr/bin/env python3
"""Shared schema and semantic validation for CAD showcase artifacts."""
from __future__ import annotations
import argparse
import copy
import fnmatch
import json
from pathlib import Path
from typing import Any
SCHEMA_VERSION = 1
CONFIG_VERSION = 1
MANIFEST_VERSION = 1
REPORT_VERSION = 1
ROOT = Path(__file__).resolve().parent.parent
SCHEMA_DIR = ROOT / "schemas"
class ValidationFailure(ValueError):
"""Raised when a config or generated artifact violates the contract."""
def _validator(schema_name: str):
try:
import jsonschema
except ImportError:
return None
schema = json.loads((SCHEMA_DIR / schema_name).read_text(encoding="utf-8"))
return jsonschema.Draft202012Validator(schema)
def _format_errors(errors) -> list[str]:
result = []
for error in sorted(errors, key=lambda item: list(item.absolute_path)):
path = ".".join(str(part) for part in error.absolute_path) or "$"
result.append(f"{path}: {error.message}")
return result
def schema_errors(data: dict[str, Any], schema_name: str) -> list[str]:
validator = _validator(schema_name)
if validator is not None:
return _format_errors(validator.iter_errors(data))
# Blender ships an isolated Python without project dependencies. Keep a
# small structural fallback so direct Blender runs still fail on broken
# artifacts; normal CPython runs use the full Draft 2020-12 schemas.
if schema_name == "building_spec.schema.json":
required = {"schema_version", "project", "source", "units", "categories", "floors"}
elif schema_name == "extraction_config.schema.json":
required = {"config_version"}
else:
required = {"manifest_version", "name", "default_key", "variants"}
return [f"$: missing required property {key!r}" for key in sorted(required - set(data))]
def normalize_config(config: dict[str, Any]) -> dict[str, Any]:
"""Attach the current version while keeping legacy v0 configs readable."""
normalized = dict(config)
normalized.setdefault("config_version", CONFIG_VERSION)
if normalized.get("origin_strategy") == "min_corner":
normalized["origin_strategy"] = "min"
return normalized
def normalize_spec(spec: dict[str, Any]) -> dict[str, Any]:
"""Read pre-versioning artifacts while emitting only the current contract."""
normalized = copy.deepcopy(spec)
normalized.setdefault("schema_version", SCHEMA_VERSION)
project = normalized.get("project", {})
if isinstance(project, str):
project = {"name": project, "description": str(normalized.pop("description", ""))}
else:
project = dict(project)
project.setdefault("name", "CAD Building Showcase")
project.setdefault("description", str(normalized.pop("description", "")))
normalized["project"] = project
source = dict(normalized.get("source", {}))
source["config"] = normalize_config(dict(source.get("config", {})))
normalized["source"] = source
raw_units = normalized.get("units", {})
units = {"source": raw_units} if isinstance(raw_units, str) else dict(raw_units)
scale = float(units.pop("scale", units.get("scale_to_meters", 0.001)))
units.setdefault("source", "millimeters" if scale == 0.001 else "unknown")
units.setdefault("scale_to_meters", scale)
units.setdefault("origin_source", [0.0, 0.0])
normalized["units"] = units
for floor in normalized.get("floors", {}).values():
floor.setdefault("source_file", "unknown")
for category, segments in floor.get("segments", {}).items():
for segment in segments:
segment.setdefault("width", 0.1)
segment.setdefault("layer", "")
segment.setdefault("source_type", "legacy")
return normalized
def floor_group(floor_key: str, config: dict[str, Any] | None = None) -> str:
"""Return the configured stack group used by caps and support checks."""
for pattern, group in (config or {}).get("cap_groups", []):
if fnmatch.fnmatch(floor_key.upper(), str(pattern).upper()):
return str(group)
if floor_key.startswith("AUX_"):
return "AUX"
if floor_key in {"B1", "B1M"}:
return "BASE"
return "MAIN"
def config_semantic_errors(config: dict[str, Any], dxf_dir: Path | None = None) -> list[str]:
errors: list[str] = []
seen: dict[str, str] = {}
drawings = config.get("drawings", []) or []
if not drawings:
errors.append("drawings: extraction config contains no drawings")
for drawing in drawings:
file_name = str(drawing.get("file", ""))
if dxf_dir is not None and file_name and not (dxf_dir / file_name).exists():
errors.append(f"drawings[{file_name}]: source DXF does not exist under {dxf_dir}")
floors = drawing.get("floors") or [{"key": Path(file_name).stem}]
for floor in floors:
key = str(floor.get("key", ""))
location = f"{file_name}:{floor.get('name', key)}"
if key in seen:
errors.append(f"duplicate floor key {key!r}: used by both {seen[key]} and {location}")
else:
seen[key] = location
order = config.get("floor_order") or []
missing = sorted(set(seen) - set(order)) if order else []
ghosts = sorted(set(order) - set(seen)) if order else []
if missing:
errors.append(f"floor_order omits configured floor keys: {missing}")
if ghosts:
errors.append(f"floor_order contains unknown floor keys: {ghosts}")
return errors
def validate_config(config: dict[str, Any], dxf_dir: Path | None = None) -> dict[str, Any]:
normalized = normalize_config(config)
errors = schema_errors(normalized, "extraction_config.schema.json")
errors.extend(config_semantic_errors(normalized, dxf_dir))
if errors:
raise ValidationFailure("Invalid extraction config:\n- " + "\n- ".join(errors))
return normalized
def spec_semantic_errors(spec: dict[str, Any]) -> list[str]:
errors: list[str] = []
floors = spec.get("floors", {})
categories = set(spec.get("categories", {}))
if not floors:
errors.append("floors: spec contains no floors")
for key, floor in floors.items():
unknown_categories = sorted(
category for category, items in floor.get("segments", {}).items() if items and category not in categories
)
if unknown_categories:
errors.append(f"floors.{key}.segments: categories missing from spec.categories: {unknown_categories}")
segment_count = sum(len(items) for items in floor.get("segments", {}).values())
polygon_count = len((floor.get("footprint") or {}).get("polygons", []))
cap_count = sum(len(cap.get("polygons", [])) for cap in floor.get("caps", []))
if segment_count == 0 and polygon_count == 0 and cap_count == 0:
errors.append(f"floors.{key}: floor has no segments, footprint polygons, or caps")
for item in spec.get("extraction_report", []):
if item.get("status") != "ok":
errors.append(f"extraction_report: {item.get('file', '?')} status={item.get('status', '?')}")
return errors
def validate_spec(spec: dict[str, Any]) -> dict[str, Any]:
errors = schema_errors(spec, "building_spec.schema.json")
embedded_config = normalize_config(dict(spec.get("source", {}).get("config", {})))
errors.extend(f"source.config.{item}" for item in schema_errors(embedded_config, "extraction_config.schema.json"))
errors.extend(spec_semantic_errors(spec))
if errors:
raise ValidationFailure("Invalid building spec:\n- " + "\n- ".join(errors))
return spec
def validate_manifest(manifest: dict[str, Any]) -> dict[str, Any]:
errors = schema_errors(manifest, "variants_manifest.schema.json")
keys = [item.get("key") for item in manifest.get("variants", [])]
if len(keys) != len(set(keys)):
errors.append("variants: duplicate variant keys")
if manifest.get("default_key") not in keys:
errors.append("default_key: does not reference a variant key")
if errors:
raise ValidationFailure("Invalid variants manifest:\n- " + "\n- ".join(errors))
return manifest
def validate_source_report(report: dict[str, Any], expected_dxf_dir: Path | None = None) -> dict[str, Any]:
if not isinstance(report, dict):
raise ValidationFailure("Invalid CAD source report:\n- $: expected a JSON object")
errors = []
if report.get("report_version") != REPORT_VERSION:
errors.append(f"report_version: expected {REPORT_VERSION}, got {report.get('report_version')!r}")
gate = report.get("gate") or {}
if not isinstance(gate, dict):
gate = {}
if gate.get("name") != "all_sources_converted_and_readable" or gate.get("status") != "PASS":
errors.append(f"gate: all_sources_converted_and_readable must be PASS, got {gate.get('status')!r}")
files = report.get("files")
if not isinstance(files, list) or not files:
errors.append("files: report contains no inspected DXF files")
else:
for index, item in enumerate(files):
if not isinstance(item, dict):
errors.append(f"files[{index}]: expected an object")
continue
try:
entity_count = int(item.get("modelspace_entities", 0) or 0)
except (TypeError, ValueError):
entity_count = 0
if item.get("status") != "ok" or entity_count <= 0:
errors.append(
f"files[{index}]: {item.get('file', '?')} is not readable and nonempty "
f"(status={item.get('status')!r}, entities={item.get('modelspace_entities')!r})"
)
if expected_dxf_dir is not None:
reported = Path(str(report.get("dxf_sanitized", "")))
if not reported.is_absolute():
reported = ROOT / reported
if reported.resolve() != expected_dxf_dir.resolve():
errors.append(
f"dxf_sanitized: report points to {reported.resolve()}, expected {expected_dxf_dir.resolve()}"
)
elif expected_dxf_dir.exists():
report_items = files if isinstance(files, list) else []
reported_files = {str(item.get("file")) for item in report_items if isinstance(item, dict)}
actual_files = {path.name for path in expected_dxf_dir.glob("*.dxf")}
if reported_files != actual_files:
errors.append(
"files: source report and sanitized directory differ "
f"(missing={sorted(actual_files - reported_files)}, stale={sorted(reported_files - actual_files)})"
)
if errors:
raise ValidationFailure("Invalid CAD source report:\n- " + "\n- ".join(errors))
return report
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("kind", choices=("config", "spec", "manifest", "source-report"))
parser.add_argument("path")
parser.add_argument("--dxf-dir", help="Required for checking config source-file existence")
args = parser.parse_args()
try:
data = json.loads(Path(args.path).read_text(encoding="utf-8"))
if args.kind == "config":
validate_config(data, Path(args.dxf_dir) if args.dxf_dir else None)
elif args.kind == "spec":
validate_spec(data)
elif args.kind == "manifest":
validate_manifest(data)
else:
validate_source_report(data, Path(args.dxf_dir) if args.dxf_dir else None)
except (OSError, json.JSONDecodeError, ValidationFailure, TypeError, ValueError, AttributeError) as exc:
print(str(exc))
return 3
print(json.dumps({"status": "PASS", "kind": args.kind, "path": args.path}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -25,16 +25,31 @@ import json
import math
from pathlib import Path
ROAD_LAYERS = {"Z5-车行道": 0.30, "Z5-道路中心线": 0.10, "Z6-其他符号": 0.12,
"Z2-绿化控制线": 0.08, "Z2-建筑退界线": 0.08, "竖向": 0.08}
ROAD_LAYERS = {
"Z5-车行道": 0.30,
"Z5-道路中心线": 0.10,
"Z6-其他符号": 0.12,
"Z2-绿化控制线": 0.08,
"Z2-建筑退界线": 0.08,
"竖向": 0.08,
}
PARKING_LAYERS = {"Z3-车位": 0.08}
FENCE_LAYERS = {"Z3-围墙": 0.15}
BOUNDARY_LAYERS = ["Z2-用地红线"]
TREE_LAYERS = ["Z4-树层(行道树)", "*树*"]
MASSING_LAYERS = ["平面", "屋面", "面积核算", "*建筑轮廓*"]
MASSING_HEIGHTS = [("2#", 24.0), ("3#", 8.5), ("辅房", 8.5), ("门卫", 3.5),
("停车", 4.0), ("污水", 2.0), ("水池", 2.0), ("消控", 3.5),
("连廊", 4.5), ("钢楼梯", 6.5)]
MASSING_HEIGHTS = [
("2#", 24.0),
("3#", 8.5),
("辅房", 8.5),
("门卫", 3.5),
("停车", 4.0),
("污水", 2.0),
("水池", 2.0),
("消控", 3.5),
("连廊", 4.5),
("钢楼梯", 6.5),
]
MASSING_SKIP = ("出入口",) # gate openings marked as small rects; not volumes
LABEL_SKIP = __import__("re").compile(r"^[XxYy]=|^[-+]?\d+([.,]\d+)?$")
DEFAULT_MASSING_H = 6.0
@@ -43,14 +58,35 @@ DEFAULT_MASSING_H = 6.0
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--dump", action="append", required=True, help="dump JSON path (repeatable)")
p.add_argument("--scale", action="append", required=True, type=float,
help="units->meters factor for the matching --dump (1.0 for m, 0.001 for mm)")
p.add_argument("--region", nargs=4, type=float, required=True, metavar=("X0", "Y0", "X1", "Y1"),
help="surveying-meter window selecting ONE plan copy")
p.add_argument("--origin", nargs=2, type=float, required=True,
help="campus local origin in surveying meters (e.g. 红线 min corner)")
p.add_argument("--exclude-quad", nargs=8, type=float, default=None,
help="4 corners (m) of the real-model building; site geometry inside is dropped")
p.add_argument(
"--scale",
action="append",
required=True,
type=float,
help="units->meters factor for the matching --dump (1.0 for m, 0.001 for mm)",
)
p.add_argument(
"--region",
nargs=4,
type=float,
required=True,
metavar=("X0", "Y0", "X1", "Y1"),
help="surveying-meter window selecting ONE plan copy",
)
p.add_argument(
"--origin",
nargs=2,
type=float,
required=True,
help="campus local origin in surveying meters (e.g. 红线 min corner)",
)
p.add_argument(
"--exclude-quad",
nargs=8,
type=float,
default=None,
help="4 corners (m) of the real-model building; site geometry inside is dropped",
)
p.add_argument("--out", required=True)
return p.parse_args()
@@ -59,8 +95,10 @@ def flatten_arc(c, r, sa, ea, scale):
if ea < sa:
ea += math.tau
steps = max(8, min(48, int(abs(ea - sa) * r * scale / 1.5) + 8))
return [(c[0] + math.cos(sa + (ea - sa) * i / steps) * r,
c[1] + math.sin(sa + (ea - sa) * i / steps) * r) for i in range(steps + 1)]
return [
(c[0] + math.cos(sa + (ea - sa) * i / steps) * r, c[1] + math.sin(sa + (ea - sa) * i / steps) * r)
for i in range(steps + 1)
]
def in_quad(pt, quad):
@@ -82,6 +120,7 @@ def in_quad(pt, quad):
def match(layer: str, patterns) -> bool:
import fnmatch
return any(fnmatch.fnmatch(layer, p) for p in patterns)
@@ -109,7 +148,8 @@ def main() -> int:
if math.hypot(b[0] - a[0], b[1] - a[1]) < 0.15:
return
segs[floor].setdefault(cat, []).append(
{"start": local(a), "end": local(b), "width": width, "layer": layer, "source_type": "SITE"})
{"start": local(a), "end": local(b), "width": width, "layer": layer, "source_type": "SITE"}
)
for dump_path, scale in zip(args.dump, args.scale):
d = json.loads(Path(dump_path).read_text(encoding="utf-8"))
@@ -127,6 +167,7 @@ def main() -> int:
def tf(pt):
tx, ty = pt[0] * sx, pt[1] * sy
return (px + tx * cr - ty * srr, py + tx * srr + ty * cr)
for be in blocks.get(name, []):
if be["t"] == "LINE":
yield "seg", (tf(be["a"]), tf(be["b"]))
@@ -199,39 +240,80 @@ def main() -> int:
xs = [p[0] for p in mpts]
ys = [p[1] for p in mpts]
w, h = max(xs) - min(xs), max(ys) - min(ys)
if (len(mpts) >= 4 and w >= 3.0 and h >= 3.0 and
max(w, h) / max(min(w, h), 0.1) <= 8.0 and not in_quad((mx, my), quad)):
if (
len(mpts) >= 4
and w >= 3.0
and h >= 3.0
and max(w, h) / max(min(w, h), 0.1) <= 8.0
and not in_quad((mx, my), quad)
):
massings.append({"pts": [local(p) for p in mpts], "c": (mx, my), "w": w, "h": h})
floors = {}
if boundary_polys:
biggest = max(boundary_polys, key=lambda poly: (max(p[0] for p in poly) - min(p[0] for p in poly)) *
(max(p[1] for p in poly) - min(p[1] for p in poly)))
floors["SITE"] = {"name": "场地地面", "z": -0.45, "height": 0.45,
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
"segments": {}, "footprint": {"source": "用地红线", "polygons": [biggest]}}
floors["ROADS"] = {"name": "道路/车位", "z": 0.02, "height": 0.05,
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
"segments": segs["ROADS"]}
biggest = max(
boundary_polys,
key=lambda poly: (max(p[0] for p in poly) - min(p[0] for p in poly))
* (max(p[1] for p in poly) - min(p[1] for p in poly)),
)
floors["SITE"] = {
"name": "场地地面",
"z": -0.45,
"height": 0.45,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": {},
"footprint": {"source": "用地红线", "polygons": [biggest]},
}
floors["ROADS"] = {
"name": "道路/车位",
"z": 0.02,
"height": 0.05,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": segs["ROADS"],
}
if segs["FENCE"]:
floors["FENCE"] = {"name": "围墙", "z": 0.0, "height": 1.8,
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
"segments": segs["FENCE"]}
floors["FENCE"] = {
"name": "围墙",
"z": 0.0,
"height": 1.8,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": segs["FENCE"],
}
if trees:
tree_segs = []
for p in trees:
lp = local(p)
tree_segs.append({"start": [lp[0] - 0.3, lp[1]], "end": [lp[0] + 0.3, lp[1]],
"width": 2.4, "layer": "行道树", "source_type": "TREE"})
floors["TREES"] = {"name": "行道树", "z": 0.0, "height": 3.5,
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
"segments": {"trees": tree_segs}}
tree_segs.append(
{
"start": [lp[0] - 0.3, lp[1]],
"end": [lp[0] + 0.3, lp[1]],
"width": 2.4,
"layer": "行道树",
"source_type": "TREE",
}
)
floors["TREES"] = {
"name": "行道树",
"z": 0.0,
"height": 3.5,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": {"trees": tree_segs},
}
# de-duplicate massings (copies drawn twice) and name them by nearest label
kept = []
for m in sorted(massings, key=lambda m: -(m["w"] * m["h"])):
if any(abs(m["c"][0] - k["c"][0]) < 2 and abs(m["c"][1] - k["c"][1]) < 2 and
abs(m["w"] - k["w"]) < 2 and abs(m["h"] - k["h"]) < 2 for k in kept):
if any(
abs(m["c"][0] - k["c"][0]) < 2
and abs(m["c"][1] - k["c"][1]) < 2
and abs(m["w"] - k["w"]) < 2
and abs(m["h"] - k["h"]) < 2
for k in kept
):
continue
kept.append(m)
for idx, m in enumerate(kept, start=1):
@@ -245,22 +327,37 @@ def main() -> int:
if any(key in name for key in MASSING_SKIP):
continue
height = next((hh for key, hh in MASSING_HEIGHTS if key in name), DEFAULT_MASSING_H)
wsegs = [{"start": a, "end": b, "width": 0.25, "layer": "massing", "source_type": "SITE"}
for a, b in zip(m["pts"], m["pts"][1:])]
wsegs = [
{"start": a, "end": b, "width": 0.25, "layer": "massing", "source_type": "SITE"}
for a, b in zip(m["pts"], m["pts"][1:])
]
if m["pts"][0] != m["pts"][-1]:
wsegs.append({"start": m["pts"][-1], "end": m["pts"][0], "width": 0.25,
"layer": "massing", "source_type": "SITE"})
floors[f"CTX{idx}"] = {"name": f"体量-{name}", "z": 0.0, "height": height,
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
"segments": {"walls": wsegs},
"footprint": {"source": "site_outline", "polygons": [m["pts"]]}}
wsegs.append(
{"start": m["pts"][-1], "end": m["pts"][0], "width": 0.25, "layer": "massing", "source_type": "SITE"}
)
floors[f"CTX{idx}"] = {
"name": f"体量-{name}",
"z": 0.0,
"height": height,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": {"walls": wsegs},
"footprint": {"source": "site_outline", "polygons": [m["pts"]]},
}
out = {"floors": floors,
"categories": {"trees": {"label": "行道树", "color": "#3e7d4f"}}}
out = {"floors": floors, "categories": {"trees": {"label": "行道树", "color": "#3e7d4f"}}}
Path(args.out).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"out": args.out,
"floors": {k: {c: len(s) for c, s in v.get("segments", {}).items()} for k, v in floors.items()},
"trees": len(trees), "massings": len(kept)}, ensure_ascii=False))
print(
json.dumps(
{
"out": args.out,
"floors": {k: {c: len(s) for c, s in v.get("segments", {}).items()} for k, v in floors.items()},
"trees": len(trees),
"massings": len(kept),
},
ensure_ascii=False,
)
)
return 0

File diff suppressed because it is too large Load Diff

283
scripts/verify_delivery.py Normal file
View File

@@ -0,0 +1,283 @@
#!/usr/bin/env python3
"""Strict, machine-readable verification for final CAD showcase delivery."""
from __future__ import annotations
import argparse
import base64
import gzip
import hashlib
import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import showcase_schema
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def add_check(checks: list[dict[str, Any]], name: str, status: str, detail: str, **data) -> None:
checks.append({"name": name, "status": status, "detail": detail, **data})
def inspect_glb(path: Path, budget_mb: float, checks: list[dict[str, Any]]) -> dict[str, Any] | None:
if not path.exists() or path.stat().st_size == 0:
add_check(checks, f"glb:{path.name}", "FAIL", f"Missing or empty GLB: {path}")
return None
with path.open("rb") as stream:
header = stream.read(4)
if header != b"glTF":
add_check(checks, f"glb:{path.name}", "FAIL", "File does not have a GLB header")
return None
try:
from pygltflib import GLTF2
model = GLTF2().load(str(path))
nodes = [node.name or "" for node in model.nodes]
named = [name for name in nodes if "__" in name]
meshes = len(model.meshes or [])
primitives = sum(len(mesh.primitives) for mesh in model.meshes or [])
if meshes == 0 or primitives == 0:
add_check(checks, f"glb:{path.name}", "FAIL", "GLB contains no mesh primitives")
return None
if not named:
add_check(checks, f"glb:{path.name}:names", "FAIL", "No <floor>__<category> node names found")
else:
add_check(checks, f"glb:{path.name}:names", "PASS", f"{len(named)} named node(s)")
extensions = list(model.extensionsUsed or [])
detail = f"{meshes} meshes, {primitives} primitives, {path.stat().st_size / 1024 / 1024:.2f} MB"
status = "PASS" if path.stat().st_size <= budget_mb * 1024 * 1024 else "FAIL"
if status == "FAIL":
detail += f"; exceeds {budget_mb:.2f} MB budget"
add_check(checks, f"glb:{path.name}:structure", status, detail)
return {
"path": str(path),
"bytes": path.stat().st_size,
"sha256": sha256(path),
"meshes": meshes,
"primitives": primitives,
"nodes": named,
"extensions": extensions,
}
except Exception as exc:
add_check(checks, f"glb:{path.name}", "FAIL", f"GLB parser failed: {exc}")
return None
def inspect_render(path: Path, checks: list[dict[str, Any]]) -> None:
if not path.exists() or path.stat().st_size == 0:
add_check(checks, f"render:{path.name}", "FAIL", f"Missing render: {path}")
return
try:
from PIL import Image, ImageStat
image = Image.open(path).convert("RGB")
stat = ImageStat.Stat(image.resize((128, 128)))
spread = max(stat.var)
status = "PASS" if image.width >= 320 and image.height >= 240 and spread > 2.0 else "FAIL"
add_check(
checks,
f"render:{path.name}",
status,
f"{image.width}x{image.height}, max channel variance {spread:.2f}",
)
except Exception as exc:
add_check(checks, f"render:{path.name}", "FAIL", f"Image inspection failed: {exc}")
def inspect_web(web_dir: Path, checks: list[dict[str, Any]]) -> None:
required = [
"index.html",
"app.js",
"styles.css",
"model.glb",
"model_metadata.json",
"node_modules/three/build/three.module.js",
"node_modules/lucide/dist/umd/lucide.js",
]
missing = [name for name in required if not (web_dir / name).exists()]
if missing:
add_check(checks, "web:files", "FAIL", "Missing Web files: " + ", ".join(missing))
return
text = (web_dir / "index.html").read_text(encoding="utf-8") + (web_dir / "app.js").read_text(encoding="utf-8")
placeholders = sorted(set(re.findall(r"\{\{[^}]+\}\}", text)))
if placeholders:
add_check(checks, "web:placeholders", "FAIL", f"Unexpanded placeholders: {placeholders}")
else:
add_check(checks, "web:placeholders", "PASS", "Template placeholders expanded")
features = ("window.__renders", "invalidate(", "DRACOLoader", "restoreStateFromHash", "switchVariant")
absent = [feature for feature in features if feature not in text]
add_check(
checks,
"web:features",
"FAIL" if absent else "PASS",
"Missing features: " + ", ".join(absent) if absent else "Required viewer features present",
)
try:
metadata = json.loads((web_dir / "model_metadata.json").read_text(encoding="utf-8"))
missing_variants = [
item.get("file", "?")
for item in metadata.get("model_variants", [])
if not (web_dir / item.get("file", "")).exists()
]
add_check(
checks,
"web:variants",
"FAIL" if missing_variants else "PASS",
"Missing variant assets: " + ", ".join(missing_variants)
if missing_variants
else "Variant assets accounted for",
)
except Exception as exc:
add_check(checks, "web:metadata", "FAIL", f"Metadata parse failed: {exc}")
def inspect_offline(path: Path, checks: list[dict[str, Any]]) -> None:
if not path.exists():
add_check(checks, "offline:viewer", "FAIL", f"Offline viewer missing: {path}")
return
text = path.read_text(encoding="utf-8")
match = re.search(r'const GLB_B64="([A-Za-z0-9+/=]+)";', text)
if not match:
add_check(checks, "offline:payload", "FAIL", "Embedded GLB payload not found")
return
try:
payload = gzip.decompress(base64.b64decode(match.group(1)))
if payload[:4] != b"glTF":
raise ValueError("decoded payload is not a GLB")
add_check(checks, "offline:payload", "PASS", f"Decoded {len(payload)} GLB bytes")
except Exception as exc:
add_check(checks, "offline:payload", "FAIL", f"Embedded payload decode failed: {exc}")
def inspect_browser_report(path: Path, checks: list[dict[str, Any]]) -> None:
try:
report = json.loads(path.read_text(encoding="utf-8"))
passed = report.get("status") == "PASS" and not report.get("console_errors")
detail = report.get("detail") or json.dumps(report, ensure_ascii=False)[:500]
add_check(checks, "browser:smoke", "PASS" if passed else "FAIL", detail)
except Exception as exc:
add_check(checks, "browser:smoke", "FAIL", f"Browser report invalid: {exc}")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec", required=True)
parser.add_argument("--source-report", required=True)
parser.add_argument("--glb", nargs="*", default=[])
parser.add_argument("--variants-manifest")
parser.add_argument("--web-dir")
parser.add_argument("--offline-viewer")
parser.add_argument("--render", nargs="*", default=[])
parser.add_argument("--browser-report")
parser.add_argument("--require-browser-report", action="store_true")
parser.add_argument("--budget-mb", type=float, default=25.0)
parser.add_argument("--evidence-out", default="evidence_manifest.json")
args = parser.parse_args()
checks: list[dict[str, Any]] = []
artifacts: list[dict[str, Any]] = []
try:
source_report = json.loads(Path(args.source_report).read_text(encoding="utf-8"))
showcase_schema.validate_source_report(source_report)
add_check(
checks,
"cad_source_report",
"PASS",
f"Source gate PASS; {len(source_report['files'])} readable DXF file(s)",
)
except Exception as exc:
add_check(checks, "cad_source_report", "FAIL", str(exc))
spec_path = Path(args.spec)
try:
spec = json.loads(spec_path.read_text(encoding="utf-8"))
showcase_schema.validate_spec(spec)
add_check(checks, "building_spec", "PASS", f"Schema v{spec['schema_version']}; {len(spec['floors'])} floor(s)")
except Exception as exc:
add_check(checks, "building_spec", "FAIL", str(exc))
glb_paths = [Path(item) for item in args.glb]
if args.variants_manifest:
manifest_path = Path(args.variants_manifest)
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
showcase_schema.validate_manifest(manifest)
add_check(checks, "variants_manifest", "PASS", f"{len(manifest['variants'])} variant(s)")
for variant in manifest["variants"]:
source = Path(variant["source_glb"])
if not source.is_absolute():
source = manifest_path.parent / source
glb_paths.append(source)
spec_file = Path(variant["spec"])
if not spec_file.is_absolute():
spec_file = manifest_path.parent / spec_file
variant_spec = json.loads(spec_file.read_text(encoding="utf-8"))
showcase_schema.validate_spec(variant_spec)
metadata_file = Path(variant["metadata"])
if not metadata_file.is_absolute():
metadata_file = manifest_path.parent / metadata_file
metadata = json.loads(metadata_file.read_text(encoding="utf-8"))
if metadata.get("metadata_version") != 1:
raise ValueError(f"{metadata_file}: metadata_version must be 1")
if metadata.get("schema_version") != variant_spec.get("schema_version"):
raise ValueError(f"{metadata_file}: schema_version does not match {spec_file}")
except Exception as exc:
add_check(checks, "variants_manifest", "FAIL", str(exc))
seen = set()
for path in glb_paths:
resolved = path.resolve()
if resolved in seen:
continue
seen.add(resolved)
artifact = inspect_glb(path, args.budget_mb, checks)
if artifact:
artifacts.append(artifact)
if not glb_paths:
add_check(checks, "glb", "FAIL", "No GLB supplied")
for path in args.render:
inspect_render(Path(path), checks)
if not args.render:
add_check(checks, "render", "FAIL", "At least one inspected render is required")
if args.web_dir:
inspect_web(Path(args.web_dir), checks)
if args.offline_viewer:
inspect_offline(Path(args.offline_viewer), checks)
if args.browser_report:
inspect_browser_report(Path(args.browser_report), checks)
elif args.require_browser_report:
add_check(checks, "browser:smoke", "FAIL", "Browser smoke report required but not supplied")
else:
add_check(checks, "browser:smoke", "WARN", "No browser smoke report supplied")
status = "FAIL" if any(item["status"] == "FAIL" for item in checks) else "PASS"
evidence = {
"evidence_version": 1,
"generated_at": datetime.now(timezone.utc).isoformat(),
"status": status,
"checks": checks,
"artifacts": artifacts,
}
out = Path(args.evidence_out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(evidence, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"status": status, "evidence": str(out), "checks": len(checks)}, ensure_ascii=False))
if status == "FAIL":
for item in checks:
if item["status"] == "FAIL":
print(f"GATE FAIL [{item['name']}]: {item['detail']}", file=sys.stderr)
return 3
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -14,10 +14,15 @@ Usage:
[--out verify_previews.png] \
[--budget-mb 0.6]
"""
from __future__ import annotations
import argparse, json, math, sys
import argparse
import json
import sys
from pathlib import Path
import showcase_schema
def load_spec(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
@@ -44,8 +49,9 @@ def glb_stats(path: Path):
}
def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> str:
def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> tuple[str, bool]:
lines = ["# Showcase verification", ""]
failed = False
floors = spec.get("floors", {})
lines.append(f"{'floor':7} {'z':>6} {'h':>4} {'fp_area':>8} {'caps':>4} segments")
for k, f in floors.items():
@@ -55,7 +61,7 @@ def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> str:
merged = sum(1 for s in f.get("segments", {}).get("glazing", []) if s.get("source_type") == "merged")
glz = len(f.get("segments", {}).get("glazing", []))
cont = f" glazing_continuous={merged}/{glz}" if glz else ""
lines.append(f"{k:7} {f.get('z',0):>6.1f} {f.get('height',0):>4.1f} {str(fp):>8} {caps:>4} {segs}{cont}")
lines.append(f"{k:7} {f.get('z', 0):>6.1f} {f.get('height', 0):>4.1f} {str(fp):>8} {caps:>4} {segs}{cont}")
lines.append("")
if glbs:
lines.append("## GLB budget")
@@ -64,38 +70,38 @@ def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> str:
st = glb_stats(p)
mb = st["bytes"] / 1024 / 1024
ok = "OK" if st["bytes"] <= budget else "OVER"
extra = f" verts={st.get('vertices','?')} draco={st.get('draco','?')}"
failed = failed or st["bytes"] > budget or not st.get("meshes")
extra = f" verts={st.get('vertices', '?')} draco={st.get('draco', '?')}"
lines.append(f" {st['file']:20} {mb:6.2f} MB [{ok} vs {budget_mb}MB]{extra}")
return "\n".join(lines)
return "\n".join(lines), failed
def render_previews(spec: dict, out: Path) -> bool:
try:
import numpy as np # noqa
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
except Exception:
return False
floors = spec["floors"]
cmap = plt.get_cmap("turbo")
keys = list(floors.keys())
fcolor = {k: cmap(i / max(1, len(keys) - 1)) for i, k in enumerate(keys)}
fig = plt.figure(figsize=(22, 7))
# front elevation (X vs Z), side elevation (Y vs Z), plan (X vs Y)
for sub, (ax_h, ax_v, title) in enumerate([(0, 2, "Front elevation (X-Z)"),
(1, 2, "Side elevation (Y-Z)"),
(0, 1, "Plan overlay (X-Y)")]):
for sub, (ax_h, ax_v, title) in enumerate(
[(0, 2, "Front elevation (X-Z)"), (1, 2, "Side elevation (Y-Z)"), (0, 1, "Plan overlay (X-Y)")]
):
ax = fig.add_subplot(1, 3, sub + 1)
for k, f in floors.items():
z = float(f["z"]); h = float(f.get("height", 4.2))
z = float(f["z"])
h = float(f.get("height", 4.2))
for cat, col in [("walls", "#8a7f6a"), ("columns", "#f58a1f"), ("glazing", "#5aa9c9")]:
for s in f.get("segments", {}).get(cat, []):
a, b = s["start"], s["end"]
p = [a, b]
if ax_v == 2: # elevation: vertical extent z..z+h at midpoint of horizontal axis
ah0, ah1 = a[ax_h], b[ax_h]
ax.plot([ah0, ah1], [z + h * 0.5, z + h * 0.5], color=col, lw=0.2, alpha=0.35)
ax.fill([ah0, ah1, ah1, ah0], [z, z, z + h, z + h], color=col, lw=0, alpha=0.12)
ax.plot([ah0, ah1], [z + h, z + h], color=col, lw=0.2, alpha=0.5)
else: # plan
ax.plot([a[ax_h], b[ax_h]], [a[ax_v], b[ax_v]], color=col, lw=0.15, alpha=0.4)
ax.set_title(title)
@@ -112,11 +118,20 @@ def main() -> int:
ap.add_argument("--glb", nargs="*", default=[])
ap.add_argument("--out", default="verify_previews.png")
ap.add_argument("--budget-mb", type=float, default=0.6)
ap.add_argument("--strict", action="store_true", help="Exit 3 on invalid GLB budget/structure or missing preview")
a = ap.parse_args()
spec = load_spec(Path(a.spec))
print(text_report(spec, [Path(p) for p in a.glb], a.budget_mb))
spec = showcase_schema.normalize_spec(load_spec(Path(a.spec)))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
report, failed = text_report(spec, [Path(p) for p in a.glb], a.budget_mb)
print(report)
ok = render_previews(spec, Path(a.out))
print(f"\npreviews: {'written ' + a.out if ok else 'skipped (matplotlib not installed)'}")
if a.strict and (failed or not ok):
return 3
return 0

View File

@@ -0,0 +1,76 @@
#!/usr/bin/env node
/** Browser smoke test for the served Three.js showcase viewer. */
import fs from "node:fs/promises";
import path from "node:path";
function arg(name, fallback = null) {
const index = process.argv.indexOf(name);
return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback;
}
const url = arg("--url");
const out = arg("--out", "browser_smoke_report.json");
const shots = arg("--screenshots-dir", "browser_smoke");
if (!url) {
throw new Error("Usage: web_smoke_test.mjs --url http://127.0.0.1:8188 --out report.json");
}
let chromium;
try {
({ chromium } = await import("playwright"));
} catch (error) {
throw new Error("Missing Playwright. Install with: npm install -D playwright && npx playwright install chromium", { cause: error });
}
await fs.mkdir(shots, { recursive: true });
const browser = await chromium.launch({ headless: true });
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
const checks = [];
async function inspect(viewport, name) {
const page = await browser.newPage({ viewportSize: viewport });
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText || "failed"}`));
await page.goto(url, { waitUntil: "networkidle", timeout: 60000 });
await page.waitForSelector("#loading", { state: "hidden", timeout: 60000 });
const selectors = ["#floor-controls", "#category-controls", "#explode", "#section", "#snapshot"];
for (const selector of selectors) {
const visible = await page.locator(selector).isVisible();
checks.push({ name: `${name}:${selector}`, status: visible ? "PASS" : "FAIL" });
}
await page.waitForTimeout(1200);
const before = await page.evaluate(() => window.__renders || 0);
await page.waitForTimeout(1500);
const after = await page.evaluate(() => window.__renders || 0);
checks.push({ name: `${name}:idle-render`, status: after === before ? "PASS" : "FAIL", detail: `${before}->${after}` });
await page.screenshot({ path: path.join(shots, `${name}.png`), fullPage: true });
await page.close();
}
try {
await inspect({ width: 1440, height: 900 }, "desktop");
await inspect({ width: 390, height: 844 }, "mobile");
} finally {
await browser.close();
}
const failedChecks = checks.filter((item) => item.status === "FAIL");
const status = failedChecks.length || consoleErrors.length || pageErrors.length || failedRequests.length ? "FAIL" : "PASS";
const report = {
status,
detail: `${checks.length - failedChecks.length}/${checks.length} checks passed`,
url,
checks,
console_errors: consoleErrors,
page_errors: pageErrors,
failed_requests: failedRequests,
};
await fs.writeFile(out, JSON.stringify(report, null, 2));
process.stdout.write(`${JSON.stringify({ status, report: out })}\n`);
if (status === "FAIL") process.exitCode = 3;

View File

@@ -29,6 +29,8 @@ import gzip
import json
from pathlib import Path
import showcase_schema
SKILL_ROOT = Path(__file__).resolve().parent.parent
@@ -51,7 +53,7 @@ def group_of(key: str) -> str:
return "主体"
MAIN_JS = r'''
MAIN_JS = r"""
(async function(){
const $load = document.getElementById('load');
const fail = m => { $load.style.display='flex'; $load.innerHTML = '<div style="max-width:520px;text-align:center">加载失败:'+m+'</div>'; };
@@ -188,35 +190,45 @@ MAIN_JS = r'''
addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); invalidate(); });
} catch (err) { fail(err.message || String(err)); }
})();
'''
"""
CSS = (
'body{margin:0;background:#1c1f24;color:#e8e6e0;font:14px/1.5 -apple-system,"PingFang SC",sans-serif;overflow:hidden}'
'#panel{position:fixed;top:12px;left:12px;background:rgba(244,241,232,.97);color:#2a2a26;border-radius:12px;padding:12px 14px;width:242px;max-height:92vh;overflow:auto;box-shadow:0 4px 18px rgba(0,0,0,.45);z-index:5}'
'#panel h1{font-size:15px;margin:0 0 2px}'
'#panel .sub{font-size:12px;color:#777;margin-bottom:6px}'
'#panel label{display:flex;gap:6px;align-items:center;font-size:13px;padding:1px 0;cursor:pointer}'
'.grp{border-top:1px solid #ddd;margin-top:8px;padding-top:6px;font-weight:600;font-size:12px;color:#555;display:flex;justify-content:space-between;align-items:center}'
'.grp button{font-size:11px;border:none;background:#e5e0d2;border-radius:6px;padding:1px 8px;cursor:pointer}'
'#info{position:fixed;bottom:14px;left:14px;background:rgba(30,33,38,.92);border:1px solid #3a3f46;color:#e8e6e0;border-radius:10px;padding:8px 12px;font-size:13px;display:none;max-width:340px;z-index:5}'
'#hint{position:fixed;bottom:10px;right:14px;font-size:12px;color:#9aa;z-index:5}'
'#load{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;color:#cfd3c9;font-size:14px;background:#1c1f24;z-index:9}'
'body{margin:0;background:#1c1f24;color:#e8e6e0;font:14px/1.5 -apple-system,"PingFang SC",sans-serif;overflow:hidden}'
"#panel{position:fixed;top:12px;left:12px;background:rgba(244,241,232,.97);color:#2a2a26;border-radius:12px;padding:12px 14px;width:242px;max-height:92vh;overflow:auto;box-shadow:0 4px 18px rgba(0,0,0,.45);z-index:5}"
"#panel h1{font-size:15px;margin:0 0 2px}"
"#panel .sub{font-size:12px;color:#777;margin-bottom:6px}"
"#panel label{display:flex;gap:6px;align-items:center;font-size:13px;padding:1px 0;cursor:pointer}"
".grp{border-top:1px solid #ddd;margin-top:8px;padding-top:6px;font-weight:600;font-size:12px;color:#555;display:flex;justify-content:space-between;align-items:center}"
".grp button{font-size:11px;border:none;background:#e5e0d2;border-radius:6px;padding:1px 8px;cursor:pointer}"
"#info{position:fixed;bottom:14px;left:14px;background:rgba(30,33,38,.92);border:1px solid #3a3f46;color:#e8e6e0;border-radius:10px;padding:8px 12px;font-size:13px;display:none;max-width:340px;z-index:5}"
"#hint{position:fixed;bottom:10px;right:14px;font-size:12px;color:#9aa;z-index:5}"
"#load{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;color:#cfd3c9;font-size:14px;background:#1c1f24;z-index:9}"
)
def main() -> int:
args = parse_args()
spec_path = Path(args.spec)
glb_path = Path(args.glb)
if not glb_path.exists() or glb_path.stat().st_size == 0:
raise SystemExit(f"GLB not found or empty: {glb_path}")
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:
raise SystemExit(str(exc)) from exc
libs = Path(args.libs_dir)
parts = {}
for name in ("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js"):
path = libs / name
if not path.exists():
raise SystemExit(f"Missing offline lib {path}. Populate via: npm pack three@0.147.0 pako@2.1.0 and copy files.")
raise SystemExit(
f"Missing offline lib {path}. Populate via: npm pack three@0.147.0 pako@2.1.0 and copy files."
)
parts[name] = path.read_text(encoding="utf-8")
assert "</scr" + "ipt>" not in parts[name]
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
glb = Path(args.glb).read_bytes()
glb = glb_path.read_bytes()
b64 = base64.b64encode(gzip.compress(glb, 6)).decode()
order = spec.get("source", {}).get("config", {}).get("floor_order") or list(spec.get("floors", {}))
@@ -224,27 +236,32 @@ def main() -> int:
for key in order:
if key in spec.get("floors", {}):
groups.setdefault(group_of(key), []).append([key, spec["floors"][key].get("name", key)])
trees = [[round((s["start"][0] + s["end"][0]) / 2, 2), round((s["start"][1] + s["end"][1]) / 2, 2)]
for s in spec.get("floors", {}).get("TREES", {}).get("segments", {}).get("trees", [])]
trees = [
[round((s["start"][0] + s["end"][0]) / 2, 2), round((s["start"][1] + s["end"][1]) / 2, 2)]
for s in spec.get("floors", {}).get("TREES", {}).get("segments", {}).get("trees", [])
]
cats = {k: v.get("label", k) for k, v in spec.get("categories", {}).items()}
title = args.title or spec.get("project", {}).get("name", "CAD 建筑模型")
main_js = (MAIN_JS
.replace("__GROUPS__", json.dumps(groups, ensure_ascii=False))
.replace("__CATS__", json.dumps(cats, ensure_ascii=False))
.replace("__TREES__", json.dumps(trees)))
main_js = (
MAIN_JS.replace("__GROUPS__", json.dumps(groups, ensure_ascii=False))
.replace("__CATS__", json.dumps(cats, ensure_ascii=False))
.replace("__TREES__", json.dumps(trees))
)
sc_close = "</scr" + "ipt>"
html = (
'<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8">'
f'<title>{title} · 3D 查看器(离线版)</title>'
f"<title>{title} · 3D 查看器(离线版)</title>"
'<meta name="viewport" content="width=device-width, initial-scale=1">'
f'<style>{CSS}</style></head><body>'
f"<style>{CSS}</style></head><body>"
'<div id="load">正在初始化…</div>'
f'<div id="panel"><h1>{title}</h1><div class="sub">{args.subtitle}</div><div id="tg"></div></div>'
'<div id="info"></div>'
'<div id="hint">拖动旋转 · 滚轮缩放 · 右键平移 · 点击构件查属性</div>'
+ "".join(f"<script>{parts[n]}{sc_close}" for n in
("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js"))
+ "".join(
f"<script>{parts[n]}{sc_close}"
for n in ("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js")
)
+ f'<script>const GLB_B64="{b64}";{sc_close}'
+ f"<script>{main_js}{sc_close}"
+ "</body></html>"
@@ -252,8 +269,17 @@ def main() -> int:
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(html, encoding="utf-8")
print(json.dumps({"out": str(out), "kb": len(html) // 1024,
"floors": sum(len(v) for v in groups.values()), "trees": len(trees)}, ensure_ascii=False))
print(
json.dumps(
{
"out": str(out),
"kb": len(html) // 1024,
"floors": sum(len(v) for v in groups.values()),
"trees": len(trees),
},
ensure_ascii=False,
)
)
return 0

View File

@@ -9,6 +9,8 @@ import shutil
import time
from pathlib import Path
import showcase_schema
def default_template() -> Path:
return Path(__file__).resolve().parents[1] / "assets" / "web-showcase-template"
@@ -63,6 +65,10 @@ def load_variants(manifest_path: Path | None) -> tuple[dict | None, list[dict]]:
if not manifest_path.exists():
raise SystemExit(f"Variants manifest not found: {manifest_path}")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
try:
showcase_schema.validate_manifest(manifest)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
variants = list(manifest.get("variants", []))
if not variants:
raise SystemExit(f"Variants manifest has no variants: {manifest_path}")
@@ -101,7 +107,9 @@ def copy_variant_assets(manifest_path: Path | None, variants: list[dict], out_di
return web_variants
def inferred_default_glb(args_glb: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]) -> Path:
def inferred_default_glb(
args_glb: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]
) -> Path:
if args_glb:
return Path(args_glb)
variant = default_variant(manifest, variants)
@@ -111,7 +119,9 @@ def inferred_default_glb(args_glb: str | None, manifest_path: Path | None, manif
return resolve_manifest_path(manifest_path, source_value) if manifest_path else Path(source_value)
def inferred_metadata(args_metadata: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]) -> Path:
def inferred_metadata(
args_metadata: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]
) -> Path:
if args_metadata:
return Path(args_metadata)
variant = default_variant(manifest, variants)
@@ -131,16 +141,19 @@ def site_trees_from_spec(spec_path: Path | None) -> list[list[float]]:
if not spec_path or not spec_path.exists():
return []
try:
spec = json.loads(spec_path.read_text(encoding="utf-8"))
spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8")))
except (OSError, json.JSONDecodeError):
return []
showcase_schema.validate_spec(spec)
trees = []
for floor in spec.get("floors", {}).values():
for seg in floor.get("segments", {}).get("trees", []):
trees.append([
round((seg["start"][0] + seg["end"][0]) / 2, 2),
round((seg["start"][1] + seg["end"][1]) / 2, 2),
])
trees.append(
[
round((seg["start"][0] + seg["end"][0]) / 2, 2),
round((seg["start"][1] + seg["end"][1]) / 2, 2),
]
)
return trees