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>
252 lines
13 KiB
Python
252 lines
13 KiB
Python
#!/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())
|