Initial commit: cad-building-showcase skill

Agent-led CAD-drawing → 3D web showcase pipeline. Inspects CAD reports,
maps layers/floors, extracts a normalized building spec (with block-probed
glazing and audit gates), builds Blender/trimesh GLB variants, and assembles
a Three.js web viewer. Includes XREF-shell detection and a regression test.

Large inputs/outputs (work/, outputs/, source_cad/, renders) are gitignored.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-12 16:16:04 +08:00
commit a6ac166049
26 changed files with 6228 additions and 0 deletions

View File

@@ -0,0 +1,118 @@
# A208 Case Notes
These notes capture the proven workflow from the A208 CAD-to-3D exploration. Use them as calibration, not as hardcoded constants.
## Source Set
The test project used 11 DWG floor-plan drawings from an XREF folder:
- A202 basement
- A205 basement mezzanine
- A208 main building 1F/2F
- A209 main building 3F/4F
- A210 main building 5F/6F
- A211 main building 7F/8F
- A212 main building roof
- A213 auxiliary building 1F
- A214 auxiliary building mezzanine
- A215 auxiliary building 2F
- A216 auxiliary building roof
DWG versions were AutoCAD 2004/2007-era files.
## Conversion and Reading
- FreeCAD 1.0.2 CLI existed at `/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd`.
- FreeCAD DXF import was brittle on LibreDWG-generated DXF because of `999` comment records and unsupported CAD entities such as `HATCH`, `VIEWPORT`, and `DIMENSION`.
- `libredwg` `dwg2dxf` plus `ezdxf` was the robust read path.
- Sanitizing DXF `999` comment pairs made files more compatible with other importers.
## Useful Layer Signals
For A208, useful layers included:
- `I-WALL`, `A-WALL`, `L-SITE-WALL`: walls
- `S-COLS`: columns
- `S-STRS`, `S-STRS-MBND`: beams/structure
- `A-FLOR`, `A-FLOR-OVHD`: floor detail
- `S-GRID`: structural grid
Avoid treating dimensions, hatches, text, and annotation layers as 3D geometry unless the goal is a drawing overlay.
## A208 Split and Alignment
A208 placed 1F and 2F side by side in one drawing. The working split used x=0 in source millimeter coordinates:
- Left side: 1F
- Right side: 2F
- 2F alignment shift: about `-158029.255 mm` in X
This shift was inferred from grid/plan alignment. It should not be reused for other drawings without checking grids.
## Extraction Details That Improved Quality
The A208-specific script handled:
- `LINE`
- `ARC`
- `CIRCLE`
- `LWPOLYLINE`
- `SPLINE`
It also used category-specific minimum segment lengths:
- walls: `0.25 m`
- columns: `0.18 m`
- beams: `0.35 m`
- floor lines: `0.40 m`
- grid: `1.0 m`
This filtered CAD noise better than one global line-length threshold.
## Showcase Model Result
The A208 massing/showcase model contained:
- floors: 2
- Blender scene objects: 17
- GLB and preview render generated successfully
- Web viewer verified on desktop and mobile
- Web controls verified: floor toggles, category toggles, explode slider, section slider, camera presets, screenshot, GLB download
This is best described as Web showcase / LOD100-150-like massing visualization, not BIM.
## Full-Building Presentation Calibration
The later full-building run expanded the workflow from a two-floor proof to a multi-floor Web presentation model. Treat these as calibration decisions, not constants:
- Use `generate_footprints: true`, `use_footprint_slabs: true`, and `use_footprint_roofs: true` when the user expects a complete interior/exterior presentation.
- Include `columns` in `footprint_categories` when column rows define platform or podium extents that wall/glazing linework misses.
- Keep `slab` enabled by default for presentation/digital-twin views. Use a display `slab_thickness` around `0.35-0.40 m`, double-sided Web materials, and opacity high enough that slab edges read through glazing.
- Keep in-scene floor labels/text off by default; CAD text-like transparent planes clutter the model and are not needed when the Web UI already names floors.
- For generated roof caps, use the roof floor's own `footprint_from` source. Broadly unioning lower floor footprints can create roof plates that protrude into empty areas.
- For 1F/podium columns, require an upper plate plus nearby upper structure before keeping them full height. Shorten unsupported display columns unless there is CAD evidence that they are freestanding architectural elements.
- Produce three Web variants for delivery: `overview` for fast browsing, `standard` as the default visible model, and `detail` for extraction review.
## IFC Proof Result
The IFC proof generated:
- `IfcBuildingStorey`: 2
- `IfcSlab`: 2
- `IfcWall`: 320
- `IfcColumn`: 160
- `IfcBeam`: 160
- `IfcPropertySet`: 643
- `IfcExtrudedAreaSolid`: 642
Geometry extraction succeeded with zero failures in the tested run. This validates a BIM-feasibility route, but still does not prove production BIM replacement.
## Blender IFC Viewing
The tested Blender 5.1.1 environment did not have a direct IFC import operator or Bonsai/BlenderBIM installed. The working visualization route was:
1. Generate IFC with IfcOpenShell.
2. Extract IFC product geometry with IfcOpenShell.
3. Render extracted meshes in Blender.
Use Bonsai/BlenderBIM only when installed and compatible with the current Blender Python version.

