Compare commits

..

7 Commits

Author SHA1 Message Date
9d7d3cb973 fix: enforce Revit roof views and orphan geometry gates
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 13:10:04 +08:00
c12d1d57cb fix: close remaining CAD delivery review gaps 2026-07-11 15:26:43 +08:00
6c1336fa59 fix: close audited CAD delivery gate gaps 2026-07-10 15:58:51 +08:00
a761175c09 fix: enforce complete building and offline viewer gates 2026-07-10 14:04:10 +08:00
cab4d320c0 fix: automate GLB compression and real viewport smoke 2026-07-10 13:19:47 +08:00
78ec1fbdcc fix: enforce strict CAD showcase delivery gates 2026-07-10 12:38:12 +08:00
8b1b1d5e89 feat: harden CAD showcase skill and delivery pipeline 2026-07-10 09:21:13 +08:00
55 changed files with 7700 additions and 1410 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

@@ -30,20 +30,28 @@ git clone ... tools/cad-building-showcase # 克隆到项目内任意位置(
```markdown
## CAD → 3D 展示模型
处理 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` 且全绿。
tools/cad-building-showcase/SKILL.md 并遵守其中 Hard Definition of Done:
门禁失败即停下修复,绝不绕过;改动任何脚本后必须跑
`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> --scope-manifest work/<project>/scope_manifest.json --out-dir outputs/<project> --name <project> --backend trimesh --web --offline --resume
```
核心链路:
```
cad_dxf_report.py 读图报告(警告:多框图纸/缓存XREF/陌生图层方言…)
@@ -52,7 +60,7 @@ detect_sheet_frames.py 图框检测(图签块定框、网格投票/墙剖面
derive_showcase_spec.py 按 config 提取 building_spec.json(分簇 footprint/楼板/顶盖)
audit_showcase_extraction.py 硬门禁审计(楼层对齐+跨层基准、幕墙、框收支表、
面积/层数互证…),FAIL 即退出码 3
spec_to_glb.py GLB 生成;write_offline_viewer.py 离线单文件 viewer
spec_to_glb.py GLB 生成;write_offline_viewer.py 离线单文件 viewer(使用 raw GLB)
register_site_outlines.py / massing_from_outline.py / assemble_campus.py
总平面配准(点-边ICP)、无图纸楼体量、厂区装配
```
@@ -60,18 +68,20 @@ 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`(首个案例全程)
- `assets/` Web 模板与离线 viewer 内联库
- `schemas/` extraction config、building spec、variants manifest 的版本化 JSON Schema
- `tests/` 契约/交付测试 + 合成 DXF 全链路回归
- `references/` 当前运行规范;历史复盘移到 `docs/history/`,不再作为 Agent 运行上下文
- `assets/` Web 模板与离线 viewer 内联库;离线交付必须通过真实 `file://` 浏览器 smoke
`work/`、`outputs/`、源 CAD 均不入库(见 `.gitignore`),由脚本从源数据再生。
## 验证纪律
```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`。

312
SKILL.md
View File

@@ -1,212 +1,168 @@
---
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;
- `scope_manifest.json` accounting for every requested building and the site;
- `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. If the source report finds two or more plan identities in one drawing, `--frames` is mandatory; do not let `frame_ledger` become `NOT_APPLICABLE`.
- Treat detector clips as proposals. If Revit views share world coordinates, keep the detector's per-floor `include_block_names` plus top-level `expand_block_names`; clips alone cannot separate overlapping views. For non-Revit overlap, split by title/wall clusters. Area and cross-floor gates must pass before modeling.
- Keep `屋面平面图` (`RF`) and `机房小屋面` (`PH`) as distinct source identities. One overlapping RF clip may not satisfy both; resolve their view-suffixed blocks, heights, and roof-cap roles from the drawing evidence.
- Model each building separately before campus assembly.
- For multi-building/campus requests, write `scope_manifest.json` before modeling. Copy every requested building ID from the user/source inventory; never shrink scope to the easiest drawing set.
- 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> --scope-manifest <scope_manifest.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.
- Treat applicable audit `WARN`/`SKIP` as `BLOCKED`, not success. `NOT_APPLICABLE` means the optional check was not armed and is non-blocking. Continue past WARN/SKIP only with an explicit `--waiver 'audit:<gate>=<evidence-based reason>'`; retain it in final evidence.
- A waiver must be explicitly approved by the user. The Agent must not invent one, and must never use one when the user says “no waivers/不要豁免”.
- Search all source sheets for economic-index tables, storey labels, and elevation ladders before declaring area/storey evidence absent. If a typical plan represents repeated floors, instantiate the source-supported repetitions; a final full-building model may not jump from F2 directly to F16.
- Open the SVG overlays. Iterate if red/unclassified geometry forms walls, glazing, columns, beams, grids, stairs, slabs, roofs, or whole building wings.
- Resolve every `disconnected_footprints` failure. A small remote polygon is usually a leaked sheet component that becomes a floating fin; only record `allowed_disconnected_footprints` when the source visibly proves a legitimate detached stair/canopy and include the reason.
- Treat every geometry-loss warning from derive (`isolated_cluster`, `unsupported_roof`, `floor_order`, `topless_group`) as a stop condition. Tune the config or restore/model the geometry; do not accept a successful exit code with these warnings.
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, use `cad_showcase.py run --web`; it Draco-compresses Trimesh GLBs, starts a temporary local server, runs `web_smoke_test.mjs` at real 1440×900 and 390×844 viewports, and feeds the report to final verification automatically.
- For `--offline`, the pipeline embeds the retained uncompressed `standard.raw.glb`, opens `viewer.html` through a real `file://` Chromium page, and records `offline_browser_smoke_report.json`. Never embed a Draco GLB in the r147 offline viewer unless a matching offline decoder is bundled and tested.
- 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 by the Agent. `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. Detection warnings are internal work signals, not a human approval queue: only ask the user when the drawing itself lacks the source/XREF or two materially different interpretations remain after all deterministic checks.
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. A reasoned partial `WARN` is usable only with a user-approved `cad_source_report` waiver and must remain visible in evidence.
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`; `--frames` is mandatory when the source reports multiple plan identities, and every detected frame key and required block selector is mapped one-to-one or appears in `discarded_frames` with a reason. `RF` and `PH` cannot satisfy each other merely because their clips overlap.
5. A required single-building/campus `scope_manifest.json` matches the requested scope and its artifacts exist.
6. Numbered floors are vertically continuous; representative typical-floor drawings are repeated into source-supported storeys instead of leaving large empty gaps.
7. Audit exits 0 and every gate is `PASS`; `WARN`/`SKIP` block delivery unless a named, user-approved waiver is recorded in evidence.
8. Derive emits no `WARNING topless_group`; GLB build emits no `WARNING mesh_from_polygons`.
9. Campus output contains every requested building and the site as `PASS`, with existing artifacts; a `BLOCKED` entry means the campus request is not complete.
10. Campus output has proven transforms, no unexplained overlap, numeric neighbour gaps, boundary containment, and a top-view placement image.
11. `disconnected_footprints` passes; iso/front/side/plan review shows no floating fins, orphan slabs, duplicated roof volumes, or unexplained detached geometry.
12. `verify_delivery.py` writes `evidence_manifest.json` with overall `PASS`; `BLOCKED`/`FAIL` must never be described as complete, and a human has looked at the render.
13. Served Web delivery includes a passing desktop/mobile browser smoke report whose viewport checks prove 1440×900 and 390×844. If Chromium cannot run, report `BLOCKED`; do not substitute the offline viewer for the requested Web template.
14. Offline delivery includes a passing `file://` browser smoke report proving the readiness marker, canvas, and first render; an embedded payload check alone is insufficient.
15. 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), and for Revit exports it automatically falls back to floor identities encoded in INSERT names when title-block text sits at paper coordinates. It 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. `AMBIGUOUS overlapping inferred frames` must be resolved by the CAD Agent with cross-floor overlays and an explicit keep/discard reason in the config; it is not a user-facing soft warning and must not be modeled twice blindly. 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 --scope-manifest work/<project>/scope_manifest.json --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/`.
- Start each independent attempt in a new project directory. Reusing a prior directory requires an explicit user request and a recorded provenance note.
- 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`
## 一、错误原因诊断

51
package-lock.json generated
View File

