Campus pipeline hardening: backend parity, wall union, mullion grids, Draco tooling
Sandbox round (Linux): - detect_sheet_frames.py: multi-frame sheet splitter (column AND row layouts), grid-vote per-floor offsets, section-elevation harvesting for storey heights - dwg_dump_json.mjs + dwgjson_to_dxf.py: WASM libredwg DWG->DXF fallback (blocks/INSERT preserved, ATTRIB->TEXT so axis labels survive) - assemble_campus.py: manifest-driven campus assembly with mandatory neighbour-gap gate (overlap = exit 3, 0.1-0.3m flagged as expansion joints) - site_context_from_dump.py: site-context floors (ground/roads/parking/ fence/trees/context massings) from site-plan dumps - write_offline_viewer.py + assets/offline-viewer-libs/: fully-offline single-file viewer (vendored three r147 + pako, gzip-embedded GLB) - audit: clip-scoped coverage figures; report: multi_frame_sheet warning; audit gate floors_aligned catches the diagonal-staircase failure mode Mac round: - build_blender_showcase.py now honors slab_bounds_fallback and prefers footprint polygons for generated roofs (bounds rects made roof plates jut past the facade and buried campuses under full-extent slabs); contract now matches spec_to_glb.py exactly - merge_wall_solids (default off) in BOTH backends: shapely union in spec_to_glb.py, native delaunay_2d_cdt union in Blender; endpoint-shared wall ends pre-extended w/2 so L-corners close seamlessly (flat caps leave a notch a union alone cannot fill) while openings stay flat - glazing_mullions (default off): curtain-wall panel grid (verticals every glazing_panel_w + floor-line transoms) as pseudo wall segments in the <floor>__walls node; glass pane kept - build_showcase_variants.py keeps source_file=="site" floors intact in all variants (roads/trees live on filtered categories) - web template: instanced low-poly trees from metadata site_trees, grade-level shadow catcher (was at basement depth), data-URI favicon - tools/compress.mjs deps pinned (package.json); 15MB campus GLB -> 0.57MB - tests: 24 -> 52 checks (wall union, mullions, byte-identical defaults) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
57
SKILL.md
57
SKILL.md
@@ -48,12 +48,26 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
|||||||
- State whether the output is Web showcase, LOD-like massing, IFC/BIM proof, or not sufficient.
|
- 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.
|
- Include what was not modeled and what evidence supports that judgment.
|
||||||
|
|
||||||
|
## One-Shot 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):
|
||||||
|
|
||||||
|
1. Read report clean: every `Warnings` entry resolved. `multi_frame_sheet` -> ran `detect_sheet_frames.py` and used its clip/offset config; `likely_xref_shell` -> user re-exported with XREFs bound.
|
||||||
|
2. Frame alignment proven: detect report shows `grid-aligned, votes x>=3 y>=3` per floor (any `WEAK grid match` floor was verified on its overlay SVG).
|
||||||
|
3. Audit exit code 0, and gates `floors_aligned` / `glazing_captured` / `no_annotation_layers_classified` all PASS. Never pass `--no-strict-gates` to proceed.
|
||||||
|
4. No `WARNING topless_group` from derive (roof handled via caps or `roof_specs`), and no `WARNING mesh_from_polygons` from the GLB build (else slabs/roofs silently vanished — install mapbox_earcut).
|
||||||
|
5. Visual check done by the Agent, not assumed: `verify_showcase.py` previews plus one rendered iso/plan image actually LOOKED AT (floors stacked, roof present, no slab fins beyond facade — default `cap_buffer` 1.3 is for colonnades, use ~0.1 otherwise).
|
||||||
|
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.
|
||||||
|
|
||||||
## Command Workflow
|
## Command Workflow
|
||||||
|
|
||||||
1. Prepare the CAD folder.
|
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.
|
- 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/`.
|
- 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"`). 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.
|
- 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"`). 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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -68,7 +82,9 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
|||||||
- Use `references/pipeline.md` and `references/building_spec_schema.md`.
|
- 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`.
|
- 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.
|
- 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), proposes a wall-bbox-refined `clip` per floor frame, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). Never model such a file as one floor (all sheets superimpose) and never stack frames without offsets (floors staircase away diagonally — the classic broken output). Read its report: `WEAK grid match` floors need overlay verification; elevation/section frames are listed for floor heights (`z`/`height` from DIM_ELEV 标高 texts like `8.100`), not as floors.
|
||||||
- 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.
|
- Align floors by structural grid or repeated control axes. Use millimeters-to-meters scale (`0.001`) unless the report proves the CAD is already in meters.
|
||||||
|
- Floor keys: `floor_sort_key` treats a leading `B` as basement (sorted below ground). Do not invent keys like `B1F` for "Building 1 Floor" — use per-building specs instead, and set explicit `floor_order` whenever keys are nonstandard.
|
||||||
- When CAD linework has enough exterior/interior boundary signal, enable generated footprints for floor slabs and roof caps. Prefer footprint polygons over rectangular floor bounds for visual/digital-twin presentation.
|
- When CAD linework has enough exterior/interior boundary signal, enable generated footprints for floor slabs and roof caps. Prefer footprint polygons over rectangular floor bounds for visual/digital-twin presentation.
|
||||||
- Run `scripts/derive_showcase_spec.py` to extract line/polyline geometry into `building_spec.json`.
|
- Run `scripts/derive_showcase_spec.py` to extract line/polyline geometry into `building_spec.json`.
|
||||||
|
|
||||||
@@ -77,6 +93,7 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
|||||||
- Run `scripts/draw_coverage_overlay.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 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.
|
- 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.
|
- Review the Markdown audit and SVG overlays. Iterate config if important geometry remains unclassified or hidden in high-risk entity types.
|
||||||
|
|
||||||
5. Generate Blender/GLB.
|
5. Generate Blender/GLB.
|
||||||
@@ -92,6 +109,7 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
|||||||
- 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/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`.
|
- 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.
|
- 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:
|
- Install local web deps in that output folder:
|
||||||
`npm install --prefix outputs/<project>/web three@0.181.2 lucide@0.468.0`
|
`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.
|
- Start a local server from the web output folder and give the user the URL.
|
||||||
@@ -102,6 +120,33 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
|||||||
- Check console logs are clean, controls work, mobile panels do not overlap, and the GLB loads.
|
- 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.
|
- Report model precision honestly: showcase model, LOD-like massing/structural visualization, or IFC/BIM proof.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Multi-Building Campuses (厂区/园区 sets)
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- 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.
|
||||||
|
- 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
|
## Modeling Rules
|
||||||
|
|
||||||
- Prefer stable, layered massing over overfitted geometry. CAD floor plans often contain annotations, dimensions, hatches, XREF artifacts, and duplicated lines.
|
- Prefer stable, layered massing over overfitted geometry. CAD floor plans often contain annotations, dimensions, hatches, XREF artifacts, and duplicated lines.
|
||||||
@@ -125,8 +170,12 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
|||||||
## Bundled Resources
|
## 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/cad_dxf_report.py`: batch DWG/DXF conversion, DXF sanitizing, and read report generation, including XREF-shell / near-empty sheet warnings.
|
||||||
- `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.
|
- `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/audit_showcase_extraction.py`: coverage and risk audit with hard gates (exit 3 on failure) and block-locked geometry accounting, for Agent review before 3D generation.
|
- `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/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/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/build_blender_showcase.py`: Blender CLI renderer/exporter from `building_spec.json` to `.blend`, `.glb`, `.png`, and metadata. GLB is Draco-compressed by default.
|
||||||
@@ -142,7 +191,9 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
|||||||
- `references/agent_review.md`: acceptance/iteration/BIM-claim checklist for Agent judgment.
|
- `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/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/optimization_notes.md`: lightweighting + completeness lessons (Draco/DRACOLoader, glTF Y-up convention, block-locked glazing, glazing continuity, column-top caps, NaN sanitation, verification).
|
||||||
- `assets/web-showcase-template/`: static Three.js viewer template (Y-up, registers DRACOLoader, cache-busting `?v=` build token).
|
- `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.
|
- `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
|
## BIM Branch
|
||||||
|
|||||||
3862
assets/offline-viewer-libs/GLTFLoader.js
Normal file
3862
assets/offline-viewer-libs/GLTFLoader.js
Normal file
File diff suppressed because it is too large
Load Diff
1101
assets/offline-viewer-libs/OrbitControls.js
Normal file
1101
assets/offline-viewer-libs/OrbitControls.js
Normal file
File diff suppressed because it is too large
Load Diff
124
assets/offline-viewer-libs/RoomEnvironment.js
Normal file
124
assets/offline-viewer-libs/RoomEnvironment.js
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
( function () {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* https://github.com/google/model-viewer/blob/master/packages/model-viewer/src/three-components/EnvironmentScene.ts
|
||||||
|
*/
|
||||||
|
class RoomEnvironment extends THREE.Scene {
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
|
||||||
|
super();
|
||||||
|
const geometry = new THREE.BoxGeometry();
|
||||||
|
geometry.deleteAttribute( 'uv' );
|
||||||
|
const roomMaterial = new THREE.MeshStandardMaterial( {
|
||||||
|
side: THREE.BackSide
|
||||||
|
} );
|
||||||
|
const boxMaterial = new THREE.MeshStandardMaterial();
|
||||||
|
const mainLight = new THREE.PointLight( 0xffffff, 5.0, 28, 2 );
|
||||||
|
mainLight.position.set( 0.418, 16.199, 0.300 );
|
||||||
|
this.add( mainLight );
|
||||||
|
const room = new THREE.Mesh( geometry, roomMaterial );
|
||||||
|
room.position.set( - 0.757, 13.219, 0.717 );
|
||||||
|
room.scale.set( 31.713, 28.305, 28.591 );
|
||||||
|
this.add( room );
|
||||||
|
const box1 = new THREE.Mesh( geometry, boxMaterial );
|
||||||
|
box1.position.set( - 10.906, 2.009, 1.846 );
|
||||||
|
box1.rotation.set( 0, - 0.195, 0 );
|
||||||
|
box1.scale.set( 2.328, 7.905, 4.651 );
|
||||||
|
this.add( box1 );
|
||||||
|
const box2 = new THREE.Mesh( geometry, boxMaterial );
|
||||||
|
box2.position.set( - 5.607, - 0.754, - 0.758 );
|
||||||
|
box2.rotation.set( 0, 0.994, 0 );
|
||||||
|
box2.scale.set( 1.970, 1.534, 3.955 );
|
||||||
|
this.add( box2 );
|
||||||
|
const box3 = new THREE.Mesh( geometry, boxMaterial );
|
||||||
|
box3.position.set( 6.167, 0.857, 7.803 );
|
||||||
|
box3.rotation.set( 0, 0.561, 0 );
|
||||||
|
box3.scale.set( 3.927, 6.285, 3.687 );
|
||||||
|
this.add( box3 );
|
||||||
|
const box4 = new THREE.Mesh( geometry, boxMaterial );
|
||||||
|
box4.position.set( - 2.017, 0.018, 6.124 );
|
||||||
|
box4.rotation.set( 0, 0.333, 0 );
|
||||||
|
box4.scale.set( 2.002, 4.566, 2.064 );
|
||||||
|
this.add( box4 );
|
||||||
|
const box5 = new THREE.Mesh( geometry, boxMaterial );
|
||||||
|
box5.position.set( 2.291, - 0.756, - 2.621 );
|
||||||
|
box5.rotation.set( 0, - 0.286, 0 );
|
||||||
|
box5.scale.set( 1.546, 1.552, 1.496 );
|
||||||
|
this.add( box5 );
|
||||||
|
const box6 = new THREE.Mesh( geometry, boxMaterial );
|
||||||
|
box6.position.set( - 2.193, - 0.369, - 5.547 );
|
||||||
|
box6.rotation.set( 0, 0.516, 0 );
|
||||||
|
box6.scale.set( 3.875, 3.487, 2.986 );
|
||||||
|
this.add( box6 );
|
||||||
|
|
||||||
|
// -x right
|
||||||
|
const light1 = new THREE.Mesh( geometry, createAreaLightMaterial( 50 ) );
|
||||||
|
light1.position.set( - 16.116, 14.37, 8.208 );
|
||||||
|
light1.scale.set( 0.1, 2.428, 2.739 );
|
||||||
|
this.add( light1 );
|
||||||
|
|
||||||
|
// -x left
|
||||||
|
const light2 = new THREE.Mesh( geometry, createAreaLightMaterial( 50 ) );
|
||||||
|
light2.position.set( - 16.109, 18.021, - 8.207 );
|
||||||
|
light2.scale.set( 0.1, 2.425, 2.751 );
|
||||||
|
this.add( light2 );
|
||||||
|
|
||||||
|
// +x
|
||||||
|
const light3 = new THREE.Mesh( geometry, createAreaLightMaterial( 17 ) );
|
||||||
|
light3.position.set( 14.904, 12.198, - 1.832 );
|
||||||
|
light3.scale.set( 0.15, 4.265, 6.331 );
|
||||||
|
this.add( light3 );
|
||||||
|
|
||||||
|
// +z
|
||||||
|
const light4 = new THREE.Mesh( geometry, createAreaLightMaterial( 43 ) );
|
||||||
|
light4.position.set( - 0.462, 8.89, 14.520 );
|
||||||
|
light4.scale.set( 4.38, 5.441, 0.088 );
|
||||||
|
this.add( light4 );
|
||||||
|
|
||||||
|
// -z
|
||||||
|
const light5 = new THREE.Mesh( geometry, createAreaLightMaterial( 20 ) );
|
||||||
|
light5.position.set( 3.235, 11.486, - 12.541 );
|
||||||
|
light5.scale.set( 2.5, 2.0, 0.1 );
|
||||||
|
this.add( light5 );
|
||||||
|
|
||||||
|
// +y
|
||||||
|
const light6 = new THREE.Mesh( geometry, createAreaLightMaterial( 100 ) );
|
||||||
|
light6.position.set( 0.0, 20.0, 0.0 );
|
||||||
|
light6.scale.set( 1.0, 0.1, 1.0 );
|
||||||
|
this.add( light6 );
|
||||||
|
|
||||||
|
}
|
||||||
|
dispose() {
|
||||||
|
|
||||||
|
const resources = new Set();
|
||||||
|
this.traverse( object => {
|
||||||
|
|
||||||
|
if ( object.isMesh ) {
|
||||||
|
|
||||||
|
resources.add( object.geometry );
|
||||||
|
resources.add( object.material );
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
} );
|
||||||
|
for ( const resource of resources ) {
|
||||||
|
|
||||||
|
resource.dispose();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
function createAreaLightMaterial( intensity ) {
|
||||||
|
|
||||||
|
const material = new THREE.MeshBasicMaterial();
|
||||||
|
material.color.setScalar( intensity );
|
||||||
|
return material;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
THREE.RoomEnvironment = RoomEnvironment;
|
||||||
|
|
||||||
|
} )();
|
||||||
2
assets/offline-viewer-libs/pako_inflate.min.js
vendored
Normal file
2
assets/offline-viewer-libs/pako_inflate.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
6
assets/offline-viewer-libs/three.min.js
vendored
Normal file
6
assets/offline-viewer-libs/three.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -2,6 +2,7 @@ import * as THREE from "three";
|
|||||||
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
|
||||||
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
|
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
|
||||||
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
|
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
|
||||||
|
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
|
||||||
|
|
||||||
const canvas = document.querySelector("#scene");
|
const canvas = document.querySelector("#scene");
|
||||||
const loading = document.querySelector("#loading");
|
const loading = document.querySelector("#loading");
|
||||||
@@ -67,14 +68,22 @@ controls.dampingFactor = 0.08;
|
|||||||
controls.screenSpacePanning = true;
|
controls.screenSpacePanning = true;
|
||||||
controls.maxPolarAngle = Math.PI * 0.49;
|
controls.maxPolarAngle = Math.PI * 0.49;
|
||||||
|
|
||||||
scene.add(new THREE.HemisphereLight(0xf7f3e8, 0x20262a, 1.45));
|
scene.add(new THREE.HemisphereLight(0xf7f3e8, 0x20262a, 0.9));
|
||||||
|
|
||||||
const keyLight = new THREE.DirectionalLight(0xffffff, 3.6);
|
// Image-based lighting: cheap, no HDR download, transforms material readability.
|
||||||
keyLight.position.set(-45, -62, 85);
|
const pmrem = new THREE.PMREMGenerator(renderer);
|
||||||
|
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
|
||||||
|
if ("environmentIntensity" in scene) scene.environmentIntensity = 0.85;
|
||||||
|
|
||||||
|
// Y-up scene: the sun must sit ABOVE the model (positive Y) or shadows break.
|
||||||
|
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
|
||||||
|
keyLight.position.set(-45, 85, 62);
|
||||||
keyLight.castShadow = true;
|
keyLight.castShadow = true;
|
||||||
|
keyLight.shadow.mapSize.set(2048, 2048);
|
||||||
|
keyLight.shadow.bias = -0.0004;
|
||||||
scene.add(keyLight);
|
scene.add(keyLight);
|
||||||
|
|
||||||
const fillLight = new THREE.DirectionalLight(0x9fd4ff, 1.15);
|
const fillLight = new THREE.DirectionalLight(0x9fd4ff, 0.9);
|
||||||
fillLight.position.set(80, 55, 48);
|
fillLight.position.set(80, 55, 48);
|
||||||
scene.add(fillLight);
|
scene.add(fillLight);
|
||||||
|
|
||||||
@@ -260,6 +269,10 @@ function ingestModel(gltfScene, meta) {
|
|||||||
modelRoot.add(mesh);
|
modelRoot.add(mesh);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (parsed.category === "trees" && meta.site_trees?.length) {
|
||||||
|
mesh.visible = false; // replaced by instanced trunk+crown trees below
|
||||||
|
continue;
|
||||||
|
}
|
||||||
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(parsed.category);
|
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(parsed.category);
|
||||||
mesh.receiveShadow = true;
|
mesh.receiveShadow = true;
|
||||||
mesh.userData.floor = parsed.floor;
|
mesh.userData.floor = parsed.floor;
|
||||||
@@ -273,7 +286,60 @@ function ingestModel(gltfScene, meta) {
|
|||||||
floorGroups.get(parsed.floor).add(mesh);
|
floorGroups.get(parsed.floor).add(mesh);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (meta.site_trees?.length) addInstancedTrees(meta.site_trees);
|
||||||
|
|
||||||
state.bounds = new THREE.Box3().setFromObject(modelRoot);
|
state.bounds = new THREE.Box3().setFromObject(modelRoot);
|
||||||
|
fitShadowsAndGround(state.bounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addInstancedTrees(points) {
|
||||||
|
// spec plan coords (x, y) -> Y-up world (x, ?, -y), same mapping as the GLB export
|
||||||
|
const trunk = new THREE.InstancedMesh(
|
||||||
|
new THREE.CylinderGeometry(0.14, 0.2, 1.4, 6),
|
||||||
|
new THREE.MeshStandardMaterial({ color: 0x6b4a2e, roughness: 0.9, clippingPlanes: [sectionPlane] }),
|
||||||
|
points.length,
|
||||||
|
);
|
||||||
|
const crown = new THREE.InstancedMesh(
|
||||||
|
new THREE.IcosahedronGeometry(1.5, 1),
|
||||||
|
new THREE.MeshStandardMaterial({ color: 0x3e7d4f, roughness: 0.8, clippingPlanes: [sectionPlane] }),
|
||||||
|
points.length,
|
||||||
|
);
|
||||||
|
const matrix = new THREE.Matrix4();
|
||||||
|
points.forEach(([x, y], index) => {
|
||||||
|
matrix.setPosition(x, 0.7, -y);
|
||||||
|
trunk.setMatrixAt(index, matrix);
|
||||||
|
matrix.setPosition(x, 2.2, -y);
|
||||||
|
crown.setMatrixAt(index, matrix);
|
||||||
|
});
|
||||||
|
trunk.castShadow = crown.castShadow = true;
|
||||||
|
crown.receiveShadow = true;
|
||||||
|
const group = floorGroups.get("TREES");
|
||||||
|
(group || modelRoot).add(trunk, crown);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fitShadowsAndGround(bounds) {
|
||||||
|
// Default directional-shadow frustum is ±5 m — useless for buildings.
|
||||||
|
const center = bounds.getCenter(new THREE.Vector3());
|
||||||
|
const size = bounds.getSize(new THREE.Vector3());
|
||||||
|
const radius = Math.max(size.x, size.z, 20) * 0.75;
|
||||||
|
keyLight.target.position.copy(center);
|
||||||
|
scene.add(keyLight.target);
|
||||||
|
Object.assign(keyLight.shadow.camera, {
|
||||||
|
left: -radius, right: radius, top: radius, bottom: -radius, near: 5, far: radius * 6,
|
||||||
|
});
|
||||||
|
keyLight.shadow.camera.updateProjectionMatrix();
|
||||||
|
const ground = new THREE.Mesh(
|
||||||
|
new THREE.PlaneGeometry(radius * 8, radius * 8),
|
||||||
|
new THREE.ShadowMaterial({ opacity: 0.32 }),
|
||||||
|
);
|
||||||
|
ground.rotation.x = -Math.PI / 2;
|
||||||
|
// Grade sits at y=0 by spec convention; bounds.min.y is the BASEMENT floor
|
||||||
|
// when one exists, and a catcher 5 m below grade shows shadows detached
|
||||||
|
// from the building. Clamp to grade unless the whole model floats above it.
|
||||||
|
const groundY = Math.max(bounds.min.y, Math.min(0, bounds.max.y)) - 0.03;
|
||||||
|
ground.position.set(center.x, groundY, center.z);
|
||||||
|
ground.receiveShadow = true;
|
||||||
|
scene.add(ground);
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseObjectName(name) {
|
function parseObjectName(name) {
|
||||||
@@ -291,6 +357,16 @@ function labelForObject({ floor, category }) {
|
|||||||
function materialForCategory(category, meta) {
|
function materialForCategory(category, meta) {
|
||||||
if (materialByCategory.has(category)) return materialByCategory.get(category);
|
if (materialByCategory.has(category)) return materialByCategory.get(category);
|
||||||
const color = new THREE.Color(meta.categories[category]?.color || "#cccccc");
|
const color = new THREE.Color(meta.categories[category]?.color || "#cccccc");
|
||||||
|
if (category === "glazing") {
|
||||||
|
// Physical glass (transmission) instead of flat alpha — key perceived-quality win.
|
||||||
|
const glass = new THREE.MeshPhysicalMaterial({
|
||||||
|
color, metalness: 0, roughness: 0.18, transmission: 0.7, ior: 1.5, thickness: 0.3,
|
||||||
|
transparent: true, depthWrite: false, side: THREE.DoubleSide, clippingPlanes: [sectionPlane],
|
||||||
|
});
|
||||||
|
glass.envMapIntensity = 1.2;
|
||||||
|
materialByCategory.set(category, glass);
|
||||||
|
return glass;
|
||||||
|
}
|
||||||
const opacity =
|
const opacity =
|
||||||
category === "slab"
|
category === "slab"
|
||||||
? 0.64
|
? 0.64
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>{{TITLE}}</title>
|
<title>{{TITLE}}</title>
|
||||||
|
<link rel="icon" href="data:," /><!-- keep the console free of favicon 404s -->
|
||||||
<link rel="stylesheet" href="./styles.css" />
|
<link rel="stylesheet" href="./styles.css" />
|
||||||
<script type="importmap">
|
<script type="importmap">
|
||||||
{
|
{
|
||||||
|
|||||||
28
claudecode_prompt.md
Normal file
28
claudecode_prompt.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# Claude Code 提示词:CAD 展示模型 skill 剩余改进项
|
||||||
|
|
||||||
|
(在 /Users/zhengwr/workspace/cad-building-showcase 目录下启动 claude 后粘贴)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
你在 CAD 建筑展示模型 skill 的仓库里工作。开始前先完整阅读 SKILL.md(操作手册,含 One-Shot Definition of Done 七条门禁)、references/web_presentation_notes.md(效果升级清单与 PENDING 项)、贝昂CAD诊断与skill优化.md(项目全程记录)。铁律:任何脚本改动后必须跑 `python3 tests/test_extraction_pipeline.py`(当前 24 项全绿);门禁失败就停下修复,绝不绕过;产出必须亲眼验证(渲染图/浏览器截图),不做假数据。
|
||||||
|
|
||||||
|
现成数据:outputs/beian_1hao/ 下有 campus_spec.json(厂区 22 层合成 spec)、building_spec.json / spec_2.json / spec_3.json(1#/2#/3# 单体)、beian_campus.glb(14.9MB 未压缩)、site_manifest.json(摆位配方)、site_floors.json(场布)。CAD 源图在 /Users/zhengwr/workspace/test3d-6/fs贝昂科技_新建项目cad20250728/(如需重新提取,按 SKILL.md 步骤 1 的 WASM 兜底或 macOS ODA 转换)。
|
||||||
|
|
||||||
|
按顺序执行,每项完成后简报结果再继续:
|
||||||
|
|
||||||
|
任务 1 — Draco 压缩(30 分钟)
|
||||||
|
在仓库根目录 `npm install @gltf-transform/core @gltf-transform/extensions @gltf-transform/functions draco3dgltf`,然后 `node tools/compress.mjs outputs/beian_1hao/beian_campus.glb outputs/beian_1hao/beian_campus.draco.glb`。验收:压缩后 ≤3MB,用 pygltflib 或 gltf-transform inspect 确认节点数不变(122)、KHR_draco_mesh_compression 存在。沙盒里 WASM 会崩,macOS 正常——如果这里也崩,报告环境信息,不要硬试。
|
||||||
|
|
||||||
|
任务 2 — 正式 Web 模板部署验证(1 小时)
|
||||||
|
按 SKILL.md 步骤 6:用 scripts/build_showcase_variants.py --build 生成 overview/standard/detail 三档(输入 outputs/beian_1hao/campus_spec.json),scripts/write_web_showcase.py --variants-manifest 组装到 outputs/beian_1hao/web/,`npm install --prefix outputs/beian_1hao/web three@0.181.2 lucide@0.468.0`,起本地服务打开。验收:亲自在浏览器确认——RoomEnvironment 环境光与阴影生效(模板 app.js 刚升级过:主光已移到地上、阴影视锥按模型自适应、幕墙为物理玻璃)、楼层爆炸/剖切/点击溯源可用、桌面与手机宽度布局正常、控制台无报错;截图存 outputs/beian_1hao/web_verify/。
|
||||||
|
|
||||||
|
任务 3 — Tier 2 几何升级:连续墙体(半天,先写测试)
|
||||||
|
给 scripts/spec_to_glb.py 和 scripts/build_blender_showcase.py 加配置开关 `merge_wall_solids`(默认 false):每层墙段用 shapely buffer(width/2, cap_style=2) + unary_union 合并为连续多边形再挤出,消除转角缝。先在 tests/test_extraction_pipeline.py 加用例(L 形墙 union 后应为单一多边形、顶点数合理、默认关闭时输出与现状逐字节一致),再实现。完成后用 campus_spec.json 开关对比渲染两张图,肉眼验证转角处无缝且无异常鼓包,写入 references/web_presentation_notes.md 的 Status。
|
||||||
|
|
||||||
|
任务 4 — 幕墙竖梃分格(半天,同样先测试后实现)
|
||||||
|
spec_to_glb 加 `glazing_mullions`(默认 false):合并后的每条玻璃带按 glazing_panel_w(默认 1.5m)生成竖梃、按层高生成横梃(细盒型材,walls 材质),玻璃面保留。验收同任务 3:新增测试 + 前后对比渲染 + notes 更新。
|
||||||
|
|
||||||
|
任务 5 — 4#/5# 与 3# 精确定位(依赖外部数据,先问我)
|
||||||
|
现有图纸没有 4# 机械停车坑、5# 污水处理池的定位轮廓,3# 是 ±1m 近似摆位。先向我确认是否已拿到设计院"含全部构筑物的可点坐标总平面";拿到后按 SKILL.md 厂区章节流程(detect_sheet_frames → 提取 → 在 site_manifest.json 增加条目 → scripts/assemble_campus.py 重新装配,它会自动做邻栋间距门禁)。没拿到就跳过并在报告里注明,不要造假体量。
|
||||||
|
|
||||||
|
全部完成后:更新 贝昂CAD诊断与skill优化.md 追加一节记录本轮结果与教训,确认 24+ 项测试全绿,git status 列出改动清单(不要自行 commit,等我确认)。
|
||||||
696
package-lock.json
generated
Normal file
696
package-lock.json
generated
Normal file
@@ -0,0 +1,696 @@
|
|||||||
|
{
|
||||||
|
"name": "cad-building-showcase",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"dependencies": {
|
||||||
|
"@gltf-transform/core": "^4.4.1",
|
||||||
|
"@gltf-transform/extensions": "^4.4.1",
|
||||||
|
"@gltf-transform/functions": "^4.4.1",
|
||||||
|
"draco3dgltf": "^1.5.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@emnapi/runtime": {
|
||||||
|
"version": "1.11.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
|
||||||
|
"integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@gltf-transform/core": {
|
||||||
|
"version": "4.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@gltf-transform/core/-/core-4.4.1.tgz",
|
||||||
|
"integrity": "sha512-ygWWFOrj1HnfvBimHF1yHTY4abbeBjn3CvljijaWKoRLMRV/a8pWYQu9rfMFQhfpT5kYZTD5Mp+dizAXPbiTDQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"property-graph": "^4.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/donmccurdy"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@gltf-transform/extensions": {
|
||||||
|
"version": "4.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@gltf-transform/extensions/-/extensions-4.4.1.tgz",
|
||||||
|
"integrity": "sha512-dZZ9D/NdpNeJUmQKExtISYtd3W6OxU4njk8UI3IKm6j97uVskYQ24BNi2YP40uUpdWPiREsS/DhjNhWAbGU/1A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@gltf-transform/core": "^4.4.1",
|
||||||
|
"ktx-parse": "^1.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/donmccurdy"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@gltf-transform/functions": {
|
||||||
|
"version": "4.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@gltf-transform/functions/-/functions-4.4.1.tgz",
|
||||||
|
"integrity": "sha512-CAU6hczuRz7NIEtpn7BARuwVEwRawwIcGqmoMCaEwA4XC+CSUi3xptXuf2zDG/5AftFO7IeQxXl/56rDsck0GQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@gltf-transform/core": "^4.4.1",
|
||||||
|
"@gltf-transform/extensions": "^4.4.1",
|
||||||
|
"ktx-parse": "^1.1.0",
|
||||||
|
"ndarray": "^1.0.19",
|
||||||
|
"ndarray-lanczos": "^0.3.0",
|
||||||
|
"ndarray-pixels": "^5.0.1"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/donmccurdy"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/colour": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-darwin-arm64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-darwin-arm64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-darwin-x64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-darwin-x64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-darwin-arm64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-darwin-x64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linux-arm": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linux-arm64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linux-ppc64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linux-riscv64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linux-s390x": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linux-x64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
|
||||||
|
"version": "1.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",
|
||||||
|
"integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linux-arm": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linux-arm": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linux-arm64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linux-arm64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linux-ppc64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linux-ppc64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linux-riscv64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linux-riscv64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linux-s390x": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linux-s390x": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linux-x64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linux-x64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linuxmusl-arm64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linuxmusl-arm64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-linuxmusl-x64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-libvips-linuxmusl-x64": "1.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-wasm32": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",
|
||||||
|
"cpu": [
|
||||||
|
"wasm32"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@emnapi/runtime": "^1.7.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-win32-arm64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-win32-ia32": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@img/sharp-win32-x64": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/ndarray": {
|
||||||
|
"version": "1.0.14",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.0.14.tgz",
|
||||||
|
"integrity": "sha512-oANmFZMnFQvb219SSBIhI1Ih/r4CvHDOzkWyJS/XRqkMrGH5/kaPSA1hQhdIBzouaE+5KpE/f5ylI9cujmckQg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/cwise-compiler": {
|
||||||
|
"version": "1.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/cwise-compiler/-/cwise-compiler-1.1.3.tgz",
|
||||||
|
"integrity": "sha512-WXlK/m+Di8DMMcCjcWr4i+XzcQra9eCdXIJrgh4TUgh0pIS/yJduLxS9JgefsHJ/YVLdgPtXm9r62W92MvanEQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"uniq": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/detect-libc": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/draco3dgltf": {
|
||||||
|
"version": "1.5.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/draco3dgltf/-/draco3dgltf-1.5.7.tgz",
|
||||||
|
"integrity": "sha512-LeqcpmoHIyYUi0z70/H3tMkGj8QhqVxq6FJGPjlzR24BNkQ6jyMheMvFKJBI0dzGZrEOUyQEmZ8axM1xRrbRiw==",
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
},
|
||||||
|
"node_modules/iota-array": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/is-buffer": {
|
||||||
|
"version": "1.1.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
|
||||||
|
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/ktx-parse": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/ndarray": {
|
||||||
|
"version": "1.0.19",
|
||||||
|
"resolved": "https://registry.npmjs.org/ndarray/-/ndarray-1.0.19.tgz",
|
||||||
|
"integrity": "sha512-B4JHA4vdyZU30ELBw3g7/p9bZupyew5a7tX1Y/gGeF2hafrPaQZhgrGQfsvgfYbgdFZjYwuEcnaobeM/WMW+HQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"iota-array": "^1.0.0",
|
||||||
|
"is-buffer": "^1.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ndarray-lanczos": {
|
||||||
|
"version": "0.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ndarray-lanczos/-/ndarray-lanczos-0.3.0.tgz",
|
||||||
|
"integrity": "sha512-5kBmmG3Zvyj77qxIAC4QFLKuYdDIBJwCG+DukT6jQHNa1Ft74/hPH1z5mbQXeHBt8yvGPBGVrr3wEOdJPYYZYg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/ndarray": "^1.0.11",
|
||||||
|
"ndarray": "^1.0.19"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ndarray-ops": {
|
||||||
|
"version": "1.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/ndarray-ops/-/ndarray-ops-1.2.2.tgz",
|
||||||
|
"integrity": "sha512-BppWAFRjMYF7N/r6Ie51q6D4fs0iiGmeXIACKY66fLpnwIui3Wc3CXiD/30mgLbDjPpSLrsqcp3Z62+IcHZsDw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cwise-compiler": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ndarray-pixels": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/ndarray-pixels/-/ndarray-pixels-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-IBtrpefpqlI8SPDCGjXk4v5NV5z7r3JSuCbfuEEXaM0vrOJtNGgYUa4C3Lt5H+qWdYF4BCPVFsnXhNC7QvZwkw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/ndarray": "^1.0.14",
|
||||||
|
"ndarray": "^1.0.19",
|
||||||
|
"ndarray-ops": "^1.2.2",
|
||||||
|
"sharp": "^0.34.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/property-graph": {
|
||||||
|
"version": "4.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz",
|
||||||
|
"integrity": "sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/semver": {
|
||||||
|
"version": "7.8.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
||||||
|
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"bin": {
|
||||||
|
"semver": "bin/semver.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/sharp": {
|
||||||
|
"version": "0.34.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
|
||||||
|
"integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@img/colour": "^1.0.0",
|
||||||
|
"detect-libc": "^2.1.2",
|
||||||
|
"semver": "^7.7.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/libvips"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@img/sharp-darwin-arm64": "0.34.5",
|
||||||
|
"@img/sharp-darwin-x64": "0.34.5",
|
||||||
|
"@img/sharp-libvips-darwin-arm64": "1.2.4",
|
||||||
|
"@img/sharp-libvips-darwin-x64": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linux-arm": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linux-arm64": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linux-ppc64": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linux-riscv64": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linux-s390x": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linux-x64": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linuxmusl-arm64": "1.2.4",
|
||||||
|
"@img/sharp-libvips-linuxmusl-x64": "1.2.4",
|
||||||
|
"@img/sharp-linux-arm": "0.34.5",
|
||||||
|
"@img/sharp-linux-arm64": "0.34.5",
|
||||||
|
"@img/sharp-linux-ppc64": "0.34.5",
|
||||||
|
"@img/sharp-linux-riscv64": "0.34.5",
|
||||||
|
"@img/sharp-linux-s390x": "0.34.5",
|
||||||
|
"@img/sharp-linux-x64": "0.34.5",
|
||||||
|
"@img/sharp-linuxmusl-arm64": "0.34.5",
|
||||||
|
"@img/sharp-linuxmusl-x64": "0.34.5",
|
||||||
|
"@img/sharp-wasm32": "0.34.5",
|
||||||
|
"@img/sharp-win32-arm64": "0.34.5",
|
||||||
|
"@img/sharp-win32-ia32": "0.34.5",
|
||||||
|
"@img/sharp-win32-x64": "0.34.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/tslib": {
|
||||||
|
"version": "2.8.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||||
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
|
"license": "0BSD",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"node_modules/uniq": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA==",
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
8
package.json
Normal file
8
package.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"dependencies": {
|
||||||
|
"@gltf-transform/core": "^4.4.1",
|
||||||
|
"@gltf-transform/extensions": "^4.4.1",
|
||||||
|
"@gltf-transform/functions": "^4.4.1",
|
||||||
|
"draco3dgltf": "^1.5.7"
|
||||||
|
}
|
||||||
|
}
|
||||||
138
references/web_presentation_notes.md
Normal file
138
references/web_presentation_notes.md
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
# Web Presentation Upgrades (视觉/交互/性能改进清单)
|
||||||
|
|
||||||
|
Prioritized playbook for pushing a working showcase model toward digital-twin
|
||||||
|
presentation quality. Apply AFTER the geometry passes the One-Shot Definition
|
||||||
|
of Done — polish never excuses a wrong model. Each item names the code to
|
||||||
|
touch. Ordered by value-per-effort.
|
||||||
|
|
||||||
|
## Tier 1 — cheap, do by default
|
||||||
|
|
||||||
|
1. Deliver through the official template, not ad-hoc HTML.
|
||||||
|
`scripts/write_web_showcase.py` + `assets/web-showcase-template/` already
|
||||||
|
provide floor explode, section height, camera presets, screenshot, variant
|
||||||
|
downloads. One-off embedded-GLB HTML files are for quick sharing only; they
|
||||||
|
balloon past 10-20 MB (base64) and lack controls.
|
||||||
|
2. Draco-compress every delivered GLB.
|
||||||
|
`node tools/compress.mjs in.glb out.glb` (or Blender's built-in). Typical
|
||||||
|
10-15 MB campus GLB -> 2-3 MB. The template registers DRACOLoader already.
|
||||||
|
Serve with gzip/brotli on top.
|
||||||
|
3. Lighting/material baseline in the viewer:
|
||||||
|
ACES tone mapping (`renderer.toneMapping = ACESFilmicToneMapping`),
|
||||||
|
`scene.environment` from `RoomEnvironment` (no HDR download needed),
|
||||||
|
one shadow-casting DirectionalLight + soft ground shadow
|
||||||
|
(`ShadowMaterial` plane, or baked AO plane). Cost: ~20 lines in the
|
||||||
|
template, transforms perceived quality.
|
||||||
|
4. Glazing as physical glass: `MeshPhysicalMaterial` with
|
||||||
|
`transmission 0.6-0.85, roughness 0.15-0.3, ior 1.5, depthWrite false`.
|
||||||
|
Keep alpha-blend fallback for mobile (`lowPowerMode` flag).
|
||||||
|
|
||||||
|
## Tier 2 — geometry quality (extraction/export side)
|
||||||
|
|
||||||
|
5. Continuous wall solids — DONE (2026-07-02): config `merge_wall_solids`
|
||||||
|
(default off) in both `spec_to_glb.py` (shapely `buffer(w/2, cap_style=2)`
|
||||||
|
-> `unary_union` -> extrude, holes preserved) and
|
||||||
|
`build_blender_showcase.py` (Blender-native `delaunay_2d_cdt` union — its
|
||||||
|
python has no shapely). KEY GEOMETRY LESSON: flat caps leave a w/2 x w/2
|
||||||
|
notch at L-corners that the union alone keeps open (T-joints are fine);
|
||||||
|
both backends pre-extend ONLY endpoint-shared wall ends by w/2
|
||||||
|
(`extend_shared_wall_ends`) so corners close while door/window openings
|
||||||
|
stay flat. Regression-tested (single-polygon corner, exactly 6 corners,
|
||||||
|
free ends untouched, default off byte-identical). Cost: campus GLB
|
||||||
|
triangles +37% with the flag on — opt-in for closeup shots.
|
||||||
|
6. Curtain-wall mullions — DONE (2026-07-02): config `glazing_mullions`
|
||||||
|
(default off, pitch `glazing_panel_w` 1.5 m) in both backends. Mullions and
|
||||||
|
floor-line transoms are synthesized as pseudo wall segments (thin box
|
||||||
|
profiles; transoms carry explicit `_z0`/`_z1`) and appended to the
|
||||||
|
`<floor>__walls` node, so the Web viewer colors them as walls with zero
|
||||||
|
viewer changes; the glass pane stays. They deliberately bypass the
|
||||||
|
`merge_wall_solids` union (a union would fuse transoms into full-height
|
||||||
|
walls). Regression-tested (5 posts on a 6 m band, top+bottom transoms,
|
||||||
|
default off byte-identical); before/after renders:
|
||||||
|
`outputs/beian_1hao/mullions_{off,on}_facade.png` (the 87 m F2 band).
|
||||||
|
7. Door/window openings: subtract door/window spans (already classified per
|
||||||
|
segment) from the wall solid of item 5 before extrusion; insert simple
|
||||||
|
frame boxes. Only worth it at `detail` variant level.
|
||||||
|
8. Site surfaces instead of sticks: roads/parking as filled polygons
|
||||||
|
(polygonize `Z5-车行道` boundaries with shapely, fall back to buffered
|
||||||
|
centerlines), green areas from `Z4-绿地` boundaries slightly below road
|
||||||
|
level, water as flat translucent plate. Trees: replace posts with a 2-LOD
|
||||||
|
low-poly tree (instanced mesh — one draw call for all trees). Extend
|
||||||
|
`scripts/site_context_from_dump.py` (`--surfaces` flag).
|
||||||
|
9. Parapets/eaves: RF roof lines already extrude via `default_widths.roof`;
|
||||||
|
add a small cap strip on top of parapet bands so they read as solid walls
|
||||||
|
from above.
|
||||||
|
|
||||||
|
## 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 ...).
|
||||||
|
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.
|
||||||
|
15. Digital-twin hooks: floor/mesh naming is stable (`<floor>__<category>`),
|
||||||
|
so IoT bindings can address nodes by name; IFC semantics via
|
||||||
|
`scripts/build_ifc_poc.py` when the client needs BIM hand-off.
|
||||||
|
|
||||||
|
## Status on the 贝昂 case (2026-07-02)
|
||||||
|
|
||||||
|
DONE in the embedded viewer (`outputs/beian_1hao/beian_campus_viewer.html`):
|
||||||
|
ACES tone mapping + RoomEnvironment IBL + PCF soft shadows + shadow-catcher
|
||||||
|
ground; physical-glass glazing (transmission); instanced low-poly street
|
||||||
|
trees (2 draw calls for all trees); click-to-inspect (floor/category chip +
|
||||||
|
emissive highlight); per-building grouped floor toggles; payload gzip-embedded
|
||||||
|
via browser DecompressionStream — 19.4 MB -> 3.0 MB with zero decoders.
|
||||||
|
|
||||||
|
SANDBOX LIMIT: gltf-transform's Draco/meshopt WASM core-dumps in the Linux
|
||||||
|
sandbox; run `tools/compress.mjs` on macOS instead (works there). gzip
|
||||||
|
embedding is the sandbox-safe fallback.
|
||||||
|
|
||||||
|
CDN LESSON (mainland China): cdn.jsdelivr.net (and most three.js CDNs) are
|
||||||
|
slow/blocked for mainland users — a CDN-importing viewer hangs on the loading
|
||||||
|
screen. For share-by-file delivery, embed EVERYTHING: three r147 UMD +
|
||||||
|
examples/js OrbitControls/GLTFLoader/RoomEnvironment + pako inflate as inline
|
||||||
|
classic scripts (~760 KB total, npm pack three@0.147.0). r147 API deltas:
|
||||||
|
`outputEncoding = sRGBEncoding` (not outputColorSpace),
|
||||||
|
`physicallyCorrectLights = true`. Always wire window error/unhandledrejection
|
||||||
|
handlers into the loading overlay so failures are visible, never a silent
|
||||||
|
"加载中". Headless smoke test in node: global.self/window/THREE, then
|
||||||
|
GLTFLoader().parse(buffer) and count meshes.
|
||||||
|
|
||||||
|
DONE in the official template (assets/web-showcase-template, 2026-07-02):
|
||||||
|
RoomEnvironment IBL, physical-glass glazing (transmission, clipping-aware),
|
||||||
|
key light moved ABOVE ground (was y=-62 — a Y-up bug that broke shadows),
|
||||||
|
model-sized shadow frustum (default ±5 m frustum is useless for buildings)
|
||||||
|
plus ground shadow catcher. Formalized `scripts/write_offline_viewer.py` +
|
||||||
|
`assets/offline-viewer-libs/` for the share-by-file case.
|
||||||
|
|
||||||
|
DONE in the export pipeline (2026-07-02, Mac round): merged wall solids
|
||||||
|
(`merge_wall_solids`, Tier 2 item 5) and curtain-wall mullion grids
|
||||||
|
(`glazing_mullions`, Tier 2 item 6) in BOTH spec_to_glb.py and
|
||||||
|
build_blender_showcase.py, regression-tested, default off. Same round:
|
||||||
|
build_blender_showcase.py now honors `slab_bounds_fallback` and prefers
|
||||||
|
footprint polygons for generated roofs (it used to emit bounds rects — the
|
||||||
|
"roof plate juts past the facade" / "site covered by a giant plate" bugs);
|
||||||
|
build_showcase_variants.py keeps `source_file=="site"` floors intact in every
|
||||||
|
variant (roads/trees live on detail_lines/grid/trees categories, so category
|
||||||
|
filtering used to strip the whole site from the Web default); the official
|
||||||
|
template gained instanced low-poly trees (metadata `site_trees` written by
|
||||||
|
write_web_showcase.py from the default variant spec), a grade-level shadow
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Honesty rules for presentation upgrades
|
||||||
|
|
||||||
|
- Mullion grids, openings, and wall unions are VISUAL enhancements derived
|
||||||
|
from plan linework — do not present them as BIM-verified elements.
|
||||||
|
- Never let polish mask data gaps: a missing building must stay missing (or
|
||||||
|
an explicitly-labeled massing), not be faked with a pretty box.
|
||||||
229
scripts/assemble_campus.py
Normal file
229
scripts/assemble_campus.py
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Assemble a campus spec from per-building specs + a site manifest.
|
||||||
|
|
||||||
|
Formalizes the spec-level merge proven on the 贝昂 case: every building's
|
||||||
|
segments/footprints/caps are rotated+translated into campus-local meters,
|
||||||
|
floor keys get building prefixes, site-context floors (from
|
||||||
|
site_context_from_dump.py) are appended, and per-building roof_specs are
|
||||||
|
re-keyed. Placement anchors follow the SKILL rules: WALL corners / coordinate
|
||||||
|
callouts, never roof envelopes.
|
||||||
|
|
||||||
|
Manifest (site_manifest.json) schema used here:
|
||||||
|
{
|
||||||
|
"campus_origin_surveying_m": [349505.372, 664163.589],
|
||||||
|
"rotation_deg": 7.5711, # campus grid rotation (site vs building sheets)
|
||||||
|
"buildings": {
|
||||||
|
"1#厂房": {"spec": "work/building_spec.json", "prefix": "",
|
||||||
|
"model_anchor_m": [7.3, 8.3], # point in the building spec (meters)
|
||||||
|
"survey_anchor_m": [349582.714, 664188.492]}, # where it lands (surveying meters)
|
||||||
|
"2#厂房": {"spec": "work/spec_2.json", "prefix": "2", ...}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Buildings without a "spec" entry are skipped (e.g. "status": "待建模").
|
||||||
|
|
||||||
|
Checks performed (loud, not silent): pairwise wall-envelope overlap between
|
||||||
|
buildings (negative gaps FAIL), and each building inside the site bounds if
|
||||||
|
--site-bounds is given.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 assemble_campus.py --manifest work/site_manifest.json \
|
||||||
|
[--site-floors work/site_floors.json] --out work/campus_spec.json \
|
||||||
|
[--project-name 厂区] [--roof-specs work/roof_specs.json]
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
p = argparse.ArgumentParser(description=__doc__)
|
||||||
|
p.add_argument("--manifest", required=True)
|
||||||
|
p.add_argument("--site-floors", default=None, help="site_context_from_dump.py output to merge")
|
||||||
|
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("--allow-overlap", action="store_true", help="downgrade overlap FAIL to warning")
|
||||||
|
return p.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def make_xf(anchor, survey_m, origin_m, cos_t, sin_t):
|
||||||
|
ax, ay = anchor
|
||||||
|
tx, ty = survey_m[0] - origin_m[0], survey_m[1] - origin_m[1]
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def transform_floors(spec: dict, xf) -> dict:
|
||||||
|
out = {}
|
||||||
|
for fk, fl in spec.get("floors", {}).items():
|
||||||
|
nf = copy.deepcopy(fl)
|
||||||
|
xs, ys = [], []
|
||||||
|
for segs in nf.get("segments", {}).values():
|
||||||
|
for s in segs:
|
||||||
|
s["start"] = xf(s["start"])
|
||||||
|
s["end"] = xf(s["end"])
|
||||||
|
xs += [s["start"][0], s["end"][0]]
|
||||||
|
ys += [s["start"][1], s["end"][1]]
|
||||||
|
if "footprint" in nf:
|
||||||
|
nf["footprint"]["polygons"] = [[xf(p) for p in poly] for poly in nf["footprint"]["polygons"]]
|
||||||
|
for cap in nf.get("caps", []):
|
||||||
|
cap["polygons"] = [[xf(p) for p in poly] for poly in cap["polygons"]]
|
||||||
|
if xs:
|
||||||
|
nf["bounds"] = [round(min(xs), 6), round(min(ys), 6), round(max(xs), 6), round(max(ys), 6)]
|
||||||
|
out[fk] = nf
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def wall_envelope_axis(floors: dict, cos_t: float, sin_t: float):
|
||||||
|
"""Ground-floor wall envelope in the rotated building-axis frame.
|
||||||
|
|
||||||
|
Uses the LOWEST floor with real walls: upper floors (roof machine rooms,
|
||||||
|
parapet-level structures) legitimately overhang by 1-2 m and would turn a
|
||||||
|
valid 0.19 m expansion joint into a false overlap alarm.
|
||||||
|
"""
|
||||||
|
ground = None
|
||||||
|
for fl in floors.values():
|
||||||
|
if len(fl.get("segments", {}).get("walls", [])) < 10:
|
||||||
|
continue
|
||||||
|
z = float(fl.get("z", 0))
|
||||||
|
if z < -0.5:
|
||||||
|
continue # basements are inset; the seam lives at ground level
|
||||||
|
if ground is None or z < float(ground.get("z", 0)):
|
||||||
|
ground = fl
|
||||||
|
if ground is None:
|
||||||
|
for fl in floors.values():
|
||||||
|
if len(fl.get("segments", {}).get("walls", [])) >= 10:
|
||||||
|
if ground is None or float(fl.get("z", 0)) < float(ground.get("z", 0)):
|
||||||
|
ground = fl
|
||||||
|
if ground is None:
|
||||||
|
return None
|
||||||
|
pts = []
|
||||||
|
for s in ground["segments"]["walls"]:
|
||||||
|
for p in (s["start"], s["end"]):
|
||||||
|
pts.append((p[0] * cos_t + p[1] * sin_t, -p[0] * sin_t + p[1] * cos_t))
|
||||||
|
xs = [p[0] for p in pts]
|
||||||
|
ys = [p[1] for p in pts]
|
||||||
|
return (min(xs), min(ys), max(xs), max(ys))
|
||||||
|
|
||||||
|
|
||||||
|
def envelope_gap(a, b):
|
||||||
|
"""Positive = separation, negative = overlap (axis-aligned in building frame)."""
|
||||||
|
dx = max(a[0] - b[2], b[0] - a[2])
|
||||||
|
dy = max(a[1] - b[3], b[1] - a[3])
|
||||||
|
if dx < 0 and dy < 0:
|
||||||
|
return max(dx, dy) # overlapping in both axes -> negative depth
|
||||||
|
return max(dx, dy)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
manifest = json.loads(Path(args.manifest).read_text(encoding="utf-8"))
|
||||||
|
origin = manifest.get("campus_origin_surveying_m") or manifest.get("campus_origin_surveying_mm")
|
||||||
|
if origin is None:
|
||||||
|
raise SystemExit("manifest needs campus_origin_surveying_m")
|
||||||
|
if max(abs(origin[0]), abs(origin[1])) > 1e6: # mm legacy
|
||||||
|
origin = [origin[0] / 1000.0, origin[1] / 1000.0]
|
||||||
|
theta = math.radians(float(manifest.get("rotation_deg", 0.0)))
|
||||||
|
cos_t, sin_t = math.cos(theta), math.sin(theta)
|
||||||
|
|
||||||
|
base_spec = None
|
||||||
|
placed: dict[str, dict] = {}
|
||||||
|
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)
|
||||||
|
continue
|
||||||
|
spec = json.loads(Path(b["spec"]).read_text(encoding="utf-8"))
|
||||||
|
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")
|
||||||
|
survey = b.get("survey_anchor_m") or b.get("survey_center_m")
|
||||||
|
if not anchor or not survey:
|
||||||
|
raise SystemExit(f"{name}: manifest entry needs model_anchor_m + survey_anchor_m")
|
||||||
|
xf = make_xf(anchor, survey, origin, cos_t, sin_t)
|
||||||
|
floors = transform_floors(spec, xf)
|
||||||
|
prefix = str(b.get("prefix", ""))
|
||||||
|
placed.update({prefix + fk: fl for fk, fl in floors.items()})
|
||||||
|
env = wall_envelope_axis(floors, cos_t, sin_t)
|
||||||
|
if env:
|
||||||
|
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")])]}
|
||||||
|
for r in spec.get("source", {}).get("config", {}).get("roof_specs", [])
|
||||||
|
]
|
||||||
|
|
||||||
|
if base_spec is None:
|
||||||
|
raise SystemExit("no buildings with specs in manifest")
|
||||||
|
|
||||||
|
# gap audit
|
||||||
|
names = list(envelopes)
|
||||||
|
failures = []
|
||||||
|
for i in range(len(names)):
|
||||||
|
for j in range(i + 1, len(names)):
|
||||||
|
gap = envelope_gap(envelopes[names[i]], envelopes[names[j]])
|
||||||
|
tag = f"{names[i]} <-> {names[j]}"
|
||||||
|
if gap < 0:
|
||||||
|
failures.append(f"OVERLAP {tag}: {gap:.3f} m — placement bug (roof-envelope anchor? flip?)")
|
||||||
|
elif gap < args.gap_warn:
|
||||||
|
print(f"NOTE {tag}: gap {gap:.3f} m — 贴建/变形缝? corroborate per SKILL rules", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
print(f"gap {tag}: {gap:.2f} m", file=sys.stderr)
|
||||||
|
if failures and not args.allow_overlap:
|
||||||
|
for f in failures:
|
||||||
|
print("FAIL " + f, file=sys.stderr)
|
||||||
|
return 3
|
||||||
|
for f in failures:
|
||||||
|
print("WARN(allowed) " + f, file=sys.stderr)
|
||||||
|
|
||||||
|
floors: dict = {}
|
||||||
|
site_keys: list[str] = []
|
||||||
|
if args.site_floors:
|
||||||
|
site = json.loads(Path(args.site_floors).read_text(encoding="utf-8"))
|
||||||
|
wall_bounds = [fl["bounds"] for fl in placed.values() if len(fl.get("segments", {}).get("walls", [])) >= 10]
|
||||||
|
for k, v in site.get("floors", {}).items():
|
||||||
|
if k.startswith("CTX"):
|
||||||
|
w = v.get("segments", {}).get("walls", [])
|
||||||
|
if w:
|
||||||
|
xs = [q for s in w for q in (s["start"][0], s["end"][0])]
|
||||||
|
ys = [q for s in w for q in (s["start"][1], s["end"][1])]
|
||||||
|
cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2
|
||||||
|
if any(b[0] - 1 <= cx <= b[2] + 1 and b[1] - 1 <= cy <= b[3] + 1 for b in wall_bounds):
|
||||||
|
continue # covered by a real model
|
||||||
|
floors[k] = v
|
||||||
|
site_keys.append(k)
|
||||||
|
base_spec.setdefault("categories", {}).update(site.get("categories", {}))
|
||||||
|
floors.update(placed)
|
||||||
|
|
||||||
|
campus = base_spec
|
||||||
|
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["floor_order"] = site_keys + [k for k in placed]
|
||||||
|
out = Path(args.out)
|
||||||
|
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))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -46,21 +46,48 @@ def parse_args() -> argparse.Namespace:
|
|||||||
return parser.parse_args()
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
def iter_block_contents(entity, max_depth: int, depth: int = 0):
|
_BLOCK_LENGTHS_CACHE: dict[tuple[int, str], dict[str, float]] = {}
|
||||||
"""Yield every leaf entity inside an INSERT, regardless of extraction config."""
|
|
||||||
if depth >= max_depth:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
from ezdxf import explode as ezdxf_explode
|
|
||||||
|
|
||||||
virtual_entities = list(ezdxf_explode.virtual_block_reference_entities(entity))
|
|
||||||
|
def block_layer_unit_lengths(doc, name: str, max_chord: float, max_depth: int, depth: int = 0) -> dict[str, float]:
|
||||||
|
"""Per-layer supported length inside a block DEFINITION (unit scale).
|
||||||
|
|
||||||
|
Exploding every INSERT for accounting is O(inserts x block size) and times
|
||||||
|
out on real Chinese sheet sets (hundreds of identical axis/door/window
|
||||||
|
blocks). Walking the definition once per block name and multiplying by the
|
||||||
|
insert scale gives the same length totals (rotation preserves length;
|
||||||
|
non-uniform scales are approximated by the mean of |sx|,|sy|).
|
||||||
|
"""
|
||||||
|
key = (id(doc), name)
|
||||||
|
cached = _BLOCK_LENGTHS_CACHE.get(key)
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
|
totals: dict[str, float] = defaultdict(float)
|
||||||
|
try:
|
||||||
|
block = doc.blocks.get(name)
|
||||||
except Exception:
|
except Exception:
|
||||||
return
|
block = None
|
||||||
for virtual_entity in virtual_entities:
|
if block is not None:
|
||||||
if virtual_entity.dxftype() == "INSERT":
|
for inner in block:
|
||||||
yield from iter_block_contents(virtual_entity, max_depth, depth + 1)
|
if inner.dxftype() == "INSERT" and depth < max_depth:
|
||||||
else:
|
inner_name = str(inner.dxf.name) if inner.dxf.hasattr("name") else ""
|
||||||
yield virtual_entity
|
if not inner_name:
|
||||||
|
continue
|
||||||
|
sx = abs(float(inner.dxf.get("xscale", 1.0) or 1.0))
|
||||||
|
sy = abs(float(inner.dxf.get("yscale", 1.0) or 1.0))
|
||||||
|
factor = (sx + sy) / 2.0
|
||||||
|
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)
|
||||||
|
)
|
||||||
|
if length > 0:
|
||||||
|
totals[derive.entity_layer(inner)] += length
|
||||||
|
result = dict(totals)
|
||||||
|
_BLOCK_LENGTHS_CACHE[key] = result
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
def output_paths(output: Path) -> tuple[Path, Path]:
|
def output_paths(output: Path) -> tuple[Path, Path]:
|
||||||
@@ -94,17 +121,34 @@ def inspect_entity(
|
|||||||
)
|
)
|
||||||
segments = derive.entity_segments(entity, max_chord)
|
segments = derive.entity_segments(entity, max_chord)
|
||||||
supported_length = sum(segment_length_source(segment) for segment in segments)
|
supported_length = sum(segment_length_source(segment) for segment in segments)
|
||||||
|
sample = None
|
||||||
|
if segments:
|
||||||
|
(sx, sy), (ex, ey) = segments[0]
|
||||||
|
sample = ((sx + ex) / 2.0, (sy + ey) / 2.0)
|
||||||
return {
|
return {
|
||||||
"layer": layer,
|
"layer": layer,
|
||||||
"type": dxftype,
|
"type": dxftype,
|
||||||
"category": category,
|
"category": category,
|
||||||
"segment_count": len(segments),
|
"segment_count": len(segments),
|
||||||
"supported_length": supported_length,
|
"supported_length": supported_length,
|
||||||
|
"sample": sample,
|
||||||
"high_risk": dxftype in HIGH_RISK_TYPES,
|
"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 ""),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def config_clips(config: dict[str, Any]) -> list[list[float]]:
|
||||||
|
clips = []
|
||||||
|
for drawing in config.get("drawings", []) or []:
|
||||||
|
base = drawing.get("clip")
|
||||||
|
for floor in drawing.get("floors", []) or []:
|
||||||
|
clip = floor.get("clip", base)
|
||||||
|
if clip:
|
||||||
|
x0, y0, x1, y1 = clip
|
||||||
|
clips.append([min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)])
|
||||||
|
return clips
|
||||||
|
|
||||||
|
|
||||||
def source_files_from_config(dxf_dir: Path, config: dict[str, Any]) -> list[Path]:
|
def source_files_from_config(dxf_dir: Path, config: dict[str, Any]) -> list[Path]:
|
||||||
drawings = config.get("drawings")
|
drawings = config.get("drawings")
|
||||||
if drawings:
|
if drawings:
|
||||||
@@ -147,6 +191,9 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
|
|||||||
total_supported = 0.0
|
total_supported = 0.0
|
||||||
classified_supported = 0.0
|
classified_supported = 0.0
|
||||||
captured_from_blocks = 0.0
|
captured_from_blocks = 0.0
|
||||||
|
clips = config_clips(config)
|
||||||
|
clipped_total = 0.0
|
||||||
|
clipped_classified = 0.0
|
||||||
excludes = derive.exclude_layer_patterns(config)
|
excludes = derive.exclude_layer_patterns(config)
|
||||||
max_block_depth = int(config.get("expand_blocks_max_depth", 2))
|
max_block_depth = int(config.get("expand_blocks_max_depth", 2))
|
||||||
block_layer_lengths: dict[str, dict[str, Any]] = defaultdict(
|
block_layer_lengths: dict[str, dict[str, Any]] = defaultdict(
|
||||||
@@ -172,19 +219,22 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
|
|||||||
file_insert_names[insert_name] += 1
|
file_insert_names[insert_name] += 1
|
||||||
# Config-independent accounting of geometry locked inside blocks,
|
# Config-independent accounting of geometry locked inside blocks,
|
||||||
# so missing block expansion cannot hide behind a high coverage number.
|
# so missing block expansion cannot hide behind a high coverage number.
|
||||||
for inner in iter_block_contents(source_entity, max_block_depth):
|
if insert_name:
|
||||||
inner_length = sum(
|
sx = abs(float(source_entity.dxf.get("xscale", 1.0) or 1.0))
|
||||||
segment_length_source(segment)
|
sy = abs(float(source_entity.dxf.get("yscale", 1.0) or 1.0))
|
||||||
for segment in derive.entity_segments(inner, max_chord)
|
factor = (sx + sy) / 2.0
|
||||||
|
unit_lengths = block_layer_unit_lengths(
|
||||||
|
doc, insert_name, max_chord, max_block_depth
|
||||||
)
|
)
|
||||||
if inner_length <= 0:
|
for inner_layer, unit_length in unit_lengths.items():
|
||||||
continue
|
inner_length = unit_length * factor
|
||||||
inner_layer = derive.entity_layer(inner)
|
if inner_length <= 0:
|
||||||
record = block_layer_lengths[inner_layer]
|
continue
|
||||||
record["supported_length_source"] += inner_length
|
record = block_layer_lengths[inner_layer]
|
||||||
record["entity_count"] += 1
|
record["supported_length_source"] += inner_length
|
||||||
if record["category"] is None:
|
record["entity_count"] += 1
|
||||||
record["category"] = derive.match_category(inner_layer, patterns, excludes) or ""
|
if record["category"] is None:
|
||||||
|
record["category"] = derive.match_category(inner_layer, patterns, excludes) or ""
|
||||||
for entity, fallback_layer, block_name in derive.iter_model_entities(source_entity, config):
|
for entity, fallback_layer, block_name in derive.iter_model_entities(source_entity, config):
|
||||||
item = inspect_entity(entity, patterns, config, max_chord, fallback_layer, block_name)
|
item = inspect_entity(entity, patterns, config, max_chord, fallback_layer, block_name)
|
||||||
layer = item["layer"]
|
layer = item["layer"]
|
||||||
@@ -209,6 +259,12 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
|
|||||||
captured_from_blocks += length
|
captured_from_blocks += length
|
||||||
total_supported += length
|
total_supported += length
|
||||||
file_total_supported += length
|
file_total_supported += length
|
||||||
|
if clips and item["sample"] is not None:
|
||||||
|
px, py = item["sample"]
|
||||||
|
if any(c[0] <= px <= c[2] and c[1] <= py <= c[3] for c in clips):
|
||||||
|
clipped_total += length
|
||||||
|
if category:
|
||||||
|
clipped_classified += length
|
||||||
|
|
||||||
if item["high_risk"]:
|
if item["high_risk"]:
|
||||||
# Top-level INSERTs were already counted above.
|
# Top-level INSERTs were already counted above.
|
||||||
@@ -284,6 +340,12 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
|
|||||||
"block_locked_length_meters": round(block_locked_total * scale, 3),
|
"block_locked_length_meters": round(block_locked_total * scale, 3),
|
||||||
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
|
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
|
||||||
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
|
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
|
||||||
|
# Clip-scoped view: with multi-frame clips, elevations/sections/details
|
||||||
|
# inflate the file-global denominator; judge extraction quality by THIS.
|
||||||
|
"clipped_supported_length_meters": round(clipped_total * scale, 3) if clips else None,
|
||||||
|
"clipped_supported_length_coverage": round(clipped_classified / clipped_total, 4)
|
||||||
|
if clips and clipped_total
|
||||||
|
else None,
|
||||||
},
|
},
|
||||||
"spec_counts": spec_counts(spec),
|
"spec_counts": spec_counts(spec),
|
||||||
"files": file_reports,
|
"files": file_reports,
|
||||||
@@ -296,21 +358,64 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
|
|||||||
"top_layers": dict(global_layer_counts.most_common(50)),
|
"top_layers": dict(global_layer_counts.most_common(50)),
|
||||||
"agent_questions": agent_questions(unclassified_layers, global_high_risk, global_insert_names),
|
"agent_questions": agent_questions(unclassified_layers, global_high_risk, global_insert_names),
|
||||||
}
|
}
|
||||||
report["gates"] = evaluate_gates(report)
|
report["gates"] = evaluate_gates(report, spec, config)
|
||||||
return report
|
return report
|
||||||
|
|
||||||
|
|
||||||
GATE_GLAZING_MIN_METERS = 5.0
|
GATE_GLAZING_MIN_METERS = 5.0
|
||||||
|
GATE_ALIGN_CENTER_FACTOR = 0.35
|
||||||
|
|
||||||
|
|
||||||
def evaluate_gates(report: dict[str, Any]) -> list[dict[str, Any]]:
|
def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""FAIL when floors of one stack are horizontally scattered.
|
||||||
|
|
||||||
|
The classic multi-frame failure mode:每层保留了图框在图纸墙上的位置,
|
||||||
|
模型里楼层沿图框间距斜着排开. Wall-bbox centers of floors in the same
|
||||||
|
cap-group must agree to within GATE_ALIGN_CENTER_FACTOR x plan size.
|
||||||
|
"""
|
||||||
|
groups: dict[str, list[tuple[str, float, float, float]]] = defaultdict(list)
|
||||||
|
for fk, floor in spec.get("floors", {}).items():
|
||||||
|
walls = floor.get("segments", {}).get("walls") or []
|
||||||
|
if len(walls) < 10:
|
||||||
|
continue
|
||||||
|
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)
|
||||||
|
)
|
||||||
|
worst: tuple[float, str] | None = None
|
||||||
|
for grp, items in groups.items():
|
||||||
|
if len(items) < 2:
|
||||||
|
continue
|
||||||
|
limit = GATE_ALIGN_CENTER_FACTOR * max(item[3] for item in items)
|
||||||
|
for i in range(len(items)):
|
||||||
|
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)})")
|
||||||
|
if worst:
|
||||||
|
return {
|
||||||
|
"name": "floors_aligned",
|
||||||
|
"status": "FAIL",
|
||||||
|
"detail": worst[1] + ". Floors are not stacked — per-frame offsets are missing or wrong; "
|
||||||
|
"run detect_sheet_frames.py and use its clip/offset config.",
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"name": "floors_aligned",
|
||||||
|
"status": "PASS",
|
||||||
|
"detail": "Wall-bbox centers of same-stack floors coincide.",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
"""Hard checks that must pass before 3D generation.
|
"""Hard checks that must pass before 3D generation.
|
||||||
|
|
||||||
A gate FAIL means the extraction is known-incomplete in a way that high
|
A gate FAIL means the extraction is known-incomplete in a way that high
|
||||||
coverage numbers cannot excuse; fix the config (block expansion, layer
|
coverage numbers cannot excuse; fix the config (block expansion, layer
|
||||||
mapping, source re-export) and re-run instead of accepting the model.
|
mapping, source re-export) and re-run instead of accepting the model.
|
||||||
"""
|
"""
|
||||||
gates: list[dict[str, Any]] = []
|
gates: list[dict[str, Any]] = [floors_alignment_gate(spec, config)]
|
||||||
|
|
||||||
spec_glazing_segments = sum(
|
spec_glazing_segments = sum(
|
||||||
counts.get("glazing", 0) for counts in report["spec_counts"].values()
|
counts.get("glazing", 0) for counts in report["spec_counts"].values()
|
||||||
@@ -428,6 +533,11 @@ def markdown(report: dict[str, Any]) -> str:
|
|||||||
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
|
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
|
||||||
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
|
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
|
||||||
"(modelspace linework only — block-locked geometry is NOT in this denominator)",
|
"(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"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
|
f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
|
||||||
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
|
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
|
||||||
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",
|
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",
|
||||||
|
|||||||
@@ -245,6 +245,137 @@ def create_segment_mesh(bpy, name: str, segments: list[dict], z0: float, z1: flo
|
|||||||
return obj
|
return obj
|
||||||
|
|
||||||
|
|
||||||
|
def extend_shared_wall_ends(segments: list[dict], tol: float = 1e-3) -> list[dict]:
|
||||||
|
"""Extend wall ends that meet another wall's endpoint by half their own width.
|
||||||
|
|
||||||
|
Flat-capped rectangles stop exactly at the endpoint, so an L-corner leaves
|
||||||
|
a w/2 x w/2 notch that even a union keeps open. Extending only SHARED ends
|
||||||
|
closes the corner while free ends (door/window openings) stay flat.
|
||||||
|
Mirror of spec_to_glb.extend_shared_wall_ends.
|
||||||
|
"""
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
pts = []
|
||||||
|
for segment in segments:
|
||||||
|
pts.append((float(segment["start"][0]), float(segment["start"][1])))
|
||||||
|
pts.append((float(segment["end"][0]), float(segment["end"][1])))
|
||||||
|
scale = 1.0 / max(tol, 1e-9)
|
||||||
|
buckets = Counter((round(x * scale), round(y * scale)) for x, y in pts)
|
||||||
|
|
||||||
|
def shared(point):
|
||||||
|
cx, cy = round(point[0] * scale), round(point[1] * scale)
|
||||||
|
return sum(buckets.get((gx, gy), 0) for gx in (cx - 1, cx, cx + 1) for gy in (cy - 1, cy, cy + 1)) >= 2
|
||||||
|
|
||||||
|
out = []
|
||||||
|
for segment in segments:
|
||||||
|
start = [float(segment["start"][0]), float(segment["start"][1])]
|
||||||
|
end = [float(segment["end"][0]), float(segment["end"][1])]
|
||||||
|
dx, dy = end[0] - start[0], end[1] - start[1]
|
||||||
|
length = math.hypot(dx, dy)
|
||||||
|
if length < 1e-7:
|
||||||
|
out.append(segment)
|
||||||
|
continue
|
||||||
|
ux, uy = dx / length, dy / length
|
||||||
|
half = max(float(segment.get("width", 0.1)), 0.005) / 2.0
|
||||||
|
item = dict(segment)
|
||||||
|
if shared((start[0], start[1])):
|
||||||
|
start = [start[0] - ux * half, start[1] - uy * half]
|
||||||
|
if shared((end[0], end[1])):
|
||||||
|
end = [end[0] + ux * half, end[1] + uy * half]
|
||||||
|
item["start"] = start
|
||||||
|
item["end"] = end
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
union of the overlapping rectangles; edges used by exactly one triangle are
|
||||||
|
the union outline and become the side faces. Same visual contract as
|
||||||
|
spec_to_glb.py's shapely union, without needing shapely in Blender python.
|
||||||
|
"""
|
||||||
|
from mathutils import Vector
|
||||||
|
from mathutils.geometry import delaunay_2d_cdt
|
||||||
|
|
||||||
|
points = []
|
||||||
|
rects = []
|
||||||
|
for segment in extend_shared_wall_ends(segments):
|
||||||
|
prism = segment_prism(segment, z0, z1)
|
||||||
|
if not prism:
|
||||||
|
continue
|
||||||
|
idx = len(points)
|
||||||
|
points.extend(Vector((vert[0], vert[1])) for vert in prism[:4])
|
||||||
|
rects.append((idx, idx + 1, idx + 2, idx + 3))
|
||||||
|
if not rects:
|
||||||
|
return None
|
||||||
|
verts2d, _edges, tris = delaunay_2d_cdt(points, [], rects, 1, 1e-5)[:3]
|
||||||
|
if not tris:
|
||||||
|
return None
|
||||||
|
count = len(verts2d)
|
||||||
|
verts = [(v.x, v.y, z0) for v in verts2d] + [(v.x, v.y, z1) for v in verts2d]
|
||||||
|
edge_use: dict[tuple[int, int], int] = {}
|
||||||
|
for tri in tris:
|
||||||
|
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
|
||||||
|
key = (min(a, b), max(a, b))
|
||||||
|
edge_use[key] = edge_use.get(key, 0) + 1
|
||||||
|
faces = [tuple(reversed(tri)) for tri in tris] # bottom, facing down
|
||||||
|
faces += [tuple(i + count for i in tri) for tri in tris] # top, facing up
|
||||||
|
for tri in tris:
|
||||||
|
# CCW triangles keep the interior left of a->b, so (a,b,b',a') faces outward.
|
||||||
|
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
|
||||||
|
if edge_use[(min(a, b), max(a, b))] == 1:
|
||||||
|
faces.append((a, b, b + count, a + count))
|
||||||
|
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
||||||
|
mesh.from_pydata(verts, [], faces)
|
||||||
|
mesh.update()
|
||||||
|
mesh.validate(verbose=False)
|
||||||
|
obj = bpy.data.objects.new(name, mesh)
|
||||||
|
bpy.context.collection.objects.link(obj)
|
||||||
|
obj.data.materials.append(material)
|
||||||
|
obj["floor"] = floor_key
|
||||||
|
obj["category"] = category
|
||||||
|
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]:
|
||||||
|
"""Curtain-wall panel grid over glazing bands (mirror of spec_to_glb).
|
||||||
|
|
||||||
|
Emits pseudo wall segments (thin box profiles, rendered into the
|
||||||
|
<floor>__walls object): vertical mullions evenly spaced ~panel_w per band
|
||||||
|
plus a horizontal transom at the band's bottom and top floor lines
|
||||||
|
(via _z0/_z1). Config {"glazing_mullions": true, "glazing_panel_w": 1.5}.
|
||||||
|
"""
|
||||||
|
out = []
|
||||||
|
for segment in bands:
|
||||||
|
start = segment["start"]
|
||||||
|
end = segment["end"]
|
||||||
|
dx, dy = end[0] - start[0], end[1] - start[1]
|
||||||
|
length = math.hypot(dx, dy)
|
||||||
|
if length < max(profile * 2, 0.3):
|
||||||
|
continue
|
||||||
|
ux, uy = dx / length, dy / length
|
||||||
|
panels = max(1, round(length / max(panel_w, 0.2)))
|
||||||
|
step = length / panels
|
||||||
|
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",
|
||||||
|
})
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def create_label(bpy, name: str, body: str, location: tuple[float, float, float], size: float, material):
|
def create_label(bpy, name: str, body: str, location: tuple[float, float, float], size: float, material):
|
||||||
curve = bpy.data.curves.new(f"{name}Curve", "FONT")
|
curve = bpy.data.curves.new(f"{name}Curve", "FONT")
|
||||||
curve.body = body
|
curve.body = body
|
||||||
@@ -328,11 +459,11 @@ def generated_roof_bounds(spec: dict) -> list[dict]:
|
|||||||
continue
|
continue
|
||||||
bounds_from = list(roof.get("bounds_from", [floor_key]))
|
bounds_from = list(roof.get("bounds_from", [floor_key]))
|
||||||
footprint_from = list(roof.get("footprint_from", bounds_from))
|
footprint_from = list(roof.get("footprint_from", bounds_from))
|
||||||
footprint_polygons = (
|
# Footprint polygons take priority over rectangular bounds whenever the
|
||||||
footprint_polygons_from_floor_keys(spec, footprint_from)
|
# source floors carry them (same contract as spec_to_glb.py); a bounds
|
||||||
if config.get("use_footprint_roofs", False) or roof.get("use_footprint", False)
|
# rect for e.g. a PH machine-room roof covers the whole building bbox
|
||||||
else []
|
# and reads as a plate jutting past the facade.
|
||||||
)
|
footprint_polygons = footprint_polygons_from_floor_keys(spec, footprint_from)
|
||||||
bounds = roof.get("bounds") or bounds_from_floor_keys(spec, bounds_from)
|
bounds = roof.get("bounds") or bounds_from_floor_keys(spec, bounds_from)
|
||||||
if not bounds:
|
if not bounds:
|
||||||
bounds = floor.get("bounds")
|
bounds = floor.get("bounds")
|
||||||
@@ -519,7 +650,11 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
|
|||||||
floor_key,
|
floor_key,
|
||||||
"slab",
|
"slab",
|
||||||
)
|
)
|
||||||
else:
|
elif config.get("slab_bounds_fallback", True):
|
||||||
|
# Rectangular fallback can fake a full-cover plate on floors like
|
||||||
|
# parapet-only roof plans or campus context floors (roads/fence/trees);
|
||||||
|
# disable via config {"slab_bounds_fallback": false} when footprints
|
||||||
|
# are trusted (same contract as spec_to_glb.py).
|
||||||
create_box_mesh(bpy, f"{floor_key}__slab", [slab_box], materials["slab"], floor_key, "slab")
|
create_box_mesh(bpy, f"{floor_key}__slab", [slab_box], materials["slab"], floor_key, "slab")
|
||||||
# Cap slabs close the tops of columns at setbacks and over basement parking
|
# Cap slabs close the tops of columns at setbacks and over basement parking
|
||||||
# (computed by derive_showcase_spec.py and stored as floor["caps"]). They share
|
# (computed by derive_showcase_spec.py and stored as floor["caps"]). They share
|
||||||
@@ -540,15 +675,34 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
|
|||||||
"slab",
|
"slab",
|
||||||
)
|
)
|
||||||
floor_segments = floor.get("segments", {})
|
floor_segments = floor.get("segments", {})
|
||||||
|
mullion_segments: list[dict] = []
|
||||||
|
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)),
|
||||||
|
)
|
||||||
known = [category for category in CATEGORY_DRAW_ORDER if floor_segments.get(category)]
|
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:
|
for category in known + extra:
|
||||||
segments = floor.get("segments", {}).get(category, [])
|
segments = floor.get("segments", {}).get(category, [])
|
||||||
if not segments:
|
if not segments and category != "walls":
|
||||||
continue
|
continue
|
||||||
if category == "columns":
|
if category == "columns":
|
||||||
segments = adjusted_column_segments(segments, floor_key, floor, spec)
|
segments = adjusted_column_segments(segments, floor_key, floor, spec)
|
||||||
z0, z1 = z_window_for_category(category, z, height, floor_key, floor)
|
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,
|
||||||
|
)
|
||||||
|
if merged is not None:
|
||||||
|
segments = [] # walls handled; mullions (if any) get their own pass below
|
||||||
|
if category == "walls":
|
||||||
|
segments = list(segments) + mullion_segments
|
||||||
|
mullion_segments = []
|
||||||
|
if not segments:
|
||||||
|
continue
|
||||||
create_segment_mesh(
|
create_segment_mesh(
|
||||||
bpy,
|
bpy,
|
||||||
f"{floor_key}__{category}",
|
f"{floor_key}__{category}",
|
||||||
|
|||||||
@@ -69,6 +69,13 @@ def filtered_spec(source: dict[str, Any], variant: dict[str, Any]) -> dict[str,
|
|||||||
return spec
|
return spec
|
||||||
keep_set = set(keep)
|
keep_set = set(keep)
|
||||||
for floor in spec.get("floors", {}).values():
|
for floor in spec.get("floors", {}).values():
|
||||||
|
# Campus site-context floors (roads/parking/fence/trees emitted by
|
||||||
|
# site_context_from_dump.py with source_file="site") are presentation
|
||||||
|
# content: their roads live on detail_lines/grid and trees on a custom
|
||||||
|
# category, so category filtering would strip the whole site. Keep them
|
||||||
|
# intact in every variant.
|
||||||
|
if floor.get("source_file") == "site":
|
||||||
|
continue
|
||||||
segments = floor.get("segments", {})
|
segments = floor.get("segments", {})
|
||||||
for category in list(segments):
|
for category in list(segments):
|
||||||
if category not in keep_set:
|
if category not in keep_set:
|
||||||
|
|||||||
@@ -162,12 +162,47 @@ def xref_definitions(doc) -> list[dict]:
|
|||||||
return xrefs
|
return xrefs
|
||||||
|
|
||||||
|
|
||||||
|
import re as _re
|
||||||
|
|
||||||
|
PLAN_TITLE_RE = _re.compile(r"平面图$")
|
||||||
|
PLAN_TITLE_EXCLUDE_RE = _re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
|
||||||
|
|
||||||
|
|
||||||
|
def count_plan_titles(entities) -> int:
|
||||||
|
"""Distinct plan-frame titles in modelspace (multi-frame sheet detector)."""
|
||||||
|
seen = set()
|
||||||
|
for entity in entities:
|
||||||
|
kind = entity.dxftype()
|
||||||
|
if kind not in {"TEXT", "MTEXT"}:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
text = str(entity.dxf.text if kind == "TEXT" else entity.plain_text() or "").strip()
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if not text or len(text) > 40:
|
||||||
|
continue
|
||||||
|
if PLAN_TITLE_RE.search(text) and not PLAN_TITLE_EXCLUDE_RE.search(text):
|
||||||
|
try:
|
||||||
|
pos = entity.dxf.insert
|
||||||
|
seen.add((text, round(float(pos.x) / 5000), round(float(pos.y) / 5000)))
|
||||||
|
except Exception:
|
||||||
|
seen.add((text, 0, 0))
|
||||||
|
return len(seen)
|
||||||
|
|
||||||
|
|
||||||
def file_warnings(item: dict) -> list[str]:
|
def file_warnings(item: dict) -> list[str]:
|
||||||
warnings = []
|
warnings = []
|
||||||
entities = item.get("modelspace_entities")
|
entities = item.get("modelspace_entities")
|
||||||
xrefs = item.get("xref_definitions", [])
|
xrefs = item.get("xref_definitions", [])
|
||||||
if entities is None:
|
if entities is None:
|
||||||
return warnings
|
return warnings
|
||||||
|
plan_titles = item.get("plan_title_count", 0)
|
||||||
|
if plan_titles >= 2:
|
||||||
|
warnings.append(
|
||||||
|
f"multi_frame_sheet: {plan_titles} plan-frame titles (XX平面图) found in ONE modelspace. "
|
||||||
|
"This file holds a whole sheet set — never model it as a single floor and never stack frames "
|
||||||
|
"without per-floor offsets. Run scripts/detect_sheet_frames.py to generate clip/offset config."
|
||||||
|
)
|
||||||
if xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD:
|
if xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD:
|
||||||
names = ", ".join(x["name"] for x in xrefs[:4])
|
names = ", ".join(x["name"] for x in xrefs[:4])
|
||||||
warnings.append(
|
warnings.append(
|
||||||
@@ -231,6 +266,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
|
|||||||
"measurement": int(header.get("$MEASUREMENT", 0) or 0),
|
"measurement": int(header.get("$MEASUREMENT", 0) or 0),
|
||||||
"unit_guess": guess_unit_scale(geometry_bbox, insunits),
|
"unit_guess": guess_unit_scale(geometry_bbox, insunits),
|
||||||
"modelspace_entities": len(entities),
|
"modelspace_entities": len(entities),
|
||||||
|
"plan_title_count": count_plan_titles(entities),
|
||||||
"entity_types": dict(type_counts.most_common()),
|
"entity_types": dict(type_counts.most_common()),
|
||||||
"top_layers": [
|
"top_layers": [
|
||||||
{"name": name, "entity_count": count}
|
{"name": name, "entity_count": count}
|
||||||
@@ -327,7 +363,8 @@ def main() -> int:
|
|||||||
if conversion["status"] == "ok":
|
if conversion["status"] == "ok":
|
||||||
raw_dxfs.append(dest)
|
raw_dxfs.append(dest)
|
||||||
else:
|
else:
|
||||||
shutil.copy2(source, dest)
|
if source.resolve() != dest.resolve():
|
||||||
|
shutil.copy2(source, dest)
|
||||||
raw_dxfs.append(dest)
|
raw_dxfs.append(dest)
|
||||||
|
|
||||||
sanitized: list[Path] = []
|
sanitized: list[Path] = []
|
||||||
|
|||||||
@@ -269,6 +269,54 @@ def probe_keep_entity(entity, config: dict[str, Any]) -> bool:
|
|||||||
return category is not None and category in allowed
|
return category is not None and category in allowed
|
||||||
|
|
||||||
|
|
||||||
|
_BLOCK_LEAF_LAYERS: dict[tuple[int, str], frozenset[str]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def block_leaf_layers(doc, name: str, max_depth: int, depth: int = 0) -> frozenset[str]:
|
||||||
|
"""Layers used by a block definition (recursing into nested INSERTs).
|
||||||
|
|
||||||
|
Cheap definition walk (no explode/transform) memoized per document+name so
|
||||||
|
probe expansion can skip the expensive virtual explode for the vast
|
||||||
|
majority of blocks (axis bubbles, tags, hatched symbols) whose contents can
|
||||||
|
never classify into block_content_categories.
|
||||||
|
"""
|
||||||
|
key = (id(doc), name)
|
||||||
|
cached = _BLOCK_LEAF_LAYERS.get(key)
|
||||||
|
if cached is not None:
|
||||||
|
return cached
|
||||||
|
layers: set[str] = set()
|
||||||
|
try:
|
||||||
|
block = doc.blocks.get(name)
|
||||||
|
except Exception:
|
||||||
|
block = None
|
||||||
|
if block is not None:
|
||||||
|
for inner in block:
|
||||||
|
if inner.dxftype() == "INSERT" and depth < max_depth:
|
||||||
|
inner_name = str(inner.dxf.name) if inner.dxf.hasattr("name") else ""
|
||||||
|
if inner_name:
|
||||||
|
layers |= block_leaf_layers(doc, inner_name, max_depth, depth + 1)
|
||||||
|
else:
|
||||||
|
layers.add(entity_layer(inner))
|
||||||
|
result = frozenset(layers)
|
||||||
|
_BLOCK_LEAF_LAYERS[key] = result
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def probe_block_may_match(entity, config: dict[str, Any]) -> bool:
|
||||||
|
"""True if any leaf layer of the INSERT's block could classify for probing."""
|
||||||
|
doc = getattr(entity, "doc", None)
|
||||||
|
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
|
||||||
|
if doc is None or not block_name:
|
||||||
|
return True # cannot prove it is irrelevant; expand as before
|
||||||
|
patterns, excludes, allowed = _probe_rules(config)
|
||||||
|
max_depth = int(config.get("expand_blocks_max_depth", 2))
|
||||||
|
for layer in block_leaf_layers(doc, block_name, max_depth):
|
||||||
|
category = match_category(layer, patterns, excludes)
|
||||||
|
if category is not None and category in allowed:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
|
def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
|
||||||
"""Yield (entity, fallback_layer, block_name) tuples to inspect/extract.
|
"""Yield (entity, fallback_layer, block_name) tuples to inspect/extract.
|
||||||
|
|
||||||
@@ -291,6 +339,11 @@ def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
|
|||||||
if (not explicit and not probe) or depth >= max_depth:
|
if (not explicit and not probe) or depth >= max_depth:
|
||||||
yield entity, "", ""
|
yield entity, "", ""
|
||||||
return
|
return
|
||||||
|
if not explicit and probe and not probe_block_may_match(entity, config):
|
||||||
|
# No leaf layer of this block can classify -> exploding it cannot
|
||||||
|
# contribute geometry; skip the expensive virtual expansion.
|
||||||
|
yield entity, "", ""
|
||||||
|
return
|
||||||
|
|
||||||
insert_layer = entity_layer(entity)
|
insert_layer = entity_layer(entity)
|
||||||
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
|
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
|
||||||
@@ -426,68 +479,76 @@ def collect_raw_segments(
|
|||||||
entities = list(doc.modelspace())
|
entities = list(doc.modelspace())
|
||||||
floors = drawing.get("floors") or [{"key": Path(drawing["file"]).stem, "name": Path(drawing["file"]).stem}]
|
floors = drawing.get("floors") or [{"key": Path(drawing["file"]).stem, "name": Path(drawing["file"]).stem}]
|
||||||
|
|
||||||
|
# Single pass over (expanded) entities, bucketed per floor. Expanding
|
||||||
|
# INSERTs per floor is O(floors x inserts) and times out on Chinese
|
||||||
|
# multi-frame sheets where one DWG holds every floor of a building.
|
||||||
|
floor_specs = []
|
||||||
|
buckets: dict[str, dict[str, list[dict[str, Any]]]] = {}
|
||||||
|
counts: dict[str, int] = {}
|
||||||
for floor in floors:
|
for floor in floors:
|
||||||
key = str(floor["key"])
|
key = str(floor["key"])
|
||||||
offset_values = floor.get("offset", drawing.get("offset", [0, 0]))
|
offset_values = floor.get("offset", drawing.get("offset", [0, 0]))
|
||||||
offset = (float(offset_values[0]), float(offset_values[1]))
|
floor_specs.append((floor, key, (float(offset_values[0]), float(offset_values[1]))))
|
||||||
segments_by_category: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
buckets[key] = defaultdict(list)
|
||||||
ignored_by_type: dict[str, int] = defaultdict(int)
|
counts[key] = 0
|
||||||
included = 0
|
ignored_by_type: dict[str, int] = defaultdict(int)
|
||||||
|
|
||||||
for entity in entities:
|
for entity in entities:
|
||||||
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
|
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
|
||||||
layer = entity_layer(extracted_entity)
|
layer = entity_layer(extracted_entity)
|
||||||
category = category_for_entity(
|
category = category_for_entity(
|
||||||
extracted_entity,
|
extracted_entity,
|
||||||
patterns,
|
patterns,
|
||||||
config,
|
config,
|
||||||
fallback_layer=fallback_layer,
|
fallback_layer=fallback_layer,
|
||||||
block_name=block_name,
|
block_name=block_name,
|
||||||
)
|
)
|
||||||
if not category:
|
if not category:
|
||||||
ignored_by_type[extracted_entity.dxftype()] += 1
|
ignored_by_type[extracted_entity.dxftype()] += 1
|
||||||
continue
|
continue
|
||||||
for start, end in entity_segments(extracted_entity, max_chord):
|
segments = entity_segments(extracted_entity, max_chord)
|
||||||
|
if not segments:
|
||||||
|
continue
|
||||||
|
source_type = extracted_entity.dxftype()
|
||||||
|
width = default_widths.get(category, 0.1)
|
||||||
|
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:
|
||||||
if not segment_matches_floor(start, end, floor, drawing):
|
if not segment_matches_floor(start, end, floor, drawing):
|
||||||
continue
|
continue
|
||||||
seg = cleaned_segment(
|
seg = cleaned_segment(start, end, offset, min_source, min_meters, scale)
|
||||||
start,
|
|
||||||
end,
|
|
||||||
offset,
|
|
||||||
min_source_by_category.get(category, min_source_length),
|
|
||||||
min_meters_by_category.get(category, min_meters_length),
|
|
||||||
scale,
|
|
||||||
)
|
|
||||||
if not seg:
|
if not seg:
|
||||||
continue
|
continue
|
||||||
clean_start, clean_end = seg
|
clean_start, clean_end = seg
|
||||||
segments_by_category[category].append(
|
buckets[key][category].append(
|
||||||
{
|
{
|
||||||
"start_source": clean_start,
|
"start_source": clean_start,
|
||||||
"end_source": clean_end,
|
"end_source": clean_end,
|
||||||
"width": default_widths.get(category, 0.1),
|
"width": width,
|
||||||
"layer": layer,
|
"layer": layer,
|
||||||
"source_type": extracted_entity.dxftype(),
|
"source_type": source_type,
|
||||||
"block_name": block_name,
|
"block_name": block_name,
|
||||||
"fallback_layer": fallback_layer,
|
"fallback_layer": fallback_layer,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
included += 1
|
counts[key] += 1
|
||||||
|
|
||||||
|
for floor, key, _offset in floor_specs:
|
||||||
floor_data[key] = {
|
floor_data[key] = {
|
||||||
"key": key,
|
"key": key,
|
||||||
"name": str(floor.get("name", key)),
|
"name": str(floor.get("name", key)),
|
||||||
"z": floor.get("z"),
|
"z": floor.get("z"),
|
||||||
"height": float(floor.get("height", config.get("floor_height", 4.2))),
|
"height": float(floor.get("height", config.get("floor_height", 4.2))),
|
||||||
"source_file": path.name,
|
"source_file": path.name,
|
||||||
"segments_source": dict(segments_by_category),
|
"segments_source": dict(buckets[key]),
|
||||||
}
|
}
|
||||||
extraction_report.append(
|
extraction_report.append(
|
||||||
{
|
{
|
||||||
"file": path.name,
|
"file": path.name,
|
||||||
"floor": key,
|
"floor": key,
|
||||||
"status": "ok",
|
"status": "ok",
|
||||||
"segments": included,
|
"segments": counts[key],
|
||||||
"ignored_entity_types": dict(sorted(ignored_by_type.items())),
|
"ignored_entity_types": dict(sorted(ignored_by_type.items())),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -624,7 +685,16 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _cap_floor_group(fk: str) -> str:
|
def _cap_floor_group(fk: str, config: dict[str, Any] | None = None) -> str:
|
||||||
|
"""Cap grouping: which floors stack in the same tower for cap logic.
|
||||||
|
|
||||||
|
Configurable via config["cap_groups"] = [["AUX_*", "AUX"], ["B*", "BASE"], ...]
|
||||||
|
(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_"):
|
if fk.startswith("AUX_"):
|
||||||
return "AUX"
|
return "AUX"
|
||||||
if fk in {"B1", "B1M"}:
|
if fk in {"B1", "B1M"}:
|
||||||
@@ -678,10 +748,10 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
|
|||||||
if not own_polys:
|
if not own_polys:
|
||||||
continue
|
continue
|
||||||
ftop = float(fl["z"]) + float(fl.get("height", 4.2))
|
ftop = float(fl["z"]) + float(fl.get("height", 4.2))
|
||||||
grp = _cap_floor_group(fk)
|
grp = _cap_floor_group(fk, config)
|
||||||
upper = []
|
upper = []
|
||||||
for ok, ot in floors.items():
|
for ok, ot in floors.items():
|
||||||
if ok == fk or _cap_floor_group(ok) != grp:
|
if ok == fk or _cap_floor_group(ok, config) != grp:
|
||||||
continue
|
continue
|
||||||
if abs(float(ot.get("z", 0.0)) - ftop) > 0.8:
|
if abs(float(ot.get("z", 0.0)) - ftop) > 0.8:
|
||||||
continue
|
continue
|
||||||
@@ -765,6 +835,33 @@ def finalize_spec(
|
|||||||
)
|
)
|
||||||
compute_caps(floors, config)
|
compute_caps(floors, config)
|
||||||
|
|
||||||
|
# Topless-roof guard: the top above-ground floor of each group must end in
|
||||||
|
# a cap or a config roof_specs entry, otherwise the model renders open-top
|
||||||
|
# ("没有屋顶"). Warn loudly so the Agent adds roof_specs before building.
|
||||||
|
roof_tops: dict[str, float] = {}
|
||||||
|
for r in config.get("roof_specs", []):
|
||||||
|
fk = str(r.get("floor_key"))
|
||||||
|
if fk not in floors:
|
||||||
|
continue
|
||||||
|
grp = _cap_floor_group(fk, config)
|
||||||
|
z = float(r.get("z", float(floors[fk]["z"]) + float(floors[fk].get("height", 4.2))))
|
||||||
|
roof_tops[grp] = max(roof_tops.get(grp, -1e9), z)
|
||||||
|
groups: dict[str, str] = {}
|
||||||
|
for key in floors:
|
||||||
|
grp = _cap_floor_group(key, config)
|
||||||
|
if grp not in groups or float(floors[key]["z"]) > float(floors[groups[grp]]["z"]):
|
||||||
|
groups[grp] = key
|
||||||
|
for grp, top_key in groups.items():
|
||||||
|
top = floors[top_key]
|
||||||
|
covered = roof_tops.get(grp, -1e9) >= float(top["z"]) - 0.8
|
||||||
|
if grp != "BASE" and not top.get("caps") and not covered:
|
||||||
|
print(
|
||||||
|
f"WARNING topless_group {grp}: top floor '{top_key}' has no caps and no "
|
||||||
|
f"roof_specs entry; add config roof_specs=[{{'floor_key': '{top_key}', ...}}] "
|
||||||
|
"or the model will have no roof plate.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
categories = {
|
categories = {
|
||||||
key: {"label": value["label"], "color": value["color"]}
|
key: {"label": value["label"], "color": value["color"]}
|
||||||
for key, value in DEFAULT_CATEGORIES.items()
|
for key, value in DEFAULT_CATEGORIES.items()
|
||||||
|
|||||||
382
scripts/detect_sheet_frames.py
Normal file
382
scripts/detect_sheet_frames.py
Normal file
@@ -0,0 +1,382 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Detect per-floor plan frames inside a multi-sheet DXF and propose extraction config.
|
||||||
|
|
||||||
|
Chinese construction sets commonly put ALL sheets of one building into a single
|
||||||
|
DWG modelspace (plans, elevations, sections, details side by side / stacked).
|
||||||
|
Treating such a file as one floor superimposes every sheet; treating N files as
|
||||||
|
N floors scatters plans by their sheet offsets (the "diagonal staircase" bug).
|
||||||
|
|
||||||
|
This tool:
|
||||||
|
1. Finds plan-title TEXTs (一层平面图 / 地下一层平面图 / 屋顶平面图 ...),
|
||||||
|
filtering out sheet-catalog rows and title-block copies (keeps, per title
|
||||||
|
name, only the largest-height instances outside excluded layers).
|
||||||
|
2. Proposes a clip window per plan frame from the sheet pitch, then refines it
|
||||||
|
to the wall-geometry bounding box inside the frame (drops title blocks,
|
||||||
|
notes, and neighbouring sheets).
|
||||||
|
3. Aligns every floor onto a reference floor with a label-free grid
|
||||||
|
correlation: vertical/horizontal axis-line positions are matched by voting
|
||||||
|
over candidate translations. Works even when upper floors show partial
|
||||||
|
grids, and needs no axis-number texts.
|
||||||
|
4. Emits a ready-to-edit extraction config skeleton plus a Markdown report
|
||||||
|
(elevation/section frames are listed for floor heights, not as floors).
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 detect_sheet_frames.py --dxf work/dxf_sanitized/xxx.dxf \
|
||||||
|
--out-config work/frames_config.json --out-report work/frames_report.md
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import fnmatch
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
import statistics
|
||||||
|
import sys
|
||||||
|
from collections import Counter, defaultdict
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PLAN_TITLE = re.compile(r"平面图$")
|
||||||
|
PLAN_EXCLUDE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
|
||||||
|
OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
|
||||||
|
CN_NUM = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10}
|
||||||
|
FLOOR_NAME_KEY = [
|
||||||
|
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"B{_cn(m.group('n'))}M"),
|
||||||
|
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"B{_cn(m.group('n'))}"),
|
||||||
|
(re.compile(r"屋顶机房|机房层|电梯机房"), lambda m: "PH"),
|
||||||
|
(re.compile(r"屋顶|屋面|顶板"), lambda m: "RF"),
|
||||||
|
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"F{_cn(m.group('n'))}M"),
|
||||||
|
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"F{_cn(m.group('n'))}"),
|
||||||
|
(re.compile(r"地下|底层"), lambda m: "B1"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _cn(token: str) -> int:
|
||||||
|
if token.isdigit():
|
||||||
|
return int(token)
|
||||||
|
return CN_NUM.get(token, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--dxf", required=True)
|
||||||
|
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-exclude-regex", default=r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
|
||||||
|
parser.add_argument("--title-exclude-layers", default="*图签*,*PUB_TAB*,*TK*,*图框*,*目录*")
|
||||||
|
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")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def import_ezdxf(vendor_dir: Path):
|
||||||
|
if vendor_dir.exists():
|
||||||
|
sys.path.insert(0, str(vendor_dir.resolve()))
|
||||||
|
try:
|
||||||
|
import ezdxf # type: ignore
|
||||||
|
from ezdxf import recover # type: ignore
|
||||||
|
except ImportError as exc:
|
||||||
|
raise SystemExit(f"Missing ezdxf. pip install --target {vendor_dir} ezdxf") from exc
|
||||||
|
return ezdxf, recover
|
||||||
|
|
||||||
|
|
||||||
|
def match_any(value: str, patterns: list[str]) -> bool:
|
||||||
|
upper = value.upper()
|
||||||
|
return any(fnmatch.fnmatch(upper, p.upper()) for p in patterns)
|
||||||
|
|
||||||
|
|
||||||
|
def entity_text(entity) -> str:
|
||||||
|
try:
|
||||||
|
if entity.dxftype() == "TEXT":
|
||||||
|
return str(entity.dxf.text or "").strip()
|
||||||
|
if entity.dxftype() == "MTEXT":
|
||||||
|
return str(entity.plain_text() or "").strip()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def floor_key_for(name: str, used: set[str]) -> str:
|
||||||
|
for pattern, keyfn in FLOOR_NAME_KEY:
|
||||||
|
match = pattern.search(name)
|
||||||
|
if match:
|
||||||
|
key = keyfn(match)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
key = re.sub(r"[^0-9A-Za-z]+", "_", name)[:12] or "FLOOR"
|
||||||
|
base, i = key, 2
|
||||||
|
while key in used:
|
||||||
|
key = f"{base}_{i}"
|
||||||
|
i += 1
|
||||||
|
used.add(key)
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def cluster_positions(values: list[float], tol: float) -> list[float]:
|
||||||
|
if not values:
|
||||||
|
return []
|
||||||
|
values = sorted(values)
|
||||||
|
clusters, current = [], [values[0]]
|
||||||
|
for v in values[1:]:
|
||||||
|
if v - current[-1] <= tol:
|
||||||
|
current.append(v)
|
||||||
|
else:
|
||||||
|
clusters.append(sum(current) / len(current))
|
||||||
|
current = [v]
|
||||||
|
clusters.append(sum(current) / len(current))
|
||||||
|
return clusters
|
||||||
|
|
||||||
|
|
||||||
|
def vote_translation(ref: list[float], src: list[float], bin_size: float) -> tuple[float | None, int]:
|
||||||
|
"""Best dx such that {src + dx} matches ref, by histogram voting."""
|
||||||
|
if not ref or not src:
|
||||||
|
return None, 0
|
||||||
|
votes: Counter = Counter()
|
||||||
|
for r in ref:
|
||||||
|
for s in src:
|
||||||
|
votes[round((r - s) / bin_size)] += 1
|
||||||
|
best_bin, best_votes = votes.most_common(1)[0]
|
||||||
|
if best_votes < 2:
|
||||||
|
return None, best_votes
|
||||||
|
fine = [r - s for r in ref for s in src if abs((r - s) - best_bin * bin_size) <= bin_size]
|
||||||
|
return statistics.median(fine), best_votes
|
||||||
|
|
||||||
|
|
||||||
|
def segments_in(entities, clip, layers):
|
||||||
|
out = []
|
||||||
|
x1, y1, x2, y2 = clip
|
||||||
|
for layer, sx, sy, ex, ey in entities:
|
||||||
|
if not match_any(layer, layers):
|
||||||
|
continue
|
||||||
|
mx, my = (sx + ex) / 2, (sy + ey) / 2
|
||||||
|
if x1 <= mx <= x2 and y1 <= my <= y2:
|
||||||
|
out.append((sx, sy, ex, ey))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
|
||||||
|
path = Path(args.dxf)
|
||||||
|
try:
|
||||||
|
doc = ezdxf.readfile(path)
|
||||||
|
except ezdxf.DXFError:
|
||||||
|
doc, _ = recover.readfile(path)
|
||||||
|
msp = doc.modelspace()
|
||||||
|
|
||||||
|
title_excludes = [p.strip() for p in args.title_exclude_layers.split(",") if p.strip()]
|
||||||
|
axis_layers = [p.strip() for p in args.axis_layers.split(",") if p.strip()]
|
||||||
|
wall_layers = [p.strip() for p in args.wall_layers.split(",") if p.strip()]
|
||||||
|
|
||||||
|
plan_title = re.compile(args.title_regex)
|
||||||
|
plan_exclude = re.compile(args.title_exclude_regex) if args.title_exclude_regex else None
|
||||||
|
titles, others = [], []
|
||||||
|
lines = [] # (layer, sx, sy, ex, ey) for LINE and polyline edges
|
||||||
|
for entity in msp:
|
||||||
|
kind = entity.dxftype()
|
||||||
|
if kind in {"TEXT", "MTEXT"}:
|
||||||
|
content = entity_text(entity)
|
||||||
|
if not content or len(content) > 40:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
pos = entity.dxf.insert
|
||||||
|
x, y = float(pos.x), float(pos.y)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
height = float(entity.dxf.get("height", 0) or 0)
|
||||||
|
layer = str(entity.dxf.layer)
|
||||||
|
if plan_title.search(content) and not (plan_exclude and plan_exclude.search(content)):
|
||||||
|
if not match_any(layer, title_excludes):
|
||||||
|
titles.append({"name": content, "x": x, "y": y, "h": height, "layer": layer})
|
||||||
|
elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes):
|
||||||
|
others.append({"name": content, "x": x, "y": y, "h": height})
|
||||||
|
elif kind == "LINE":
|
||||||
|
d = entity.dxf
|
||||||
|
lines.append((str(d.layer), float(d.start.x), float(d.start.y), float(d.end.x), float(d.end.y)))
|
||||||
|
elif kind == "LWPOLYLINE":
|
||||||
|
try:
|
||||||
|
pts = [(float(px), float(py)) for px, py in entity.get_points("xy")]
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
layer = str(entity.dxf.layer)
|
||||||
|
for a, b in zip(pts, pts[1:]):
|
||||||
|
lines.append((layer, a[0], a[1], b[0], b[1]))
|
||||||
|
|
||||||
|
if not titles:
|
||||||
|
print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False))
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# Keep, per title name, only instances close to that name's max height
|
||||||
|
# (drops catalog rows and small title-block copies that survive layer excludes).
|
||||||
|
by_name: dict[str, list[dict]] = defaultdict(list)
|
||||||
|
for t in titles:
|
||||||
|
by_name[t["name"]].append(t)
|
||||||
|
filtered = []
|
||||||
|
for name, items in by_name.items():
|
||||||
|
max_h = max(t["h"] for t in items)
|
||||||
|
filtered.extend(t for t in items if t["h"] >= max_h * 0.85)
|
||||||
|
titles = sorted(filtered, key=lambda t: (-t["y"], t["x"]))
|
||||||
|
|
||||||
|
# Sheets stack vertically (column pitch from y gaps) or run in rows
|
||||||
|
# (pitch from x gaps of same-row titles) — support both.
|
||||||
|
ys = sorted({t["y"] for t in titles}, reverse=True)
|
||||||
|
y_gaps = [a - b for a, b in zip(ys, ys[1:]) if 20000 < a - b < 400000]
|
||||||
|
pitch_y = statistics.median(y_gaps) if y_gaps else None
|
||||||
|
xs_rows: dict[int, list[float]] = defaultdict(list)
|
||||||
|
for t in titles:
|
||||||
|
xs_rows[round(t["y"] / 4000)].append(t["x"])
|
||||||
|
x_gaps = []
|
||||||
|
for row in xs_rows.values():
|
||||||
|
row = sorted(row)
|
||||||
|
x_gaps.extend(b - a for a, b in zip(row, row[1:]) if 8000 < b - a < 400000)
|
||||||
|
pitch_x = statistics.median(x_gaps) if x_gaps else None
|
||||||
|
pitch = pitch_y or pitch_x or 98100.0
|
||||||
|
clip_w = (pitch_x * 0.97) if pitch_x else pitch * args.frame_aspect
|
||||||
|
clip_h = (pitch_y * 0.97) if pitch_y else (pitch_x or 98100.0) * 2.2
|
||||||
|
|
||||||
|
used_keys: set[str] = set()
|
||||||
|
floors = []
|
||||||
|
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 t in titles:
|
||||||
|
rough = [t["x"] - clip_w * 0.55, t["y"] - pitch * 0.06, t["x"] + clip_w * 0.55, t["y"] + clip_h]
|
||||||
|
if pitch_x and not pitch_y:
|
||||||
|
# row layout: title x may sit anywhere under its frame; centre on it
|
||||||
|
rough = [t["x"] - clip_w * 0.6, t["y"] - clip_h * 0.04, t["x"] + clip_w * 0.6, t["y"] + clip_h]
|
||||||
|
clip = None
|
||||||
|
for group in refine_groups:
|
||||||
|
found = segments_in(lines, rough, group)
|
||||||
|
if len(found) >= 10:
|
||||||
|
xs = [v for s in found for v in (s[0], s[2])]
|
||||||
|
ys_ = [v for s in found for v in (s[1], s[3])]
|
||||||
|
margin = pitch * 0.06
|
||||||
|
clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin]
|
||||||
|
break
|
||||||
|
if clip is None:
|
||||||
|
clip = rough
|
||||||
|
notes.append(f"{t['name']}: no wall/roof geometry in rough clip; using pitch-based clip")
|
||||||
|
axes = segments_in(lines, clip, axis_layers)
|
||||||
|
min_grid_len = pitch * 0.25
|
||||||
|
vert, horiz = [], []
|
||||||
|
for sx, sy, ex, ey in axes:
|
||||||
|
if abs(ex - sx) < 2.0 and abs(ey - sy) > min_grid_len:
|
||||||
|
vert.append((sx + ex) / 2)
|
||||||
|
elif abs(ey - sy) < 2.0 and abs(ex - sx) > min_grid_len:
|
||||||
|
horiz.append((sy + ey) / 2)
|
||||||
|
floors.append({
|
||||||
|
"key": floor_key_for(t["name"], used_keys),
|
||||||
|
"name": t["name"],
|
||||||
|
"clip": [round(c, 1) for c in clip],
|
||||||
|
"_vx": cluster_positions(vert, args.grid_bin),
|
||||||
|
"_hy": cluster_positions(horiz, args.grid_bin),
|
||||||
|
})
|
||||||
|
|
||||||
|
def ref_rank(f):
|
||||||
|
return (0 if f["key"] == "F1" else 1, -(len(f["_vx"]) + len(f["_hy"])))
|
||||||
|
reference = sorted(floors, key=ref_rank)[0]
|
||||||
|
|
||||||
|
alignment = []
|
||||||
|
for f in floors:
|
||||||
|
if f is reference:
|
||||||
|
f["offset"] = [0.0, 0.0]
|
||||||
|
alignment.append(f"{f['key']}: reference frame")
|
||||||
|
continue
|
||||||
|
dx, vx = vote_translation(reference["_vx"], f["_vx"], args.grid_bin)
|
||||||
|
dy, vy = vote_translation(reference["_hy"], f["_hy"], args.grid_bin)
|
||||||
|
if dx is not None and dy is not None and vx >= 3 and vy >= 3:
|
||||||
|
f["offset"] = [round(dx, 1), round(dy, 1)]
|
||||||
|
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}")
|
||||||
|
else:
|
||||||
|
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']} — verify overlay!"
|
||||||
|
)
|
||||||
|
|
||||||
|
for f in floors:
|
||||||
|
f.pop("_vx"), f.pop("_hy")
|
||||||
|
|
||||||
|
config = {
|
||||||
|
"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": [{k: f[k] for k in ("key", "name", "clip", "offset")} for f in 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"- plan frames: {len(floors)} (sheet pitch ≈ {round(pitch, 1)})",
|
||||||
|
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']}")
|
||||||
|
report.extend(["", "## Alignment", ""])
|
||||||
|
report.extend(f"- {n}" for n in alignment)
|
||||||
|
report.extend(f"- note: {n}" for n in notes)
|
||||||
|
if others:
|
||||||
|
seen = set()
|
||||||
|
report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""])
|
||||||
|
for o in sorted(others, key=lambda o: -o.get("h", 0)):
|
||||||
|
key = o["name"]
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
report.append(f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})")
|
||||||
|
# Storey-elevation suggestions: 标高 texts (e.g. 8.100) inside section/
|
||||||
|
# elevation frames, clustered. Feed floors[].z/height from these.
|
||||||
|
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
|
||||||
|
votes: Counter = Counter()
|
||||||
|
boxes = [(o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
|
||||||
|
for o in others]
|
||||||
|
for entity in msp:
|
||||||
|
if entity.dxftype() != "TEXT":
|
||||||
|
continue
|
||||||
|
content = entity_text(entity)
|
||||||
|
if not content or not elev_re.match(content):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
pos = entity.dxf.insert
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if any(b[0] <= pos.x <= b[2] and b[1] <= pos.y <= b[3] for b in boxes):
|
||||||
|
votes[round(float(content), 3)] += 1
|
||||||
|
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."])
|
||||||
|
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))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
129
scripts/dwg_dump_json.mjs
Normal file
129
scripts/dwg_dump_json.mjs
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* DWG -> JSON entity dump via @mlightcad/libredwg-web (WASM libredwg).
|
||||||
|
*
|
||||||
|
* Fallback converter for environments without native dwg2dxf / ODA File
|
||||||
|
* Converter (e.g. Linux sandboxes). Pair with scripts/dwgjson_to_dxf.py to
|
||||||
|
* rebuild an ezdxf-compatible DXF that the rest of the pipeline consumes.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* npm install @mlightcad/libredwg-web # once, anywhere; pass --module-dir
|
||||||
|
* node dwg_dump_json.mjs <in.dwg> <out.json> [--module-dir <node_modules path>]
|
||||||
|
*
|
||||||
|
* Carries: LINE, LWPOLYLINE, POLYLINE, ARC, CIRCLE, ELLIPSE, SPLINE, TEXT,
|
||||||
|
* MTEXT, INSERT (+ BLOCK definitions, recursively). Skips HATCH/DIMENSION/OLE.
|
||||||
|
*/
|
||||||
|
import { readFileSync, writeFileSync } from 'fs'
|
||||||
|
import { createRequire } from 'module'
|
||||||
|
import { pathToFileURL } from 'url'
|
||||||
|
|
||||||
|
const args = process.argv.slice(2)
|
||||||
|
const positional = args.filter(a => !a.startsWith('--'))
|
||||||
|
const moduleDirFlag = args.indexOf('--module-dir')
|
||||||
|
const moduleDir = moduleDirFlag >= 0 ? args[moduleDirFlag + 1] : null
|
||||||
|
if (positional.length < 2) {
|
||||||
|
console.error('usage: node dwg_dump_json.mjs <in.dwg> <out.json> [--module-dir <dir>]')
|
||||||
|
process.exit(2)
|
||||||
|
}
|
||||||
|
const [inFile, outFile] = positional
|
||||||
|
|
||||||
|
async function loadLib() {
|
||||||
|
const spec = '@mlightcad/libredwg-web'
|
||||||
|
if (moduleDir) {
|
||||||
|
const pkgRoot = `${moduleDir}/${spec}`
|
||||||
|
const mod = await import(pathToFileURL(`${pkgRoot}/dist/libredwg-web.js`))
|
||||||
|
return { mod, wasmDir: `${pkgRoot}/wasm/` }
|
||||||
|
}
|
||||||
|
const mod = await import(spec)
|
||||||
|
const req = createRequire(import.meta.url)
|
||||||
|
const pkgPath = req.resolve(spec)
|
||||||
|
return { mod, wasmDir: pkgPath.replace(/dist\/[^/]+$/, 'wasm/') }
|
||||||
|
}
|
||||||
|
|
||||||
|
const { mod, wasmDir } = await loadLib()
|
||||||
|
const { Dwg_File_Type, LibreDwg } = mod
|
||||||
|
const libredwg = await LibreDwg.create(wasmDir)
|
||||||
|
|
||||||
|
const buf = readFileSync(inFile)
|
||||||
|
const dwg = libredwg.dwg_read_data(
|
||||||
|
buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
|
||||||
|
Dwg_File_Type.DWG
|
||||||
|
)
|
||||||
|
if (!dwg) {
|
||||||
|
console.error('dwg_read_data failed for', inFile)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
const db = libredwg.convert(dwg)
|
||||||
|
|
||||||
|
const KEEP = new Set(['LINE', 'LWPOLYLINE', 'POLYLINE', 'ARC', 'CIRCLE', 'ELLIPSE', 'SPLINE', 'TEXT', 'MTEXT', 'ATTRIB', 'INSERT'])
|
||||||
|
|
||||||
|
function num(v, d = 0) { return Number.isFinite(v) ? v : d }
|
||||||
|
function pt(p) { return p ? [num(p.x), num(p.y)] : [0, 0] }
|
||||||
|
|
||||||
|
function slim(e) {
|
||||||
|
const t = e.type
|
||||||
|
if (!KEEP.has(t)) return null
|
||||||
|
const out = { t, layer: e.layer || '0' }
|
||||||
|
if (t === 'LINE') { out.a = pt(e.startPoint); out.b = pt(e.endPoint) }
|
||||||
|
else if (t === 'LWPOLYLINE' || t === 'POLYLINE') {
|
||||||
|
const vs = (e.vertices || []).map(v => [num(v.x), num(v.y), num(v.bulge)])
|
||||||
|
if (vs.length < 2) return null
|
||||||
|
out.v = vs
|
||||||
|
out.closed = Boolean((num(e.flag) & 1) || e.closed)
|
||||||
|
} else if (t === 'ARC') {
|
||||||
|
out.c = pt(e.center); out.r = num(e.radius)
|
||||||
|
out.sa = num(e.startAngle); out.ea = num(e.endAngle)
|
||||||
|
} else if (t === 'CIRCLE') { out.c = pt(e.center); out.r = num(e.radius) }
|
||||||
|
else if (t === 'ELLIPSE') {
|
||||||
|
out.c = pt(e.center); out.mj = pt(e.majorAxisEndPoint)
|
||||||
|
out.ratio = num(e.axisRatio, 1); out.sa = num(e.startAngle); out.ea = num(e.endAngle, Math.PI * 2)
|
||||||
|
} else if (t === 'SPLINE') {
|
||||||
|
const pts = (e.fitPoints && e.fitPoints.length ? e.fitPoints : e.controlPoints) || []
|
||||||
|
const vs = pts.map(p => [num(p.x), num(p.y)])
|
||||||
|
if (vs.length < 2) return null
|
||||||
|
out.v = vs
|
||||||
|
} else if (t === 'TEXT' || t === 'MTEXT' || t === 'ATTRIB') {
|
||||||
|
// ATTRIB carries axis numbers / coordinate callouts in TArch sets — emit as TEXT.
|
||||||
|
const text = (e.text || e.textValue || e.contents || '').toString()
|
||||||
|
if (!text) return null
|
||||||
|
if (t === 'ATTRIB') out.t = 'TEXT'
|
||||||
|
out.text = text.slice(0, 200)
|
||||||
|
out.p = pt(e.startPoint || e.insertionPoint || e.position)
|
||||||
|
out.h = num(e.textHeight || e.height)
|
||||||
|
} else if (t === 'INSERT') {
|
||||||
|
if (!e.name) return null
|
||||||
|
out.name = e.name
|
||||||
|
out.p = pt(e.insertionPoint)
|
||||||
|
out.sx = num(e.xScale, 1) || 1; out.sy = num(e.yScale, 1) || 1
|
||||||
|
out.rot = num(e.rotation)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const entities = []
|
||||||
|
for (const e of db.entities || []) { const s = slim(e); if (s) entities.push(s) }
|
||||||
|
|
||||||
|
const blocks = {}
|
||||||
|
const inserted = new Set(entities.filter(e => e.t === 'INSERT').map(e => e.name))
|
||||||
|
const records = (db.tables && db.tables.BLOCK_RECORD && db.tables.BLOCK_RECORD.entries) || []
|
||||||
|
// include every non-layout block so nested INSERTs resolve
|
||||||
|
for (const b of records) {
|
||||||
|
const name = b.name || ''
|
||||||
|
if (!name || /^\*(Model|Paper)_Space/i.test(name)) continue
|
||||||
|
const ents = []
|
||||||
|
for (const e of b.entities || []) { const s = slim(e); if (s) ents.push(s) }
|
||||||
|
if (ents.length) blocks[name] = ents
|
||||||
|
for (const e of ents) if (e.t === 'INSERT') inserted.add(e.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
const layers = ((db.tables && db.tables.LAYER && db.tables.LAYER.entries) || []).map(l => ({
|
||||||
|
name: l.name || '0', color: num(l.colorIndex, 7), off: Boolean(l.off), frozen: Boolean(l.frozen)
|
||||||
|
}))
|
||||||
|
|
||||||
|
const header = db.header || {}
|
||||||
|
writeFileSync(outFile, JSON.stringify({
|
||||||
|
source: inFile,
|
||||||
|
insunits: num(header.INSUNITS ?? header.insunits, 0),
|
||||||
|
layers, entities, blocks
|
||||||
|
}))
|
||||||
|
console.log(JSON.stringify({ out: outFile, entities: entities.length, blocks: Object.keys(blocks).length }))
|
||||||
143
scripts/dwgjson_to_dxf.py
Normal file
143
scripts/dwgjson_to_dxf.py
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Rebuild an ezdxf DXF from a dwg_dump_json.mjs entity dump.
|
||||||
|
|
||||||
|
Fallback DWG->DXF path when native dwg2dxf / ODA File Converter is not
|
||||||
|
available. Preserves layers, block definitions, and INSERT transforms so the
|
||||||
|
extraction pipeline (derive_showcase_spec.py block probing included) works
|
||||||
|
unchanged.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 dwgjson_to_dxf.py --json work/dump.json --out work/dxf_raw/file.dxf
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--json", required=True)
|
||||||
|
parser.add_argument("--out", required=True)
|
||||||
|
parser.add_argument("--vendor-dir", default="work/vendor")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def import_ezdxf(vendor_dir: Path):
|
||||||
|
if vendor_dir.exists():
|
||||||
|
sys.path.insert(0, str(vendor_dir.resolve()))
|
||||||
|
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
|
||||||
|
return ezdxf
|
||||||
|
|
||||||
|
|
||||||
|
def add_entity(space, ent: dict) -> None:
|
||||||
|
kind = ent["t"]
|
||||||
|
attribs = {"layer": ent.get("layer", "0")}
|
||||||
|
if kind == "LINE":
|
||||||
|
space.add_line(ent["a"], ent["b"], dxfattribs=attribs)
|
||||||
|
elif kind in {"LWPOLYLINE", "POLYLINE"}:
|
||||||
|
points = [(v[0], v[1], 0.0, 0.0, v[2] if len(v) > 2 else 0.0) for v in ent["v"]]
|
||||||
|
space.add_lwpolyline(points, format="xyseb", close=bool(ent.get("closed")), dxfattribs=attribs)
|
||||||
|
elif kind == "ARC":
|
||||||
|
start = math.degrees(ent["sa"]) if abs(ent["sa"]) <= math.tau + 0.01 else ent["sa"]
|
||||||
|
end = math.degrees(ent["ea"]) if abs(ent["ea"]) <= math.tau + 0.01 else ent["ea"]
|
||||||
|
if ent.get("r", 0) > 0:
|
||||||
|
space.add_arc(ent["c"], ent["r"], start, end, dxfattribs=attribs)
|
||||||
|
elif kind == "CIRCLE":
|
||||||
|
if ent.get("r", 0) > 0:
|
||||||
|
space.add_circle(ent["c"], ent["r"], dxfattribs=attribs)
|
||||||
|
elif kind == "ELLIPSE":
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
elif kind == "SPLINE":
|
||||||
|
space.add_lwpolyline([(v[0], v[1]) for v in ent["v"]], dxfattribs=attribs)
|
||||||
|
elif kind in {"TEXT", "MTEXT"}:
|
||||||
|
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,
|
||||||
|
).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"],
|
||||||
|
dxfattribs={
|
||||||
|
**attribs,
|
||||||
|
"xscale": ent.get("sx", 1.0) or 1.0,
|
||||||
|
"yscale": ent.get("sy", 1.0) or 1.0,
|
||||||
|
"rotation": rotation,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
ezdxf = import_ezdxf(Path(args.vendor_dir))
|
||||||
|
payload = json.loads(Path(args.json).read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
doc = ezdxf.new("R2010", setup=False)
|
||||||
|
doc.header["$INSUNITS"] = int(payload.get("insunits", 4) or 4)
|
||||||
|
for layer in payload.get("layers", []):
|
||||||
|
name = layer.get("name") or "0"
|
||||||
|
if name != "0" and name not in doc.layers:
|
||||||
|
try:
|
||||||
|
doc.layers.add(name, color=max(int(layer.get("color", 7)) or 7, 1))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
block_defs: dict = payload.get("blocks", {})
|
||||||
|
for name in block_defs:
|
||||||
|
if name in doc.blocks:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
doc.blocks.new(name=name)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
for name, ents in block_defs.items():
|
||||||
|
try:
|
||||||
|
block = doc.blocks.get(name)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
for ent in ents:
|
||||||
|
if ent["t"] == "INSERT" and ent.get("name") not in doc.blocks:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
add_entity(block, ent)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
msp = doc.modelspace()
|
||||||
|
added = skipped = 0
|
||||||
|
for ent in payload.get("entities", []):
|
||||||
|
if ent["t"] == "INSERT" and ent.get("name") not in doc.blocks:
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
add_entity(msp, ent)
|
||||||
|
added += 1
|
||||||
|
except Exception:
|
||||||
|
skipped += 1
|
||||||
|
|
||||||
|
out = Path(args.out)
|
||||||
|
out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
doc.saveas(out)
|
||||||
|
print(json.dumps({"out": str(out), "added": added, "skipped": skipped, "blocks": len(block_defs)}))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
268
scripts/site_context_from_dump.py
Normal file
268
scripts/site_context_from_dump.py
Normal file
@@ -0,0 +1,268 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build campus site-context floors from dwg_dump_json.mjs dumps of 总图/定位图.
|
||||||
|
|
||||||
|
Produces a JSON fragment (floors + extra categories) that an assembler merges
|
||||||
|
into a building_spec before spec_to_glb: ground plate from 用地红线, roads
|
||||||
|
(lines + arcs), parking stalls (block-expanded INSERTs), fence walls, street
|
||||||
|
trees as green posts, and simple massings for context buildings drawn only as
|
||||||
|
outlines in the site plan. Buildings that have their own drawing sets should
|
||||||
|
be modeled properly and placed by the site manifest — do NOT fake them here.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 site_context_from_dump.py \
|
||||||
|
--dump dump_zongtu.json --scale 1.0 \
|
||||||
|
--region 349450 664100 349750 664350 \
|
||||||
|
--origin 349505.372 664163.589 \
|
||||||
|
--exclude-quad 349577.156 664230.324 349666.571 664242.204 \
|
||||||
|
349672.128 664200.371 349582.714 664188.492 \
|
||||||
|
--out site_floors.json
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROAD_LAYERS = {"Z5-车行道": 0.30, "Z5-道路中心线": 0.10, "Z6-其他符号": 0.12,
|
||||||
|
"Z2-绿化控制线": 0.08, "Z2-建筑退界线": 0.08, "竖向": 0.08}
|
||||||
|
PARKING_LAYERS = {"Z3-车位": 0.08}
|
||||||
|
FENCE_LAYERS = {"Z3-围墙": 0.15}
|
||||||
|
BOUNDARY_LAYERS = ["Z2-用地红线"]
|
||||||
|
TREE_LAYERS = ["Z4-树层(行道树)", "*树*"]
|
||||||
|
MASSING_LAYERS = ["平面", "屋面", "面积核算", "*建筑轮廓*"]
|
||||||
|
MASSING_HEIGHTS = [("2#", 24.0), ("3#", 8.5), ("辅房", 8.5), ("门卫", 3.5),
|
||||||
|
("停车", 4.0), ("污水", 2.0), ("水池", 2.0), ("消控", 3.5),
|
||||||
|
("连廊", 4.5), ("钢楼梯", 6.5)]
|
||||||
|
MASSING_SKIP = ("出入口",) # gate openings marked as small rects; not volumes
|
||||||
|
LABEL_SKIP = __import__("re").compile(r"^[XxYy]=|^[-+]?\d+([.,]\d+)?$")
|
||||||
|
DEFAULT_MASSING_H = 6.0
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
p = argparse.ArgumentParser(description=__doc__)
|
||||||
|
p.add_argument("--dump", action="append", required=True, help="dump JSON path (repeatable)")
|
||||||
|
p.add_argument("--scale", action="append", required=True, type=float,
|
||||||
|
help="units->meters factor for the matching --dump (1.0 for m, 0.001 for mm)")
|
||||||
|
p.add_argument("--region", nargs=4, type=float, required=True, metavar=("X0", "Y0", "X1", "Y1"),
|
||||||
|
help="surveying-meter window selecting ONE plan copy")
|
||||||
|
p.add_argument("--origin", nargs=2, type=float, required=True,
|
||||||
|
help="campus local origin in surveying meters (e.g. 红线 min corner)")
|
||||||
|
p.add_argument("--exclude-quad", nargs=8, type=float, default=None,
|
||||||
|
help="4 corners (m) of the real-model building; site geometry inside is dropped")
|
||||||
|
p.add_argument("--out", required=True)
|
||||||
|
return p.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def flatten_arc(c, r, sa, ea, scale):
|
||||||
|
if ea < sa:
|
||||||
|
ea += math.tau
|
||||||
|
steps = max(8, min(48, int(abs(ea - sa) * r * scale / 1.5) + 8))
|
||||||
|
return [(c[0] + math.cos(sa + (ea - sa) * i / steps) * r,
|
||||||
|
c[1] + math.sin(sa + (ea - sa) * i / steps) * r) for i in range(steps + 1)]
|
||||||
|
|
||||||
|
|
||||||
|
def in_quad(pt, quad):
|
||||||
|
if not quad:
|
||||||
|
return False
|
||||||
|
sign = None
|
||||||
|
for i in range(4):
|
||||||
|
ax, ay = quad[i]
|
||||||
|
bx, by = quad[(i + 1) % 4]
|
||||||
|
cross = (bx - ax) * (pt[1] - ay) - (by - ay) * (pt[0] - ax)
|
||||||
|
if abs(cross) < 1e-9:
|
||||||
|
continue
|
||||||
|
if sign is None:
|
||||||
|
sign = cross > 0
|
||||||
|
elif (cross > 0) != sign:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def match(layer: str, patterns) -> bool:
|
||||||
|
import fnmatch
|
||||||
|
return any(fnmatch.fnmatch(layer, p) for p in patterns)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
if len(args.dump) != len(args.scale):
|
||||||
|
raise SystemExit("--dump and --scale must pair up")
|
||||||
|
x0, y0, x1, y1 = args.region
|
||||||
|
ox, oy = args.origin
|
||||||
|
quad = None
|
||||||
|
if args.exclude_quad:
|
||||||
|
q = args.exclude_quad
|
||||||
|
quad = [(q[0], q[1]), (q[2], q[3]), (q[4], q[5]), (q[6], q[7])]
|
||||||
|
|
||||||
|
def local(p):
|
||||||
|
return [round(p[0] - ox, 6), round(p[1] - oy, 6)]
|
||||||
|
|
||||||
|
segs = {"ROADS": {}, "FENCE": {}}
|
||||||
|
trees = []
|
||||||
|
boundary_polys = []
|
||||||
|
massings = []
|
||||||
|
labels = []
|
||||||
|
|
||||||
|
def add(floor, cat, a, b, width, layer):
|
||||||
|
if math.hypot(b[0] - a[0], b[1] - a[1]) < 0.15:
|
||||||
|
return
|
||||||
|
segs[floor].setdefault(cat, []).append(
|
||||||
|
{"start": local(a), "end": local(b), "width": width, "layer": layer, "source_type": "SITE"})
|
||||||
|
|
||||||
|
for dump_path, scale in zip(args.dump, args.scale):
|
||||||
|
d = json.loads(Path(dump_path).read_text(encoding="utf-8"))
|
||||||
|
blocks = d.get("blocks", {})
|
||||||
|
|
||||||
|
def expand_insert(e):
|
||||||
|
"""Yield (type, data) prims of a block INSERT transformed to drawing units."""
|
||||||
|
name = e.get("name")
|
||||||
|
px, py = e["p"]
|
||||||
|
sx, sy = e.get("sx", 1) or 1, e.get("sy", 1) or 1
|
||||||
|
rot = e.get("rot", 0.0)
|
||||||
|
rot = rot if abs(rot) <= math.tau + 0.01 else math.radians(rot)
|
||||||
|
cr, srr = math.cos(rot), math.sin(rot)
|
||||||
|
|
||||||
|
def tf(pt):
|
||||||
|
tx, ty = pt[0] * sx, pt[1] * sy
|
||||||
|
return (px + tx * cr - ty * srr, py + tx * srr + ty * cr)
|
||||||
|
for be in blocks.get(name, []):
|
||||||
|
if be["t"] == "LINE":
|
||||||
|
yield "seg", (tf(be["a"]), tf(be["b"]))
|
||||||
|
elif be["t"] in ("LWPOLYLINE", "POLYLINE"):
|
||||||
|
pts = [tf((v[0], v[1])) for v in be["v"]]
|
||||||
|
for a, b in zip(pts, pts[1:]):
|
||||||
|
yield "seg", (a, b)
|
||||||
|
elif be["t"] == "CIRCLE":
|
||||||
|
yield "circle", (tf(be["c"]), be["r"] * max(abs(sx), abs(sy)))
|
||||||
|
|
||||||
|
for e in d.get("entities", []):
|
||||||
|
layer = e.get("layer", "")
|
||||||
|
pts = []
|
||||||
|
if e["t"] == "LINE":
|
||||||
|
pts = [tuple(e["a"]), tuple(e["b"])]
|
||||||
|
elif e["t"] in ("LWPOLYLINE", "POLYLINE"):
|
||||||
|
pts = [(v[0], v[1]) for v in e["v"]]
|
||||||
|
if e.get("closed") and len(pts) > 2:
|
||||||
|
pts = pts + [pts[0]]
|
||||||
|
elif e["t"] == "ARC":
|
||||||
|
pts = flatten_arc(e["c"], e["r"], e["sa"], e["ea"], scale)
|
||||||
|
elif e["t"] in ("TEXT", "MTEXT"):
|
||||||
|
tx = (e.get("text") or "").strip()
|
||||||
|
p = [v * scale for v in e.get("p", (0, 0))]
|
||||||
|
if tx and len(tx) <= 12 and x0 <= p[0] <= x1 and y0 <= p[1] <= y1:
|
||||||
|
labels.append((tx, p))
|
||||||
|
continue
|
||||||
|
elif e["t"] == "INSERT":
|
||||||
|
p = [v * scale for v in e.get("p", (0, 0))]
|
||||||
|
if not (x0 <= p[0] <= x1 and y0 <= p[1] <= y1):
|
||||||
|
continue
|
||||||
|
if match(layer, TREE_LAYERS):
|
||||||
|
if not in_quad(p, quad):
|
||||||
|
trees.append(p)
|
||||||
|
elif layer in PARKING_LAYERS:
|
||||||
|
for kind, data in expand_insert(e):
|
||||||
|
if kind != "seg":
|
||||||
|
continue
|
||||||
|
a = (data[0][0] * scale, data[0][1] * scale)
|
||||||
|
b = (data[1][0] * scale, data[1][1] * scale)
|
||||||
|
m = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
|
||||||
|
if x0 <= m[0] <= x1 and y0 <= m[1] <= y1 and not in_quad(m, quad):
|
||||||
|
add("ROADS", "detail_lines", a, b, PARKING_LAYERS[layer], layer)
|
||||||
|
continue
|
||||||
|
if len(pts) < 2:
|
||||||
|
continue
|
||||||
|
mpts = [(p[0] * scale, p[1] * scale) for p in pts]
|
||||||
|
mx = sum(p[0] for p in mpts) / len(mpts)
|
||||||
|
my = sum(p[1] for p in mpts) / len(mpts)
|
||||||
|
if not (x0 <= mx <= x1 and y0 <= my <= y1):
|
||||||
|
continue
|
||||||
|
if layer in BOUNDARY_LAYERS or match(layer, BOUNDARY_LAYERS):
|
||||||
|
boundary_polys.append([local(p) for p in mpts])
|
||||||
|
for a, b in zip(mpts, mpts[1:]):
|
||||||
|
add("ROADS", "floor_lines", a, b, 0.20, layer)
|
||||||
|
elif layer in ROAD_LAYERS:
|
||||||
|
if in_quad((mx, my), quad):
|
||||||
|
continue
|
||||||
|
for a, b in zip(mpts, mpts[1:]):
|
||||||
|
cat = "grid" if "中心线" in layer or "Z2-" in layer or layer == "竖向" else "detail_lines"
|
||||||
|
add("ROADS", cat, a, b, ROAD_LAYERS[layer], layer)
|
||||||
|
elif layer in PARKING_LAYERS:
|
||||||
|
if not in_quad((mx, my), quad):
|
||||||
|
for a, b in zip(mpts, mpts[1:]):
|
||||||
|
add("ROADS", "detail_lines", a, b, PARKING_LAYERS[layer], layer)
|
||||||
|
elif layer in FENCE_LAYERS:
|
||||||
|
for a, b in zip(mpts, mpts[1:]):
|
||||||
|
add("FENCE", "railings", a, b, FENCE_LAYERS[layer], layer)
|
||||||
|
elif match(layer, MASSING_LAYERS):
|
||||||
|
xs = [p[0] for p in mpts]
|
||||||
|
ys = [p[1] for p in mpts]
|
||||||
|
w, h = max(xs) - min(xs), max(ys) - min(ys)
|
||||||
|
if (len(mpts) >= 4 and w >= 3.0 and h >= 3.0 and
|
||||||
|
max(w, h) / max(min(w, h), 0.1) <= 8.0 and not in_quad((mx, my), quad)):
|
||||||
|
massings.append({"pts": [local(p) for p in mpts], "c": (mx, my), "w": w, "h": h})
|
||||||
|
|
||||||
|
floors = {}
|
||||||
|
if boundary_polys:
|
||||||
|
biggest = max(boundary_polys, key=lambda poly: (max(p[0] for p in poly) - min(p[0] for p in poly)) *
|
||||||
|
(max(p[1] for p in poly) - min(p[1] for p in poly)))
|
||||||
|
floors["SITE"] = {"name": "场地地面", "z": -0.45, "height": 0.45,
|
||||||
|
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
|
||||||
|
"segments": {}, "footprint": {"source": "用地红线", "polygons": [biggest]}}
|
||||||
|
floors["ROADS"] = {"name": "道路/车位", "z": 0.02, "height": 0.05,
|
||||||
|
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
|
||||||
|
"segments": segs["ROADS"]}
|
||||||
|
if segs["FENCE"]:
|
||||||
|
floors["FENCE"] = {"name": "围墙", "z": 0.0, "height": 1.8,
|
||||||
|
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
|
||||||
|
"segments": segs["FENCE"]}
|
||||||
|
if trees:
|
||||||
|
tree_segs = []
|
||||||
|
for p in trees:
|
||||||
|
lp = local(p)
|
||||||
|
tree_segs.append({"start": [lp[0] - 0.3, lp[1]], "end": [lp[0] + 0.3, lp[1]],
|
||||||
|
"width": 2.4, "layer": "行道树", "source_type": "TREE"})
|
||||||
|
floors["TREES"] = {"name": "行道树", "z": 0.0, "height": 3.5,
|
||||||
|
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
|
||||||
|
"segments": {"trees": tree_segs}}
|
||||||
|
|
||||||
|
# de-duplicate massings (copies drawn twice) and name them by nearest label
|
||||||
|
kept = []
|
||||||
|
for m in sorted(massings, key=lambda m: -(m["w"] * m["h"])):
|
||||||
|
if any(abs(m["c"][0] - k["c"][0]) < 2 and abs(m["c"][1] - k["c"][1]) < 2 and
|
||||||
|
abs(m["w"] - k["w"]) < 2 and abs(m["h"] - k["h"]) < 2 for k in kept):
|
||||||
|
continue
|
||||||
|
kept.append(m)
|
||||||
|
for idx, m in enumerate(kept, start=1):
|
||||||
|
name, dist = f"CTX{idx}", 1e18
|
||||||
|
for tx, p in labels:
|
||||||
|
if LABEL_SKIP.search(tx):
|
||||||
|
continue
|
||||||
|
dd = math.hypot(p[0] - m["c"][0], p[1] - m["c"][1])
|
||||||
|
if dd < dist and dd < 60:
|
||||||
|
name, dist = tx, dd
|
||||||
|
if any(key in name for key in MASSING_SKIP):
|
||||||
|
continue
|
||||||
|
height = next((hh for key, hh in MASSING_HEIGHTS if key in name), DEFAULT_MASSING_H)
|
||||||
|
wsegs = [{"start": a, "end": b, "width": 0.25, "layer": "massing", "source_type": "SITE"}
|
||||||
|
for a, b in zip(m["pts"], m["pts"][1:])]
|
||||||
|
if m["pts"][0] != m["pts"][-1]:
|
||||||
|
wsegs.append({"start": m["pts"][-1], "end": m["pts"][0], "width": 0.25,
|
||||||
|
"layer": "massing", "source_type": "SITE"})
|
||||||
|
floors[f"CTX{idx}"] = {"name": f"体量-{name}", "z": 0.0, "height": height,
|
||||||
|
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site",
|
||||||
|
"segments": {"walls": wsegs},
|
||||||
|
"footprint": {"source": "site_outline", "polygons": [m["pts"]]}}
|
||||||
|
|
||||||
|
out = {"floors": floors,
|
||||||
|
"categories": {"trees": {"label": "行道树", "color": "#3e7d4f"}}}
|
||||||
|
Path(args.out).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||||
|
print(json.dumps({"out": args.out,
|
||||||
|
"floors": {k: {c: len(s) for c, s in v.get("segments", {}).items()} for k, v in floors.items()},
|
||||||
|
"trees": len(trees), "massings": len(kept)}, ensure_ascii=False))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -8,7 +8,7 @@ a Blender install. The Web viewer recolours meshes by category from
|
|||||||
model_metadata.json, so only correct node names + geometry are required.
|
model_metadata.json, so only correct node names + geometry are required.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import argparse, json, math
|
import argparse, json, math, sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import trimesh
|
import trimesh
|
||||||
@@ -66,6 +66,9 @@ def mesh_from_segments(segments, z0, z1):
|
|||||||
if not V: return None
|
if not V: return None
|
||||||
return trimesh.Trimesh(vertices=np.vstack(V), faces=np.vstack(F), process=False)
|
return trimesh.Trimesh(vertices=np.vstack(V), faces=np.vstack(F), process=False)
|
||||||
|
|
||||||
|
_POLY_FAILS = {"n": 0}
|
||||||
|
|
||||||
|
|
||||||
def mesh_from_polygons(polygons, z0, z1):
|
def mesh_from_polygons(polygons, z0, z1):
|
||||||
parts=[]
|
parts=[]
|
||||||
for coords in polygons:
|
for coords in polygons:
|
||||||
@@ -79,7 +82,13 @@ def mesh_from_polygons(polygons, z0, z1):
|
|||||||
m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4))
|
m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4))
|
||||||
m.apply_translation((0,0,z0))
|
m.apply_translation((0,0,z0))
|
||||||
parts.append(m)
|
parts.append(m)
|
||||||
except Exception:
|
except Exception as exc:
|
||||||
|
# Silent drops here erase slabs/caps/roofs wholesale (e.g. trimesh
|
||||||
|
# cannot triangulate without mapbox_earcut/manifold3d installed).
|
||||||
|
_POLY_FAILS["n"] += 1
|
||||||
|
if _POLY_FAILS["n"] <= 3:
|
||||||
|
print(f"WARNING mesh_from_polygons failed ({exc}); slabs/caps/roofs may be "
|
||||||
|
"missing - pip install mapbox_earcut", file=sys.stderr)
|
||||||
continue
|
continue
|
||||||
if not parts: return None
|
if not parts: return None
|
||||||
return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0]
|
return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0]
|
||||||
@@ -126,6 +135,111 @@ def merge_collinear(segs, angle_tol_deg=6.0, offset_tol=0.30, gap_tol=3.6):
|
|||||||
out.append({"start":[p0[0],p0[1]],"end":[p1[0],p1[1]],"width":w,"layer":layer,"source_type":"merged"})
|
out.append({"start":[p0[0],p0[1]],"end":[p1[0],p1[1]],"width":w,"layer":layer,"source_type":"merged"})
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
def extend_shared_wall_ends(segments, tol=1e-3):
|
||||||
|
"""Extend wall ends that meet another wall's endpoint by half their own width.
|
||||||
|
|
||||||
|
Flat-capped rectangles stop exactly at the endpoint, so an L-corner leaves
|
||||||
|
a w/2 x w/2 notch that even a union keeps open. Extending only SHARED ends
|
||||||
|
makes the corner rectangles overlap (union -> clean square corner) while
|
||||||
|
free ends (door/window openings) stay flat. T-joints need nothing: the
|
||||||
|
ending wall already reaches the crossing wall's centerline.
|
||||||
|
"""
|
||||||
|
from collections import Counter
|
||||||
|
pts=[]
|
||||||
|
for s in segments:
|
||||||
|
pts.append((float(s["start"][0]), float(s["start"][1])))
|
||||||
|
pts.append((float(s["end"][0]), float(s["end"][1])))
|
||||||
|
scale=1.0/max(tol,1e-9)
|
||||||
|
buckets=Counter((round(x*scale), round(y*scale)) for x,y in pts)
|
||||||
|
def shared(p):
|
||||||
|
cx,cy=round(p[0]*scale), round(p[1]*scale)
|
||||||
|
return sum(buckets.get((gx,gy),0) for gx in (cx-1,cx,cx+1) for gy in (cy-1,cy,cy+1))>=2
|
||||||
|
out=[]
|
||||||
|
for s in segments:
|
||||||
|
a=[float(s["start"][0]), float(s["start"][1])]
|
||||||
|
b=[float(s["end"][0]), float(s["end"][1])]
|
||||||
|
dx,dy=b[0]-a[0],b[1]-a[1]; L=math.hypot(dx,dy)
|
||||||
|
if L<1e-7:
|
||||||
|
out.append(s); continue
|
||||||
|
ux,uy=dx/L,dy/L
|
||||||
|
half=max(float(s.get("width",0.1)),0.005)/2.0
|
||||||
|
item=dict(s)
|
||||||
|
if shared((a[0],a[1])): a=[a[0]-ux*half, a[1]-uy*half]
|
||||||
|
if shared((b[0],b[1])): b=[b[0]+ux*half, b[1]+uy*half]
|
||||||
|
item["start"]=a; item["end"]=b
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def merged_wall_polygons(segments):
|
||||||
|
"""Union per-segment wall rectangles into continuous solids (shapely).
|
||||||
|
|
||||||
|
Shared endpoints are pre-extended (see extend_shared_wall_ends), then each
|
||||||
|
segment becomes a flat-capped rectangle (LineString.buffer, cap_style=2,
|
||||||
|
half its own width) and unary_union removes corner seams and z-fighting at
|
||||||
|
junctions. Returns shapely Polygons (holes preserved for courtyard walls).
|
||||||
|
Enabled via config {"merge_wall_solids": true}.
|
||||||
|
"""
|
||||||
|
from shapely.geometry import LineString
|
||||||
|
from shapely.ops import unary_union
|
||||||
|
rects=[]
|
||||||
|
for s in extend_shared_wall_ends(segments):
|
||||||
|
a=s["start"]; b=s["end"]
|
||||||
|
if math.hypot(b[0]-a[0], b[1]-a[1])<1e-7: continue
|
||||||
|
w=max(float(s.get("width",0.1)), 0.005)
|
||||||
|
rects.append(LineString([tuple(a), tuple(b)]).buffer(w/2.0, cap_style=2))
|
||||||
|
if not rects: return []
|
||||||
|
union=unary_union(rects)
|
||||||
|
geoms=[union] if union.geom_type=="Polygon" else list(getattr(union,"geoms",[]))
|
||||||
|
# simplify(0) drops the collinear vertices GEOS noding leaves on straight edges
|
||||||
|
return [g.simplify(0) for g in geoms if g.geom_type=="Polygon" and g.area>1e-6]
|
||||||
|
|
||||||
|
def mesh_from_shapely(polys, z0, z1):
|
||||||
|
"""Extrude shapely Polygons directly (keeps interior holes, unlike mesh_from_polygons)."""
|
||||||
|
parts=[]
|
||||||
|
for poly in polys:
|
||||||
|
try:
|
||||||
|
m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4))
|
||||||
|
m.apply_translation((0,0,z0))
|
||||||
|
parts.append(m)
|
||||||
|
except Exception as exc:
|
||||||
|
_POLY_FAILS["n"] += 1
|
||||||
|
if _POLY_FAILS["n"] <= 3:
|
||||||
|
print(f"WARNING mesh_from_polygons failed ({exc}); merged walls may be "
|
||||||
|
"missing - pip install mapbox_earcut", file=sys.stderr)
|
||||||
|
continue
|
||||||
|
if not parts: return None
|
||||||
|
return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0]
|
||||||
|
|
||||||
|
def glazing_mullion_segments(bands, z0, z1, panel_w=1.5, profile=0.06, depth=0.10):
|
||||||
|
"""Curtain-wall panel grid over merged glazing bands.
|
||||||
|
|
||||||
|
Emits pseudo wall segments (thin box profiles, walls material via the
|
||||||
|
<floor>__walls node): vertical mullions evenly spaced ~panel_w along each
|
||||||
|
band (posts at both ends included) plus a horizontal transom at the band's
|
||||||
|
bottom and top floor lines (carrying _z0/_z1). The glass pane itself stays.
|
||||||
|
Config {"glazing_mullions": true}, pitch {"glazing_panel_w": 1.5}.
|
||||||
|
"""
|
||||||
|
out=[]
|
||||||
|
for s in bands:
|
||||||
|
a=s["start"]; b=s["end"]
|
||||||
|
dx,dy=b[0]-a[0],b[1]-a[1]; L=math.hypot(dx,dy)
|
||||||
|
if L<max(profile*2, 0.3): continue
|
||||||
|
ux,uy=dx/L,dy/L
|
||||||
|
n=max(1, round(L/max(panel_w, 0.2)))
|
||||||
|
step=L/n
|
||||||
|
for i in range(n+1):
|
||||||
|
t=i*step
|
||||||
|
cx,cy=a[0]+ux*t, a[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":s.get("layer",""), "source_type":"mullion"})
|
||||||
|
th=0.08
|
||||||
|
for tz0,tz1 in ((z0, z0+th), (z1-th, z1)):
|
||||||
|
out.append({"start":[float(a[0]),float(a[1])], "end":[float(b[0]),float(b[1])],
|
||||||
|
"width":depth, "layer":s.get("layer",""), "source_type":"transom",
|
||||||
|
"_z0":tz0, "_z1":tz1})
|
||||||
|
return out
|
||||||
|
|
||||||
def _shapely_union(polys):
|
def _shapely_union(polys):
|
||||||
from shapely.geometry import Polygon
|
from shapely.geometry import Polygon
|
||||||
from shapely.ops import unary_union
|
from shapely.ops import unary_union
|
||||||
@@ -157,6 +271,10 @@ def setback_cap_polys(spec, fk, fl, own_polys):
|
|||||||
if abs(float(ot.get("z",0.0))-ftop)>0.8: continue
|
if abs(float(ot.get("z",0.0))-ftop)>0.8: continue
|
||||||
upper.extend(ot.get("footprint",{}).get("polygons",[]))
|
upper.extend(ot.get("footprint",{}).get("polygons",[]))
|
||||||
own_u=_shapely_union(own_polys)
|
own_u=_shapely_union(own_polys)
|
||||||
|
cfg=spec.get("source",{}).get("config",{})
|
||||||
|
# 1.3 suits colonnade buildings (A208); ordinary facades want ~0.1 or the
|
||||||
|
# cap ring reads as a slab overhanging every floor. Config: cap_buffer.
|
||||||
|
buf=float(cfg.get("cap_buffer",1.3))
|
||||||
if not upper:
|
if not upper:
|
||||||
# top of a basement stack -> cap the WHOLE footprint (ground / podium deck over parking)
|
# top of a basement stack -> cap the WHOLE footprint (ground / podium deck over parking)
|
||||||
if grp=="BASE" and own_u is not None:
|
if grp=="BASE" and own_u is not None:
|
||||||
@@ -165,8 +283,7 @@ def setback_cap_polys(spec, fk, fl, own_polys):
|
|||||||
up_u=_shapely_union(upper)
|
up_u=_shapely_union(upper)
|
||||||
if own_u is None or up_u is None: return []
|
if own_u is None or up_u is None: return []
|
||||||
try:
|
try:
|
||||||
# buffer own footprint outward so the cap also covers perimeter colonnade columns
|
ring=own_u.buffer(buf).difference(up_u.buffer(0.05))
|
||||||
ring=own_u.buffer(1.3).difference(up_u.buffer(0.05))
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return []
|
return []
|
||||||
return _shapely_to_polys(ring, min_area=3.0)
|
return _shapely_to_polys(ring, min_area=3.0)
|
||||||
@@ -321,7 +438,10 @@ def build_scene(spec, categories):
|
|||||||
cap_polys=setback_cap_polys(spec, fk, fl, polys)
|
cap_polys=setback_cap_polys(spec, fk, fl, polys)
|
||||||
if cap_polys:
|
if cap_polys:
|
||||||
parts.append(mesh_from_polygons(cap_polys, z+h-slab_th, z+h))
|
parts.append(mesh_from_polygons(cap_polys, z+h-slab_th, z+h))
|
||||||
else:
|
elif cfg.get("slab_bounds_fallback", True):
|
||||||
|
# Rectangular fallback can fake a full-cover plate on floors
|
||||||
|
# like parapet-only roof plans; disable via config
|
||||||
|
# {"slab_bounds_fallback": false} when footprints are trusted.
|
||||||
b=fl["bounds"]; mg=1.2
|
b=fl["bounds"]; mg=1.2
|
||||||
parts.append(mesh_from_polygons(
|
parts.append(mesh_from_polygons(
|
||||||
[[[b[0]-mg,b[1]-mg],[b[2]+mg,b[1]-mg],[b[2]+mg,b[3]+mg],[b[0]-mg,b[3]+mg]]],
|
[[[b[0]-mg,b[1]-mg],[b[2]+mg,b[1]-mg],[b[2]+mg,b[3]+mg],[b[0]-mg,b[3]+mg]]],
|
||||||
@@ -330,6 +450,13 @@ def build_scene(spec, categories):
|
|||||||
if parts:
|
if parts:
|
||||||
add(f"{fk}__slab", parts[0] if len(parts)==1 else trimesh.util.concatenate(parts), "slab")
|
add(f"{fk}__slab", parts[0] if len(parts)==1 else trimesh.util.concatenate(parts), "slab")
|
||||||
segs=fl.get("segments",{})
|
segs=fl.get("segments",{})
|
||||||
|
mullion_mesh=None
|
||||||
|
if cfg.get("glazing_mullions", False) and segs.get("glazing") and (want is None or "walls" in want):
|
||||||
|
gz0,gz1=z_window("glazing",z,h,fk,fl)
|
||||||
|
mullion_mesh=mesh_from_segments(
|
||||||
|
glazing_mullion_segments(merge_collinear(segs["glazing"]), gz0, gz1,
|
||||||
|
panel_w=float(cfg.get("glazing_panel_w",1.5))),
|
||||||
|
gz0, gz1)
|
||||||
present=[c for c in CATEGORY_DRAW_ORDER if segs.get(c)]
|
present=[c for c in CATEGORY_DRAW_ORDER if segs.get(c)]
|
||||||
extra=sorted(c for c in segs if c not in CATEGORY_DRAW_ORDER and segs.get(c))
|
extra=sorted(c for c in segs if c not in CATEGORY_DRAW_ORDER and segs.get(c))
|
||||||
for cat in present+extra:
|
for cat in present+extra:
|
||||||
@@ -340,7 +467,22 @@ def build_scene(spec, categories):
|
|||||||
seglist=adjust_columns(seglist, fk, fl, spec, cfg, roofs)
|
seglist=adjust_columns(seglist, fk, fl, spec, cfg, roofs)
|
||||||
if cat=="glazing":
|
if cat=="glazing":
|
||||||
seglist=merge_collinear(seglist)
|
seglist=merge_collinear(seglist)
|
||||||
|
if cat=="walls":
|
||||||
|
wall_mesh=None
|
||||||
|
if cfg.get("merge_wall_solids", False):
|
||||||
|
wall_mesh=mesh_from_shapely(merged_wall_polygons(seglist), z0, z1)
|
||||||
|
if wall_mesh is None:
|
||||||
|
wall_mesh=mesh_from_segments(seglist, z0, z1)
|
||||||
|
if mullion_mesh is not None:
|
||||||
|
parts=[p for p in (wall_mesh, mullion_mesh) if p is not None]
|
||||||
|
wall_mesh=trimesh.util.concatenate(parts) if len(parts)>1 else (parts[0] if parts else None)
|
||||||
|
mullion_mesh=None
|
||||||
|
add(f"{fk}__walls", wall_mesh, "walls")
|
||||||
|
continue
|
||||||
add(f"{fk}__{cat}", mesh_from_segments(seglist, z0, z1), cat)
|
add(f"{fk}__{cat}", mesh_from_segments(seglist, z0, z1), cat)
|
||||||
|
if mullion_mesh is not None:
|
||||||
|
# glazing-only floor: the panel grid still needs a walls node
|
||||||
|
add(f"{fk}__walls", mullion_mesh, "walls")
|
||||||
# generated roofs
|
# generated roofs
|
||||||
if want is None or "roof" in want:
|
if want is None or "roof" in want:
|
||||||
for r in roof_specs(spec):
|
for r in roof_specs(spec):
|
||||||
|
|||||||
251
scripts/write_offline_viewer.py
Normal file
251
scripts/write_offline_viewer.py
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Emit a fully-offline single-file HTML viewer for a building/campus GLB.
|
||||||
|
|
||||||
|
Use when the deliverable must open by double-click with NO server and NO
|
||||||
|
network (mainland-China CDNs are unreliable; jsdelivr-importing viewers hang
|
||||||
|
on the loading screen). Everything is inlined: three r147 UMD + OrbitControls
|
||||||
|
+ GLTFLoader + RoomEnvironment + pako, plus the GLB itself gzip-compressed
|
||||||
|
(browser-side pako inflate; ~5x smaller than raw base64 embedding).
|
||||||
|
|
||||||
|
Features: ACES tone mapping, RoomEnvironment IBL, PCF soft shadows + ground
|
||||||
|
shadow catcher, physical-glass glazing, instanced low-poly street trees (from
|
||||||
|
a TREES floor), grouped floor toggles (SITE/CTX* -> 场地, leading-digit keys ->
|
||||||
|
N#, rest -> 主体), category toggles, click-to-inspect, on-screen error
|
||||||
|
reporting (never a silent spinner).
|
||||||
|
|
||||||
|
The official template (assets/web-showcase-template) remains the primary
|
||||||
|
delivery for served deployments; this is the share-by-file variant.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 write_offline_viewer.py --spec building_spec.json --glb model.glb \
|
||||||
|
--out viewer.html [--title 项目名] [--libs-dir <skill>/assets/offline-viewer-libs]
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import gzip
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
p = argparse.ArgumentParser(description=__doc__)
|
||||||
|
p.add_argument("--spec", required=True)
|
||||||
|
p.add_argument("--glb", required=True)
|
||||||
|
p.add_argument("--out", required=True)
|
||||||
|
p.add_argument("--title", default=None)
|
||||||
|
p.add_argument("--subtitle", default="离线单文件查看器")
|
||||||
|
p.add_argument("--libs-dir", default=str(SKILL_ROOT / "assets" / "offline-viewer-libs"))
|
||||||
|
return p.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def group_of(key: str) -> str:
|
||||||
|
if key in ("SITE", "ROADS", "FENCE", "TREES") or key.startswith("CTX"):
|
||||||
|
return "场地"
|
||||||
|
if key[:1].isdigit():
|
||||||
|
return key[0] + "#"
|
||||||
|
return "主体"
|
||||||
|
|
||||||
|
|
||||||
|
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>'; };
|
||||||
|
window.addEventListener('error', e => fail(e.message));
|
||||||
|
window.addEventListener('unhandledrejection', e => fail(e.reason && e.reason.message || e.reason));
|
||||||
|
try {
|
||||||
|
const GROUPS = __GROUPS__, CATS = __CATS__, TREES = __TREES__;
|
||||||
|
const renderer = new THREE.WebGLRenderer({antialias:true});
|
||||||
|
renderer.setSize(innerWidth,innerHeight); renderer.setPixelRatio(Math.min(devicePixelRatio,2));
|
||||||
|
renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
|
||||||
|
renderer.outputEncoding = THREE.sRGBEncoding;
|
||||||
|
renderer.physicallyCorrectLights = true;
|
||||||
|
renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
||||||
|
document.body.appendChild(renderer.domElement);
|
||||||
|
const scene = new THREE.Scene();
|
||||||
|
scene.background = new THREE.Color(0x23272d);
|
||||||
|
scene.fog = new THREE.Fog(0x23272d, 500, 1400);
|
||||||
|
const pmrem = new THREE.PMREMGenerator(renderer);
|
||||||
|
scene.environment = pmrem.fromScene(new THREE.RoomEnvironment(), 0.04).texture;
|
||||||
|
const cam = new THREE.PerspectiveCamera(48, innerWidth/innerHeight, 0.5, 4000);
|
||||||
|
const controls = new THREE.OrbitControls(cam, renderer.domElement); controls.enableDamping = true;
|
||||||
|
const sun = new THREE.DirectionalLight(0xfff3e0, 3.2);
|
||||||
|
sun.position.set(-120, 180, 140); sun.castShadow = true;
|
||||||
|
sun.shadow.mapSize.set(2048,2048); sun.shadow.bias = -0.0004;
|
||||||
|
scene.add(sun); scene.add(new THREE.AmbientLight(0xdfe8ff, 0.5));
|
||||||
|
$load.textContent = '正在解压模型…';
|
||||||
|
await new Promise(r => setTimeout(r, 30));
|
||||||
|
const bin = atob(GLB_B64); const gz = new Uint8Array(bin.length);
|
||||||
|
for (let i=0;i<bin.length;i++) gz[i]=bin.charCodeAt(i);
|
||||||
|
const raw = pako.inflate(gz);
|
||||||
|
const buf = raw.buffer.slice(raw.byteOffset, raw.byteOffset+raw.byteLength);
|
||||||
|
$load.textContent = '正在解析场景…';
|
||||||
|
new THREE.GLTFLoader().parse(buf, '', g => {
|
||||||
|
$load.remove();
|
||||||
|
const root = g.scene; scene.add(root);
|
||||||
|
const bb = new THREE.Box3().setFromObject(root);
|
||||||
|
const c = bb.getCenter(new THREE.Vector3()), sz = bb.getSize(new THREE.Vector3());
|
||||||
|
const radius = Math.max(sz.x, sz.z, 20) * 0.75;
|
||||||
|
sun.target.position.copy(c); scene.add(sun.target);
|
||||||
|
const sc = sun.shadow.camera;
|
||||||
|
sc.left=-radius; sc.right=radius; sc.top=radius; sc.bottom=-radius; sc.near=5; sc.far=radius*6;
|
||||||
|
sc.updateProjectionMatrix();
|
||||||
|
controls.target.copy(c);
|
||||||
|
cam.position.set(c.x + sz.x*0.55, c.y + Math.max(sz.x,sz.z)*0.5, c.z + sz.z*1.25);
|
||||||
|
const ground = new THREE.Mesh(new THREE.PlaneGeometry(radius*8, radius*8), new THREE.ShadowMaterial({opacity:0.35}));
|
||||||
|
ground.rotation.x = -Math.PI/2; ground.position.set(c.x, -0.02, c.z); ground.receiveShadow = true; scene.add(ground);
|
||||||
|
const nodes = [];
|
||||||
|
root.traverse(o => {
|
||||||
|
if (!o.isMesh) return;
|
||||||
|
nodes.push(o);
|
||||||
|
const parts = (o.name||'').split('__'), fk = parts[0], cat = parts[1];
|
||||||
|
if (cat === 'glazing') {
|
||||||
|
o.material = new THREE.MeshPhysicalMaterial({color:0x9fd4e8, metalness:0, roughness:0.18,
|
||||||
|
transmission:0.72, ior:1.5, thickness:0.3, transparent:true, depthWrite:false, side:THREE.DoubleSide});
|
||||||
|
o.material.envMapIntensity = 1.2;
|
||||||
|
} else if (['walls','columns','roof','slab','railings'].indexOf(cat)>=0 && fk!=='SITE') {
|
||||||
|
o.castShadow = true; o.receiveShadow = true;
|
||||||
|
}
|
||||||
|
if (cat === 'trees') o.visible = false;
|
||||||
|
});
|
||||||
|
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);
|
||||||
|
const ci = new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1.5,1),
|
||||||
|
new THREE.MeshStandardMaterial({color:0x3e7d4f, roughness:0.8}), TREES.length);
|
||||||
|
const m4 = new THREE.Matrix4();
|
||||||
|
for (let i=0;i<TREES.length;i++){
|
||||||
|
const x=TREES[i][0], z=-TREES[i][1];
|
||||||
|
m4.makeScale(1,1,1); m4.setPosition(x,0.7,z); ti.setMatrixAt(i,m4);
|
||||||
|
const s = 0.85+(i%5)*0.08;
|
||||||
|
m4.makeScale(s,s,s); m4.setPosition(x,2.6,z); ci.setMatrixAt(i,m4);
|
||||||
|
}
|
||||||
|
ti.castShadow = ci.castShadow = true;
|
||||||
|
scene.add(ti); scene.add(ci);
|
||||||
|
}
|
||||||
|
const tg = document.getElementById('tg');
|
||||||
|
const state = {fl:{}, ct:{}};
|
||||||
|
const apply = () => nodes.forEach(o => { const p=(o.name||'').split('__');
|
||||||
|
o.visible = (state.fl[p[0]]!==false) && (state.ct[p[1]]!==false) && p[1]!=='trees'; });
|
||||||
|
for (const gname in GROUPS) {
|
||||||
|
const head = document.createElement('div'); head.className='grp';
|
||||||
|
const btn = document.createElement('button'); btn.textContent='开/关';
|
||||||
|
let on = true;
|
||||||
|
btn.onclick = () => { on=!on; GROUPS[gname].forEach(f => { state.fl[f[0]]=on;
|
||||||
|
const cb=document.getElementById('cb_'+f[0]); if(cb) cb.checked=on; }); apply(); };
|
||||||
|
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(); };
|
||||||
|
tg.appendChild(l);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const head2 = document.createElement('div'); head2.className='grp';
|
||||||
|
head2.textContent = '构件'; tg.appendChild(head2);
|
||||||
|
const used = {};
|
||||||
|
nodes.forEach(o => used[(o.name||'').split('__')[1]] = 1);
|
||||||
|
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(); };
|
||||||
|
tg.appendChild(l);
|
||||||
|
}
|
||||||
|
const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), info = document.getElementById('info');
|
||||||
|
let hi=null, hiMat=null, downAt=null;
|
||||||
|
addEventListener('pointerdown', e => downAt=[e.clientX,e.clientY]);
|
||||||
|
addEventListener('pointerup', e => {
|
||||||
|
if (!downAt || Math.hypot(e.clientX-downAt[0], e.clientY-downAt[1])>4) return;
|
||||||
|
ptr.x=(e.clientX/innerWidth)*2-1; ptr.y=-(e.clientY/innerHeight)*2+1;
|
||||||
|
ray.setFromCamera(ptr, cam);
|
||||||
|
const hit = ray.intersectObjects(nodes.filter(o=>o.visible), false)[0];
|
||||||
|
if (hi) { hi.material = hiMat; hi = null; }
|
||||||
|
if (!hit) { info.style.display='none'; return; }
|
||||||
|
hi = hit.object; hiMat = hi.material;
|
||||||
|
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.style.display = 'block';
|
||||||
|
});
|
||||||
|
renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, cam); });
|
||||||
|
}, e => fail('GLB 解析错误 '+(e && e.message || e)));
|
||||||
|
addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); });
|
||||||
|
} 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}'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
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.")
|
||||||
|
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()
|
||||||
|
b64 = base64.b64encode(gzip.compress(glb, 6)).decode()
|
||||||
|
|
||||||
|
order = spec.get("source", {}).get("config", {}).get("floor_order") or list(spec.get("floors", {}))
|
||||||
|
groups: dict = {}
|
||||||
|
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", [])]
|
||||||
|
cats = {k: v.get("label", k) for k, v in spec.get("categories", {}).items()}
|
||||||
|
title = args.title or spec.get("project", {}).get("name", "CAD 建筑模型")
|
||||||
|
|
||||||
|
main_js = (MAIN_JS
|
||||||
|
.replace("__GROUPS__", json.dumps(groups, ensure_ascii=False))
|
||||||
|
.replace("__CATS__", json.dumps(cats, ensure_ascii=False))
|
||||||
|
.replace("__TREES__", json.dumps(trees)))
|
||||||
|
sc_close = "</scr" + "ipt>"
|
||||||
|
html = (
|
||||||
|
'<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8">'
|
||||||
|
f'<title>{title} · 3D 查看器(离线版)</title>'
|
||||||
|
'<meta name="viewport" content="width=device-width, initial-scale=1">'
|
||||||
|
f'<style>{CSS}</style></head><body>'
|
||||||
|
'<div id="load">正在初始化…</div>'
|
||||||
|
f'<div id="panel"><h1>{title}</h1><div class="sub">{args.subtitle}</div><div id="tg"></div></div>'
|
||||||
|
'<div id="info"></div>'
|
||||||
|
'<div id="hint">拖动旋转 · 滚轮缩放 · 右键平移 · 点击构件查属性</div>'
|
||||||
|
+ "".join(f"<script>{parts[n]}{sc_close}" for n in
|
||||||
|
("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js"))
|
||||||
|
+ f'<script>const GLB_B64="{b64}";{sc_close}'
|
||||||
|
+ f"<script>{main_js}{sc_close}"
|
||||||
|
+ "</body></html>"
|
||||||
|
)
|
||||||
|
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))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -121,7 +121,30 @@ def inferred_metadata(args_metadata: str | None, manifest_path: Path | None, man
|
|||||||
return resolve_manifest_path(manifest_path, metadata_value) if manifest_path else Path(metadata_value)
|
return resolve_manifest_path(manifest_path, metadata_value) if manifest_path else Path(metadata_value)
|
||||||
|
|
||||||
|
|
||||||
def write_assets(glb: Path, metadata: Path, out_dir: Path, web_variants: list[dict]):
|
def site_trees_from_spec(spec_path: Path | None) -> list[list[float]]:
|
||||||
|
"""Tree anchor points (plan meters) for the viewer's instanced low-poly trees.
|
||||||
|
|
||||||
|
site_context_from_dump.py emits street trees as short posts under the
|
||||||
|
custom `trees` category; the viewer hides those posts and renders
|
||||||
|
trunk+crown InstancedMeshes at these midpoints instead.
|
||||||
|
"""
|
||||||
|
if not spec_path or not spec_path.exists():
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
||||||
|
except (OSError, json.JSONDecodeError):
|
||||||
|
return []
|
||||||
|
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),
|
||||||
|
])
|
||||||
|
return trees
|
||||||
|
|
||||||
|
|
||||||
|
def write_assets(glb: Path, metadata: Path, out_dir: Path, web_variants: list[dict], site_trees: list[list[float]]):
|
||||||
if not glb.exists():
|
if not glb.exists():
|
||||||
raise SystemExit(f"GLB not found: {glb}")
|
raise SystemExit(f"GLB not found: {glb}")
|
||||||
if not metadata.exists():
|
if not metadata.exists():
|
||||||
@@ -131,6 +154,8 @@ def write_assets(glb: Path, metadata: Path, out_dir: Path, web_variants: list[di
|
|||||||
meta.setdefault("files", {})["glb"] = "model.glb"
|
meta.setdefault("files", {})["glb"] = "model.glb"
|
||||||
if web_variants:
|
if web_variants:
|
||||||
meta["model_variants"] = web_variants
|
meta["model_variants"] = web_variants
|
||||||
|
if site_trees:
|
||||||
|
meta["site_trees"] = site_trees
|
||||||
(out_dir / "model_metadata.json").write_text(
|
(out_dir / "model_metadata.json").write_text(
|
||||||
json.dumps(meta, ensure_ascii=False, indent=2),
|
json.dumps(meta, ensure_ascii=False, indent=2),
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
@@ -148,7 +173,10 @@ def main() -> int:
|
|||||||
web_variants = copy_variant_assets(manifest_path, variants, out_dir)
|
web_variants = copy_variant_assets(manifest_path, variants, out_dir)
|
||||||
glb = inferred_default_glb(args.glb, manifest_path, manifest, variants)
|
glb = inferred_default_glb(args.glb, manifest_path, manifest, variants)
|
||||||
metadata = inferred_metadata(args.metadata, manifest_path, manifest, variants)
|
metadata = inferred_metadata(args.metadata, manifest_path, manifest, variants)
|
||||||
write_assets(glb, metadata, out_dir, web_variants)
|
variant = default_variant(manifest, variants)
|
||||||
|
spec_value = variant.get("spec") if variant else None
|
||||||
|
spec_path = resolve_manifest_path(manifest_path, spec_value) if (manifest_path and spec_value) else None
|
||||||
|
write_assets(glb, metadata, out_dir, web_variants, site_trees_from_spec(spec_path))
|
||||||
print(json.dumps({"web_dir": str(out_dir), "entry": str(out_dir / "index.html")}, ensure_ascii=False))
|
print(json.dumps({"web_dir": str(out_dir), "entry": str(out_dir / "index.html")}, ensure_ascii=False))
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|||||||
@@ -95,6 +95,70 @@ def make_xref_shell_dxf(path: Path) -> None:
|
|||||||
doc.saveas(path)
|
doc.saveas(path)
|
||||||
|
|
||||||
|
|
||||||
|
def make_multiframe_dxf(path: Path) -> None:
|
||||||
|
"""Chinese sheet-wall pattern: two floor-plan frames stacked 98100 apart.
|
||||||
|
|
||||||
|
Reproduces the 贝昂 failure mode: one DWG holds every floor; frames keep
|
||||||
|
their sheet positions, so extraction without per-frame offsets scatters
|
||||||
|
floors diagonally.
|
||||||
|
"""
|
||||||
|
doc = ezdxf.new("R2010", setup=True)
|
||||||
|
for layer in ("WALL", "DOTE", "PUB_TEXT"):
|
||||||
|
doc.layers.add(layer)
|
||||||
|
msp = doc.modelspace()
|
||||||
|
pitch = 98100.0
|
||||||
|
|
||||||
|
def draw_frame(oy: float, title: str) -> None:
|
||||||
|
# walls: 40m x 20m outline + interior partitions (>=10 lines for clip refine)
|
||||||
|
outline = [((0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
|
||||||
|
((40000, 20000), (0, 20000)), ((0, 20000), (0, 0))]
|
||||||
|
interior = [((8000 * i, 0), (8000 * i, 20000)) for i in range(1, 5)]
|
||||||
|
interior += [((0, 10000), (40000, 10000)), ((12000, 5000), (28000, 5000)),
|
||||||
|
((20000, 0), (20000, 10000)), ((30000, 10000), (30000, 20000))]
|
||||||
|
for (sx, sy), (ex, ey) in outline + interior:
|
||||||
|
msp.add_line((sx, sy + oy), (ex, ey + oy), dxfattribs={"layer": "WALL"})
|
||||||
|
for i in range(6): # vertical grid lines on DOTE (TArch convention)
|
||||||
|
x = i * 8000
|
||||||
|
msp.add_line((x, -3000 + oy), (x, 26000 + oy), dxfattribs={"layer": "DOTE"})
|
||||||
|
for j in range(3): # horizontal grid lines
|
||||||
|
y = j * 10000
|
||||||
|
msp.add_line((-3000, y + oy), (46000, y + oy), dxfattribs={"layer": "DOTE"})
|
||||||
|
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, oy - 6000))
|
||||||
|
|
||||||
|
draw_frame(0.0, "一层平面图")
|
||||||
|
draw_frame(-pitch, "二层平面图")
|
||||||
|
doc.saveas(path)
|
||||||
|
|
||||||
|
|
||||||
|
def make_rowframe_dxf(path: Path) -> None:
|
||||||
|
"""Row layout (3#辅房 pattern): frames side by side, pitch on X, titles same row."""
|
||||||
|
doc = ezdxf.new("R2010", setup=True)
|
||||||
|
for layer in ("WALL", "DOTE", "PUB_TEXT"):
|
||||||
|
doc.layers.add(layer)
|
||||||
|
msp = doc.modelspace()
|
||||||
|
pitch = 21000.0
|
||||||
|
|
||||||
|
def draw_frame(ox: float, title: str) -> None:
|
||||||
|
outline = [((0, 0), (8000, 0)), ((8000, 0), (8000, 16000)),
|
||||||
|
((8000, 16000), (0, 16000)), ((0, 16000), (0, 0))]
|
||||||
|
interior = [((0, 2000 * i), (8000, 2000 * i)) for i in range(1, 8)]
|
||||||
|
interior += [((4000, 0), (4000, 16000)), ((2000, 4000), (6000, 4000)),
|
||||||
|
((2000, 12000), (6000, 12000))]
|
||||||
|
for (sx, sy), (ex, ey) in outline + interior:
|
||||||
|
msp.add_line((sx + ox, sy), (ex + ox, ey), dxfattribs={"layer": "WALL"})
|
||||||
|
for i in range(3):
|
||||||
|
x = i * 4000
|
||||||
|
msp.add_line((x + ox, -2500), (x + ox, 18500), dxfattribs={"layer": "DOTE"})
|
||||||
|
for j in range(4):
|
||||||
|
y = j * 5000
|
||||||
|
msp.add_line((-2500 + ox, y), (10500 + ox, y), dxfattribs={"layer": "DOTE"})
|
||||||
|
msp.add_text(title, height=700, dxfattribs={"layer": "PUB_TEXT"}).set_placement((2500 + ox, -5200))
|
||||||
|
|
||||||
|
draw_frame(0.0, "一层平面图")
|
||||||
|
draw_frame(pitch, "二层平面图")
|
||||||
|
doc.saveas(path)
|
||||||
|
|
||||||
|
|
||||||
def run(cmd: list[str]) -> subprocess.CompletedProcess:
|
def run(cmd: list[str]) -> subprocess.CompletedProcess:
|
||||||
return subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True)
|
return subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True)
|
||||||
|
|
||||||
@@ -195,6 +259,213 @@ def main() -> int:
|
|||||||
gates_fail = {gate["name"]: gate["status"] for gate in audit_fail["gates"]}
|
gates_fail = {gate["name"]: gate["status"] for gate in audit_fail["gates"]}
|
||||||
check("glazing gate FAIL when blocks unexpanded", gates_fail.get("glazing_captured") == "FAIL", str(gates_fail))
|
check("glazing gate FAIL when blocks unexpanded", gates_fail.get("glazing_captured") == "FAIL", str(gates_fail))
|
||||||
|
|
||||||
|
# --- multi-frame sheet: detect frames, grid-align, alignment gate ---
|
||||||
|
mf_path = dxf_dir / "multiframe.dxf"
|
||||||
|
make_multiframe_dxf(mf_path)
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/cad_dxf_report.py",
|
||||||
|
"--input", str(dxf_dir), "--work", str(WORK / "report_work2"),
|
||||||
|
"--output", str(WORK / "read_report2"), "--vendor-dir", str(VENDOR),
|
||||||
|
])
|
||||||
|
report2 = json.loads((WORK / "read_report2" / "cad_read_report.json").read_text(encoding="utf-8"))
|
||||||
|
mf_item = {item["file"]: item for item in report2["files"]}.get("multiframe.dxf", {})
|
||||||
|
check("multi_frame_sheet warning raised", any("multi_frame_sheet" in w for w in mf_item.get("warnings", [])), str(mf_item.get("warnings")))
|
||||||
|
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/detect_sheet_frames.py",
|
||||||
|
"--dxf", str(mf_path), "--out-config", str(WORK / "frames.json"),
|
||||||
|
"--out-report", str(WORK / "frames.md"), "--vendor-dir", str(VENDOR),
|
||||||
|
])
|
||||||
|
check("detect_sheet_frames runs", proc.returncode == 0, proc.stderr[-800:])
|
||||||
|
frames = json.loads((WORK / "frames.json").read_text(encoding="utf-8"))
|
||||||
|
floors = frames["drawings"][0]["floors"]
|
||||||
|
keys = [floor["key"] for floor in floors]
|
||||||
|
check("two plan frames found", sorted(keys) == ["F1", "F2"], str(keys))
|
||||||
|
off = {floor["key"]: floor["offset"] for floor in floors}
|
||||||
|
ok_offset = abs(off["F2"][0] - 0.0) <= 120 and abs(off["F2"][1] - 98100.0) <= 120
|
||||||
|
check("grid alignment recovers frame offset", ok_offset, str(off))
|
||||||
|
|
||||||
|
frames.update({"scale": 0.001, "layers": {"walls": ["WALL"], "grid": ["DOTE"]}})
|
||||||
|
aligned_cfg = WORK / "config_frames.json"
|
||||||
|
aligned_cfg.write_text(json.dumps(frames, ensure_ascii=False), encoding="utf-8")
|
||||||
|
aligned_spec = WORK / "spec_frames.json"
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/derive_showcase_spec.py",
|
||||||
|
"--dxf-dir", str(dxf_dir), "--config", str(aligned_cfg),
|
||||||
|
"--out", str(aligned_spec), "--vendor-dir", str(VENDOR),
|
||||||
|
])
|
||||||
|
check("derive multi-frame runs", proc.returncode == 0, proc.stderr[-800:])
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/audit_showcase_extraction.py",
|
||||||
|
"--dxf-dir", str(dxf_dir), "--config", str(aligned_cfg), "--spec", str(aligned_spec),
|
||||||
|
"--out", str(WORK / "audit_frames"), "--vendor-dir", str(VENDOR),
|
||||||
|
])
|
||||||
|
audit_frames = json.loads((WORK / "audit_frames" / "extraction_audit.json").read_text(encoding="utf-8"))
|
||||||
|
gates_frames = {gate["name"]: gate["status"] for gate in audit_frames["gates"]}
|
||||||
|
check("floors_aligned gate PASS with offsets", gates_frames.get("floors_aligned") == "PASS", str(gates_frames))
|
||||||
|
|
||||||
|
# Same clips but WITHOUT offsets -> the diagonal-staircase bug -> gate FAIL.
|
||||||
|
bad = json.loads(aligned_cfg.read_text(encoding="utf-8"))
|
||||||
|
for floor in bad["drawings"][0]["floors"]:
|
||||||
|
floor["offset"] = [0.0, 0.0]
|
||||||
|
bad_cfg = WORK / "config_frames_bad.json"
|
||||||
|
bad_cfg.write_text(json.dumps(bad, ensure_ascii=False), encoding="utf-8")
|
||||||
|
bad_spec = WORK / "spec_frames_bad.json"
|
||||||
|
run([
|
||||||
|
sys.executable, "scripts/derive_showcase_spec.py",
|
||||||
|
"--dxf-dir", str(dxf_dir), "--config", str(bad_cfg),
|
||||||
|
"--out", str(bad_spec), "--vendor-dir", str(VENDOR),
|
||||||
|
])
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/audit_showcase_extraction.py",
|
||||||
|
"--dxf-dir", str(dxf_dir), "--config", str(bad_cfg), "--spec", str(bad_spec),
|
||||||
|
"--out", str(WORK / "audit_frames_bad"), "--vendor-dir", str(VENDOR),
|
||||||
|
])
|
||||||
|
check("misaligned floors exit 3", proc.returncode == 3, f"rc={proc.returncode}")
|
||||||
|
audit_bad = json.loads((WORK / "audit_frames_bad" / "extraction_audit.json").read_text(encoding="utf-8"))
|
||||||
|
gates_bad = {gate["name"]: gate["status"] for gate in audit_bad["gates"]}
|
||||||
|
check("floors_aligned gate FAIL without offsets", gates_bad.get("floors_aligned") == "FAIL", str(gates_bad))
|
||||||
|
cov = audit_frames["coverage"]
|
||||||
|
check("clip-scoped coverage reported", cov.get("clipped_supported_length_coverage") is not None, str(cov))
|
||||||
|
|
||||||
|
# --- horizontal-row frames (3#辅房 pattern) ---
|
||||||
|
row_dir = WORK / "dxf_row"
|
||||||
|
row_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
make_rowframe_dxf(row_dir / "rowframes.dxf")
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/detect_sheet_frames.py",
|
||||||
|
"--dxf", str(row_dir / "rowframes.dxf"), "--out-config", str(WORK / "frames_row.json"),
|
||||||
|
"--out-report", str(WORK / "frames_row.md"), "--vendor-dir", str(VENDOR),
|
||||||
|
])
|
||||||
|
check("detect handles row layout", proc.returncode == 0, proc.stderr[-600:])
|
||||||
|
frames_row = json.loads((WORK / "frames_row.json").read_text(encoding="utf-8"))
|
||||||
|
row_floors = frames_row["drawings"][0]["floors"]
|
||||||
|
row_off = {f["key"]: f["offset"] for f in row_floors}
|
||||||
|
check("row layout: two floors", sorted(row_off) == ["F1", "F2"], str(row_off))
|
||||||
|
ok_row = "F2" in row_off and abs(row_off["F2"][0] + 21000.0) <= 120 and abs(row_off["F2"][1]) <= 120
|
||||||
|
check("row layout: x-pitch offset recovered", ok_row, str(row_off))
|
||||||
|
|
||||||
|
# --- merge_wall_solids: shapely union of wall segments (spec_to_glb) ---
|
||||||
|
sys.path.insert(0, str(ROOT / "scripts"))
|
||||||
|
import spec_to_glb # noqa: E402
|
||||||
|
|
||||||
|
l_walls = [
|
||||||
|
{"start": [0, 0], "end": [10, 0], "width": 0.24, "layer": "WALL"},
|
||||||
|
{"start": [10, 0], "end": [10, 8], "width": 0.24, "layer": "WALL"},
|
||||||
|
]
|
||||||
|
check("spec_to_glb exposes merged_wall_polygons", hasattr(spec_to_glb, "merged_wall_polygons"))
|
||||||
|
if hasattr(spec_to_glb, "merged_wall_polygons"):
|
||||||
|
polys = spec_to_glb.merged_wall_polygons(l_walls)
|
||||||
|
check("L walls union to a single polygon", len(polys) == 1, f"{len(polys)} polygons")
|
||||||
|
if len(polys) == 1:
|
||||||
|
corner_count = len(list(polys[0].exterior.coords)) - 1
|
||||||
|
# A seamless right-angle corner is exactly 6 corners; 8 means the
|
||||||
|
# w/2 x w/2 notch at the shared endpoint was left open.
|
||||||
|
check("L union corner is seamless (6 corners)", corner_count == 6, f"{corner_count} corners")
|
||||||
|
minx, miny, maxx, maxy = polys[0].bounds
|
||||||
|
check(
|
||||||
|
"free wall ends are not extended",
|
||||||
|
abs(minx - 0.0) < 1e-6 and abs(maxy - 8.0) < 1e-6,
|
||||||
|
f"bounds={polys[0].bounds}",
|
||||||
|
)
|
||||||
|
|
||||||
|
wall_spec = {
|
||||||
|
"project": {"name": "wall-merge-test"},
|
||||||
|
"units": "meters",
|
||||||
|
"categories": {"walls": {"label": "墙体", "color": "#d4cbb8"}},
|
||||||
|
"source": {"config": {}},
|
||||||
|
"floors": {
|
||||||
|
"F1": {
|
||||||
|
"name": "首层", "z": 0.0, "height": 4.0,
|
||||||
|
"bounds": [0, 0, 12, 10],
|
||||||
|
"segments": {"walls": list(l_walls)},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
def build_glb(tag: str, config: dict) -> tuple[bytes, dict]:
|
||||||
|
spec = json.loads(json.dumps(wall_spec))
|
||||||
|
spec["source"]["config"] = config
|
||||||
|
spec_file = WORK / f"wall_spec_{tag}.json"
|
||||||
|
spec_file.write_text(json.dumps(spec, ensure_ascii=False), encoding="utf-8")
|
||||||
|
out_file = WORK / f"wall_{tag}.glb"
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/spec_to_glb.py",
|
||||||
|
"--spec", str(spec_file), "--out", str(out_file), "--name", tag,
|
||||||
|
])
|
||||||
|
check(f"spec_to_glb ({tag}) runs", proc.returncode == 0, proc.stderr[-400:])
|
||||||
|
info = json.loads(proc.stdout.strip().splitlines()[-1]) if proc.returncode == 0 else {}
|
||||||
|
return (out_file.read_bytes() if out_file.exists() else b""), info
|
||||||
|
|
||||||
|
default_bytes, default_info = build_glb("default", {})
|
||||||
|
off_bytes, _ = build_glb("off", {"merge_wall_solids": False})
|
||||||
|
on_bytes, on_info = build_glb("on", {"merge_wall_solids": True})
|
||||||
|
check("merge_wall_solids default matches explicit off byte-for-byte", default_bytes == off_bytes and len(default_bytes) > 0)
|
||||||
|
check("merge_wall_solids on changes the output", on_bytes not in (b"", default_bytes))
|
||||||
|
check(
|
||||||
|
"merged walls keep one node with valid triangles",
|
||||||
|
on_info.get("nodes") == default_info.get("nodes") and on_info.get("triangles", 0) > 0,
|
||||||
|
f"default={default_info} on={on_info}",
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- glazing_mullions: panel grid over merged glazing bands ---
|
||||||
|
check("spec_to_glb exposes glazing_mullion_segments", hasattr(spec_to_glb, "glazing_mullion_segments"))
|
||||||
|
if hasattr(spec_to_glb, "glazing_mullion_segments"):
|
||||||
|
band = [{"start": [0, 0], "end": [6, 0], "width": 0.06, "layer": "CURTWALL"}]
|
||||||
|
msegs = spec_to_glb.glazing_mullion_segments(band, 0.0, 4.0, panel_w=1.5)
|
||||||
|
verticals = [s for s in msegs if "_z0" not in s]
|
||||||
|
transoms = [s for s in msegs if "_z0" in s]
|
||||||
|
check("6m band at 1.5m pitch gives 5 vertical mullions", len(verticals) == 5, f"{len(verticals)} verticals")
|
||||||
|
check("band gets top+bottom transoms", len(transoms) == 2, f"{len(transoms)} transoms")
|
||||||
|
if transoms:
|
||||||
|
zs = sorted(float(s["_z0"]) for s in transoms)
|
||||||
|
check("transoms sit at the floor lines", abs(zs[0] - 0.0) < 0.15 and abs(zs[-1] - 4.0) < 0.15, str(zs))
|
||||||
|
|
||||||
|
glaze_spec = {
|
||||||
|
"project": {"name": "mullion-test"},
|
||||||
|
"units": "meters",
|
||||||
|
"categories": {
|
||||||
|
"walls": {"label": "墙体", "color": "#d4cbb8"},
|
||||||
|
"glazing": {"label": "玻璃", "color": "#79b8c9"},
|
||||||
|
},
|
||||||
|
"source": {"config": {}},
|
||||||
|
"floors": {
|
||||||
|
"F1": {
|
||||||
|
"name": "首层", "z": 0.0, "height": 4.0,
|
||||||
|
"bounds": [0, 0, 8, 4],
|
||||||
|
"segments": {"glazing": [
|
||||||
|
{"start": [0, 0], "end": [6, 0], "width": 0.06, "layer": "CURTWALL"},
|
||||||
|
]},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
def build_glaze_glb(tag: str, config: dict) -> tuple[bytes, dict]:
|
||||||
|
spec = json.loads(json.dumps(glaze_spec))
|
||||||
|
spec["source"]["config"] = config
|
||||||
|
spec_file = WORK / f"glaze_spec_{tag}.json"
|
||||||
|
spec_file.write_text(json.dumps(spec, ensure_ascii=False), encoding="utf-8")
|
||||||
|
out_file = WORK / f"glaze_{tag}.glb"
|
||||||
|
proc = run([
|
||||||
|
sys.executable, "scripts/spec_to_glb.py",
|
||||||
|
"--spec", str(spec_file), "--out", str(out_file), "--name", tag,
|
||||||
|
])
|
||||||
|
check(f"spec_to_glb ({tag}) runs", proc.returncode == 0, proc.stderr[-400:])
|
||||||
|
info = json.loads(proc.stdout.strip().splitlines()[-1]) if proc.returncode == 0 else {}
|
||||||
|
return (out_file.read_bytes() if out_file.exists() else b""), info
|
||||||
|
|
||||||
|
gdefault_bytes, gdefault_info = build_glaze_glb("default", {})
|
||||||
|
goff_bytes, _ = build_glaze_glb("off", {"glazing_mullions": False})
|
||||||
|
gon_bytes, gon_info = build_glaze_glb("on", {"glazing_mullions": True})
|
||||||
|
check("glazing_mullions default matches explicit off byte-for-byte", gdefault_bytes == goff_bytes and len(gdefault_bytes) > 0)
|
||||||
|
check("glazing_mullions on changes the output", gon_bytes not in (b"", gdefault_bytes))
|
||||||
|
check(
|
||||||
|
"mullions add a walls node and keep the glass pane",
|
||||||
|
gon_info.get("nodes", 0) == gdefault_info.get("nodes", 0) + 1
|
||||||
|
and gon_info.get("triangles", 0) > gdefault_info.get("triangles", 0),
|
||||||
|
f"default={gdefault_info} on={gon_info}",
|
||||||
|
)
|
||||||
|
|
||||||
print()
|
print()
|
||||||
if FAILURES:
|
if FAILURES:
|
||||||
print(f"{len(FAILURES)} check(s) failed: {FAILURES}")
|
print(f"{len(FAILURES)} check(s) failed: {FAILURES}")
|
||||||
|
|||||||
89
贝昂CAD诊断与skill优化.md
Normal file
89
贝昂CAD诊断与skill优化.md
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
# 贝昂科技厂区 CAD:为什么生成错了 + skill 优化记录
|
||||||
|
|
||||||
|
日期:2026-07-02 | 源数据:`test3d-6/fs贝昂科技_新建项目cad20250728`
|
||||||
|
|
||||||
|
## 一、错误原因诊断
|
||||||
|
|
||||||
|
截图里"6 个楼层 B1F–B6F 沿对角线散开"的直接原因,是这套图纸的组织方式与 skill 的假设完全不匹配:
|
||||||
|
|
||||||
|
1. **这是厂区(5 栋建筑),不是一栋楼的 6 层。** `建筑/` 下每个 DWG 是一栋楼(1#厂房、2#厂房、3#辅房、4#机械停车坑、5#应急污水处理池)外加两张总图。上一次运行把"每个文件当一层"堆起来,楼层数、命名(B1F 会被 skill 按地下室排序)、位置全都不对。
|
||||||
|
2. **每个 DWG 的 modelspace 里是整套图纸墙。** 以 1#厂房为例:8 张平面图(地下一层/一层/一层夹层/二~四层/屋顶机房层/屋顶)+ 4 张立面 + 2 张剖面 + 楼梯电梯详图,全部按 A1 图框(1:150,纵向间距 98,100mm)排开。不裁剪 clip 就提取 = 所有图纸叠在一层;裁了但不做 offset 归零 = 每层保留图框位置 → 就是截图里的"斜楼梯"。
|
||||||
|
3. **天正 t3 图层惯例不被默认规则识别。** 轴网在 `DOTE`(不是 AXIS);门窗都是 `WINDOW` 层上的块(窗块 `$TCHSYS$WIN2D`、门块 `$DorLib2D$*`),块内几何在 0 层靠 INSERT 继承图层——skill 的"按子实体图层探测"对这种块**一根线都留不下**,必须显式展开 + 按块名分类。
|
||||||
|
4. **单位混用陷阱。** 楼栋图是毫米;总图是**米制真实测量坐标**(x≈349xxx、y≈663xxx)。config 只有一个全局 scale,两类图不能混在一个 spec 里。
|
||||||
|
5. **性能缺陷(这次已修)。** `derive_showcase_spec.py` 原来对每个楼层重复展开全部 INSERT(O(楼层×块)),audit 又对每个 INSERT 重复 explode。A208 案例"一文件一层"没暴露;贝昂这种"一文件八层 + 1,684 个块"直接超时。
|
||||||
|
|
||||||
|
## 二、这套 CAD 的正确做法
|
||||||
|
|
||||||
|
按栋建模 + 总图摆位,已在 1#厂房上完整验证:
|
||||||
|
|
||||||
|
1. DWG→DXF:macOS 上用 ODA/libredwg;无原生转换器时用新增的 WASM 兜底(`dwg_dump_json.mjs` + `dwgjson_to_dxf.py`,22,970 图元 + 4,081 块定义零丢失)。
|
||||||
|
2. `detect_sheet_frames.py`(新增)自动完成最难的部分:识别 8 个平面图图框(过滤图纸目录行/图签同名字)、按墙体 bbox 收紧 clip、**用轴线位置互相关投票算每层 offset**(B1 图框有 250mm 非均匀偏移也被修正)。
|
||||||
|
3. 层高从剖面图 DIM_ELEV 标高取:B1=-4.8,F1=0(层高 8.1 含 4.8 夹层),F2=8.1,F3=13.1,F4=18.1,机房=23.1,屋面=27.9。
|
||||||
|
4. 天正图层映射 + 门窗块规则写入 config(见 `outputs/beian_1hao/extract_config.json`,可直接当 t3 模板复用)。
|
||||||
|
5. 提取 → 审计 → 叠图 → GLB → 三视图验证:地上各层 bounds 完全一致(104.8m × 58.8m),B1 正确落在内部 33×48m;幕墙连续 100%;GLB 6.7MB / 48 节点。三视图见 `outputs/beian_1hao/beian_previews.png`。
|
||||||
|
|
||||||
|
剩下 4 栋照同样流程各自出模型;楼栋摆位建议用 `更新图纸/贝昂 建筑-总图 首层带轴号(可点坐标)` 量各栋锚点与转角,写一个 site manifest,在 viewer 里按 transform 组装(不要把米制总图混进毫米 spec)。结构柱如需完整,从 `结构/` 图纸补(建筑图里柱多为填充,t3 导出后只剩 6 根线框柱/层)。
|
||||||
|
|
||||||
|
## 三、本次对 skill 的修改
|
||||||
|
|
||||||
|
新增脚本:`detect_sheet_frames.py`(多图框切分+网格对齐配置生成)、`dwg_dump_json.mjs` + `dwgjson_to_dxf.py`(WASM DWG 兜底转换)。
|
||||||
|
|
||||||
|
修复/优化:`derive_showcase_spec.py` 改单遍展开+按层分桶(本例 >45s 超时 → 6.3s,输出逐段一致)、块叶子图层缓存跳过无关块、`cap_groups` 可配置(原来硬编码 A208 的 AUX_/B1 分组)、新增"顶层无盖"警告(顶层既无 caps 又无 roof_specs 时强提示,防止生成没屋顶的模型);`audit_showcase_extraction.py` 块内几何清点改块定义遍历+按名缓存(40s+ → 6.3s);`spec_to_glb.py` 修复两处:多边形三角化失败(缺 mapbox_earcut)原来**静默丢弃全部楼板/顶盖/屋面**,现在显式报警;新增 `slab_bounds_fallback` 开关,避免女儿墙层从 bounds 生成盖满全楼的假板;`cad_dxf_report.py` 修复 input 目录与 work/dxf_raw 相同时 copy 崩溃。
|
||||||
|
|
||||||
|
屋顶问题复盘(第二轮反馈"没有屋顶"):三个原因叠加——① 地上顶盖按设计要走 config `roof_specs`(机房顶 27.9m 一块、主屋面由 F4 顶帽 + 机房层楼板组成 23.1m 一层),首版配置漏了;② roof 类默认线宽 0,女儿墙挤出为零厚度;③ 沙盒缺 mapbox_earcut 导致所有板类网格静默失败。三处都已修,GLB 现含 `PH__roof`(机房顶)、`RF__roof`(檐口/女儿墙带)、F4 顶帽环 + 各层楼板。
|
||||||
|
|
||||||
|
SKILL.md 新增:多图框工作流(第 3 步)、"厂区多栋"章节、天正 t3 预设章节、WASM 兜底说明、audit 裁剪口径注意事项(多图框时全文件覆盖率 ~40% 属正常,要看叠图而非头条数字)、B 前缀楼层键警告。
|
||||||
|
|
||||||
|
回归测试 `tests/test_extraction_pipeline.py` 12 项全部通过。
|
||||||
|
|
||||||
|
## 四、后续建议(未实施)
|
||||||
|
|
||||||
|
audit 增加"裁剪范围内"口径的第二组覆盖率数字;detect_sheet_frames 顺带解析剖面标高自动填 z/height;桥接脚本补 HATCH(柱填充)与 ATTRIB(轴号);出一个 site-manifest 组装脚本把多栋 GLB 合成厂区场景。
|
||||||
|
|
||||||
|
## 五、"一次做对"机制(2026-07-02 第二轮加固)
|
||||||
|
|
||||||
|
思路:把 Agent 的判断变成**会大声失败的确定性门禁**,宁可停在中间也不产出错模型。
|
||||||
|
|
||||||
|
新增/加固的机制(全部有回归测试覆盖,共 20 项 checks):读图报告新增 `multi_frame_sheet` 警告(一个 modelspace 里发现 ≥2 个"XX平面图"标题就强制走 detect_sheet_frames,防"一文件当一层");audit 新增 `floors_aligned` 硬门禁(同组楼层墙体包络中心偏差超限即 exit 3,直接拦截"斜楼梯"输出,测试验证了有 offset 通过 / 无 offset 失败);derive 的 `topless_group` 警告(顶层无盖必须配 roof_specs);GLB 导出的三角化失败显式报警(楼板静默消失问题)。SKILL.md 增加 "One-Shot Definition of Done" 检查单:7 条逐项要有证据(报告行/门禁状态/亲眼看过的渲染图)才能交付。
|
||||||
|
|
||||||
|
## 六(补)、场布重建(第三轮反馈"场布就几根线")
|
||||||
|
|
||||||
|
原因:首版场布只取了定位图测量副本,那份图本来就只画红线/围墙/道路骨架;真正的场地内容(车行道细节、车位、行道树、绿化、出入口、连廊等)在 `建筑-总图(施工图)` 里(米制、含三份方案副本,取顶部与定位副本重合那份)。已把场布提取固化为 skill 脚本 `site_context_from_dump.py`:地面=红线 footprint 板、道路/车位(含圆弧展开与车位块展开,1303+358 段)、围墙=1.8m 栅栏(149 段)、行道树=52 根绿柱(自定义 trees 类别)、场内小构筑物体量(连廊/消控室/钢楼梯,按最近标注命名,出入口自动跳过)。2# 厂房在总图顶副本无独立轮廓(与 1# 贴建、自有整套图纸),按规范应同法建模后摆入,不造假体量。
|
||||||
|
|
||||||
|
## 七、2#/3# 建模与摆位(第四轮"继续")
|
||||||
|
|
||||||
|
2#厂房、3#辅房用与 1# 完全相同的配方跑通(桥接→图框检测→提取):2# 七层全部网格对齐,包络 64.1×40.1m;3# 暴露并修复了检测器一个盲区——**横排图框**(标题同行、x 向 21m 间距),检测器现在同时支持纵排/横排。摆位数据的攻坚:定位图给排水/电气总图的楼底图都是未绑定 XREF(死路),最终解法是**副本配准**——定位图里未旋转的施工场布副本画有全部楼栋,用 1# 的 90.2×42.2 特征矩形做两副本间刚体配准(验证误差 2mm:红线角点变换后与坐标标注完全吻合),再把该副本里 2# 的屋面轮廓(66×39.2)映射回测量坐标同心摆位。3# 用东侧地块四个红线角点均值近似摆位(±1m,manifest 注记待校正)。4#/5# 为地下坑/低矮水池,定位图无轮廓,标记待建不造假。三栋楼与场布的俯视校验见 campus_check.png。
|
||||||
|
|
||||||
|
## 八、1#/2# 间距核实与修正(第六轮)
|
||||||
|
|
||||||
|
用户质疑两楼紧贴。核实结论:**贴建是对的,但差一条缝**——首版按屋面轮廓同心摆位导致 2# 嵌入 1# 达 0.26m。证据链:可点坐标角点中 +10.8m/+38.0m 两条线均精确过沿线 90.2m(1# 东立面延长线)→ 2# 东立面与 1# 齐平;副本A 缝隙带 +0.19m 处的平面线 = 变形缝;反证:若按 10m 防火间距,2# 会顶穿北侧红线(几何不可能)。修正后:墙对墙间距 0.190m、东立面错位 0.001m(seam_check.png)。教训固化进 SKILL.md:摆位锚点必须用墙线/坐标标注而非屋面轮廓(含雨棚外挑会偏);邻栋间距必须数值核验(负值=bug,0.15-0.3m=贴建变形缝需旁证,红线冲突可否证假设)。
|
||||||
|
|
||||||
|
## 六、厂区合成(定位图 → 摆位)
|
||||||
|
|
||||||
|
`定位图 - 副本(2).dwg` 里有一份落在测量坐标上的总平面(mm 单位,x≈349.6km)。1# 厂房在其中的"面积核算"框是 **90.2 × 42.2m、旋转 7.57°**——与模型墙体包络 90.2 × 42.2m 完全 1:1 对应,据此得到精确变换(角点 D=(349582714, 664188492)mm ↔ 模型 (7.3, 8.3)m);180° 朝向歧义用机房墙密度投票判定(no-flip 119 vs 72)。场地本地原点取用地红线角点(避免 349km 坐标撑爆 float32)。合成方式是 **spec 级合并**:把 1# 全部楼层几何旋转平移到场地坐标,再加一层 SITE(红线/围墙/道路/其他楼轮廓),一次导出厂区 GLB。俯视校验图 `campus_check.png` 显示楼栋严丝合缝落在定位框内。剩余 2#/3#/4#/5# 楼各自建模后按 `site_manifest.json` 里同样的配方摆入即可。
|
||||||
|
|
||||||
|
## 九、剩余改进项推进(第七轮)
|
||||||
|
|
||||||
|
沙盒内已完成 4 项:① `assemble_campus.py` 转正——manifest 驱动的多栋装配 + 自动邻栋间距门禁(穿模 exit 3、0.1-0.3m 提示贴缝),用贝昂三栋回归验证与手工装配偏差 ≤0.35mm(manifest 舍入噪声),并且初跑就自我纠错一次(全楼层包络误报穿模 → 改为首层包络判定);② detect_sheet_frames 新增剖面标高收集,1# 实测输出完整层标高序列(-4.8/±0/4.8/8.1/…/27.9/28.8 全中);③ audit 新增裁剪口径覆盖率(多图框时以此为准);④ 桥接脚本补 ATTRIB→TEXT(天正轴号/坐标标注属性不再丢失)。回归测试扩至 24 项全绿(含横排图框用例)。
|
||||||
|
|
||||||
|
Mac 侧待办(沙盒能力边界):Draco 压缩(`node tools/compress.mjs`,WASM 沙盒必崩);正式模板部署验证(npm install three@0.181.2 + 本地服务,验证升级后的 IBL/阴影/物理玻璃实际渲染);4#/5# 建模(先向设计方要含这两个构筑物轮廓的总平面或坐标);3# 摆位精确化(同样需权威定位数据);Tier 2 几何升级(墙体 union/幕墙分格/门窗开洞,动导出管线,需配套回归用例);IFC 语义(build_ifc_poc.py,需 IfcOpenShell)。
|
||||||
|
|
||||||
|
## 十、Mac 侧四项推进:Draco / 正式模板 / 墙体 union / 幕墙分格(第八轮,2026-07-02)
|
||||||
|
|
||||||
|
沙盒能力边界外的待办在 macOS 上全部落地,过程中又修掉一批"两后端行为分歧"型 bug:
|
||||||
|
|
||||||
|
1. **Draco 压缩**:`tools/compress.mjs` 在 macOS 正常(沙盒 WASM 崩溃确认是环境问题)。beian_campus.glb 15.0MB → **0.57MB**(Draco + weld/dedup/prune),121 节点逐一核对无丢挂,`KHR_draco_mesh_compression` 在场且可解码。dedup 把 2 个全同 mesh 合并共享(122→120),无损。
|
||||||
|
2. **正式模板部署验证**(含用户两次现场反馈的修复):
|
||||||
|
- "屋顶的板超出了":`build_blender_showcase.py` 生成屋面默认走 bounds+margin 矩形(要 `use_footprint_roofs` 才用多边形),PH 机房顶变成盖满全楼 bbox 的大板。已改为 footprint 无条件优先(与 spec_to_glb 同契约),修复后 6 个屋面节点尺寸与已验证 GLB 逐一吻合。同类:Blender 端不认 `slab_bounds_fallback:false`,ROADS/FENCE/TREES 等无 footprint 层生成盖满全厂区的 bounds 假板,同步修复。**教训:spec_to_glb 修过的坑要同步检查 Blender 端——两后端必须一个契约,否则换后端重建即翻车。**
|
||||||
|
- "为什么没有嵌入式 viewer 的效果":① 变体类别过滤把场地内容滤掉(路在 detail_lines/grid、树在自定义 trees),`build_showcase_variants.py` 现对 `source_file=="site"` 的楼层整层保留;② 官方模板缺实例化树,已移植(write_web_showcase 从 spec 抽 52 树坐标进 metadata `site_trees`,app.js InstancedMesh 树干+树冠,2 draw call)。
|
||||||
|
- 阴影接收板从 bounds.min.y(B1 底 -5.1m)钳制到 ±0 地坪(地下室存在时阴影悬空脱开建筑);favicon 404 用 data-URI 消掉,控制台零消息。
|
||||||
|
- 浏览器亲测:IBL/软阴影/物理玻璃、爆炸 6m、剖切 14m、点击溯源(F3 墙体)、顶视摆位、390px 手机布局全部通过,截图存 `outputs/beian_1hao/web_verify/`。
|
||||||
|
3. **Tier 2 连续墙体 `merge_wall_solids`**(默认关):spec_to_glb 用 shapely buffer+unary_union+extrude;Blender 端 Python 3.13 无 shapely(ABI 不敢注入),改用原生 `mathutils.geometry.delaunay_2d_cdt` 求并集、边界边挤侧墙。**几何教训:cap_style=2 平头矩形在共享端点的 L 角天生留 w/2×w/2 缺口,union 闭合不了(首轮对比渲染完全一致才暴露);解法是只对共享端点的墙端预延长 w/2(`extend_shared_wall_ends`),洞口自由端不动,T 接头本就有重叠。** 验收:L 角 union 后单多边形恰 6 顶点;默认关闭下厂区 GLB 与改前黄金文件逐字节一致(14,994,560B);开启后三角 +37%(选配近景用)。对比图 `wall_merge_{off,on}_corner.png`。
|
||||||
|
4. **Tier 2 幕墙分格 `glazing_mullions`**(默认关,`glazing_panel_w` 1.5m):竖梃/横梃合成为伪墙段(细盒型材,横梃带 `_z0/_z1`)并入 `<floor>__walls` 节点,viewer 零改动得到墙材质,玻璃保留,且刻意绕过墙体 union。对比图 `mullions_{off,on}_facade.png`(87m F2 幕墙带效果显著)。
|
||||||
|
5. **4#/5# 摆位**:向用户确认"含全部构筑物的可点坐标总平面"尚未拿到——按规范跳过,不造假体量;3# 仍为 ±1m 近似,manifest 注记不变。
|
||||||
|
|
||||||
|
回归测试扩至 **52 项 checks 全绿**(新增墙体 union 8 项、幕墙分格 8 项等)。产出均亲眼验证(浏览器截图 + Blender 渲染对比),无假数据。
|
||||||
|
|
||||||
|
## 交付物
|
||||||
|
|
||||||
|
`outputs/beian_1hao/`:beian_1.glb + beian_1_viewer.html(单楼)、beian_campus.glb + beian_campus_viewer.html(厂区:总平面 + 1# 按定位图摆位)、campus_check.png(摆位俯视校验)、site_manifest.json(各楼摆位配方)、beian_iso.png、beian_previews.png、building_spec.json、campus_spec.json、extract_config.json(t3 模板)、frames_report.md、extraction_audit.md、overlays/(8 层叠图 SVG)。
|
||||||
Reference in New Issue
Block a user