From 1e11d38fa922446080137032e165c7ba9bd4c472 Mon Sep 17 00:00:00 2001 From: zhengwr Date: Fri, 3 Jul 2026 07:48:22 +0800 Subject: [PATCH] =?UTF-8?q?derive:=20per-cluster=20footprint=20hulls=20?= =?UTF-8?q?=E2=80=94=20twin-tower=20floors=20no=20longer=20bridged?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit concave_hull over all points cannot split disconnected masses: 13号 一号楼 standard floors (A/B towers in one floor key) got ONE 135.6m hull and use_footprint_slabs laid plates across the 36m void (user-visible as "triangular links" between towers). Points are now union-find clustered (footprint_cluster_linkage, 6m grid buckets; segment endpoints forced into one cluster) and hulled per cluster — real link bridges keep clusters merged via their walls. F4-F10 now 2x49.8m hulls matching the site-plan OBB; 黄桥/27号 re-derived with no regression; DoD visual check extended (look at the AIR between masses in front/side views). Regression: twintower scenario (+3 checks). Co-Authored-By: Claude Fable 5 --- SKILL.md | 4 +- references/generalization_test_log.md | 9 ++++ scripts/derive_showcase_spec.py | 70 +++++++++++++++++++++++---- tests/test_extraction_pipeline.py | 33 +++++++++++++ 4 files changed, 104 insertions(+), 12 deletions(-) diff --git a/SKILL.md b/SKILL.md index 12eefe0..fb6c719 100644 --- a/SKILL.md +++ b/SKILL.md @@ -56,7 +56,7 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate 2. Frame alignment proven: detect report shows `grid-aligned, votes x>=3 y>=3` per floor (any `WEAK grid match` floor was verified on its overlay SVG). 3. Audit exit code 0, and gates `floors_aligned` / `glazing_captured` / `no_annotation_layers_classified` all PASS. Never pass `--no-strict-gates` to proceed. 4. No `WARNING topless_group` from derive (roof handled via caps or `roof_specs`), and no `WARNING mesh_from_polygons` from the GLB build (else slabs/roofs silently vanished — install mapbox_earcut). -5. Visual check done by the Agent, not assumed: `verify_showcase.py` previews plus one rendered iso/plan image actually LOOKED AT (floors stacked, roof present, no slab fins beyond facade — default `cap_buffer` 1.3 is for colonnades, use ~0.1 otherwise). +5. Visual check done by the Agent, not assumed: `verify_showcase.py` previews plus one rendered iso/plan image actually LOOKED AT (floors stacked, roof present, no slab fins beyond facade — default `cap_buffer` 1.3 is for colonnades, use ~0.1 otherwise; and check the AIR between separate masses in the front/side views — bridged footprint hulls lay slab plates between twin towers, invisible in top views and to every gate). 6. Campus placement (if 总图/定位图 exists): building envelope dims match the site rect 1:1 (e.g. 面积核算 frame), rotation taken from the rect edge angle, 180° flip disambiguated by an asymmetric feature (machine rooms / basement / entrance), and a top-view overlay image confirms the building inside its site rect. Neighbour gaps measured numerically: no overlaps, 贴建 joints 0.15-0.3 m with corroborating evidence, buildings inside 红线. 7. `tests/test_extraction_pipeline.py` passes after ANY script change. @@ -85,7 +85,7 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate - MULTI-FRAME SHEETS (the common Chinese pattern: one DWG per building holding ALL its plans + elevations + sections stacked in modelspace): run `scripts/detect_sheet_frames.py` on the sanitized DXF. It finds `XX平面图` title texts (filtering catalog rows and title-block copies; titles INSIDE cached-xref blocks are scanned too), proposes a wall-bbox-refined `clip` per floor frame, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). When a frame has NO axis geometry at all, it falls back to wall-profile correlation (length-weighted wall-position histograms, x and y independently, coverage+peak-ratio gated) before surrendering to the clip-corner anchor — clip corners track wall bboxes and drift by whole bays when balconies differ. Auxiliary-titled frames (非机动坡道/无障碍改造/人防…) are flagged and never become the alignment reference (a bike-ramp frame once anchored a whole tower to nothing). Never model such a file as one floor (all sheets superimpose) and never stack frames without offsets (floors staircase away diagonally — the classic broken output). Read its report: `WEAK grid match` floors need overlay verification; `wall-correlated` floors deserve one overlay check too; elevation/section frames are listed for floor heights (`z`/`height` from DIM_ELEV 标高 texts like `8.100`), not as floors. Frame clips can swallow the sheet above/below (refine bbox includes between-sheet strips): if a floor's footprint depth is ~2-4x its siblings, cluster its wall y-midpoints and cut the clip band to the plan's own row. - Align floors by structural grid or repeated control axes. Use millimeters-to-meters scale (`0.001`) unless the report proves the CAD is already in meters. - Floor keys: `floor_sort_key` treats a leading `B` as basement (sorted below ground). Do not invent keys like `B1F` for "Building 1 Floor" — use per-building specs instead, and set explicit `floor_order` whenever keys are nonstandard. - - When CAD linework has enough exterior/interior boundary signal, enable generated footprints for floor slabs and roof caps. Prefer footprint polygons over rectangular floor bounds for visual/digital-twin presentation. + - When CAD linework has enough exterior/interior boundary signal, enable generated footprints for floor slabs and roof caps. Prefer footprint polygons over rectangular floor bounds for visual/digital-twin presentation. Footprints are hulled PER proximity cluster (`footprint_cluster_linkage`, 6 m): a floor holding two disconnected masses (13号 twin towers in one floor key) gets separate hulls — a single concave hull would bridge the void and `use_footprint_slabs` would lay plates across it; genuinely linked wings stay merged because the 连廊 walls connect the clusters. - Run `scripts/derive_showcase_spec.py` to extract line/polyline geometry into `building_spec.json`. 4. Audit extraction before 3D generation. diff --git a/references/generalization_test_log.md b/references/generalization_test_log.md index 9fb5bb0..632f608 100644 --- a/references/generalization_test_log.md +++ b/references/generalization_test_log.md @@ -282,6 +282,15 @@ glazing 在 walls 之前匹配。3.0m×22 层梯(0..66,机房顶69)。 都大声告警。回归 fo_config 场景。 17. **assemble_campus 每栋 rotation_deg**(27号 4#楼独自斜置):manifest 每栋可覆盖全局旋转。回归 90° 旋转场景。 +18. **凹包桥接双塔生成横跨楼板**(13号 一号楼,用户 viewer 目检发现): + 一层 key 装 A/B 两塔时 concave_hull 对全部点只出一个包, + use_footprint_slabs 在 36m 空隙上逐层铺板(侧视=塔间"三角连接")。 + 修复:出包前按端点邻近分簇(footprint_cluster_linkage 6m,网格桶并查集, + 段两端强制同簇),每簇独立凹包——真连廊因连廊墙自然连通不受影响。 + 修后 F4-F10 = 2×49.8m 独立塔包(与总图 OBB 一致);黄桥 F4/RF 北侧 + 1.4m 长条构件也随之脱离主包(更诚实);27号 各楼无回归。回归 twintower + 场景(两簇 40m 距,断言 2 包且无 25m+ 跨包)。教训:**门禁与顶视图对 + 桥接楼板都不敏感,侧视/正视目检必须看"楼间空气"**——已列入 DoD 目检项。 **已知未修(记录在案)**:③ 图签块 INSERT 定图框(加长A0 被 pitch 截半, 13号教训——mixed-pitch 修复部分缓解,完整方案待设计);⑤ floors_aligned diff --git a/scripts/derive_showcase_spec.py b/scripts/derive_showcase_spec.py index eebd805..1cde8ea 100755 --- a/scripts/derive_showcase_spec.py +++ b/scripts/derive_showcase_spec.py @@ -643,20 +643,70 @@ def generated_footprint(segments: dict[str, list[dict[str, Any]]], config: dict[ if len(unique_points) < 4: return None + # Cluster points by proximity BEFORE hulling: concave_hull over all points + # can never split disconnected masses, so a twin-tower floor got ONE + # bridged hull and use_footprint_slabs laid plates across the 36 m void + # (13号 一号楼 A/B座). Per-cluster hulls keep genuinely linked wings — + # a real 连廊 contributes walls that join the clusters. + linkage = float(config.get("footprint_cluster_linkage", 6.0)) + parent = list(range(len(unique_points))) + + def find(a: int) -> int: + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + def union(a: int, b: int) -> None: + ra, rb = find(a), find(b) + if ra != rb: + parent[rb] = ra + + cell = max(linkage, 1e-6) + buckets: dict[tuple[int, int], list[int]] = {} + for idx, (px, py) in enumerate(unique_points): + buckets.setdefault((int(px // cell), int(py // cell)), []).append(idx) + for (bx, by), members in buckets.items(): + for gx in (bx - 1, bx, bx + 1): + for gy in (by - 1, by, by + 1): + for other in buckets.get((gx, gy), []): + union(members[0], other) + for other in members[1:]: + union(members[0], other) + # Segments span their endpoints: both ends of one segment belong together. + seg_pt_index = {pt: i for i, pt in enumerate(unique_points)} + for category in categories: + for segment in segments.get(category, []): + start = segment.get("start") + end = segment.get("end") + if not start or not end: + continue + a = seg_pt_index.get((float(start[0]), float(start[1]))) + b = seg_pt_index.get((float(end[0]), float(end[1]))) + if a is not None and b is not None: + union(a, b) + clusters: dict[int, list[tuple[float, float]]] = {} + for idx, pt in enumerate(unique_points): + clusters.setdefault(find(idx), []).append(pt) + ratio = float(config.get("footprint_concave_ratio", 0.35)) simplify = float(config.get("footprint_simplify_tolerance", 0.12)) min_area = float(config.get("footprint_min_area", 8.0)) + polygons = [] try: - hull = concave_hull(MultiPoint(unique_points), ratio=ratio) - if simplify > 0: - hull = hull.simplify(simplify, preserve_topology=True) - if hull.is_empty or hull.area < min_area: - return None - if hull.geom_type == "Polygon": - polygons = [hull] - elif hull.geom_type == "MultiPolygon": - polygons = list(hull.geoms) - else: + for cluster_pts in clusters.values(): + if len(cluster_pts) < 4: + continue + hull = concave_hull(MultiPoint(cluster_pts), ratio=ratio) + if simplify > 0: + hull = hull.simplify(simplify, preserve_topology=True) + if hull.is_empty or hull.area < min_area: + continue + if hull.geom_type == "Polygon": + polygons.append(hull) + elif hull.geom_type == "MultiPolygon": + polygons.extend(hull.geoms) + if not polygons: return None except Exception: return None diff --git a/tests/test_extraction_pipeline.py b/tests/test_extraction_pipeline.py index d6131d3..22c9c73 100644 --- a/tests/test_extraction_pipeline.py +++ b/tests/test_extraction_pipeline.py @@ -887,6 +887,39 @@ def main() -> int: ok_mx = f2 is not None and abs(f2["offset"][0]) <= 120 and abs(f2["offset"][1] - 98100.0) <= 120 check("mixed layout offset recovered", ok_mx, str(f2 and f2["offset"])) + # --- twin-tower floors must get SEPARATE footprint hulls (13号 一号楼: 凹包桥接 + # 两塔, use_footprint_slabs 在 36m 空隙上生成横跨飘板) --- + tt_dir = WORK / "dxf_twintower" + tt_dir.mkdir(parents=True, exist_ok=True) + tt_doc = ezdxf.new("R2010", setup=True) + tt_doc.layers.add("I-WALL") + tt_msp = tt_doc.modelspace() + for ox in (0.0, 60000.0): # two 20m x 10m towers, 40 m of void between + for start, end in [((ox, 0), (ox + 20000, 0)), ((ox + 20000, 0), (ox + 20000, 10000)), + ((ox + 20000, 10000), (ox, 10000)), ((ox, 10000), (ox, 0)), + ((ox + 7000, 0), (ox + 7000, 10000)), ((ox + 13000, 0), (ox + 13000, 10000)), + ((ox, 5000), (ox + 20000, 5000))]: + tt_msp.add_line(start, end, dxfattribs={"layer": "I-WALL"}) + tt_doc.saveas(tt_dir / "twin.dxf") + tt_config = { + "scale": 0.001, "generate_footprints": True, "use_footprint_slabs": True, + "drawings": [{"file": "twin.dxf", "floors": [{"key": "F4", "name": "标准层", "z": 12.0, "height": 4.2}]}], + } + tt_cfg = WORK / "tt_config.json" + tt_cfg.write_text(json.dumps(tt_config, ensure_ascii=False), encoding="utf-8") + proc = run([ + sys.executable, "scripts/derive_showcase_spec.py", + "--dxf-dir", str(tt_dir), "--config", str(tt_cfg), + "--out", str(WORK / "tt_spec.json"), "--vendor-dir", str(VENDOR), + ]) + check("derive twin-tower floor runs", proc.returncode == 0, proc.stderr[-400:]) + if proc.returncode == 0: + tt_spec = json.loads((WORK / "tt_spec.json").read_text(encoding="utf-8")) + polys = tt_spec["floors"]["F4"]["footprint"]["polygons"] + spans = [max(p[0] for p in poly) - min(p[0] for p in poly) for poly in polys] + check("two separate footprint hulls", len(polys) == 2, f"n={len(polys)} spans={spans}") + check("no hull bridges the void", all(s < 25.0 for s in spans), f"spans={spans}") + # --- floor_order gaps must warn loudly, not silently drop floors (13号 b2: F11-F16 消失) --- fo_config = { "scale": 0.001,