@@ -4,11 +4,15 @@
"requires": true,
"packages": {
"": {
"name": "cad-building-showcase",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
"@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 +562,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 +636,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,14 @@
{
"name": "cad-building-showcase",
"private": true,
"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 scripts/offline_viewer_smoke.mjs && node --check tools/compress.mjs",
"smoke:web": "node scripts/web_smoke_test.mjs",
"smoke:offline": "node scripts/offline_viewer_smoke.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,75 @@
# Campus and Multi-Building Workflow
## Contents
1. Branch selection
2. Scope contract
3. Placement evidence
4. Site outlines and missing buildings
5. Assembly gates
6. 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.
## Scope Contract
Before modeling, write `scope_manifest.json` from the user request and source inventory. Do not derive requested scope from whichever config or GLB happened to succeed. Minimum shape:
```json
{
"scope_version": 1,
"mode": "campus",
"requested": ["1#", "2#", "3#"],
"buildings": [
{"id": "1#", "status": "PASS", "artifacts": ["../../outputs/1/model.glb"]},
{"id": "2#", "status": "BLOCKED", "reason": "unresolved XREF", "artifacts": []}
],
"site": {"status": "PASS", "artifacts": ["../../outputs/site_top.png", "../../outputs/campus.glb"]}
}
```
Every `requested` ID must have exactly one ledger entry and there may be no unrequested extras. `PASS` requires at least one verifiable model artifact: a GLB with mesh primitives, a Blender file with a valid header, or a schema-valid `building_spec.json`; an arbitrary non-empty text/JSON file does not satisfy scope. Campus site evidence must include a valid model or readable image. Relative paths resolve from the scope manifest's directory. `BLOCKED` requires a concrete reason and makes the overall campus result `BLOCKED`, not complete. Feed the ledger to `cad_showcase.py run --scope-manifest ...` or `verify_delivery.py --scope-manifest ...`.
## 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.
Do not classify a small gap from distance alone. Corroborate a 0.15-0.30m attached-building/expansion-joint interpretation with the neighbour roof shown on the subject building's roof plan and matching floor elevations. A negative gap is always a placement error. A multi-metre hypothesis that pushes either building through the red line is also wrong.
`--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. On macOS the command shape is `ODAFileConverter <abs_in_dir> <abs_out_dir> ACAD2004 DXF 0 1 "*.dwg"`; create both directories first. Bad arguments are often reported only through a GUI dialog, with empty stderr, and the process may return exit 0 while producing nothing. Treat “exit 0 + no DXF” as failure, check the screen for a blocked dialog, and keep the script's ASCII staging plus produced-file verification.
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,68 @@
# 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.
The detector emits sheet-level proposals. Two different plan titles can sit inside one title-block/frame INSERT and therefore receive the same broad clip (for example `一层平面图` plus `夹层平面图`, or `二层平面图` plus `十六层平面图`). Never duplicate that shared clip across floors. Split it at the wall-cluster gap between title positions, then recompute each floor offset. Use independent declared area/storey evidence to prove the split; a roughly 2× footprint is the characteristic failure signal.
## 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, exceeds declared area, or contains distant sliver polygons. Tighten both X/Y clip bands or use evidence-backed isolated-cluster filtering; do not simply raise noise thresholds until the artifact disappears. Inspect the final browser screenshot too: repeated floating strips at every storey usually mean off-envelope plan symbols survived the clip.
## 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 脚本与模板的具体改进建议。修复均已在该项目落地验证。
---
@@ -68,7 +78,7 @@ CAD 把幕墙画成稀疏分格板(实测 8F:1.42m 板 / 每 4.5m 一块 /
### 3.3 柱头封顶(比 `shorten_unsupported_columns` 更好)
现有的“无支撑柱缩短”会产生突兀的 1.2m 矮柱。更自然的做法是**生成盖板**:
- 地上退台层:`cap = 本层footprint(外扩~1.3m) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。外扩是为了盖住凹包络切掉的外圈柱廊柱。
- 地上退台层:`cap = 本层footprint(外扩cap_buffer) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。普通立面默认 `0.1m`;A208 的外圈柱廊有图纸佐证,才显式使用约 `1.3m`。
- **地下室顶层**:直接把整层 footprint 在 z=0 封成地面/顶板(停车区上方的地坪)。
- 顶层(8F)/辅楼顶:用现有 `roof_specs` 屋顶盖。

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,12 +172,27 @@ 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.
Use `clip` rectangles for irregular sheet layouts. Use `split_x` plus `side` when a sheet cleanly places plans left/right; this is less likely to accidentally cut off geometry than a tight clip rectangle.
Arm cross-evidence checks whenever the drawings contain the evidence:
- Copy per-floor areas from the 经济技术指标表/area labels into `declared_areas_m2`; use `declared_area_tolerance` only for a justified source convention. A model area off by roughly 100% usually means two plans or two wings were swallowed into one clip, not balcony noise.
- Copy the above-ground count from 总图 labels or elevation/section ladders into `expected_storeys_above_ground`. When one typical plan represents a range, instantiate those floors and record that they are source-supported repetitions.
- Pass every frame-detector config through `--frames`; list deliberately unused frames in `discarded_frames` with reasons.
These checks report `NOT_APPLICABLE` when no independent evidence exists. That is not proof of correctness; document what was searched before leaving them unarmed.
Keep `expand_blocks` false for the first pass. If the audit shows important geometry in `INSERT`, set `expand_blocks` to `true` or to a list of block-name patterns, then rerun extraction/audit/overlays. When virtual block entities live on layer `0`, `block_insert_layer_fallback: true` lets the parent INSERT layer participate in category matching.
## 5. Spec Extraction
@@ -181,6 +211,7 @@ Review `building_spec.json` before rendering:
- Segment counts are not dominated by dimensions/hatches/annotations.
- Footprint polygons exist when slabs/roofs are meant to follow CAD floor plates.
- `default_disabled_categories` does not hide `slab` for presentation/digital-twin views.
- Generated cap edges do not protrude as slab fins. `cap_buffer` defaults to `0.1m` for ordinary facade-aligned floors. Set it explicitly around `1.3m` only for evidenced colonnade/overhang cases such as A208, then confirm front/side views.
## 6. Agent Audit and Overlay Review
@@ -216,6 +247,7 @@ Agent review rules:
- If frequent blocks appear in the audit, inspect block names and decide whether to recursively explode block geometry.
- If hatches carry wall/slab/column information, do not rely only on line extraction.
- Continue only when missing geometry is acceptable for the requested output level.
- A floor can be internally self-consistent yet occupy the wrong repeated slot. If wall-profile correlation finds a strong non-zero shift, treat it as the 13号 F3 “错槽” pattern and correct the frame offset rather than trusting envelope centers.
## 7. Blender Generation
@@ -297,10 +329,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,78 @@
# 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 backends retain a decoder-free `.raw.glb` for offline embedding. The Trimesh branch then runs `tools/compress.mjs` (weld, dedup, prune, Draco), while the Blender branch performs a second Blender Draco export for each delivered `.glb`. `verify_showcase.py --strict` must see `draco=True` and every delivered variant within the size budget.
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 **uncompressed** GLB. The Trimesh pipeline therefore uses retained `standard.raw.glb`; passing a Draco GLB is a hard error because this offline bundle intentionally has no Draco decoder.
`cad_showcase.py run --offline` automatically opens the result via `file://` in Chromium and writes `offline_browser_smoke_report.json` plus a screenshot. For a manual/custom delivery, run `offline_viewer_smoke.mjs` and pass its report to `verify_delivery.py --offline-browser-report`. Decoding the base64 payload is not proof that GLTFLoader can render it.
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
`cad_showcase.py run --web` performs this gate automatically. For a manual/custom delivery, 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 real 1440×900/390×844 viewport dimensions, desktop/mobile control visibility, console/page/request failures, and idle render behavior. Feed the report to final verification with `--browser-report`. Supplying `--web-dir` makes the report mandatory: no report is `BLOCKED`, never PASS.
The verifier validates the report contract, not just its top-level `status`: all required named checks must exist and be PASS, viewport details must match exactly, and console/page/request arrays must be present and empty. A hand-written `{status: PASS}` report is invalid.
When an execution tool already has a `run_in_background` option, launch `python3 -m http.server ...` as the foreground command of that background process. Do not append shell `&`; the child server can die with the wrapper. Before presenting the viewer, probe the URL and keep that server process alive. Present the formal `web/index.html` URL when Web was requested; `viewer.html` is a separate offline fallback, not a substitute.
## 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 \
--audit outputs/<project>/extraction_audit.json --require-audit \
--scope-manifest work/<project>/scope_manifest.json --require-scope-manifest \
--variants-manifest outputs/<project>/delivery/variants_manifest.json \
--web-dir outputs/<project>/web \
--offline-viewer outputs/<project>/viewer.html \
--offline-browser-report outputs/<project>/offline_browser_smoke_report.json \
--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, audit gates, scope artifacts, GLB headers/mesh structure/naming/budgets, render dimensions/foreground occupancy/noise, Web assets/placeholders/features/variants, offline payload, offline `file://` browser load, and served-Web browser report. Only overall `PASS` is complete. Applicable `WARN`/`SKIP` produce overall `BLOCKED` unless the exact check has an explicit `--waiver 'CHECK=REASON'`; `NOT_APPLICABLE` is recorded but non-blocking, and `FAIL` cannot be waived.

View File

@@ -1,7 +1,15 @@
# 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
presentation quality. Apply AFTER the geometry passes the Hard Definition
of Done — polish never excuses a wrong model. Each item names the code to
touch. Ordered by value-per-effort.
@@ -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

7
requirements-core.txt Normal file
View File

@@ -0,0 +1,7 @@
ezdxf>=1.4,<2
jsonschema>=4.20,<5
mapbox-earcut>=1.0,<2
numpy>=1.26,<3
scipy>=1.13,<2
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,192 @@
{
"$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
}
},
"allowed_disconnected_footprints": {
"type": "array",
"items": {
"type": "object",
"required": ["floor_key", "reason"],
"properties": {
"floor_key": {"type": "string", "minLength": 1},
"reason": {"type": "string", "minLength": 1}
},
"additionalProperties": false
}
},
"layers": {"$ref": "#/$defs/patternMap"},
"categories": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"label": {"type": "string", "minLength": 1},
"color": {"type": "string", "minLength": 1}
},
"additionalProperties": false
}
},
"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"},
"include_block_names": {"$ref": "#/$defs/stringList"},
"exclude_block_names": {"$ref": "#/$defs/stringList"}
},
"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"},
"include_block_names": {"$ref": "#/$defs/stringList"},
"exclude_block_names": {"$ref": "#/$defs/stringList"},
"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 = {
@@ -48,8 +49,8 @@ def parse_args() -> argparse.Namespace:
nargs="*",
default=None,
help="detect_sheet_frames out-config JSON(s): enables the frame-ledger gate "
"(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)",
"(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)",
)
return parser.parse_args()
@@ -87,10 +88,7 @@ def block_layer_unit_lengths(doc, name: str, max_chord: float, max_depth: int, d
for layer, length in block_layer_unit_lengths(doc, inner_name, max_chord, max_depth, depth + 1).items():
totals[layer] += length * factor
else:
length = sum(
segment_length_source(segment)
for segment in derive.entity_segments(inner, max_chord)
)
length = sum(segment_length_source(segment) for segment in derive.entity_segments(inner, max_chord))
if length > 0:
totals[derive.entity_layer(inner)] += length
result = dict(totals)
@@ -141,7 +139,8 @@ def inspect_entity(
"supported_length": supported_length,
"sample": sample,
"high_risk": dxftype in HIGH_RISK_TYPES,
"insert_name": block_name or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
"insert_name": block_name
or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
}
@@ -168,15 +167,17 @@ def spec_counts(spec: dict[str, Any]) -> dict[str, dict[str, int]]:
categories = [key for key in spec.get("categories", {}) if key != "slab"]
result = {}
for floor_key, floor in spec.get("floors", {}).items():
result[floor_key] = {
category: len(floor.get("segments", {}).get(category, []))
for category in categories
}
result[floor_key] = {category: len(floor.get("segments", {}).get(category, [])) for category in categories}
return result
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path,
frames: list[dict[str, Any]] | None = None) -> dict[str, Any]:
def audit(
dxf_dir: Path,
config: dict[str, Any],
spec: dict[str, Any],
vendor_dir: Path,
frames: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -232,9 +233,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
sx = abs(float(source_entity.dxf.get("xscale", 1.0) or 1.0))
sy = abs(float(source_entity.dxf.get("yscale", 1.0) or 1.0))
factor = (sx + sy) / 2.0
unit_lengths = block_layer_unit_lengths(
doc, insert_name, max_chord, max_block_depth
)
unit_lengths = block_layer_unit_lengths(doc, insert_name, max_chord, max_block_depth)
for inner_layer, unit_length in unit_lengths.items():
inner_length = unit_length * factor
if inner_length <= 0:
@@ -343,9 +342,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"coverage": {
"supported_length_meters": round(total_supported * scale, 3),
"classified_supported_length_meters": round(classified_supported * scale, 3),
"supported_length_coverage": round(classified_supported / total_supported, 4)
if total_supported
else None,
"supported_length_coverage": round(classified_supported / total_supported, 4) if total_supported else None,
"block_locked_length_meters": round(block_locked_total * scale, 3),
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
@@ -390,9 +387,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
xs = [v for s in walls for v in (s["start"][0], s["end"][0])]
ys = [v for s in walls for v in (s["start"][1], s["end"][1])]
size = max(max(xs) - min(xs), max(ys) - min(ys))
groups[derive._cap_floor_group(fk, config)].append(
(fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size)
)
groups[derive._cap_floor_group(fk, config)].append((fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size))
worst: tuple[float, str] | None = None
for grp, items in groups.items():
if len(items) < 2:
@@ -402,7 +397,10 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for j in range(i + 1, len(items)):
dist = math.hypot(items[i][1] - items[j][1], items[i][2] - items[j][2])
if dist > limit and (worst is None or dist > worst[0]):
worst = (dist, f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})")
worst = (
dist,
f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})",
)
if worst:
return {
"name": "floors_aligned",
@@ -432,16 +430,15 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for grp, keys in by_group.items():
if len(keys) < 2:
continue
ref_key = max(keys, key=lambda k: sum(
math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_key = max(keys, key=lambda k: sum(math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4)
ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4)
def zero_cov(ref_prof, prof, tol: float = 0.25) -> float:
total = sum(w for _, w in prof)
if total <= 0:
return 0.0
matched = sum(w for p, w in prof
if any(abs(p - rp) <= tol for rp, _ in ref_prof))
matched = sum(w for p, w in prof if any(abs(p - rp) <= tol for rp, _ in ref_prof))
return matched / total
for fk in keys:
@@ -455,8 +452,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
# let any small profile "match" somewhere: 27号 1#A PH)
if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov:
continue
if (shift is not None and cov >= 0.45 and ratio >= 1.5
and abs(shift) > 1.0):
if shift is not None and cov >= 0.45 and ratio >= 1.5 and abs(shift) > 1.0:
return {
"name": "floors_aligned",
"status": "FAIL",
@@ -475,32 +471,44 @@ 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:
status, detail = "SKIP", "No curtain-wall/glazing evidence in blocks or block names."
status, detail = "NOT_APPLICABLE", "No curtain-wall/glazing evidence in blocks or block names."
elif spec_glazing_segments > 0:
status = "PASS"
detail = (
@@ -560,6 +568,8 @@ def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[st
}
)
gates.append(frame_ledger_gate(config, frames))
gates.append(disconnected_footprints_gate(spec, config))
gates.append(vertical_storey_continuity_gate(spec))
gates.append(declared_area_gate(spec, config))
gates.append(storey_count_gate(spec, config))
return gates
@@ -586,8 +596,11 @@ 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": "NOT_APPLICABLE",
"detail": "No --frames given; frame ledger is not armed for this project.",
}
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 []:
@@ -598,18 +611,30 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
for drawing in fcfg.get("drawings", []) or []:
file = str(drawing.get("file", ""))
cfg_floors = cfg_by_file.get(file, [])
used_cfg: set[int] = set()
for frame in drawing.get("floors", []) or []:
total += 1
name = str(frame.get("name", ""))
key = str(frame.get("key", ""))
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
):
matches = [
index
for index, floor in enumerate(cfg_floors)
if index not in used_cfg
and str(floor.get("key", "")) == key
and set(frame.get("include_block_names", []) or []).issubset(
set(floor.get("include_block_names", []) or [])
)
and clip
and floor.get("clip")
and _rect_overlap_ratio(clip, floor["clip"]) >= 0.3
]
if matches:
used_cfg.add(matches[0])
continue
unaccounted.append(f"{file}: {frame.get('key', '?')} {name}")
unaccounted.append(f"{file}: {key or '?'} {name}")
if unaccounted:
shown = "; ".join(unaccounted[:12]) + (" …" if len(unaccounted) > 12 else "")
return {
@@ -621,8 +646,98 @@ 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 _polygon_area(points: list[list[float]]) -> float:
if len(points) < 3:
return 0.0
return (
abs(
sum(
float(points[index][0]) * float(points[(index + 1) % len(points)][1])
- float(points[(index + 1) % len(points)][0]) * float(points[index][1])
for index in range(len(points))
)
)
/ 2.0
)
def _polygon_bounds(points: list[list[float]]) -> list[float]:
xs = [float(point[0]) for point in points]
ys = [float(point[1]) for point in points]
return [min(xs), min(ys), max(xs), max(ys)]
def _bounds_gap(a: list[float], b: list[float]) -> float:
dx = max(0.0, max(a[0] - b[2], b[0] - a[2]))
dy = max(0.0, max(a[1] - b[3], b[1] - a[3]))
return math.hypot(dx, dy)
def disconnected_footprints_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""Reject small, remote footprint islands unless they are explained.
A stray but substantial curtain-wall/component cluster can survive the
line-level isolated-cluster filter and become a tall floating fin. The
generated footprint exposes it deterministically. Legitimate detached
stairs/canopies must be acknowledged with a floor key and reason.
"""
allowed = {
str(item.get("floor_key", ""))
for item in config.get("allowed_disconnected_footprints", []) or []
if isinstance(item, dict) and str(item.get("reason", "")).strip()
}
problems: list[str] = []
checked = 0
for floor_key, floor in spec.get("floors", {}).items():
polygons = [
polygon
for polygon in (floor.get("footprint") or {}).get("polygons", []) or []
if isinstance(polygon, list) and len(polygon) >= 3
]
if len(polygons) < 2 or str(floor_key) in allowed:
continue
checked += 1
measured = sorted(
[(_polygon_area(polygon), _polygon_bounds(polygon)) for polygon in polygons],
key=lambda item: item[0],
reverse=True,
)
main_area, main_bounds = measured[0]
if main_area <= 0:
continue
for area, bounds in measured[1:]:
ratio = area / main_area
gap = _bounds_gap(main_bounds, bounds)
if ratio < 0.05 and gap > 2.0:
problems.append(
f"{floor_key}: {area:.1f} m² island is {ratio:.1%} of the main footprint and {gap:.1f} m away"
)
if problems:
return {
"name": "disconnected_footprints",
"status": "FAIL",
"detail": (
"Small remote footprint islands would render as floating/orphan building parts: "
+ "; ".join(problems)
+ ". Fix the clip/layer/block mapping, or document a legitimate detached element in "
"allowed_disconnected_footprints with floor_key and reason."
),
}
return {
"name": "disconnected_footprints",
"status": "PASS",
"detail": (
f"No unexplained small remote footprint islands across {len(spec.get('floors', {}))} floor(s)"
+ (f" ({checked} multi-component floor(s) checked)." if checked else ".")
),
}
def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -635,8 +750,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": "NOT_APPLICABLE",
"detail": "No declared_areas_m2 in config; area cross-check is not armed.",
}
tol = float(config.get("declared_area_tolerance", 0.15))
problems = []
for key, want in declared.items():
@@ -649,19 +767,80 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
if got <= 0:
problems.append(f"{key}: no footprint area in spec")
elif abs(got - want) / want > tol:
problems.append(f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)")
problems.append(
f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)"
)
if problems:
return {
"name": "area_declared",
"status": "FAIL",
"detail": ("Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."),
"detail": (
"Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."
),
}
return {"name": "area_declared", "status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values."}
return {
"name": "area_declared",
"status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values.",
}
def vertical_storey_continuity_gate(spec: dict[str, Any]) -> dict[str, Any]:
"""A final full-building model may not jump from F2 directly to F16.
Representative typical-floor drawings are source evidence, not permission
to leave the repeated storeys absent from the delivered building. The
repeated floors must be instantiated and labelled as derived repetitions.
"""
import re as _re
numbered: list[tuple[int, str, dict[str, Any]]] = []
for key, floor in spec.get("floors", {}).items():
match = _re.fullmatch(r"F(\d+)", str(key))
if match:
numbered.append((int(match.group(1)), str(key), floor))
numbered.sort()
if len(numbered) < 2:
return {
"name": "vertical_storey_continuity",
"status": "PASS",
"detail": f"{len(numbered)} numbered storey; no internal continuity gap to test.",
}
missing: list[str] = []
z_gaps: list[str] = []
for (left_no, left_key, left), (right_no, right_key, right) in zip(numbered, numbered[1:]):
if right_no != left_no + 1:
missing.append(f"{left_key}->{right_key}")
continue
left_z = float(left.get("z", 0.0))
right_z = float(right.get("z", 0.0))
nominal = max(float(left.get("height", 0.0)), float(right.get("height", 0.0)), 1.0)
if right_z - left_z > max(8.0, nominal * 2.0):
z_gaps.append(f"{left_key}->{right_key}={round(right_z - left_z, 2)}m")
if missing or z_gaps:
parts = []
if missing:
parts.append("missing numbered ranges " + ", ".join(missing))
if z_gaps:
parts.append("unexplained elevation gaps " + ", ".join(z_gaps))
return {
"name": "vertical_storey_continuity",
"status": "WARN",
"detail": (
"; ".join(parts)
+ ". Instantiate source-supported repeated typical floors; do not deliver separated floor islands."
),
}
return {
"name": "vertical_storey_continuity",
"status": "PASS",
"detail": f"Numbered storeys are contiguous from {numbered[0][1]} to {numbered[-1][1]}.",
}
def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -672,20 +851,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": "NOT_APPLICABLE",
"detail": "No expected_storeys_above_ground in config; count cross-check is not armed.",
}
import re as _re
actual = sum(1 for k in spec.get("floors", {}) if _re.fullmatch(r"F\d+", str(k)))
if actual != int(expected):
return {
"name": "storey_count",
"status": "FAIL",
"detail": (f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."),
"detail": (
f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."
),
}
return {"name": "storey_count", "status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count."}
return {
"name": "storey_count",
"status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count.",
}
def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]:
@@ -727,11 +915,15 @@ def markdown(report: dict[str, Any]) -> str:
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
"(modelspace linework only — block-locked geometry is NOT in this denominator)",
*([
f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over "
f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — "
"on multi-frame sheets judge extraction by THIS number, not the file-global one"
] if coverage.get("clipped_supported_length_coverage") is not None else []),
*(
[
f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over "
f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — "
"on multi-frame sheets judge extraction by THIS number, not the file-global one"
]
if coverage.get("clipped_supported_length_coverage") is not None
else []
),
f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",
@@ -765,14 +957,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 +971,12 @@ def main() -> int:
args = parse_args()
config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
try:
config = showcase_schema.validate_config(config, Path(args.dxf_dir))
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
frames = None
if args.frames:
frames = [json.loads(Path(p).read_text(encoding="utf-8")) for p in args.frames]

View File

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

View File

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

View File

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

View File

@@ -8,6 +8,7 @@ import glob
import fnmatch
import json
import os
import re
import shutil
import subprocess
import sys
@@ -24,7 +25,17 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--work", default="work/cad_showcase", help="Intermediate work folder")
parser.add_argument("--output", default="outputs/cad_read_report", help="Output path stem or folder")
parser.add_argument("--vendor-dir", default="work/vendor", help="Optional Python vendor dir containing ezdxf")
parser.add_argument("--no-convert", action="store_true", help="Skip DWG conversion and only read existing DXF files")
parser.add_argument(
"--no-convert", action="store_true", help="Skip DWG conversion and only read existing DXF files"
)
parser.add_argument(
"--converter",
choices=("auto", "libredwg", "oda"),
default="auto",
help="auto=libredwg then ODA fallback; choose oda explicitly for 3DSOLID/ACIS drawings",
)
parser.add_argument("--allow-partial", action="store_true", help="Write a partial report instead of failing")
parser.add_argument("--partial-reason", help="Required justification when --allow-partial is used")
return parser.parse_args()
@@ -36,8 +47,7 @@ def import_ezdxf(vendor_dir: Path):
from ezdxf import bbox, recover # type: ignore
except ImportError as exc:
raise SystemExit(
"Missing dependency: ezdxf. Install locally with:\n"
f" python3 -m pip install --target {vendor_dir} ezdxf"
f"Missing dependency: ezdxf. Install locally with:\n python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
return ezdxf, bbox, recover
@@ -54,10 +64,7 @@ def safe_name(path: Path, used: set[str]) -> str:
def find_cad_files(input_dir: Path) -> list[Path]:
return sorted(
path for path in input_dir.rglob("*")
if path.is_file() and path.suffix.lower() in CAD_SUFFIXES
)
return sorted(path for path in input_dir.rglob("*") if path.is_file() and path.suffix.lower() in CAD_SUFFIXES)
def run_dwg2dxf(source: Path, dest: Path) -> dict:
@@ -129,7 +136,8 @@ def run_oda_batch(sources: list[Path], work_dir: Path) -> dict[Path, Path]:
try:
subprocess.run(
[exe, str(in_dir.resolve()), str(out_dir.resolve()), "ACAD2018", "DXF", "0", "1", "*.dwg"],
capture_output=True, timeout=1800,
capture_output=True,
timeout=1800,
)
except (subprocess.TimeoutExpired, OSError):
return {}
@@ -240,13 +248,11 @@ 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"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
PLAN_TITLE_EXCLUDE_LAYERS = ("*图签*", "*PUB_TAB*", "*TTLB*", "*TK*", "*图框*", "*目录*")
CAD_TEXT_FORMAT_RE = _re.compile(r"\\[LlOoKk]|%%[UuOoKk]")
FLOOR_TOKEN_RE = _re.compile(
CAD_TEXT_FORMAT_RE = re.compile(r"\\[LlOoKk]|%%[UuOoKk]")
FLOOR_TOKEN_RE = re.compile(
r"机房小屋面|机房屋面|"
r"地下[一二三四五六七八九十\d]+层夹层|"
r"地下[一二三四五六七八九十\d]+层|"
@@ -258,7 +264,7 @@ FLOOR_TOKEN_RE = _re.compile(
# 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"}
@@ -266,7 +272,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:
@@ -292,7 +298,7 @@ def floor_identities(label: str) -> list[tuple[str, str]]:
head = label[:-3]
matches = list(FLOOR_TOKEN_RE.finditer(head))
tokens = [match.group(0) for match in matches]
qualifier = _re.sub(r"[、,,\s]+$", "", head[:matches[0].start()]) if matches else ""
qualifier = re.sub(r"[、,,\s]+$", "", head[: matches[0].start()]) if matches else ""
if len(qualifier) > 12:
qualifier = ""
out = []
@@ -347,8 +353,7 @@ def count_plan_titles(entities) -> int:
# a sheet-title block may add ``主楼`` while families remain unqualified.
# Count that as one frame, but retain two genuinely different qualified
# buildings that both contain (say) an F1 plan in the same modelspace.
return sum(max(1, len({q for q in qualifiers if q}))
for qualifiers in floor_qualifiers.values())
return sum(max(1, len({q for q in qualifiers if q})) for qualifiers in floor_qualifiers.values())
def insert_block_content(doc, entities) -> list[dict]:
@@ -391,11 +396,14 @@ def file_warnings(item: dict) -> list[str]:
# pipeline has never seen — the layer mapping must be built consciously,
# or extraction silently captures nothing (patterns age, invariants don't).
wall_dialects = ("*WALL*", "*墙*", "*QIANG*")
layer_names = [l["name"] for l in item.get("layers", []) if l.get("entity_count", 0) > 0]
if (plan_titles >= 1 and (entities or 0) >= 400
and layer_names
and not any(fnmatch.fnmatch(n.upper(), p.upper()) for n in layer_names for p in wall_dialects)):
tops = ", ".join(l["name"] for l in item.get("top_layers", [])[:8])
layer_names = [layer["name"] for layer in item.get("layers", []) if layer.get("entity_count", 0) > 0]
if (
plan_titles >= 1
and (entities or 0) >= 400
and layer_names
and not any(fnmatch.fnmatch(n.upper(), p.upper()) for n in layer_names for p in wall_dialects)
):
tops = ", ".join(layer["name"] for layer in item.get("top_layers", [])[:8])
warnings.append(
f"unknown_layer_dialect: {plan_titles} plan title(s) but no wall-like layer "
f"(*WALL*/*墙*) among {len(layer_names)} populated layers — an unfamiliar design-institute "
@@ -441,11 +449,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.
@@ -476,10 +480,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,
@@ -506,12 +507,14 @@ def markdown_report(results: list[dict], conversions: list[dict], input_dir: Pat
for file_name, warning in all_warnings:
lines.append(f"- `{file_name}`: {warning}")
lines.append("")
lines.extend([
"## Files",
"",
"| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |",
"| --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
])
lines.extend(
[
"## Files",
"",
"| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |",
"| --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
]
)
for item in results:
bbox_data = item.get("bbox") or {}
size = bbox_data.get("size", ["", "", ""])
@@ -577,21 +580,43 @@ def main() -> int:
if not input_dir.exists():
raise SystemExit(f"Input folder not found: {input_dir}")
if args.allow_partial and not (args.partial_reason or "").strip():
raise SystemExit("--allow-partial requires --partial-reason")
# These folders are generated intermediates. Recreate them so a source
# removed between runs cannot survive as a stale DXF and enter modeling.
shutil.rmtree(raw_dir, ignore_errors=True)
shutil.rmtree(clean_dir, ignore_errors=True)
raw_dir.mkdir(parents=True, exist_ok=True)
clean_dir.mkdir(parents=True, exist_ok=True)
cad_files = find_cad_files(input_dir)
used_names: set[str] = set()
conversions: list[dict] = []
raw_dxfs: list[Path] = []
for source in find_cad_files(input_dir):
dest = raw_dir / safe_name(source, used_names)
assigned = [(source, raw_dir / safe_name(source, used_names)) for source in cad_files]
oda_outputs: dict[Path, Path] = {}
if args.converter == "oda" and not args.no_convert:
oda_outputs = run_oda_batch(
[source for source, _dest in assigned if source.suffix.lower() == ".dwg"],
work_dir,
)
for source, dest in assigned:
if source.suffix.lower() == ".dwg":
if args.no_convert:
continue
conversion = run_dwg2dxf(source, dest)
if args.converter == "oda":
produced = oda_outputs.get(source)
if produced:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(produced, dest)
conversion = {"source": str(source), "dest": str(dest), "status": "oda_ok"}
else:
conversion = {"source": str(source), "dest": str(dest), "status": "oda_failed"}
else:
conversion = run_dwg2dxf(source, dest)
conversions.append(conversion)
if conversion["status"] == "ok":
if conversion["status"] in {"ok", "oda_ok"}:
raw_dxfs.append(dest)
else:
if source.resolve() != dest.resolve():
@@ -626,7 +651,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)
@@ -653,17 +678,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

846
scripts/cad_showcase.py Normal file
View File

@@ -0,0 +1,846 @@
#!/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 os
import shutil
import socket
import subprocess
import sys
import time
import urllib.request
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
from delivery_waivers import apply_waivers, parse_waivers
ROOT = Path(__file__).resolve().parent.parent
SCRIPTS = ROOT / "scripts"
def now() -> str:
return datetime.now(timezone.utc).isoformat()
DERIVE_FORBIDDEN_WARNINGS = (
"WARNING isolated_cluster",
"WARNING unsupported_roof",
"WARNING floor_order",
"WARNING topless_group",
)
def fingerprint(
config: Path,
source_report: Path,
dxf_dir: Path,
extra_inputs: tuple[Path, ...] = (),
) -> str:
"""Hash source data and pipeline code so resume cannot reuse stale work."""
digest = hashlib.sha256()
tracked = [config, source_report, *extra_inputs, *sorted(dxf_dir.glob("*.dxf"))]
tracked.extend(sorted(SCRIPTS.glob("*.py")))
tracked.extend(sorted(SCRIPTS.glob("*.mjs")))
tracked.extend(sorted((ROOT / "schemas").glob("*.json")))
tracked.extend(sorted(path for path in (ROOT / "tools").rglob("*") if path.is_file()))
tracked.extend(sorted(path for path in (ROOT / "assets" / "web-showcase-template").rglob("*") if path.is_file()))
tracked.extend(sorted(path for path in (ROOT / "assets" / "offline-viewer-libs").rglob("*") if path.is_file()))
tracked.extend(path for path in (ROOT / "package.json", ROOT / "package-lock.json") if path.exists())
for path in sorted(set(tracked), key=lambda item: str(item)):
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 as exc:
raise SystemExit(f"Pipeline state is corrupt and was not overwritten: {state_path}: {exc}") from exc
else:
current = {}
if current.get("input_fingerprint") != input_fingerprint:
if resume and current:
print(
json.dumps(
{
"status": "INVALIDATED",
"reason": "input fingerprint changed",
"state": str(state_path),
},
ensure_ascii=False,
)
)
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)
temporary = self.path.with_name(f".{self.path.name}.{os.getpid()}.tmp")
try:
with temporary.open("w", encoding="utf-8") as stream:
json.dump(self.state, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, self.path)
finally:
temporary.unlink(missing_ok=True)
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 resolve_executable(name: str) -> str:
"""Resolve command shims portably (notably npm.cmd on Windows)."""
candidates = [name]
if sys.platform == "win32":
candidates = [f"{name}.cmd", f"{name}.exe", name]
for candidate in candidates:
found = shutil.which(candidate)
if found:
return found
raise SystemExit(f"Required executable not found on PATH: {name}")
def npm_command(*args: str) -> list[str]:
return [resolve_executable("npm"), *args]
def node_script(path: Path, *args: str) -> list[str]:
return [resolve_executable("node"), str(path), *args]
def enforce_audit_gates(pipeline: Pipeline, audit_path: Path, waivers: dict[str, str]) -> bool:
report = json.loads(audit_path.read_text(encoding="utf-8"))
checks = [
{
"name": f"audit:{gate.get('name', 'unnamed')}",
"status": str(gate.get("status", "FAIL")),
"detail": str(gate.get("detail", "")),
}
for gate in report.get("gates", [])
]
audit_waivers = {name: reason for name, reason in waivers.items() if name.startswith("audit:")}
apply_waivers(checks, audit_waivers)
waived = [
{
"name": check["name"],
"original_status": check["original_status"],
"reason": check["waiver_reason"],
}
for check in checks
if "waiver_reason" in check
]
blocked = [check for check in checks if check.get("status") not in {"PASS", "NOT_APPLICABLE"}]
pipeline.state["audit_waivers"] = waived
if blocked:
pipeline.state["status"] = "BLOCKED"
pipeline.state["blocked_gates"] = blocked
pipeline.save()
for gate in blocked:
print(f"GATE BLOCKED [{gate['name']}]: {gate['detail']}", file=sys.stderr)
return False
pipeline.save()
return True
def preflight_waiver_targets(
args: argparse.Namespace,
source_report: dict[str, Any],
audit_report: dict[str, Any],
scope_manifest: Path,
waivers: dict[str, str],
) -> list[dict[str, Any]]:
"""Return invalid waiver checks before overlays/model builds begin.
The orchestrator knows every check that can legitimately be WARN/SKIP by
this point. Browser/offline checks generated by this pipeline are expected
to PASS; the only future SKIP is an explicitly required browser report when
no served Web delivery was requested.
"""
source_gate = source_report.get("gate") or {}
checks = [
{
"name": "cad_source_report",
"status": str(source_gate.get("status", "FAIL")),
"detail": str(source_gate.get("detail", "")),
}
]
checks.extend(
{
"name": f"audit:{gate.get('name', 'unnamed')}",
"status": str(gate.get("status", "FAIL")),
"detail": str(gate.get("detail", "")),
}
for gate in audit_report.get("gates", [])
)
try:
scope = json.loads(scope_manifest.read_text(encoding="utf-8"))
requested = scope.get("requested", [])
raw_buildings = scope.get("buildings", [])
if not isinstance(raw_buildings, list):
raw_buildings = []
buildings = {str(item.get("id", "")): item for item in raw_buildings if isinstance(item, dict)}
for building_id in requested if isinstance(requested, list) else []:
item = buildings.get(str(building_id), {})
status = str(item.get("status", "FAIL"))
reason = str(item.get("reason", "")).strip()
check_status = "WARN" if status == "BLOCKED" and reason else "PASS" if status == "PASS" else "FAIL"
checks.append(
{
"name": f"scope:building:{building_id}",
"status": check_status,
"detail": reason or f"Scope building status is {status}",
}
)
if scope.get("mode") == "campus":
site = scope.get("site", {}) if isinstance(scope.get("site"), dict) else {}
status = str(site.get("status", "FAIL"))
reason = str(site.get("reason", "")).strip()
check_status = "WARN" if status == "BLOCKED" and reason else "PASS" if status == "PASS" else "FAIL"
checks.append(
{
"name": "scope:site",
"status": check_status,
"detail": reason or f"Campus site status is {status}",
}
)
except (OSError, json.JSONDecodeError):
# Final scope verification reports the malformed manifest. With no
# trustworthy target inventory, every scope waiver remains unused.
pass
if args.web:
checks.append({"name": "browser:smoke", "status": "PASS", "detail": "Generated browser smoke required"})
elif args.require_browser_report:
checks.append(
{
"name": "browser:smoke",
"status": "SKIP",
"detail": "Required browser report without a served Web delivery",
}
)
if args.offline:
checks.append(
{
"name": "offline:browser-smoke",
"status": "PASS",
"detail": "Generated offline browser smoke required",
}
)
apply_waivers(checks, waivers)
return [
check for check in checks if check.get("status") == "FAIL" and str(check.get("name", "")).startswith("waiver:")
]
def multi_frame_source_files(source_report: dict[str, Any]) -> list[str]:
"""Return source drawings that require a detector-backed frame ledger.
A single modelspace can contain several floor plans. In that case a
hand-written extraction config is not enough evidence: every detected
frame must be mapped or explicitly discarded. Accept either the structured
count or the compatible warning emitted by older source inspectors.
"""
required: list[str] = []
for item in source_report.get("files", []) or []:
if not isinstance(item, dict) or item.get("status") != "ok":
continue
warnings = [str(value) for value in item.get("warnings", []) or []]
if int(item.get("plan_title_count", 0) or 0) >= 2 or any(
"multi_frame_sheet" in warning for warning in warnings
):
required.append(str(item.get("file", "?")))
return required
def available_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as stream:
stream.bind(("127.0.0.1", 0))
return int(stream.getsockname()[1])
def wait_for_http(url: str, timeout: float = 20.0) -> None:
deadline = time.monotonic() + timeout
last_error: Exception | None = None
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=1) as response:
if response.status < 500:
return
except Exception as exc: # pragma: no cover - timing depends on host
last_error = exc
time.sleep(0.2)
raise RuntimeError(f"Local Web server did not become ready: {last_error}")
def ensure_node_runtime(pipeline: Pipeline, *, browser: bool) -> None:
pipeline.run(
"node_dependencies",
npm_command("install", "--prefix", str(ROOT), "--ignore-scripts"),
[
ROOT / "node_modules" / "playwright" / "package.json",
ROOT / "node_modules" / "@gltf-transform" / "core" / "package.json",
],
)
if browser:
pipeline.run(
"browser_runtime",
node_script(ROOT / "node_modules" / "playwright" / "cli.js", "install", "chromium"),
[],
)
def run_browser_smoke(pipeline: Pipeline, web_dir: Path, report: Path, screenshots: Path) -> None:
"""Serve the formal Web bundle and mechanically prove desktop/mobile loading."""
report.parent.mkdir(parents=True, exist_ok=True)
port = available_port()
url = f"http://127.0.0.1:{port}/"
server = subprocess.Popen(
[
sys.executable,
"-m",
"http.server",
str(port),
"--bind",
"127.0.0.1",
"--directory",
str(web_dir),
],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
wait_for_http(url)
pipeline.run(
"browser_smoke",
node_script(
SCRIPTS / "web_smoke_test.mjs",
"--url",
url,
"--out",
str(report),
"--screenshots-dir",
str(screenshots),
),
[report, screenshots],
)
finally:
server.terminate()
try:
server.wait(timeout=5)
except subprocess.TimeoutExpired: # pragma: no cover - defensive cleanup
server.kill()
server.wait(timeout=5)
def run_offline_browser_smoke(pipeline: Pipeline, viewer: Path, report: Path, screenshot: Path) -> None:
"""Open the single-file viewer through file:// and prove that its model renders."""
pipeline.run(
"offline_browser_smoke",
node_script(
SCRIPTS / "offline_viewer_smoke.mjs",
"--viewer",
str(viewer),
"--out",
str(report),
"--screenshot",
str(screenshot),
),
[report, screenshot],
)
def doctor() -> int:
modules = ["ezdxf", "jsonschema", "numpy", "scipy", "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"):
try:
path = resolve_executable(executable)
except SystemExit:
path = None
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,
)
if args.allow_partial:
command.extend(["--allow-partial", "--partial-reason", args.partial_reason])
if args.no_convert:
command.append("--no-convert")
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
raw_glb = out_dir / f"{key}.raw.glb"
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(raw_glb),
"--metadata-out",
str(metadata),
"--name",
key,
),
[raw_glb, metadata],
forbidden_stderr=("WARNING mesh_from_polygons",),
)
pipeline.run(
f"compress_{key}",
node_script(ROOT / "tools" / "compress.mjs", str(raw_glb), str(glb)),
[glb],
)
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()
scope_manifest = Path(args.scope_manifest).resolve()
frame_inputs = tuple(Path(path).resolve() for path in args.frames)
try:
waivers = parse_waivers(args.waiver)
except ValueError as exc:
print(f"GATE FAIL [waiver]: {exc}", file=sys.stderr)
return 3
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
source_status = str((report.get("gate") or {}).get("status", "FAIL"))
source_checks = [
{
"name": "cad_source_report",
"status": source_status,
"detail": str((report.get("gate") or {}).get("detail", "")),
}
]
source_waivers = {name: reason for name, reason in waivers.items() if name == "cad_source_report"}
apply_waivers(source_checks, source_waivers)
if source_checks[0]["status"] == "WARN":
print(
"GATE BLOCKED [cad_source_report]: partial source report requires "
"--waiver 'cad_source_report=<user-approved reason>'",
file=sys.stderr,
)
return 3
invalid_source_waiver = next((check for check in source_checks if check["status"] == "FAIL"), None)
if invalid_source_waiver:
print(
f"GATE FAIL [{invalid_source_waiver['name']}]: {invalid_source_waiver['detail']}",
file=sys.stderr,
)
return 3
multi_frame_files = multi_frame_source_files(report)
if multi_frame_files and not frame_inputs:
print(
"GATE FAIL [frame_ledger_required]: multi-plan source drawing(s) require "
"detect_sheet_frames output via --frames: " + ", ".join(multi_frame_files),
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, (scope_manifest, *frame_inputs)),
args.resume,
)
if source_status == "WARN":
pipeline.state["source_waiver"] = {
"check": "cad_source_report",
"reason": waivers["cad_source_report"],
}
pipeline.save()
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=DERIVE_FORBIDDEN_WARNINGS,
)
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])
audit_report = json.loads(audit.read_text(encoding="utf-8"))
invalid_waivers = preflight_waiver_targets(args, report, audit_report, scope_manifest, waivers)
if invalid_waivers:
pipeline.state["status"] = "BLOCKED"
pipeline.state["invalid_waivers"] = invalid_waivers
pipeline.save()
for check in invalid_waivers:
print(f"GATE FAIL [{check['name']}]: {check['detail']}", file=sys.stderr)
return 3
if not enforce_audit_gates(pipeline, audit, waivers):
return 3
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" or args.web or args.offline:
ensure_node_runtime(pipeline, browser=args.web or args.offline)
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_command("install", "--prefix", str(web_dir), "--ignore-scripts"),
[web_dir / "node_modules" / "three" / "build" / "three.module.js"],
)
browser_report = (
Path(args.browser_report).resolve() if args.browser_report else out_dir / "browser_smoke_report.json"
)
run_browser_smoke(pipeline, web_dir, browser_report, out_dir / "browser_smoke")
standard = bundle / "variants" / "standard" / "standard.glb"
offline = out_dir / "viewer.html"
offline_browser_report = out_dir / "offline_browser_smoke_report.json"
if args.offline:
offline_source = standard.with_name("standard.raw.glb")
if not offline_source.exists():
offline_source = standard
pipeline.run(
"offline",
python_script(
"write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(offline_source),
"--out",
str(offline),
"--title",
args.name,
),
[offline],
)
run_offline_browser_smoke(
pipeline,
offline,
offline_browser_report,
out_dir / "offline_browser_smoke.png",
)
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),
"--audit",
str(audit),
"--require-audit",
"--budget-mb",
str(args.budget_mb),
"--evidence-out",
str(evidence),
"--scope-manifest",
str(scope_manifest),
"--require-scope-manifest",
)
if args.web:
verify_cmd.extend(
["--web-dir", str(web_dir), "--browser-report", str(browser_report), "--require-browser-report"]
)
if args.offline:
verify_cmd.extend(
[
"--offline-viewer",
str(offline),
"--offline-browser-report",
str(offline_browser_report),
]
)
if args.require_browser_report and not args.web:
verify_cmd.append("--require-browser-report")
for value in args.waiver:
verify_cmd.extend(["--waiver", value])
pipeline.run("delivery_verification", verify_cmd, [evidence])
verification = json.loads(evidence.read_text(encoding="utf-8"))
if verification.get("status") != "PASS":
pipeline.state["status"] = "BLOCKED"
pipeline.save()
print(f"GATE BLOCKED [delivery_verification]: {verification.get('status')}", file=sys.stderr)
return 3
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")
inspect.add_argument("--no-convert", action="store_true")
inspect.add_argument("--allow-partial", action="store_true")
inspect.add_argument("--partial-reason", default="")
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(
"--scope-manifest",
required=True,
help="Required single-building/campus scope ledger included in final verification",
)
run.add_argument(
"--waiver",
action="append",
default=[],
metavar="CHECK=REASON",
help="Explicitly acknowledge one WARN/SKIP audit or delivery check",
)
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

