Deploy browser-only DWG and 3DM reader with private-file isolation
Browse files- PROJECT_README.md +4 -2
- README.md +2 -0
- deploy/SPACE_README.md +2 -0
- src/extrusion.worker.ts +22 -0
- src/geometry.ts +28 -6
- src/main.ts +17 -11
- src/model-viewer.ts +27 -3
- src/style.css +1 -0
- src/types.ts +1 -1
- src/viewer.ts +4 -3
- tests/geometry.test.ts +16 -0
PROJECT_README.md
CHANGED
|
@@ -28,16 +28,18 @@ npm run dev
|
|
| 28 |
|
| 29 |
左侧文件面板自动保存成功读取过的 DWG 和 3DM,刷新或关闭页面后可在同一浏览器、同一地址直接重新打开。历史记录使用 IndexedDB 保留文件副本,最多 10 份、合计 250 MB,超出时移除较早的记录。可单独移除或清空。历史副本反映上次读取的版本,原文件有修改时应重新选择文件;清理浏览器数据也会清除历史,浏览器存储不可用或空间不足时会提示。
|
| 30 |
|
|
|
|
|
|
|
| 31 |
指定示例文件路径保存在被 Git 忽略的 `.local/sample-path.json` 中。双击启动器后首页可直接打开这份文件,文件本身没有复制进项目。开发终端如需同样入口,可以先设置 `$env:DWG_SAMPLE='完整DWG路径'` 再运行 `npm run dev`。
|
| 32 |
|
| 33 |
## 读取范围与限制
|
| 34 |
|
| 35 |
DWG 支持直线、多段线及凸度圆弧、圆、圆弧、椭圆、样条曲线、文字/属性文字、嵌套图块和已有标注图块。处理图块基点、二维旋转缩放、继承图层以及标注图块插入偏移。
|
| 36 |
|
| 37 |
-
3DM 显示文件内的网格、曲线、点、带显示网格的曲面
|
| 38 |
|
| 39 |
- 图案填充目前显示边界;实体填充显示实心区域,多环填充的孔洞可能不精确。
|
| 40 |
-
- WIPEOUT 遮罩、外部图片、三维实体、自定义代理实体
|
| 41 |
- 使用系统中文字体替代 CAD 的 SHX 字体,复杂多行文字的格式、宽度、字间距和线型/线宽可能与 AutoCAD 不一致。
|
| 42 |
- 解析告警和未完整显示的对象会汇总在左下角,点击状态可查看详情;不能将此版本视为 AutoCAD 的精确打印或审图替代品。
|
| 43 |
|
|
|
|
| 28 |
|
| 29 |
左侧文件面板自动保存成功读取过的 DWG 和 3DM,刷新或关闭页面后可在同一浏览器、同一地址直接重新打开。历史记录使用 IndexedDB 保留文件副本,最多 10 份、合计 250 MB,超出时移除较早的记录。可单独移除或清空。历史副本反映上次读取的版本,原文件有修改时应重新选择文件;清理浏览器数据也会清除历史,浏览器存储不可用或空间不足时会提示。
|
| 30 |
|
| 31 |
+
解析结果缓存在当前浏览器页面内,重复打开相同内容可跳过解析;DWG 和 3DM 各保留最近三个文件的解析结果。刷新或关闭页面会清除内存缓存,历史副本仍可重开。缓存和文件都不会发送到服务器。
|
| 32 |
+
|
| 33 |
指定示例文件路径保存在被 Git 忽略的 `.local/sample-path.json` 中。双击启动器后首页可直接打开这份文件,文件本身没有复制进项目。开发终端如需同样入口,可以先设置 `$env:DWG_SAMPLE='完整DWG路径'` 再运行 `npm run dev`。
|
| 34 |
|
| 35 |
## 读取范围与限制
|
| 36 |
|
| 37 |
DWG 支持直线、多段线及凸度圆弧、圆、圆弧、椭圆、样条曲线、文字/属性文字、嵌套图块和已有标注图块。处理图块基点、二维旋转缩放、继承图层以及标注图块插入偏移。
|
| 38 |
|
| 39 |
+
3DM 显示文件内的网格、曲线、点、带显示网格的曲面等对象;没有预存网格的拉伸体可根据轮廓生成近似网格。打开时显示隐藏图层,可在图层面板切换。需要浏览器支持 WebGL。部分 NURBS 曲面没有预存显示网格时无法显示,应在 Rhino 中启用保存显示网格后另存。三维目录反映文件已有对象和组合关系,不自动推断“柜门、柜体”等语义。模型的非嵌入外部纹理或环境资源不会联网读取,材质和灯光与 Rhino 的最终渲染可能不同。
|
| 40 |
|
| 41 |
- 图案填充目前显示边界;实体填充显示实心区域,多环填充的孔洞可能不精确。
|
| 42 |
+
- 布局支持二维正交矩形视口的模型投影与裁剪;透视、倾斜和非矩形裁剪视口暂不支持。WIPEOUT 遮罩、外部图片、三维实体、自定义代理实体尚不支持。缺少外部参照内容时不会自动寻找其他文件。
|
| 43 |
- 使用系统中文字体替代 CAD 的 SHX 字体,复杂多行文字的格式、宽度、字间距和线型/线宽可能与 AutoCAD 不一致。
|
| 44 |
- 解析告警和未完整显示的对象会汇总在左下角,点击状态可查看详情;不能将此版本视为 AutoCAD 的精确打印或审图替代品。
|
| 45 |
|
README.md
CHANGED
|
@@ -22,4 +22,6 @@ short_description: 本机解析 DWG / 3DM,支持结构定位、三维旋转和
|
|
| 22 |
|
| 23 |
支持 100 MB 以内的 DWG / 3DM。部分 CAD 自定义对象、图案填充和没有显示网格的 Rhino 曲面可能不能完整显示;需要时请在 Rhino 中保存显示网格后另存。
|
| 24 |
|
|
|
|
|
|
|
| 25 |
源码及构建说明:[GitHub](https://github.com/delltom2000/dwgreadder)。部署仓库包含同版程序源码与 GPL 许可证,技术说明见 `PROJECT_README.md`。
|
|
|
|
| 22 |
|
| 23 |
支持 100 MB 以内的 DWG / 3DM。部分 CAD 自定义对象、图案填充和没有显示网格的 Rhino 曲面可能不能完整显示;需要时请在 Rhino 中保存显示网格后另存。
|
| 24 |
|
| 25 |
+
相同文件在同一浏览器页面中重复打开时使用本机内存缓存。DWG 布局支持二维正交矩形视口;无显示网格的 3DM 拉伸体按轮廓生成近似网格。
|
| 26 |
+
|
| 27 |
源码及构建说明:[GitHub](https://github.com/delltom2000/dwgreadder)。部署仓库包含同版程序源码与 GPL 许可证,技术说明见 `PROJECT_README.md`。
|
deploy/SPACE_README.md
CHANGED
|
@@ -22,4 +22,6 @@ short_description: 本机解析 DWG / 3DM,支持结构定位、三维旋转和
|
|
| 22 |
|
| 23 |
支持 100 MB 以内的 DWG / 3DM。部分 CAD 自定义对象、图案填充和没有显示网格的 Rhino 曲面可能不能完整显示;需要时请在 Rhino 中保存显示网格后另存。
|
| 24 |
|
|
|
|
|
|
|
| 25 |
源码及构建说明:[GitHub](https://github.com/delltom2000/dwgreadder)。部署仓库包含同版程序源码与 GPL 许可证,技术说明见 `PROJECT_README.md`。
|
|
|
|
| 22 |
|
| 23 |
支持 100 MB 以内的 DWG / 3DM。部分 CAD 自定义对象、图案填充和没有显示网格的 Rhino 曲面可能不能完整显示;需要时请在 Rhino 中保存显示网格后另存。
|
| 24 |
|
| 25 |
+
相同文件在同一浏览器页面中重复打开时使用本机内存缓存。DWG 布局支持二维正交矩形视口;无显示网格的 3DM 拉伸体按轮廓生成近似网格。
|
| 26 |
+
|
| 27 |
源码及构建说明:[GitHub](https://github.com/delltom2000/dwgreadder)。部署仓库包含同版程序源码与 GPL 许可证,技术说明见 `PROJECT_README.md`。
|
src/extrusion.worker.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Decode fallback profiles locally for extrusions lacking Rhino display meshes.
|
| 2 |
+
declare const rhino3dm:(config:unknown)=>Promise<any>;
|
| 3 |
+
self.onmessage=async(e:MessageEvent)=>{
|
| 4 |
+
try{
|
| 5 |
+
const url=new URL(e.data.libraryUrl);importScripts(new URL('rhino3dm.js',url).href);
|
| 6 |
+
const rhino=await rhino3dm({locateFile:(name:string)=>new URL(name,url).href});
|
| 7 |
+
const doc=rhino.File3dm.fromByteArray(new Uint8Array(e.data.buffer)),out:any[]=[];
|
| 8 |
+
for(let i=0;i<doc.objects().count;i++){
|
| 9 |
+
const obj=doc.objects().get(i),g=obj.geometry();if(g.objectType!==rhino.ObjectType.Extrusion)continue;
|
| 10 |
+
const existing=g.getMesh(rhino.MeshType.Any);if(existing){existing.delete();continue;}
|
| 11 |
+
const profiles:any[]=[];
|
| 12 |
+
for(let p=0;p<g.profileCount;p++){
|
| 13 |
+
const start=g.profile3d(p,0),end=g.profile3d(p,1);if(!start||!end)continue;
|
| 14 |
+
const count=Math.min(256,Math.max(64,Math.ceil((start.spanCount||1)*16))),d0=start.domain,d1=end.domain,bottom=[],top=[];
|
| 15 |
+
for(let j=0;j<count;j++){const t=j/count;bottom.push(start.pointAt(d0[0]+(d0[1]-d0[0])*t));top.push(end.pointAt(d1[0]+(d1[1]-d1[0])*t));}
|
| 16 |
+
profiles.push({bottom,top,closed:start.isClosed});start.delete();end.delete();
|
| 17 |
+
}
|
| 18 |
+
const a=obj.attributes();if(profiles.length)out.push({profiles,attributes:{id:a.id,name:a.name,layerIndex:a.layerIndex},bottom:g.isCappedAtBottom,top:g.isCappedAtTop});
|
| 19 |
+
}
|
| 20 |
+
doc.delete();self.postMessage({out});
|
| 21 |
+
}catch(error){self.postMessage({error:error instanceof Error?error.message:String(error)});}
|
| 22 |
+
};
|
src/geometry.ts
CHANGED
|
@@ -61,15 +61,16 @@ export function buildScene(db:any,space='*Model_Space',unknown=0):Scene{
|
|
| 61 |
}else{const key=block?'循环图块':'缺失图块';unsupported[key]=(unsupported[key]||0)+1;}
|
| 62 |
}else if(['TEXT','MTEXT','ATTRIB'].includes(e.type)){
|
| 63 |
const t=e.type==='ATTRIB'?{...e,...e.text}:e,text=cleanText(t.text),h=t.textHeight||1,pos=t.insertionPoint??t.startPoint??{x:0,y:0},a=e.type==='MTEXT'&&t.direction?Math.atan2(t.direction.y,t.direction.x):(t.rotation||0),sx=t.xScale||1;
|
| 64 |
-
const tm:Matrix=multiply(m,[Math.cos(a)*sx,Math.sin(a)*sx,-Math.sin(a),Math.cos(a),pos.x,pos.y]);
|
| 65 |
const lines=text.split('\n'),w=Math.max(...lines.map(s=>Array.from(s).reduce((n,c)=>n+(/[\u2e80-\uffff]/.test(c)?1:0.62),0)))*h;
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
if(e.type==='MTEXT'){const at=t.attachmentPoint||1;x=(at-1)%3===1?-w/2:(at-1)%3===2?-w:0;y=at<=3?-h:at<=6?lines.length*h*.65:lines.length*h*1.3;}
|
| 68 |
else if(t.valign)y=t.valign===2?-h/2:t.valign===3?-h:0;
|
| 69 |
-
if(t.halign&&t.endPoint&&(t.endPoint.x||t.endPoint.y)){const p=transform(t.endPoint,m);tm[4]=p.x;tm[5]=p.y;}
|
| 70 |
const textMatrix=multiply(tm,[1,0,0,1,x,y]);
|
| 71 |
const corners=[{x:0,y:h},{x:w,y:h},{x:w,y:-h*1.3*(lines.length-1)},{x:0,y:-h*1.3*(lines.length-1)}].map(p=>transform(p,textMatrix));
|
| 72 |
-
parent=identity;add(corners,false,false,text,h,textMatrix);item.label=text.replace(/\n/g,' ');
|
| 73 |
}else{
|
| 74 |
let points:Point[]=[],closed=false,fill=false;
|
| 75 |
switch(e.type){
|
|
@@ -98,7 +99,7 @@ export function buildScene(db:any,space='*Model_Space',unknown=0):Scene{
|
|
| 98 |
}add(contour,true,!!e.solidFill);
|
| 99 |
}
|
| 100 |
}if(!e.solidFill)unsupported['图案填充仅显示边界']=(unsupported['图案填充仅显示边界']||0)+1;break;
|
| 101 |
-
case 'VIEWPORT':
|
| 102 |
case 'SEQEND':return null;
|
| 103 |
default:unsupported[e.type]=(unsupported[e.type]||0)+1;
|
| 104 |
}
|
|
@@ -108,6 +109,27 @@ export function buildScene(db:any,space='*Model_Space',unknown=0):Scene{
|
|
| 108 |
}
|
| 109 |
const model=blocks.get(space),roots=model?.entities??db.entities.filter((e:any)=>!e.isInPaperSpace);
|
| 110 |
for(const e of roots){if(e.type==='ATTRIB')continue;const n=visit(e,identity);if(n)items.push(n);}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
const bounds=emptyBounds();items.forEach(n=>union(bounds,n.bounds));const used=new Set(primitives.map(p=>p.layer));
|
| 112 |
-
return{primitives,items,bounds,space,spaces:[...blocks.
|
| 113 |
}
|
|
|
|
| 61 |
}else{const key=block?'循环图块':'缺失图块';unsupported[key]=(unsupported[key]||0)+1;}
|
| 62 |
}else if(['TEXT','MTEXT','ATTRIB'].includes(e.type)){
|
| 63 |
const t=e.type==='ATTRIB'?{...e,...e.text}:e,text=cleanText(t.text),h=t.textHeight||1,pos=t.insertionPoint??t.startPoint??{x:0,y:0},a=e.type==='MTEXT'&&t.direction?Math.atan2(t.direction.y,t.direction.x):(t.rotation||0),sx=t.xScale||1;
|
|
|
|
| 64 |
const lines=text.split('\n'),w=Math.max(...lines.map(s=>Array.from(s).reduce((n,c)=>n+(/[\u2e80-\uffff]/.test(c)?1:0.62),0)))*h;
|
| 65 |
+
const fit=(t.halign===3||t.halign===5)&&t.startPoint&&t.endPoint&&w>0,dx=fit?t.endPoint.x-t.startPoint.x:0,dy=fit?t.endPoint.y-t.startPoint.y:0,distance=Math.hypot(dx,dy),angle=fit&&distance?Math.atan2(dy,dx):a,scaleX=fit&&distance?distance/w:sx,scaleY=fit&&distance&&t.halign===3?scaleX:1;
|
| 66 |
+
const tm:Matrix=multiply(m,[Math.cos(angle)*scaleX,Math.sin(angle)*scaleX,-Math.sin(angle)*scaleY,Math.cos(angle)*scaleY,pos.x,pos.y]);
|
| 67 |
+
let x=t.halign===1||t.halign===4?-w/2:t.halign===2?-w:0,y=t.halign===4?-h/2:0;
|
| 68 |
if(e.type==='MTEXT'){const at=t.attachmentPoint||1;x=(at-1)%3===1?-w/2:(at-1)%3===2?-w:0;y=at<=3?-h:at<=6?lines.length*h*.65:lines.length*h*1.3;}
|
| 69 |
else if(t.valign)y=t.valign===2?-h/2:t.valign===3?-h:0;
|
| 70 |
+
if(!fit&&(t.halign||t.valign)&&t.endPoint&&(t.endPoint.x||t.endPoint.y)){const p=transform(t.endPoint,m);tm[4]=p.x;tm[5]=p.y;}
|
| 71 |
const textMatrix=multiply(tm,[1,0,0,1,x,y]);
|
| 72 |
const corners=[{x:0,y:h},{x:w,y:h},{x:w,y:-h*1.3*(lines.length-1)},{x:0,y:-h*1.3*(lines.length-1)}].map(p=>transform(p,textMatrix));
|
| 73 |
+
parent=identity;add(corners,false,false,text,h,textMatrix);const primitive=primitives[item.primitives[0]];if(primitive){primitive.textAlign=x===0?'left':x===-w/2?'center':'right';primitive.textOffsetX=x;if(fit&&distance)primitive.textFitWidth=w;}item.label=text.replace(/\n/g,' ');
|
| 74 |
}else{
|
| 75 |
let points:Point[]=[],closed=false,fill=false;
|
| 76 |
switch(e.type){
|
|
|
|
| 99 |
}add(contour,true,!!e.solidFill);
|
| 100 |
}
|
| 101 |
}if(!e.solidFill)unsupported['图案填充仅显示边界']=(unsupported['图案填充仅显示边界']||0)+1;break;
|
| 102 |
+
case 'VIEWPORT':return null;
|
| 103 |
case 'SEQEND':return null;
|
| 104 |
default:unsupported[e.type]=(unsupported[e.type]||0)+1;
|
| 105 |
}
|
|
|
|
| 109 |
}
|
| 110 |
const model=blocks.get(space),roots=model?.entities??db.entities.filter((e:any)=>!e.isInPaperSpace);
|
| 111 |
for(const e of roots){if(e.type==='ATTRIB')continue;const n=visit(e,identity);if(n)items.push(n);}
|
| 112 |
+
// Paper-space viewports are windows into model space, not independent geometry.
|
| 113 |
+
const viewports=roots.filter((e:any)=>e.type==='VIEWPORT'&&e.viewportId>1&&e.status>0&&!(e.statusBitFlags&131072));
|
| 114 |
+
if(viewports.length){
|
| 115 |
+
const modelName=[...blocks.keys()].find(n=>/^\*model_space$/i.test(n));
|
| 116 |
+
const source=modelName?buildScene(db,modelName,unknown):null;
|
| 117 |
+
if(source)for(const vp of viewports){
|
| 118 |
+
if(!vp.width||!vp.height||!vp.viewHeight||!vp.displayCenter||!vp.viewportCenter)continue;
|
| 119 |
+
if((vp.statusBitFlags&65537)||Math.abs(vp.viewDirection?.x||0)>1e-7||Math.abs(vp.viewDirection?.y||0)>1e-7||(vp.viewDirection?.z??1)<0){unsupported['不支持的视口投影']=(unsupported['不支持的视口投影']||0)+1;continue;}
|
| 120 |
+
const s=vp.height/vp.viewHeight,a=-(vp.viewTwistAngle||0),cs=Math.cos(a)*s,sn=Math.sin(a)*s,center=vp.displayCenter,target=vp.targetPoint??{x:0,y:0};
|
| 121 |
+
const matrix:Matrix=[cs,sn,-sn,cs,vp.viewportCenter.x-cs*(center.x+target.x)+sn*(center.y+target.y),vp.viewportCenter.y-sn*(center.x+target.x)-cs*(center.y+target.y)];
|
| 122 |
+
const clip:Bounds={minX:vp.viewportCenter.x-vp.width/2,maxX:vp.viewportCenter.x+vp.width/2,minY:vp.viewportCenter.y-vp.height/2,maxY:vp.viewportCenter.y+vp.height/2};
|
| 123 |
+
const frozen=new Set(vp.frozenLayerIds??[]),id=`n${++seq}`,group:Item={id,label:`视口 ${vp.viewportId}`,type:'VIEWPORT',layer:vp.layer||'0',bounds:emptyBounds(),children:[],primitives:[]};
|
| 124 |
+
for(const p of source.primitives){
|
| 125 |
+
if(frozen.has(layerMap.get(p.layer)?.handle))continue;
|
| 126 |
+
const corners=[{x:p.bounds.minX,y:p.bounds.minY},{x:p.bounds.maxX,y:p.bounds.minY},{x:p.bounds.maxX,y:p.bounds.maxY},{x:p.bounds.minX,y:p.bounds.maxY}].map(v=>transform(v,matrix)),b=emptyBounds();for(const v of corners)union(b,{minX:v.x,minY:v.y,maxX:v.x,maxY:v.y});
|
| 127 |
+
b.minX=Math.max(b.minX,clip.minX);b.minY=Math.max(b.minY,clip.minY);b.maxX=Math.min(b.maxX,clip.maxX);b.maxY=Math.min(b.maxY,clip.maxY);if(b.minX>b.maxX||b.minY>b.maxY)continue;
|
| 128 |
+
group.primitives.push(primitives.length);primitives.push({...p,points:p.points.map(v=>transform(v,matrix)),matrix:p.matrix?multiply(matrix,p.matrix):undefined,bounds:b,clip,node:id});union(group.bounds,b);
|
| 129 |
+
}
|
| 130 |
+
if(valid(group.bounds))items.push(group);
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
const bounds=emptyBounds();items.forEach(n=>union(bounds,n.bounds));const used=new Set(primitives.map(p=>p.layer));
|
| 134 |
+
return{primitives,items,bounds,space,spaces:[...blocks.values()].filter(b=>/^\*.*space/i.test(b.name)&&((b.entities?.length??0)>0||b.name===space||/^\*model_space$/i.test(b.name))).map(b=>b.name),layers:[...layerMap.values()].filter(l=>used.has(l.name)).map(l=>({name:l.name,color:aci(l.colorIndex),off:!!(l.off||l.frozen)})),unsupported,unknown};
|
| 135 |
}
|
src/main.ts
CHANGED
|
@@ -29,6 +29,7 @@ $('file-history-host').append($('history-list'));
|
|
| 29 |
document.querySelector('.header-actions')!.insertAdjacentHTML('afterbegin','<button id="toggle-files" class="panel-toggle" aria-label="展开或收起文件面板" title="展开或收起文件面板" aria-expanded="true">☰</button>');
|
| 30 |
document.querySelector('.header-actions')!.insertAdjacentHTML('beforeend','<button id="toggle-properties" class="panel-toggle" aria-label="展开或收起属性面板" title="展开或收起属性面板" aria-expanded="true">◧</button>');
|
| 31 |
$('canvas').insertAdjacentHTML('afterend','<div id="model-host" hidden></div>');
|
|
|
|
| 32 |
$('file').setAttribute('accept','.dwg,.3dm');document.querySelector('.brand-sub')!.textContent='DWG / 3DM';
|
| 33 |
$('file-name').textContent='图纸与模型阅读器';$('stats').textContent='DWG 二维 / 3DM 三维';
|
| 34 |
document.querySelector('h1')!.textContent='从图纸,到空间。';
|
|
@@ -39,6 +40,7 @@ document.querySelector('.history-note')!.textContent='历史副本保存在当
|
|
| 39 |
let mode:'dwg'|'3dm'='dwg',model:ModelViewer|null=null,modelController:AbortController|null=null,activeFile:File|null=null;
|
| 40 |
const viewer=new Viewer($<HTMLCanvasElement>('canvas'));
|
| 41 |
let scene:Scene|null=null,worker:Worker|null=null,tab='layers',busy=false,fileName='',timer:ReturnType<typeof setTimeout>|null=null,requestId=0;
|
|
|
|
| 42 |
const nodes=new Map<string,Item>();let allNodes:Item[]=[];
|
| 43 |
let pendingHistoryFile:File|null=null;
|
| 44 |
viewer.onChange=()=>{if(mode==='dwg')$('zoom-label').textContent=scene?`1 px ≈ ${(1/viewer.scale).toLocaleString('zh-CN',{maximumFractionDigits:2})} 图纸单位`: '—';};
|
|
@@ -53,36 +55,40 @@ function showProperties(rows:[string,string][]){const root=$('properties');root.
|
|
| 53 |
const number=(n:number)=>n.toLocaleString('zh-CN',{maximumFractionDigits:2});
|
| 54 |
function fileProperties(){if(activeFile)showProperties([['文件',activeFile.name],['格式',mode==='3dm'?'Rhino 3DM · 三维':'AutoCAD DWG · 二维'],['大小',`${(activeFile.size/1024/1024).toFixed(2)} MB`],['操作',mode==='3dm'?'旋转 / 平移 / 部件聚焦':'平移 / 缩放 / 对象定位']]);}
|
| 55 |
function toast(message:string){$('toast').textContent=message;$('toast').hidden=false;setTimeout(()=>$('toast').hidden=true,7000);}
|
| 56 |
-
function loading(value:boolean){busy=value;$('loading').hidden=!value;$<HTMLButtonElement>('open').disabled=value;$<HTMLButtonElement>('recent').disabled=value;$<HTMLSelectElement>('spaces').disabled=value;}
|
| 57 |
function failure(message:string){pendingHistoryFile=null;loading(false);if(timer)clearTimeout(timer);toast(message);$('status').textContent=activeFile?'读取失败 · 保留当前文件':'读取失败';$('status-dot').classList.add('warn');}
|
| 58 |
-
function
|
|
|
|
|
|
|
| 59 |
if(e.data.progress)$('progress').textContent=e.data.progress;
|
| 60 |
if(e.data.error)failure(e.data.error);
|
| 61 |
-
if(e.data.scene){if(timer)clearTimeout(timer);scene=e.data.scene;loading(false);nodes.clear();allNodes=[];
|
| 62 |
const walk=(items:Item[])=>items.forEach(n=>{nodes.set(n.id,n);allNodes.push(n);walk(n.children);});walk(scene!.items);
|
| 63 |
setMode('dwg');model?.clear();viewer.load(scene!);$('welcome').hidden=true;$('file-name').textContent=fileName;$('file-name').title=fileName;
|
| 64 |
if(pendingHistoryFile){const savedFile=pendingHistoryFile;activeFile=savedFile;pendingHistoryFile=null;void rememberDrawing(savedFile).then(renderHistory).catch(()=>toast('文件已打开,但浏览器未能保存历史副本。'));}fileProperties();
|
| 65 |
$('drawing-state').textContent='只读预览';$('space-label').textContent=scene!.space.toLowerCase().includes('model')?'模型空间':'布局空间';$('item-count').textContent=allNodes.length.toLocaleString();
|
| 66 |
-
const spaces=$<HTMLSelectElement>('spaces');spaces.replaceChildren(...scene!.spaces.map(s=>{const o=document.createElement('option');o.value=s;o.textContent=s.toLowerCase().includes('model')?'模型空间':`布局空间 · ${s}`;return o;}));spaces.value=scene!.space;spaces.hidden=
|
|
|
|
| 67 |
const unsupported=Object.entries(scene!.unsupported),missing=unsupported.reduce((n,[,v])=>n+v,0)+scene!.unknown;
|
| 68 |
$('status').textContent=missing?`已读取 · ${missing} 项兼容提示`:(scene!.warnings?.length?'已读取 · 有兼容提示':'已读取');$('status').title=unsupported.map(([t,n])=>`${t}:${n}`).join(';')+(scene!.unknown?`;解析器未知对象:${scene!.unknown}`:'')+(scene!.warnings?.length?`;DWG 解析告警:${scene!.warnings.join(', ')},部分自定义对象可能不完整`:'');$('status-dot').classList.toggle('warn',!!missing||!!scene!.warnings?.length);
|
| 69 |
$('stats').textContent=`${scene!.items.length.toLocaleString()} 个顶层对象 · ${scene!.layers.length} 个可见图层 · ${scene!.primitives.length.toLocaleString()} 个图元`;
|
| 70 |
$('selection').hidden=true;renderTree();if(!valid(scene!.bounds))toast('当前空间没有可显示的图形,请切换空间。');
|
| 71 |
}
|
| 72 |
};worker.onerror=e=>failure(`解析失败:${e.message||'解析器异常,请重新打开文件'}`);return worker;}
|
| 73 |
-
function timeout(){if(timer)clearTimeout(timer);timer=setTimeout(()=>{requestId++;
|
| 74 |
async function openFile(file:File){if(busy)return;if(!/\.(dwg|3dm)$/i.test(file.name)){toast('请选择 DWG 图纸或 3DM 模型。');return;}if(file.size>100*1024*1024){toast('当前版本支持 100 MB 以内的文件。');return;}
|
| 75 |
const current=++requestId;loading(true);$('progress').textContent='正在读取文件…';timeout();try{
|
| 76 |
const buffer=await file.arrayBuffer();if(current!==requestId)return;const isModel=/\.3dm$/i.test(file.name),header=new TextDecoder().decode(buffer.slice(0,32));
|
| 77 |
if(isModel?!header.startsWith('3D Geometry File Format'):!header.startsWith('AC10'))throw new Error('文件头与格式不匹配,请确认文件未损坏。');
|
|
|
|
| 78 |
fileName=file.name;pendingHistoryFile=file;
|
| 79 |
-
if(!isModel){makeWorker().postMessage({buffer,wasmUrl:new URL('./',location.href).href},[buffer]);return;}
|
| 80 |
$('progress').textContent='正在解析 3DM 几何与部件…';modelController=new AbortController();const signal=modelController.signal;
|
| 81 |
if(!model){const module=await import('./model-viewer');if(current!==requestId)return;model=new module.ModelViewer($('model-host'));model.onSelect=part=>selectedModel(part,false);model.onChange=()=>{if(mode==='3dm')$('zoom-label').textContent='3DM · 透视视图';};}
|
| 82 |
-
await model.load(buffer,signal);if(current!==requestId)return;if(timer)clearTimeout(timer);worker
|
| 83 |
activeFile=file;pendingHistoryFile=null;void rememberDrawing(file).then(renderHistory).catch(()=>toast('模型已打开,但未能保存历史副本。'));
|
| 84 |
-
$('welcome').hidden=true;$('file-name').textContent=file.name;$('file-name').title=file.name;fileProperties();$('spaces').hidden=true;$('space-label').textContent='3DM · 三维模型';$('drawing-state').textContent='只读预览';$('item-count').textContent=model.parts.length.toLocaleString();
|
| 85 |
-
$('stats').textContent=`${model.parts.length.toLocaleString()} 个对象 · ${model.layers.length} 个图层`;$('status').textContent=model.warnings.length?`已读取 · ${model.warnings.length} 项兼容提示`:'已读取';$('status').title=model.warnings.length?'部分对象没有显示网格或暂不支持,可能未完整显示。请在 Rhino 中保存显示网格后重试。':'';$('status-dot').classList.toggle('warn',!!model.warnings.length);loading(false);renderTree();
|
| 86 |
}catch(e){if(current===requestId)failure(e instanceof Error?e.message:String(e));}
|
| 87 |
}
|
| 88 |
function indexes(item:Item):number[]{return[...item.primitives,...item.children.flatMap(indexes)];}
|
|
@@ -115,13 +121,13 @@ function renderTree(){
|
|
| 115 |
}
|
| 116 |
$('open').onclick=$('choose').onclick=()=>$<HTMLInputElement>('file').click();
|
| 117 |
$<HTMLInputElement>('file').onchange=e=>{const input=e.target as HTMLInputElement;if(input.files?.[0])void openFile(input.files[0]);input.value='';};
|
| 118 |
-
$('cancel').onclick=()=>{requestId++;pendingHistoryFile=null;modelController?.abort();
|
| 119 |
$('zoom-in').onclick=()=>mode==='3dm'?model?.zoom(1.4):viewer.zoom(1.4);$('zoom-out').onclick=()=>mode==='3dm'?model?.zoom(1/1.4):viewer.zoom(1/1.4);$('fit').onclick=()=>{if(mode==='3dm'){model?.fit();$('selection').hidden=true;fileProperties();}else viewer.fit();};
|
| 120 |
$('clear-selection').onclick=()=>{if(mode==='3dm')model?.clearSelection();else{viewer.selected.clear();viewer.selection=null;viewer.draw();}$('selection').hidden=true;fileProperties();};
|
| 121 |
$('status').onclick=()=>{if($('status').title)toast($('status').title);};
|
| 122 |
$<HTMLInputElement>('search').oninput=()=>renderTree();
|
| 123 |
document.querySelectorAll<HTMLButtonElement>('[data-tab]').forEach(b=>b.onclick=()=>{tab=b.dataset.tab!;document.querySelectorAll('[data-tab]').forEach(t=>t.setAttribute('aria-selected',String(t===b)));renderTree();});
|
| 124 |
-
$<HTMLSelectElement>('spaces').onchange=e=>{if(!worker||busy)return;loading(true);
|
| 125 |
document.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='o'){e.preventDefault();if(!busy)$<HTMLInputElement>('file').click();}if(e.key==='/'&&!(e.target instanceof HTMLInputElement)){e.preventDefault();$('search').focus();}});
|
| 126 |
let dragDepth=0;window.addEventListener('dragenter',e=>{e.preventDefault();dragDepth++;if(!busy)$('drop-mask').classList.add('visible');});window.addEventListener('dragover',e=>e.preventDefault());window.addEventListener('dragleave',()=>{dragDepth=Math.max(0,dragDepth-1);if(!dragDepth)$('drop-mask').classList.remove('visible');});window.addEventListener('drop',e=>{e.preventDefault();dragDepth=0;$('drop-mask').classList.remove('visible');if(e.dataTransfer?.files[0])void openFile(e.dataTransfer.files[0]);});
|
| 127 |
fetch('/api/sample-info').then(r=>r.ok?r.json():null).then(info=>{if(!info)return;$('sample').hidden=false;$('sample').onclick=async()=>{try{const r=await fetch('/api/sample');if(!r.ok)throw new Error('读取示例失败');await openFile(new File([await r.arrayBuffer()],info.name,{lastModified:0}));}catch(e){toast(String(e));}};}).catch(()=>{});
|
|
|
|
| 29 |
document.querySelector('.header-actions')!.insertAdjacentHTML('afterbegin','<button id="toggle-files" class="panel-toggle" aria-label="展开或收起文件面板" title="展开或收起文件面板" aria-expanded="true">☰</button>');
|
| 30 |
document.querySelector('.header-actions')!.insertAdjacentHTML('beforeend','<button id="toggle-properties" class="panel-toggle" aria-label="展开或收起属性面板" title="展开或收起属性面板" aria-expanded="true">◧</button>');
|
| 31 |
$('canvas').insertAdjacentHTML('afterend','<div id="model-host" hidden></div>');
|
| 32 |
+
$('spaces').insertAdjacentHTML('afterend','<div id="space-buttons" class="space-buttons" role="group" aria-label="切换图纸空间" hidden></div>');
|
| 33 |
$('file').setAttribute('accept','.dwg,.3dm');document.querySelector('.brand-sub')!.textContent='DWG / 3DM';
|
| 34 |
$('file-name').textContent='图纸与模型阅读器';$('stats').textContent='DWG 二维 / 3DM 三维';
|
| 35 |
document.querySelector('h1')!.textContent='从图纸,到空间。';
|
|
|
|
| 40 |
let mode:'dwg'|'3dm'='dwg',model:ModelViewer|null=null,modelController:AbortController|null=null,activeFile:File|null=null;
|
| 41 |
const viewer=new Viewer($<HTMLCanvasElement>('canvas'));
|
| 42 |
let scene:Scene|null=null,worker:Worker|null=null,tab='layers',busy=false,fileName='',timer:ReturnType<typeof setTimeout>|null=null,requestId=0;
|
| 43 |
+
const drawingCache=new Map<string,{worker:Worker;scenes:Map<string,Scene>}>();let drawingKey='';
|
| 44 |
const nodes=new Map<string,Item>();let allNodes:Item[]=[];
|
| 45 |
let pendingHistoryFile:File|null=null;
|
| 46 |
viewer.onChange=()=>{if(mode==='dwg')$('zoom-label').textContent=scene?`1 px ≈ ${(1/viewer.scale).toLocaleString('zh-CN',{maximumFractionDigits:2})} 图纸单位`: '—';};
|
|
|
|
| 55 |
const number=(n:number)=>n.toLocaleString('zh-CN',{maximumFractionDigits:2});
|
| 56 |
function fileProperties(){if(activeFile)showProperties([['文件',activeFile.name],['格式',mode==='3dm'?'Rhino 3DM · 三维':'AutoCAD DWG · 二维'],['大小',`${(activeFile.size/1024/1024).toFixed(2)} MB`],['操作',mode==='3dm'?'旋转 / 平移 / 部件聚焦':'平移 / 缩放 / 对象定位']]);}
|
| 57 |
function toast(message:string){$('toast').textContent=message;$('toast').hidden=false;setTimeout(()=>$('toast').hidden=true,7000);}
|
| 58 |
+
function loading(value:boolean){busy=value;$('loading').hidden=!value;$<HTMLButtonElement>('open').disabled=value;$<HTMLButtonElement>('recent').disabled=value;$<HTMLSelectElement>('spaces').disabled=value;document.querySelectorAll<HTMLButtonElement>('#space-buttons button').forEach(button=>button.disabled=value);}
|
| 59 |
function failure(message:string){pendingHistoryFile=null;loading(false);if(timer)clearTimeout(timer);toast(message);$('status').textContent=activeFile?'读取失败 · 保留当前文件':'读取失败';$('status-dot').classList.add('warn');}
|
| 60 |
+
function discardWorker(){if(worker){worker.terminate();for(const [key,entry] of drawingCache)if(entry.worker===worker)drawingCache.delete(key);worker=null;}}
|
| 61 |
+
function makeWorker(key:string){worker=new Worker(new URL('./parser.worker.ts',import.meta.url),{type:'module'});const owned=worker,entry={worker:owned,scenes:new Map<string,Scene>()};drawingCache.set(key,entry);while(drawingCache.size>3){const oldest=drawingCache.keys().next().value!;drawingCache.get(oldest)!.worker.terminate();drawingCache.delete(oldest);}worker.onmessage=e=>{
|
| 62 |
+
if(worker!==owned)return;
|
| 63 |
if(e.data.progress)$('progress').textContent=e.data.progress;
|
| 64 |
if(e.data.error)failure(e.data.error);
|
| 65 |
+
if(e.data.scene){if(timer)clearTimeout(timer);scene=e.data.scene;entry.scenes.set(scene!.space,scene!);loading(false);nodes.clear();allNodes=[];
|
| 66 |
const walk=(items:Item[])=>items.forEach(n=>{nodes.set(n.id,n);allNodes.push(n);walk(n.children);});walk(scene!.items);
|
| 67 |
setMode('dwg');model?.clear();viewer.load(scene!);$('welcome').hidden=true;$('file-name').textContent=fileName;$('file-name').title=fileName;
|
| 68 |
if(pendingHistoryFile){const savedFile=pendingHistoryFile;activeFile=savedFile;pendingHistoryFile=null;void rememberDrawing(savedFile).then(renderHistory).catch(()=>toast('文件已打开,但浏览器未能保存历史副本。'));}fileProperties();
|
| 69 |
$('drawing-state').textContent='只读预览';$('space-label').textContent=scene!.space.toLowerCase().includes('model')?'模型空间':'布局空间';$('item-count').textContent=allNodes.length.toLocaleString();
|
| 70 |
+
const spaces=$<HTMLSelectElement>('spaces');spaces.replaceChildren(...scene!.spaces.map(s=>{const o=document.createElement('option');o.value=s;o.textContent=s.toLowerCase().includes('model')?'模型空间':`布局空间 · ${s}`;return o;}));spaces.value=scene!.space;spaces.hidden=true;
|
| 71 |
+
const buttons=$('space-buttons');buttons.replaceChildren(...scene!.spaces.map((s,i)=>{const b=document.createElement('button');b.textContent=/model/i.test(s)?'模型空间':scene!.spaces.filter(n=>!/model/i.test(n)).length>1?`布局 ${i+1}`:'布局空间';b.setAttribute('aria-pressed',String(s===scene!.space));b.onclick=()=>{spaces.value=s;spaces.dispatchEvent(new Event('change'));};return b;}));buttons.hidden=scene!.spaces.length<2;
|
| 72 |
const unsupported=Object.entries(scene!.unsupported),missing=unsupported.reduce((n,[,v])=>n+v,0)+scene!.unknown;
|
| 73 |
$('status').textContent=missing?`已读取 · ${missing} 项兼容提示`:(scene!.warnings?.length?'已读取 · 有兼容提示':'已读取');$('status').title=unsupported.map(([t,n])=>`${t}:${n}`).join(';')+(scene!.unknown?`;解析器未知对象:${scene!.unknown}`:'')+(scene!.warnings?.length?`;DWG 解析告警:${scene!.warnings.join(', ')},部分自定义对象可能不完整`:'');$('status-dot').classList.toggle('warn',!!missing||!!scene!.warnings?.length);
|
| 74 |
$('stats').textContent=`${scene!.items.length.toLocaleString()} 个顶层对象 · ${scene!.layers.length} 个可见图层 · ${scene!.primitives.length.toLocaleString()} 个图元`;
|
| 75 |
$('selection').hidden=true;renderTree();if(!valid(scene!.bounds))toast('当前空间没有可显示的图形,请切换空间。');
|
| 76 |
}
|
| 77 |
};worker.onerror=e=>failure(`解析失败:${e.message||'解析器异常,请重新打开文件'}`);return worker;}
|
| 78 |
+
function timeout(){if(timer)clearTimeout(timer);timer=setTimeout(()=>{requestId++;discardWorker();modelController?.abort();failure('读取超过 120 秒,已停止。请尝试较小文件,或在原软件中保存显示网格后重试。');},120000);}
|
| 79 |
async function openFile(file:File){if(busy)return;if(!/\.(dwg|3dm)$/i.test(file.name)){toast('请选择 DWG 图纸或 3DM 模型。');return;}if(file.size>100*1024*1024){toast('当前版本支持 100 MB 以内的文件。');return;}
|
| 80 |
const current=++requestId;loading(true);$('progress').textContent='正在读取文件…';timeout();try{
|
| 81 |
const buffer=await file.arrayBuffer();if(current!==requestId)return;const isModel=/\.3dm$/i.test(file.name),header=new TextDecoder().decode(buffer.slice(0,32));
|
| 82 |
if(isModel?!header.startsWith('3D Geometry File Format'):!header.startsWith('AC10'))throw new Error('文件头与格式不匹配,请确认文件未损坏。');
|
| 83 |
+
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',buffer)),b=>b.toString(16).padStart(2,'0')).join('');if(current!==requestId)return;
|
| 84 |
fileName=file.name;pendingHistoryFile=file;
|
| 85 |
+
if(!isModel){drawingKey=hash;const cached=drawingCache.get(hash);if(cached){drawingCache.delete(hash);drawingCache.set(hash,cached);worker=cached.worker;const existing=cached.scenes.get('*Model_Space')??cached.scenes.values().next().value;if(existing){worker.onmessage!(new MessageEvent('message',{data:{scene:existing}}));$('status').textContent+=' · 本机缓存';}else worker.postMessage({});}else makeWorker(hash).postMessage({buffer,wasmUrl:new URL('./',location.href).href},[buffer]);return;}
|
| 86 |
$('progress').textContent='正在解析 3DM 几何与部件…';modelController=new AbortController();const signal=modelController.signal;
|
| 87 |
if(!model){const module=await import('./model-viewer');if(current!==requestId)return;model=new module.ModelViewer($('model-host'));model.onSelect=part=>selectedModel(part,false);model.onChange=()=>{if(mode==='3dm')$('zoom-label').textContent='3DM · 透视视图';};}
|
| 88 |
+
const fromCache=await model.load(buffer,signal,hash);if(current!==requestId)return;if(timer)clearTimeout(timer);worker=null;scene=null;allNodes=[];nodes.clear();setMode('3dm');
|
| 89 |
activeFile=file;pendingHistoryFile=null;void rememberDrawing(file).then(renderHistory).catch(()=>toast('模型已打开,但未能保存历史副本。'));
|
| 90 |
+
$('welcome').hidden=true;$('file-name').textContent=file.name;$('file-name').title=file.name;fileProperties();$('spaces').hidden=true;$('space-buttons').hidden=true;$('space-label').textContent='3DM · 三维模型';$('drawing-state').textContent='只读预览';$('item-count').textContent=model.parts.length.toLocaleString();
|
| 91 |
+
$('stats').textContent=`${model.parts.length.toLocaleString()} 个对象 · ${model.layers.length} 个图层`;$('status').textContent=(model.warnings.length?`已读取 · ${model.warnings.length} 项兼容提示`:'已读取')+(fromCache?' · 本机缓存':'');$('status').title=model.warnings.length?'部分对象没有显示网格或暂不支持,可能未完整显示。请在 Rhino 中保存显示网格后重试。':'';$('status-dot').classList.toggle('warn',!!model.warnings.length);loading(false);renderTree();
|
| 92 |
}catch(e){if(current===requestId)failure(e instanceof Error?e.message:String(e));}
|
| 93 |
}
|
| 94 |
function indexes(item:Item):number[]{return[...item.primitives,...item.children.flatMap(indexes)];}
|
|
|
|
| 121 |
}
|
| 122 |
$('open').onclick=$('choose').onclick=()=>$<HTMLInputElement>('file').click();
|
| 123 |
$<HTMLInputElement>('file').onchange=e=>{const input=e.target as HTMLInputElement;if(input.files?.[0])void openFile(input.files[0]);input.value='';};
|
| 124 |
+
$('cancel').onclick=()=>{requestId++;pendingHistoryFile=null;modelController?.abort();discardWorker();if(timer)clearTimeout(timer);loading(false);$('status').textContent=activeFile?'已取消 · 保留当前文件':'已取消';};
|
| 125 |
$('zoom-in').onclick=()=>mode==='3dm'?model?.zoom(1.4):viewer.zoom(1.4);$('zoom-out').onclick=()=>mode==='3dm'?model?.zoom(1/1.4):viewer.zoom(1/1.4);$('fit').onclick=()=>{if(mode==='3dm'){model?.fit();$('selection').hidden=true;fileProperties();}else viewer.fit();};
|
| 126 |
$('clear-selection').onclick=()=>{if(mode==='3dm')model?.clearSelection();else{viewer.selected.clear();viewer.selection=null;viewer.draw();}$('selection').hidden=true;fileProperties();};
|
| 127 |
$('status').onclick=()=>{if($('status').title)toast($('status').title);};
|
| 128 |
$<HTMLInputElement>('search').oninput=()=>renderTree();
|
| 129 |
document.querySelectorAll<HTMLButtonElement>('[data-tab]').forEach(b=>b.onclick=()=>{tab=b.dataset.tab!;document.querySelectorAll('[data-tab]').forEach(t=>t.setAttribute('aria-selected',String(t===b)));renderTree();});
|
| 130 |
+
$<HTMLSelectElement>('spaces').onchange=e=>{if(!worker||busy)return;loading(true);const space=(e.target as HTMLSelectElement).value,cached=drawingCache.get(drawingKey)?.scenes.get(space);if(cached){worker.onmessage!(new MessageEvent('message',{data:{scene:cached}}));$('status').textContent+=' · 本机缓存';}else{worker.postMessage({space});timeout();}};
|
| 131 |
document.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='o'){e.preventDefault();if(!busy)$<HTMLInputElement>('file').click();}if(e.key==='/'&&!(e.target instanceof HTMLInputElement)){e.preventDefault();$('search').focus();}});
|
| 132 |
let dragDepth=0;window.addEventListener('dragenter',e=>{e.preventDefault();dragDepth++;if(!busy)$('drop-mask').classList.add('visible');});window.addEventListener('dragover',e=>e.preventDefault());window.addEventListener('dragleave',()=>{dragDepth=Math.max(0,dragDepth-1);if(!dragDepth)$('drop-mask').classList.remove('visible');});window.addEventListener('drop',e=>{e.preventDefault();dragDepth=0;$('drop-mask').classList.remove('visible');if(e.dataTransfer?.files[0])void openFile(e.dataTransfer.files[0]);});
|
| 133 |
fetch('/api/sample-info').then(r=>r.ok?r.json():null).then(info=>{if(!info)return;$('sample').hidden=false;$('sample').onclick=async()=>{try{const r=await fetch('/api/sample');if(!r.ok)throw new Error('读取示例失败');await openFile(new File([await r.arrayBuffer()],info.name,{lastModified:0}));}catch(e){toast(String(e));}};}).catch(()=>{});
|
src/model-viewer.ts
CHANGED
|
@@ -12,6 +12,7 @@ export class ModelViewer{
|
|
| 12 |
onSelect:(part:ModelPart)=>void=()=>{};onChange:()=>void=()=>{};
|
| 13 |
private objectParts=new Map<THREE.Object3D,ModelPart>();private frame=0;private active=false;
|
| 14 |
private originalMaterials=new Map<THREE.Object3D,THREE.Material|THREE.Material[]>();
|
|
|
|
| 15 |
private helper:THREE.Box3Helper|null=null;
|
| 16 |
private animation:{start:number;from:THREE.Vector3;to:THREE.Vector3;targetFrom:THREE.Vector3;targetTo:THREE.Vector3}|null=null;
|
| 17 |
constructor(readonly host:HTMLElement){
|
|
@@ -31,7 +32,10 @@ export class ModelViewer{
|
|
| 31 |
this.renderer.domElement.addEventListener('keydown',e=>{if(e.key==='Home'||e.key.toLowerCase()==='f'){e.preventDefault();this.fit();}if(e.key==='Escape')this.clearSelection();if(e.key==='+'||e.key==='=')this.zoom(1.3);if(e.key==='-')this.zoom(1/1.3);});
|
| 32 |
}
|
| 33 |
setActive(value:boolean){this.active=value;this.controls.enabled=value;this.host.hidden=!value;if(value){const w=this.host.clientWidth,h=this.host.clientHeight;if(w&&h){this.renderer.setSize(w,h);this.camera.aspect=w/h;this.camera.updateProjectionMatrix();}if(this.root)this.fit(true);this.draw();}else{cancelAnimationFrame(this.frame);this.frame=0;}}
|
| 34 |
-
async load(buffer:ArrayBuffer,signal:AbortSignal){
|
|
|
|
|
|
|
|
|
|
| 35 |
const manager=new THREE.LoadingManager();
|
| 36 |
manager.setURLModifier(url=>{
|
| 37 |
if(url.startsWith('data:')||url.startsWith('blob:'))return url;
|
|
@@ -46,6 +50,23 @@ export class ModelViewer{
|
|
| 46 |
loader.parse(buffer,result=>{signal.removeEventListener('abort',abort);loader.dispose();if(signal.aborted){this.disposeObject(result);reject(new DOMException('已取消读取','AbortError'));}else resolve(result);},error=>{signal.removeEventListener('abort',abort);loader.dispose();reject(new Error(error?.message||'无法解析 3DM,请检查文件是否损坏。'));});
|
| 47 |
});
|
| 48 |
if(signal.aborted){this.disposeObject(object);throw new DOMException('已取消读取','AbortError');}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
object.updateMatrixWorld(true);
|
| 50 |
const initialBox=new THREE.Box3();object.traverseVisible(o=>{const g=(o as THREE.Mesh).geometry;if(g){if(!g.boundingBox)g.computeBoundingBox();if(g.boundingBox)initialBox.union(g.boundingBox.clone().applyMatrix4(o.matrixWorld));}});
|
| 51 |
if(initialBox.isEmpty()||!Number.isFinite(initialBox.min.length()+initialBox.max.length())){this.disposeObject(object);throw new Error('此 3DM 没有可显示的几何对象。请在 Rhino 中开启保存显示网格后另存。');}
|
|
@@ -69,9 +90,12 @@ export class ModelViewer{
|
|
| 69 |
// Retain the original geometry/materials; Rhino lights do not control the reader lighting.
|
| 70 |
object.traverse(o=>{if((o as THREE.Light).isLight)o.visible=false;});
|
| 71 |
this.root=object;this.scene.add(object);this.fit(true);
|
|
|
|
|
|
|
|
|
|
| 72 |
}
|
| 73 |
private visibleBounds(){const bounds=new THREE.Box3();this.root?.traverseVisible(o=>{const g=(o as THREE.Mesh).geometry;if(g){if(!g.boundingBox)g.computeBoundingBox();if(g.boundingBox)bounds.union(g.boundingBox.clone().applyMatrix4(o.matrixWorld));}});return bounds;}
|
| 74 |
-
fit(initial=false){
|
| 75 |
private frameBox(bounds:THREE.Box3,initial=false){
|
| 76 |
const center=bounds.getCenter(new THREE.Vector3()),size=bounds.getSize(new THREE.Vector3()),radius=Math.max(size.length()/2,.001);
|
| 77 |
const vFov=THREE.MathUtils.degToRad(this.camera.fov),hFov=2*Math.atan(Math.tan(vFov/2)*this.camera.aspect),distance=radius/Math.sin(Math.min(vFov,hFov)/2)*1.2;
|
|
@@ -99,6 +123,6 @@ export class ModelViewer{
|
|
| 99 |
if(hits[0]){let o:THREE.Object3D|null=hits[0].object;while(o&&!this.objectParts.has(o))o=o.parent;if(o){const part=this.objectParts.get(o)!;this.focus([part]);this.onSelect(part);}}
|
| 100 |
}
|
| 101 |
draw(){if(!this.active||this.frame)return;this.frame=requestAnimationFrame(()=>{this.frame=0;if(this.animation){const a=this.animation,t=Math.min(1,(performance.now()-a.start)/380),s=1-(1-t)**3;this.camera.position.lerpVectors(a.from,a.to,s);this.controls.target.lerpVectors(a.targetFrom,a.targetTo,s);if(t===1)this.animation=null;}const changed=this.controls.update();this.renderer.render(this.scene,this.camera);this.onChange();if(this.animation||changed)this.draw();});}
|
| 102 |
-
clear(){this.clearSelection();if(this.root)
|
| 103 |
private disposeObject(object:THREE.Object3D){const materials=new Set<THREE.Material>(),geometries=new Set<THREE.BufferGeometry>(),textures=new Set<THREE.Texture>();object.traverse(o=>{const mesh=o as THREE.Mesh;if(mesh.geometry)geometries.add(mesh.geometry);if(mesh.material)for(const m of Array.isArray(mesh.material)?mesh.material:[mesh.material])materials.add(m);});materials.forEach(m=>{Object.values(m).forEach(v=>{if(v instanceof THREE.Texture)textures.add(v);});m.dispose();});textures.forEach(t=>t.dispose());geometries.forEach(g=>g.dispose());}
|
| 104 |
}
|
|
|
|
| 12 |
onSelect:(part:ModelPart)=>void=()=>{};onChange:()=>void=()=>{};
|
| 13 |
private objectParts=new Map<THREE.Object3D,ModelPart>();private frame=0;private active=false;
|
| 14 |
private originalMaterials=new Map<THREE.Object3D,THREE.Material|THREE.Material[]>();
|
| 15 |
+
private cache=new Map<string,{root:THREE.Object3D;parts:ModelPart[];roots:ModelPart[];layers:string[];warnings:string[];map:Map<THREE.Object3D,ModelPart>}>();
|
| 16 |
private helper:THREE.Box3Helper|null=null;
|
| 17 |
private animation:{start:number;from:THREE.Vector3;to:THREE.Vector3;targetFrom:THREE.Vector3;targetTo:THREE.Vector3}|null=null;
|
| 18 |
constructor(readonly host:HTMLElement){
|
|
|
|
| 32 |
this.renderer.domElement.addEventListener('keydown',e=>{if(e.key==='Home'||e.key.toLowerCase()==='f'){e.preventDefault();this.fit();}if(e.key==='Escape')this.clearSelection();if(e.key==='+'||e.key==='=')this.zoom(1.3);if(e.key==='-')this.zoom(1/1.3);});
|
| 33 |
}
|
| 34 |
setActive(value:boolean){this.active=value;this.controls.enabled=value;this.host.hidden=!value;if(value){const w=this.host.clientWidth,h=this.host.clientHeight;if(w&&h){this.renderer.setSize(w,h);this.camera.aspect=w/h;this.camera.updateProjectionMatrix();}if(this.root)this.fit(true);this.draw();}else{cancelAnimationFrame(this.frame);this.frame=0;}}
|
| 35 |
+
async load(buffer:ArrayBuffer,signal:AbortSignal,key:string){
|
| 36 |
+
const cached=this.cache.get(key);if(cached){this.clear();this.cache.delete(key);this.cache.set(key,cached);this.root=cached.root;this.parts=cached.parts;this.roots=cached.roots;this.layers=cached.layers;this.warnings=cached.warnings;this.objectParts=cached.map;this.scene.add(cached.root);this.fit(true);return true;}
|
| 37 |
+
const fallbackBuffer=buffer.slice(0);
|
| 38 |
+
const fallback=new Promise<any[]>((resolve)=>{const worker=new Worker(new URL('./extrusion.worker.ts',import.meta.url));const done=(value:any[])=>{worker.terminate();resolve(value);};worker.onmessage=e=>done(e.data.out??[]);worker.onerror=()=>done([]);signal.addEventListener('abort',()=>done([]),{once:true});worker.postMessage({buffer:fallbackBuffer,libraryUrl:new URL('./rhino/',location.href).href},[fallbackBuffer]);});
|
| 39 |
const manager=new THREE.LoadingManager();
|
| 40 |
manager.setURLModifier(url=>{
|
| 41 |
if(url.startsWith('data:')||url.startsWith('blob:'))return url;
|
|
|
|
| 50 |
loader.parse(buffer,result=>{signal.removeEventListener('abort',abort);loader.dispose();if(signal.aborted){this.disposeObject(result);reject(new DOMException('已取消读取','AbortError'));}else resolve(result);},error=>{signal.removeEventListener('abort',abort);loader.dispose();reject(new Error(error?.message||'无法解析 3DM,请检查文件是否损坏。'));});
|
| 51 |
});
|
| 52 |
if(signal.aborted){this.disposeObject(object);throw new DOMException('已取消读取','AbortError');}
|
| 53 |
+
const extrusions=await fallback;
|
| 54 |
+
if(signal.aborted){this.disposeObject(object);throw new DOMException('已取消读取','AbortError');}
|
| 55 |
+
for(const entry of extrusions){
|
| 56 |
+
const positions:number[]=[],indices:number[]=[],profiles=entry.profiles as {bottom:number[][];top:number[][];closed:boolean}[];
|
| 57 |
+
let offset=0;for(const p of profiles){const n=p.bottom.length;if(n<3)continue;for(const v of p.bottom)positions.push(...v);for(const v of p.top)positions.push(...v);for(let i=0;i<(p.closed?n:n-1);i++){const j=(i+1)%n;indices.push(offset+i,offset+j,offset+n+j,offset+i,offset+n+j,offset+n+i);}offset+=n*2;}
|
| 58 |
+
if(!positions.length)continue;
|
| 59 |
+
// Triangulate caps in their own plane, including inner profile holes.
|
| 60 |
+
const outer=profiles[0],origin=new THREE.Vector3().fromArray(outer.bottom[0]),axis=new THREE.Vector3().fromArray(outer.top[0]).sub(origin).normalize();
|
| 61 |
+
let u=new THREE.Vector3().fromArray(outer.bottom[1]).sub(origin).normalize();if(!u.lengthSq())u.set(1,0,0);const v=new THREE.Vector3().crossVectors(axis,u).normalize();u=new THREE.Vector3().crossVectors(v,axis).normalize();
|
| 62 |
+
const planar=profiles.map(p=>p.bottom.map(q=>{const point=new THREE.Vector3().fromArray(q).sub(origin);return new THREE.Vector2(point.dot(u),point.dot(v));}));
|
| 63 |
+
const flatBottom:number[]=[],flatTop:number[]=[];let base=0;for(const p of profiles){for(let i=0;i<p.bottom.length;i++){flatBottom.push(base+i);flatTop.push(base+p.bottom.length+i);}base+=p.bottom.length*2;}
|
| 64 |
+
if(outer.closed&&(entry.bottom||entry.top))for(const tri of THREE.ShapeUtils.triangulateShape(planar[0],planar.slice(1))){if(entry.bottom)indices.push(...tri.map(i=>flatBottom[i]));if(entry.top)indices.push(...tri.map(i=>flatTop[i]));}
|
| 65 |
+
const geometry=new THREE.BufferGeometry();geometry.setAttribute('position',new THREE.Float32BufferAttribute(positions,3));geometry.setIndex(indices);geometry.computeVertexNormals();
|
| 66 |
+
const mesh=new THREE.Mesh(geometry,new THREE.MeshStandardMaterial({color:'#a8b9c5',side:THREE.DoubleSide,roughness:.8}));mesh.userData={attributes:entry.attributes,objectType:'Extrusion',fallbackExtrusion:true};object.add(mesh);
|
| 67 |
+
}
|
| 68 |
+
// Show geometry on initially hidden layers too; users can hide layers in the panel.
|
| 69 |
+
object.traverse(o=>{if(!(o as THREE.Light).isLight)o.visible=true;});
|
| 70 |
object.updateMatrixWorld(true);
|
| 71 |
const initialBox=new THREE.Box3();object.traverseVisible(o=>{const g=(o as THREE.Mesh).geometry;if(g){if(!g.boundingBox)g.computeBoundingBox();if(g.boundingBox)initialBox.union(g.boundingBox.clone().applyMatrix4(o.matrixWorld));}});
|
| 72 |
if(initialBox.isEmpty()||!Number.isFinite(initialBox.min.length()+initialBox.max.length())){this.disposeObject(object);throw new Error('此 3DM 没有可显示的几何对象。请在 Rhino 中开启保存显示网格后另存。');}
|
|
|
|
| 90 |
// Retain the original geometry/materials; Rhino lights do not control the reader lighting.
|
| 91 |
object.traverse(o=>{if((o as THREE.Light).isLight)o.visible=false;});
|
| 92 |
this.root=object;this.scene.add(object);this.fit(true);
|
| 93 |
+
this.cache.set(key,{root:object,parts:this.parts,roots:this.roots,layers:this.layers,warnings:this.warnings,map:this.objectParts});
|
| 94 |
+
while(this.cache.size>3){const oldest=this.cache.keys().next().value!;const entry=this.cache.get(oldest)!;this.cache.delete(oldest);this.disposeObject(entry.root);}
|
| 95 |
+
return false;
|
| 96 |
}
|
| 97 |
private visibleBounds(){const bounds=new THREE.Box3();this.root?.traverseVisible(o=>{const g=(o as THREE.Mesh).geometry;if(g){if(!g.boundingBox)g.computeBoundingBox();if(g.boundingBox)bounds.union(g.boundingBox.clone().applyMatrix4(o.matrixWorld));}});return bounds;}
|
| 98 |
+
fit(initial=false){let b=this.visibleBounds();if(initial&&this.root){const preferred=new THREE.Box3();this.root.traverseVisible(o=>{if(o.userData.fallbackExtrusion)preferred.union(new THREE.Box3().setFromObject(o));});if(!preferred.isEmpty())b=preferred;}if(b.isEmpty())return;this.clearSelection();this.frameBox(b,initial);}
|
| 99 |
private frameBox(bounds:THREE.Box3,initial=false){
|
| 100 |
const center=bounds.getCenter(new THREE.Vector3()),size=bounds.getSize(new THREE.Vector3()),radius=Math.max(size.length()/2,.001);
|
| 101 |
const vFov=THREE.MathUtils.degToRad(this.camera.fov),hFov=2*Math.atan(Math.tan(vFov/2)*this.camera.aspect),distance=radius/Math.sin(Math.min(vFov,hFov)/2)*1.2;
|
|
|
|
| 123 |
if(hits[0]){let o:THREE.Object3D|null=hits[0].object;while(o&&!this.objectParts.has(o))o=o.parent;if(o){const part=this.objectParts.get(o)!;this.focus([part]);this.onSelect(part);}}
|
| 124 |
}
|
| 125 |
draw(){if(!this.active||this.frame)return;this.frame=requestAnimationFrame(()=>{this.frame=0;if(this.animation){const a=this.animation,t=Math.min(1,(performance.now()-a.start)/380),s=1-(1-t)**3;this.camera.position.lerpVectors(a.from,a.to,s);this.controls.target.lerpVectors(a.targetFrom,a.targetTo,s);if(t===1)this.animation=null;}const changed=this.controls.update();this.renderer.render(this.scene,this.camera);this.onChange();if(this.animation||changed)this.draw();});}
|
| 126 |
+
clear(){this.clearSelection();if(this.root)this.scene.remove(this.root);this.root=null;this.parts=[];this.roots=[];this.layers=[];this.objectParts=new Map();}
|
| 127 |
private disposeObject(object:THREE.Object3D){const materials=new Set<THREE.Material>(),geometries=new Set<THREE.BufferGeometry>(),textures=new Set<THREE.Texture>();object.traverse(o=>{const mesh=o as THREE.Mesh;if(mesh.geometry)geometries.add(mesh.geometry);if(mesh.material)for(const m of Array.isArray(mesh.material)?mesh.material:[mesh.material])materials.add(m);});materials.forEach(m=>{Object.values(m).forEach(v=>{if(v instanceof THREE.Texture)textures.add(v);});m.dispose();});textures.forEach(t=>t.dispose());geometries.forEach(g=>g.dispose());}
|
| 128 |
}
|
src/style.css
CHANGED
|
@@ -23,3 +23,4 @@ header{height:60px;padding:0 18px;gap:16px}.brand strong{font-size:19px}.brand-s
|
|
| 23 |
aside.files-panel{width:240px;border-right:1px solid #ccdfef;border-left:0;background:#f0f6fc}.properties-panel{width:300px;border-left:1px solid #ccdfef;border-right:0;background:#f6faff}.panel-heading{height:62px;display:flex;align-items:center;justify-content:space-between;padding:0 18px;font-size:13px}.properties-panel .aside-heading{padding:20px 18px 16px}.new-file{margin:0 12px 23px;display:flex;align-items:center;gap:9px;padding:11px 10px;border:1px solid #c4dced;border-radius:7px;background:#e5f1fb;font-size:12px;color:#3c698b}.new-file span{margin-left:auto}.new-file svg{width:16px}.new-file:hover{background:#d7eaf9}.files-section-title{padding:0 18px 12px;color:#718ba0;font-size:11px}.files-list{flex:1;min-height:0;overflow:auto}.files-list .history-list{padding:0 8px;max-height:none;overflow:visible}.files-list .history-row{gap:0;margin-bottom:5px;border-radius:7px;align-items:center}.files-list .history-row.current{background:#d5e9f8}.files-list .history-open{gap:8px;padding:12px 7px}.files-list .history-open>svg{width:16px;height:16px;flex-shrink:0}.files-list .history-name{font-size:11px}.files-list .history-meta{font-size:9px;line-height:1.6}.files-list .history-remove{font-size:10px;padding:8px 5px}.files-list .history-empty{font-size:11px;line-height:1.8;padding:25px 10px}.files-footer{border-top:1px solid #ccdfef;padding:15px 12px;display:flex;align-items:center;justify-content:space-between;font-size:9px;color:#718ba0;gap:8px}.files-footer button{font-size:10px;color:#4e7798}.property-summary{padding:0 18px 16px;border-bottom:1px solid #d7e6f2;flex-shrink:0;margin-bottom:18px;max-height:245px;overflow:auto}.property-row{display:grid;grid-template-columns:72px minmax(0,1fr);gap:8px;padding:6px 0;font-size:10px}.property-row>span:first-child{color:#7890a5}.property-row>span:last-child{color:#3d5f7c;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.property-placeholder{font-size:11px;color:#839aac}.properties-panel .tabs{margin-top:17px}.properties-panel .tree-empty{margin-top:35px}.workspace{min-width:150px}#model-host{position:absolute;inset:0}#model-host canvas{width:100%;height:100%;cursor:grab}.welcome{z-index:1}.canvas-heading{z-index:2;padding:17px}.selection,.view-tools,.axis,.canvas-hint{z-index:2}.welcome p{max-width:390px;padding:0 20px}.canvas-hint{font-size:9px;bottom:20px}.selection{top:58px;left:17px}.view-tools{right:16px}.canvas-heading select{max-width:160px}.canvas-heading .crumb{font-size:10px;gap:6px}#drawing-state{font-size:9px;padding-left:7px;margin-left:0}
|
| 24 |
@media(max-width:1100px){aside.files-panel{width:205px}.properties-panel{width:265px}.brand-sub{display:none}.key{display:none}.header-actions{gap:5px}.canvas-heading #drawing-state{display:none}.canvas-hint{display:none}}
|
| 25 |
@media(max-width:760px){aside.files-panel{width:185px}.properties-panel{width:230px}.header-file{font-size:10px}.recent-button{display:none}.welcome h1{font-size:19px}.welcome p{font-size:11px}.welcome-art{width:75px;height:70px}.welcome-art>svg{width:40px}.eyebrow{font-size:8px;letter-spacing:1px}.canvas-heading select{max-width:105px}.workspace{min-width:120px}.property-row{grid-template-columns:58px minmax(0,1fr)}}
|
|
|
|
|
|
| 23 |
aside.files-panel{width:240px;border-right:1px solid #ccdfef;border-left:0;background:#f0f6fc}.properties-panel{width:300px;border-left:1px solid #ccdfef;border-right:0;background:#f6faff}.panel-heading{height:62px;display:flex;align-items:center;justify-content:space-between;padding:0 18px;font-size:13px}.properties-panel .aside-heading{padding:20px 18px 16px}.new-file{margin:0 12px 23px;display:flex;align-items:center;gap:9px;padding:11px 10px;border:1px solid #c4dced;border-radius:7px;background:#e5f1fb;font-size:12px;color:#3c698b}.new-file span{margin-left:auto}.new-file svg{width:16px}.new-file:hover{background:#d7eaf9}.files-section-title{padding:0 18px 12px;color:#718ba0;font-size:11px}.files-list{flex:1;min-height:0;overflow:auto}.files-list .history-list{padding:0 8px;max-height:none;overflow:visible}.files-list .history-row{gap:0;margin-bottom:5px;border-radius:7px;align-items:center}.files-list .history-row.current{background:#d5e9f8}.files-list .history-open{gap:8px;padding:12px 7px}.files-list .history-open>svg{width:16px;height:16px;flex-shrink:0}.files-list .history-name{font-size:11px}.files-list .history-meta{font-size:9px;line-height:1.6}.files-list .history-remove{font-size:10px;padding:8px 5px}.files-list .history-empty{font-size:11px;line-height:1.8;padding:25px 10px}.files-footer{border-top:1px solid #ccdfef;padding:15px 12px;display:flex;align-items:center;justify-content:space-between;font-size:9px;color:#718ba0;gap:8px}.files-footer button{font-size:10px;color:#4e7798}.property-summary{padding:0 18px 16px;border-bottom:1px solid #d7e6f2;flex-shrink:0;margin-bottom:18px;max-height:245px;overflow:auto}.property-row{display:grid;grid-template-columns:72px minmax(0,1fr);gap:8px;padding:6px 0;font-size:10px}.property-row>span:first-child{color:#7890a5}.property-row>span:last-child{color:#3d5f7c;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.property-placeholder{font-size:11px;color:#839aac}.properties-panel .tabs{margin-top:17px}.properties-panel .tree-empty{margin-top:35px}.workspace{min-width:150px}#model-host{position:absolute;inset:0}#model-host canvas{width:100%;height:100%;cursor:grab}.welcome{z-index:1}.canvas-heading{z-index:2;padding:17px}.selection,.view-tools,.axis,.canvas-hint{z-index:2}.welcome p{max-width:390px;padding:0 20px}.canvas-hint{font-size:9px;bottom:20px}.selection{top:58px;left:17px}.view-tools{right:16px}.canvas-heading select{max-width:160px}.canvas-heading .crumb{font-size:10px;gap:6px}#drawing-state{font-size:9px;padding-left:7px;margin-left:0}
|
| 24 |
@media(max-width:1100px){aside.files-panel{width:205px}.properties-panel{width:265px}.brand-sub{display:none}.key{display:none}.header-actions{gap:5px}.canvas-heading #drawing-state{display:none}.canvas-hint{display:none}}
|
| 25 |
@media(max-width:760px){aside.files-panel{width:185px}.properties-panel{width:230px}.header-file{font-size:10px}.recent-button{display:none}.welcome h1{font-size:19px}.welcome p{font-size:11px}.welcome-art{width:75px;height:70px}.welcome-art>svg{width:40px}.eyebrow{font-size:8px;letter-spacing:1px}.canvas-heading select{max-width:105px}.workspace{min-width:120px}.property-row{grid-template-columns:58px minmax(0,1fr)}}
|
| 26 |
+
.space-buttons{display:flex;gap:4px;padding:3px;background:#f2f8fe;border:1px solid #c4dced;border-radius:6px;pointer-events:auto}.space-buttons button{padding:5px 9px;border-radius:4px;color:#557b98;font-size:11px;white-space:nowrap}.space-buttons button[aria-pressed=true]{background:#d4e9f9;color:#176ca0;font-weight:600}
|
src/types.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
export type Point={x:number;y:number};
|
| 2 |
export type Matrix=[number,number,number,number,number,number];
|
| 3 |
export type Bounds={minX:number;minY:number;maxX:number;maxY:number};
|
| 4 |
-
export type Primitive={points:Point[];color:string;layer:string;closed?:boolean;fill?:boolean;text?:string;height?:number;matrix?:Matrix;bounds:Bounds;node:string};
|
| 5 |
export type Item={id:string;label:string;type:string;layer:string;bounds:Bounds;children:Item[];primitives:number[]};
|
| 6 |
export type Scene={primitives:Primitive[];items:Item[];bounds:Bounds;layers:{name:string;color:string;off:boolean}[];spaces:string[];space:string;unsupported:Record<string,number>;unknown:number;warnings?:number[]};
|
|
|
|
| 1 |
export type Point={x:number;y:number};
|
| 2 |
export type Matrix=[number,number,number,number,number,number];
|
| 3 |
export type Bounds={minX:number;minY:number;maxX:number;maxY:number};
|
| 4 |
+
export type Primitive={points:Point[];color:string;layer:string;closed?:boolean;fill?:boolean;text?:string;textAlign?:CanvasTextAlign;textOffsetX?:number;textFitWidth?:number;height?:number;matrix?:Matrix;bounds:Bounds;node:string;clip?:Bounds};
|
| 5 |
export type Item={id:string;label:string;type:string;layer:string;bounds:Bounds;children:Item[];primitives:number[]};
|
| 6 |
export type Scene={primitives:Primitive[];items:Item[];bounds:Bounds;layers:{name:string;color:string;off:boolean}[];spaces:string[];space:string;unsupported:Record<string,number>;unknown:number;warnings?:number[]};
|
src/viewer.ts
CHANGED
|
@@ -32,12 +32,13 @@ export class Viewer {
|
|
| 32 |
const left=this.cx-this.w/2/this.scale,right=this.cx+this.w/2/this.scale,bottom=this.cy-this.h/2/this.scale,top=this.cy+this.h/2/this.scale;
|
| 33 |
const paint=(p:Primitive,highlight=false)=>{
|
| 34 |
if(this.hidden.has(p.layer)||p.bounds.maxX<left||p.bounds.minX>right||p.bounds.maxY<bottom||p.bounds.minY>top)return;
|
|
|
|
| 35 |
c.globalAlpha=this.selected.size&&!highlight ? .65:1;
|
| 36 |
const color=highlight?'#0069ab':drawingColor(p.color);c.strokeStyle=color;c.fillStyle=color;c.lineWidth=(highlight?2:1)/this.scale;
|
| 37 |
if(p.text!==undefined&&p.matrix){
|
| 38 |
-
const m=p.matrix,h=p.height!;if(h*Math.hypot(m[2],m[3])*this.scale<2)return;c.save();c.transform(...m);c.scale(1,-1);c.font=`${h}px "Microsoft YaHei", "SimSun", sans-serif`;c.textBaseline='alphabetic';
|
| 39 |
-
p.text.split('\n').forEach((line,i)=>c.fillText(line,0,i*h*1.3));c.restore();
|
| 40 |
-
}else{c.beginPath();p.points.forEach((v,i)=>i?c.lineTo(v.x,v.y):c.moveTo(v.x,v.y));if(p.points.length===1){const p0=p.points[0];c.lineTo(p0.x+2/this.scale,p0.y);}if(p.closed)c.closePath();if(p.fill)c.fill('evenodd');else c.stroke();}
|
| 41 |
};
|
| 42 |
this.scene.primitives.forEach(p=>paint(p));this.selected.forEach(i=>paint(this.scene!.primitives[i],true));c.restore();
|
| 43 |
if(this.selection){const b=this.selection,x=(b.minX-this.cx)*this.scale+this.w/2,y=(this.cy-b.maxY)*this.scale+this.h/2,w=(b.maxX-b.minX)*this.scale,h=(b.maxY-b.minY)*this.scale;c.strokeStyle='#0069ab';c.lineWidth=1;c.setLineDash([5,5]);c.strokeRect(x-7,y-7,w+14,h+14);c.setLineDash([]);}
|
|
|
|
| 32 |
const left=this.cx-this.w/2/this.scale,right=this.cx+this.w/2/this.scale,bottom=this.cy-this.h/2/this.scale,top=this.cy+this.h/2/this.scale;
|
| 33 |
const paint=(p:Primitive,highlight=false)=>{
|
| 34 |
if(this.hidden.has(p.layer)||p.bounds.maxX<left||p.bounds.minX>right||p.bounds.maxY<bottom||p.bounds.minY>top)return;
|
| 35 |
+
c.save();if(p.clip){c.beginPath();c.rect(p.clip.minX,p.clip.minY,p.clip.maxX-p.clip.minX,p.clip.maxY-p.clip.minY);c.clip();}
|
| 36 |
c.globalAlpha=this.selected.size&&!highlight ? .65:1;
|
| 37 |
const color=highlight?'#0069ab':drawingColor(p.color);c.strokeStyle=color;c.fillStyle=color;c.lineWidth=(highlight?2:1)/this.scale;
|
| 38 |
if(p.text!==undefined&&p.matrix){
|
| 39 |
+
const m=p.matrix,h=p.height!;if(h*Math.hypot(m[2],m[3])*this.scale<2){c.restore();return;}c.save();c.transform(...m);c.translate(-(p.textOffsetX||0),0);c.scale(1,-1);c.font=`${h}px "Microsoft YaHei", "SimSun", sans-serif`;c.textBaseline='alphabetic';c.textAlign=p.textAlign??'left';
|
| 40 |
+
p.text.split('\n').forEach((line,i)=>{c.save();if(p.textFitWidth){const measured=c.measureText(line).width;if(measured)c.scale(p.textFitWidth/measured,1);}c.fillText(line,0,i*h*1.3);c.restore();});c.restore();
|
| 41 |
+
}else{c.beginPath();p.points.forEach((v,i)=>i?c.lineTo(v.x,v.y):c.moveTo(v.x,v.y));if(p.points.length===1){const p0=p.points[0];c.lineTo(p0.x+2/this.scale,p0.y);}if(p.closed)c.closePath();if(p.fill)c.fill('evenodd');else c.stroke();}c.restore();
|
| 42 |
};
|
| 43 |
this.scene.primitives.forEach(p=>paint(p));this.selected.forEach(i=>paint(this.scene!.primitives[i],true));c.restore();
|
| 44 |
if(this.selection){const b=this.selection,x=(b.minX-this.cx)*this.scale+this.w/2,y=(this.cy-b.maxY)*this.scale+this.h/2,w=(b.maxX-b.minX)*this.scale,h=(b.maxY-b.minY)*this.scale;c.strokeStyle='#0069ab';c.lineWidth=1;c.setLineDash([5,5]);c.strokeRect(x-7,y-7,w+14,h+14);c.setLineDash([]);}
|
tests/geometry.test.ts
CHANGED
|
@@ -30,3 +30,19 @@ test('bulged polyline retains its arc rather than a straight chord',()=>{
|
|
| 30 |
test('CAD formatting is cleaned while document text stays plain data',()=>{
|
| 31 |
assert.equal(cleanText('{\\fSimSun;客厅\\P35.2%%d}'),'客厅\n35.2°');assert.equal(cleanText('<script>alert(1)</script>'),'<script>alert(1)</script>');
|
| 32 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
test('CAD formatting is cleaned while document text stays plain data',()=>{
|
| 31 |
assert.equal(cleanText('{\\fSimSun;客厅\\P35.2%%d}'),'客厅\n35.2°');assert.equal(cleanText('<script>alert(1)</script>'),'<script>alert(1)</script>');
|
| 32 |
});
|
| 33 |
+
test('paper viewport projects model geometry and clips its bounds',()=>{
|
| 34 |
+
const vp={type:'VIEWPORT',viewportId:2,status:1,statusBitFlags:0,viewportCenter:{x:100,y:200},displayCenter:{x:5,y:0},viewDirection:{x:0,y:0,z:1},width:4,height:4,viewHeight:4};
|
| 35 |
+
const scene=buildScene(db([block('*Model_Space',[line]),block('*Paper_Space',[vp])]),'*Paper_Space');
|
| 36 |
+
assert.equal(scene.primitives.length,1);assert.deepEqual(scene.primitives[0].points,[{x:95,y:200},{x:105,y:200}]);assert.deepEqual(scene.primitives[0].bounds,{minX:98,minY:200,maxX:102,maxY:200});assert.deepEqual(scene.primitives[0].clip,{minX:98,minY:198,maxX:102,maxY:202});
|
| 37 |
+
});
|
| 38 |
+
test('vertical text justification uses the alignment point even with left horizontal alignment',()=>{
|
| 39 |
+
const text={type:'TEXT',handle:'t',layer:'0',text:'label',textHeight:2,halign:0,valign:3,startPoint:{x:10,y:20},endPoint:{x:10,y:22}};
|
| 40 |
+
const scene=buildScene(db([block('*Model_Space',[text])]));assert.equal(scene.primitives[0].matrix?.[5],20);
|
| 41 |
+
});
|
| 42 |
+
test('fit text spans its two specified alignment points',()=>{
|
| 43 |
+
const text={type:'TEXT',handle:'t',layer:'0',text:'11',textHeight:3,halign:5,valign:0,xScale:1.6,startPoint:{x:10,y:20},endPoint:{x:14,y:20}};
|
| 44 |
+
const p=buildScene(db([block('*Model_Space',[text])])).primitives[0];assert.equal(p.bounds.minX,10);assert.ok(Math.abs(p.bounds.maxX-14)<1e-9);assert.ok(p.textFitWidth);assert.equal(p.textAlign,'left');
|
| 45 |
+
});
|
| 46 |
+
test('empty paper block placeholders are omitted from space choices',()=>{
|
| 47 |
+
const scene=buildScene(db([block('*Model_Space',[line]),block('*Paper_Space',[line]),block('*Paper_Space0',[])]));assert.deepEqual(scene.spaces,['*Model_Space','*Paper_Space']);
|
| 48 |
+
});
|