View File

@@ -0,0 +1,59 @@
# Agent Review Checklist
Use this checklist after `building_spec.json`, extraction audit, and overlay SVGs exist.
## Accept for Web Showcase
Accept when:
- Main floor outlines, walls, columns, beams, floor detail, and grid are visible in overlays.
- Unclassified geometry is mostly annotation, dimensions, text, furniture, landscaping, or detail symbols.
- High-risk `INSERT`/`HATCH` entities are either irrelevant or visually accounted for by extracted linework.
- Blender preview is nonblank, correctly framed, and visually matches the floor-plan intent.
- Web viewer loads with clean console logs and controls work.
- Presentation/digital-twin views show readable slab edges from side views; floor plates do not disappear behind glazing.
- Generated roofs use roof-floor footprints unless CAD evidence supports a canopy/overhang.
- Ground/podium columns that have no upper plate plus nearby upper structure are shortened or documented as intentional.
- Web delivery exposes overview, standard, and detail GLB downloads when lightweight variants were requested.
State known gaps in the notes.
## Iterate Extraction
Return to config or parser work when:
- Red dashed overlay geometry forms obvious walls, columns, beams, grids, stairs, or slab outlines.
- A large unclassified layer has high supported vector length and architectural names.
- Frequent `INSERT` blocks likely contain architectural geometry.
- `HATCH` or `SOLID` represents primary filled walls/columns and line extraction missed it.
- Multiple floors are misaligned after overlay/Blender review.
- Generated slabs are much larger/smaller than the true building footprint.
- Slabs are technically present but visually unreadable from side views.
- Generated roof caps extend across unrelated lower-floor footprints.
- Many columns stand full-height with no upper floor/roof or nearby upper structural support.
- Web/digital-twin output has only one heavy GLB when the user requested lightweight download tiers.
## Escalate Beyond Line Extraction
Use additional strategies when needed:
- Recursive block expansion for `INSERT`.
- Hatch boundary extraction for filled wall/slab/column regions.
- OCR/title-block reading for floor labels when filenames are ambiguous.
- Manual floor split rectangles for complex sheet layouts.
- Footprint tuning with wall/glazing/floor-line/railing/column source categories.
- Variant generation with `build_showcase_variants.py` before writing the Web viewer.
- IFC/BIM generation only after extracted geometry passes showcase-level review.
## BIM Claim Rules
Never call the Web showcase a BIM replacement.
Call it an IFC/BIM proof only when:
- IFC entities exist with storeys and spatial containment.
- `IfcWall`, `IfcColumn`, `IfcBeam`, `IfcSlab` counts are reported.
- IfcOpenShell geometry generation succeeds or failures are explained.
- Remaining gaps are listed: openings, rooms/spaces, doors/windows, quantities, materials, classifications, georeferencing, and coordination.
Call it a BIM replacement candidate only after discipline-specific semantic validation, quantity validation, and human review.

View File

