// MapLibre/WebGL interoperability only. Telemetry decoding and UI state are Rust. import {attachTileBuffer} from './map-tile-buffer.js'; import * as maplibre from './vendor/maplibre-gl.mjs'; maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs'); let tileBuffer; let map, layer, latest, ids = [], selected = '', pending = false; let frameTimes = [], lastFrame = 0; let markers=new Map(), idIndexes=new Map(), markerInfos=null, markerScanDirty=true, lastMarkerScan=0, lastMarkerText=0; let history=[], lastTrail=0, generations=null, selectedGeneration=null, liveConnected=true; const MAX_VISIBLE_CARDS=120; let centered=false, workerWasmBytes=0, resizeObserver, rawFocus=null; let basemap="imagery",tileRevision=0,mapCreations=0; const basemapLayers={road:["vec_w","cva_w"],imagery:["img_w","cia_w"]}; function tileUrl(index){return `/api/maps/tile/${basemapLayers[basemap][index]}/{z}/{x}/{y}${tileRevision?`?v=${tileRevision}`:''}`;} let classification=new Map(),listFilter="all",sourceIds=null; function setSources(value){sourceIds=value?new Set(Array.from(value)):null;markerScanDirty=true;flush();} function targetKind(id){return classification.get(id)||"unknown";} function located(id,i=ids.indexOf(id)){if(i<0||!latest)return false;const lon=latest[i*4],lat=latest[i*4+1];return Number.isFinite(lon)&&Number.isFinite(lat)&&Math.abs(lon)<=180&&Math.abs(lat)<=90&&(lon!==0||lat!==0);} function passesFilters(id){return (!sourceIds||sourceIds.has(id))&&(listFilter==="all"||targetKind(id)===listFilter);} function targetVisible(id,i=ids.indexOf(id)){return passesFilters(id)&&located(id,i);} function setClassification(value,filter="all"){classification=new Map(Object.entries(value||{}).filter(([,kind])=>kind==="white"||kind==="black"));listFilter=["white","black","unknown"].includes(filter)?filter:"all";markerScanDirty=true;flush();} let occlusion={top:0,right:0,bottom:0,left:0}; let fenceEntries=[],fenceMarkers=[]; function clearFenceMarkers(){for(const marker of fenceMarkers)marker.remove();fenceMarkers=[];} function fenceRing(geometry){ if(!geometry)return null; if(geometry.type==='polygon'&&Array.isArray(geometry.vertices)){ const vertices=geometry.vertices.filter(point=>Array.isArray(point)&&Number.isFinite(point[0])&&Number.isFinite(point[1])&&Math.abs(point[0])<=180&&Math.abs(point[1])<=90); return vertices.length>=3?[...vertices,vertices[0]]:null; } const center=geometry.center,radius=geometry.radius_m; if(geometry.type!=='circle'||!Array.isArray(center)||!Number.isFinite(center[0])||!Number.isFinite(center[1])||Math.abs(center[0])>180||Math.abs(center[1])>90||!Number.isFinite(radius)||radius<1||radius>1000000)return null; const delta=radius/6371008.8,a=center[1]*Math.PI/180,b=center[0]*Math.PI/180,points=[]; for(let i=0;i<=96;i++){const bearing=i/96*2*Math.PI,p=Math.asin(Math.sin(a)*Math.cos(delta)+Math.cos(a)*Math.sin(delta)*Math.cos(bearing));const q=b+Math.atan2(Math.sin(bearing)*Math.sin(delta)*Math.cos(a),Math.cos(delta)-Math.sin(a)*Math.sin(p));points.push([q*180/Math.PI,p*180/Math.PI]);} return points; } function fenceLabelPoint(geometry){ if(geometry?.type==='circle'&&Array.isArray(geometry.center)&&geometry.center.every(Number.isFinite))return geometry.center; const ring=fenceRing(geometry); if(!ring)return null; const unique=ring.slice(0,-1),lon=unique.reduce((sum,point)=>sum+point[0],0)/unique.length,lat=unique.reduce((sum,point)=>sum+point[1],0)/unique.length; return Number.isFinite(lon)&&Number.isFinite(lat)?[lon,lat]:null; } function paintFences(){ if(!map?.getSource('fences'))return; clearFenceMarkers(); const features=[]; for(const fence of fenceEntries){ const ring=fenceRing(fence.geometry); if(!ring)continue; const enabled=fence.enabled!==false; features.push({type:'Feature',properties:{id:String(fence.id??''),name:String(fence.name??'围栏'),enabled},geometry:{type:'Polygon',coordinates:[ring]}}); const point=fenceLabelPoint(fence.geometry); if(!point)continue; const element=document.createElement('div'); element.className='rt-fence-label'; element.textContent=fence.name||'围栏'; element.dataset.enabled=enabled?'true':'false'; fenceMarkers.push(new maplibre.Marker({element,anchor:'center'}).setLngLat(point).addTo(map)); } map.getSource('fences').setData({type:'FeatureCollection',features}); } function setFences(entries){fenceEntries=Array.isArray(entries)?entries.filter(fence=>fence&&fence.geometry):[];paintFences();} function shader(gl, type, source) { const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s); if (!gl.getShaderParameter(s,gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));return s; } function create(container,initialBasemap="imagery",preferences=null) { basemap=initialBasemap==="road"?"road":"imagery";mapCreations++; tileBuffer?.destroy(); clearFenceMarkers(); clearTargetMarkers(); if (map) map.remove(); const initialCenter=preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)?[preferences.longitude,preferences.latitude]:[118.778863,32.043828]; // A configured startup camera takes precedence over the legacy first-target fallback. centered=!!(preferences&&Number.isFinite(preferences.longitude)&&Number.isFinite(preferences.latitude)); const initialZoom=Number.isFinite(preferences?.zoom)?Math.max(0,Math.min(18,preferences.zoom)):15; map=new maplibre.Map({container,center:initialCenter,zoom:initialZoom,pitch:0,bearing:0,maxZoom:18,maxTileCacheSize:1024,attributionControl:false, style:{version:8,sources:{ 'tdt-base':{type:'raster',tiles:[tileUrl(0)],tileSize:256,maxzoom:18,attribution:'天地图 © 自然资源部 / 本地缓存与离线资源'}, 'tdt-labels':{type:'raster',tiles:[tileUrl(1)],tileSize:256,maxzoom:18} },layers:[ {id:'background',type:'background',paint:{'background-color':'#060c18'}}, {id:'tdt-base',type:'raster',source:'tdt-base'}, {id:'tdt-labels',type:'raster',source:'tdt-labels'} ]}}); tileBuffer=attachTileBuffer(map,()=>basemap,()=>tileRevision); resizeObserver?.disconnect(); resizeObserver=new ResizeObserver(()=>map?.resize());resizeObserver.observe(document.getElementById(container)); map.addControl(new maplibre.AttributionControl({compact:true}),'bottom-right'); layer={id:'rid-targets',type:'custom',renderingMode:'2d', onAdd(map,gl){ if (!gl.drawArraysInstanced) throw new Error('WebGL2 required'); this.gl=gl;this.map=map;this.origin=maplibre.MercatorCoordinate.fromLngLat(initialCenter); this.program=gl.createProgram(); this.vs=shader(gl,gl.VERTEX_SHADER,`#version 300 es precision highp float; in vec2 shape; in vec4 target; uniform mat4 matrix; uniform vec2 pixel; uniform float bearing; out float chosen; void main(){vec4 p=matrix*vec4(target.xy,0.,1.);float c=cos(target.z+bearing),s=sin(target.z+bearing);vec2 q=vec2(shape.x*c-shape.y*s,shape.x*s+shape.y*c);p.xy+=q*pixel*p.w;gl_Position=p;chosen=target.w;}`); this.fs=shader(gl,gl.FRAGMENT_SHADER,`#version 300 es precision highp float; in float chosen; out vec4 color; void main(){float kind=floor(chosen/2.);float picked=mod(chosen,2.);vec4 base=kind>1.5?vec4(.98,.42,.39,1.):kind>.5?vec4(.38,.82,.63,1.):vec4(.22,.74,.97,1.);color=kind<.5?mix(base,vec4(1.,.75,.15,1.),picked):mix(base,vec4(1.),picked*.25);}`); gl.attachShader(this.program,this.vs);gl.attachShader(this.program,this.fs);gl.linkProgram(this.program); if (!gl.getProgramParameter(this.program,gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(this.program)); this.vao=gl.createVertexArray();gl.bindVertexArray(this.vao); this.shape=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.shape);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([0,10,-6,-6,0,-2,0,10,0,-2,6,-6]),gl.STATIC_DRAW); const a=gl.getAttribLocation(this.program,'shape');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0); this.instances=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.instances);gl.bufferData(gl.ARRAY_BUFFER,10000*16,gl.DYNAMIC_DRAW); const b=gl.getAttribLocation(this.program,'target');gl.enableVertexAttribArray(b);gl.vertexAttribPointer(b,4,gl.FLOAT,false,16,0);gl.vertexAttribDivisor(b,1); gl.bindVertexArray(null);this.count=0;this.matrix=gl.getUniformLocation(this.program,'matrix');this.pixel=gl.getUniformLocation(this.program,'pixel');this.bearing=gl.getUniformLocation(this.program,'bearing'); }, render(gl,args){ if (!this.count || !this.map.getCanvas().clientWidth || !this.map.getCanvas().clientHeight) return; const source=args.defaultProjectionData?.mainMatrix || args.modelViewProjectionMatrix; if (!source) return; const m=new Float32Array(source);for(let r=0;r<4;r++)m[12+r]=source[r]*this.origin.x+source[4+r]*this.origin.y+source[12+r]; gl.useProgram(this.program);gl.bindVertexArray(this.vao);gl.uniformMatrix4fv(this.matrix,false,m);gl.uniform2f(this.pixel,2/this.map.getCanvas().clientWidth,2/this.map.getCanvas().clientHeight);gl.uniform1f(this.bearing,this.map.getBearing()*Math.PI/180); gl.disable(gl.DEPTH_TEST);gl.drawArraysInstanced(gl.TRIANGLES,0,6,this.count);gl.bindVertexArray(null); const now=performance.now();if(lastFrame)frameTimes.push(now-lastFrame);lastFrame=now;if(frameTimes.length>300)frameTimes.shift(); }, onRemove(map,gl){gl.deleteBuffer(this.shape);gl.deleteBuffer(this.instances);gl.deleteVertexArray(this.vao);gl.deleteProgram(this.program);gl.deleteShader(this.vs);gl.deleteShader(this.fs);} }; map.on('style.load',()=>{ // Mission Control tactical radar grid & range rings const features=[]; for(let lon=initialCenter[0]-2;lon<=initialCenter[0]+2;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,initialCenter[1]-2],[lon,initialCenter[1]+2]]},properties:{}}); for(let lat=initialCenter[1]-2;lat<=initialCenter[1]+2;lat+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[initialCenter[0]-2,lat],[initialCenter[0]+2,lat]]},properties:{}}); // Concentric tactical range rings around default center const center=initialCenter; for(const radiusKm of [1, 2, 5, 10]) { const ring=[]; for(let a=0;a<=360;a+=6){ const rad=a*Math.PI/180; const dLat=(radiusKm/111)*Math.cos(rad); const dLon=(radiusKm/(111*Math.cos(center[1]*Math.PI/180)))*Math.sin(rad); ring.push([center[0]+dLon, center[1]+dLat]); } features.push({type:'Feature',geometry:{type:'LineString',coordinates:ring},properties:{}}); } map.addSource('grid',{type:'geojson',data:{type:'FeatureCollection',features}}); map.addLayer({id:'grid',type:'line',source:'grid',paint:{'line-color':'rgba(48,100,180,0.3)','line-width':1,'line-dasharray':[2,2]}}); map.addSource('selected-trail',{type:'geojson',data:{type:'FeatureCollection',features:[]}}); map.addLayer({id:'selected-trail',type:'line',source:'selected-trail',paint:{'line-color':'#38bdf8','line-width':3,'line-blur':1}}); map.addSource('fences',{type:'geojson',data:{type:'FeatureCollection',features:[]}}); map.addLayer({id:'fence-fill',type:'fill',source:'fences',paint:{'fill-color':['case',['get','enabled'],'#5ba6ed','#8192a5'],'fill-opacity':['case',['get','enabled'],.18,.08]}}); map.addLayer({id:'fence-line',type:'line',source:'fences',paint:{'line-color':['case',['get','enabled'],'#9fd4ff','#8192a5'],'line-width':['case',['get','enabled'],2,1.5]}}); map.addLayer(layer);paintFences();flush(); }); map.on('click',event=>{ if(!latest)return;let index=-1,distance=18; for(let i=0;i=0)window.dispatchEvent(new CustomEvent('rid-select',{detail:ids[index]})); }); map.on('moveend',()=>{markerScanDirty=true;syncTargetMarkers(true);}); map.on('error',e=>{if(!e.sourceId?.startsWith('tdt-'))console.error('map:',e.error?.message || e);}); return true; } function flush(){ pending=false;if(!latest||!layer?.gl)return;const gl=layer.gl; const data=new Float32Array(ids.length*4);let visible=0;for(let i=0;i=0&&targetVisible(selected)){ rawFocus=null; const coordinate=[latest[index*4],latest[index*4+1]]; const now=performance.now();if(now-lastTrail>=100){lastTrail=now;history.push({time:now,coordinate});history=history.filter(p=>now-p.time<30000).slice(-200); map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:history.length<2?[]:[{type:'Feature',properties:{},geometry:{type:'LineString',coordinates:history.map(p=>p.coordinate)}}]});} }else{history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});} syncTargetMarkers(); } function update(positions,newIds,newGenerations,newMarkerInfos){latest=positions;generations=newGenerations;markerInfos=newMarkerInfos||null;if(newIds){ids=Array.from(newIds);idIndexes=new Map(ids.map((id,index)=>[id,index]));markerScanDirty=true;}const selectedIndex=ids.indexOf(selected);if(selected&&selectedIndex<0){selected='';rawFocus=null;markerScanDirty=true;}const generation=selectedIndex>=0?generations?.[selectedIndex]:null;if(!located(selected)||generation!==selectedGeneration){history=[];lastTrail=0;}selectedGeneration=generation;if(!centered){const i=ids.findIndex(located);if(i>=0){centered=true;focusCoordinate([latest[i*4],latest[i*4+1]], false);}}if(!pending){pending=true;requestAnimationFrame(flush);}} function clearTargetMarkers(){for(const entry of markers.values())entry.marker.remove();markers.clear();markerScanDirty=true;lastMarkerScan=0;lastMarkerText=0;} function markerCoordinate(id,index){ if(targetVisible(id,index))return {coordinate:[latest[index*4],latest[index*4+1]],unverified:false}; if(id===selected&&rawFocus&&passesFilters(id))return {coordinate:rawFocus,unverified:true}; return null; } function markerFrequency(value){if(!liveConnected)return '连接断开';if(!Number.isFinite(value)||value<0)return '—';if(value===0)return '0 Hz';if(value<0.1)return `${value.toFixed(2)} Hz`;if(value<100)return `${value.toFixed(1)} Hz`;return `${Math.round(value)} Hz`;} function createTargetMarker(id,coordinate){ const root=document.createElement('div');root.className='rt-target-pin'; const card=document.createElement('div');card.className='rt-target-info'; const header=document.createElement('div');header.className='rt-target-info-head'; const name=document.createElement('span');name.className='rt-target-info-id';name.textContent=id;name.title=id; const frequency=document.createElement('span');frequency.className='rt-target-info-frequency';frequency.title='服务端接受的目标数据更新频率;多个接收来源合计,5 秒无更新时显示 0 Hz'; header.append(name,frequency); const coordinates=document.createElement('div');coordinates.className='rt-target-info-coordinates'; const longitude=document.createElement('span');const latitude=document.createElement('span');coordinates.append(longitude,latitude); const height=document.createElement('div');height.className='rt-target-info-height'; const verification=document.createElement('div');verification.className='rt-target-info-verification'; card.append(header,coordinates,height,verification); const icon=document.createElement('button');icon.type='button';icon.className='rt-drone-icon';icon.setAttribute('aria-label',`选择目标 ${id}`); icon.innerHTML=''; icon.addEventListener('click',event=>{event.stopPropagation();window.dispatchEvent(new CustomEvent('rid-select',{detail:id}));}); const point=document.createElement('i');point.className='rt-drone-point'; root.append(card,icon,point); const marker=new maplibre.Marker({element:root,anchor:'bottom'}).setLngLat(coordinate).addTo(map); return {marker,root,card,name,frequency,longitude,latitude,height,verification,icon,coordinate:[...coordinate]}; } function syncTargetMarkers(force=false){ if(!map||!latest)return; const now=performance.now(),scan=force||markerScanDirty||now-lastMarkerScan>=250; if(scan){ const wanted=new Set(),canvas=map.getCanvas(),width=canvas.clientWidth,height=canvas.clientHeight; const chosen=idIndexes.get(selected); if(chosen!==undefined&&markerCoordinate(selected,chosen))wanted.add(selected); for(let i=0;i=-240&&pixel.x<=width+240&&pixel.y>=-150&&pixel.y<=height+150)wanted.add(id); } for(const [id,entry] of markers){if(!wanted.has(id)){entry.marker.remove();markers.delete(id);}} for(const id of wanted){if(!markers.has(id)){const i=idIndexes.get(id),position=markerCoordinate(id,i);if(position)markers.set(id,createTargetMarker(id,position.coordinate));}} lastMarkerScan=now;markerScanDirty=false; } const updateText=force||scan||now-lastMarkerText>=200; for(const [id,entry] of markers){ const index=idIndexes.get(id),position=index===undefined?null:markerCoordinate(id,index); if(!position){entry.marker.remove();markers.delete(id);continue;} const [lon,lat]=position.coordinate; if(entry.coordinate[0]!==lon||entry.coordinate[1]!==lat){entry.marker.setLngLat(position.coordinate);entry.coordinate=[lon,lat];} if(!updateText)continue; const selectedNow=id===selected,kind=targetKind(id); entry.root.dataset.listKind=kind;entry.root.dataset.selected=selectedNow?'true':'false';entry.root.style.zIndex=selectedNow?'10':'1';entry.icon.setAttribute('aria-pressed',selectedNow?'true':'false'); entry.name.textContent=id+(kind==='black'?' · 黑名单':kind==='white'?' · 白名单':'');entry.name.title=entry.name.textContent; entry.longitude.textContent=`经度 ${lon.toFixed(6)}`;entry.latitude.textContent=`纬度 ${lat.toFixed(6)}`; const value=markerInfos?.[index*3+1],heightKind=markerInfos?.[index*3+2]; const label=({1:'高度',2:'几何高度',3:'离地高度',4:'相对高度(原始)',5:'气压高度'})[heightKind]||'高度'; entry.height.textContent=`${label} ${Number.isFinite(value)?`${value.toFixed(1)} m`:'—'}`; entry.frequency.textContent=`数据频率 ${markerFrequency(markerInfos?.[index*3])}`; entry.verification.textContent=position.unverified?'坐标待核实':''; } if(updateText)lastMarkerText=now; } function rawPoint(point){if(!Array.isArray(point)||point.length<2)return null;const [lon,lat]=point;return Number.isFinite(lon)&&Number.isFinite(lat)&&Math.abs(lon)<=180&&Math.abs(lat)<=90&&(lon!==0||lat!==0)?[lon,lat]:null;} function updateRaw(point){if(!map||!selected||!ids.includes(selected))return;const next=rawPoint(point);if((next?.[0]??null)!==(rawFocus?.[0]??null)||(next?.[1]??null)!==(rawFocus?.[1]??null))markerScanDirty=true;rawFocus=next;flush();} function focusRaw(point){const position=rawPoint(point);if(!map||!selected||!ids.includes(selected)||!position)return;rawFocus=position;markerScanDirty=true;focusCoordinate(position);flush();} function select(id){if(selected!==id){selected=id;history=[];rawFocus=null;selectedGeneration=generations?.[ids.indexOf(id)]??null;markerScanDirty=true;flush();}if(located(id)){rawFocus=null;centerSelected();}const i=ids.indexOf(id);return located(id)?Array.from(latest.slice(i*4,i*4+4)):[];} function metrics(){const sorted=[...frameTimes].sort((a,b)=>a-b);const gl=layer?.gl;const ext=gl?.getExtension('WEBGL_debug_renderer_info');const projected=map&&located(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {tileBuffer:tileBuffer?.metrics(),basemap,mapCreations,camera:map?{center:map.getCenter().toArray(),zoom:map.getZoom(),pitch:map.getPitch(),bearing:map.getBearing()}:null,baseTiles:map?.getSource('tdt-base')?.tiles,labelTiles:map?.getSource('tdt-labels')?.tiles,selectedPixel:projected?{x:projected.x,y:projected.y}:null,occlusion:{...occlusion},mapReady:!!layer?.gl,styleReady:map?.isStyleLoaded()||false,mapCanvasWidth:map?.getCanvas().clientWidth||0,mapCanvasHeight:map?.getCanvas().clientHeight||0,samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,visibleTargets:ids.filter(targetVisible).length,listFilter,classifiedTargets:{white:ids.filter(id=>targetKind(id)==="white").length,black:ids.filter(id=>targetKind(id)==="black").length},renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes,fences:fenceEntries.length};} function connection(connected){const changed=liveConnected!==connected;liveConnected=connected;const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';if(changed)syncTargetMarkers(true);} function refresh(){tileRevision++;tileBuffer?.schedule();for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);} function setBasemap(value){const next=value==='road'?'road':'imagery';if(next!==basemap){basemap=next;for(const [i,id]of ['tdt-base','tdt-labels'].entries())map?.getSource(id)?.setTiles([tileUrl(i)]);tileBuffer?.schedule();}} function baseReady(ready){if(map?.getLayer('grid'))map.setLayoutProperty('grid','visibility',ready?'none':'visible');} function setOcclusion(value){ occlusion=Object.fromEntries(['top','right','bottom','left'].map(k=>[k,Number.isFinite(value?.[k])?Math.max(0,value[k]):0])); } function visiblePadding(){ if(!map)return {top:0,right:0,bottom:0,left:0}; const w=map.getCanvas().clientWidth,h=map.getCanvas().clientHeight; const p={...occlusion}; // Hidden mobile overlays may have just closed; measure visible panels at focus time. const root=document.getElementById('rt-layout')?.getBoundingClientRect(); if(root){const scale=Math.max(.01,root.width/w);for(const [id,side] of [['rt-directory','left'],['rt-details','right']]){const el=document.getElementById(id);const r=el?.getBoundingClientRect();p[side]=r?.height?side==='left'?(r.right-root.left)/scale+12:(root.right-r.left)/scale+12:0;} const manager=document.getElementById("rt-list-manager")?.getBoundingClientRect();if(manager?.height)p.right=Math.max(p.right,(root.right-manager.left)/scale+12); const dock=document.getElementById('rt-dock')?.getBoundingClientRect();p.bottom=dock?.height?(root.bottom-dock.top)/scale+40:116; } if(p.left+p.right>w-80){p.left=0;p.right=0;} if(p.top+p.bottom>h-80){p.top=0;p.bottom=0;} return p; } function focusCoordinate(center,animate=true){ if(!map)return; const p=visiblePadding(); const options={center,offset:[(p.left-p.right)/2,(p.top-p.bottom)/2]}; if(animate)map.flyTo({...options,zoom:Math.max(map.getZoom(),13),duration:400});else map.easeTo({...options,duration:0}); } function centerSelected(){if(!map||!latest||!selected)return;const i=ids.indexOf(selected);if(i>=0&&located(selected))focusCoordinate([latest[i*4],latest[i*4+1]]);} window.ridMap={setSources,setFences,workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,focusRaw,updateRaw,metrics,connection,refresh,setBasemap,setClassification,baseReady,setOcclusion,focusVisible(){requestAnimationFrame(()=>requestAnimationFrame(centerSelected));},zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected,resetBearing(){if(map)map.resetNorthPitch({duration:400});},toggle3d(){if(!map)return;const p=map.getPitch();map.easeTo({pitch:p>10?0:55,duration:500});},destroy(){clearFenceMarkers();fenceEntries=[];tileBuffer?.destroy();tileBuffer=null;resizeObserver?.disconnect();resizeObserver=null;clearTargetMarkers();history=[];rawFocus=null;generations=null;markerInfos=null;selectedGeneration=null;map?.remove();map=null;layer=null;latest=null;ids=[];idIndexes.clear();selected='';liveConnected=true;centered=false;classification=new Map();listFilter="all";sourceIds=null;occlusion={top:0,right:0,bottom:0,left:0};}};