feat: harden CAD showcase skill and delivery pipeline

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

54
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,54 @@
name: ci
on:
push:
pull_request:
jobs:
test:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python: ["3.10", "3.12"]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
cache: pip
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
- run: python -m pip install -r requirements-qa.txt
- run: npm ci
- run: python -m compileall -q scripts tests
- run: ruff format --check scripts tests
- run: ruff check scripts tests
- run: node --check assets/web-showcase-template/app.js
- run: node --check scripts/dwg_dump_json.mjs
- run: node --check scripts/web_smoke_test.mjs
- run: node --check tools/compress.mjs
- run: pytest tests/test_contracts.py tests/test_delivery.py
- run: python tests/test_extraction_pipeline.py
browser-smoke:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
- run: python -m pip install -r requirements-qa.txt
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: pytest tests/test_browser_smoke.py
env:
RUN_BROWSER_SMOKE: "1"

View File

@@ -32,18 +32,26 @@ git clone ... tools/cad-building-showcase # 克隆到项目内任意位置(
处理 DWG/DXF 转 3D/Web 展示任务时,必须先完整阅读
tools/cad-building-showcase/SKILL.md 并遵守其中 One-Shot Definition of Done
七条门禁:门禁失败即停下修复,绝不绕过;改动任何脚本后必须跑
`python3 tools/cad-building-showcase/tests/test_extraction_pipeline.py` 且全绿。
`pytest tools/cad-building-showcase/tests/test_contracts.py tools/cad-building-showcase/tests/test_delivery.py`
与 `python3 tools/cad-building-showcase/tests/test_extraction_pipeline.py` 且全绿。
```
**任何其他 Agent 的兜底用法**:把上面那段话作为任务开场白直接粘给它——skill 的全部约定都在 `SKILL.md` 里,脚本自含 CLI(`--help` 可查),不依赖宿主工具的任何私有机制。
**运行依赖**:Python ≥3.10 + `ezdxf`(惯例装到 `pip install --target work/vendor ezdxf`)、`shapely`、`trimesh`、`matplotlib`;Node ≥18(`tools/compress.mjs`、无原生转换器时的 WASM DWG 兜底)。可选:libredwg(`dwg2dxf` 批量转换)、ODA File Converter(坏件/天正大图兜底,脚本自动调用)、Blender(高保真渲染分支)。
**运行依赖**:Python ≥3.10,核心运行 `pip install -r requirements-core.txt`,交付验证再装 `requirements-delivery.txt`;Node ≥18。可选:libredwg、ODA File Converter、Blender、IfcOpenShell。先运行 `python3 scripts/cad_showcase.py doctor` 检查环境。
**跨平台**:脚本全用 pathlib + 显式 UTF-8 I/O + 子进程 bytes 解码,macOS/Linux/Windows 均可跑。工具发现顺序:Blender = env `BLENDER` → PATH → 平台安装默认(macOS 应用包 / Windows `Program Files\Blender Foundation`);ODA = env `ODA_CONVERTER` → PATH → 平台默认(Windows 含 `Program Files\ODA`)。Windows 建议:设 `PYTHONUTF8=1`(防重定向输出按 GBK 解码)、开启 LongPathsEnabled(中文长文件名的深层 work/ 目录可能触及 260 字符 MAX_PATH);Windows 上 libredwg 少见,DWG 转换以 ODA 为主路径。
## 用法
入口是 `SKILL.md`(操作手册):决策循环、One-Shot Definition of Done 七条门禁、天正图层方言预设、多栋厂区流程。核心链路:
入口是 `SKILL.md`(决策树与硬门禁),详细分支按需读取 `references/`。推荐统一 CLI:
```bash
python3 scripts/cad_showcase.py inspect --input <cad> --work work/<project> --output outputs/<project>/read_report
python3 scripts/cad_showcase.py run --dxf-dir <dxf> --config <config> --source-report <cad_read_report.json> --out-dir outputs/<project> --name <project> --backend trimesh --web --offline --resume
```
核心链路:
```
cad_dxf_report.py 读图报告(警告:多框图纸/缓存XREF/陌生图层方言…)
@@ -60,10 +68,9 @@ register_site_outlines.py / massing_from_outline.py / assemble_campus.py
## 目录
- `scripts/` 全部流水线脚本(自含 CLI,`--help` 有说明)
- `tests/test_extraction_pipeline.py` 回归套件(改任何脚本后必跑)
- `references/` 案例记录与校准资料:`pipeline.md`(详细流程)、
`generalization_test_log.md`(泛化测试与缺口修复清单)、
`贝昂CAD诊断与skill优化.md`(首个案例全程)
- `schemas/` extraction config、building spec、variants manifest 的版本化 JSON Schema
- `tests/` 契约/交付测试 + 合成 DXF 全链路回归
- `references/` 当前运行规范;历史复盘移到 `docs/history/`,不再作为 Agent 运行上下文
- `assets/` Web 模板与离线 viewer 内联库
`work/`、`outputs/`、源 CAD 均不入库(见 `.gitignore`),由脚本从源数据再生。
@@ -71,7 +78,10 @@ register_site_outlines.py / massing_from_outline.py / assemble_campus.py
## 验证纪律
```bash
python3 tests/test_extraction_pipeline.py # 必须全绿
pytest tests/test_contracts.py tests/test_delivery.py
python3 tests/test_extraction_pipeline.py
ruff format --check scripts tests && ruff check scripts tests
npm run check:js
```
已在四套真实图纸上端到端验证:贝昂科技厂区(基线)、黄桥文体中心、13号地块(双塔+酒店厂区)、27号地块(7栋混合厂区)。质量对比表见 `references/generalization_test_log.md`。
已在四套真实图纸上端到端验证:贝昂科技厂区(基线)、黄桥文体中心、13号地块(双塔+酒店厂区)、27号地块(7栋混合厂区)。历史质量对比见 `docs/history/generalization_test_log.md`。

296
SKILL.md
View File

