Files
cad-building-showcase/scripts/dwg_dump_json.mjs
zhengwr 6ace84ffba 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>
2026-07-02 17:44:41 +08:00

130 lines
5.0 KiB
JavaScript

#!/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 }))