366 lines
13 KiB
Python
366 lines
13 KiB
Python
#!/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())
|