@@ -1,212 +1,152 @@
---
name: cad-building-showcase
description: Agent-led workflow for generating and auditing architectural 3D web showcase models from CAD drawing folders. Use when Codex is given DWG/DXF/PDF CAD plans, XREF folders, floor plans, building drawings, or asks like "用 CAD 图纸生成 3D 建筑演示模型", "把所有 CAD 图纸做成 Web 展示模型", "DWG/DXF 转 Blender/GLB", "建筑平面图生成完整建筑展示模型", or asks whether CAD-derived output can replace BIM. This skill is specifically for cases where an Agent must inspect CAD reports, decide layer/floor/block rules, run scripts, audit coverage, and iterate; not for blind one-shot script conversion.
description: Agent-led workflow for auditing DWG/DXF architectural drawings and generating verified building_spec.json, Blender or lightweight GLB models, offline/served Three.js showcases, multi-building campus assemblies, and optional IFC proofs. Use for CAD floor-plan folders, XREF-heavy Chinese construction drawings, TArch/天正 exports, multi-frame sheets, DWG/DXF-to-3D/Web requests, campus placement, 3DSOLID/MESH extraction, or questions about whether CAD-derived output can replace BIM. Do not use for PDF-only plans unless the user first supplies or authorizes a separate PDF-to-vector/CAD conversion workflow.
---
# CAD Building Showcase
## Outcome
Create a usable architectural demonstration model through Agent judgment plus deterministic scripts. Do not treat this as blind CAD conversion. The target deliverables are:
Produce an evidence-backed architectural showcase, not a blind CAD conversion. Deliver as applicable:
- CAD read report: converted/sanitized DXF inventory, layer counts, entity counts, drawing bounds, likely units.
- Agent extraction config: explicit layer mapping, floor split/alignment, unit scale, curve and filtering rules.
- `building_spec.json`: normalized floor-by-floor geometry in meters.
- Extraction audit: coverage, unclassified layers, high-risk entity types, block/INSERT signals, and Agent questions.
- 2D overlay review: SVG overlays comparing source CAD vectors with extracted model geometry.
- Blender scene: `.blend`, `.glb`, and preview `.png`.
- Web showcase: static Three.js viewer with floor/component toggles, floor explode, section height, camera presets, screenshot, and GLB download.
- Lightweight variants: produce at least overview, standard, and detail GLB variants when the user asks for Web/digital-twin presentation. The Web viewer should default to the standard variant and expose download links for all variants.
- Notes file: source drawings, assumptions, extraction limits, and verification results.
- sanitized DXF inventory and source gate report;
- versioned extraction config and `building_spec.json`;
- extraction audit and per-floor SVG overlays;
- overview/standard/detail GLBs plus metadata;
- Blender scene/preview when Blender is selected;
- served Web viewer and/or offline single-file viewer;
- `evidence_manifest.json` with machine-readable final checks;
- notes stating assumptions, missing geometry, source limitations, and confidence level.
If the user asks to replace BIM, branch explicitly to IFC/BIM validation. Treat Web showcase and BIM replacement as separate products.
Treat Web showcase, massing, 3D-solid extraction, and BIM/IFC as separate products.
## Reference Router
Read only the branches needed for the current task:
- Standard extraction/config/schema: `references/pipeline.md` and `references/building_spec_schema.md`.
- Input conversion, dependencies, PDF boundary, 3DSOLID/MESH: `references/input_formats.md`.
- Multi-frame sheets and TArch/天正 mappings: `references/multi_frame_tarch.md`.
- Multi-building sites, placement, context, gaps: `references/campus_workflow.md`.
- GLB variants, Web/offline delivery, browser and final QA: `references/web_delivery.md`.
- IFC/BIM claims and validation: `references/bim_branch.md`.
- Acceptance judgment: `references/agent_review.md`.
- Calibration only, never constants: `references/a208_case_notes.md` and `references/optimization_notes.md`.
## Agent Decision Loop
The Agent owns interpretation. Scripts are tools for evidence and repeatable execution.
1. Inspect before modeling.
- Run `python3 scripts/cad_showcase.py inspect --input <cad> --work <work> --output <report>`.
- Require source gate `all_sources_converted_and_readable=PASS`.
- Read warnings, units, bounds, entity types, top layers, XREF/block signals, and plan-title counts.
1. Inspect first, do not model blind.
- Run `cad_dxf_report.py`.
- Read top layers, entity types, bounding boxes, units, and high-risk entities.
- Form hypotheses: which drawings are floor plans, which layers are walls/glazing/roof/columns/beams/railings/doors/detail lines/grid, whether blocks or hatches matter, and how floors align.
2. Select the branch.
- Use standard line extraction for architectural DWG/DXF plans.
- Use `detect_sheet_frames.py` for multi-frame sheets.
- Model each building separately before campus assembly.
- Use `--converter oda` plus `extract_3d_solids.py` for known 3DSOLID/ACIS drawings.
- Stop and request DWG/DXF/vector conversion for PDF-only input.
2. Write an explicit extraction config.
- Decide layer mappings, floor splits, offsets, origin strategy, curve chord length, and category-specific line-length filters.
- Use `references/pipeline.md`, `references/building_spec_schema.md`, and `references/a208_case_notes.md` as calibration.
3. Write and validate an explicit config.
- Set layer mappings, scale, floor clips/offsets/order, heights, origin, block rules, footprints, caps, and evidence values.
- Run `python3 scripts/showcase_schema.py config <config.json> --dxf-dir <sanitized-dxf>`.
- Treat unknown keys, missing drawings, duplicate floor keys, incomplete `floor_order`, and invalid values as hard failures.
3. Extract, audit, and review overlays before accepting.
- Run `derive_showcase_spec.py`.
- Run `audit_showcase_extraction.py`.
- Run `draw_coverage_overlay.py`.
- Inspect unclassified layers, high-risk `INSERT`/`HATCH` counts, and overlay SVGs. If major geometry is red/unclassified or missing, adjust config or parsing strategy and repeat.
4. Extract, audit, and review overlays.
- Prefer the resumable entry point after the config is approved:
`python3 scripts/cad_showcase.py run --dxf-dir <dxf> --config <config> --source-report <cad_read_report.json> --out-dir <out> --name <name> --frames <frames.json> --backend trimesh`.
- Use `--backend blender` when `.blend` and Blender preview are required.
- Never pass `--no-strict-gates` to proceed toward delivery.
- Open the SVG overlays. Iterate if red/unclassified geometry forms walls, glazing, columns, beams, grids, stairs, slabs, roofs, or whole building wings.
4. Generate and verify the 3D/Web model only after the extraction passes review.
- Run Blender/GLB generation and Web template assembly.
- Verify preview image, Web controls, console logs, and mobile layout.
5. Verify actual deliverables.
- Require `verify_showcase.py --strict` and `verify_delivery.py` to pass.
- Inspect at least one iso/front/side/plan render personally.
- For served Web output, run `web_smoke_test.mjs` at desktop and 390px widths and feed its report to `verify_delivery.py --browser-report`.
- Confirm idle `window.__renders` does not grow, GLBs decode, variants exist, controls work, and console errors are zero.
5. Report confidence and limits.
- State whether the output is Web showcase, LOD-like massing, IFC/BIM proof, or not sufficient.
- Include what was not modeled and what evidence supports that judgment.
6. Report confidence and limits.
- Label the result `Web showcase`, `Massing/LOD100-150`, `3D-solid partial extraction`, or `IFC/BIM proof`.
- State what was not modeled and cite report/gate/image evidence.
## One-Shot Definition of Done
## Hard Definition of Done
The pipeline is designed so a first pass either succeeds or STOPS at a loud gate. Do not hand over a model unless every line below has evidence (a report line, a gate status, or an image):
Do not hand over a model unless every applicable item has evidence:
1. Read report clean: every `Warnings` entry resolved. `multi_frame_sheet` -> ran `detect_sheet_frames.py` and used its clip/offset config; `cached_xref_content` -> the XREF content is CACHED as in-file block definitions, expand blocks (≈bind) instead of asking for a re-export; `likely_xref_shell` (no cached content) -> user re-exported with XREFs bound.
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. `floors_aligned` also cross-checks every floor's wall profile against the group's reference floor (a strong correlation peak at a non-zero shift = "self-consistent but misplaced", the 13号 F3 错槽 pattern that envelope centers cannot see). Never pass `--no-strict-gates` to proceed.
Leak gates (SKIP unless armed — arm them on every new project, they are the cross-evidence net): `--frames <detect out-config>` arms `frame_ledger` (every detected plan frame must be used by the config or listed in `discarded_frames` with a reason — silently ignored frames are where wings vanish); config `declared_areas_m2` arms `area_declared` (model footprint area vs 经济技术指标表/标注, ±15% default — 1#B lost half the building and only the site plan showed it); config `expected_storeys_above_ground` arms `storey_count` (vs 总图 `22F` labels / elevation ladder).
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; 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.
1. `cad_read_report.json.gate.status == PASS`; no unresolved conversion/read failure.
2. Config and spec pass their versioned JSON Schemas.
3. Every configured source exists, every floor key is unique, every floor is nonempty, and `floor_order` has no gaps/ghosts.
4. Multi-frame projects pass `frame_ledger`; every detected plan frame is used or appears in `discarded_frames` with a reason.
5. Audit exits 0 and all required gates pass: source presence, floor uniqueness/nonempty, floor alignment/cross-floor datum, glazing capture, annotation exclusion, declared areas, and storey count when armed.
6. Derive emits no `WARNING topless_group`; GLB build emits no `WARNING mesh_from_polygons`.
7. Campus output has proven transforms, no unexplained overlap, numeric neighbour gaps, boundary containment, and a top-view placement image.
8. `verify_delivery.py` writes `evidence_manifest.json` with overall `PASS`; a human has looked at the render.
9. Served Web delivery includes a passing browser smoke report when the environment permits browser testing.
10. After any script/schema/template change, run:
- `pytest tests/test_contracts.py tests/test_delivery.py`
- `python3 tests/test_extraction_pipeline.py`
- `ruff format --check scripts tests && ruff check scripts tests`
- `npm run check:js`
## Command Workflow
## Core Commands
1. Prepare the CAD folder.
- Work from a folder under the current workspace when possible. On macOS, avoid direct reads from `Downloads` if TCC blocks access; ask the user to move/copy the CAD folder into the workspace.
- Preserve the original CAD folder. Put converted/intermediate files in `work/`.
- If DWG files are present, prefer `libredwg` `dwg2dxf` for batch conversion. Use ODA/QCAD/FreeCAD only as fallback — EXCEPT for drawings containing `3DSOLID`/ACIS entities: libredwg silently drops ACIS data (R2013+ stores it in the ACDSDATA section), so 3D-solid DWGs must go through ODA File Converter (`/Applications/ODAFileConverter.app/Contents/MacOS/ODAFileConverter <abs_in_dir> <abs_out_dir> ACAD2004 DXF 0 1 "*.dwg"` — macOS path shown; discovery order everywhere is env `ODA_CONVERTER` > `ODAFileConverter` on PATH > that macOS default). ODA reports bad arguments via GUI dialogs, not stderr: both directories must exist as absolute paths, and a silent exit-0 with no output means a dialog is blocking on screen.
- No native converter available (Linux sandbox, no ODA/libredwg)? Use the WASM fallback: `npm install @mlightcad/libredwg-web`, then `node scripts/dwg_dump_json.mjs in.dwg dump.json --module-dir <node_modules>` and `python3 scripts/dwgjson_to_dxf.py --json dump.json --out work/dxf_raw/file.dxf`. This carries LINE/PLINE/ARC/CIRCLE/ELLIPSE/SPLINE/TEXT/INSERT + full block definitions (enough for the extraction pipeline), but drops HATCH/DIMENSION/ATTRIB — do not use it to judge hatch-only column fills or attribute-held axis numbers.
- Multi-discipline sets (建筑/结构/给排水/电气/暖通 subfolders): model from 建筑 (architecture) only by default; pull 结构 later just for columns/beams if the showcase needs structure. Never feed all disciplines into one extraction pass.
Check prerequisites:
3D-solid DWG branch: if the read report shows `3DSOLID`/`MESH` as the main types (typically also flagged `near_empty` for plan purposes), the floor-plan extrusion pipeline does not apply. Convert via ODA, then tessellate with `ezdxf.acis` (`load_dxf` → `mesh_from_body`, which returns a list of meshes). Only polyhedral/flat ACIS faces tessellate; count curved records (`cone-surface`, `spline-surface`, ...) in the SAT text and report them as not extractable. Export captured meshes + `MESH` entities to OBJ/GLB (OBJ is Z-up: import into Blender with `up_axis='Z'`). If curved skin dominates, tell the user to export OBJ/STL/STEP from a full CAD kernel (AutoCAD/BricsCAD) instead of promising a complete model.
```bash
python3 scripts/cad_showcase.py doctor
```
2. Generate a CAD read report.
- Run `scripts/cad_dxf_report.py` from this skill.
- Install missing parser dependencies into the current project work area, not globally:
`python3 -m pip install --target work/vendor ezdxf`
- Inspect the Markdown/JSON report before modeling. Confirm drawings, units, bounding boxes, and the top layers for walls/glazing/roof/columns/beams/railings/doors/detail lines/floor lines/grid.
- `unknown_layer_dialect` warning = a plan file whose layers match no known wall naming (*WALL*/*墙*): a design-institute convention this pipeline has never seen. Build the layer mapping consciously from the top-layers list before modeling — patterns age, and a wrong mapping extracts nothing silently.
- Resolve the report's `Warnings` section before modeling. `cached_xref_content` means the "empty" sheet's INSERT stubs reference block definitions cached INSIDE the file (AutoCAD keeps unbound-XREF content as blocks; both libredwg and ODA export the cache) — expand blocks in detect/derive (`expand_blocks` ≈ bind), no re-export needed. Only `likely_xref_shell` / `near_empty` WITHOUT cached content means geometry truly lives outside: ask the user to bind/insert the XREFs in CAD and re-export that DXF (do not model the shell and report the floor as done).
Inspect/convert sources:
3. Build the extraction config and `building_spec.json`.
- Use `references/pipeline.md` and `references/building_spec_schema.md`.
- Map CAD layers to normalized categories: `walls`, `glazing`, `roof`, `columns`, `beams`, `railings`, `doors`, `detail_lines`, `floor_lines`, and `grid`.
- Identify one drawing per floor or split sheets that contain multiple floor plans side by side.
- 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), prefers title-block frame INSERTs (`A0_V1`/`A0+0.5_V1`/`*图框*`… world bboxes) as clip windows — pitch-sized windows halve elongated sheets (13号 加长A0 held two towers in one frame) — refines each clip to the wall bbox inside it, 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). Multi-floor titles (四、六、八层平面图 / 十一至十四层平面图) are expanded into one config entry per storey sharing the frame's clip/offset — hand-copying N entries is where floors silently vanished (13号 b2). 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 with a PER-FRAME `ladder:` of DIM_ELEV values plus a `suggested storey table` line (uniform-step chain) — the suggestion is evidence, not a decision: fill `z`/`height` yourself after checking the 剖面 ladder (stair sections beat at half-storey rhythm; podium/machine floors differ). 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. 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`.
```bash
python3 scripts/cad_showcase.py inspect \
--input <cad-folder> --work work/<project> --output outputs/<project>/cad_read_report \
--converter auto
```
4. Audit extraction before 3D generation.
- Run `scripts/audit_showcase_extraction.py`.
- Run `scripts/draw_coverage_overlay.py`.
- The audit enforces hard gates and exits with code 3 on failure (e.g. glazing evidence exists in blocks but the spec has 0 glazing segments). A failed gate means the extraction is known-incomplete: fix the config or source export and re-run; never bypass with `--no-strict-gates` just to proceed.
- The headline coverage ratio counts modelspace linework only. Read the `Block-Locked Geometry By Layer` section too — geometry inside INSERT blocks is reported separately and a 96% coverage can coexist with an entirely missing curtain wall.
- CLIP-SCOPE CAVEAT: audit accounting is file-global while clip-based extraction is frame-scoped. On multi-frame sheets a healthy extraction can still show ~40% coverage and a block-locked WARN, because elevations/sections/details inflate the denominator. Judge such runs by the per-floor overlays and segment counts, not the headline ratio.
- Review the Markdown audit and SVG overlays. Iterate config if important geometry remains unclassified or hidden in high-risk entity types.
Run from an Agent-approved extraction config:
5. Generate Blender/GLB.
- Use Blender CLI (macOS app-bundle path shown; on Linux/other, `blender` from PATH works — `build_showcase_variants.py` discovers it via env `BLENDER` > PATH > the macOS default):
`/Applications/Blender.app/Contents/MacOS/Blender -b --python <skill>/scripts/build_blender_showcase.py -- --spec work/building_spec.json --out-dir outputs/<project> --name <project>`
- Use Blender MCP only after the CLI artifact exists, for inspection, scene tuning, or interactive refinement.
```bash
python3 scripts/cad_showcase.py run \
--dxf-dir work/<project>/dxf_sanitized \
--config work/<project>/extract_config.json \
--source-report outputs/<project>/cad_read_report/cad_read_report.json \
--frames work/<project>/frames_config.json \
--out-dir outputs/<project> --name <project> \
--backend trimesh --web --offline --resume
```
6. Generate the Web showcase.
- The template renders ON DEMAND (static scene + 60fps loop = pegged GPU/fans for identical frames): anything that changes the view calls invalidate(); shadows are baked per change (`shadowMap.autoUpdate=false`), and `window.__renders` is the diagnostic frame counter — idle MUST read 0 growth. The offline viewer follows the same contract. Template features: building-grouped floor toggles (metadata.buildings or floor-key prefix fallback), per-(floor,category) geometry merging (draw-call reduction), progressive overview->standard loading (single-GLB deployments skip the swap), in-page variant switching, auto tour, camera bookmarks (list + restore + removable), share-link (full state in the URL hash), toast notices.
- For digital-twin-style Web delivery, keep generated slabs visible by default and create three filtered specs/models:
- `overview`: walls, glazing, roof, columns, beams, and generated slabs.
- `standard`: overview plus railings and doors; use this as the default Web model.
- `detail`: full extraction, including grid, floor lines, and detail lines for audit/review.
- Run `scripts/build_showcase_variants.py --build` to write the filtered specs, call Blender for all three GLBs, and create `variants_manifest.json`.
- Run `scripts/write_web_showcase.py --variants-manifest ...` to copy the template, use the standard model as `model.glb`, copy all variant GLBs, and add `model_variants` to `model_metadata.json`.
- Use the single-GLB `write_web_showcase.py --glb ... --metadata ...` path only when the user explicitly wants a quick one-model preview.
- Share-by-file delivery (no server, no network — mainland-China CDNs hang): `scripts/write_offline_viewer.py --spec ... --glb ... --out viewer.html` emits a fully self-contained HTML (three r147 UMD + pako inlined from `assets/offline-viewer-libs/`, GLB gzip-embedded, ACES + IBL + shadows + physical glass + instanced trees + grouped toggles + click-to-inspect, loading failures shown on screen). Smoke-test headlessly in node: decode the embedded payload and GLTFLoader().parse it.
- Install local web deps in that output folder:
`npm install --prefix outputs/<project>/web three@0.181.2 lucide@0.468.0`
- Start a local server from the web output folder and give the user the URL.
For a known ACIS/3DSOLID source, force ODA during inspection; do not let an apparently nonempty libredwg conversion hide dropped solids:
7. Verify before final delivery.
- Open the preview PNG or render another screenshot; check that geometry is nonblank and framed.
- Open the Web viewer in the Browser plugin on desktop and mobile widths.
- Check console logs are clean, controls work, mobile panels do not overlap, and the GLB loads.
- Report model precision honestly: showcase model, LOD-like massing/structural visualization, or IFC/BIM proof.
```bash
python3 scripts/cad_showcase.py inspect ... --converter oda
python3 scripts/extract_3d_solids.py \
--dxf work/<project>/dxf_sanitized/model.dxf \
--out-glb outputs/<project>/solids.glb \
--report outputs/<project>/solids_report.json
```
8. Raise presentation quality when the user wants "digital-twin" polish.
- Follow `references/web_presentation_notes.md` in tier order: official template + Draco + ACES/RoomEnvironment lighting + physical glass first (cheap, big win); then geometry upgrades (merged wall solids, mullion grids, road/green surfaces, instanced trees); then interaction (click-to-inspect from GLB extras, camera tours, progressive per-building loading).
- Polish never excuses a wrong model, and enhancements derived from plan linework must not be presented as BIM-verified elements.
## Modeling and Honesty Rules
## Multi-Building Campuses (厂区/园区 sets)
- Prefer stable layered geometry over overfitted CAD noise.
- Preserve floor/category naming as `<floor_key>__<category>` and glTF Y-up.
- Keep source originals unchanged; write intermediates under `work/` and deliveries under `outputs/`.
- Use CAD-derived footprint polygons for slabs/roofs when evidence is sufficient; do not present generated caps, hulls, mullions, wall unions, or massings as BIM-verified geometry.
- Keep slabs visible for presentation, grids/details toggleable, and in-scene labels off by default.
- Never claim rooms, openings, quantities, materials, MEP coordination, code compliance, or production BIM unless the IFC branch explicitly generates and validates them.
- A missing building stays missing or becomes an explicitly labeled outline massing; never invent detail to make a scene look complete.
A folder like `建筑-1#厂房 / 2#厂房 / 3#辅房 / 总图` is a CAMPUS: several buildings plus a site plan — NOT floors of one building. Never map "one DWG = one floor" here.
## Bundled Entry Points
- Model each building separately: one detect-frames pass, one extraction config, one `building_spec.json`/GLB per building DWG. Small structures (机械停车坑/水池) are usually one or two frames.
- Assemble with `scripts/assemble_campus.py`: record each building's transform (model anchor -> surveying anchor + campus rotation) in `site_manifest.json` and let the script do the merge — it also runs the mandatory neighbour-gap check automatically. Buildings on one campus can face different ways (27号: 4#楼 sits ~27° off its siblings): a per-building `rotation_deg` in the manifest overrides the global one.
- Units differ by sheet type: building plans are almost always millimeters (`scale 0.001`), while 总图 site plans are often METERS at real surveying coordinates (huge x/y like 349xxx/663xxx, texts ~2-4 units tall). The extraction config has a single global `scale`, so never mix a meters site plan and mm building plans in one spec.
- Place buildings with a site manifest: from 总图/定位图 (prefer a "带轴号(可点坐标)" version if present) measure each building's anchor point and rotation, then assemble per-building GLBs in the viewer/scene with those transforms. Record the manifest (building -> position/rotation/source) in the notes file.
- Proven placement recipe (贝昂 case): find the building's envelope rectangle in the site drawing (layer 面积核算/建筑轮廓线) — its edge lengths must equal the model's wall-envelope bbox 1:1 (here 90.2 x 42.2 m exactly), edge angle gives rotation (7.57°), the corner matching the model's (min x, min y) gives translation. Resolve the 180° flip by densest-feature voting (e.g. machine-room walls inside a known sub-rect). Then EITHER merge at spec level (transform all segments/footprints/caps into site-local meters and append a SITE context floor) and export one GLB, OR keep per-building GLBs plus transforms in the manifest. Pick a site-local origin (用地红线 min corner), never raw surveying coordinates — float32 breaks at 349 km.
- Anchor placement on WALL evidence, never roof/eave envelopes: 屋面 outlines include canopies and asymmetric overhangs — concentric placement against one put 2# 0.45 m off (26 cm INSIDE its neighbour). Best anchors, in order: corner coordinate callouts (X=/Y= texts), wall lines, envelope rects whose edges equal the wall bbox exactly.
- Site plans without per-building envelope rects (27号 pattern): building outlines may hide on odd layers (EVTR!) — match each closed polyline to its nearest 楼栋 label, then register the model footprint onto the outline with `scripts/register_site_outlines.py` (point-to-edge ICP: brute-force angle + translation refine, trim worst 10%; emits a manifest-ready placement + residual). Constrain `--angle-window` when the outline is visibly axis-aligned — balcony bumps love a tilted false minimum (2# found a 10.75° pit). A building with NO drawn outline can still be anchored from its DIM_COOR corner callouts alone (pair X=/Y= texts, drop points that fall on the garage outline / fire-pad rects), and registering the UNION of several floors' footprints (`--floors F1 F2 F4`) beats one floor when upper wings overhang. Judge residuals: 0.06 m = outline equals model; 0.5-1 m normal with balconies; >2 m = wrong outline/floors, check the overlay. Surveying convention on both 13号/27号 site plans: drawing x = 测绘Y (east), drawing y = 测绘X (north), meters.
- Buildings named on the site plan but with NO delivered drawings (27号 3#/4#): `scripts/massing_from_outline.py --outline pts.json --storeys 22 --height 3.0` builds an honest massing spec (outline-edge walls, footprint slabs, top cap, description marked 总图轮廓体量) and prints manifest-ready anchors — never silently fake a detailed model. Storey counts come from the `22F` labels next to each outline; heights from the sibling tower's ladder.
- Adjacent-building gap sanity check is mandatory: compute the wall-to-wall gap in the shared-edge frame. ~0.15-0.30 m means 贴建 with an expansion joint (变形缝) — corroborate with the neighbour's roof labeled on this building's roof plan and matching floor elevations. Several metres means fire separation. A NEGATIVE gap (overlap) is always a placement bug. Cross-check the chosen position against the boundary: if a hypothesis (e.g. a 10 m fire gap) pushes the building through 用地红线, the hypothesis is wrong.
- Site context is a deliverable, not decoration — a campus scene with only a few boundary lines reads as broken. Run `scripts/site_context_from_dump.py` on the 总图/定位图 dumps: it emits ready-to-merge floors for ground (用地红线 footprint slab), roads + parking stalls (lines, arcs, block-expanded 车位 INSERTs), fence (围墙 as 1.8 m railings), street trees (行道树 INSERT points as green posts, custom `trees` category), and low-confidence massings for context structures drawn only in the site plan (连廊/门卫/消控室, named by nearest label). It takes one plan-copy window (site sheets usually hold several scheme copies), a per-source unit scale (总图 in meters, 定位图 copies in mm), and an exclude-quad so the real building model replaces its own site outline. Buildings that have their own drawing sets get real models placed by the manifest — never fake them as massings.
## TArch / 天正 t3 Export Preset (most Chinese architecture DWGs)
`_t3` exports use TArch layer names that the AIA-style defaults miss. Calibrated mapping:
- `walls: ["WALL"]`, `columns: ["COLUMN", "*COL*"]`, `glazing: ["CURTWALL", ...]`, `roof: ["屋面", "*屋顶*"]`, `detail_lines: ["STAIR", "EVTR", "平面", "开口"]`, `grid: ["DOTE", "AXIS"]` — plan grids are on `DOTE` (dash-dot); `AXIS` often holds only detail-sheet stubs.
- Doors and windows BOTH live on layer `WINDOW` as INSERTs, and the block geometry sits on layer `0` (inherits by insert), so layer-based block probing keeps NOTHING. Use explicit expansion plus block-name classification:
`"expand_blocks": ["$TCHSYS$*", "$DorLib2D$*"]`, `"block_name_categories": {"glazing": ["$TCHSYS$WIN2D*"], "doors": ["$DorLib2D$*"]}`.
- Exclude annotation/frame layers inside clips: `["*-IDEN", "*图签*", "PUB_*", "DIM_*", "*TEXT*", "初审修改", "面积核算", "格子线", "辅注", "SEC-*", "立面", "剖面", "雨水管", "家具"]` (revision clouds live on `初审修改`-style layers).
- TArch column fills may be HATCH-based; if arch plans yield suspiciously few `columns`, take columns/beams from the 结构 set instead of inventing them.
## Modeling Rules
- Prefer stable, layered massing over overfitted geometry. CAD floor plans often contain annotations, dimensions, hatches, XREF artifacts, and duplicated lines.
- Use linework from walls/glazing/columns/beams/railings/doors as visual extrusions. Generate explicit `roof`/roof-cover geometry when roof drawings are sparse or when top-floor columns need an overhead cap. Keep generic detail layers as low plan detail unless the Agent has evidence they are vertical building elements. Do not claim parametric wall joins, rooms, MEP, quantities, or code-compliant BIM unless IFC semantics and validation are generated.
- Keep 3D floor labels off by default. The Web UI already names floors; generated in-scene text usually clutters the building view.
- Prefer CAD-derived footprint polygon `slab` meshes over rectangular `bounds` slabs. Generate the footprint from mapped wall/glazing/floor-line/railing/column vectors, simplify it, and cap it to a small number of high-area polygons. For digital-twin-style presentation, use a looser concave hull so floor plates read as continuous platforms instead of leaving avoidable visual voids. Treat this as a visual floor/roof plate, not a BIM-grade slab with validated openings and joins.
- For presentation models, make slab edges visible in side views: use a display thickness around 0.35-0.40 m, render slabs double-sided in the Web viewer, and avoid very low slab opacity. Otherwise transparent glazing can make floor plates look missing even when the footprint is present.
- Keep `slab` available as a toggle. Default it on for presentation/digital-twin models; default it off only for audit views where slabs obscure linework review.
- For generated roof caps, do not blindly union lower floor footprints into the roof geometry. Use the roof floor's own `footprint_from` source unless there is clear CAD evidence that a canopy/overhang exists.
- For columns that visually stand without anything above, do not rely on broad floor bounds or broad footprint alone to infer support. Require an adjacent upper floor/roof plate and nearby upper structural geometry; shorten unsupported display columns unless the Agent has evidence they are meant to be full-height freestanding elements.
- Keep floors separable in object names and metadata. The Web viewer expects objects named `<floor_key>__<category>`.
- Use neutral, readable colors and transparent slabs. Avoid a single-hue scene.
- Document every assumption that affects geometry: layer mapping, floor heights, sheet splits, coordinate offsets, unit scale, and ignored entity types.
- Curtain walls/glazing are frequently inside INSERT blocks (e.g. `系统嵌板/幕墙` blocks resolving to layer `A-GLAZ-CURT`). `derive_showcase_spec.py` handles this two ways: block-name expansion (`GLAZING_BLOCK_PATTERNS`, fragile — DWG→DXF conversion can mangle CJK names like `系统嵌板`→`系统嵌`) and layer-based probing (`classify_block_contents`, default on): every INSERT — including wrapper/sheet blocks — is expanded up to `expand_blocks_max_depth` and sub-entities are kept only when their own layer classifies into `block_content_categories` (default glazing/railings/doors). Check the audit's glazing gate and block-locked section before accepting.
- Identification/annotation layers (`*-IDEN`: door tags, axis numbers, area labels) are excluded from classification by default (`exclude_layers`), so `A-DOOR-IDEN` no longer counts as door geometry. If a category only ever matched an `*-IDEN` layer, the drawing has no real geometry for it — say so instead of modeling tags.
- CAD draws curtain walls as sparse panel/mullion segments; `derive_showcase_spec.py` merges collinear glazing into continuous bands (`merge_glazing`, `glazing_gap_tol`). Only bridge gaps that contain no opaque wall on the same line.
- Prefer capping column tops over shortening them. `derive_showcase_spec.py` stores `floor.caps` (setback overhang rings for above-ground floors, full ground/podium deck for the top basement level) which both backends extrude as slab caps; this avoids stray topless columns and odd short stubs.
- Coordinate convention: GLB is glTF-standard **Y-up**; the Web viewer sets `camera.up=(0,1,0)`, sections/explode along Y, and registers a `DRACOLoader`. Keep GLB up-axis and viewer up-axis in sync, otherwise the building renders lying on its side.
- Lightweighting: export Draco-compressed GLB (Blender built-in, or `tools/compress.mjs`); the viewer must register `DRACOLoader` (it does). Sanitize degenerate faces / NaN normals before export so strict importers (Blender, online viewers) accept the file.
## Bundled Resources
- `scripts/cad_dxf_report.py`: batch DWG/DXF conversion, DXF sanitizing, and read report generation, including XREF-shell / near-empty sheet warnings.
- `scripts/detect_sheet_frames.py`: multi-frame sheet splitter — finds plan-title frames (column AND row layouts), refines per-floor clips, grid-correlates per-floor offsets, and emits a config skeleton + report, including suggested storey elevations harvested from 剖面/立面 标高 texts.
- `scripts/assemble_campus.py`: manifest-driven campus assembly — transforms per-building specs into site-local meters (prefixing floor keys, re-keying roof_specs), merges site-context floors (dropping massings covered by real models), and enforces the neighbour-gap check (overlap = exit 3; 0.1-0.3 m flagged as expansion-joint candidates).
- `scripts/dwg_dump_json.mjs` + `scripts/dwgjson_to_dxf.py`: WASM libredwg fallback (npm `@mlightcad/libredwg-web`) for DWG->DXF when neither native libredwg nor ODA exists; preserves block definitions and INSERT transforms.
- `scripts/site_context_from_dump.py`: campus site-context floors (ground/roads/parking/fence/trees/context massings) from 总图/定位图 dumps, with per-source unit scale, plan-copy windowing, and an exclude-quad for the really-modeled building.
- `scripts/derive_showcase_spec.py`: configurable extraction from DXF line/polyline layers into a normalized building spec, with block-content probing for glazing/railings/doors locked inside INSERTs. Single-pass over expanded entities (floors share one INSERT expansion; block leaf-layer memoization skips irrelevant blocks), so multi-frame configs with many floors stay fast.
- `scripts/audit_showcase_extraction.py`: coverage and risk audit with hard gates (exit 3 on failure) and block-locked geometry accounting (definition-walk with per-block-name caching, no per-INSERT explode), for Agent review before 3D generation.
- `scripts/draw_coverage_overlay.py`: SVG overlays comparing source CAD vectors to extracted model geometry.
- `scripts/verify_showcase.py`: Blender-free QA from `building_spec.json` (+ optional GLBs): per-floor segment/cap/glazing-continuity report, GLB size-budget check, and orthographic front/side/plan previews.
- `scripts/build_blender_showcase.py`: Blender CLI renderer/exporter from `building_spec.json` to `.blend`, `.glb`, `.png`, and metadata. GLB is Draco-compressed by default.
- `scripts/spec_to_glb.py`: Blender-free `building_spec.json` -> GLB exporter (trimesh). Use when Blender is unavailable; produces the same `<floor>__<category>` naming, Y-up, flat normals, glazing merge, and setback/basement caps.
- `tools/compress.mjs`: gltf-transform Draco compressor (`node tools/compress.mjs in.glb out.glb`); alternative to Blender's built-in Draco, usually smaller.
- `scripts/build_showcase_variants.py`: creates overview/standard/detail filtered specs, optionally builds their GLBs, and writes a manifest for Web delivery.
- `scripts/write_web_showcase.py`: copies the static Web viewer template and model assets into an output folder.
- `scripts/build_ifc_poc.py`: optional IFC4 semantic proof-of-concept generator from `building_spec.json`.
- `scripts/extract_ifc_meshes.py`: extracts IFC geometry to JSON for render verification.
- `scripts/render_ifc_meshes_blender.py`: renders IFC geometry in Blender and exports `.blend`, `.glb`, and `.png`.
- `references/pipeline.md`: detailed CAD-to-model procedure and quality gates.
- `references/building_spec_schema.md`: expected JSON contract between CAD extraction, Blender, and Web viewer.
- `references/agent_review.md`: acceptance/iteration/BIM-claim checklist for Agent judgment.
- `references/a208_case_notes.md`: proven details from the A208 DWG/DXF/Blender/Web/IFC run.
- `references/optimization_notes.md`: lightweighting + completeness lessons (Draco/DRACOLoader, glTF Y-up convention, block-locked glazing, glazing continuity, column-top caps, NaN sanitation, verification).
- `references/web_presentation_notes.md`: tiered visual/interaction/performance upgrade playbook for the Web showcase (template + Draco + ACES/environment lighting + physical glass; merged wall solids, mullions, site surfaces, instanced trees; click-to-inspect, tours, progressive campus loading) with honesty rules for presentation enhancements.
- `assets/web-showcase-template/`: static Three.js viewer template (Y-up, registers DRACOLoader, cache-busting `?v=` build token; RoomEnvironment IBL, model-sized shadow frustum + ground shadow catcher, physical-glass glazing, click-to-inspect).
- `scripts/write_offline_viewer.py` + `assets/offline-viewer-libs/`: fully-offline single-file HTML viewer generator (vendored three r147 UMD + addons + pako; gzip-embedded GLB) for share-by-file delivery where CDNs/servers are unavailable.
- `tests/test_extraction_pipeline.py`: synthetic-DXF regression test for block-locked glazing capture, `*-IDEN` exclusion, audit gates, and XREF-shell warnings. Run it after changing extraction/audit/report scripts.
## BIM Branch
When the user asks whether the model can replace BIM:
- Say that the Web showcase model cannot replace BIM by itself.
- Create IFC only if the task explicitly needs BIM-like semantics.
- Use `scripts/build_ifc_poc.py` with IfcOpenShell to generate and validate IFC entity counts, schema validity, geometry generation, storeys, and property sets.
- Use `scripts/extract_ifc_meshes.py` and `scripts/render_ifc_meshes_blender.py` when the user asks to see the IFC render effect or when Blender cannot import IFC directly.
- State the remaining BIM gaps: wall/slab joins, object classifications, openings, doors/windows, room spaces, quantities, materials, levels, georeferencing, and discipline coordination.
- `scripts/cad_showcase.py`: doctor, source inspection, resumable deterministic pipeline, state ledger.
- `scripts/showcase_schema.py` + `schemas/`: config/spec/manifest validation and shared floor-group contract.
- `scripts/cad_dxf_report.py`: DWG/DXF conversion, sanitizing, inventory, source gate.
- `scripts/detect_sheet_frames.py`: frame detection, grid/wall correlation, title expansion, elevation evidence.
- `scripts/derive_showcase_spec.py`: normalized extraction and canonical caps.
- `scripts/audit_showcase_extraction.py` + `scripts/draw_coverage_overlay.py`: gates and visual coverage evidence.
- `scripts/spec_to_glb.py` / `scripts/build_blender_showcase.py`: Y-up GLB/Blender backends consuming the same spec contract.
- `scripts/build_showcase_variants.py`, `scripts/write_web_showcase.py`, `scripts/write_offline_viewer.py`: delivery assembly.
- `scripts/verify_showcase.py`, `scripts/verify_delivery.py`, `scripts/web_smoke_test.mjs`: strict final QA.
- `scripts/assemble_campus.py`, `scripts/register_site_outlines.py`, `scripts/site_context_from_dump.py`, `scripts/massing_from_outline.py`: campus branch.
- `scripts/extract_3d_solids.py`: flat ACIS/MESH extraction with curved-surface limitation report.
- `scripts/build_ifc_poc.py`, `scripts/extract_ifc_meshes.py`, `scripts/render_ifc_meshes_blender.py`: IFC proof branch.

View File

@@ -1,4 +1,4 @@
> 归档:skill 早期迭代时使用的工作提示词,仅作历史记录;文中路径以当时的仓库布局为准。
> 归档:skill 早期迭代时使用的工作提示词,仅作历史记录;文中路径以当时的仓库布局为准。当前规则以 `SKILL.md` 为准。
# Claude Code 提示词:CAD 展示模型 skill 剩余改进项

View File

@@ -1,5 +1,7 @@
# Skill 泛化测试记录(test3d-7 三项目,2026-07-02 起)
> 历史工程日志;当前规则以 `SKILL.md` 与 `references/` 为准。
目的:验证 cad-building-showcase skill 在不同 CAD 图纸上能否达到与贝昂案例
同等的 3D 模型质量。判定标尺 = One-Shot Definition of Done 七条门禁 +
量化指标 + 固定目检清单,任何门禁失败 → 修 skill(不绕过)→ 重跑。

View File

@@ -1,5 +1,7 @@
# 贝昂科技厂区 CAD:为什么生成错了 + skill 优化记录
> 历史复盘;当前操作规范以 `SKILL.md` 与 `references/` 为准。
日期:2026-07-02 | 源数据:`test3d-6/fs贝昂科技_新建项目cad20250728`
## 一、错误原因诊断

50
package-lock.json generated
View File

@@ -9,6 +9,9 @@
"@gltf-transform/extensions": "^4.4.1",
"@gltf-transform/functions": "^4.4.1",
"draco3dgltf": "^1.5.7"
},
"devDependencies": {
"playwright": "^1.52.0"
}
},
"node_modules/@emnapi/runtime": {
@@ -558,6 +561,21 @@
"integrity": "sha512-LeqcpmoHIyYUi0z70/H3tMkGj8QhqVxq6FJGPjlzR24BNkQ6jyMheMvFKJBI0dzGZrEOUyQEmZ8axM1xRrbRiw==",
"license": "Apache-2.0"
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/iota-array": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
@@ -617,6 +635,38 @@
"sharp": "^0.34.0"
}
},
"node_modules/playwright": {
"version": "1.61.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
"integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.61.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.61.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
"integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/property-graph": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz",

View File

@@ -1,4 +1,11 @@
{
"scripts": {
"check:js": "node --check assets/web-showcase-template/app.js && node --check scripts/dwg_dump_json.mjs && node --check scripts/web_smoke_test.mjs && node --check tools/compress.mjs",
"smoke:web": "node scripts/web_smoke_test.mjs"
},
"devDependencies": {
"playwright": "^1.52.0"
},
"dependencies": {
"@gltf-transform/core": "^4.4.1",
"@gltf-transform/extensions": "^4.4.1",

14
pyproject.toml Normal file
View File

@@ -0,0 +1,14 @@
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
[tool.ruff]
target-version = "py310"
line-length = 120
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"

View File

@@ -1,5 +1,12 @@
# A208 Case Notes
## Contents
1. Source/conversion calibration
2. Layer and alignment signals
3. Showcase/IFC results
4. Presentation calibration
These notes capture the proven workflow from the A208 CAD-to-3D exploration. Use them as calibration, not as hardcoded constants.
## Source Set

29
references/bim_branch.md Normal file
View File

@@ -0,0 +1,29 @@
# BIM and IFC Branch
Use this branch only when the user explicitly requests IFC, BIM-like semantics, or asks whether the showcase can replace BIM.
## Claim Levels
- `Web showcase`: CAD-derived visual model; never BIM replacement.
- `Massing/LOD100-150`: approximate floor/wall/structure visualization.
- `IFC/BIM proof`: IFC entities, storeys, containment, properties, and geometry validation exist.
- `BIM replacement candidate`: require discipline-specific semantics, openings, spaces, quantities, materials, classifications, georeferencing, coordination, and human review. The bundled proof script alone does not reach this level.
## Generate and Validate
Run:
```bash
python3 scripts/build_ifc_poc.py \
--spec outputs/<project>/building_spec.json \
--out-ifc outputs/<project>/<project>_proof.ifc \
--out-report outputs/<project>/<project>_proof_report.json \
--out-notes outputs/<project>/<project>_proof_notes.md \
--vendor-dir work/vendor --validate-geometry
```
Require schema validity, storey/spatial containment, `IfcWall`/`IfcColumn`/`IfcBeam`/`IfcSlab` counts, property sets, and geometry results. Explain every geometry failure.
When Blender cannot import IFC directly, run `extract_ifc_meshes.py` and render with `render_ifc_meshes_blender.py`. Do not imply that a rendered IFC proves production BIM completeness.
Always list remaining gaps: joins, openings, doors/windows, rooms/spaces, quantities, materials, classifications, levels, georeferencing, MEP, and discipline coordination.

View File

@@ -1,19 +1,28 @@
# building_spec.json Schema
Use `building_spec.json` as the contract between CAD extraction, Blender generation, and the Web showcase.
Use `building_spec.json` as the versioned contract between extraction, Blender, trimesh, IFC, and Web delivery. The executable schema is `schemas/building_spec.schema.json`; validate with `python3 scripts/showcase_schema.py spec <file>`.
## Contents
1. Top-level contract
2. Segment/category/footprint semantics
3. Generation config keys
4. Object naming and metadata
5. Precision labels
## Top Level
```json
{
"schema_version": 1,
"project": {
"name": "Project name",
"description": "Short user-facing description"
},
"source": {
"cad_folder": "work/XREF",
"report": "outputs/cad_read_report.json",
"dxf_dir": "work/cad_showcase/dxf_sanitized",
"config": {
"config_version": 1,
"generate_footprints": true,
"use_footprint_slabs": true,
"use_footprint_roofs": true,
@@ -66,7 +75,10 @@ Use `building_spec.json` as the contract between CAD extraction, Blender generat
"detail_lines": [],
"floor_lines": [],
"grid": []
}
},
"caps": [
{"z": 4.2, "polygons": [[[0, 0], [80, 0], [80, 42], [0, 42]]]}
]
}
}
}
@@ -134,6 +146,9 @@ Common `source.config` keys used by `derive_showcase_spec.py` and `build_blender
- `column_support_distance`: XY tolerance for matching upper structural support.
- `column_support_requires_upper_plate`: require an adjacent upper floor/roof footprint before accepting nearby upper structure as support.
- `column_support_allow_plate_only`: if true, an upper plate alone is enough support; leave false when broad footprints would keep too many isolated columns.
- `cap_groups`: ordered `[pattern, group]` pairs used by derive and both exporters; `floor.caps` is the canonical generated-cap geometry.
Unknown config keys, duplicate floor keys, missing source files, incomplete `floor_order`, empty floors, and unsupported schema versions are hard validation failures. The exporters consume canonical `floor.caps`; they do not independently choose another floor grouping.
## Object Naming

View File

@@ -0,0 +1,53 @@
# Campus and Multi-Building Workflow
## Contents
1. Branch selection
2. Placement evidence
3. Site outlines and missing buildings
4. Assembly gates
5. Site context
## Branch Selection
Treat folders such as `1#厂房 / 2#厂房 / 3#辅房 / 总图` as a campus, not floors of one building. Produce one frame-detection run, config, spec, and model per delivered building drawing set. Keep site plans in their own units.
Building plans are usually millimeters; total/site plans may be meters at surveying coordinates. Never combine both in one extraction config. Convert everything to site-local meters before GLB export; raw coordinates hundreds of kilometers from origin lose float32 precision.
## Placement Evidence
Prefer anchors in this order:
1. coordinate callouts;
2. wall lines;
3. envelope rectangles whose dimensions equal the model wall bbox;
4. registered site outlines.
Use wall evidence, not roof/eave envelopes. Derive rotation from a matched edge and resolve the 180-degree ambiguity with an asymmetric feature such as entrances, machine rooms, or basement ramps. Save the source and reasoning in `site_manifest.json`.
For irregular outlines use `register_site_outlines.py`. Constrain the angle window when the building is visibly axis-aligned. Treat residuals roughly as: 0.06m excellent, 0.5-1m plausible with balconies, above 2m likely wrong outline/floors.
## Site Outlines and Missing Buildings
If a building has no delivered drawings but has a site outline and storey label, use `massing_from_outline.py`. Label every such floor/model as total-plan outline massing. Never silently fabricate detailed walls/windows.
Use multiple floor footprints for registration when upper wings/overhangs explain the site outline better than one floor.
## Assembly Gates
Use `assemble_campus.py` with per-building `rotation_deg` where needed. Require:
- no unexplained negative wall-envelope gaps;
- 0.15-0.30m joints corroborated as expansion joints;
- several-meter separations checked against fire/site evidence;
- all buildings inside the red line;
- a top-view overlay or render showing each model inside its site outline;
- numeric envelope dimensions and neighbour gaps in the notes/evidence.
`--allow-overlap` is for a documented shared structure or verified interlocking geometry, not a shortcut around placement bugs.
## Site Context
Use `site_context_from_dump.py` to generate ground/red-line footprints, roads, parking, fences, trees, and low-confidence context massings from one selected site-plan copy. Supply the correct per-dump unit scale, region window, origin, and exclusion quad for real modeled buildings.
Keep site context in every presentation variant. Replace context massings with real models when drawing sets exist. A campus with only boundary sticks is incomplete presentation, but visual completeness never permits fake buildings.

View File

@@ -0,0 +1,85 @@
# Input Formats and Conversion Branches
## Contents
1. Supported inputs
2. DWG conversion selection
3. XREF and cached-block handling
4. 3DSOLID/MESH branch
5. PDF boundary
6. Dependencies and portability
## Supported Inputs
Use this skill directly for architectural DWG/DXF drawing folders and DXF files produced by the bundled WASM bridge. Preserve source folders and write conversions under `work/`.
For multi-discipline sets, model from 建筑 by default. Pull 结构 later for columns/beams only when the requested showcase needs them. Never feed architecture, structure, MEP, and site drawings into one extraction config.
## DWG Conversion Selection
Run `cad_showcase.py inspect` or `cad_dxf_report.py` with an explicit converter policy:
- `--converter auto`: use libredwg first and retry failed/zero-entity conversions with ODA.
- `--converter libredwg`: require libredwg and do not change converter silently.
- `--converter oda`: use ODA for every DWG. Choose this for known 3DSOLID/ACIS drawings and TArch files known to break libredwg.
Tool discovery is environment variable, PATH, then platform defaults:
- Blender: `BLENDER` -> PATH -> macOS/Windows install defaults.
- ODA: `ODA_CONVERTER` -> PATH -> macOS/Windows install defaults.
ODA requires existing absolute input/output directories. It may show GUI errors while returning no useful stderr; an exit 0 with no output is still a failure. The script stages ASCII file names and verifies produced files.
If native converters are unavailable, use the tested WASM bridge:
```bash
npm install --prefix work/vendor-js @mlightcad/libredwg-web
node scripts/dwg_dump_json.mjs input.dwg work/dump.json \
--module-dir work/vendor-js/node_modules
python3 scripts/dwgjson_to_dxf.py --json work/dump.json --out work/dxf_raw/input.dxf
```
The bridge carries LINE/POLYLINE/ARC/CIRCLE/ELLIPSE/SPLINE/TEXT/INSERT and block definitions. It drops HATCH/DIMENSION/ATTRIB; record that limitation and do not infer hatch-only columns or attribute-held axis labels from the result.
## XREF and Cached Blocks
- `cached_xref_content`: the file contains INSERT stubs plus cached block definitions. Expand blocks in detect/derive; do not ask for a re-export.
- `likely_xref_shell`: the referenced geometry is absent. Ask the user to bind/insert XREFs and re-export DXF.
- `has_xref_definitions`: verify that no essential external content is missing before modeling.
Never treat an unresolved XREF shell as a completed floor.
## 3DSOLID/MESH Branch
Force ODA before inspecting known solid models because libredwg can keep annotations while silently dropping ACIS data. Then run:
```bash
python3 scripts/extract_3d_solids.py \
--dxf work/dxf_sanitized/model.dxf \
--out-glb outputs/model/solids.glb \
--out-obj outputs/model/solids.obj \
--report outputs/model/solids_report.json
```
The extractor supports DXF MESH and flat polygonal ACIS faces. It counts cone/sphere/spline/torus/cylinder/swept/revolution surface records as unsupported. If curved records dominate, request OBJ/STL/STEP exported by AutoCAD, BricsCAD, or another full CAD kernel. Label partial output honestly.
## PDF Boundary
This skill does not natively reconstruct CAD geometry from PDF. For PDF-only input:
- ask for DWG/DXF when precision matters;
- or use a separate PDF/vector/OCR workflow with explicit scale calibration before invoking this skill;
- never treat raster tracing as CAD-equivalent geometry without dimensional evidence.
Do not advertise PDF support merely because a floor plan is visible in a PDF.
## Dependencies and Portability
Install deterministic dependency sets in the project environment:
```bash
python3 -m pip install -r requirements-core.txt
python3 -m pip install -r requirements-delivery.txt
```
Use `cad_showcase.py doctor` before a full run. On Windows set `PYTHONUTF8=1` and enable long paths for deep Chinese file names. Keep optional Blender/IfcOpenShell branches separate from the core Python path.

View File

@@ -0,0 +1,66 @@
# Multi-Frame Sheets and TArch/天正
## Contents
1. Detecting sheet walls
2. Alignment evidence
3. Titles and storeys
4. Clip risks
5. TArch mapping preset
## Detecting Sheet Walls
Chinese architectural DWGs often place all plans, elevations, sections, and details in one modelspace. Run `detect_sheet_frames.py`; never model the whole file as one floor.
The detector:
- scans plan titles in modelspace and cached blocks;
- rejects catalog/title-block copies and auxiliary titles;
- prefers title-block INSERT bboxes over pitch-only windows;
- expands enumerated/ranged titles such as `三、五层` and `十一至十四层`;
- emits a config skeleton plus a Markdown evidence report.
Pass every detector output config to audit with `--frames`. Account for every detected plan frame in extraction config or `discarded_frames` with a nonempty reason.
## Alignment Evidence
Prefer structural-grid voting. TArch grids often live on `DOTE`, not `AXIS`. When through grids are absent, accept tick-grid voting. When no axes exist, use wall-profile correlation independently in X/Y. Use clip-corner anchoring only as a weak fallback.
Require overlay review for `WEAK grid match` and `wall-correlated` results. The audit cross-floor datum gate must reject a strong correlation peak at a nonzero shift; envelope centers alone cannot detect a floor placed into the wrong tower slot.
Never stack frames without offsets. That preserves sheet-layout pitch and creates the classic diagonal staircase building.
## Titles and Storeys
Read per-frame elevation ladders from section/elevation frames, but treat suggested storey tables as evidence rather than truth. Stair sections can contain half-storey rhythms; podium, machine-room, and roof heights differ.
Set explicit `z`, `height`, and `floor_order`. The schema rejects floor-order gaps and ghost keys.
## Clip Risks
Title-block or refined clips can still swallow adjacent rows, details, legends, or revision tables. Investigate when a footprint dimension is 2-4x its siblings or contains distant sliver polygons. Tighten the clip band or use isolated-cluster filtering; do not simply raise noise thresholds until the artifact disappears.
## TArch Mapping Preset
Start consciously from this calibration, then inspect actual top layers:
- walls: `WALL`, `*WALL*`, `*墙*`
- columns: `COLUMN`, `*COL*`
- glazing: `CURTWALL`, `*GLAZ*`, `*幕墙*`, `*玻璃*`
- roof: `屋面`, `*屋顶*`
- detail: `STAIR`, `EVTR`, `平面`, `开口`
- grid: `DOTE`, `AXIS`
Doors/windows may both be INSERTs on `WINDOW`, with leaf geometry on layer `0`. Use block-name classification:
```json
{
"expand_blocks": ["$TCHSYS$*", "$DorLib2D$*"],
"block_name_categories": {
"glazing": ["$TCHSYS$WIN2D*"],
"doors": ["$DorLib2D$*"]
}
}
```
Exclude annotation/frame layers such as `*-IDEN`, `*图签*`, `PUB_*`, `DIM_*`, `*TEXT*`, `面积核算`, `格子线`, `SEC-*`, `立面`, `剖面`, `家具`. TArch column fills can be HATCH-only; pull structure from the structural drawing set instead of inventing columns.

View File

@@ -1,5 +1,15 @@
# Skill 优化建议(来自主辅楼建筑群 11 张图实战复盘)
## Contents
1. Lightweighting
2. Up-axis contract
3. Geometry completeness
4. Robustness
5. QA
6. Portability
7. Reusable artifacts
本文记录在一次完整实战(A202/A205/A208–A213 共 11 张 CAD 平面图 → 轻量化 Web 展示模型)中暴露的问题与已验证的修复,作为对 skill 脚本与模板的具体改进建议。修复均已在该项目落地验证。
---

View File

@@ -1,5 +1,19 @@
# CAD to Web Building Showcase Pipeline
Prefer `scripts/cad_showcase.py` for source inspection and the resumable post-config pipeline. Use the individual commands below when diagnosing or iterating a specific stage.
## Contents
1. Inventory and conversion
2. CAD read report
3. Layer mapping
4. Floor detection and alignment
5. Spec extraction
6. Audit and overlays
7. Blender generation
8. Web showcase
9. Verification and IFC proof
## 1. Inventory and Conversion
Start by listing source files and preserving names. CAD drawing names often encode floor numbers, building zones, and drawing type.
@@ -88,6 +102,7 @@ Example:
```json
{
"config_version": 1,
"project_name": "Main Building",
"scale": 0.001,
"origin_strategy": "center",
@@ -157,6 +172,13 @@ Example:
}
```
Validate before extraction:
```bash
python3 <skill>/scripts/showcase_schema.py config work/cad_showcase/config.json \
--dxf-dir work/cad_showcase/dxf_sanitized
```
In the A208 test project, 1F and 2F were on the same sheet and the second floor required an X shift of about `-158029.255 mm` to align the grids. Treat this as an example, not a constant.
Use `origin_strategy: "center"` for large CAD coordinates. It mirrors the A208 proven workflow and keeps Blender/Web coordinates numerically stable.
@@ -297,10 +319,12 @@ Run the Blender-free QA pass first, then eyeball the previews before opening the
python3 <skill>/scripts/verify_showcase.py \
--spec work/cad_showcase/building_spec.json \
--glb outputs/<project>/variants/overview.glb outputs/<project>/variants/standard.glb outputs/<project>/variants/detail.glb \
--out outputs/<project>/verify_previews.png --budget-mb 0.6
--out outputs/<project>/verify_previews.png --budget-mb 25 --strict
```
It prints per-floor segment/cap/glazing-continuity counts and a GLB size-budget pass/fail, and writes front/side/plan orthographic previews. Use these to catch missing floors, a lying-down (wrong up-axis) model, uncapped columns, or discontinuous glazing **before** declaring the model done — early visual verification avoids most rework.
It prints per-floor segment/cap/glazing-continuity counts and a GLB size-budget pass/fail, and writes front/side/plan previews from the spec. Use those previews for stacking and footprint gaps. Use an actual GLB render/browser screenshot to verify Y-up orientation, caps, materials, and slab fins; a spec preview cannot prove exported geometry orientation.
Finish with `verify_delivery.py` and retain its `evidence_manifest.json`; for formal Web delivery include the passing report from `web_smoke_test.mjs`.
Minimum verification:

View File

@@ -0,0 +1,67 @@
# GLB and Web Delivery
## Contents
1. Variant contract
2. Served viewer
3. Offline viewer
4. Browser smoke test
5. Strict evidence manifest
## Variant Contract
Deliver three variants for Web/digital-twin presentation:
- overview: walls, glazing, roof, columns, beams, slabs;
- standard: overview plus railings and doors; use as default;
- detail: all extracted categories for review.
Generate them with `build_showcase_variants.py` or `cad_showcase.py run`. Validate `variants_manifest.json` and every variant spec. Keep `source_file==site` floors intact across variants.
Both GLB backends consume versioned `building_spec.json`. They must preserve `<floor>__<category>` names and glTF Y-up. `floor.caps` is canonical; exporters must not independently infer different cap groups.
## Served Viewer
Use `write_web_showcase.py`, then install local dependencies from the copied exact-version `package.json`. Do not use mainland-unreliable CDNs.
The official template includes on-demand rendering, ACES/RoomEnvironment lighting, physical glass, shadows, grouped floor/category toggles, overview-to-standard progressive load, in-page variant switching, explode/section controls, presets, tour, bookmarks, URL-hash state, screenshot, inspection, and downloads.
Require idle `window.__renders` growth of zero after damping stops.
## Offline Viewer
Use `write_offline_viewer.py` only for double-click/no-server delivery. It embeds vendored Three r147, pako, and a gzip-compressed GLB. Run `verify_delivery.py --offline-viewer` to decode and verify the embedded payload.
The offline viewer intentionally follows an older Three API. Keep its vendored library versions/checksums documented when updating them; do not copy modern template code blindly into r147.
## Browser Smoke Test
Serve the Web directory locally, then run:
```bash
node scripts/web_smoke_test.mjs \
--url http://127.0.0.1:8188 \
--out outputs/<project>/browser_smoke_report.json \
--screenshots-dir outputs/<project>/browser_smoke
```
Install Playwright/Chromium first when needed. The script checks desktop/mobile control visibility, console/page/request failures, and idle render behavior. Feed the report to final verification with `--browser-report`; use `--require-browser-report` for formal Web delivery.
## Strict Evidence Manifest
Run `verify_showcase.py --strict` for spec previews and GLB budgets, then:
```bash
python3 scripts/verify_delivery.py \
--source-report outputs/<project>/cad_read_report.json \
--spec outputs/<project>/building_spec.json \
--variants-manifest outputs/<project>/delivery/variants_manifest.json \
--web-dir outputs/<project>/web \
--offline-viewer outputs/<project>/viewer.html \
--render outputs/<project>/verify_previews.png outputs/<project>/iso.png \
--browser-report outputs/<project>/browser_smoke_report.json \
--require-browser-report \
--evidence-out outputs/<project>/evidence_manifest.json
```
The verifier checks schema versions, GLB headers/mesh structure/naming/budgets, render dimensions/nonblank variance, Web assets/placeholders/features/variants, offline payload, and browser report. Treat overall FAIL as a delivery blocker.

View File

@@ -1,5 +1,13 @@
# Web Presentation Upgrades (视觉/交互/性能改进清单)
## Contents
1. Tier 1 defaults
2. Tier 2 geometry quality
3. Tier 3 interaction and scale-out
4. Current implementation status
5. Honesty rules
Prioritized playbook for pushing a working showcase model toward digital-twin
presentation quality. Apply AFTER the geometry passes the One-Shot Definition
of Done — polish never excuses a wrong model. Each item names the code to
@@ -64,16 +72,13 @@ touch. Ordered by value-per-effort.
## Tier 3 — interaction & scale-out
10. Click-to-inspect: raycast -> highlight mesh, show floor/category/source
layer + drawing file (all present in `building_spec.json`; write it into
GLB `extras` during export so the viewer needs no extra fetch).
11. Camera bookmarks + auto-orbit tour; state (visible floors, section
height, camera) serialized into the URL hash for sharing.
12. Progressive loading for campuses: load `overview` GLB first, swap in
`standard`/`detail` per building on idle or on selection
(`build_showcase_variants.py` already produces the variants + manifest).
13. Per-building toggles grouped in the panel (floors nested under building)
once floor keys carry building prefixes (1F1 / 2F1 / 3F1 ...).
10. Click-to-inspect — PARTIAL: raycast/highlight plus floor/category is done.
Source layer + drawing file still require preserved GLB extras; merging
currently collapses that provenance.
11. Camera bookmarks + auto-orbit tour + URL-hash state — DONE.
12. Progressive loading — PARTIAL: overview -> standard global swap is done;
per-building idle/selection loading remains future work.
13. Per-building grouped toggles with floor-key prefix fallback — DONE.
14. Instancing & merge policy: merge static same-material meshes per building
(`BufferGeometryUtils.mergeGeometries`) — target < 150 draw calls for a
5-building campus; keep per-floor granularity only for toggleable nodes.
@@ -128,7 +133,8 @@ catcher (was at basement depth — shadows floated detached), and a data-URI
favicon (console stays clean).
PENDING (Tier 2/3): door/window openings, road/green surfaces (filled
polygons), camera tours / URL state, progressive per-building loading.
polygons), source-layer/drawing provenance through merged GLB extras, and
progressive per-building loading. Camera tours / URL state are complete.
## Honesty rules for presentation upgrades

6
requirements-core.txt Normal file
View File

@@ -0,0 +1,6 @@
ezdxf>=1.4,<2
jsonschema>=4.20,<5
mapbox-earcut>=1.0,<2
numpy>=1.26,<3
shapely>=2.0,<3
trimesh>=4.5,<5

View File

@@ -0,0 +1,4 @@
-r requirements-core.txt
matplotlib>=3.8,<4
pillow>=10,<12
pygltflib>=1.16,<2

3
requirements-qa.txt Normal file
View File

@@ -0,0 +1,3 @@
-r requirements-delivery.txt
pytest>=7.4,<9
ruff>=0.5,<1

View File

@@ -0,0 +1,125 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://cad-building-showcase.local/schemas/building-spec-v1.json",
"title": "CAD Building Showcase building_spec.json",
"type": "object",
"required": ["schema_version", "project", "source", "units", "categories", "floors"],
"properties": {
"schema_version": {"const": 1},
"project": {
"type": "object",
"required": ["name", "description"],
"properties": {"name": {"type": "string"}, "description": {"type": "string"}},
"additionalProperties": true
},
"source": {
"type": "object",
"required": ["config"],
"properties": {
"dxf_dir": {"type": "string"},
"report": {"type": "string"},
"config": {"type": "object"}
},
"additionalProperties": true
},
"units": {
"type": "object",
"required": ["source", "scale_to_meters", "origin_source"],
"properties": {
"source": {"type": "string"},
"scale_to_meters": {"type": "number", "exclusiveMinimum": 0},
"origin_source": {"$ref": "#/$defs/point"}
},
"additionalProperties": false
},
"categories": {
"type": "object",
"additionalProperties": {
"type": "object",
"required": ["label", "color"],
"properties": {"label": {"type": "string"}, "color": {"type": "string"}},
"additionalProperties": true
}
},
"floors": {
"type": "object",
"additionalProperties": {"$ref": "#/$defs/floor"}
},
"extraction_report": {"type": "array", "items": {"type": "object"}}
},
"additionalProperties": false,
"$defs": {
"point": {
"type": "array",
"prefixItems": [{"type": "number"}, {"type": "number"}],
"minItems": 2,
"maxItems": 2
},
"rect": {
"type": "array",
"prefixItems": [
{"type": "number"}, {"type": "number"}, {"type": "number"}, {"type": "number"}
],
"minItems": 4,
"maxItems": 4
},
"segment": {
"type": "object",
"required": ["start", "end", "width", "layer", "source_type"],
"properties": {
"start": {"$ref": "#/$defs/point"},
"end": {"$ref": "#/$defs/point"},
"width": {"type": "number", "minimum": 0},
"layer": {"type": "string"},
"source_type": {"type": "string"},
"_z0": {"type": "number"},
"_z1": {"type": "number"}
},
"additionalProperties": true
},
"polygon": {
"type": "array",
"minItems": 3,
"items": {"$ref": "#/$defs/point"}
},
"footprint": {
"type": "object",
"required": ["polygons"],
"properties": {
"method": {"type": "string"},
"source": {"type": "string"},
"source_categories": {"type": "array", "items": {"type": "string"}},
"area": {"type": "number", "minimum": 0},
"polygons": {"type": "array", "items": {"$ref": "#/$defs/polygon"}}
},
"additionalProperties": true
},
"cap": {
"type": "object",
"required": ["z", "polygons"],
"properties": {
"z": {"type": "number"},
"polygons": {"type": "array", "items": {"$ref": "#/$defs/polygon"}}
},
"additionalProperties": false
},
"floor": {
"type": "object",
"required": ["name", "z", "height", "bounds", "source_file", "segments"],
"properties": {
"name": {"type": "string"},
"z": {"type": "number"},
"height": {"type": "number", "exclusiveMinimum": 0},
"bounds": {"$ref": "#/$defs/rect"},
"source_file": {"type": "string"},
"segments": {
"type": "object",
"additionalProperties": {"type": "array", "items": {"$ref": "#/$defs/segment"}}
},
"footprint": {"$ref": "#/$defs/footprint"},
"caps": {"type": "array", "items": {"$ref": "#/$defs/cap"}}
},
"additionalProperties": true
}
}
}

View File

@@ -0,0 +1,166 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://cad-building-showcase.local/schemas/extraction-config-v1.json",
"title": "CAD Building Showcase extraction config",
"type": "object",
"properties": {
"config_version": {"const": 1},
"_comment": {"type": ["string", "array", "object"]},
"project_name": {"type": "string"},
"description": {"type": "string"},
"source_units": {"type": "string"},
"scale": {"type": "number", "exclusiveMinimum": 0},
"scale_to_meters": {"type": "number", "exclusiveMinimum": 0},
"origin": {"$ref": "#/$defs/point"},
"origin_strategy": {"enum": ["center", "min"]},
"floor_height": {"type": "number", "exclusiveMinimum": 0},
"floor_order": {"type": "array", "items": {"type": "string"}, "uniqueItems": true},
"drawings": {
"type": "array",
"items": {"$ref": "#/$defs/drawing"}
},
"discarded_frames": {
"type": "array",
"items": {
"type": "object",
"required": ["name", "reason"],
"properties": {
"name": {"type": "string", "minLength": 1},
"reason": {"type": "string", "minLength": 1}
},
"additionalProperties": false
}
},
"layers": {"$ref": "#/$defs/patternMap"},
"categories": {"type": "object"},
"exclude_layers": {"$ref": "#/$defs/stringList"},
"default_widths": {"$ref": "#/$defs/numberMap"},
"default_disabled_categories": {"$ref": "#/$defs/stringList"},
"min_source_length": {"type": "number", "minimum": 0},
"min_source_length_by_category": {"$ref": "#/$defs/numberMap"},
"min_length_meters": {"type": "number", "minimum": 0},
"min_length_meters_by_category": {"$ref": "#/$defs/numberMap"},
"curve_chord_source_length": {"type": "number", "exclusiveMinimum": 0},
"expand_blocks": {"oneOf": [{"type": "boolean"}, {"$ref": "#/$defs/stringList"}]},
"expand_block_names": {"$ref": "#/$defs/stringList"},
"expand_blocks_max_depth": {"type": "integer", "minimum": 0, "maximum": 16},
"expand_glazing_blocks": {"type": "boolean"},
"classify_block_contents": {"type": "boolean"},
"block_content_categories": {"$ref": "#/$defs/stringList"},
"block_name_categories": {"$ref": "#/$defs/patternMap"},
"block_insert_layer_fallback": {"type": "boolean"},
"generate_footprints": {"type": "boolean"},
"footprint_categories": {"$ref": "#/$defs/stringList"},
"footprint_concave_ratio": {"type": "number", "minimum": 0, "maximum": 1},
"footprint_simplify_tolerance": {"type": "number", "minimum": 0},
"footprint_min_area": {"type": "number", "minimum": 0},
"footprint_max_polygons": {"type": "integer", "minimum": 1},
"footprint_cluster_linkage": {"type": "number", "exclusiveMinimum": 0},
"use_footprint_slabs": {"type": "boolean"},
"use_footprint_roofs": {"type": "boolean"},
"slab_bounds_fallback": {"type": "boolean"},
"slab_thickness": {"type": "number", "exclusiveMinimum": 0},
"generate_caps": {"type": "boolean"},
"cap_buffer": {"type": "number", "minimum": 0},
"cap_groups": {
"type": "array",
"items": {
"type": "array",
"prefixItems": [{"type": "string"}, {"type": "string"}],
"minItems": 2,
"maxItems": 2
}
},
"roof_specs": {"type": "array", "items": {"$ref": "#/$defs/roofSpec"}},
"merge_glazing": {"type": "boolean"},
"glazing_gap_tol": {"type": "number", "minimum": 0},
"merge_wall_solids": {"type": "boolean"},
"glazing_mullions": {"type": "boolean"},
"glazing_panel_w": {"type": "number", "exclusiveMinimum": 0},
"drop_isolated_clusters": {"type": "boolean"},
"cluster_linkage": {"type": "number", "exclusiveMinimum": 0},
"isolation_distance": {"type": "number", "minimum": 0},
"isolation_min_length": {"type": "number", "minimum": 0},
"drop_unsupported_roof_lines": {"type": "boolean"},
"roof_support_distance": {"type": "number", "minimum": 0},
"shorten_unsupported_columns": {"type": "boolean"},
"shorten_unsupported_columns_floor_keys": {"$ref": "#/$defs/stringList"},
"unsupported_column_height": {"type": "number", "minimum": 0},
"column_support_distance": {"type": "number", "minimum": 0},
"column_support_z_tolerance": {"type": "number", "minimum": 0},
"column_roof_support_z_tolerance": {"type": "number", "minimum": 0},
"column_support_categories": {"$ref": "#/$defs/stringList"},
"column_support_requires_upper_plate": {"type": "boolean"},
"column_support_allow_plate_only": {"type": "boolean"},
"show_floor_labels": {"type": "boolean"},
"declared_areas_m2": {"$ref": "#/$defs/numberMap"},
"declared_area_tolerance": {"type": "number", "minimum": 0},
"expected_storeys_above_ground": {"type": "integer", "minimum": 0},
"showcase_variant": {"type": "string"},
"showcase_variant_categories": {"oneOf": [{"type": "string"}, {"$ref": "#/$defs/stringList"}]}
},
"additionalProperties": false,
"$defs": {
"point": {
"type": "array",
"prefixItems": [{"type": "number"}, {"type": "number"}],
"minItems": 2,
"maxItems": 2
},
"rect": {
"type": "array",
"prefixItems": [
{"type": "number"}, {"type": "number"}, {"type": "number"}, {"type": "number"}
],
"minItems": 4,
"maxItems": 4
},
"stringList": {"type": "array", "items": {"type": "string"}},
"numberMap": {"type": "object", "additionalProperties": {"type": "number"}},
"patternMap": {
"type": "object",
"additionalProperties": {"$ref": "#/$defs/stringList"}
},
"floor": {
"type": "object",
"required": ["key"],
"properties": {
"key": {"type": "string", "minLength": 1},
"name": {"type": "string"},
"z": {"type": ["number", "null"]},
"height": {"type": "number", "exclusiveMinimum": 0},
"clip": {"$ref": "#/$defs/rect"},
"offset": {"$ref": "#/$defs/point"},
"side": {"type": "string"},
"split_x": {"type": "number"}
},
"additionalProperties": false
},
"drawing": {
"type": "object",
"required": ["file"],
"properties": {
"file": {"type": "string", "minLength": 1},
"clip": {"$ref": "#/$defs/rect"},
"offset": {"$ref": "#/$defs/point"},
"split_x": {"type": "number"},
"floors": {"type": "array", "items": {"$ref": "#/$defs/floor"}}
},
"additionalProperties": false
},
"roofSpec": {
"type": "object",
"required": ["floor_key"],
"properties": {
"floor_key": {"type": "string"},
"bounds_from": {"$ref": "#/$defs/stringList"},
"footprint_from": {"$ref": "#/$defs/stringList"},
"bounds": {"$ref": "#/$defs/rect"},
"z": {"type": "number"},
"thickness": {"type": "number", "exclusiveMinimum": 0},
"margin": {"type": "number", "minimum": 0}
},
"additionalProperties": false
}
}
}

View File

@@ -0,0 +1,31 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://cad-building-showcase.local/schemas/variants-manifest-v1.json",
"title": "CAD Building Showcase variants manifest",
"type": "object",
"required": ["manifest_version", "name", "default_key", "variants"],
"properties": {
"manifest_version": {"const": 1},
"name": {"type": "string"},
"default_key": {"type": "string"},
"variants": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["key", "label", "file", "source_glb", "metadata", "spec"],
"properties": {
"key": {"type": "string", "minLength": 1},
"label": {"type": "string"},
"description": {"type": "string"},
"file": {"type": "string"},
"source_glb": {"type": "string"},
"metadata": {"type": "string"},
"spec": {"type": "string"}
},
"additionalProperties": false
}
}
},
"additionalProperties": false
}

View File

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

View File

@@ -14,6 +14,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import derive_showcase_spec as derive # noqa: E402
import showcase_schema # noqa: E402
HIGH_RISK_TYPES = {
@@ -87,10 +88,7 @@ def block_layer_unit_lengths(doc, name: str, max_chord: float, max_depth: int, d
for layer, length in block_layer_unit_lengths(doc, inner_name, max_chord, max_depth, depth + 1).items():
totals[layer] += length * factor
else:
length = sum(
segment_length_source(segment)
for segment in derive.entity_segments(inner, max_chord)
)
length = sum(segment_length_source(segment) for segment in derive.entity_segments(inner, max_chord))
if length > 0:
totals[derive.entity_layer(inner)] += length
result = dict(totals)
@@ -141,7 +139,8 @@ def inspect_entity(
"supported_length": supported_length,
"sample": sample,
"high_risk": dxftype in HIGH_RISK_TYPES,
"insert_name": block_name or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
"insert_name": block_name
or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
}
@@ -168,15 +167,17 @@ def spec_counts(spec: dict[str, Any]) -> dict[str, dict[str, int]]:
categories = [key for key in spec.get("categories", {}) if key != "slab"]
result = {}
for floor_key, floor in spec.get("floors", {}).items():
result[floor_key] = {
category: len(floor.get("segments", {}).get(category, []))
for category in categories
}
result[floor_key] = {category: len(floor.get("segments", {}).get(category, [])) for category in categories}
return result
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path,
frames: list[dict[str, Any]] | None = None) -> dict[str, Any]:
def audit(
dxf_dir: Path,
config: dict[str, Any],
spec: dict[str, Any],
vendor_dir: Path,
frames: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -232,9 +233,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
sx = abs(float(source_entity.dxf.get("xscale", 1.0) or 1.0))
sy = abs(float(source_entity.dxf.get("yscale", 1.0) or 1.0))
factor = (sx + sy) / 2.0
unit_lengths = block_layer_unit_lengths(
doc, insert_name, max_chord, max_block_depth
)
unit_lengths = block_layer_unit_lengths(doc, insert_name, max_chord, max_block_depth)
for inner_layer, unit_length in unit_lengths.items():
inner_length = unit_length * factor
if inner_length <= 0:
@@ -343,9 +342,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"coverage": {
"supported_length_meters": round(total_supported * scale, 3),
"classified_supported_length_meters": round(classified_supported * scale, 3),
"supported_length_coverage": round(classified_supported / total_supported, 4)
if total_supported
else None,
"supported_length_coverage": round(classified_supported / total_supported, 4) if total_supported else None,
"block_locked_length_meters": round(block_locked_total * scale, 3),
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
@@ -390,9 +387,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
xs = [v for s in walls for v in (s["start"][0], s["end"][0])]
ys = [v for s in walls for v in (s["start"][1], s["end"][1])]
size = max(max(xs) - min(xs), max(ys) - min(ys))
groups[derive._cap_floor_group(fk, config)].append(
(fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size)
)
groups[derive._cap_floor_group(fk, config)].append((fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size))
worst: tuple[float, str] | None = None
for grp, items in groups.items():
if len(items) < 2:
@@ -402,7 +397,10 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for j in range(i + 1, len(items)):
dist = math.hypot(items[i][1] - items[j][1], items[i][2] - items[j][2])
if dist > limit and (worst is None or dist > worst[0]):
worst = (dist, f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})")
worst = (
dist,
f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})",
)
if worst:
return {
"name": "floors_aligned",
@@ -432,16 +430,15 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for grp, keys in by_group.items():
if len(keys) < 2:
continue
ref_key = max(keys, key=lambda k: sum(
math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_key = max(keys, key=lambda k: sum(math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4)
ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4)
def zero_cov(ref_prof, prof, tol: float = 0.25) -> float:
total = sum(w for _, w in prof)
if total <= 0:
return 0.0
matched = sum(w for p, w in prof
if any(abs(p - rp) <= tol for rp, _ in ref_prof))
matched = sum(w for p, w in prof if any(abs(p - rp) <= tol for rp, _ in ref_prof))
return matched / total
for fk in keys:
@@ -455,8 +452,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
# let any small profile "match" somewhere: 27号 1#A PH)
if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov:
continue
if (shift is not None and cov >= 0.45 and ratio >= 1.5
and abs(shift) > 1.0):
if shift is not None and cov >= 0.45 and ratio >= 1.5 and abs(shift) > 1.0:
return {
"name": "floors_aligned",
"status": "FAIL",
@@ -475,28 +471,40 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
}
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any],
frames: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]:
def evaluate_gates(
report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any], frames: list[dict[str, Any]] | None = None
) -> list[dict[str, Any]]:
"""Hard checks that must pass before 3D generation.
A gate FAIL means the extraction is known-incomplete in a way that high
coverage numbers cannot excuse; fix the config (block expansion, layer
mapping, source re-export) and re-run instead of accepting the model.
"""
gates: list[dict[str, Any]] = [floors_alignment_gate(spec, config)]
gates: list[dict[str, Any]] = [
{
"name": "all_config_drawings_present",
"status": "PASS",
"detail": "Every configured source drawing exists and passed config validation.",
},
{
"name": "unique_floor_keys",
"status": "PASS",
"detail": "Configured floor keys are unique.",
},
{
"name": "every_floor_nonempty",
"status": "PASS",
"detail": "Every floor contains segments, footprint polygons, or caps.",
},
floors_alignment_gate(spec, config),
]
spec_glazing_segments = sum(
counts.get("glazing", 0) for counts in report["spec_counts"].values()
)
spec_glazing_segments = sum(counts.get("glazing", 0) for counts in report["spec_counts"].values())
locked_glazing_meters = sum(
item["supported_length_meters"]
for item in report["block_locked_layers"]
if item["category"] == "glazing"
item["supported_length_meters"] for item in report["block_locked_layers"] if item["category"] == "glazing"
)
glazing_named_blocks = [
name
for name in report["top_insert_names"]
if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
name for name in report["top_insert_names"] if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
]
glazing_evidence = locked_glazing_meters >= GATE_GLAZING_MIN_METERS or bool(glazing_named_blocks)
if not glazing_evidence:
@@ -524,7 +532,7 @@ def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[st
gates.append(
{
"name": "no_annotation_layers_classified",
"status": "WARN" if annotation_classified else "PASS",
"status": "FAIL" if annotation_classified else "PASS",
"detail": (
f"Annotation/identification layers classified as geometry: {', '.join(annotation_classified[:5])}. "
"These are tags, not elements; exclude them."
@@ -586,8 +594,7 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
`"discarded_frames": [{"name": ..., "reason": ...}]`.
"""
if not frames:
return {"name": "frame_ledger", "status": "SKIP",
"detail": "No --frames given; frame ledger not checked."}
return {"name": "frame_ledger", "status": "SKIP", "detail": "No --frames given; frame ledger not checked."}
discarded = {str(d.get("name", "")) for d in config.get("discarded_frames", [])}
cfg_by_file: dict[str, list[dict[str, Any]]] = {}
for drawing in config.get("drawings", []) or []:
@@ -604,10 +611,7 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
clip = frame.get("clip")
if name in discarded:
continue
if clip and any(
fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3
for fl in cfg_floors
):
if clip and any(fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3 for fl in cfg_floors):
continue
unaccounted.append(f"{file}: {frame.get('key', '?')} {name}")
if unaccounted:
@@ -621,8 +625,11 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
"floors/wings vanish — use them or discard them WITH a reason."
),
}
return {"name": "frame_ledger", "status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded."}
return {
"name": "frame_ledger",
"status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded.",
}
def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -635,8 +642,11 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
"""
declared = config.get("declared_areas_m2")
if not declared:
return {"name": "area_declared", "status": "SKIP",
"detail": "No declared_areas_m2 in config; area cross-check not requested."}
return {
"name": "area_declared",
"status": "SKIP",
"detail": "No declared_areas_m2 in config; area cross-check not requested.",
}
tol = float(config.get("declared_area_tolerance", 0.15))
problems = []
for key, want in declared.items():
@@ -649,19 +659,26 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
if got <= 0:
problems.append(f"{key}: no footprint area in spec")
elif abs(got - want) / want > tol:
problems.append(f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)")
problems.append(
f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)"
)
if problems:
return {
"name": "area_declared",
"status": "FAIL",
"detail": ("Footprint area disagrees with the declared evidence: "
"detail": (
"Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."),
"sheet moves the area far more than balconies do."
),
}
return {
"name": "area_declared",
"status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values.",
}
return {"name": "area_declared", "status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values."}
def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -672,20 +689,29 @@ def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str,
"""
expected = config.get("expected_storeys_above_ground")
if expected is None:
return {"name": "storey_count", "status": "SKIP",
"detail": "No expected_storeys_above_ground in config; count cross-check not requested."}
return {
"name": "storey_count",
"status": "SKIP",
"detail": "No expected_storeys_above_ground in config; count cross-check not requested.",
}
import re as _re
actual = sum(1 for k in spec.get("floors", {}) if _re.fullmatch(r"F\d+", str(k)))
if actual != int(expected):
return {
"name": "storey_count",
"status": "FAIL",
"detail": (f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
"detail": (
f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."),
"floor_order entry or an unexpanded multi-floor frame is the usual cause."
),
}
return {
"name": "storey_count",
"status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count.",
}
return {"name": "storey_count", "status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count."}
def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]:
@@ -727,11 +753,15 @@ def markdown(report: dict[str, Any]) -> str:
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
"(modelspace linework only — block-locked geometry is NOT in this denominator)",
*([
*(
[
f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over "
f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — "
"on multi-frame sheets judge extraction by THIS number, not the file-global one"
] if coverage.get("clipped_supported_length_coverage") is not None else []),
]
if coverage.get("clipped_supported_length_coverage") is not None
else []
),
f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",
@@ -765,14 +795,12 @@ def markdown(report: dict[str, Any]) -> str:
lines.extend(["", "## Classified Layers", ""])
for layer in report["classified_layers"][:30]:
lines.append(
f"- `{layer['layer']}`: `{layer['categories']}`, "
f"classified length `{layer['classified_length_meters']}` m"
f"- `{layer['layer']}`: `{layer['categories']}`, classified length `{layer['classified_length_meters']}` m"
)
lines.extend(["", "## Files", ""])
for item in report["files"]:
lines.append(
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, "
f"high-risk `{item['high_risk_types']}`"
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, high-risk `{item['high_risk_types']}`"
)
return "\n".join(lines)
@@ -781,6 +809,12 @@ def main() -> int:
args = parse_args()
config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
try:
config = showcase_schema.validate_config(config, Path(args.dxf_dir))
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
frames = None
if args.frames:
frames = [json.loads(Path(p).read_text(encoding="utf-8")) for p in args.frames]

View File

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

View File

@@ -9,6 +9,8 @@ import math
import sys
from pathlib import Path
import showcase_schema
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
@@ -118,7 +120,15 @@ def segment_length(segment: dict) -> float:
return math.hypot(ex - sx, ey - sy)
def add_cad_pset(ifcopenshell, model, element, floor_key: str, category: str, segment: dict | None = None, source_index: int | None = None):
def add_cad_pset(
ifcopenshell,
model,
element,
floor_key: str,
category: str,
segment: dict | None = None,
source_index: int | None = None,
):
pset = ifcopenshell.api.pset.add_pset(model, product=element, name="CAD2BIM_Source")
props = {
"FloorKey": floor_key,
@@ -172,7 +182,17 @@ def add_slab(np, ifcopenshell, model, body_context, storey, floor_key: str, floo
return slab
def add_segment_element(ifcopenshell, model, body_context, storey, floor_key: str, floor: dict, category: str, segment: dict, source_index: int):
def add_segment_element(
ifcopenshell,
model,
body_context,
storey,
floor_key: str,
floor: dict,
category: str,
segment: dict,
source_index: int,
):
length = segment_length(segment)
if length < 0.05:
return None
@@ -276,9 +296,7 @@ def validate_ifc(ifcopenshell, path: Path, validate_geometry: bool) -> dict:
try:
geom.create_shape(settings, element)
except Exception as exc:
geometry_failures.append(
{"ifc_type": ifc_type, "name": element.Name, "error": str(exc)}
)
geometry_failures.append({"ifc_type": ifc_type, "name": element.Name, "error": str(exc)})
return {
"ifc_path": str(path),
@@ -310,7 +328,15 @@ def make_notes(report: dict) -> str:
"## Entity Counts",
"",
]
for key in ("IfcBuildingStorey", "IfcSlab", "IfcWall", "IfcColumn", "IfcBeam", "IfcPropertySet", "IfcExtrudedAreaSolid"):
for key in (
"IfcBuildingStorey",
"IfcSlab",
"IfcWall",
"IfcColumn",
"IfcBeam",
"IfcPropertySet",
"IfcExtrudedAreaSolid",
):
lines.append(f"- `{key}`: {counts.get(key, 0)}")
lines.extend(["", "## Storey Containment", ""])
for storey in report["storeys"]:
@@ -337,7 +363,11 @@ def make_notes(report: dict) -> str:
def main() -> int:
args = parse_args()
np, ifcopenshell = import_deps(Path(args.vendor_dir))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
spec = showcase_schema.normalize_spec(json.loads(Path(args.spec).read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
model, body_context, building = make_model(np, ifcopenshell, spec, args.project_name)
created = {"IfcSlab": 0, "IfcWall": 0, "IfcColumn": 0, "IfcBeam": 0}
limits = {
@@ -384,7 +414,12 @@ def main() -> int:
out_notes.parent.mkdir(parents=True, exist_ok=True)
out_report.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
out_notes.write_text(make_notes(report), encoding="utf-8")
print(json.dumps({"ifc": str(out_ifc), "report": str(out_report), "notes": str(out_notes), "created": created}, ensure_ascii=False))
print(
json.dumps(
{"ifc": str(out_ifc), "report": str(out_report), "notes": str(out_notes), "created": created},
ensure_ascii=False,
)
)
return 0

View File

@@ -18,6 +18,8 @@ import subprocess
from pathlib import Path
from typing import Any
import showcase_schema
VARIANTS = [
{
@@ -160,10 +162,12 @@ def write_manifest(entries: list[dict[str, Any]], out_dir: Path, name: str) -> P
}
)
manifest = {
"manifest_version": showcase_schema.MANIFEST_VERSION,
"name": name,
"default_key": "standard",
"variants": variants,
}
showcase_schema.validate_manifest(manifest)
manifest_path = out_dir / "variants_manifest.json"
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
return manifest_path
@@ -174,7 +178,12 @@ def main() -> int:
spec_path = Path(args.spec)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
spec = json.loads(spec_path.read_text(encoding="utf-8"))
spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
entries = write_variant_specs(spec, out_dir)
if args.build:
run_blender(entries, out_dir, args.blender, Path(args.build_script))

View File

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

419
scripts/cad_showcase.py Normal file
View File

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

View File

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

View File

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

View File

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

View File

@@ -33,9 +33,7 @@ def import_ezdxf(vendor_dir: Path):
try:
import ezdxf # type: ignore
except ImportError as exc:
raise SystemExit(
f"Missing ezdxf. Install with: python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
raise SystemExit(f"Missing ezdxf. Install with: python3 -m pip install --target {vendor_dir} ezdxf") from exc
return ezdxf
@@ -59,8 +57,12 @@ def add_entity(space, ent: dict) -> None:
major = (ent["mj"][0], ent["mj"][1], 0.0)
if math.hypot(major[0], major[1]) > 0:
space.add_ellipse(
ent["c"], major_axis=major, ratio=max(min(ent.get("ratio", 1.0), 1.0), 1e-6),
start_param=ent.get("sa", 0.0), end_param=ent.get("ea", math.tau), dxfattribs=attribs,
ent["c"],
major_axis=major,
ratio=max(min(ent.get("ratio", 1.0), 1.0), 1e-6),
start_param=ent.get("sa", 0.0),
end_param=ent.get("ea", math.tau),
dxfattribs=attribs,
)
elif kind == "SPLINE":
space.add_lwpolyline([(v[0], v[1]) for v in ent["v"]], dxfattribs=attribs)
@@ -68,13 +70,16 @@ def add_entity(space, ent: dict) -> None:
text = ent.get("text", "")
if text:
space.add_text(
text, height=max(float(ent.get("h", 250.0) or 250.0), 1e-3), dxfattribs=attribs,
text,
height=max(float(ent.get("h", 250.0) or 250.0), 1e-3),
dxfattribs=attribs,
).set_placement(ent["p"])
elif kind == "INSERT":
rotation = ent.get("rot", 0.0)
rotation = math.degrees(rotation) if abs(rotation) <= math.tau + 0.01 else rotation
space.add_blockref(
ent["name"], ent["p"],
ent["name"],
ent["p"],
dxfattribs={
**attribs,
"xscale": ent.get("sx", 1.0) or 1.0,

View File

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

View File

@@ -57,10 +57,7 @@ def main() -> int:
model = ifcopenshell.open(str(Path(args.ifc)))
settings = geom.settings()
settings.set(settings.USE_WORLD_COORDS, True)
groups = {
ifc_type: {"ifc_type": ifc_type, "vertices": [], "faces": [], "elements": 0}
for ifc_type in args.types
}
groups = {ifc_type: {"ifc_type": ifc_type, "vertices": [], "faces": [], "elements": 0} for ifc_type in args.types}
failures = []
for ifc_type in args.types:
for element in model.by_type(ifc_type):

View File

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

View File

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

View File

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

268
scripts/showcase_schema.py Normal file
View File

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

View File

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

File diff suppressed because it is too large Load Diff

283
scripts/verify_delivery.py Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,84 @@
from __future__ import annotations
import json
import os
import socket
import subprocess
import sys
import time
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
@pytest.mark.skipif(
os.environ.get("RUN_BROWSER_SMOKE") != "1", reason="set RUN_BROWSER_SMOKE=1 with Playwright installed"
)
def test_served_viewer_in_desktop_and_mobile(tmp_path: Path) -> None:
from test_contracts import minimal_spec
spec = tmp_path / "spec.json"
glb = tmp_path / "model.glb"
metadata = tmp_path / "model_metadata.json"
web = tmp_path / "web"
spec.write_text(json.dumps(minimal_spec()), encoding="utf-8")
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "spec_to_glb.py"),
"--spec",
str(spec),
"--out",
str(glb),
"--metadata-out",
str(metadata),
],
check=True,
)
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "write_web_showcase.py"),
"--glb",
str(glb),
"--metadata",
str(metadata),
"--out-dir",
str(web),
],
check=True,
)
subprocess.run(["npm", "install", "--prefix", str(web), "--ignore-scripts"], check=True)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
server = subprocess.Popen(
[sys.executable, "-m", "http.server", str(port), "--bind", "127.0.0.1"],
cwd=web,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
time.sleep(0.8)
report = tmp_path / "browser_report.json"
proc = subprocess.run(
[
"node",
str(ROOT / "scripts" / "web_smoke_test.mjs"),
"--url",
f"http://127.0.0.1:{port}",
"--out",
str(report),
"--screenshots-dir",
str(tmp_path / "screenshots"),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
assert json.loads(report.read_text(encoding="utf-8"))["status"] == "PASS"
finally:
server.terminate()
server.wait(timeout=10)

423
tests/test_contracts.py Normal file
View File

@@ -0,0 +1,423 @@
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
import pytest
import ezdxf
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import build_blender_showcase # noqa: E402
import cad_showcase # noqa: E402
import showcase_schema # noqa: E402
import spec_to_glb # noqa: E402
def minimal_spec() -> dict:
wall = {
"start": [0.0, 0.0],
"end": [10.0, 0.0],
"width": 0.2,
"layer": "WALL",
"source_type": "LINE",
}
return {
"schema_version": 1,
"project": {"name": "test", "description": "contract fixture"},
"source": {"config": {"config_version": 1, "use_footprint_slabs": True}},
"units": {"source": "meters", "scale_to_meters": 1.0, "origin_source": [0.0, 0.0]},
"categories": {
"walls": {"label": "墙", "color": "#cccccc"},
"slab": {"label": "楼板", "color": "#aaaaaa"},
},
"floors": {
"F1": {
"name": "一层",
"z": 0.0,
"height": 3.0,
"bounds": [0.0, 0.0, 10.0, 8.0],
"source_file": "fixture.dxf",
"segments": {"walls": [wall]},
"footprint": {"source": "fixture", "area": 80.0, "polygons": [[[0, 0], [10, 0], [10, 8], [0, 8]]]},
"caps": [{"z": 3.0, "polygons": [[[0, 0], [10, 0], [10, 8], [0, 8]]]}],
}
},
}
def test_config_rejects_unknown_keys() -> None:
with pytest.raises(showcase_schema.ValidationFailure, match="unexpected_typo"):
showcase_schema.validate_config({"config_version": 1, "unexpected_typo": True})
def test_config_requires_at_least_one_drawing() -> None:
with pytest.raises(showcase_schema.ValidationFailure, match="contains no drawings"):
showcase_schema.validate_config({"config_version": 1})
def test_config_rejects_duplicate_floor_keys(tmp_path: Path) -> None:
(tmp_path / "a.dxf").touch()
(tmp_path / "b.dxf").touch()
config = {
"config_version": 1,
"drawings": [
{"file": "a.dxf", "floors": [{"key": "F1"}]},
{"file": "b.dxf", "floors": [{"key": "F1"}]},
],
}
with pytest.raises(showcase_schema.ValidationFailure, match="duplicate floor key"):
showcase_schema.validate_config(config, tmp_path)
def test_config_rejects_missing_source(tmp_path: Path) -> None:
config = {"config_version": 1, "drawings": [{"file": "missing.dxf", "floors": [{"key": "F1"}]}]}
with pytest.raises(showcase_schema.ValidationFailure, match="does not exist"):
showcase_schema.validate_config(config, tmp_path)
def test_source_report_rejects_partial_gate() -> None:
report = {
"report_version": 1,
"gate": {"name": "all_sources_converted_and_readable", "status": "WARN"},
"files": [{"file": "partial.dxf", "status": "ok", "modelspace_entities": 1}],
}
with pytest.raises(showcase_schema.ValidationFailure, match="must be PASS"):
showcase_schema.validate_source_report(report)
def test_doctor_uses_platform_tool_resolvers(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys) -> None:
oda = tmp_path / "ODAFileConverter"
blender = tmp_path / "blender"
oda.touch()
blender.touch()
monkeypatch.setattr(cad_showcase, "oda_converter", lambda: str(oda))
monkeypatch.setattr(cad_showcase, "default_blender", lambda: str(blender))
assert cad_showcase.doctor() == 0
report = json.loads(capsys.readouterr().out)
checks = {item["name"]: item for item in report["checks"]}
assert checks["ODAFileConverter"] == {"name": "ODAFileConverter", "status": "PASS", "path": str(oda)}
assert checks["blender"] == {"name": "blender", "status": "PASS", "path": str(blender)}
def test_spec_schema_and_backend_group_contract() -> None:
spec = minimal_spec()
showcase_schema.validate_spec(spec)
config = {"cap_groups": [["TOWER_A_*", "A"], ["B*", "BASEMENT"]]}
assert showcase_schema.floor_group("TOWER_A_F3", config) == "A"
assert spec_to_glb.floor_group("TOWER_A_F3", config) == "A"
assert build_blender_showcase.floor_group("TOWER_A_F3", config) == "A"
def test_spec_rejects_segment_category_without_metadata() -> None:
spec = minimal_spec()
spec["floors"]["F1"]["segments"]["unregistered"] = [
{"start": [0, 0], "end": [1, 0], "width": 0.1, "layer": "X", "source_type": "LINE"}
]
with pytest.raises(showcase_schema.ValidationFailure, match="missing from spec.categories"):
showcase_schema.validate_spec(spec)
def test_report_empty_input_is_a_hard_failure(tmp_path: Path) -> None:
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
],
text=True,
capture_output=True,
)
assert proc.returncode == 3
assert "all_sources_converted_and_readable" in proc.stderr
def test_partial_report_requires_and_records_a_reason(tmp_path: Path) -> None:
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
"--allow-partial",
"--partial-reason",
"inventory-only test",
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
report = json.loads((tmp_path / "report" / "cad_read_report.json").read_text(encoding="utf-8"))
assert report["gate"]["status"] == "WARN"
assert report["gate"]["partial_reason"] == "inventory-only test"
def test_no_convert_cannot_hide_dwg_sources(tmp_path: Path) -> None:
ezdxf.new("R2010").saveas(tmp_path / "readable.dxf")
(tmp_path / "unconverted.dwg").write_bytes(b"not converted")
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
"--no-convert",
],
text=True,
capture_output=True,
)
assert proc.returncode == 3
report = json.loads((tmp_path / "report" / "cad_read_report.json").read_text(encoding="utf-8"))
assert "unconverted.dwg" in report["gate"]["detail"]
def test_variants_manifest_is_versioned(tmp_path: Path) -> None:
spec_path = tmp_path / "spec.json"
spec_path.write_text(json.dumps(minimal_spec()), encoding="utf-8")
out = tmp_path / "variants"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "build_showcase_variants.py"),
"--spec",
str(spec_path),
"--out-dir",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
manifest = json.loads((out / "variants_manifest.json").read_text(encoding="utf-8"))
assert manifest["manifest_version"] == 1
showcase_schema.validate_manifest(manifest)
def test_massing_output_conforms_to_schema(tmp_path: Path) -> None:
outline = tmp_path / "outline.json"
outline.write_text(json.dumps([[0, 0], [10, 0], [10, 8], [0, 8]]), encoding="utf-8")
out = tmp_path / "massing.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "massing_from_outline.py"),
"--outline",
str(outline),
"--storeys",
"3",
"--name",
"massing",
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
showcase_schema.validate_spec(json.loads(out.read_text(encoding="utf-8")))
def test_orchestrator_runs_resumable_trimesh_pipeline(tmp_path: Path) -> None:
input_dir = tmp_path / "dxf"
input_dir.mkdir()
doc = ezdxf.new("R2010")
doc.layers.add("WALL")
model = doc.modelspace()
for start, end in [
((0, 0), (10000, 0)),
((10000, 0), (10000, 8000)),
((10000, 8000), (0, 8000)),
((0, 8000), (0, 0)),
]:
model.add_line(start, end, dxfattribs={"layer": "WALL"})
doc.saveas(input_dir / "plan.dxf")
report_work = tmp_path / "report_work"
report_out = tmp_path / "source_report"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(input_dir),
"--work",
str(report_work),
"--output",
str(report_out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
dxf_dir = report_work / "dxf_sanitized"
source_report = report_out / "cad_read_report.json"
config = {
"config_version": 1,
"project_name": "orchestrator-test",
"scale": 0.001,
"generate_footprints": True,
"use_footprint_slabs": True,
"layers": {"walls": ["WALL"]},
"roof_specs": [{"floor_key": "F1", "footprint_from": ["F1"], "z": 3.0, "thickness": 0.3}],
"drawings": [{"file": "plan.dxf", "floors": [{"key": "F1", "z": 0.0, "height": 3.0}]}],
}
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(config), encoding="utf-8")
out = tmp_path / "out"
command = [
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"run",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config_path),
"--source-report",
str(source_report),
"--out-dir",
str(out),
"--name",
"orchestrator-test",
"--budget-mb",
"5",
]
proc = subprocess.run(command, text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
evidence = json.loads((out / "evidence_manifest.json").read_text(encoding="utf-8"))
assert evidence["status"] == "PASS"
assert any(check["name"] == "cad_source_report" and check["status"] == "PASS" for check in evidence["checks"])
proc = subprocess.run([*command, "--resume"], text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
assert '"status": "SKIP"' in proc.stdout
proc = subprocess.run([*command[:-1], "6", "--resume"], text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
state = json.loads((out / "pipeline_state.json").read_text(encoding="utf-8"))
assert state["steps"]["preview"]["command"][-3:] == ["--budget-mb", "6.0", "--strict"]
def test_mesh_branch_exports_y_up_glb(tmp_path: Path) -> None:
doc = ezdxf.new("R2010")
mesh = doc.modelspace().add_mesh()
with mesh.edit_data() as data:
data.vertices = [(0, 0, 0), (2, 0, 0), (2, 1, 0), (0, 1, 0), (0, 0, 3), (2, 0, 3), (2, 1, 3), (0, 1, 3)]
data.faces = [(0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (3, 7, 4, 0)]
source = tmp_path / "mesh.dxf"
doc.saveas(source)
glb = tmp_path / "mesh.glb"
report = tmp_path / "mesh_report.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "extract_3d_solids.py"),
"--dxf",
str(source),
"--out-glb",
str(glb),
"--report",
str(report),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
data = json.loads(report.read_text(encoding="utf-8"))
assert data["captured_meshes"] == 1
assert data["captured_triangles"] == 12
assert glb.read_bytes()[:4] == b"glTF"
def test_dwg_json_fallback_preserves_blocks_and_inserts(tmp_path: Path) -> None:
payload = {
"insunits": 4,
"layers": [{"name": "WALL", "color": 7}],
"blocks": {
"WINDOW": [
{"t": "LINE", "a": [0, 0], "b": [1000, 0], "layer": "WALL"},
]
},
"entities": [
{"t": "LINE", "a": [0, 0], "b": [5000, 0], "layer": "WALL"},
{"t": "INSERT", "name": "WINDOW", "p": [1000, 0], "layer": "WALL"},
],
}
source = tmp_path / "dump.json"
source.write_text(json.dumps(payload), encoding="utf-8")
out = tmp_path / "rebuilt.dxf"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "dwgjson_to_dxf.py"),
"--json",
str(source),
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
result = json.loads(proc.stdout)
assert result == {"out": str(out), "added": 2, "skipped": 0, "blocks": 1}
rebuilt = ezdxf.readfile(out)
assert "WINDOW" in rebuilt.blocks
assert [entity.dxftype() for entity in rebuilt.modelspace()] == ["LINE", "INSERT"]
def test_site_context_dump_builds_boundary_and_roads(tmp_path: Path) -> None:
payload = {
"entities": [
{
"t": "LWPOLYLINE",
"v": [[100, 200], [120, 200], [120, 215], [100, 215]],
"closed": True,
"layer": "Z2-用地红线",
},
{"t": "LINE", "a": [102, 202], "b": [118, 202], "layer": "Z5-车行道"},
]
}
source = tmp_path / "site_dump.json"
source.write_text(json.dumps(payload), encoding="utf-8")
out = tmp_path / "site_context.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "site_context_from_dump.py"),
"--dump",
str(source),
"--scale",
"1",
"--region",
"95",
"195",
"125",
"220",
"--origin",
"100",
"200",
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
fragment = json.loads(out.read_text(encoding="utf-8"))
assert set(fragment["floors"]) == {"SITE", "ROADS"}
assert fragment["floors"]["SITE"]["footprint"]["polygons"][0][0] == [0, 0]
assert len(fragment["floors"]["ROADS"]["segments"]["floor_lines"]) == 4
assert len(fragment["floors"]["ROADS"]["segments"]["detail_lines"]) == 1

213
tests/test_delivery.py Normal file
View File

@@ -0,0 +1,213 @@
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import showcase_schema # noqa: E402
from test_contracts import minimal_spec # noqa: E402
def run(*args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(list(args), cwd=ROOT, text=True, capture_output=True)
def build_fixture(tmp_path: Path) -> tuple[Path, Path, Path]:
spec = tmp_path / "spec.json"
glb = tmp_path / "model.glb"
metadata = tmp_path / "model_metadata.json"
spec.write_text(json.dumps(minimal_spec()), encoding="utf-8")
proc = run(
sys.executable,
"scripts/spec_to_glb.py",
"--spec",
str(spec),
"--out",
str(glb),
"--metadata-out",
str(metadata),
)
assert proc.returncode == 0, proc.stderr
return spec, glb, metadata
def render_fixture(path: Path) -> None:
image = Image.new("RGB", (640, 480), "white")
draw = ImageDraw.Draw(image)
draw.rectangle((100, 120, 540, 400), fill="#4477aa", outline="black", width=4)
image.save(path)
def source_report_fixture(tmp_path: Path) -> Path:
path = tmp_path / "cad_read_report.json"
path.write_text(
json.dumps(
{
"report_version": 1,
"dxf_sanitized": str(tmp_path),
"gate": {"name": "all_sources_converted_and_readable", "status": "PASS"},
"files": [{"file": "fixture.dxf", "status": "ok", "modelspace_entities": 1}],
}
),
encoding="utf-8",
)
return path
def test_strict_delivery_passes_for_glb_render_and_offline_viewer(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
offline = tmp_path / "viewer.html"
proc = run(
sys.executable,
"scripts/write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
)
assert proc.returncode == 0, proc.stderr
evidence = tmp_path / "evidence.json"
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--offline-viewer",
str(offline),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 0, proc.stderr
report = json.loads(evidence.read_text(encoding="utf-8"))
assert report["status"] == "PASS"
assert any(item["name"] == "offline:payload" and item["status"] == "PASS" for item in report["checks"])
def test_strict_delivery_requires_a_render(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--evidence-out",
str(tmp_path / "evidence.json"),
)
assert proc.returncode == 3
assert "At least one inspected render is required" in proc.stderr
def test_web_writer_and_static_delivery_checks(tmp_path: Path) -> None:
spec, glb, metadata = build_fixture(tmp_path)
web = tmp_path / "web"
proc = run(
sys.executable,
"scripts/write_web_showcase.py",
"--glb",
str(glb),
"--metadata",
str(metadata),
"--out-dir",
str(web),
)
assert proc.returncode == 0, proc.stderr
for relative in ("node_modules/three/build/three.module.js", "node_modules/lucide/dist/umd/lucide.js"):
target = web / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("// test dependency", encoding="utf-8")
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--web-dir",
str(web),
"--evidence-out",
str(tmp_path / "web_evidence.json"),
)
assert proc.returncode == 0, proc.stderr
def test_variants_manifest_requires_metadata_artifact(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
manifest = tmp_path / "variants_manifest.json"
manifest.write_text(
json.dumps(
{
"manifest_version": 1,
"name": "missing-metadata",
"default_key": "standard",
"variants": [
{
"key": "standard",
"label": "standard",
"file": glb.name,
"source_glb": glb.name,
"metadata": "missing_metadata.json",
"spec": spec.name,
}
],
}
),
encoding="utf-8",
)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--source-report",
str(source_report),
"--spec",
str(spec),
"--variants-manifest",
str(manifest),
"--render",
str(render),
"--evidence-out",
str(tmp_path / "evidence.json"),
)
assert proc.returncode == 3
assert "missing_metadata.json" in proc.stderr
def test_schema_validator_rejects_legacy_spec_in_strict_mode() -> None:
legacy = minimal_spec()
legacy.pop("schema_version")
try:
showcase_schema.validate_spec(legacy)
except showcase_schema.ValidationFailure:
return
raise AssertionError("strict validator accepted a spec without schema_version")

File diff suppressed because it is too large Load Diff