@@ -0,0 +1,182 @@
# building_spec.json Schema
Use `building_spec.json` as the contract between CAD extraction, Blender generation, and the Web showcase.
## Top Level
```json
{
"project": {
"name": "Project name",
"description": "Short user-facing description"
},
"source": {
"cad_folder": "work/XREF",
"report": "outputs/cad_read_report.json",
"config": {
"generate_footprints": true,
"use_footprint_slabs": true,
"use_footprint_roofs": true,
"footprint_categories": ["walls", "glazing", "floor_lines", "railings", "columns"],
"slab_thickness": 0.38,
"default_disabled_categories": []
}
},
"units": {
"source": "millimeters",
"scale_to_meters": 0.001,
"origin_source": [0.0, 0.0]
},
"categories": {
"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"}
},
"floors": {
"1F": {
"name": "首层",
"z": 0.0,
"height": 4.2,
"bounds": [0.0, 0.0, 80.0, 42.0],
"source_file": "A208.dxf",
"footprint": {
"method": "concave_hull",
"source_categories": ["walls", "glazing", "floor_lines", "railings", "columns"],
"area": 3120.4,
"polygons": [
[[0.0, 0.0], [80.0, 0.0], [80.0, 42.0], [0.0, 42.0]]
]
},
"segments": {
"walls": [],
"glazing": [],
"roof": [],
"columns": [],
"beams": [],
"railings": [],
"doors": [],
"detail_lines": [],
"floor_lines": [],
"grid": []
}
}
}
}
```
## Segment Shape
Each segment is a straight prism centerline in meters:
```json
{
"start": [12.0, 3.5],
"end": [18.0, 3.5],
"width": 0.2,
"layer": "I-WALL",
"source_type": "LINE"
}
```
Use short chord segments for polylines and arcs. The showcase model does not need exact NURBS/curve preservation unless the user asks for close-up modeling.
`derive_showcase_spec.py` supports `LINE`, `LWPOLYLINE`, `POLYLINE`, `ARC`, `CIRCLE`, and `SPLINE` by converting curves into short line segments. Configure curve density with `curve_chord_source_length`.
It can also expand `INSERT` blocks when the Agent enables `expand_blocks`. Keep the block expansion decision in the config so the final notes can explain whether block geometry was used.
## Category Semantics
- `walls`: vertical extrusions from floor `z` to `z + height`. Include architectural wall layers and obvious site/partition wall layers.
- `glazing`: transparent full-height extrusions for curtain wall, window wall, or glass layers. Keep separate from opaque walls so missing walls are not confused with glass.
- `roof`: opaque or near-opaque cover geometry for roof slabs, canopies, or generated roof caps. It may be generated from `roof_specs` instead of direct CAD roof line segments when roof drawings are sparse.
- `columns`: vertical extrusions from floor `z` to `z + height`. For CAD outlines, extrude the visible outline linework rather than trying to infer a single solid column unless the source is clean.
- `beams`: horizontal extrusions near the floor ceiling, normally `z + height - beam_drop` to `z + height`.
- `railings`: low vertical extrusions, normally about 1.1-1.2 m above the floor.
- `doors`: door leaf/opening arcs and swing lines, normally about 2.1-2.3 m above the floor for visual context.
- `detail_lines`: low plan strips for generic details, parking, area, thin detail, and other high-value linework that should remain visible without being misclassified as vertical walls.
- `floor_lines`: low visual strips just above the slab. Use for floor finish edges and important plan guide lines that are not better represented by a specific category.
- `grid`: thin low strips. Use for axes/control grid only; keep toggleable.
- `slab`: generated by Blender script from each floor `footprint.polygons` when present, otherwise from `bounds`. A footprint slab is a CAD-derived visual plate, not a validated BIM slab with openings, joins, quantities, or fire/acoustic properties.
## Footprint Shape
`derive_showcase_spec.py` can generate `floor.footprint` when the Agent enables footprint generation in the extraction config.
- `method`: usually `concave_hull`.
- `source_categories`: categories used to collect source points, commonly `walls`, `glazing`, `floor_lines`, `railings`, and `columns`.
- `area`: total footprint polygon area in square meters after simplification.
- `polygons`: one or more closed polygon rings in meters. Keep only high-confidence, high-area polygons; do not include annotation islands or tiny hatch fragments.
Blender uses these polygons for generated `slab` meshes and can also use them for generated roof/roof-cap meshes. This improves visual accuracy compared with rectangular bounds but is still a presentation approximation unless BIM semantics are generated separately.
## Generation Config Keys
Common `source.config` keys used by `derive_showcase_spec.py` and `build_blender_showcase.py`:
- `generate_footprints`: enables CAD-derived `floor.footprint`.
- `footprint_categories`: source segment categories for footprints. For presentation models, include `columns` when column rows define usable floor plate extents.
- `footprint_concave_ratio`, `footprint_simplify_tolerance`, `footprint_min_area`, `footprint_max_polygons`: tune the concave hull and remove noise.
- `use_footprint_slabs`: use `floor.footprint.polygons` instead of rectangular `bounds` for generated `slab`.
- `use_footprint_roofs`: allow `roof_specs[].footprint_from` polygons to drive generated roof caps.
- `slab_thickness`: display thickness in meters. Use about `0.35-0.40` for Web presentation so floor edges remain visible through glazing.
- `roof_specs[]`: generated roof/canopy definitions. Use `floor_key`, `bounds_from`, and `footprint_from`; do not union lower-floor footprints unless there is CAD evidence for an overhang.
- `shorten_unsupported_columns`: shortens display columns that have no upper support.
- `shorten_unsupported_columns_floor_keys`: optional floor-key filter, commonly ground or podium levels.
- `unsupported_column_height`: shortened display height in meters.
- `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.
## Object Naming
Blender objects for Web output must use:
```text
<floor_key>__<category>
```
Examples:
- `1F__walls`
- `RF__roof`
- `B1__columns`
- `RF__grid`
The Web template parses this double-underscore pattern.
## Metadata
`build_blender_showcase.py` writes `model_metadata.json` for the Web viewer. Keep it aligned with `building_spec.json` and include:
- project name/description
- ordered floors with keys/names/z values
- category labels/colors
- model bounds
- generated file names
- optional `viewer_defaults.disabled_categories`; keep `slab` enabled for presentation/digital-twin views
- optional `model_variants`, normally written by `write_web_showcase.py` from `variants_manifest.json`, for example:
```json
[
{"key": "overview", "label": "总览轻量版", "file": "overview.glb"},
{"key": "standard", "label": "展示标准版", "file": "standard.glb"},
{"key": "detail", "label": "完整审图版", "file": "detail.glb"}
]
```
## Precision Labels
Use these labels in notes:
- `Web showcase`: visual architectural walkthrough/exploded diagram from CAD linework.
- `Massing/LOD100-150`: slabs, walls, columns, beams, floor lines, grid; not parametric BIM.
- `BIM proof`: IFC entities exist and validate, but may not be production BIM.
- `BIM replacement candidate`: only after semantic IFC, openings, spaces, quantities, materials, levels, and coordination checks pass.

View File

@@ -0,0 +1,112 @@
# Skill 优化建议(来自主辅楼建筑群 11 张图实战复盘)
本文记录在一次完整实战(A202/A205/A208–A213 共 11 张 CAD 平面图 → 轻量化 Web 展示模型)中暴露的问题与已验证的修复,作为对 skill 脚本与模板的具体改进建议。修复均已在该项目落地验证。
---
## 0. 一句话结论
- **轻量化的关键 = Draco 压缩 + 查看器挂 DRACOLoader(成对)**,实测体积 ~3–4MB → ~0.4–0.6MB(−92%)。
- **最该修的潜在 bug = glTF 上方向约定不统一**(模板按 Z-up 写,Blender 默认导出 Y-up),会让建筑“躺倒”。
- 几何完整性(块内幕墙、玻璃连续、柱头封顶、地下室顶板)需要新增专门步骤,CAD 平面图本身不会自动给出这些。
---
## 1. 轻量化(最高优先级)
### 1.1 GLB 压缩(`build_blender_showcase.py`)
现状是裸导出:
```python
bpy.ops.export_scene.gltf(filepath=str(glb_path), export_format="GLB")
```
建议二选一:
- Blender 自带 Draco:`export_draco_mesh_compression_enable=True, export_draco_mesh_compression_level=6`。
- 更彻底(推荐):导出后跑 `gltf-transform`,顺序 `weld → dedup → prune → draco(quantizePosition=14, quantizeNormal=10, quantizeGeneric=12)`。本项目用的 node 脚本见 `tools/compress.mjs`(可随 skill 附带)。
### 1.2 查看器必须挂解码器(`assets/web-showcase-template/app.js`)
模板只有 `new GLTFLoader()`,压了 Draco 会**直接加载失败**。补:
```js
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/"); // three 自带,离线可用
loader.setDRACOLoader(dracoLoader);
```
`npm install three` 已含解码器 wasm,无需 CDN。
### 1.3 变体即 LOD
overview/standard/detail 按构件类别过滤(现有机制即可),默认 standard。若要再轻,可对 overview 做几何减面(当前仅图层过滤,不是真减面)。
---
## 2. 上方向约定(潜在严重 bug,强烈建议修)
模板 `app.js` 通篇按 **Z 为上**写:`group.position.z`(楼层展开)、`new THREE.Plane(new THREE.Vector3(0,0,-1))`(剖切)、相机 `center.z + maxSize`。但 `bpy.ops.export_scene.gltf` 默认 `export_yup=True`,导出的是 **Y-up**。两者不一致 → 建筑在 three / Blender / 任何标准查看器里**躺倒**。
**建议锁死标准 Y-up:**
- GLB 保持 Y-up(Blender 默认即可;纯 Python 后端需显式把 Z-up 旋到 Y-up:`(x,y,z)->(x,z,-y)`)。
- 查看器:
- `camera.up.set(0,1,0)`(否则 OrbitControls 的 `maxPolarAngle` 会把相机钳在近水平轨道,**俯视/鸟瞰放不开**——这是另一个隐藏坑)。
- 剖切面法线 `(0,-1,0)`;楼层展开走 `.y`;相机预设 top/side/overview 按 Y-up 重写。
---
## 3. 几何完整性(CAD 平面图 → 体量模型新增步骤)
### 3.1 块内几何要定向展开(已升级为按图层探测)
幕墙/门窗常封装在 INSERT 块里。本项目玻璃在 `系统嵌板 - SZ_玻璃…`、`幕墙平拼…` 块内,展开后落在图层 `A-GLAZ-CURT`。按块名定向展开(`["*幕墙*","*玻璃*","*嵌板*","*GLAZ*","*CURT*"]`)是第一道防线,但实战证明**块名匹配不可靠**:
- DWG→DXF 转换会损坏中文块名(`系统嵌板`→`系统嵌`、`偏移`→`偏`),模式匹配不上;
- 幕墙嵌板常套在排版/包裹块里,父块名不命中就永远扫不到内层。
`derive_showcase_spec.py` 现已内置**按块内实体图层分类**(`classify_block_contents`,默认开):展开所有 INSERT 到 `expand_blocks_max_depth`,只保留自身图层能归类到 `block_content_categories`(默认 glazing/railings/doors)的子实体。配套的 `audit_showcase_extraction.py` 增加了:
- **块内锁定几何统计**(与配置无关的全量展开核算),96% 覆盖率再也藏不住整面幕墙缺失;
- **glazing 硬门禁**:图中存在幕墙证据(块内玻璃图层长度 / 幕墙命名块)而 spec glazing=0 时审计直接 FAIL(exit 3)。
另外 `*-IDEN` 标识图层(`A-DOOR-IDEN` 等)默认排除出分类(`exclude_layers`),门标号不再被当成门几何;`cad_dxf_report.py` 会在建模前对 XREF 空壳图(如本项目 A212/A214/A215/A216)输出 `likely_xref_shell` 警告。回归测试见 `tests/test_extraction_pipeline.py`。
### 3.2 立面玻璃连续化
CAD 把幕墙画成稀疏分格板(实测 8F:1.42m 板 / 每 4.5m 一块 / 中间 3.08m 空)。逐段挤出 = 隔空竖条。需做**共线合并 + 桥接窗间缝**:按 (角度, 垂距) 分组,沿线方向合并区间,`gap_tol` 取得比窗间缝大(本项目 3.6m)即连成整条玻璃带。注意先确认缝里**没有墙**(本项目实测该立面墙长 0m)再桥接,避免把实墙盖成玻璃。
### 3.3 柱头封顶(比 `shorten_unsupported_columns` 更好)
现有的“无支撑柱缩短”会产生突兀的 1.2m 矮柱。更自然的做法是**生成盖板**:
- 地上退台层:`cap = 本层footprint(外扩~1.3m) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。外扩是为了盖住凹包络切掉的外圈柱廊柱。
- **地下室顶层**:直接把整层 footprint 在 z=0 封成地面/顶板(停车区上方的地坪)。
- 顶层(8F)/辅楼顶:用现有 `roof_specs` 屋顶盖。
### 3.4 ⚠ `floor_group` 的 bug
`build_blender_showcase.py` 的 `floor_group()` 把 `B1/B1M` 归 BASE、地上归 MAIN、`AUX_` 归 AUX,柱支撑/封顶只在**同组**内找上层。结果:**地下室顶层(B1M)永远找不到地上的 1F 作为上层,拿不到顶板**——本项目 983 根地下柱有 397 根(40%)露顶。修复:地下室顶层特判为“整层封顶”,或允许跨组找上方 footprint。
---
## 4. 健壮性
- 生成的盖板(shapely 差集)可能产生退化/狭长面 → 法线 NaN → Blender 导入报 `Bad glTF: json contained NaN`。导出前必须:**丢弃零面积面**(`area>1e-9`)+ **钳 NaN/Inf 法线**(置默认向上)。
- 检查顶点 `isfinite`,跳过非法网格。
---
## 5. 验证 / QA(应做成标准动作)
这次定位问题全靠这些,建议固化进 skill 验证步骤:
- **正交立面 + 顶视渲染**:一眼看出整层缺失、躺倒、退台是否合理。
- **覆盖率叠合图**(`draw_coverage_overlay.py` 已有):红虚线=未提取,客观回答“是否缺料”。本项目支持长度覆盖率 96%。
- **量化报告**:柱头封顶率、玻璃连续段数变化、各变体 GLB 体积预算(如 overview ≤ 0.5MB)。
- **早验证原则**:生成后立即开查看器/渲立面再下结论。本次迭代 8 版的主要原因是“先猜后验”(误判朝向、误判窗间缝是墙),早点眼见为实可省大量来回。
---
## 6. 环境 / 可移植性
- skill 硬依赖 Blender + `dwg2dxf`;受限沙箱(无 root、无 Blender、PyPI 无 bpy)两者皆无。建议:
1. 文档明确宿主机前置条件;
2. 提供**纯 Python 后端**(`trimesh` + `gltf-transform`)作为无 Blender 的可移植替代——本项目即用它跑通全流程(见 `spec_to_glb.py`),且天然产出轻量化 GLB;
3. 无转换器时优雅回退到“请用户提供 DXF”。
- Web 输出加 **cache-busting(`?v=` 或内容哈希)+ 可见构建版本号**:浏览器对 ES 模块/GLB 缓存极顽固,否则用户刷新看不到更新(本次踩坑多轮)。
---
## 7. 可直接并入 skill 的产物
本项目沉淀、建议提升为 skill 资源:
- `spec_to_glb.py`:无 Blender 的 spec→GLB 导出器(含 z 窗口、segment 棱柱、footprint 楼板、玻璃共线合并、退台/地下封顶、Y-up、NaN 清洗、`楼层__类别` 命名)。
- `tools/compress.mjs`:gltf-transform Draco 压缩脚本。
- `app.js` 的 DRACOLoader + Y-up 改动。

