"""Native Rhino solids + source node hierarchy. Geometry is stored in millimetres.""" import sys,json,pathlib,collections ROOT=pathlib.Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'.local/runtime/python')) import rhino3dm as rh def export(scene_path,project,out): project=pathlib.Path(project).resolve();out=pathlib.Path(out);data=json.loads(pathlib.Path(scene_path).read_text(encoding='utf-8')) out.mkdir(parents=True,exist_ok=True) node_path=project/'inputs/20240426壁龛节点-1.3dm' model=rh.File3dm.Read(str(node_path)) if node_path.exists() else rh.File3dm() original_count=len(model.Objects);original_layers=list(model.Layers) reference=None if original_count: reference=rh.Layer();reference.Name='参考节点(原始坐标,未定位到房间)';reference.Color=(150,150,150,255);reference.Visible=False ri=model.Layers.Add(reference);reference=model.Layers[ri] for layer in original_layers: if str(layer.ParentLayerId)=='00000000-0000-0000-0000-000000000000':layer.ParentLayerId=reference.Id # Source geometry is retained but does not interfere with the apartment view. layer.Visible=False model.Settings.ModelUnitSystem=rh.UnitSystem.Millimeters;model.Settings.ModelAbsoluteTolerance=.1 model.ApplicationName='ArchRobot';model.ApplicationDetails='DWG floor geometry with reviewable room/finish parameters. Source node is preserved, not automatically assigned.' def layer(name,parent=None,color=(191,184,172,255)): l=rh.Layer();l.Name=name;l.Color=color if parent is not None:l.ParentLayerId=model.Layers[parent].Id return model.Layers.Add(l) root=layer('128户型 · 核审模型');cad_layer=layer('施工图底图(DWG毫米坐标归一)',root,(100,110,120,255)) room_layers={};material_indices={} for r in data['rooms']: parent=layer(r['name'],root) room_layers[r['id']]={n:layer(n,parent) for n in ['地面','墙面表皮','墙面基层','固定家具','洁具']} structural=layer('墙柱 · DWG闭合轮廓',root) window_layer=layer('门窗 · 平面定位 / 高度待核审',root,(160,193,204,255)) for item in data['materials']: mat=rh.Material();mat.Name=item['id']+' '+item['name'];mat.DiffuseColor=(202,190,170,255) texture=(project/item['texture']).resolve() if not texture.is_relative_to(project):raise ValueError('Invalid texture path') if texture.exists(): from PIL import Image color=Image.open(texture).convert('RGB').resize((1,1)).getpixel((0,0));mat.DiffuseColor=(*color,255) material_indices[item['id']]=model.Materials.Add(mat) solids=0 def add(geom,name,li,material='',source='',verification=''): nonlocal solids if geom is None or not geom.IsValid:raise ValueError('Invalid geometry: '+name) attr=rh.ObjectAttributes();attr.Name=name;attr.LayerIndex=li attr.SetUserString('source',source);attr.SetUserString('verification',verification);attr.SetUserString('material_code',material) if material in material_indices: attr.MaterialIndex=material_indices[material];attr.MaterialSource=rh.ObjectMaterialSource.MaterialFromObject model.Objects.Add(geom,attr) if isinstance(geom,(rh.Extrusion,rh.Brep)) and geom.IsSolid:solids+=1 def extrusion(points,z,height): # Rounded CAD coordinates may collapse neighbouring vertices onto one point. clean=[] for point in points: if not clean or tuple(point)!=tuple(clean[-1]):clean.append(point) points=clean if points[-1]!=points[0]:points.append(points[0]) curve=rh.PolylineCurve([rh.Point3d(x*1000,y*1000,z*1000) for x,y in points]) return rh.Extrusion.Create(curve,height*1000,True) for r in data['rooms']: x0,y0,x1,y1=r['bounds'] add(extrusion([(x0,y0),(x1,y0),(x1,y1),(x0,y1)],-.1,.1),r['name']+'地面',room_layers[r['id']]['地面'],r['material'],r['source'],r['verification']) for w in data['walls']: add(extrusion(w['polygon'],0,w['height']),w['id'],structural,w['material'],w['source'],w['verification']) for f in data.get('features',[]): x,y,z=f['position'];sx,sy,sz=f['size'] geom=extrusion([(x-sx/2,y-sy/2),(x+sx/2,y-sy/2),(x+sx/2,y+sy/2),(x-sx/2,y+sy/2)],z-sz/2,sz) add(geom,f['name'],room_layers[f['room']]['固定家具'],f['material'],f['source'],f['verification']) for i,line in enumerate(data.get('linework',[])): curve=rh.PolylineCurve([rh.Point3d(x*1000,y*1000,5) for x,y in line['points']]) if curve.IsValid:add(curve,'CAD-'+line['layer']+'-'+str(i),cad_layer,source='DWG '+line['layer']) for w in data.get('windows',[]): import math a,b=w['a'],w['b'];length=math.dist(a,b);nx=-(b[1]-a[1])/length*.0125;ny=(b[0]-a[0])/length*.0125 points=[(a[0]+nx,a[1]+ny),(b[0]+nx,b[1]+ny),(b[0]-nx,b[1]-ny),(a[0]-nx,a[1]-ny)] add(extrusion(points,w['bottom'],w['height']),w['id'],window_layer,source=w['source'],verification=w['verification']) model.Strings['model_status']='核审预览:实际DWG闭合轮廓;房间边界、开口、层高与节点落位待核审' model.Strings['reference_node']='原始壁龛节点完整保留在隐藏参考图层;未自动插入主卫/公卫' model.Strings['geometry_units']='millimetres' model.Strings['material_note']='3DM材质为原始样板平均色与编码;完整纹理见同版本GLB/Blender及项目物料库' bounds=rh.BoundingBox(rh.Point3d(-1000,-1000,-100),rh.Point3d(18000,10500,3000)) for view in model.Views: vp=view.Viewport vp.SetCameraLocation(rh.Point3d(24000,-22000,25000));vp.SetCameraDirection(rh.Vector3d(-16000,26000,-23000)) vp.DollyExtents(bounds,1.25) file=out/'model.3dm' if not model.Write(str(file),8):raise RuntimeError('Rhino write failed') checked=rh.File3dm.Read(str(file)) if checked is None or len(checked.Objects)<=original_count:raise RuntimeError('Rhino read-back failed') report=dict(file='model.3dm',units='mm',sourceObjects=original_count,sourceLayers=len(original_layers),objects=len(checked.Objects),layers=len(checked.Layers),newSolids=solids, invalidObjects=sum(not o.Geometry.IsValid for o in checked.Objects),referenceNodeEmbedded=bool(original_count),nodePlacement='未自动落位,参考层隐藏',geometry='原生Extrusion实体与CAD曲线,保留原始节点Brep',materialMode='样板平均色 / 编码(完整纹理在GLB和Blender)') (out/'rhino-report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') print(json.dumps(report,ensure_ascii=False)) return report if __name__=='__main__':export(sys.argv[1],sys.argv[2],sys.argv[3])