@@ -0,0 +1,59 @@
"""Shared parsing and application rules for explicit delivery waivers."""
from __future__ import annotations
from typing import Any
WAIVABLE_STATUSES = frozenset({"WARN", "SKIP"})
def parse_waivers(values: list[str]) -> dict[str, str]:
"""Parse CHECK=REASON values and reject malformed or duplicate entries."""
waivers: dict[str, str] = {}
for value in values:
name, separator, reason = value.partition("=")
name = name.strip()
reason = reason.strip()
if not separator or not name or not reason:
raise ValueError(f"Invalid waiver {value!r}; expected CHECK=REASON")
if name in waivers:
raise ValueError(f"Duplicate waiver for {name!r}")
waivers[name] = reason
return waivers
def apply_waivers(checks: list[dict[str, Any]], waivers: dict[str, str]) -> None:
"""Apply waivers to WARN/SKIP checks and add FAIL checks for invalid targets.
Passing a namespace-specific subset lets an earlier pipeline stage reject
misspelled, unused, PASS, FAIL, or NOT_APPLICABLE targets before expensive
downstream work begins. Final verification calls the same function with the
complete waiver map, so both stages have identical semantics.
"""
by_name = {str(check.get("name", "")): check for check in checks}
for name, reason in waivers.items():
check = by_name.get(name)
if check is None:
checks.append(
{
"name": f"waiver:{name}",
"status": "FAIL",
"detail": f"Unused or misspelled waiver: {name}",
}
)
continue
status = str(check.get("status", "FAIL"))
if status not in WAIVABLE_STATUSES:
checks.append(
{
"name": f"waiver:{name}",
"status": "FAIL",
"detail": f"Waivers may only acknowledge WARN/SKIP checks; {name} is {status}",
}
)
continue
check["original_status"] = status
check["status"] = "PASS"
check["waiver_reason"] = reason
check["detail"] = f"WAIVED ({reason}): {check.get('detail', '')}"

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):
@@ -243,6 +244,23 @@ def match_patterns(value: str, patterns: list[str]) -> bool:
return any(fnmatch.fnmatch(upper_value, str(pattern).upper()) for pattern in patterns)
def block_matches_floor(block_name: str, floor: dict[str, Any], drawing: dict[str, Any]) -> bool:
"""Apply source-view block selectors before expanding a Revit sheet.
Revit DXF exports can place several views at identical world coordinates;
their top-level INSERT names retain the view suffix (for example
``-屋面平面图`` vs ``-机房小屋面``). A clip cannot separate those views, so
the floor config must be able to select the corresponding block family.
"""
includes = list(floor.get("include_block_names", drawing.get("include_block_names", [])) or [])
excludes = list(floor.get("exclude_block_names", drawing.get("exclude_block_names", [])) or [])
if includes and (not block_name or not match_patterns(block_name, includes)):
return False
if excludes and block_name and match_patterns(block_name, excludes):
return False
return True
def block_category(block_name: str, config: dict[str, Any]) -> str | None:
for category, patterns in config.get("block_name_categories", {}).items():
if match_patterns(block_name, list(patterns)):
@@ -405,10 +423,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 +504,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))
@@ -532,6 +544,12 @@ def collect_raw_segments(
ignored_by_type: dict[str, int] = defaultdict(int)
for entity in entities:
root_block_name = (
str(entity.dxf.name) if entity.dxftype() == "INSERT" and entity.dxf.hasattr("name") else ""
)
eligible_floors = [item for item in floor_specs if block_matches_floor(root_block_name, item[0], drawing)]
if not eligible_floors:
continue
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
layer = entity_layer(extracted_entity)
category = category_for_entity(
@@ -552,7 +570,7 @@ def collect_raw_segments(
min_source = min_source_by_category.get(category, min_source_length)
min_meters = min_meters_by_category.get(category, min_meters_length)
for start, end in segments:
for floor, key, offset in floor_specs:
for floor, key, offset in eligible_floors:
if not segment_matches_floor(start, end, floor, drawing):
continue
trimmed = clip_segment_to_rect(start, end, floor.get("clip", drawing.get("clip")))
@@ -731,7 +749,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 +762,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 +781,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 +793,15 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
else:
merged.append([lo, hi])
for lo, hi in merged:
out.append({
"start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
"end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
"width": width, "layer": layer, "source_type": "merged",
})
out.append(
{
"start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
"end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
"width": width,
"layer": layer,
"source_type": "merged",
}
)
return out
@@ -783,14 +812,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):
@@ -833,7 +855,9 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
"""
if not config.get("generate_caps", True):
return
buf = float(config.get("cap_buffer", 1.3))
# Ordinary facade-aligned floors need only a small tolerance. Colonnade or
# broad-overhang projects such as A208 must opt into a larger value.
buf = float(config.get("cap_buffer", 0.1))
for fk, fl in floors.items():
own_polys = fl.get("footprint", {}).get("polygons", [])
if not own_polys:
@@ -857,12 +881,21 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
polys = [] # roof_specs handles above-ground tops
else:
up_u = _shapely_union(upper)
polys = _shapely_to_polys(own_u.buffer(buf).difference(up_u.buffer(0.05))) if up_u is not None else []
# A 0.1 m facade tolerance creates a thin evidence ring whose area
# can be below the generic 3 m² polygon-noise threshold on small
# buildings. Caps are already footprint-derived, so retain them.
polys = (
_shapely_to_polys(own_u.buffer(buf).difference(up_u.buffer(0.05)), min_area=0.25)
if up_u is not None
else []
)
if polys:
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 +958,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 +1086,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 +1168,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 +1199,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

@@ -37,6 +37,8 @@ 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"(立面图|剖面图)$")
@@ -99,7 +101,7 @@ def floor_titles_from_label(label: str) -> list[str]:
matches = list(FLOOR_TOKEN_RE.finditer(head))
if not matches:
return [label]
qualifier = re.sub(r"[、,,\s]+$", "", head[:matches[0].start()])
qualifier = re.sub(r"[、,,\s]+$", "", head[: matches[0].start()])
# A long prefix is normally an element/family name, not a building label.
if len(qualifier) > 12:
qualifier = ""
@@ -181,22 +183,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*,*TTLB*,*TK*,*图框*,*目录*")
# Wildcards matter: design institutes prefix layers (13号地块: A_DOTE/A_AXIS),
# and an exact "DOTE" token silently zeroes the grid-correlation votes.
parser.add_argument("--axis-layers", default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*",
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs")
parser.add_argument(
"--axis-layers",
default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*",
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs",
)
parser.add_argument("--wall-layers", default="WALL,*WALL*,*墙*")
parser.add_argument("--refine-fallback-layers",
default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*",
help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)")
parser.add_argument("--frame-aspect", type=float, default=1.5,
help="Initial clip width = pitch * aspect (A1 landscape + margin)")
parser.add_argument("--grid-bin", type=float, default=60.0,
help="Cluster tolerance (source units) for axis positions and vote bins")
parser.add_argument(
"--refine-fallback-layers",
default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*",
help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)",
)
parser.add_argument(
"--frame-aspect", type=float, default=1.5, help="Initial clip width = pitch * aspect (A1 landscape + margin)"
)
parser.add_argument(
"--grid-bin", type=float, default=60.0, help="Cluster tolerance (source units) for axis positions and vote bins"
)
return parser.parse_args()
@@ -313,8 +323,7 @@ def plan_geometry_components(entities, layers):
steps = max(1, math.ceil(length / cell))
for i in range(steps + 1):
t = i / steps
occupied.add((round((sx + (ex - sx) * t) / cell),
round((sy + (ey - sy) * t) / cell)))
occupied.add((round((sx + (ex - sx) * t) / cell), round((sy + (ey - sy) * t) / cell)))
components = []
while occupied:
seed = occupied.pop()
@@ -332,8 +341,7 @@ def plan_geometry_components(entities, layers):
continue
xs = [c[0] for c in cells]
ys = [c[1] for c in cells]
bbox = [min(xs) * cell, min(ys) * cell,
(max(xs) + 1) * cell, (max(ys) + 1) * cell]
bbox = [min(xs) * cell, min(ys) * cell, (max(xs) + 1) * cell, (max(ys) + 1) * cell]
if bbox[2] - bbox[0] >= cell * 3 and bbox[3] - bbox[1] >= cell * 3:
components.append({"bbox": bbox, "cells": len(cells), "cell": cell})
return sorted(components, key=lambda item: item["cells"], reverse=True)
@@ -426,8 +434,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
@@ -463,7 +470,8 @@ def main() -> int:
refine_patterns = [
pattern.strip()
for group in args.refine_fallback_layers.split("|")
for pattern in group.split(",") if pattern.strip()
for pattern in group.split(",")
if pattern.strip()
]
# Roof-only cached blocks can have no WALL/GRID layer at all. They still
# need expansion so roof/railing/floor geometry can seed the frame clip.
@@ -557,10 +565,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:
@@ -626,15 +636,12 @@ def main() -> int:
for key in insert_title_labels:
points = insert_title_points.get(key, [])
expanded = insert_title_lines.get(key, [])
evidence = points if len(points) >= 5 else [
((sx + ex) / 2, (sy + ey) / 2) for _, sx, sy, ex, ey in expanded
]
evidence = points if len(points) >= 5 else [((sx + ex) / 2, (sy + ey) / 2) for _, sx, sy, ex, ey in expanded]
scores = []
for index, component in enumerate(geometry_components):
x1, y1, x2, y2 = component["bbox"]
pad = component["cell"] * 2
score = sum(1 for x, y in evidence
if x1 - pad <= x <= x2 + pad and y1 - pad <= y <= y2 + pad)
score = sum(1 for x, y in evidence if x1 - pad <= x <= x2 + pad and y1 - pad <= y <= y2 + pad)
scores.append((score, component["cells"], index))
scores.sort(reverse=True)
best = scores[0][0] if scores else 0
@@ -645,8 +652,7 @@ def main() -> int:
for _, best, key, scores in sorted(ranked_keys, reverse=True):
if best <= 0:
continue
choice = next((index for score, _, index in scores
if score > 0 and index not in used_components), None)
choice = next((index for score, _, index in scores if score > 0 and index not in used_components), None)
if choice is not None:
component_choice[key] = geometry_components[choice]
used_components.add(choice)
@@ -663,8 +669,7 @@ def main() -> int:
for key, labels in insert_title_labels.items():
points = insert_title_points.get(key, [])
expanded = insert_title_lines.get(key, [])
strong_insert_evidence = (len(points) >= 5 or len(expanded) >= 50
or key in component_choice)
strong_insert_evidence = len(points) >= 5 or len(expanded) >= 50 or key in component_choice
if strong_insert_evidence:
titles = [t for t in titles if floor_base_key(t["name"]) != key]
elif any(floor_base_key(t["name"]) == key for t in titles):
@@ -676,8 +681,12 @@ def main() -> int:
clip_hint = list(component["bbox"])
point_bbox = robust_point_bbox(points)
if len(insert_title_labels) == 1 and point_bbox is not None:
union = [min(clip_hint[0], point_bbox[0]), min(clip_hint[1], point_bbox[1]),
max(clip_hint[2], point_bbox[2]), max(clip_hint[3], point_bbox[3])]
union = [
min(clip_hint[0], point_bbox[0]),
min(clip_hint[1], point_bbox[1]),
max(clip_hint[2], point_bbox[2]),
max(clip_hint[3], point_bbox[3]),
]
if union != clip_hint:
clip_hint = union
preserve_component_union_keys.add(key)
@@ -692,8 +701,7 @@ def main() -> int:
width = max(clip_hint[2] - clip_hint[0], 1.0)
height = max(clip_hint[3] - clip_hint[1], 1.0)
margin = max(3000.0, min(max(width, height) * 0.08, 15000.0))
clip_hint = [clip_hint[0] - margin, clip_hint[1] - margin,
clip_hint[2] + margin, clip_hint[3] + margin]
clip_hint = [clip_hint[0] - margin, clip_hint[1] - margin, clip_hint[2] + margin, clip_hint[3] + margin]
x = (clip_hint[0] + clip_hint[2]) / 2
y = (clip_hint[1] + clip_hint[3]) / 2
elif points:
@@ -701,9 +709,18 @@ def main() -> int:
y = statistics.median(p[1] for p in points)
else:
continue
titles.append({"name": label, "x": x, "y": y, "h": 1.0,
"layer": "INSERT_NAME", "_clip_hint": clip_hint,
"_preserve_component_union": key in preserve_component_union_keys})
titles.append(
{
"name": label,
"x": x,
"y": y,
"h": 1.0,
"layer": "INSERT_NAME",
"_clip_hint": clip_hint,
"_preserve_component_union": key in preserve_component_union_keys,
"_include_block_names": [f"*-{label}"],
}
)
if not titles:
print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False))
@@ -749,19 +766,28 @@ 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.get("_clip_hint") or [t["x"] - clip_w * 0.55, t["y"] - pitch * 0.06, t["x"] + clip_w * 0.55, t["y"] + clip_h]
rough = t.get("_clip_hint") or [
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 and not t.get("_clip_hint"):
# 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 = rough if t.get("_preserve_component_union") else None
if clip is None:
@@ -773,8 +799,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
@@ -803,7 +833,7 @@ def main() -> int:
f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a "
"separate structure or revision sheet; excluded from reference candidacy"
)
floors.append({
floor = {
"key": floor_key_for(t["name"], used_keys),
"name": t["name"],
"clip": [round(c, 1) for c in clip],
@@ -811,13 +841,17 @@ def main() -> int:
"_hy": cluster_positions(horiz, args.grid_bin),
"_walls": segments_in(lines, clip, wall_layers),
"_aux": bool(qualifier),
})
}
if t.get("_include_block_names"):
floor["include_block_names"] = list(t["_include_block_names"])
floors.append(floor)
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 = []
@@ -836,12 +870,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} "
@@ -849,8 +880,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!"
)
@@ -862,18 +892,25 @@ def main() -> int:
# trustworthy frames. Keep the skeleton for inspection, but say plainly
# that cross-floor overlay must resolve which view belongs in the stack.
for i, left in enumerate(floors):
for right in floors[i + 1:]:
for right in floors[i + 1 :]:
ax1, ay1, ax2, ay2 = left["clip"]
bx1, by1, bx2, by2 = right["clip"]
overlap = max(0.0, min(ax2, bx2) - max(ax1, bx1)) * max(0.0, min(ay2, by2) - max(ay1, by1))
smaller = min(max((ax2 - ax1) * (ay2 - ay1), 1.0),
max((bx2 - bx1) * (by2 - by1), 1.0))
smaller = min(max((ax2 - ax1) * (ay2 - ay1), 1.0), max((bx2 - bx1) * (by2 - by1), 1.0))
if overlap / smaller >= 0.8:
notes.append(
f"AMBIGUOUS overlapping inferred frames: {left['key']} and {right['key']} "
f"overlap {overlap / smaller:.0%}; resolve by cross-floor overlay and keep/discard "
"explicitly — do not model both blindly"
)
left_blocks = set(left.get("include_block_names", []))
right_blocks = set(right.get("include_block_names", []))
if left_blocks and right_blocks and left_blocks.isdisjoint(right_blocks):
notes.append(
f"OVERLAPPING clips separated by Revit view identity: {left['key']} uses "
f"{sorted(left_blocks)}, {right['key']} uses {sorted(right_blocks)}"
)
else:
notes.append(
f"AMBIGUOUS overlapping inferred frames: {left['key']} and {right['key']} "
f"overlap {overlap / smaller:.0%}; resolve by cross-floor overlay and keep/discard "
"explicitly — do not model both blindly"
)
# Expand multi-floor titles (四、六、八层 / 十一至十四层) into one config
# entry per storey sharing the frame's clip/offset — hand-copying N entries
@@ -892,34 +929,60 @@ 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"],
**({"include_block_names": f["include_block_names"]} if f.get("include_block_names") else {}),
}
)
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"],
**({"include_block_names": f["include_block_names"]} if f.get("include_block_names") else {}),
}
)
view_block_patterns = sorted(
{pattern for floor in config_floors for pattern in floor.get("include_block_names", [])}
)
config = {
"config_version": showcase_schema.CONFIG_VERSION,
"project_name": path.stem,
"scale": 0.001,
"floor_height": 4.2,
"_comment": "Review floor order/keys/z/heights (use elevation/section frames). offset stacks each frame onto the reference frame; origin_strategy normalizes globally.",
"origin_strategy": "min",
"drawings": [{
"file": path.name,
"floors": config_floors,
}],
**({"expand_block_names": view_block_patterns} if view_block_patterns else {}),
"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']}")
@@ -940,8 +1003,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
@@ -967,10 +1032,16 @@ def main() -> int:
report.append(line)
levels = sorted(v for v, n in votes.items() if n >= 2 or (votes[v] >= 1 and -20 < v < 150))
if levels:
report.extend(["", "## Suggested storey elevations (from 剖面/立面 标高 texts)", "",
"- " + ", ".join(f"{v:+.3f}" for v in levels),
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
"storey z = consecutive major levels, height = difference."])
report.extend(
[
"",
"## Suggested storey elevations (from 剖面/立面 标高 texts)",
"",
"- " + ", ".join(f"{v:+.3f}" for v in levels),
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
"storey z = consecutive major levels, height = difference.",
]
)
# Uniform-step suggestion: the dominant consecutive difference and
# its longest chain. A SUGGESTION for the Agent to verify against
# the 剖面 — stair sections beat at half-storey rhythm (2.25 for a
@@ -998,12 +1069,20 @@ def main() -> int:
report.append(
f"- suggested storey table: uniform step {step} m x {len(best_chain) - 1} "
f"storeys, z {best_chain[0]:+.3f} → {best_chain[-1]:+.3f} — verify against "
"剖面/立面 per-frame ladders (podium and machine floors may differ)")
"剖面/立面 per-frame ladders (podium and machine floors may differ)"
)
Path(args.out_report).write_text("\n".join(report) + "\n", encoding="utf-8")
print(json.dumps({
"config": str(out_config), "report": args.out_report,
"floors": [f["key"] for f in floors], "pitch": round(pitch, 1),
}, ensure_ascii=False))
print(
json.dumps(
{
"config": str(out_config),
"report": args.out_report,
"floors": [f["key"] for f in floors],
"pitch": round(pitch, 1),
},
ensure_ascii=False,
)
)
return 0

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env node
/** Prove that the self-contained offline viewer loads from file:// in Chromium. */
import fs from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
function arg(name, fallback = null) {
const index = process.argv.indexOf(name);
return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback;
}
const viewer = arg("--viewer");
const out = arg("--out", "offline_browser_smoke_report.json");
const screenshot = arg("--screenshot", "offline_browser_smoke.png");
if (!viewer) {
throw new Error("Usage: offline_viewer_smoke.mjs --viewer viewer.html --out report.json --screenshot smoke.png");
}
let chromium;
try {
({ chromium } = await import("playwright"));
} catch (error) {
throw new Error("Missing Playwright. Install dependencies and Chromium before running this smoke test.", {
cause: error,
});
}
await fs.mkdir(path.dirname(out), { recursive: true });
await fs.mkdir(path.dirname(screenshot), { recursive: true });
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
const checks = [];
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"}`));
try {
const url = pathToFileURL(path.resolve(viewer)).href;
await page.goto(url, { waitUntil: "load", timeout: 60000 });
await page.waitForFunction(
() => window.__offlineReady || document.getElementById("load")?.textContent?.includes("加载失败"),
null,
{ timeout: 60000 },
);
const state = await page.evaluate(() => ({
viewport: { width: window.innerWidth, height: window.innerHeight },
ready: window.__offlineReady || null,
loadText: document.getElementById("load")?.textContent || "",
canvas: Boolean(document.querySelector("canvas")),
renders: window.__renders || 0,
}));
const viewportPass = state.viewport.width === 1440 && state.viewport.height === 900;
checks.push({
name: "offline:viewport",
status: viewportPass ? "PASS" : "FAIL",
detail: `${state.viewport.width}x${state.viewport.height} expected 1440x900`,
});
checks.push({
name: "offline:model-ready",
status: state.ready?.meshes > 0 && !state.loadText ? "PASS" : "FAIL",
detail: state.ready ? `${state.ready.meshes} mesh(es)` : state.loadText || "readiness marker missing",
});
checks.push({ name: "offline:canvas", status: state.canvas ? "PASS" : "FAIL" });
checks.push({
name: "offline:render",
status: state.renders > 0 ? "PASS" : "FAIL",
detail: `${state.renders} render(s)`,
});
await page.screenshot({ path: screenshot, fullPage: true });
} catch (error) {
checks.push({ name: "offline:load", status: "FAIL", detail: error.message });
await page.screenshot({ path: screenshot, fullPage: true }).catch(() => {});
} finally {
await page.close();
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`,
viewer: path.resolve(viewer),
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

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

View File

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

312
scripts/showcase_schema.py Normal file
View File

@@ -0,0 +1,312 @@
#!/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"
LEGACY_CATEGORY_STYLES = {
"walls": {"label": "墙体", "color": "#d4cbb8"},
"glazing": {"label": "玻璃/幕墙", "color": "#79b8c9"},
"roof": {"label": "屋顶/屋盖", "color": "#b8ae98"},
"columns": {"label": "柱", "color": "#f58a1f"},
"beams": {"label": "梁/结构", "color": "#1f66c2"},
"railings": {"label": "栏杆/扶手", "color": "#6f746d"},
"doors": {"label": "门/开启线", "color": "#8a6a45"},
"detail_lines": {"label": "平面细节", "color": "#8c9088"},
"floor_lines": {"label": "楼面线", "color": "#18a058"},
"grid": {"label": "轴网", "color": "#20242a"},
"slab": {"label": "楼板", "color": "#c8ccc2"},
}
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
raw_categories = normalized.get("categories", {})
categories = copy.deepcopy(raw_categories) if isinstance(raw_categories, dict) else {}
configured_categories = source["config"].get("categories", {})
used_categories = {
category
for floor in normalized.get("floors", {}).values()
for category, segments in floor.get("segments", {}).items()
if segments
}
if source["config"].get("use_footprint_slabs"):
used_categories.add("slab")
for category in sorted(used_categories):
if category in categories:
continue
style = dict(LEGACY_CATEGORY_STYLES.get(category, {"label": category, "color": "#8c9088"}))
override = configured_categories.get(category, {}) if isinstance(configured_categories, dict) else {}
if isinstance(override, dict):
style.update({key: override[key] for key in ("label", "color") if key in override})
categories[category] = style
normalized["categories"] = categories
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 = {}
gate_status = gate.get("status")
if gate.get("name") != "all_sources_converted_and_readable" or gate_status not in {"PASS", "WARN"}:
errors.append(
f"gate: all_sources_converted_and_readable must be PASS or a reasoned partial WARN, got {gate_status!r}"
)
if gate_status == "WARN" and not str(gate.get("partial_reason", "")).strip():
errors.append("gate.partial_reason: WARN source reports require a non-empty partial reason")
files = report.get("files")
if not isinstance(files, list) or not files:
errors.append("files: report contains no inspected DXF files")
else:
readable = 0
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" and entity_count > 0:
readable += 1
elif gate_status == "PASS":
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 readable == 0:
errors.append("files: partial reports still require at least one readable nonempty DXF")
if expected_dxf_dir is not None:
reported = Path(str(report.get("dxf_sanitized", "")))
if not reported.is_absolute():
reported = ROOT / reported
if reported.resolve() != expected_dxf_dir.resolve():
errors.append(
f"dxf_sanitized: report points to {reported.resolve()}, expected {expected_dxf_dir.resolve()}"
)
elif expected_dxf_dir.exists():
report_items = files if isinstance(files, list) else []
reported_files = {str(item.get("file")) for item in report_items if isinstance(item, dict)}
actual_files = {path.name for path in expected_dxf_dir.glob("*.dxf")}
if reported_files != actual_files:
errors.append(
"files: source report and sanitized directory differ "
f"(missing={sorted(actual_files - reported_files)}, stale={sorted(reported_files - actual_files)})"
)
if errors:
raise ValidationFailure("Invalid CAD source report:\n- " + "\n- ".join(errors))
return report
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("kind", choices=("config", "spec", "manifest", "source-report"))
parser.add_argument("path")
parser.add_argument("--dxf-dir", help="Required for checking config source-file existence")
args = parser.parse_args()
try:
data = json.loads(Path(args.path).read_text(encoding="utf-8"))
if args.kind == "config":
validate_config(data, Path(args.dxf_dir) if args.dxf_dir else None)
elif args.kind == "spec":
validate_spec(data)
elif args.kind == "manifest":
validate_manifest(data)
else:
validate_source_report(data, Path(args.dxf_dir) if args.dxf_dir else None)
except (OSError, json.JSONDecodeError, ValidationFailure, TypeError, ValueError, AttributeError) as exc:
print(str(exc))
return 3
print(json.dumps({"status": "PASS", "kind": args.kind, "path": args.path}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

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

File diff suppressed because it is too large Load Diff

634
scripts/verify_delivery.py Normal file
View File

@@ -0,0 +1,634 @@
#!/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 statistics
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import showcase_schema
from delivery_waivers import apply_waivers, parse_waivers
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")
sample = image.resize((128, 128))
stat = ImageStat.Stat(sample)
spread = max(stat.var)
pixels = list(sample.getdata())
border = []
for index in range(128):
border.extend((sample.getpixel((index, 0)), sample.getpixel((index, 127))))
for index in range(1, 127):
border.extend((sample.getpixel((0, index)), sample.getpixel((127, index))))
background = tuple(int(statistics.median(pixel[channel] for pixel in border)) for channel in range(3))
foreground = [max(abs(pixel[channel] - background[channel]) for channel in range(3)) > 12 for pixel in pixels]
occupancy = sum(foreground) / len(foreground)
xs = [index % 128 for index, present in enumerate(foreground) if present]
ys = [index // 128 for index, present in enumerate(foreground) if present]
bbox_w = max(xs) - min(xs) + 1 if xs else 0
bbox_h = max(ys) - min(ys) + 1 if ys else 0
def luminance(pixel: tuple[int, int, int]) -> float:
return pixel[0] * 0.2126 + pixel[1] * 0.7152 + pixel[2] * 0.0722
transitions = 0
comparisons = 0
for y in range(128):
for x in range(128):
here = luminance(sample.getpixel((x, y)))
if x + 1 < 128:
transitions += abs(here - luminance(sample.getpixel((x + 1, y)))) > 45
comparisons += 1
if y + 1 < 128:
transitions += abs(here - luminance(sample.getpixel((x, y + 1)))) > 45
comparisons += 1
edge_ratio = transitions / comparisons
status = (
"PASS"
if image.width >= 320
and image.height >= 240
and spread > 2.0
and 0.01 <= occupancy <= 0.95
and bbox_w >= 24
and bbox_h >= 24
and edge_ratio < 0.45
else "FAIL"
)
add_check(
checks,
f"render:{path.name}",
status,
(
f"{image.width}x{image.height}, variance {spread:.2f}, "
f"foreground {occupancy:.1%}, bbox {bbox_w}x{bbox_h}/128, edge ratio {edge_ratio:.3f}"
),
)
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 = []
for item in metadata.get("model_variants", []):
file_name = item.get("file")
if not isinstance(file_name, str) or not file_name or not (web_dir / file_name).is_file():
missing_variants.append(file_name or "<missing file>")
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}")
WEB_BROWSER_CHECKS = {
"desktop:viewport",
"desktop:#floor-controls",
"desktop:#category-controls",
"desktop:#explode",
"desktop:#section",
"desktop:#snapshot",
"desktop:idle-render",
"mobile:viewport",
"mobile:#floor-controls",
"mobile:#category-controls",
"mobile:#explode",
"mobile:#section",
"mobile:#snapshot",
"mobile:idle-render",
}
OFFLINE_BROWSER_CHECKS = {
"offline:viewport",
"offline:model-ready",
"offline:canvas",
"offline:render",
}
def inspect_browser_report(path: Path, checks: list[dict[str, Any]], name: str = "browser:smoke") -> None:
try:
report = json.loads(path.read_text(encoding="utf-8"))
report_checks = report.get("checks")
if not isinstance(report_checks, list) or not report_checks:
raise ValueError("checks must be a non-empty list")
by_name: dict[str, dict[str, Any]] = {}
for item in report_checks:
if not isinstance(item, dict) or not isinstance(item.get("name"), str):
raise ValueError("every browser check must be an object with a name")
if item["name"] in by_name:
raise ValueError(f"duplicate browser check: {item['name']}")
by_name[item["name"]] = item
required = OFFLINE_BROWSER_CHECKS if name == "offline:browser-smoke" else WEB_BROWSER_CHECKS
missing = sorted(required - set(by_name))
failed = sorted(item_name for item_name, item in by_name.items() if item.get("status") != "PASS")
if missing:
raise ValueError("missing required checks: " + ", ".join(missing))
if failed:
raise ValueError("non-PASS checks: " + ", ".join(failed))
expected_viewports = (
{"offline:viewport": "1440x900 expected 1440x900"}
if name == "offline:browser-smoke"
else {
"desktop:viewport": "1440x900 expected 1440x900",
"mobile:viewport": "390x844 expected 390x844",
}
)
for check_name, expected_detail in expected_viewports.items():
if by_name[check_name].get("detail") != expected_detail:
raise ValueError(f"{check_name} has untrusted viewport evidence: {by_name[check_name].get('detail')!r}")
for error_key in ("console_errors", "page_errors", "failed_requests"):
if not isinstance(report.get(error_key), list):
raise ValueError(f"{error_key} must be a list")
passed = (
report.get("status") == "PASS"
and not report.get("console_errors")
and not report.get("page_errors")
and not report.get("failed_requests")
)
detail = f"validated {len(required)}/{len(required)} required checks; " + (
report.get("detail") or json.dumps(report, ensure_ascii=False)[:300]
)
add_check(checks, name, "PASS" if passed else "FAIL", detail)
except Exception as exc:
add_check(checks, name, "FAIL", f"Browser report invalid: {exc}")
def inspect_audit(path: Path, checks: list[dict[str, Any]]) -> None:
try:
report = json.loads(path.read_text(encoding="utf-8"))
gates = report.get("gates")
if not isinstance(gates, list) or not gates:
raise ValueError("audit has no gates")
for gate in gates:
status = str(gate.get("status", "FAIL"))
if status not in {"PASS", "WARN", "SKIP", "FAIL", "NOT_APPLICABLE"}:
status = "FAIL"
add_check(
checks,
f"audit:{gate.get('name', 'unnamed')}",
status,
str(gate.get("detail", "Audit gate has no detail")),
)
except Exception as exc:
add_check(checks, "audit:report", "FAIL", f"Extraction audit invalid: {exc}")
def verifiable_model_artifact(path: Path) -> tuple[bool, str]:
"""Reject scope ledgers backed only by arbitrary non-empty files."""
try:
suffix = path.suffix.lower()
if suffix == ".glb":
from pygltflib import GLTF2
model = GLTF2().load(str(path))
primitives = sum(len(mesh.primitives) for mesh in model.meshes or [])
if primitives <= 0:
return False, "GLB has no mesh primitives"
return True, f"GLB with {primitives} primitive(s)"
if suffix == ".blend":
if path.read_bytes()[:7] != b"BLENDER":
return False, "invalid Blender header"
return True, "Blender scene"
if suffix == ".json":
document = json.loads(path.read_text(encoding="utf-8"))
showcase_schema.validate_spec(document)
return True, f"building spec with {len(document['floors'])} floor(s)"
return False, f"unsupported model artifact type {suffix or '<none>'}"
except Exception as exc:
return False, str(exc)
def verifiable_site_artifact(path: Path) -> tuple[bool, str]:
model_ok, model_detail = verifiable_model_artifact(path)
if model_ok:
return True, model_detail
try:
from PIL import Image
with Image.open(path) as image:
image.verify()
if image.width < 320 or image.height < 240:
return False, f"site image too small: {image.width}x{image.height}"
return True, f"site image {image.width}x{image.height}"
except Exception:
return False, model_detail
def inspect_scope(path: Path, checks: list[dict[str, Any]]) -> None:
"""Validate a single-building/campus scope ledger against real artifacts."""
try:
scope = json.loads(path.read_text(encoding="utf-8"))
if scope.get("scope_version") != 1:
raise ValueError("scope_version must be 1")
mode = scope.get("mode")
if mode not in {"single", "campus"}:
raise ValueError("mode must be single or campus")
requested = scope.get("requested")
buildings = scope.get("buildings")
if (
not isinstance(requested, list)
or not requested
or not all(isinstance(item, str) and item for item in requested)
):
raise ValueError("requested must be a non-empty list of building IDs")
if len(set(requested)) != len(requested):
raise ValueError("requested contains duplicate building IDs")
if mode == "single" and len(requested) != 1:
raise ValueError("single mode requires exactly one requested building ID")
if not isinstance(buildings, list):
raise ValueError("buildings must be a list")
by_id: dict[str, dict[str, Any]] = {}
for item in buildings:
building_id = str(item.get("id", ""))
if not building_id or building_id in by_id:
raise ValueError(f"missing or duplicate building id: {building_id!r}")
by_id[building_id] = item
missing = [item for item in requested if item not in by_id]
unexpected = sorted(set(by_id) - set(requested))
if missing or unexpected:
add_check(
checks,
"scope:inventory",
"FAIL",
(
("Requested buildings missing from ledger: " + ", ".join(missing) if missing else "")
+ ("; " if missing and unexpected else "")
+ ("Unrequested buildings in ledger: " + ", ".join(unexpected) if unexpected else "")
),
)
else:
add_check(
checks, "scope:inventory", "PASS", f"All {len(requested)} requested building(s) are in the ledger"
)
for building_id in requested:
item = by_id.get(building_id)
if not item:
continue
status = item.get("status")
reason = str(item.get("reason", "")).strip()
artifacts = item.get("artifacts", [])
if status == "BLOCKED":
add_check(
checks,
f"scope:building:{building_id}",
"WARN" if reason else "FAIL",
reason or "BLOCKED building has no reason",
)
continue
if status != "PASS":
add_check(checks, f"scope:building:{building_id}", "FAIL", f"Invalid status: {status!r}")
continue
if not isinstance(artifacts, list) or not artifacts:
add_check(checks, f"scope:building:{building_id}", "FAIL", "PASS building has no artifacts")
continue
missing_artifacts = []
verified_models = []
invalid_models = []
for artifact in artifacts:
artifact_path = Path(str(artifact))
if not artifact_path.is_absolute():
artifact_path = path.parent / artifact_path
if not artifact_path.exists() or (artifact_path.is_file() and artifact_path.stat().st_size == 0):
missing_artifacts.append(str(artifact))
continue
verified, detail = verifiable_model_artifact(artifact_path)
if verified:
verified_models.append(f"{artifact}: {detail}")
else:
invalid_models.append(f"{artifact}: {detail}")
failed = bool(missing_artifacts or not verified_models)
add_check(
checks,
f"scope:building:{building_id}",
"FAIL" if failed else "PASS",
"Missing artifacts: " + ", ".join(missing_artifacts)
if missing_artifacts
else (
f"{len(verified_models)} verifiable model artifact(s)"
if verified_models
else "No verifiable GLB/BLEND/building-spec artifact; rejected: " + "; ".join(invalid_models)
),
)
site = scope.get("site", {})
if mode == "campus":
site_status = site.get("status") if isinstance(site, dict) else None
if site_status == "BLOCKED":
reason = str(site.get("reason", "")).strip()
add_check(checks, "scope:site", "WARN" if reason else "FAIL", reason or "Campus site is blocked")
elif site_status != "PASS":
add_check(checks, "scope:site", "FAIL", "Campus scope requires site.status=PASS or BLOCKED")
else:
artifacts = site.get("artifacts", [])
missing_site = []
verified_site = []
for artifact in artifacts if isinstance(artifacts, list) else []:
artifact_path = Path(str(artifact))
if not artifact_path.is_absolute():
artifact_path = path.parent / artifact_path
if not artifact_path.exists() or (artifact_path.is_file() and artifact_path.stat().st_size == 0):
missing_site.append(str(artifact))
continue
verified, detail = verifiable_site_artifact(artifact_path)
if verified:
verified_site.append(f"{artifact}: {detail}")
if not artifacts or missing_site or not verified_site:
add_check(
checks,
"scope:site",
"FAIL",
"Campus site has no artifacts"
if not artifacts
else (
"Missing site artifacts: " + ", ".join(missing_site)
if missing_site
else "Campus site has no verifiable model or image artifact"
),
)
else:
add_check(checks, "scope:site", "PASS", f"{len(verified_site)} verified site artifact(s)")
except Exception as exc:
add_check(checks, "scope:manifest", "FAIL", f"Scope manifest 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("--offline-browser-report")
parser.add_argument("--render", nargs="*", default=[])
parser.add_argument("--audit")
parser.add_argument("--require-audit", action="store_true")
parser.add_argument("--scope-manifest")
parser.add_argument("--require-scope-manifest", action="store_true")
parser.add_argument("--browser-report")
parser.add_argument("--require-browser-report", action="store_true")
parser.add_argument(
"--waiver",
action="append",
default=[],
metavar="CHECK=REASON",
help="Explicitly acknowledge one WARN/SKIP check with a non-empty reason",
)
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:
waivers = parse_waivers(args.waiver)
except ValueError as exc:
print(f"GATE FAIL [waiver]: {exc}", file=sys.stderr)
return 3
try:
source_report = json.loads(Path(args.source_report).read_text(encoding="utf-8"))
showcase_schema.validate_source_report(source_report)
source_gate = source_report["gate"]
source_status = str(source_gate.get("status", "FAIL"))
add_check(
checks,
"cad_source_report",
source_status,
(
f"Source gate {source_status}; {len(source_report['files'])} inspected DXF file(s)"
+ (f"; partial reason: {source_gate.get('partial_reason')}" if source_status == "WARN" else "")
),
)
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.audit:
inspect_audit(Path(args.audit), checks)
elif args.require_audit:
add_check(checks, "audit:report", "FAIL", "Required extraction audit was not supplied")
if args.scope_manifest:
inspect_scope(Path(args.scope_manifest), checks)
elif args.require_scope_manifest:
add_check(checks, "scope:manifest", "FAIL", "Required scope manifest was not supplied")
if args.offline_viewer:
inspect_offline(Path(args.offline_viewer), checks)
if args.offline_browser_report:
inspect_browser_report(Path(args.offline_browser_report), checks, "offline:browser-smoke")
else:
add_check(
checks,
"offline:browser-smoke",
"SKIP",
"Offline viewer has no real file:// browser smoke report",
)
if args.browser_report:
inspect_browser_report(Path(args.browser_report), checks)
elif args.web_dir or args.require_browser_report:
add_check(checks, "browser:smoke", "SKIP", "Formal Web delivery has no browser smoke report")
apply_waivers(checks, waivers)
status = (
"FAIL"
if any(item["status"] == "FAIL" for item in checks)
else "BLOCKED"
if any(item["status"] in {"WARN", "SKIP"} for item in checks)
else "PASS"
)
evidence = {
"evidence_version": 1,
"generated_at": datetime.now(timezone.utc).isoformat(),
"status": status,
"waivers": [{"check": name, "reason": reason} for name, reason in sorted(waivers.items())],
"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 != "PASS":
for item in checks:
if item["status"] in {"FAIL", "WARN", "SKIP"}:
print(f"GATE {status} [{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,83 @@
#!/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({ 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 actualViewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
const viewportMatches = actualViewport.width === viewport.width && actualViewport.height === viewport.height;
checks.push({
name: `${name}:viewport`,
status: viewportMatches ? "PASS" : "FAIL",
detail: `${actualViewport.width}x${actualViewport.height} expected ${viewport.width}x${viewport.height}`,
});
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

@@ -26,9 +26,13 @@ from __future__ import annotations
import argparse
import base64
import gzip
import html as html_lib
import json
import struct
from pathlib import Path
import showcase_schema
SKILL_ROOT = Path(__file__).resolve().parent.parent
@@ -51,10 +55,27 @@ def group_of(key: str) -> str:
return "主体"
MAIN_JS = r'''
def glb_extensions(path: Path) -> set[str]:
"""Return extensionsUsed from the GLB JSON chunk without extra dependencies."""
data = path.read_bytes()
if len(data) < 20 or data[:4] != b"glTF":
raise SystemExit(f"Not a valid GLB: {path}")
chunk_length, chunk_type = struct.unpack_from("<II", data, 12)
if chunk_type != 0x4E4F534A or 20 + chunk_length > len(data):
raise SystemExit(f"GLB JSON chunk is missing or truncated: {path}")
document = json.loads(data[20 : 20 + chunk_length].decode("utf-8").rstrip("\x00 \t\r\n"))
return set(document.get("extensionsUsed", []))
def script_json(value) -> str:
"""Serialize JSON for an inline script without allowing an early script close."""
return json.dumps(value, ensure_ascii=False).replace("</", "<\\/")
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>'; };
const fail = m => { $load.style.display='flex'; $load.textContent = '加载失败:'+m; };
window.addEventListener('error', e => fail(e.message));
window.addEventListener('unhandledrejection', e => fail(e.reason && e.reason.message || e.reason));
try {
@@ -117,6 +138,7 @@ MAIN_JS = r'''
}
if (cat === 'trees') o.visible = false;
});
window.__offlineReady = {meshes:nodes.length};
if (TREES.length) {
const ti = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.14,0.2,1.4,6),
new THREE.MeshStandardMaterial({color:0x6b4a2e, roughness:0.9}), TREES.length);
@@ -145,8 +167,9 @@ MAIN_JS = r'''
head.appendChild(document.createTextNode(gname)); head.appendChild(btn); tg.appendChild(head);
GROUPS[gname].forEach(f => {
const l = document.createElement('label');
l.innerHTML = '<input id="cb_'+f[0]+'" type="checkbox" checked> '+f[0]+' '+f[1];
l.querySelector('input').onchange = e => { state.fl[f[0]]=e.target.checked; apply(); };
const input = document.createElement('input'); input.id='cb_'+f[0]; input.type='checkbox'; input.checked=true;
input.onchange = e => { state.fl[f[0]]=e.target.checked; apply(); };
l.appendChild(input); l.appendChild(document.createTextNode(' '+f[0]+' '+f[1]));
tg.appendChild(l);
});
}
@@ -157,8 +180,9 @@ MAIN_JS = r'''
for (const k in CATS) {
if (!used[k] || k==='trees') continue;
const l = document.createElement('label');
l.innerHTML = '<input type="checkbox" checked> '+CATS[k];
l.querySelector('input').onchange = e => { state.ct[k]=e.target.checked; apply(); };
const input = document.createElement('input'); input.type='checkbox'; input.checked=true;
input.onchange = e => { state.ct[k]=e.target.checked; apply(); };
l.appendChild(input); l.appendChild(document.createTextNode(' '+CATS[k]));
tg.appendChild(l);
}
const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), info = document.getElementById('info');
@@ -175,7 +199,10 @@ MAIN_JS = r'''
hi.material = hiMat.clone(); hi.material.emissive = new THREE.Color(0x2a6bd4); hi.material.emissiveIntensity = 0.55;
const p = (hi.name||'').split('__');
let fname=''; for (const gname in GROUPS) GROUPS[gname].forEach(f => { if (f[0]===p[0]) fname=f[1]; });
info.innerHTML = '<b>'+p[0]+'</b> '+fname+'<br>构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name;
info.replaceChildren();
const strong=document.createElement('b'); strong.textContent=p[0]; info.appendChild(strong);
info.appendChild(document.createTextNode(' '+fname)); info.appendChild(document.createElement('br'));
info.appendChild(document.createTextNode('构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name));
info.style.display = 'block';
invalidate();
});
@@ -188,35 +215,51 @@ MAIN_JS = r'''
addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); invalidate(); });
} catch (err) { fail(err.message || String(err)); }
})();
'''
"""
CSS = (
'body{margin:0;background:#1c1f24;color:#e8e6e0;font:14px/1.5 -apple-system,"PingFang SC",sans-serif;overflow:hidden}'
'#panel{position:fixed;top:12px;left:12px;background:rgba(244,241,232,.97);color:#2a2a26;border-radius:12px;padding:12px 14px;width:242px;max-height:92vh;overflow:auto;box-shadow:0 4px 18px rgba(0,0,0,.45);z-index:5}'
'#panel h1{font-size:15px;margin:0 0 2px}'
'#panel .sub{font-size:12px;color:#777;margin-bottom:6px}'
'#panel label{display:flex;gap:6px;align-items:center;font-size:13px;padding:1px 0;cursor:pointer}'
'.grp{border-top:1px solid #ddd;margin-top:8px;padding-top:6px;font-weight:600;font-size:12px;color:#555;display:flex;justify-content:space-between;align-items:center}'
'.grp button{font-size:11px;border:none;background:#e5e0d2;border-radius:6px;padding:1px 8px;cursor:pointer}'
'#info{position:fixed;bottom:14px;left:14px;background:rgba(30,33,38,.92);border:1px solid #3a3f46;color:#e8e6e0;border-radius:10px;padding:8px 12px;font-size:13px;display:none;max-width:340px;z-index:5}'
'#hint{position:fixed;bottom:10px;right:14px;font-size:12px;color:#9aa;z-index:5}'
'#load{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;color:#cfd3c9;font-size:14px;background:#1c1f24;z-index:9}'
'body{margin:0;background:#1c1f24;color:#e8e6e0;font:14px/1.5 -apple-system,"PingFang SC",sans-serif;overflow:hidden}'
"#panel{position:fixed;top:12px;left:12px;background:rgba(244,241,232,.97);color:#2a2a26;border-radius:12px;padding:12px 14px;width:242px;max-height:92vh;overflow:auto;box-shadow:0 4px 18px rgba(0,0,0,.45);z-index:5}"
"#panel h1{font-size:15px;margin:0 0 2px}"
"#panel .sub{font-size:12px;color:#777;margin-bottom:6px}"
"#panel label{display:flex;gap:6px;align-items:center;font-size:13px;padding:1px 0;cursor:pointer}"
".grp{border-top:1px solid #ddd;margin-top:8px;padding-top:6px;font-weight:600;font-size:12px;color:#555;display:flex;justify-content:space-between;align-items:center}"
".grp button{font-size:11px;border:none;background:#e5e0d2;border-radius:6px;padding:1px 8px;cursor:pointer}"
"#info{position:fixed;bottom:14px;left:14px;background:rgba(30,33,38,.92);border:1px solid #3a3f46;color:#e8e6e0;border-radius:10px;padding:8px 12px;font-size:13px;display:none;max-width:340px;z-index:5}"
"#hint{position:fixed;bottom:10px;right:14px;font-size:12px;color:#9aa;z-index:5}"
"#load{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;color:#cfd3c9;font-size:14px;background:#1c1f24;z-index:9}"
)
def main() -> int:
args = parse_args()
spec_path = Path(args.spec)
glb_path = Path(args.glb)
if not glb_path.exists() or glb_path.stat().st_size == 0:
raise SystemExit(f"GLB not found or empty: {glb_path}")
extensions = glb_extensions(glb_path)
if "KHR_draco_mesh_compression" in extensions:
raise SystemExit(
"Offline single-file viewer requires an uncompressed GLB; "
f"KHR_draco_mesh_compression found in {glb_path}. Pass the matching *.raw.glb instead."
)
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 +267,34 @@ 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 建筑模型")
title = str(args.title or spec.get("project", {}).get("name", "CAD 建筑模型"))
escaped_title = html_lib.escape(title, quote=True)
escaped_subtitle = html_lib.escape(str(args.subtitle), quote=True)
main_js = (MAIN_JS
.replace("__GROUPS__", json.dumps(groups, ensure_ascii=False))
.replace("__CATS__", json.dumps(cats, ensure_ascii=False))
.replace("__TREES__", json.dumps(trees)))
main_js = (
MAIN_JS.replace("__GROUPS__", script_json(groups))
.replace("__CATS__", script_json(cats))
.replace("__TREES__", script_json(trees))
)
sc_close = "</scr" + "ipt>"
html = (
'<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8">'
f'<title>{title} · 3D 查看器(离线版)</title>'
f"<title>{escaped_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>'
f'<div id="panel"><h1>{escaped_title}</h1><div class="sub">{escaped_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 +302,17 @@ def main() -> int:
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(html, encoding="utf-8")
print(json.dumps({"out": str(out), "kb": len(html) // 1024,
"floors": sum(len(v) for v in groups.values()), "trees": len(trees)}, ensure_ascii=False))
print(
json.dumps(
{
"out": str(out),
"kb": len(html) // 1024,
"floors": sum(len(v) for v in groups.values()),
"trees": len(trees),
},
ensure_ascii=False,
)
)
return 0

View File

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

126
tests/test_browser_smoke.py Normal file
View File

@@ -0,0 +1,126 @@
from __future__ import annotations
import json
import os
import shutil
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,
)
npm = shutil.which("npm.cmd" if sys.platform == "win32" else "npm") or shutil.which("npm")
assert npm, "npm executable not found"
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
result = json.loads(report.read_text(encoding="utf-8"))
assert result["status"] == "PASS"
checks = {item["name"]: item for item in result["checks"]}
assert checks["desktop:viewport"]["detail"] == "1440x900 expected 1440x900"
assert checks["mobile:viewport"]["detail"] == "390x844 expected 390x844"
offline = tmp_path / "viewer.html"
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "write_offline_viewer.py"),
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
],
check=True,
)
offline_report = tmp_path / "offline_browser_report.json"
offline_screenshot = tmp_path / "offline_browser.png"
proc = subprocess.run(
[
"node",
str(ROOT / "scripts" / "offline_viewer_smoke.mjs"),
"--viewer",
str(offline),
"--out",
str(offline_report),
"--screenshot",
str(offline_screenshot),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
offline_result = json.loads(offline_report.read_text(encoding="utf-8"))
assert offline_result["status"] == "PASS"
assert offline_screenshot.exists()
finally:
server.terminate()
server.wait(timeout=10)

805
tests/test_contracts.py Normal file
View File

@@ -0,0 +1,805 @@
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 audit_showcase_extraction # noqa: E402
import build_blender_showcase # noqa: E402
import cad_showcase # noqa: E402
import delivery_waivers # noqa: E402
import derive_showcase_spec # 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_vertical_storey_continuity_rejects_representative_floor_islands() -> None:
spec = minimal_spec()
spec["floors"]["F2"] = {**spec["floors"]["F1"], "name": "二层", "z": 5.0}
spec["floors"]["F16"] = {**spec["floors"]["F1"], "name": "十六层", "z": 59.6}
gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec)
assert gate["status"] == "WARN"
assert "F2->F16" in gate["detail"]
def test_vertical_storey_continuity_accepts_instantiated_typical_floors() -> None:
spec = minimal_spec()
base = spec["floors"]["F1"]
spec["floors"] = {f"F{number}": {**base, "name": f"{number}层", "z": (number - 1) * 3.9} for number in range(1, 17)}
gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec)
assert gate["status"] == "PASS"
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_requires_reason_for_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="partial reason"):
showcase_schema.validate_source_report(report)
def test_source_report_accepts_reasoned_partial_gate() -> None:
report = {
"report_version": 1,
"gate": {
"name": "all_sources_converted_and_readable",
"status": "WARN",
"partial_reason": "One optional elevation DWG is unavailable",
},
"files": [{"file": "partial.dxf", "status": "ok", "modelspace_entities": 1}],
}
assert showcase_schema.validate_source_report(report) == report
def test_unarmed_cross_evidence_gates_are_not_applicable() -> None:
spec = minimal_spec()
assert audit_showcase_extraction.frame_ledger_gate({}, None)["status"] == "NOT_APPLICABLE"
assert audit_showcase_extraction.declared_area_gate(spec, {})["status"] == "NOT_APPLICABLE"
assert audit_showcase_extraction.storey_count_gate(spec, {})["status"] == "NOT_APPLICABLE"
def test_multi_frame_source_requires_detector_ledger() -> None:
report = {
"files": [
{"file": "A212.dxf", "status": "ok", "plan_title_count": 2},
{"file": "A213.dxf", "status": "ok", "plan_title_count": 1},
]
}
assert cad_showcase.multi_frame_source_files(report) == ["A212.dxf"]
def test_frame_ledger_requires_distinct_floor_identity_even_when_roof_clips_overlap() -> None:
frames = [
{
"drawings": [
{
"file": "A212.dxf",
"floors": [
{
"key": "RF",
"name": "屋面平面图",
"clip": [0, 0, 100, 100],
"include_block_names": ["*-屋面平面图"],
},
{
"key": "PH",
"name": "机房小屋面",
"clip": [0, 0, 100, 100],
"include_block_names": ["*-机房小屋面"],
},
],
}
]
}
]
config = {
"drawings": [
{
"file": "A212.dxf",
"floors": [
{"key": "RF", "clip": [0, 0, 100, 100]},
{"key": "PH", "clip": [0, 0, 100, 100]},
],
}
]
}
gate = audit_showcase_extraction.frame_ledger_gate(config, frames)
assert gate["status"] == "FAIL"
assert "屋面平面图" in gate["detail"]
config["drawings"][0]["floors"][0]["include_block_names"] = ["*-屋面平面图"]
config["drawings"][0]["floors"][1]["include_block_names"] = ["*-机房小屋面"]
assert audit_showcase_extraction.frame_ledger_gate(config, frames)["status"] == "PASS"
def test_revit_view_block_selector_separates_overlapping_floor_views() -> None:
rf = {"include_block_names": ["*-屋面平面图"]}
drawing: dict = {}
assert derive_showcase_spec.block_matches_floor("墙族-123-屋面平面图", rf, drawing)
assert not derive_showcase_spec.block_matches_floor("墙族-456-机房小屋面", rf, drawing)
assert not derive_showcase_spec.block_matches_floor("", rf, drawing)
def test_disconnected_footprint_island_fails_until_explicitly_explained() -> None:
spec = minimal_spec()
spec["floors"]["F1"]["footprint"]["polygons"].append([[25.0, 0.0], [26.0, 0.0], [26.0, 1.0], [25.0, 1.0]])
failed = audit_showcase_extraction.disconnected_footprints_gate(spec, {})
assert failed["status"] == "FAIL"
assert "F1" in failed["detail"]
accepted = audit_showcase_extraction.disconnected_footprints_gate(
spec,
{"allowed_disconnected_footprints": [{"floor_key": "F1", "reason": "独立雨棚,有柱网证据"}]},
)
assert accepted["status"] == "PASS"
def test_annotation_is_waivable_warn_and_absent_glazing_is_not_applicable() -> None:
report = {
"spec_counts": {"F1": {"glazing": 0}},
"block_locked_layers": [],
"top_insert_names": [],
"classified_layers": [{"layer": "A-ANNO-DIMS"}],
"coverage": {
"block_locked_classifiable_length_meters": 0,
"block_captured_classified_length_meters": 0,
},
}
gates = {
gate["name"]: gate["status"]
for gate in audit_showcase_extraction.evaluate_gates(report, minimal_spec(), {}, None)
}
assert gates["no_annotation_layers_classified"] == "WARN"
assert gates["glazing_captured"] == "NOT_APPLICABLE"
def test_config_rejects_malformed_category_overrides() -> None:
config = {
"config_version": 1,
"drawings": [{"file": "fixture.dxf", "floors": [{"key": "F1"}]}],
"categories": {"walls": "not-an-object"},
}
with pytest.raises(showcase_schema.ValidationFailure, match="categories.walls"):
showcase_schema.validate_config(config)
def test_all_derive_geometry_loss_warnings_are_forbidden() -> None:
assert set(cad_showcase.DERIVE_FORBIDDEN_WARNINGS) == {
"WARNING isolated_cluster",
"WARNING unsupported_roof",
"WARNING floor_order",
"WARNING topless_group",
}
def test_waivers_share_one_implementation_and_reject_not_applicable_targets(tmp_path: Path) -> None:
import verify_delivery
assert cad_showcase.parse_waivers is delivery_waivers.parse_waivers
assert verify_delivery.parse_waivers is delivery_waivers.parse_waivers
audit = tmp_path / "audit.json"
audit.write_text(
json.dumps(
{
"gates": [
{
"name": "frame_ledger",
"status": "NOT_APPLICABLE",
"detail": "No frame report supplied",
}
]
}
),
encoding="utf-8",
)
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
assert not cad_showcase.enforce_audit_gates(
pipeline,
audit,
{"audit:frame_ledger": "pre-approved in case this gate becomes armed"},
)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
blocked = state["blocked_gates"]
assert blocked[0]["name"] == "waiver:audit:frame_ledger"
assert "NOT_APPLICABLE" in blocked[0]["detail"]
def test_audit_waiver_typo_fails_before_downstream_work(tmp_path: Path) -> None:
audit = tmp_path / "audit.json"
audit.write_text(
json.dumps({"gates": [{"name": "floors_aligned", "status": "PASS", "detail": "aligned"}]}),
encoding="utf-8",
)
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
assert not cad_showcase.enforce_audit_gates(
pipeline,
audit,
{"audit:floors_aligend": "typo must not survive to final verification"},
)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
assert state["blocked_gates"][0]["name"] == "waiver:audit:floors_aligend"
def test_waiver_preflight_rejects_misspelled_namespace_and_extra_future_waiver(tmp_path: Path) -> None:
scope = tmp_path / "scope.json"
scope.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["main"],
"buildings": [{"id": "main", "status": "PASS", "artifacts": ["future.glb"]}],
}
),
encoding="utf-8",
)
args = cad_showcase.parser().parse_args(
[
"run",
"--dxf-dir",
str(tmp_path),
"--config",
str(tmp_path / "config.json"),
"--source-report",
str(tmp_path / "source.json"),
"--out-dir",
str(tmp_path / "out"),
"--scope-manifest",
str(scope),
"--web",
]
)
invalid = cad_showcase.preflight_waiver_targets(
args,
{"gate": {"status": "PASS"}},
{"gates": [{"name": "floors_aligned", "status": "WARN", "detail": "needs evidence"}]},
scope,
{
"audti:floors_aligned": "misspelled namespace",
"browser:smoke": "cannot pre-waive a generated PASS check",
},
)
assert {check["name"] for check in invalid} == {
"waiver:audti:floors_aligned",
"waiver:browser:smoke",
}
def test_default_cap_buffer_is_small_and_large_overhang_is_explicit() -> None:
pytest.importorskip("shapely")
base_floor = {
"name": "一层",
"z": 0.0,
"height": 3.0,
"bounds": [0.0, 0.0, 10.0, 10.0],
"source_file": "fixture.dxf",
"segments": {},
"footprint": {"polygons": [[[0, 0], [10, 0], [10, 10], [0, 10]]]},
}
upper_floor = {**base_floor, "name": "二层", "z": 3.0}
floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))}
derive_showcase_spec.compute_caps(floors, {})
default_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon)
assert default_max_x == pytest.approx(10.1)
floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))}
derive_showcase_spec.compute_caps(floors, {"cap_buffer": 1.3})
colonnade_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon)
assert colonnade_max_x == pytest.approx(11.3)
def test_pipeline_fails_on_derive_geometry_loss_warning(tmp_path: Path) -> None:
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
command = [
sys.executable,
"-c",
"import sys; print('WARNING isolated_cluster F1: dropped geometry', file=sys.stderr)",
]
with pytest.raises(SystemExit):
pipeline.run("derive", command, [], forbidden_stderr=cad_showcase.DERIVE_FORBIDDEN_WARNINGS)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
assert state["steps"]["derive"]["status"] == "FAIL"
assert state["steps"]["derive"]["forbidden_stderr_hits"] == ["WARNING isolated_cluster"]
def test_windows_command_resolution_uses_cmd_shims(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(cad_showcase.sys, "platform", "win32")
monkeypatch.setattr(
cad_showcase.shutil,
"which",
lambda candidate: f"C:/tools/{candidate}" if candidate in {"npm.cmd", "node.exe"} else None,
)
assert cad_showcase.npm_command("install")[0] == "C:/tools/npm.cmd"
assert cad_showcase.node_script(Path("smoke.mjs"))[0] == "C:/tools/node.exe"
def test_resume_fingerprint_tracks_tools_offline_libs_and_extra_inputs(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
root = tmp_path / "skill"
scripts = root / "scripts"
dxf_dir = tmp_path / "dxf"
for directory in (
scripts,
root / "schemas",
root / "tools",
root / "assets" / "web-showcase-template",
root / "assets" / "offline-viewer-libs",
dxf_dir,
):
directory.mkdir(parents=True, exist_ok=True)
config = tmp_path / "config.json"
source = tmp_path / "source.json"
frames = tmp_path / "frames.json"
config.write_text("{}", encoding="utf-8")
source.write_text("{}", encoding="utf-8")
frames.write_text("{}", encoding="utf-8")
(dxf_dir / "plan.dxf").write_text("DXF", encoding="utf-8")
(scripts / "step.py").write_text("pass", encoding="utf-8")
compressor = root / "tools" / "compress.mjs"
compressor.write_text("v1", encoding="utf-8")
offline_lib = root / "assets" / "offline-viewer-libs" / "three.min.js"
offline_lib.write_text("v1", encoding="utf-8")
monkeypatch.setattr(cad_showcase, "ROOT", root)
monkeypatch.setattr(cad_showcase, "SCRIPTS", scripts)
first = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
compressor.write_text("v2", encoding="utf-8")
second = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
offline_lib.write_text("v2", encoding="utf-8")
third = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
frames.write_text('{"changed": true}', encoding="utf-8")
fourth = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
assert len({first, second, third, fourth}) == 4
def test_pipeline_state_is_atomic_and_corruption_is_loud(tmp_path: Path) -> None:
state = tmp_path / "pipeline_state.json"
pipeline = cad_showcase.Pipeline(state, "fingerprint", resume=False)
pipeline.state["proof"] = "saved"
pipeline.save()
assert json.loads(state.read_text(encoding="utf-8"))["proof"] == "saved"
assert not list(tmp_path.glob(".pipeline_state.json.*.tmp"))
state.write_text("{truncated", encoding="utf-8")
with pytest.raises(SystemExit, match="corrupt and was not overwritten"):
cad_showcase.Pipeline(state, "fingerprint", resume=True)
assert state.read_text(encoding="utf-8") == "{truncated"
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_normalize_spec_backfills_categories_used_by_legacy_segments() -> None:
legacy = minimal_spec()
legacy.pop("schema_version")
legacy.pop("categories")
legacy["floors"]["F1"]["segments"]["legacy_custom"] = [
{"start": [0, 0], "end": [0, 1], "width": 0.1, "layer": "OLD", "source_type": "LINE"}
]
normalized = showcase_schema.normalize_spec(legacy)
assert normalized["categories"]["walls"] == {"label": "墙体", "color": "#d4cbb8"}
assert normalized["categories"]["slab"] == {"label": "楼板", "color": "#c8ccc2"}
assert normalized["categories"]["legacy_custom"] == {"label": "legacy_custom", "color": "#8c9088"}
showcase_schema.validate_spec(normalized)
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_showcase.py"),
"inspect",
"--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_showcase.py"),
"inspect",
"--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"
scope_manifest = tmp_path / "scope_manifest.json"
scope_manifest.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["orchestrator-test"],
"buildings": [
{
"id": "orchestrator-test",
"status": "PASS",
"artifacts": [str(out / "building_spec.json")],
}
],
}
),
encoding="utf-8",
)
command = [
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"run",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config_path),
"--source-report",
str(source_report),
"--scope-manifest",
str(scope_manifest),
"--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

