Campus pipeline hardening: backend parity, wall union, mullion grids, Draco tooling

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

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

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-02 17:44:41 +08:00
parent 74cc7168f7
commit 6ace84ffba
27 changed files with 8515 additions and 85 deletions

229
scripts/assemble_campus.py Normal file
View File

@@ -0,0 +1,229 @@
#!/usr/bin/env python3
"""Assemble a campus spec from per-building specs + a site manifest.
Formalizes the spec-level merge proven on the 贝昂 case: every building's
segments/footprints/caps are rotated+translated into campus-local meters,
floor keys get building prefixes, site-context floors (from
site_context_from_dump.py) are appended, and per-building roof_specs are
re-keyed. Placement anchors follow the SKILL rules: WALL corners / coordinate
callouts, never roof envelopes.
Manifest (site_manifest.json) schema used here:
{
"campus_origin_surveying_m": [349505.372, 664163.589],
"rotation_deg": 7.5711, # campus grid rotation (site vs building sheets)
"buildings": {
"1#厂房": {"spec": "work/building_spec.json", "prefix": "",
"model_anchor_m": [7.3, 8.3], # point in the building spec (meters)
"survey_anchor_m": [349582.714, 664188.492]}, # where it lands (surveying meters)
"2#厂房": {"spec": "work/spec_2.json", "prefix": "2", ...}
}
}
Buildings without a "spec" entry are skipped (e.g. "status": "待建模").
Checks performed (loud, not silent): pairwise wall-envelope overlap between
buildings (negative gaps FAIL), and each building inside the site bounds if
--site-bounds is given.
Usage:
python3 assemble_campus.py --manifest work/site_manifest.json \
[--site-floors work/site_floors.json] --out work/campus_spec.json \
[--project-name 厂区] [--roof-specs work/roof_specs.json]
"""
from __future__ import annotations
import argparse
import copy
import json
import math
import sys
from pathlib import Path
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--manifest", required=True)
p.add_argument("--site-floors", default=None, help="site_context_from_dump.py output to merge")
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("--allow-overlap", action="store_true", help="downgrade overlap FAIL to warning")
return p.parse_args()
def make_xf(anchor, survey_m, origin_m, cos_t, sin_t):
ax, ay = anchor
tx, ty = survey_m[0] - origin_m[0], survey_m[1] - origin_m[1]
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
def transform_floors(spec: dict, xf) -> dict:
out = {}
for fk, fl in spec.get("floors", {}).items():
nf = copy.deepcopy(fl)
xs, ys = [], []
for segs in nf.get("segments", {}).values():
for s in segs:
s["start"] = xf(s["start"])
s["end"] = xf(s["end"])
xs += [s["start"][0], s["end"][0]]
ys += [s["start"][1], s["end"][1]]
if "footprint" in nf:
nf["footprint"]["polygons"] = [[xf(p) for p in poly] for poly in nf["footprint"]["polygons"]]
for cap in nf.get("caps", []):
cap["polygons"] = [[xf(p) for p in poly] for poly in cap["polygons"]]
if xs:
nf["bounds"] = [round(min(xs), 6), round(min(ys), 6), round(max(xs), 6), round(max(ys), 6)]
out[fk] = nf
return out
def wall_envelope_axis(floors: dict, cos_t: float, sin_t: float):
"""Ground-floor wall envelope in the rotated building-axis frame.
Uses the LOWEST floor with real walls: upper floors (roof machine rooms,
parapet-level structures) legitimately overhang by 1-2 m and would turn a
valid 0.19 m expansion joint into a false overlap alarm.
"""
ground = None
for fl in floors.values():
if len(fl.get("segments", {}).get("walls", [])) < 10:
continue
z = float(fl.get("z", 0))
if z < -0.5:
continue # basements are inset; the seam lives at ground level
if ground is None or z < float(ground.get("z", 0)):
ground = fl
if ground is None:
for fl in floors.values():
if len(fl.get("segments", {}).get("walls", [])) >= 10:
if ground is None or float(fl.get("z", 0)) < float(ground.get("z", 0)):
ground = fl
if ground is None:
return None
pts = []
for s in ground["segments"]["walls"]:
for p in (s["start"], s["end"]):
pts.append((p[0] * cos_t + p[1] * sin_t, -p[0] * sin_t + p[1] * cos_t))
xs = [p[0] for p in pts]
ys = [p[1] for p in pts]
return (min(xs), min(ys), max(xs), max(ys))
def envelope_gap(a, b):
"""Positive = separation, negative = overlap (axis-aligned in building frame)."""
dx = max(a[0] - b[2], b[0] - a[2])
dy = max(a[1] - b[3], b[1] - a[3])
if dx < 0 and dy < 0:
return max(dx, dy) # overlapping in both axes -> negative depth
return max(dx, dy)
def main() -> int:
args = parse_args()
manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8"))
origin = manifest.get("campus_origin_surveying_m") or manifest.get("campus_origin_surveying_mm")
if origin is None:
raise SystemExit("manifest needs campus_origin_surveying_m")
if max(abs(origin[0]), abs(origin[1])) > 1e6: # mm legacy
origin = [origin[0] / 1000.0, origin[1] / 1000.0]
theta = math.radians(float(manifest.get("rotation_deg", 0.0)))
cos_t, sin_t = math.cos(theta), math.sin(theta)
base_spec = None
placed: dict[str, dict] = {}
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)
continue
spec = json.loads(Path(b["spec"]).read_text(encoding="utf-8"))
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")
survey = b.get("survey_anchor_m") or b.get("survey_center_m")
if not anchor or not survey:
raise SystemExit(f"{name}: manifest entry needs model_anchor_m + survey_anchor_m")
xf = make_xf(anchor, survey, origin, cos_t, sin_t)
floors = transform_floors(spec, xf)
prefix = str(b.get("prefix", ""))
placed.update({prefix + fk: fl for fk, fl in floors.items()})
env = wall_envelope_axis(floors, cos_t, sin_t)
if env:
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")])]}
for r in spec.get("source", {}).get("config", {}).get("roof_specs", [])
]
if base_spec is None:
raise SystemExit("no buildings with specs in manifest")
# gap audit
names = list(envelopes)
failures = []
for i in range(len(names)):
for j in range(i + 1, len(names)):
gap = envelope_gap(envelopes[names[i]], envelopes[names[j]])
tag = f"{names[i]} <-> {names[j]}"
if gap < 0:
failures.append(f"OVERLAP {tag}: {gap:.3f} m — placement bug (roof-envelope anchor? flip?)")
elif gap < args.gap_warn:
print(f"NOTE {tag}: gap {gap:.3f} m — 贴建/变形缝? corroborate per SKILL rules", file=sys.stderr)
else:
print(f"gap {tag}: {gap:.2f} m", file=sys.stderr)
if failures and not args.allow_overlap:
for f in failures:
print("FAIL " + f, file=sys.stderr)
return 3
for f in failures:
print("WARN(allowed) " + f, file=sys.stderr)
floors: dict = {}
site_keys: list[str] = []
if args.site_floors:
site = json.loads(Path(args.site_floors).read_text(encoding="utf-8"))
wall_bounds = [fl["bounds"] for fl in placed.values() if len(fl.get("segments", {}).get("walls", [])) >= 10]
for k, v in site.get("floors", {}).items():
if k.startswith("CTX"):
w = v.get("segments", {}).get("walls", [])
if w:
xs = [q for s in w for q in (s["start"][0], s["end"][0])]
ys = [q for s in w for q in (s["start"][1], s["end"][1])]
cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2
if any(b[0] - 1 <= cx <= b[2] + 1 and b[1] - 1 <= cy <= b[3] + 1 for b in wall_bounds):
continue # covered by a real model
floors[k] = v
site_keys.append(k)
base_spec.setdefault("categories", {}).update(site.get("categories", {}))
floors.update(placed)
campus = base_spec
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["floor_order"] = site_keys + [k for k in placed]
out = Path(args.out)
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))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

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

View File

