/** Cesium-only adapter: terrain - virtual depth, ENU tiles, glTF GPU instance streams. */ import { Cartesian3, Cartographic, DistanceDisplayCondition, Matrix4, Model, Quaternion, Transforms, sampleTerrainMostDetailed } from 'cesium' import { planPipeModels, PIPE_MODEL_NOTE } from '../domain/pipeModels.js' import { createPipeModelBatches } from './pipeModelBatches.js' import { enuToGltf, instanceGltf } from './pipeInstanceGltf.js' import { PIPE_DISPLAY } from '../domain/pipeVisual.js' import { createPipeModelShader } from './pipeModelShader.js' const templates = new Map() const DEG = Math.PI / 180 const TILE_DEG = 0.01 const FAR_GUIDE = new DistanceDisplayCondition(PIPE_DISPLAY.guideFromM, Number.MAX_VALUE) const ALL_DISTANCES = new DistanceDisplayCondition(0, Number.MAX_VALUE) const gltfCoordinates = (point) => enuToGltf([point.x, point.y, point.z]) async function templateOf(kind, base) { const url = `${base}cockpit/models/pipes/${kind}.gltf` if (!templates.has(url)) { const promise = fetch(url).then(async (response) => { if (!response.ok) throw new Error(`管件素材 ${response.status}`) const gltf = await response.json() if (gltf.asset?.version !== '2.0' || gltf.nodes?.length !== 1 || !gltf.meshes?.length) throw new Error('Invalid pipe template') for (const buffer of gltf.buffers || []) { const resource = new URL(buffer.uri, new URL(url, window.location.href)) if (resource.origin !== window.location.origin) throw new Error('Pipe buffer must be same-origin') buffer.uri = resource.href } return gltf }).catch((error) => { templates.delete(url); throw error }) templates.set(url, promise) } return templates.get(url) } function rotationFromZ(direction) { const length = Cartesian3.magnitude(direction) const unit = Cartesian3.divideByScalar(direction, length, new Cartesian3()) const dot = Math.max(-1, Math.min(1, unit.z)) if (dot > 0.99999999) return [0,0,0,1] const axis = dot < -0.99999999 ? Cartesian3.UNIT_X : Cartesian3.normalize(Cartesian3.cross(Cartesian3.UNIT_Z, unit, new Cartesian3()), new Cartesian3()) const q = Quaternion.fromAxisAngle(axis, Math.acos(dot), new Quaternion()) return [q.x,q.y,q.z,q.w] } /** Geographic subspans lie ON the original path; not smoothing and not connection inference. */ function terrainSpans(instance) { if (instance.kind !== 'spline') return [instance] const a=instance.start,b=instance.end const approximateM=Math.hypot((b[0]-a[0])*Math.cos(a[1]*DEG),(b[1]-a[1]))*111320 const count=Math.max(1,Math.ceil(approximateM/20)) const point=(t)=>[a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t] return Array.from({length:count},(_,i)=>({...instance,start:point(i/count),end:point((i+1)/count)})) } async function groupsFor(viewer, plan, heights, alive) { const rows=plan.instances.flatMap(terrainSpans) const needed=new Map() const keyOf=(p)=>`${p[0]},${p[1]}` for(const row of rows) for(const point of row.kind==='spline'?[row.start,row.end]:[row.position]) { const key=keyOf(point) if(!heights.has(key)) needed.set(key,point) } const entries=[...needed] const chunks=[] for(let i=0;i{ while(alive()) { const index=cursor cursor+=1 if(index>=chunks.length) return const chunk=chunks[index] try { const values=await sampleTerrainMostDetailed(viewer.terrainProvider,chunk.map(([,p])=>Cartographic.fromDegrees(p[0],p[1]))) if(!alive()) return for(let j=0;j{ const height=heights.get(keyOf(p)) return Number.isFinite(height)?Cartesian3.fromDegrees(p[0],p[1],height-depthM):null } const groups=new Map(), missing=new Set() for(const row of rows) { const p=row.start||row.position const tileX=Math.floor(p[0]/TILE_DEG),tileY=Math.floor(p[1]/TILE_DEG) const key=`${tileX}:${tileY}:${row.kind}:${row.colorKey||'UNKNOWN'}:${row.surface?.kind || 'unknown'}` const origin=[(tileX+.5)*TILE_DEG,(tileY+.5)*TILE_DEG] const matrix=Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(...origin)) const inverse=Matrix4.inverseTransformation(matrix,new Matrix4()) const a=world(p,row.virtualDepthM),b=row.end?world(row.end,row.virtualDepthM):null if(!a||(row.end&&!b)){missing.add(row.id);continue} const local=Matrix4.multiplyByPoint(inverse,a,new Cartesian3()) let translation=gltfCoordinates(local),rotation=[0,0,0,1],scale=[row.sizeM,row.sizeM,row.sizeM] if(row.kind==='spline') { const end=Matrix4.multiplyByPoint(inverse,b,new Cartesian3()),delta=Cartesian3.subtract(end,local,new Cartesian3()) const length=Cartesian3.magnitude(delta) if(length<0.001){missing.add(row.id);continue} rotation=rotationFromZ(new Cartesian3(...gltfCoordinates(delta))) scale=[row.displayDiameterM,row.displayDiameterM,length] } if(!groups.has(key)) groups.set(key,{key,kind:row.kind,industry:row.industry,colorKey:row.colorKey||'UNKNOWN',surface:row.surface,origin,instances:[]}) groups.get(key).instances.push({id:row.id,translation,rotation,scale}) } // One missing span keeps its entire business pipe's fallback visible. return { groups:[...groups.values()], missing } } export function createCesiumPipeModels(viewer, { source, onChange=()=>{}, base=import.meta.env?.BASE_URL||'/', viewMode='ground', componentOverlayActive=()=>false }={}) { const heights=new Map() const guideStates=new WeakMap() let active=true,generation=0,fingerprint='',missing=new Set(),allIds=[],task=null,planning=false let lastGroups=[], signatures=new Map(), terrainFailed=false, lastTerrainAttempt=0 let diameterSummary={reported:0,interpolated:0,missing:0}, visualDefaultCount=0 let pipelineView=viewMode==='pipeline' // 最近一次拿到的管网数据。地面视图虽然不建模型,但必须**记住数据**: // 计划同步(`syncPipeLayerForPlan`)只由计划数组变化触发,切视图模式不会叫它, // 所以切回管线时只有这里能立刻重建(详见 setViewMode 的说明)。 let lastNetwork=null const publish=(state)=>{ if(!active) return const covered=new Set(state.covered.filter((id)=>!missing.has(id))) for(const entity of source.entities.values) { const modeled=covered.has(entity.id) if(entity.polyline) { if(entity.show!==true) entity.show=true const distantOnly=pipelineView&&modeled if(guideStates.get(entity.polyline)!==distantOnly) { entity.polyline.distanceDisplayCondition=distantOnly?FAR_GUIDE:ALL_DISTANCES guideStates.set(entity.polyline,distantOnly) } } else { // 票 101:地面视图的构件点位交给 DOM overlay 标记(icon+标签,与设备/设施同一套视觉), // Cesium 兜底点隐藏,避免同一构件出现两套视觉;管线视图保留原语义—— // 未建模(无 3D 模型)的构件仍用 Cesium 点兜底,不让构件在地下视图里消失。 const show = pipelineView ? !modeled : !componentOverlayActive() if(entity.show!==show) entity.show=show } } onChange({...state,covered:[...covered],fallback:allIds.length-covered.size,planning,terrainFailed,diameterSummary,visualDefaultCount,viewMode:pipelineView?'pipeline':'ground',note:PIPE_MODEL_NOTE}) viewer.scene.requestRender() } const batches=createPipeModelBatches({ load:async(group,events)=>{ const template=await templateOf(group.kind,base) if (!active || !events.alive() || viewer.isDestroyed()) throw new Error('Cancelled pipe batch') const gltf=instanceGltf(template,group.instances) // Use a public URL/Resource entry, not Cesium's private options.gltf JSON hook. const url=URL.createObjectURL(new Blob([JSON.stringify(gltf)],{type:'model/gltf+json'})) const shader=createPipeModelShader(group.colorKey, group.surface) let model try { model=await Model.fromGltfAsync({url,modelMatrix:Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(...group.origin)), id:{kind:'pipe-model-batch',key:group.key,instances:group.instances.map((row)=>row.id)},incrementallyLoadTextures:false, customShader:shader}) const release=()=>{ URL.revokeObjectURL(url) } model.readyEvent.addEventListener(()=>{release();events.ready()}) model.errorEvent.addEventListener(()=>{release();events.error()}) if(!active || !events.alive() || viewer.isDestroyed()){model.destroy();throw new Error('Disposed pipe batch')} viewer.scene.primitives.add(model) viewer.scene.requestRender() return {model,url,shader} } catch(error){URL.revokeObjectURL(url);shader.destroy();throw error} }, remove:({model,url,shader})=>{ URL.revokeObjectURL(url) if(!viewer.isDestroyed()&&!model.isDestroyed()) viewer.scene.primitives.remove(model) else if(!model.isDestroyed()) model.destroy() if(!shader.isDestroyed()) shader.destroy() }, onChange:publish, }) function sync(network) { if (!active || viewer.isDestroyed()) return Promise.resolve() lastNetwork = network // 维护者要求(第 352 轮):**地面视图不建任何管线 3D 模型**,只保留地图上的走向线。 // 原实现即使 `ground` 也照样采样地形、拼 GLTF、上传 GPU 模型 —— 那是纯浪费: // 地面视图下这些模型本来就被 `show=false` 隐藏,等于白花 CPU/GPU/内存。 // 这里显式清空批次并释放 GPU 资源,等切到管线视图再重建。 if (!pipelineView) { lastGroups = [] signatures = new Map() fingerprint = '' planning = false const cleared = batches.clear() // 票 101:地面视图也要 publish 一次 —— 构件点的 Cesium 兜底点必须在这里被隐藏 //(DOM overlay 标记接管),否则首次同步后地面视图会出现「DOM 标记 + Cesium 点」双视觉。 publish(batches.state()) return cleared } const plan=planPipeModels(network) diameterSummary=plan.diameterSummary visualDefaultCount=plan.visualDefaultCount const next=JSON.stringify(plan) if(next===fingerprint && !(terrainFailed && Date.now()-lastTerrainAttempt>=30000)) { if (planning) return task task=batches.sync(lastGroups) publish(batches.state()) return task } fingerprint=next const token=++generation const previousSignatures=signatures const byId=new Map() for(const row of plan.instances) { if(!byId.has(row.id)) byId.set(row.id,[]) byId.get(row.id).push(row) } signatures=new Map([...byId].map(([id,rows])=>[id,JSON.stringify(rows)])) allIds=[...(network.pipes||[]).map((p)=>`pipe:${p.code}`),...(network.components||[]).map((c)=>`component:${c.code}`)] planning=true // Remove only changed/removed batches before awaits. Keep stable geometry visible. batches.retain((group)=>group.instances.every((row)=>signatures.has(row.id)&&signatures.get(row.id)===previousSignatures.get(row.id))) task=(async()=>{ const alive=()=>active&&token===generation&&!viewer.isDestroyed() lastTerrainAttempt=Date.now() const result=await groupsFor(viewer,plan,heights,alive) if(!alive()) return missing=result.missing terrainFailed=missing.size>0 for(const row of plan.fallbacks) missing.add(row.id) lastGroups=result.groups planning=false await batches.sync(lastGroups) if(alive()) publish(batches.state()) })().catch(()=>{if(active&&token===generation){terrainFailed=true;planning=false;publish(batches.state())}}) return task } function destroy() { active=false;generation+=1 batches.clear() heights.clear() } function setViewMode(mode) { const next = mode==='pipeline' if (next === pipelineView) return pipelineView = next if (!pipelineView) { // 切回地面视图:立刻释放 GPU 模型(下一帧还会被 sync 的短路再确认一次)。 lastGroups = [] signatures = new Map() fingerprint = '' planning = false batches.clear() } publish(batches.state()) // 切回管线视图必须**自己重建**,不能等下一次计划同步。 // 缺陷复盘(维护者 2026-10-27 现场反馈):地面期已把批次清空,而计划同步只由 // MapCanvas 的 watch(依赖 markers/byStatus/pipelines/facilities,**不看 viewMode**) // 触发 —— 切视图模式根本叫不动它。旧实现里地面视图"顺手"把模型建好了, // 所以切过去立刻能看见;票 60 把地面建模去掉后这条顺带路径消失,现象变成: // 切到管线视图仍只显示地面视图的 2D 走向线,3D 模型要等下一次翻页/30s tick // 才可能出现,甚至一直不出现。 if (pipelineView && lastNetwork) void sync(lastNetwork) } return {sync,setViewMode,destroy,state:batches.state} }