feat(target-lists): 新增黑白名单管理与实时告警功能 - rid-shared 新增 target_lists 模块,定义名单数据契约 - 地图适配器支持按名单类型着色渲染目标(白/黑/未知) - 新增名单筛选器与目标目录过滤联动 - 实时详情面板支持加入/编辑白名单与黑名单操作 - 新增黑名单命中告警横幅与事件日志高亮 - 新增名单管理浮层(Manager 组件)与徽章展示 - 底图默认切换为影像图,相机初始俯仰角归零 - color-scheme 切换为 dark,新增 glass/workbench 样式 ```
140 lines
13 KiB
JavaScript
140 lines
13 KiB
JavaScript
// 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, resizeObserver;
|
|
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}?v=${tileRevision}`;}
|
|
let classification=new Map(),listFilter="all";
|
|
function targetKind(id){return classification.get(id)||"unknown";}
|
|
function targetVisible(id){return listFilter==="all"||targetKind(id)===listFilter;}
|
|
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";flush();}
|
|
let occlusion={top:0,right:0,bottom:0,left: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,initialBasemap="imagery") {
|
|
basemap=initialBasemap==="road"?"road":"imagery";mapCreations++;
|
|
if (map) map.remove();
|
|
map=new maplibre.Map({container,center:[120.1538,30.2874],zoom:11,pitch:0,bearing:0,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'}
|
|
]}});
|
|
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([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(){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) 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=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<ids.length;i++){if(!targetVisible(ids[i]))continue;const p=map.project([latest[i*4],latest[i*4+1]]);const d=Math.hypot(p.x-event.point.x,p.y-event.point.y);if(d<distance){index=i;distance=d;}}
|
|
if(index>=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);let visible=0;for(let i=0;i<ids.length;i++){if(!targetVisible(ids[i]))continue;const j=visible++;const p=maplibre.MercatorCoordinate.fromLngLat([latest[i*4],latest[i*4+1]]);data[j*4]=p.x-layer.origin.x;data[j*4+1]=p.y-layer.origin.y;data[j*4+2]=-latest[i*4+3]*Math.PI/180;const kind=targetKind(ids[i]);data[j*4+3]=(kind==="black"?4:kind==="white"?2:0)+(ids[i]===selected?1:0);}
|
|
gl.bindBuffer(gl.ARRAY_BUFFER,layer.instances);gl.bufferSubData(gl.ARRAY_BUFFER,0,data);layer.count=visible;map.triggerRepaint();
|
|
const index=ids.indexOf(selected);
|
|
if(index>=0&&targetVisible(selected)){
|
|
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+(targetKind(selected)==="black"?" · 黑名单":targetKind(selected)==="white"?" · 白名单":"");marker.getElement().dataset.listKind=targetKind(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;focusCoordinate([latest[0],latest[1]], false);}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');const projected=map&&latest&&ids.includes(selected)?map.project([latest[ids.indexOf(selected)*4],latest[ids.indexOf(selected)*4+1]]):null;return {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};}
|
|
function connection(connected){const canvas=document.getElementById('rt-map');if(canvas)canvas.dataset.stale=connected?'false':'true';}
|
|
function refresh(){tileRevision++;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;refresh();}}
|
|
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)focusCoordinate([latest[i*4],latest[i*4+1]]);}
|
|
window.ridMap={workerMemory(bytes){if(Number.isFinite(bytes))workerWasmBytes=bytes;},create,update,select,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(){resizeObserver?.disconnect();resizeObserver=null;marker?.remove();marker=null;history=[];map?.remove();map=null;layer=null;latest=null;ids=[];centered=false;classification=new Map();listFilter="all";occlusion={top:0,right:0,bottom:0,left:0};}};
|