347
references/pipeline.md Normal file
View File

@@ -0,0 +1,347 @@
# CAD to Web Building Showcase Pipeline
## 1. Inventory and Conversion
Start by listing source files and preserving names. CAD drawing names often encode floor numbers, building zones, and drawing type.
Recommended workspace layout:
```text
work/
cad_showcase/
dxf_raw/
dxf_sanitized/
reports/
building_spec.json
outputs/
<project>/
<project>.blend
<project>.glb
<project>.png
web/
```
For DWG conversion:
```bash
dwg2dxf -y -o work/cad_showcase/dxf_raw/A208.dxf "work/XREF/A208 - 主楼首层、二层平面图.dwg"
```
LibreDWG DXF files may contain `999` comment records. Sanitize before using brittle importers. `ezdxf.recover` usually tolerates them, but sanitizing keeps the files friendlier to FreeCAD and other tools.
## 2. CAD Read Report
Run:
```bash
python3 <skill>/scripts/cad_dxf_report.py --input work/XREF --work work/cad_showcase --output outputs/cad_read_report
```
If `ezdxf` is missing:
```bash
python3 -m pip install --target work/vendor ezdxf
```
Read the report and identify:
- Which drawings are plans versus elevations/details.
- Whether the unit scale is probably millimeters or meters.
- Main modelspace bounding boxes.
- Layer counts and top layers.
- Entity types that matter: `LINE`, `LWPOLYLINE`, `POLYLINE`, `INSERT`, `HATCH`, `TEXT`, `MTEXT`, `DIMENSION`.
## 3. Layer Mapping
Default layer heuristics:
| Category | Common layer names |
| --- | --- |
| walls | `I-WALL`, `A-WALL`, `L-SITE-WALL`, names containing `WALL`, `墙` |
| glazing | `A-GLAZ*`, names containing `GLAZ`, `CURT`, `WINDOW`, `幕墙`, `玻璃`, `窗` |
| roof | `A-ROOF`, `A-FLOR-ROOF`, `A-FLOR-OVHD`, names containing `ROOF`, `屋面`, `屋顶`, `雨棚` |
| columns | `S-COLS`, names containing `COL`, `COLUMN`, `柱` |
| beams | `S-STRS`, `S-STRS-MBND`, names containing `BEAM`, `梁`, `结构` |
| railings | names containing `RAIL`, `HANDRAIL`, `栏杆`, `扶手` |
| doors | names containing `DOOR`, `DR`, `门`, `开启` |
| detail_lines | `A-GENM`, `A-DETL*`, parking/area/detail layers that should stay as low plan context |
| floor_lines | `A-FLOR`, `A-FLOR-OVHD`, names containing `FLOOR`, `FLOR`, `楼面`, `地面` |
| grid | `S-GRID`, names containing `GRID`, `轴网`, `轴线` |
Do not include annotation/dimension/text layers in geometry categories unless the user wants a drawing-like overlay.
## 4. Floor Detection and Alignment
Many architectural sheets place multiple floor plans side by side. Do not assume one DWG equals one floor.
Use this order of evidence:
1. File name and drawing title.
2. Text labels in modelspace/paperspace.
3. Large separated plan clusters in the drawing bounding box.
4. `S-GRID` or equivalent structural axis layers.
5. Repeated column/grid patterns across floors.
For side-by-side plans, create a config with one `floors[]` entry per floor, each with a source `clip` rectangle and optional `offset`.
Example:
```json
{
"project_name": "Main Building",
"scale": 0.001,
"origin_strategy": "center",
"floor_height": 4.2,
"curve_chord_source_length": 750,
"expand_blocks": false,
"expand_blocks_max_depth": 2,
"block_insert_layer_fallback": true,
"generate_footprints": true,
"use_footprint_slabs": true,
"use_footprint_roofs": true,
"footprint_categories": ["walls", "glazing", "floor_lines", "railings", "columns"],
"footprint_concave_ratio": 0.85,
"footprint_simplify_tolerance": 0.12,
"slab_thickness": 0.38,
"default_disabled_categories": [],
"shorten_unsupported_columns": true,
"shorten_unsupported_columns_floor_keys": ["1F"],
"unsupported_column_height": 1.2,
"column_support_distance": 0.55,
"column_support_requires_upper_plate": true,
"column_support_allow_plate_only": false,
"block_name_categories": {
"walls": ["*WALL*", "*墙*"],
"glazing": ["*GLAZ*", "*CURT*", "*幕墙*", "*玻璃*"],
"columns": ["*COL*", "*柱*"],
"beams": ["*BEAM*", "*梁*"]
},
"min_length_meters_by_category": {
"walls": 0.25,
"columns": 0.18,
"beams": 0.35,
"floor_lines": 0.40,
"grid": 1.0
},
"drawings": [
{
"file": "A208.dxf",
"split_x": 0,
"floors": [
{"key": "1F", "name": "首层", "side": "left"},
{"key": "2F", "name": "二层", "side": "right", "offset": [-158029.255, 0]}
]
}
],
"layers": {
"walls": ["I-WALL", "A-WALL", "L-SITE-WALL"],
"glazing": ["A-GLAZ*"],
"roof": ["A-ROOF", "A-FLOR-ROOF"],
"columns": ["S-COLS"],
"beams": ["S-STRS", "S-STRS-MBND"],
"railings": ["*RAIL*"],
"doors": ["*DOOR*", "*DR*"],
"detail_lines": ["A-GENM", "A-DETL*", "*PRKG*", "A-AREA"],
"floor_lines": ["A-FLOR", "A-FLOR-OVHD"],
"grid": ["S-GRID"]
},
"roof_specs": [
{
"floor_key": "RF",
"bounds_from": ["RF"],
"footprint_from": ["RF"],
"thickness": 0.35,
"margin": 0.4
}
]
}
```
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.
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
Run:
```bash
python3 <skill>/scripts/derive_showcase_spec.py --dxf-dir work/cad_showcase/dxf_sanitized --config work/cad_showcase/config.json --out work/cad_showcase/building_spec.json
```
Review `building_spec.json` before rendering:
- Floors are ordered correctly.
- Bounds are plausible in meters.
- Each major floor has nonzero `walls`, `columns`, and `grid` or `floor_lines`.
- 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.
## 6. Agent Audit and Overlay Review
Do not proceed to Blender until the Agent has reviewed extraction evidence.
Run the audit:
```bash
python3 <skill>/scripts/audit_showcase_extraction.py \
--dxf-dir work/cad_showcase/dxf_sanitized \
--config work/cad_showcase/config.json \
--spec work/cad_showcase/building_spec.json \
--out work/cad_showcase/extraction_audit \
--vendor-dir work/vendor
```
Generate 2D overlays:
```bash
python3 <skill>/scripts/draw_coverage_overlay.py \
--dxf-dir work/cad_showcase/dxf_sanitized \
--config work/cad_showcase/config.json \
--spec work/cad_showcase/building_spec.json \
--out-dir work/cad_showcase/overlays \
--vendor-dir work/vendor
```
Agent review rules:
- Treat `INSERT`, `HATCH`, `ACAD_PROXY_ENTITY`, `SOLID`, `3DFACE`, and large unclassified layers as potential missing-model risks.
- Open overlay SVGs. Gray means source vectors already classified, red dashed means source vectors not classified, color means extracted model geometry.
- If red dashed geometry forms walls, columns, beams, stairs, grids, or floor outlines, update layer mapping or parser strategy and rerun extraction.
- 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.
## 7. Blender Generation
Run:
```bash
/Applications/Blender.app/Contents/MacOS/Blender -b \
--python <skill>/scripts/build_blender_showcase.py -- \
--spec work/cad_showcase/building_spec.json \
--out-dir outputs/<project> \
--name <project>
```
Expected outputs:
- `<project>.blend`
- `<project>.glb`
- `<project>.png`
- `model_metadata.json`
If Blender CLI fails, verify the path. On this machine, the app path has been:
```text
/Applications/Blender.app/Contents/MacOS/Blender
```
## 8. Web Showcase
For a quick single-model preview, run:
```bash
python3 <skill>/scripts/write_web_showcase.py \
--template <skill>/assets/web-showcase-template \
--glb outputs/<project>/<project>.glb \
--metadata outputs/<project>/model_metadata.json \
--out-dir outputs/<project>/web \
--title "<project> Web 展示模型"
```
For Web or digital-twin presentation, generate three reusable variants and let the Web writer consume the manifest:
```bash
python3 <skill>/scripts/build_showcase_variants.py \
--spec work/cad_showcase/building_spec.json \
--out-dir outputs/<project>/variants \
--name <project> \
--build \
--blender /Applications/Blender.app/Contents/MacOS/Blender
python3 <skill>/scripts/write_web_showcase.py \
--template <skill>/assets/web-showcase-template \
--variants-manifest outputs/<project>/variants/variants_manifest.json \
--out-dir outputs/<project>/web \
--title "<project> Web 展示模型"
npm install --prefix outputs/<project>/web three@0.181.2 lucide@0.468.0
python3 -m http.server 8188 --directory outputs/<project>/web
```
The manifest path makes `standard` the default `model.glb`, copies `overview.glb`, `standard.glb`, and `detail.glb`, and writes `model_variants` for the download controls.
Use another port if 8188 is occupied.
Notes:
- GLBs are Draco-compressed (Blender built-in, or post-process with `node tools/compress.mjs in.glb out.glb`). `npm install three` ships the matching decoder under `node_modules/three/examples/jsm/libs/draco/`; the template already registers a `DRACOLoader` pointing there, so no CDN is needed.
- The template is glTF-standard **Y-up**. If you swap in a Z-up GLB the building will render lying down — keep GLB and viewer on the same up-axis.
- `write_web_showcase.py` stamps a `?v=<build>` token on `app.js` / `model.glb` / `model_metadata.json` to defeat browser caching; if a user reports "no change after rebuild", confirm the served folder and hard-refresh.
## 9. Verification
Run the Blender-free QA pass first, then eyeball the previews before opening the Web viewer:
```bash
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
```
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.
Minimum verification:
- Preview PNG is nonblank, building is framed, and floors are visible.
- GLB file exists and has reasonable size.
- Browser loads the Web viewer with zero console errors.
- Floor toggles, component toggles, explode slider, section slider, presets, screenshot, and GLB download work.
- Variant download links exist for overview, standard, and detail when the task is Web/digital-twin presentation.
- Slabs are visible from side views; transparent glazing should not make floor plates look missing.
- Roof caps do not visibly overrun unrelated lower floor footprints.
- Ground-level columns that have no upper support are not left full-height without explanation.
- Mobile viewport around 390 px wide has no incoherent overlap.
- Extraction audit is attached or summarized, including high-risk entity counts and unclassified layers.
- Overlay review result is stated: accepted, accepted with known gaps, or rejected and iterated.
For BIM branch:
- Validate IFC schema with IfcOpenShell.
- Count `IfcBuildingStorey`, `IfcSlab`, `IfcWall`, `IfcColumn`, `IfcBeam`, and property sets.
- Run geometry extraction on all products.
- Do not claim BIM replacement unless semantic and geometric validation has passed.
Generate IFC:
```bash
python3 <skill>/scripts/build_ifc_poc.py \
--spec work/cad_showcase/building_spec.json \
--out-ifc outputs/<project>/<project>_bim_poc.ifc \
--out-report outputs/<project>/<project>_bim_poc_report.json \
--out-notes outputs/<project>/<project>_bim_poc_notes.md \
--vendor-dir work/vendor \
--validate-geometry
```
Render IFC geometry when Blender cannot import IFC directly:
```bash
python3 <skill>/scripts/extract_ifc_meshes.py \
--ifc outputs/<project>/<project>_bim_poc.ifc \
--out work/cad_showcase/<project>_ifc_meshes.json \
--vendor-dir work/vendor
/Applications/Blender.app/Contents/MacOS/Blender -b \
--python <skill>/scripts/render_ifc_meshes_blender.py -- \
--meshes work/cad_showcase/<project>_ifc_meshes.json \
--out-dir outputs/<project> \
--name <project>_ifc_render
```