@@ -245,6 +245,137 @@ def create_segment_mesh(bpy, name: str, segments: list[dict], z0: float, z1: flo
return obj
def extend_shared_wall_ends(segments: list[dict], tol: float = 1e-3) -> list[dict]:
"""Extend wall ends that meet another wall's endpoint by half their own width.
Flat-capped rectangles stop exactly at the endpoint, so an L-corner leaves
a w/2 x w/2 notch that even a union keeps open. Extending only SHARED ends
closes the corner while free ends (door/window openings) stay flat.
Mirror of spec_to_glb.extend_shared_wall_ends.
"""
from collections import Counter
pts = []
for segment in segments:
pts.append((float(segment["start"][0]), float(segment["start"][1])))
pts.append((float(segment["end"][0]), float(segment["end"][1])))
scale = 1.0 / max(tol, 1e-9)
buckets = Counter((round(x * scale), round(y * scale)) for x, y in pts)
def shared(point):
cx, cy = round(point[0] * scale), round(point[1] * scale)
return sum(buckets.get((gx, gy), 0) for gx in (cx - 1, cx, cx + 1) for gy in (cy - 1, cy, cy + 1)) >= 2
out = []
for segment in segments:
start = [float(segment["start"][0]), float(segment["start"][1])]
end = [float(segment["end"][0]), float(segment["end"][1])]
dx, dy = end[0] - start[0], end[1] - start[1]
length = math.hypot(dx, dy)
if length < 1e-7:
out.append(segment)
continue
ux, uy = dx / length, dy / length
half = max(float(segment.get("width", 0.1)), 0.005) / 2.0
item = dict(segment)
if shared((start[0], start[1])):
start = [start[0] - ux * half, start[1] - uy * half]
if shared((end[0], end[1])):
end = [end[0] + ux * half, end[1] + uy * half]
item["start"] = start
item["end"] = end
out.append(item)
return out
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
union of the overlapping rectangles; edges used by exactly one triangle are
the union outline and become the side faces. Same visual contract as
spec_to_glb.py's shapely union, without needing shapely in Blender python.
"""
from mathutils import Vector
from mathutils.geometry import delaunay_2d_cdt
points = []
rects = []
for segment in extend_shared_wall_ends(segments):
prism = segment_prism(segment, z0, z1)
if not prism:
continue
idx = len(points)
points.extend(Vector((vert[0], vert[1])) for vert in prism[:4])
rects.append((idx, idx + 1, idx + 2, idx + 3))
if not rects:
return None
verts2d, _edges, tris = delaunay_2d_cdt(points, [], rects, 1, 1e-5)[:3]
if not tris:
return None
count = len(verts2d)
verts = [(v.x, v.y, z0) for v in verts2d] + [(v.x, v.y, z1) for v in verts2d]
edge_use: dict[tuple[int, int], int] = {}
for tri in tris:
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
key = (min(a, b), max(a, b))
edge_use[key] = edge_use.get(key, 0) + 1
faces = [tuple(reversed(tri)) for tri in tris] # bottom, facing down
faces += [tuple(i + count for i in tri) for tri in tris] # top, facing up
for tri in tris:
# CCW triangles keep the interior left of a->b, so (a,b,b',a') faces outward.
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
if edge_use[(min(a, b), max(a, b))] == 1:
faces.append((a, b, b + count, a + count))
mesh = bpy.data.meshes.new(f"{name}Mesh")
mesh.from_pydata(verts, [], faces)
mesh.update()
mesh.validate(verbose=False)
obj = bpy.data.objects.new(name, mesh)
bpy.context.collection.objects.link(obj)
obj.data.materials.append(material)
obj["floor"] = floor_key
obj["category"] = category
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]:
"""Curtain-wall panel grid over glazing bands (mirror of spec_to_glb).
Emits pseudo wall segments (thin box profiles, rendered into the
<floor>__walls object): vertical mullions evenly spaced ~panel_w per band
plus a horizontal transom at the band's bottom and top floor lines
(via _z0/_z1). Config {"glazing_mullions": true, "glazing_panel_w": 1.5}.
"""
out = []
for segment in bands:
start = segment["start"]
end = segment["end"]
dx, dy = end[0] - start[0], end[1] - start[1]
length = math.hypot(dx, dy)
if length < max(profile * 2, 0.3):
continue
ux, uy = dx / length, dy / length
panels = max(1, round(length / max(panel_w, 0.2)))
step = length / panels
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",
})
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,
})
return out
def create_label(bpy, name: str, body: str, location: tuple[float, float, float], size: float, material):
curve = bpy.data.curves.new(f"{name}Curve", "FONT")
curve.body = body
@@ -328,11 +459,11 @@ def generated_roof_bounds(spec: dict) -> list[dict]:
continue
bounds_from = list(roof.get("bounds_from", [floor_key]))
footprint_from = list(roof.get("footprint_from", bounds_from))
footprint_polygons = (
footprint_polygons_from_floor_keys(spec, footprint_from)
if config.get("use_footprint_roofs", False) or roof.get("use_footprint", False)
else []
)
# Footprint polygons take priority over rectangular bounds whenever the
# source floors carry them (same contract as spec_to_glb.py); a bounds
# rect for e.g. a PH machine-room roof covers the whole building bbox
# and reads as a plate jutting past the facade.
footprint_polygons = footprint_polygons_from_floor_keys(spec, footprint_from)
bounds = roof.get("bounds") or bounds_from_floor_keys(spec, bounds_from)
if not bounds:
bounds = floor.get("bounds")
@@ -519,7 +650,11 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
floor_key,
"slab",
)
else:
elif config.get("slab_bounds_fallback", True):
# Rectangular fallback can fake a full-cover plate on floors like
# parapet-only roof plans or campus context floors (roads/fence/trees);
# disable via config {"slab_bounds_fallback": false} when footprints
# are trusted (same contract as spec_to_glb.py).
create_box_mesh(bpy, f"{floor_key}__slab", [slab_box], materials["slab"], floor_key, "slab")
# Cap slabs close the tops of columns at setbacks and over basement parking
# (computed by derive_showcase_spec.py and stored as floor["caps"]). They share
@@ -540,15 +675,34 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
"slab",
)
floor_segments = floor.get("segments", {})
mullion_segments: list[dict] = []
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)),
)
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))
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:
segments = floor.get("segments", {}).get(category, [])
if not segments:
if not segments and category != "walls":
continue
if category == "columns":
segments = adjusted_column_segments(segments, floor_key, floor, spec)
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,
)
if merged is not None:
segments = [] # walls handled; mullions (if any) get their own pass below
if category == "walls":
segments = list(segments) + mullion_segments
mullion_segments = []
if not segments:
continue
create_segment_mesh(
bpy,
f"{floor_key}__{category}",

View File

@@ -69,6 +69,13 @@ def filtered_spec(source: dict[str, Any], variant: dict[str, Any]) -> dict[str,
return spec
keep_set = set(keep)
for floor in spec.get("floors", {}).values():
# Campus site-context floors (roads/parking/fence/trees emitted by
# site_context_from_dump.py with source_file="site") are presentation
# content: their roads live on detail_lines/grid and trees on a custom
# category, so category filtering would strip the whole site. Keep them
# intact in every variant.
if floor.get("source_file") == "site":
continue
segments = floor.get("segments", {})
for category in list(segments):
if category not in keep_set:

View File

@@ -162,12 +162,47 @@ 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"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
def count_plan_titles(entities) -> int:
"""Distinct plan-frame titles in modelspace (multi-frame sheet detector)."""
seen = set()
for entity in entities:
kind = entity.dxftype()
if kind not in {"TEXT", "MTEXT"}:
continue
try:
text = str(entity.dxf.text if kind == "TEXT" else entity.plain_text() or "").strip()
except Exception:
continue
if not text or len(text) > 40:
continue
if PLAN_TITLE_RE.search(text) and not PLAN_TITLE_EXCLUDE_RE.search(text):
try:
pos = entity.dxf.insert
seen.add((text, round(float(pos.x) / 5000), round(float(pos.y) / 5000)))
except Exception:
seen.add((text, 0, 0))
return len(seen)
def file_warnings(item: dict) -> list[str]:
warnings = []
entities = item.get("modelspace_entities")
xrefs = item.get("xref_definitions", [])
if entities is None:
return warnings
plan_titles = item.get("plan_title_count", 0)
if plan_titles >= 2:
warnings.append(
f"multi_frame_sheet: {plan_titles} plan-frame titles (XX平面图) found in ONE modelspace. "
"This file holds a whole sheet set — never model it as a single floor and never stack frames "
"without per-floor offsets. Run scripts/detect_sheet_frames.py to generate clip/offset config."
)
if xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD:
names = ", ".join(x["name"] for x in xrefs[:4])
warnings.append(
@@ -231,6 +266,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
"measurement": int(header.get("$MEASUREMENT", 0) or 0),
"unit_guess": guess_unit_scale(geometry_bbox, insunits),
"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}
@@ -327,7 +363,8 @@ def main() -> int:
if conversion["status"] == "ok":
raw_dxfs.append(dest)
else:
shutil.copy2(source, dest)
if source.resolve() != dest.resolve():
shutil.copy2(source, dest)
raw_dxfs.append(dest)
sanitized: list[Path] = []

View File

@@ -269,6 +269,54 @@ def probe_keep_entity(entity, config: dict[str, Any]) -> bool:
return category is not None and category in allowed
_BLOCK_LEAF_LAYERS: dict[tuple[int, str], frozenset[str]] = {}
def block_leaf_layers(doc, name: str, max_depth: int, depth: int = 0) -> frozenset[str]:
"""Layers used by a block definition (recursing into nested INSERTs).
Cheap definition walk (no explode/transform) memoized per document+name so
probe expansion can skip the expensive virtual explode for the vast
majority of blocks (axis bubbles, tags, hatched symbols) whose contents can
never classify into block_content_categories.
"""
key = (id(doc), name)
cached = _BLOCK_LEAF_LAYERS.get(key)
if cached is not None:
return cached
layers: set[str] = set()
try:
block = doc.blocks.get(name)
except Exception:
block = None
if block is not None:
for inner in block:
if inner.dxftype() == "INSERT" and depth < max_depth:
inner_name = str(inner.dxf.name) if inner.dxf.hasattr("name") else ""
if inner_name:
layers |= block_leaf_layers(doc, inner_name, max_depth, depth + 1)
else:
layers.add(entity_layer(inner))
result = frozenset(layers)
_BLOCK_LEAF_LAYERS[key] = result
return result
def probe_block_may_match(entity, config: dict[str, Any]) -> bool:
"""True if any leaf layer of the INSERT's block could classify for probing."""
doc = getattr(entity, "doc", None)
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
if doc is None or not block_name:
return True # cannot prove it is irrelevant; expand as before
patterns, excludes, allowed = _probe_rules(config)
max_depth = int(config.get("expand_blocks_max_depth", 2))
for layer in block_leaf_layers(doc, block_name, max_depth):
category = match_category(layer, patterns, excludes)
if category is not None and category in allowed:
return True
return False
def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
"""Yield (entity, fallback_layer, block_name) tuples to inspect/extract.
@@ -291,6 +339,11 @@ def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
if (not explicit and not probe) or depth >= max_depth:
yield entity, "", ""
return
if not explicit and probe and not probe_block_may_match(entity, config):
# No leaf layer of this block can classify -> exploding it cannot
# contribute geometry; skip the expensive virtual expansion.
yield entity, "", ""
return
insert_layer = entity_layer(entity)
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
@@ -426,68 +479,76 @@ def collect_raw_segments(
entities = list(doc.modelspace())
floors = drawing.get("floors") or [{"key": Path(drawing["file"]).stem, "name": Path(drawing["file"]).stem}]
# Single pass over (expanded) entities, bucketed per floor. Expanding
# INSERTs per floor is O(floors x inserts) and times out on Chinese
# multi-frame sheets where one DWG holds every floor of a building.
floor_specs = []
buckets: dict[str, dict[str, list[dict[str, Any]]]] = {}
counts: dict[str, int] = {}
for floor in floors:
key = str(floor["key"])
offset_values = floor.get("offset", drawing.get("offset", [0, 0]))
offset = (float(offset_values[0]), float(offset_values[1]))
segments_by_category: dict[str, list[dict[str, Any]]] = defaultdict(list)
ignored_by_type: dict[str, int] = defaultdict(int)
included = 0
floor_specs.append((floor, key, (float(offset_values[0]), float(offset_values[1]))))
buckets[key] = defaultdict(list)
counts[key] = 0
ignored_by_type: dict[str, int] = defaultdict(int)
for entity in entities:
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
layer = entity_layer(extracted_entity)
category = category_for_entity(
extracted_entity,
patterns,
config,
fallback_layer=fallback_layer,
block_name=block_name,
)
if not category:
ignored_by_type[extracted_entity.dxftype()] += 1
continue
for start, end in entity_segments(extracted_entity, max_chord):
for entity in entities:
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
layer = entity_layer(extracted_entity)
category = category_for_entity(
extracted_entity,
patterns,
config,
fallback_layer=fallback_layer,
block_name=block_name,
)
if not category:
ignored_by_type[extracted_entity.dxftype()] += 1
continue
segments = entity_segments(extracted_entity, max_chord)
if not segments:
continue
source_type = extracted_entity.dxftype()
width = default_widths.get(category, 0.1)
min_source = min_source_by_category.get(category, min_source_length)
min_meters = min_meters_by_category.get(category, min_meters_length)
for start, end in segments:
for floor, key, offset in floor_specs:
if not segment_matches_floor(start, end, floor, drawing):
continue
seg = cleaned_segment(
start,
end,
offset,
min_source_by_category.get(category, min_source_length),
min_meters_by_category.get(category, min_meters_length),
scale,
)
seg = cleaned_segment(start, end, offset, min_source, min_meters, scale)
if not seg:
continue
clean_start, clean_end = seg
segments_by_category[category].append(
buckets[key][category].append(
{
"start_source": clean_start,
"end_source": clean_end,
"width": default_widths.get(category, 0.1),
"width": width,
"layer": layer,
"source_type": extracted_entity.dxftype(),
"source_type": source_type,
"block_name": block_name,
"fallback_layer": fallback_layer,
}
)
included += 1
counts[key] += 1
for floor, key, _offset in floor_specs:
floor_data[key] = {
"key": key,
"name": str(floor.get("name", key)),
"z": floor.get("z"),
"height": float(floor.get("height", config.get("floor_height", 4.2))),
"source_file": path.name,
"segments_source": dict(segments_by_category),
"segments_source": dict(buckets[key]),
}
extraction_report.append(
{
"file": path.name,
"floor": key,
"status": "ok",
"segments": included,
"segments": counts[key],
"ignored_entity_types": dict(sorted(ignored_by_type.items())),
}
)
@@ -624,7 +685,16 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
return out
def _cap_floor_group(fk: str) -> str:
def _cap_floor_group(fk: str, config: dict[str, Any] | None = None) -> str:
"""Cap grouping: which floors stack in the same tower for cap logic.
Configurable via config["cap_groups"] = [["AUX_*", "AUX"], ["B*", "BASE"], ...]
(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"}:
@@ -678,10 +748,10 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
if not own_polys:
continue
ftop = float(fl["z"]) + float(fl.get("height", 4.2))
grp = _cap_floor_group(fk)
grp = _cap_floor_group(fk, config)
upper = []
for ok, ot in floors.items():
if ok == fk or _cap_floor_group(ok) != grp:
if ok == fk or _cap_floor_group(ok, config) != grp:
continue
if abs(float(ot.get("z", 0.0)) - ftop) > 0.8:
continue
@@ -765,6 +835,33 @@ def finalize_spec(
)
compute_caps(floors, config)
# Topless-roof guard: the top above-ground floor of each group must end in
# a cap or a config roof_specs entry, otherwise the model renders open-top
# ("没有屋顶"). Warn loudly so the Agent adds roof_specs before building.
roof_tops: dict[str, float] = {}
for r in config.get("roof_specs", []):
fk = str(r.get("floor_key"))
if fk not in floors:
continue
grp = _cap_floor_group(fk, config)
z = float(r.get("z", float(floors[fk]["z"]) + float(floors[fk].get("height", 4.2))))
roof_tops[grp] = max(roof_tops.get(grp, -1e9), z)
groups: dict[str, str] = {}
for key in floors:
grp = _cap_floor_group(key, config)
if grp not in groups or float(floors[key]["z"]) > float(floors[groups[grp]]["z"]):
groups[grp] = key
for grp, top_key in groups.items():
top = floors[top_key]
covered = roof_tops.get(grp, -1e9) >= float(top["z"]) - 0.8
if grp != "BASE" and not top.get("caps") and not covered:
print(
f"WARNING topless_group {grp}: top floor '{top_key}' has no caps and no "
f"roof_specs entry; add config roof_specs=[{{'floor_key': '{top_key}', ...}}] "
"or the model will have no roof plate.",
file=sys.stderr,
)
categories = {
key: {"label": value["label"], "color": value["color"]}
for key, value in DEFAULT_CATEGORIES.items()

View File

@@ -0,0 +1,382 @@
#!/usr/bin/env python3
"""Detect per-floor plan frames inside a multi-sheet DXF and propose extraction config.
Chinese construction sets commonly put ALL sheets of one building into a single
DWG modelspace (plans, elevations, sections, details side by side / stacked).
Treating such a file as one floor superimposes every sheet; treating N files as
N floors scatters plans by their sheet offsets (the "diagonal staircase" bug).
This tool:
1. Finds plan-title TEXTs (一层平面图 / 地下一层平面图 / 屋顶平面图 ...),
filtering out sheet-catalog rows and title-block copies (keeps, per title
name, only the largest-height instances outside excluded layers).
2. Proposes a clip window per plan frame from the sheet pitch, then refines it
to the wall-geometry bounding box inside the frame (drops title blocks,
notes, and neighbouring sheets).
3. Aligns every floor onto a reference floor with a label-free grid
correlation: vertical/horizontal axis-line positions are matched by voting
over candidate translations. Works even when upper floors show partial
grids, and needs no axis-number texts.
4. Emits a ready-to-edit extraction config skeleton plus a Markdown report
(elevation/section frames are listed for floor heights, not as floors).
Usage:
python3 detect_sheet_frames.py --dxf work/dxf_sanitized/xxx.dxf \
--out-config work/frames_config.json --out-report work/frames_report.md
"""
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
PLAN_TITLE = re.compile(r"平面图$")
PLAN_EXCLUDE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
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"),
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"B{_cn(m.group('n'))}"),
(re.compile(r"屋顶机房|机房层|电梯机房"), lambda m: "PH"),
(re.compile(r"屋顶|屋面|顶板"), lambda m: "RF"),
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"F{_cn(m.group('n'))}M"),
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"F{_cn(m.group('n'))}"),
(re.compile(r"地下|底层"), lambda m: "B1"),
]
def _cn(token: str) -> int:
if token.isdigit():
return int(token)
return CN_NUM.get(token, 0)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dxf", required=True)
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-exclude-regex", default=r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
parser.add_argument("--title-exclude-layers", default="*图签*,*PUB_TAB*,*TK*,*图框*,*目录*")
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")
return parser.parse_args()
def import_ezdxf(vendor_dir: Path):
if vendor_dir.exists():
sys.path.insert(0, str(vendor_dir.resolve()))
try:
import ezdxf # type: ignore
from ezdxf import recover # type: ignore
except ImportError as exc:
raise SystemExit(f"Missing ezdxf. pip install --target {vendor_dir} ezdxf") from exc
return ezdxf, recover
def match_any(value: str, patterns: list[str]) -> bool:
upper = value.upper()
return any(fnmatch.fnmatch(upper, p.upper()) for p in patterns)
def entity_text(entity) -> str:
try:
if entity.dxftype() == "TEXT":
return str(entity.dxf.text or "").strip()
if entity.dxftype() == "MTEXT":
return str(entity.plain_text() or "").strip()
except Exception:
pass
return ""
def floor_key_for(name: str, used: set[str]) -> str:
for pattern, keyfn in FLOOR_NAME_KEY:
match = pattern.search(name)
if match:
key = keyfn(match)
break
else:
key = re.sub(r"[^0-9A-Za-z]+", "_", name)[:12] or "FLOOR"
base, i = key, 2
while key in used:
key = f"{base}_{i}"
i += 1
used.add(key)
return key
def cluster_positions(values: list[float], tol: float) -> list[float]:
if not values:
return []
values = sorted(values)
clusters, current = [], [values[0]]
for v in values[1:]:
if v - current[-1] <= tol:
current.append(v)
else:
clusters.append(sum(current) / len(current))
current = [v]
clusters.append(sum(current) / len(current))
return clusters
def vote_translation(ref: list[float], src: list[float], bin_size: float) -> tuple[float | None, int]:
"""Best dx such that {src + dx} matches ref, by histogram voting."""
if not ref or not src:
return None, 0
votes: Counter = Counter()
for r in ref:
for s in src:
votes[round((r - s) / bin_size)] += 1
best_bin, best_votes = votes.most_common(1)[0]
if best_votes < 2:
return None, best_votes
fine = [r - s for r in ref for s in src if abs((r - s) - best_bin * bin_size) <= bin_size]
return statistics.median(fine), best_votes
def segments_in(entities, clip, layers):
out = []
x1, y1, x2, y2 = clip
for layer, sx, sy, ex, ey in entities:
if not match_any(layer, layers):
continue
mx, my = (sx + ex) / 2, (sy + ey) / 2
if x1 <= mx <= x2 and y1 <= my <= y2:
out.append((sx, sy, ex, ey))
return out
def main() -> int:
args = parse_args()
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
path = Path(args.dxf)
try:
doc = ezdxf.readfile(path)
except ezdxf.DXFError:
doc, _ = recover.readfile(path)
msp = doc.modelspace()
title_excludes = [p.strip() for p in args.title_exclude_layers.split(",") if p.strip()]
axis_layers = [p.strip() for p in args.axis_layers.split(",") if p.strip()]
wall_layers = [p.strip() for p in args.wall_layers.split(",") if p.strip()]
plan_title = re.compile(args.title_regex)
plan_exclude = re.compile(args.title_exclude_regex) if args.title_exclude_regex else None
titles, others = [], []
lines = [] # (layer, sx, sy, ex, ey) for LINE and polyline edges
for entity in msp:
kind = entity.dxftype()
if kind in {"TEXT", "MTEXT"}:
content = entity_text(entity)
if not content or len(content) > 40:
continue
try:
pos = entity.dxf.insert
x, y = float(pos.x), float(pos.y)
except Exception:
continue
height = float(entity.dxf.get("height", 0) or 0)
layer = str(entity.dxf.layer)
if plan_title.search(content) and not (plan_exclude and plan_exclude.search(content)):
if not match_any(layer, title_excludes):
titles.append({"name": content, "x": x, "y": y, "h": height, "layer": layer})
elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes):
others.append({"name": content, "x": x, "y": y, "h": height})
elif kind == "LINE":
d = entity.dxf
lines.append((str(d.layer), float(d.start.x), float(d.start.y), float(d.end.x), float(d.end.y)))
elif kind == "LWPOLYLINE":
try:
pts = [(float(px), float(py)) for px, py in entity.get_points("xy")]
except Exception:
continue
layer = str(entity.dxf.layer)
for a, b in zip(pts, pts[1:]):
lines.append((layer, a[0], a[1], b[0], b[1]))
if not titles:
print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False))
return 1
# Keep, per title name, only instances close to that name's max height
# (drops catalog rows and small title-block copies that survive layer excludes).
by_name: dict[str, list[dict]] = defaultdict(list)
for t in titles:
by_name[t["name"]].append(t)
filtered = []
for name, items in by_name.items():
max_h = max(t["h"] for t in items)
filtered.extend(t for t in items if t["h"] >= max_h * 0.85)
titles = sorted(filtered, key=lambda t: (-t["y"], t["x"]))
# Sheets stack vertically (column pitch from y gaps) or run in rows
# (pitch from x gaps of same-row titles) — support both.
ys = sorted({t["y"] for t in titles}, reverse=True)
y_gaps = [a - b for a, b in zip(ys, ys[1:]) if 20000 < a - b < 400000]
pitch_y = statistics.median(y_gaps) if y_gaps else None
xs_rows: dict[int, list[float]] = defaultdict(list)
for t in titles:
xs_rows[round(t["y"] / 4000)].append(t["x"])
x_gaps = []
for row in xs_rows.values():
row = sorted(row)
x_gaps.extend(b - a for a, b in zip(row, row[1:]) if 8000 < b - a < 400000)
pitch_x = statistics.median(x_gaps) if x_gaps else None
pitch = pitch_y or pitch_x or 98100.0
clip_w = (pitch_x * 0.97) if pitch_x else pitch * args.frame_aspect
clip_h = (pitch_y * 0.97) if pitch_y else (pitch_x or 98100.0) * 2.2
used_keys: set[str] = set()
floors = []
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 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]
clip = None
for group in refine_groups:
found = segments_in(lines, rough, group)
if len(found) >= 10:
xs = [v for s in found for v in (s[0], s[2])]
ys_ = [v for s in found for v in (s[1], s[3])]
margin = pitch * 0.06
clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin]
break
if clip is None:
clip = rough
notes.append(f"{t['name']}: no wall/roof geometry in rough clip; using pitch-based clip")
axes = segments_in(lines, clip, axis_layers)
min_grid_len = pitch * 0.25
vert, horiz = [], []
for sx, sy, ex, ey in axes:
if abs(ex - sx) < 2.0 and abs(ey - sy) > min_grid_len:
vert.append((sx + ex) / 2)
elif abs(ey - sy) < 2.0 and abs(ex - sx) > min_grid_len:
horiz.append((sy + ey) / 2)
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),
})
def ref_rank(f):
return (0 if f["key"] == "F1" else 1, -(len(f["_vx"]) + len(f["_hy"])))
reference = sorted(floors, key=ref_rank)[0]
alignment = []
for f in floors:
if f is reference:
f["offset"] = [0.0, 0.0]
alignment.append(f"{f['key']}: reference frame")
continue
dx, vx = vote_translation(reference["_vx"], f["_vx"], args.grid_bin)
dy, vy = vote_translation(reference["_hy"], f["_hy"], args.grid_bin)
if dx is not None and dy is not None and vx >= 3 and vy >= 3:
f["offset"] = [round(dx, 1), round(dy, 1)]
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}")
else:
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']} — verify overlay!"
)
for f in floors:
f.pop("_vx"), f.pop("_hy")
config = {
"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": [{k: f[k] for k in ("key", "name", "clip", "offset")} for f in 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"- plan frames: {len(floors)} (sheet pitch ≈ {round(pitch, 1)})",
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']}")
report.extend(["", "## Alignment", ""])
report.extend(f"- {n}" for n in alignment)
report.extend(f"- note: {n}" for n in notes)
if others:
seen = set()
report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""])
for o in sorted(others, key=lambda o: -o.get("h", 0)):
key = o["name"]
if key in seen:
continue
seen.add(key)
report.append(f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})")
# Storey-elevation suggestions: 标高 texts (e.g. 8.100) inside section/
# elevation frames, clustered. Feed floors[].z/height from these.
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
votes: Counter = Counter()
boxes = [(o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
for o in others]
for entity in msp:
if entity.dxftype() != "TEXT":
continue
content = entity_text(entity)
if not content or not elev_re.match(content):
continue
try:
pos = entity.dxf.insert
except Exception:
continue
if any(b[0] <= pos.x <= b[2] and b[1] <= pos.y <= b[3] for b in boxes):
votes[round(float(content), 3)] += 1
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."])
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))
return 0
if __name__ == "__main__":
raise SystemExit(main())