608
tests/test_delivery.py Normal file
View File

@@ -0,0 +1,608 @@
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 browser_report_payload(*, offline: bool = False) -> dict:
if offline:
checks = [
{"name": "offline:viewport", "status": "PASS", "detail": "1440x900 expected 1440x900"},
{"name": "offline:model-ready", "status": "PASS", "detail": "1 mesh(es)"},
{"name": "offline:canvas", "status": "PASS"},
{"name": "offline:render", "status": "PASS", "detail": "1 render(s)"},
]
else:
checks = []
for viewport, detail in (
("desktop", "1440x900 expected 1440x900"),
("mobile", "390x844 expected 390x844"),
):
checks.append({"name": f"{viewport}:viewport", "status": "PASS", "detail": detail})
for selector in ("#floor-controls", "#category-controls", "#explode", "#section", "#snapshot"):
checks.append({"name": f"{viewport}:{selector}", "status": "PASS"})
checks.append({"name": f"{viewport}:idle-render", "status": "PASS", "detail": "3->3"})
return {
"status": "PASS",
"detail": f"{len(checks)}/{len(checks)} checks passed",
"checks": checks,
"console_errors": [],
"page_errors": [],
"failed_requests": [],
}
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
offline_browser_report = tmp_path / "offline_browser_smoke_report.json"
offline_browser_report.write_text(
json.dumps(browser_report_payload(offline=True)),
encoding="utf-8",
)
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),
"--offline-browser-report",
str(offline_browser_report),
"--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"])
assert any(item["name"] == "offline:browser-smoke" and item["status"] == "PASS" for item in report["checks"])
def test_browser_report_cannot_forge_pass_without_required_checks(tmp_path: Path) -> None:
import verify_delivery
path = tmp_path / "forged.json"
path.write_text(
json.dumps(
{
"status": "PASS",
"checks": [],
"console_errors": [],
"page_errors": [],
"failed_requests": [],
}
),
encoding="utf-8",
)
checks: list[dict] = []
verify_delivery.inspect_browser_report(path, checks)
assert checks[0]["status"] == "FAIL"
assert "non-empty list" in checks[0]["detail"]
def test_render_gate_rejects_high_variance_noise(tmp_path: Path) -> None:
import verify_delivery
noisy = Image.new("RGB", (640, 480))
pixels = noisy.load()
for y in range(noisy.height):
for x in range(noisy.width):
pixels[x, y] = (255, 255, 255) if (x + y) % 2 else (0, 0, 0)
path = tmp_path / "noise.png"
noisy.save(path)
checks: list[dict] = []
verify_delivery.inspect_render(path, checks)
assert checks[0]["status"] == "FAIL"
def test_offline_viewer_without_real_browser_report_is_blocked(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
source_report = source_report_fixture(tmp_path)
evidence = tmp_path / "evidence.json"
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 == 3
report = json.loads(evidence.read_text(encoding="utf-8"))
assert report["status"] == "BLOCKED"
assert any(item["name"] == "offline:browser-smoke" and item["status"] == "SKIP" for item in report["checks"])
def test_offline_viewer_escapes_html_and_inline_script_data(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
document = json.loads(spec.read_text(encoding="utf-8"))
document["project"]["name"] = '<Tower & Co></script><script>alert("title")</script>'
document["floors"]["F1"]["name"] = '首层</script><script>alert("floor")</script>'
document["categories"]["walls"]["label"] = "墙<&>"
spec.write_text(json.dumps(document), encoding="utf-8")
offline = tmp_path / "viewer.html"
proc = run(
sys.executable,
"scripts/write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
"--subtitle",
"<unsafe & subtitle>",
)
assert proc.returncode == 0, proc.stderr
text = offline.read_text(encoding="utf-8")
assert "&lt;Tower &amp; Co&gt;&lt;/script&gt;" in text
assert "&lt;unsafe &amp; subtitle&gt;" in text
assert '首层<\\/script><script>alert(\\"floor\\")<\\/script>' in text
assert '首层</script><script>alert("floor")</script>' not in text
def test_web_variant_entry_requires_a_nonempty_file(tmp_path: Path) -> None:
import verify_delivery
web = tmp_path / "web"
for relative in (
"index.html",
"app.js",
"styles.css",
"model.glb",
"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(
"window.__renders; invalidate(); DRACOLoader; restoreStateFromHash; switchVariant", encoding="utf-8"
)
(web / "model_metadata.json").write_text(json.dumps({"model_variants": [{"key": "standard", "file": ""}]}))
checks: list[dict] = []
verify_delivery.inspect_web(web, checks)
variant_check = next(item for item in checks if item["name"] == "web:variants")
assert variant_check["status"] == "FAIL"
assert "<missing file>" in variant_check["detail"]
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 == 3
assert "browser:smoke" in proc.stderr
browser_report = tmp_path / "browser_smoke_report.json"
browser_report.write_text(
json.dumps(browser_report_payload()),
encoding="utf-8",
)
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),
"--browser-report",
str(browser_report),
"--evidence-out",
str(tmp_path / "web_evidence.json"),
)
assert proc.returncode == 0, proc.stderr
def test_reasoned_partial_source_can_only_pass_with_named_waiver(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)
source = json.loads(source_report.read_text(encoding="utf-8"))
source["gate"] = {
"name": "all_sources_converted_and_readable",
"status": "WARN",
"detail": "one optional elevation is missing",
"partial_reason": "User approved plan-only delivery",
}
source_report.write_text(json.dumps(source), encoding="utf-8")
evidence = tmp_path / "evidence.json"
base = [
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--evidence-out",
str(evidence),
]
proc = run(*base)
assert proc.returncode == 3
assert json.loads(evidence.read_text(encoding="utf-8"))["status"] == "BLOCKED"
proc = run(*base, "--waiver", "cad_source_report=User approved plan-only delivery")
assert proc.returncode == 0, proc.stderr
report = json.loads(evidence.read_text(encoding="utf-8"))
source_check = next(item for item in report["checks"] if item["name"] == "cad_source_report")
assert source_check["original_status"] == "WARN"
def test_warn_or_skip_blocks_without_explicit_reasoned_waiver(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)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--require-browser-report",
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
assert json.loads(evidence.read_text(encoding="utf-8"))["status"] == "BLOCKED"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--require-browser-report",
"--waiver",
"browser:smoke=No browser is available in this offline-only benchmark",
"--evidence-out",
str(evidence),
)
assert proc.returncode == 0, proc.stderr
report = json.loads(evidence.read_text(encoding="utf-8"))
smoke = next(item for item in report["checks"] if item["name"] == "browser:smoke")
assert smoke["status"] == "PASS"
assert smoke["original_status"] == "SKIP"
assert smoke["waiver_reason"]
def test_campus_scope_cannot_pass_with_a_missing_requested_building(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)
site = tmp_path / "site.png"
render_fixture(site)
scope = tmp_path / "scope_manifest.json"
scope.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "campus",
"requested": ["1#", "2#"],
"buildings": [
{"id": "1#", "status": "PASS", "artifacts": [glb.name]},
{"id": "2#", "status": "BLOCKED", "reason": "No readable source drawing", "artifacts": []},
],
"site": {"status": "PASS", "artifacts": [site.name]},
}
),
encoding="utf-8",
)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--scope-manifest",
str(scope),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
report = json.loads(evidence.read_text(encoding="utf-8"))
assert report["status"] == "BLOCKED"
assert any(item["name"] == "scope:building:2#" and item["status"] == "WARN" for item in report["checks"])
def test_scope_rejects_arbitrary_nonempty_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)
fake = tmp_path / "looks-done.txt"
fake.write_text("not a model", encoding="utf-8")
scope = tmp_path / "scope_manifest.json"
scope.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["11#"],
"buildings": [{"id": "11#", "status": "PASS", "artifacts": [fake.name]}],
}
),
encoding="utf-8",
)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--scope-manifest",
str(scope),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
report = json.loads(evidence.read_text(encoding="utf-8"))
check = next(item for item in report["checks"] if item["name"] == "scope:building:11#")
assert check["status"] == "FAIL"
assert "No verifiable" in check["detail"]
def test_required_audit_and_scope_cannot_be_omitted(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)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--require-audit",
"--require-scope-manifest",
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
failed = {
item["name"] for item in json.loads(evidence.read_text(encoding="utf-8"))["checks"] if item["status"] == "FAIL"
}
assert {"audit:report", "scope:manifest"} <= failed
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