// MapLibre/WebGL interoperability only. Telemetry decoding and UI state are Rust. import * as maplibre from './vendor/maplibre-gl.mjs'; maplibre.setWorkerUrl('/vendor/maplibre-gl-worker.mjs'); let map, layer, latest, ids = [], selected = '', pending = false; let frameTimes = [], lastFrame = 0; let marker=null, history=[], lastTrail=0; let centered=false, workerWasmBytes=0; 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) { if (map) map.remove(); map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:35,bearing:0,attributionControl:false, style:{version:8,sources:{ 'tdt-base':{type:'raster',tiles:['/api/maps/tile/img_w/{z}/{x}/{y}'],tileSize:256,maxzoom:18,attribution:'天地图卫星 / 本地离线资源'}, 'tdt-labels':{type:'raster',tiles:['/api/maps/tile/cia_w/{z}/{x}/{y}'],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'} ]}}); 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([120.1538,30.2874]); 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(){color=mix(vec4(.22,.74,.97,1.),vec4(1.,.75,.15,1.),chosen);}`); 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) 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('load',()=>{ // Mission Control tactical radar grid & range rings const features=[]; for(let lon=118;lon<=122;lon+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[lon,28],[lon,32]]},properties:{}}); for(let lat=28;lat<=32;lat+=.05)features.push({type:'Feature',geometry:{type:'LineString',coordinates:[[118,lat],[122,lat]]},properties:{}}); // Concentric tactical range rings around default center const center=[120.1538,30.2874]; 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.addLayer(layer);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('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);for(let i=0;i=0){ const coordinate=[latest[index*4],latest[index*4+1]]; if(!marker){const label=document.createElement('div');label.className='rt-target-label';marker=new maplibre.Marker({element:label,anchor:'bottom'}).setLngLat(coordinate).addTo(map);} marker.getElement().textContent=selected;marker.setLngLat(coordinate); 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{marker?.remove();marker=null;history=[];map.getSource('selected-trail')?.setData({type:'FeatureCollection',features:[]});} } function update(positions,newIds){latest=positions;if(newIds)ids=Array.from(newIds);if(!centered&&latest.length>=4){centered=true;map.jumpTo({center:[latest[0],latest[1]]});}if(!pending){pending=true;requestAnimationFrame(flush);}} function select(id){if(selected!==id){selected=id;history=[];flush();}const i=ids.indexOf(id);return i>=0&&latest?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');return {samples:sorted.length,drawSubmissionIntervalP95Ms:sorted[Math.floor(sorted.length*.95)]||0,targets:ids.length,renderer:ext?gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):'unavailable',selectedTrailPoints:history.length,workerWasmBytes};} function connection(connected){const canvas=document.querySelector('.rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';} function refresh(){for(const [id,layer]of [['tdt-base','img_w'],['tdt-labels','cia_w']])map?.getSource(id)?.setTiles([`/api/maps/tile/${layer}/{z}/{x}/{y}`]);} window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,metrics,connection,refresh,zoomIn(){if(map)map.zoomIn();},zoomOut(){if(map)map.zoomOut();},centerSelected(){if(!map||!latest||!selected)return;const index=ids.indexOf(selected);if(index>=0){map.flyTo({center:[latest[index*4],latest[index*4+1]],zoom:Math.max(map.getZoom(),13),essential:true});}},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(){marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;}};