129
scripts/dwg_dump_json.mjs Normal file
View File

@@ -0,0 +1,129 @@
#!/usr/bin/env node
/**
* DWG -> JSON entity dump via @mlightcad/libredwg-web (WASM libredwg).
*
* Fallback converter for environments without native dwg2dxf / ODA File
* Converter (e.g. Linux sandboxes). Pair with scripts/dwgjson_to_dxf.py to
* rebuild an ezdxf-compatible DXF that the rest of the pipeline consumes.
*
* Usage:
* npm install @mlightcad/libredwg-web # once, anywhere; pass --module-dir
* node dwg_dump_json.mjs <in.dwg> <out.json> [--module-dir <node_modules path>]
*
* Carries: LINE, LWPOLYLINE, POLYLINE, ARC, CIRCLE, ELLIPSE, SPLINE, TEXT,
* MTEXT, INSERT (+ BLOCK definitions, recursively). Skips HATCH/DIMENSION/OLE.
*/
import { readFileSync, writeFileSync } from 'fs'
import { createRequire } from 'module'
import { pathToFileURL } from 'url'
const args = process.argv.slice(2)
const positional = args.filter(a => !a.startsWith('--'))
const moduleDirFlag = args.indexOf('--module-dir')
const moduleDir = moduleDirFlag >= 0 ? args[moduleDirFlag + 1] : null
if (positional.length < 2) {
console.error('usage: node dwg_dump_json.mjs <in.dwg> <out.json> [--module-dir <dir>]')
process.exit(2)
}
const [inFile, outFile] = positional
async function loadLib() {
const spec = '@mlightcad/libredwg-web'
if (moduleDir) {
const pkgRoot = `${moduleDir}/${spec}`
const mod = await import(pathToFileURL(`${pkgRoot}/dist/libredwg-web.js`))
return { mod, wasmDir: `${pkgRoot}/wasm/` }
}
const mod = await import(spec)
const req = createRequire(import.meta.url)
const pkgPath = req.resolve(spec)
return { mod, wasmDir: pkgPath.replace(/dist\/[^/]+$/, 'wasm/') }
}
const { mod, wasmDir } = await loadLib()
const { Dwg_File_Type, LibreDwg } = mod
const libredwg = await LibreDwg.create(wasmDir)
const buf = readFileSync(inFile)
const dwg = libredwg.dwg_read_data(
buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
Dwg_File_Type.DWG
)
if (!dwg) {
console.error('dwg_read_data failed for', inFile)
process.exit(1)
}
const db = libredwg.convert(dwg)
const KEEP = new Set(['LINE', 'LWPOLYLINE', 'POLYLINE', 'ARC', 'CIRCLE', 'ELLIPSE', 'SPLINE', 'TEXT', 'MTEXT', 'ATTRIB', 'INSERT'])
function num(v, d = 0) { return Number.isFinite(v) ? v : d }
function pt(p) { return p ? [num(p.x), num(p.y)] : [0, 0] }
function slim(e) {
const t = e.type
if (!KEEP.has(t)) return null
const out = { t, layer: e.layer || '0' }
if (t === 'LINE') { out.a = pt(e.startPoint); out.b = pt(e.endPoint) }
else if (t === 'LWPOLYLINE' || t === 'POLYLINE') {
const vs = (e.vertices || []).map(v => [num(v.x), num(v.y), num(v.bulge)])
if (vs.length < 2) return null
out.v = vs
out.closed = Boolean((num(e.flag) & 1) || e.closed)
} else if (t === 'ARC') {
out.c = pt(e.center); out.r = num(e.radius)
out.sa = num(e.startAngle); out.ea = num(e.endAngle)
} else if (t === 'CIRCLE') { out.c = pt(e.center); out.r = num(e.radius) }
else if (t === 'ELLIPSE') {
out.c = pt(e.center); out.mj = pt(e.majorAxisEndPoint)
out.ratio = num(e.axisRatio, 1); out.sa = num(e.startAngle); out.ea = num(e.endAngle, Math.PI * 2)
} else if (t === 'SPLINE') {
const pts = (e.fitPoints && e.fitPoints.length ? e.fitPoints : e.controlPoints) || []
const vs = pts.map(p => [num(p.x), num(p.y)])
if (vs.length < 2) return null
out.v = vs
} else if (t === 'TEXT' || t === 'MTEXT' || t === 'ATTRIB') {
// ATTRIB carries axis numbers / coordinate callouts in TArch sets — emit as TEXT.
const text = (e.text || e.textValue || e.contents || '').toString()
if (!text) return null
if (t === 'ATTRIB') out.t = 'TEXT'
out.text = text.slice(0, 200)
out.p = pt(e.startPoint || e.insertionPoint || e.position)
out.h = num(e.textHeight || e.height)
} else if (t === 'INSERT') {
if (!e.name) return null
out.name = e.name
out.p = pt(e.insertionPoint)
out.sx = num(e.xScale, 1) || 1; out.sy = num(e.yScale, 1) || 1
out.rot = num(e.rotation)
}
return out
}
const entities = []
for (const e of db.entities || []) { const s = slim(e); if (s) entities.push(s) }
const blocks = {}
const inserted = new Set(entities.filter(e => e.t === 'INSERT').map(e => e.name))
const records = (db.tables && db.tables.BLOCK_RECORD && db.tables.BLOCK_RECORD.entries) || []
// include every non-layout block so nested INSERTs resolve
for (const b of records) {
const name = b.name || ''
if (!name || /^\*(Model|Paper)_Space/i.test(name)) continue
const ents = []
for (const e of b.entities || []) { const s = slim(e); if (s) ents.push(s) }
if (ents.length) blocks[name] = ents
for (const e of ents) if (e.t === 'INSERT') inserted.add(e.name)
}
const layers = ((db.tables && db.tables.LAYER && db.tables.LAYER.entries) || []).map(l => ({
name: l.name || '0', color: num(l.colorIndex, 7), off: Boolean(l.off), frozen: Boolean(l.frozen)
}))
const header = db.header || {}
writeFileSync(outFile, JSON.stringify({
source: inFile,
insunits: num(header.INSUNITS ?? header.insunits, 0),
layers, entities, blocks
}))
console.log(JSON.stringify({ out: outFile, entities: entities.length, blocks: Object.keys(blocks).length }))

143
scripts/dwgjson_to_dxf.py Normal file
View File

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

View File

@@ -0,0 +1,268 @@
#!/usr/bin/env python3
"""Build campus site-context floors from dwg_dump_json.mjs dumps of 总图/定位图.
Produces a JSON fragment (floors + extra categories) that an assembler merges
into a building_spec before spec_to_glb: ground plate from 用地红线, roads
(lines + arcs), parking stalls (block-expanded INSERTs), fence walls, street
trees as green posts, and simple massings for context buildings drawn only as
outlines in the site plan. Buildings that have their own drawing sets should
be modeled properly and placed by the site manifest — do NOT fake them here.
Usage:
python3 site_context_from_dump.py \
--dump dump_zongtu.json --scale 1.0 \
--region 349450 664100 349750 664350 \
--origin 349505.372 664163.589 \
--exclude-quad 349577.156 664230.324 349666.571 664242.204 \
349672.128 664200.371 349582.714 664188.492 \
--out site_floors.json
"""
from __future__ import annotations
import argparse
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}
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_SKIP = ("出入口",) # gate openings marked as small rects; not volumes
LABEL_SKIP = __import__("re").compile(r"^[XxYy]=|^[-+]?\d+([.,]\d+)?$")
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("--out", required=True)
return p.parse_args()
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)]
def in_quad(pt, quad):
if not quad:
return False
sign = None
for i in range(4):
ax, ay = quad[i]
bx, by = quad[(i + 1) % 4]
cross = (bx - ax) * (pt[1] - ay) - (by - ay) * (pt[0] - ax)
if abs(cross) < 1e-9:
continue
if sign is None:
sign = cross > 0
elif (cross > 0) != sign:
return False
return True
def match(layer: str, patterns) -> bool:
import fnmatch
return any(fnmatch.fnmatch(layer, p) for p in patterns)
def main() -> int:
args = parse_args()
if len(args.dump) != len(args.scale):
raise SystemExit("--dump and --scale must pair up")
x0, y0, x1, y1 = args.region
ox, oy = args.origin
quad = None
if args.exclude_quad:
q = args.exclude_quad
quad = [(q[0], q[1]), (q[2], q[3]), (q[4], q[5]), (q[6], q[7])]
def local(p):
return [round(p[0] - ox, 6), round(p[1] - oy, 6)]
segs = {"ROADS": {}, "FENCE": {}}
trees = []
boundary_polys = []
massings = []
labels = []
def add(floor, cat, a, b, width, layer):
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"})
for dump_path, scale in zip(args.dump, args.scale):
d = json.loads(Path(dump_path).read_text(encoding="utf-8"))
blocks = d.get("blocks", {})
def expand_insert(e):
"""Yield (type, data) prims of a block INSERT transformed to drawing units."""
name = e.get("name")
px, py = e["p"]
sx, sy = e.get("sx", 1) or 1, e.get("sy", 1) or 1
rot = e.get("rot", 0.0)
rot = rot if abs(rot) <= math.tau + 0.01 else math.radians(rot)
cr, srr = math.cos(rot), math.sin(rot)
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"]))
elif be["t"] in ("LWPOLYLINE", "POLYLINE"):
pts = [tf((v[0], v[1])) for v in be["v"]]
for a, b in zip(pts, pts[1:]):
yield "seg", (a, b)
elif be["t"] == "CIRCLE":
yield "circle", (tf(be["c"]), be["r"] * max(abs(sx), abs(sy)))
for e in d.get("entities", []):
layer = e.get("layer", "")
pts = []
if e["t"] == "LINE":
pts = [tuple(e["a"]), tuple(e["b"])]
elif e["t"] in ("LWPOLYLINE", "POLYLINE"):
pts = [(v[0], v[1]) for v in e["v"]]
if e.get("closed") and len(pts) > 2:
pts = pts + [pts[0]]
elif e["t"] == "ARC":
pts = flatten_arc(e["c"], e["r"], e["sa"], e["ea"], scale)
elif e["t"] in ("TEXT", "MTEXT"):
tx = (e.get("text") or "").strip()
p = [v * scale for v in e.get("p", (0, 0))]
if tx and len(tx) <= 12 and x0 <= p[0] <= x1 and y0 <= p[1] <= y1:
labels.append((tx, p))
continue
elif e["t"] == "INSERT":
p = [v * scale for v in e.get("p", (0, 0))]
if not (x0 <= p[0] <= x1 and y0 <= p[1] <= y1):
continue
if match(layer, TREE_LAYERS):
if not in_quad(p, quad):
trees.append(p)
elif layer in PARKING_LAYERS:
for kind, data in expand_insert(e):
if kind != "seg":
continue
a = (data[0][0] * scale, data[0][1] * scale)
b = (data[1][0] * scale, data[1][1] * scale)
m = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
if x0 <= m[0] <= x1 and y0 <= m[1] <= y1 and not in_quad(m, quad):
add("ROADS", "detail_lines", a, b, PARKING_LAYERS[layer], layer)
continue
if len(pts) < 2:
continue
mpts = [(p[0] * scale, p[1] * scale) for p in pts]
mx = sum(p[0] for p in mpts) / len(mpts)
my = sum(p[1] for p in mpts) / len(mpts)
if not (x0 <= mx <= x1 and y0 <= my <= y1):
continue
if layer in BOUNDARY_LAYERS or match(layer, BOUNDARY_LAYERS):
boundary_polys.append([local(p) for p in mpts])
for a, b in zip(mpts, mpts[1:]):
add("ROADS", "floor_lines", a, b, 0.20, layer)
elif layer in ROAD_LAYERS:
if in_quad((mx, my), quad):
continue
for a, b in zip(mpts, mpts[1:]):
cat = "grid" if "中心线" in layer or "Z2-" in layer or layer == "竖向" else "detail_lines"
add("ROADS", cat, a, b, ROAD_LAYERS[layer], layer)
elif layer in PARKING_LAYERS:
if not in_quad((mx, my), quad):
for a, b in zip(mpts, mpts[1:]):
add("ROADS", "detail_lines", a, b, PARKING_LAYERS[layer], layer)
elif layer in FENCE_LAYERS:
for a, b in zip(mpts, mpts[1:]):
add("FENCE", "railings", a, b, FENCE_LAYERS[layer], layer)
elif match(layer, MASSING_LAYERS):
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)):
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"]}
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"]}
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}}
# 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):
continue
kept.append(m)
for idx, m in enumerate(kept, start=1):
name, dist = f"CTX{idx}", 1e18
for tx, p in labels:
if LABEL_SKIP.search(tx):
continue
dd = math.hypot(p[0] - m["c"][0], p[1] - m["c"][1])
if dd < dist and dd < 60:
name, dist = tx, dd
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:])]
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"]]}}
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))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -8,7 +8,7 @@ a Blender install. The Web viewer recolours meshes by category from
model_metadata.json, so only correct node names + geometry are required.
"""
from __future__ import annotations
import argparse, json, math
import argparse, json, math, sys
from pathlib import Path
import numpy as np
import trimesh
@@ -66,6 +66,9 @@ def mesh_from_segments(segments, z0, z1):
if not V: return None
return trimesh.Trimesh(vertices=np.vstack(V), faces=np.vstack(F), process=False)
_POLY_FAILS = {"n": 0}
def mesh_from_polygons(polygons, z0, z1):
parts=[]
for coords in polygons:
@@ -79,7 +82,13 @@ def mesh_from_polygons(polygons, z0, z1):
m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4))
m.apply_translation((0,0,z0))
parts.append(m)
except Exception:
except Exception as exc:
# Silent drops here erase slabs/caps/roofs wholesale (e.g. trimesh
# cannot triangulate without mapbox_earcut/manifold3d installed).
_POLY_FAILS["n"] += 1
if _POLY_FAILS["n"] <= 3:
print(f"WARNING mesh_from_polygons failed ({exc}); slabs/caps/roofs may be "
"missing - pip install mapbox_earcut", file=sys.stderr)
continue
if not parts: return None
return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0]
@@ -126,6 +135,111 @@ def merge_collinear(segs, angle_tol_deg=6.0, offset_tol=0.30, gap_tol=3.6):
out.append({"start":[p0[0],p0[1]],"end":[p1[0],p1[1]],"width":w,"layer":layer,"source_type":"merged"})
return out
def extend_shared_wall_ends(segments, tol=1e-3):
"""Extend wall ends that meet another wall's endpoint by half their own width.
Flat-capped rectangles stop exactly at the endpoint, so an L-corner leaves
a w/2 x w/2 notch that even a union keeps open. Extending only SHARED ends
makes the corner rectangles overlap (union -> clean square corner) while
free ends (door/window openings) stay flat. T-joints need nothing: the
ending wall already reaches the crossing wall's centerline.
"""
from collections import Counter
pts=[]
for s in segments:
pts.append((float(s["start"][0]), float(s["start"][1])))
pts.append((float(s["end"][0]), float(s["end"][1])))
scale=1.0/max(tol,1e-9)
buckets=Counter((round(x*scale), round(y*scale)) for x,y in pts)
def shared(p):
cx,cy=round(p[0]*scale), round(p[1]*scale)
return sum(buckets.get((gx,gy),0) for gx in (cx-1,cx,cx+1) for gy in (cy-1,cy,cy+1))>=2
out=[]
for s in segments:
a=[float(s["start"][0]), float(s["start"][1])]
b=[float(s["end"][0]), float(s["end"][1])]
dx,dy=b[0]-a[0],b[1]-a[1]; L=math.hypot(dx,dy)
if L<1e-7:
out.append(s); continue
ux,uy=dx/L,dy/L
half=max(float(s.get("width",0.1)),0.005)/2.0
item=dict(s)
if shared((a[0],a[1])): a=[a[0]-ux*half, a[1]-uy*half]
if shared((b[0],b[1])): b=[b[0]+ux*half, b[1]+uy*half]
item["start"]=a; item["end"]=b
out.append(item)
return out
def merged_wall_polygons(segments):
"""Union per-segment wall rectangles into continuous solids (shapely).
Shared endpoints are pre-extended (see extend_shared_wall_ends), then each
segment becomes a flat-capped rectangle (LineString.buffer, cap_style=2,
half its own width) and unary_union removes corner seams and z-fighting at
junctions. Returns shapely Polygons (holes preserved for courtyard walls).
Enabled via config {"merge_wall_solids": true}.
"""
from shapely.geometry import LineString
from shapely.ops import unary_union
rects=[]
for s in extend_shared_wall_ends(segments):
a=s["start"]; b=s["end"]
if math.hypot(b[0]-a[0], b[1]-a[1])<1e-7: continue
w=max(float(s.get("width",0.1)), 0.005)
rects.append(LineString([tuple(a), tuple(b)]).buffer(w/2.0, cap_style=2))
if not rects: return []
union=unary_union(rects)
geoms=[union] if union.geom_type=="Polygon" else list(getattr(union,"geoms",[]))
# simplify(0) drops the collinear vertices GEOS noding leaves on straight edges
return [g.simplify(0) for g in geoms if g.geom_type=="Polygon" and g.area>1e-6]
def mesh_from_shapely(polys, z0, z1):
"""Extrude shapely Polygons directly (keeps interior holes, unlike mesh_from_polygons)."""
parts=[]
for poly in polys:
try:
m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4))
m.apply_translation((0,0,z0))
parts.append(m)
except Exception as exc:
_POLY_FAILS["n"] += 1
if _POLY_FAILS["n"] <= 3:
print(f"WARNING mesh_from_polygons failed ({exc}); merged walls may be "
"missing - pip install mapbox_earcut", file=sys.stderr)
continue
if not parts: return None
return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0]
def glazing_mullion_segments(bands, z0, z1, panel_w=1.5, profile=0.06, depth=0.10):
"""Curtain-wall panel grid over merged glazing bands.
Emits pseudo wall segments (thin box profiles, walls material via the
<floor>__walls node): vertical mullions evenly spaced ~panel_w along each
band (posts at both ends included) plus a horizontal transom at the band's
bottom and top floor lines (carrying _z0/_z1). The glass pane itself stays.
Config {"glazing_mullions": true}, pitch {"glazing_panel_w": 1.5}.
"""
out=[]
for s in bands:
a=s["start"]; b=s["end"]
dx,dy=b[0]-a[0],b[1]-a[1]; L=math.hypot(dx,dy)
if L<max(profile*2, 0.3): continue
ux,uy=dx/L,dy/L
n=max(1, round(L/max(panel_w, 0.2)))
step=L/n
for i in range(n+1):
t=i*step
cx,cy=a[0]+ux*t, a[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":s.get("layer",""), "source_type":"mullion"})
th=0.08
for tz0,tz1 in ((z0, z0+th), (z1-th, z1)):
out.append({"start":[float(a[0]),float(a[1])], "end":[float(b[0]),float(b[1])],
"width":depth, "layer":s.get("layer",""), "source_type":"transom",
"_z0":tz0, "_z1":tz1})
return out
def _shapely_union(polys):
from shapely.geometry import Polygon
from shapely.ops import unary_union
@@ -157,6 +271,10 @@ def setback_cap_polys(spec, fk, fl, own_polys):
if abs(float(ot.get("z",0.0))-ftop)>0.8: continue
upper.extend(ot.get("footprint",{}).get("polygons",[]))
own_u=_shapely_union(own_polys)
cfg=spec.get("source",{}).get("config",{})
# 1.3 suits colonnade buildings (A208); ordinary facades want ~0.1 or the
# cap ring reads as a slab overhanging every floor. Config: cap_buffer.
buf=float(cfg.get("cap_buffer",1.3))
if not upper:
# top of a basement stack -> cap the WHOLE footprint (ground / podium deck over parking)
if grp=="BASE" and own_u is not None:
@@ -165,8 +283,7 @@ def setback_cap_polys(spec, fk, fl, own_polys):
up_u=_shapely_union(upper)
if own_u is None or up_u is None: return []
try:
# buffer own footprint outward so the cap also covers perimeter colonnade columns
ring=own_u.buffer(1.3).difference(up_u.buffer(0.05))
ring=own_u.buffer(buf).difference(up_u.buffer(0.05))
except Exception:
return []
return _shapely_to_polys(ring, min_area=3.0)
@@ -321,7 +438,10 @@ def build_scene(spec, categories):
cap_polys=setback_cap_polys(spec, fk, fl, polys)
if cap_polys:
parts.append(mesh_from_polygons(cap_polys, z+h-slab_th, z+h))
else:
elif cfg.get("slab_bounds_fallback", True):
# Rectangular fallback can fake a full-cover plate on floors
# like parapet-only roof plans; disable via config
# {"slab_bounds_fallback": false} when footprints are trusted.
b=fl["bounds"]; mg=1.2
parts.append(mesh_from_polygons(
[[[b[0]-mg,b[1]-mg],[b[2]+mg,b[1]-mg],[b[2]+mg,b[3]+mg],[b[0]-mg,b[3]+mg]]],
@@ -330,6 +450,13 @@ def build_scene(spec, categories):
if parts:
add(f"{fk}__slab", parts[0] if len(parts)==1 else trimesh.util.concatenate(parts), "slab")
segs=fl.get("segments",{})
mullion_mesh=None
if cfg.get("glazing_mullions", False) and segs.get("glazing") and (want is None or "walls" in want):
gz0,gz1=z_window("glazing",z,h,fk,fl)
mullion_mesh=mesh_from_segments(
glazing_mullion_segments(merge_collinear(segs["glazing"]), gz0, gz1,
panel_w=float(cfg.get("glazing_panel_w",1.5))),
gz0, gz1)
present=[c for c in CATEGORY_DRAW_ORDER if segs.get(c)]
extra=sorted(c for c in segs if c not in CATEGORY_DRAW_ORDER and segs.get(c))
for cat in present+extra:
@@ -340,7 +467,22 @@ def build_scene(spec, categories):
seglist=adjust_columns(seglist, fk, fl, spec, cfg, roofs)
if cat=="glazing":
seglist=merge_collinear(seglist)
if cat=="walls":
wall_mesh=None
if cfg.get("merge_wall_solids", False):
wall_mesh=mesh_from_shapely(merged_wall_polygons(seglist), z0, z1)
if wall_mesh is None:
wall_mesh=mesh_from_segments(seglist, z0, z1)
if mullion_mesh is not None:
parts=[p for p in (wall_mesh, mullion_mesh) if p is not None]
wall_mesh=trimesh.util.concatenate(parts) if len(parts)>1 else (parts[0] if parts else None)
mullion_mesh=None
add(f"{fk}__walls", wall_mesh, "walls")
continue
add(f"{fk}__{cat}", mesh_from_segments(seglist, z0, z1), cat)
if mullion_mesh is not None:
# glazing-only floor: the panel grid still needs a walls node
add(f"{fk}__walls", mullion_mesh, "walls")
# generated roofs
if want is None or "roof" in want:
for r in roof_specs(spec):

View File

@@ -0,0 +1,251 @@
#!/usr/bin/env python3
"""Emit a fully-offline single-file HTML viewer for a building/campus GLB.
Use when the deliverable must open by double-click with NO server and NO
network (mainland-China CDNs are unreliable; jsdelivr-importing viewers hang
on the loading screen). Everything is inlined: three r147 UMD + OrbitControls
+ GLTFLoader + RoomEnvironment + pako, plus the GLB itself gzip-compressed
(browser-side pako inflate; ~5x smaller than raw base64 embedding).
Features: ACES tone mapping, RoomEnvironment IBL, PCF soft shadows + ground
shadow catcher, physical-glass glazing, instanced low-poly street trees (from
a TREES floor), grouped floor toggles (SITE/CTX* -> 场地, leading-digit keys ->
N#, rest -> 主体), category toggles, click-to-inspect, on-screen error
reporting (never a silent spinner).
The official template (assets/web-showcase-template) remains the primary
delivery for served deployments; this is the share-by-file variant.
Usage:
python3 write_offline_viewer.py --spec building_spec.json --glb model.glb \
--out viewer.html [--title 项目名] [--libs-dir <skill>/assets/offline-viewer-libs]
"""
from __future__ import annotations
import argparse
import base64
import gzip
import json
from pathlib import Path
SKILL_ROOT = Path(__file__).resolve().parent.parent
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--spec", required=True)
p.add_argument("--glb", required=True)
p.add_argument("--out", required=True)
p.add_argument("--title", default=None)
p.add_argument("--subtitle", default="离线单文件查看器")
p.add_argument("--libs-dir", default=str(SKILL_ROOT / "assets" / "offline-viewer-libs"))
return p.parse_args()
def group_of(key: str) -> str:
if key in ("SITE", "ROADS", "FENCE", "TREES") or key.startswith("CTX"):
return "场地"
if key[:1].isdigit():
return key[0] + "#"
return "主体"
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>'; };
window.addEventListener('error', e => fail(e.message));
window.addEventListener('unhandledrejection', e => fail(e.reason && e.reason.message || e.reason));
try {
const GROUPS = __GROUPS__, CATS = __CATS__, TREES = __TREES__;
const renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(innerWidth,innerHeight); renderer.setPixelRatio(Math.min(devicePixelRatio,2));
renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.physicallyCorrectLights = true;
renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x23272d);
scene.fog = new THREE.Fog(0x23272d, 500, 1400);
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new THREE.RoomEnvironment(), 0.04).texture;
const cam = new THREE.PerspectiveCamera(48, innerWidth/innerHeight, 0.5, 4000);
const controls = new THREE.OrbitControls(cam, renderer.domElement); controls.enableDamping = true;
const sun = new THREE.DirectionalLight(0xfff3e0, 3.2);
sun.position.set(-120, 180, 140); sun.castShadow = true;
sun.shadow.mapSize.set(2048,2048); sun.shadow.bias = -0.0004;
scene.add(sun); scene.add(new THREE.AmbientLight(0xdfe8ff, 0.5));
$load.textContent = '正在解压模型…';
await new Promise(r => setTimeout(r, 30));
const bin = atob(GLB_B64); const gz = new Uint8Array(bin.length);
for (let i=0;i<bin.length;i++) gz[i]=bin.charCodeAt(i);
const raw = pako.inflate(gz);
const buf = raw.buffer.slice(raw.byteOffset, raw.byteOffset+raw.byteLength);
$load.textContent = '正在解析场景…';
new THREE.GLTFLoader().parse(buf, '', g => {
$load.remove();
const root = g.scene; scene.add(root);
const bb = new THREE.Box3().setFromObject(root);
const c = bb.getCenter(new THREE.Vector3()), sz = bb.getSize(new THREE.Vector3());
const radius = Math.max(sz.x, sz.z, 20) * 0.75;
sun.target.position.copy(c); scene.add(sun.target);
const sc = sun.shadow.camera;
sc.left=-radius; sc.right=radius; sc.top=radius; sc.bottom=-radius; sc.near=5; sc.far=radius*6;
sc.updateProjectionMatrix();
controls.target.copy(c);
cam.position.set(c.x + sz.x*0.55, c.y + Math.max(sz.x,sz.z)*0.5, c.z + sz.z*1.25);
const ground = new THREE.Mesh(new THREE.PlaneGeometry(radius*8, radius*8), new THREE.ShadowMaterial({opacity:0.35}));
ground.rotation.x = -Math.PI/2; ground.position.set(c.x, -0.02, c.z); ground.receiveShadow = true; scene.add(ground);
const nodes = [];
root.traverse(o => {
if (!o.isMesh) return;
nodes.push(o);
const parts = (o.name||'').split('__'), fk = parts[0], cat = parts[1];
if (cat === 'glazing') {
o.material = new THREE.MeshPhysicalMaterial({color:0x9fd4e8, metalness:0, roughness:0.18,
transmission:0.72, ior:1.5, thickness:0.3, transparent:true, depthWrite:false, side:THREE.DoubleSide});
o.material.envMapIntensity = 1.2;
} else if (['walls','columns','roof','slab','railings'].indexOf(cat)>=0 && fk!=='SITE') {
o.castShadow = true; o.receiveShadow = true;
}
if (cat === 'trees') o.visible = false;
});
if (TREES.length) {
const ti = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.14,0.2,1.4,6),
new THREE.MeshStandardMaterial({color:0x6b4a2e, roughness:0.9}), TREES.length);
const ci = new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1.5,1),
new THREE.MeshStandardMaterial({color:0x3e7d4f, roughness:0.8}), TREES.length);
const m4 = new THREE.Matrix4();
for (let i=0;i<TREES.length;i++){
const x=TREES[i][0], z=-TREES[i][1];
m4.makeScale(1,1,1); m4.setPosition(x,0.7,z); ti.setMatrixAt(i,m4);
const s = 0.85+(i%5)*0.08;
m4.makeScale(s,s,s); m4.setPosition(x,2.6,z); ci.setMatrixAt(i,m4);
}
ti.castShadow = ci.castShadow = true;
scene.add(ti); scene.add(ci);
}
const tg = document.getElementById('tg');
const state = {fl:{}, ct:{}};
const apply = () => nodes.forEach(o => { const p=(o.name||'').split('__');
o.visible = (state.fl[p[0]]!==false) && (state.ct[p[1]]!==false) && p[1]!=='trees'; });
for (const gname in GROUPS) {
const head = document.createElement('div'); head.className='grp';
const btn = document.createElement('button'); btn.textContent='开/关';
let on = true;
btn.onclick = () => { on=!on; GROUPS[gname].forEach(f => { state.fl[f[0]]=on;
const cb=document.getElementById('cb_'+f[0]); if(cb) cb.checked=on; }); apply(); };
head.appendChild(document.createTextNode(gname)); head.appendChild(btn); tg.appendChild(head);
GROUPS[gname].forEach(f => {
const l = document.createElement('label');
l.innerHTML = '<input id="cb_'+f[0]+'" type="checkbox" checked> '+f[0]+' '+f[1];
l.querySelector('input').onchange = e => { state.fl[f[0]]=e.target.checked; apply(); };
tg.appendChild(l);
});
}
const head2 = document.createElement('div'); head2.className='grp';
head2.textContent = '构件'; tg.appendChild(head2);
const used = {};
nodes.forEach(o => used[(o.name||'').split('__')[1]] = 1);
for (const k in CATS) {
if (!used[k] || k==='trees') continue;
const l = document.createElement('label');
l.innerHTML = '<input type="checkbox" checked> '+CATS[k];
l.querySelector('input').onchange = e => { state.ct[k]=e.target.checked; apply(); };
tg.appendChild(l);
}
const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), info = document.getElementById('info');
let hi=null, hiMat=null, downAt=null;
addEventListener('pointerdown', e => downAt=[e.clientX,e.clientY]);
addEventListener('pointerup', e => {
if (!downAt || Math.hypot(e.clientX-downAt[0], e.clientY-downAt[1])>4) return;
ptr.x=(e.clientX/innerWidth)*2-1; ptr.y=-(e.clientY/innerHeight)*2+1;
ray.setFromCamera(ptr, cam);
const hit = ray.intersectObjects(nodes.filter(o=>o.visible), false)[0];
if (hi) { hi.material = hiMat; hi = null; }
if (!hit) { info.style.display='none'; return; }
hi = hit.object; hiMat = hi.material;
hi.material = hiMat.clone(); hi.material.emissive = new THREE.Color(0x2a6bd4); hi.material.emissiveIntensity = 0.55;
const p = (hi.name||'').split('__');
let fname=''; for (const gname in GROUPS) GROUPS[gname].forEach(f => { if (f[0]===p[0]) fname=f[1]; });
info.innerHTML = '<b>'+p[0]+'</b> '+fname+'<br>构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name;
info.style.display = 'block';
});
renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, cam); });
}, e => fail('GLB 解析错误 '+(e && e.message || e)));
addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); });
} 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}'
)
def main() -> int:
args = parse_args()
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.")
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()
b64 = base64.b64encode(gzip.compress(glb, 6)).decode()
order = spec.get("source", {}).get("config", {}).get("floor_order") or list(spec.get("floors", {}))
groups: dict = {}
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", [])]
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)))
sc_close = "</scr" + "ipt>"
html = (
'<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8">'
f'<title>{title} · 3D 查看器(离线版)</title>'
'<meta name="viewport" content="width=device-width, initial-scale=1">'
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"))
+ f'<script>const GLB_B64="{b64}";{sc_close}'
+ f"<script>{main_js}{sc_close}"
+ "</body></html>"
)
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))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -121,7 +121,30 @@ def inferred_metadata(args_metadata: str | None, manifest_path: Path | None, man
return resolve_manifest_path(manifest_path, metadata_value) if manifest_path else Path(metadata_value)
def write_assets(glb: Path, metadata: Path, out_dir: Path, web_variants: list[dict]):
def site_trees_from_spec(spec_path: Path | None) -> list[list[float]]:
"""Tree anchor points (plan meters) for the viewer's instanced low-poly trees.
site_context_from_dump.py emits street trees as short posts under the
custom `trees` category; the viewer hides those posts and renders
trunk+crown InstancedMeshes at these midpoints instead.
"""
if not spec_path or not spec_path.exists():
return []
try:
spec = json.loads(spec_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return []
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),
])
return trees
def write_assets(glb: Path, metadata: Path, out_dir: Path, web_variants: list[dict], site_trees: list[list[float]]):
if not glb.exists():
raise SystemExit(f"GLB not found: {glb}")
if not metadata.exists():
@@ -131,6 +154,8 @@ def write_assets(glb: Path, metadata: Path, out_dir: Path, web_variants: list[di
meta.setdefault("files", {})["glb"] = "model.glb"
if web_variants:
meta["model_variants"] = web_variants
if site_trees:
meta["site_trees"] = site_trees
(out_dir / "model_metadata.json").write_text(
json.dumps(meta, ensure_ascii=False, indent=2),
encoding="utf-8",
@@ -148,7 +173,10 @@ def main() -> int:
web_variants = copy_variant_assets(manifest_path, variants, out_dir)
glb = inferred_default_glb(args.glb, manifest_path, manifest, variants)
metadata = inferred_metadata(args.metadata, manifest_path, manifest, variants)
write_assets(glb, metadata, out_dir, web_variants)
variant = default_variant(manifest, variants)
spec_value = variant.get("spec") if variant else None
spec_path = resolve_manifest_path(manifest_path, spec_value) if (manifest_path and spec_value) else None
write_assets(glb, metadata, out_dir, web_variants, site_trees_from_spec(spec_path))
print(json.dumps({"web_dir": str(out_dir), "entry": str(out_dir / "index.html")}, ensure_ascii=False))
return 0