Vue3 + Canvas/WebGL 雷达扫描可视化实战:PPI、RHI、VOL、SVOL 四种模式原理与实现
关键词:Vue3、TypeScript、Canvas 2D、WebGL2、雷达扫描、PPI、RHI、VOL、SVOL、速度色标、极坐标绘制
前言
做气象/风场类上位机时,最容易混淆的不是接口,而是"雷达到底在扫什么"。同样是速度数据,为什么有的图是整圆、有的是半圆剖面、有的能转成 3D 体扫?
本文基于项目里的真实组件,把雷达扫描的几种典型模式和实现方式拆开讲清楚:
- PPI:平面位置显示,固定俯仰角,方位角 0°~360° 扫一圈
- RHI:距离高度显示,固定方位角,俯仰角扫一个垂直剖面
- VOL:体扫,多俯仰层叠加成 3D 体积
- SVOL:扇区体扫,与 VOL 的区别在拼接方式
- RealTime 系列:增量式实时扫描与波束拖尾
正文按模式拆解实现思路,每个模式后附上对应组件的完整源码,可直接对照阅读。
一、先理解雷达的球坐标系
雷达测量的本质是三个量:
r:目标到雷达的距离(距离门)azimuth:方位角,水平面内 0°~360°elevation:俯仰角,天线抬升角度
再加上一个目标沿波束方向的速度分量 speed,就得到一条"射线"上的径向速度序列。
所谓扫描模式,无非是固定其中一个角、让另一个角变化:
| 模式 | 固定角 | 变化角 | 视图形态 | 本项目组件 |
|---|---|---|---|---|
| PPI | 俯仰角 elevation | 方位角 azimuth 0°~360° | 整圆俯视图 | PPIChart.vue |
| RHI | 方位角 azimuth | 俯仰角 elevation | 上半圆垂直剖面 | RHIChart.vue |
| VOL | 无(多层) | 每层做一次 PPI | 3D 体积 | VOLChart.vue |
| SVOL | 无(多层扇区) | 扇区内多仰角 | 3D 扇区体积 | SVOLChart.vue |
理解这张表,后面的代码就顺了。
二、统一的数据结构
几条图表能共用一套绘制思路,前提是后端返回的数据结构一致。实际数据大致长这样:
json
{
"Scan": { "RTC": "2026-11-20T10:00:00" },
"Scans": [
{
"Mode": "PPI",
"AzimuthCurrent": 30,
"ElevationCurrent": 5,
"StartDistance": 0,
"GateDistance": 30,
"SpeedRadial": [1.2, 2.3, 999, 4.5]
}
]
}
关键字段说明:
AzimuthCurrent:当前方位角ElevationCurrent:当前俯仰角StartDistance:起始距离GateDistance:距离门间隔SpeedRadial:一条射线上每个距离门的速度数组999:约定为无效值(No Data),绘制时必须跳过
每个距离门对应的距离是:
ts
const distance = startDist + index * gateDist;
这条公式在 PPI、RHI、VOL 里反复出现,是整个绘制的地基。
三、PPI:整圆俯视图
3.1 坐标映射
PPI 的 canvas 圆心在容器中心,半径取短边的一半再留边距:
ts
const cx = containerWidth / 2;
const cy = containerHeight / 2;
const radius = Math.min(containerWidth, containerHeight) / 2 - 40;
屏幕坐标里 0° 朝上,而 canvas 的角度 0 是朝右,所以统一做 -90° 的偏移:
ts
const rad = ((angle - 90) * Math.PI) / 180;
const x = cx + r * Math.cos(rad);
const y = cy + r * Math.sin(rad);
3.2 网格与标注
同心圆按量程自适应,保证环间隔是"整数感"的:
ts
const gridStep = Math.max(1000, Math.ceil(maxDistance / 10 / 1000) * 1000);
const gridCount = Math.floor(maxDistance / gridStep);
for (let i = 1; i <= gridCount; i++) {
const r = (i * gridStep / maxDistance) * radius;
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.stroke();
}
径向线每 45° 一条,共 8 条,最外圈和 0° 主线加粗。
3.3 扇形色块怎么画
这是 PPI 的核心。每个距离门不是一个点,而是一个环形扇区:角度宽度是一个步长,径向宽度是一个距离门。
ts
// 半波束宽度:优先用相邻扫描角的差值,兜底 0.5°
const halfAngleDeg = step && step > 0 ? step / 2 : 0.5;
const halfAngleRad = (halfAngleDeg * Math.PI) / 180;
const rad = ((angle - 90) * Math.PI) / 180;
const startRad = rad - halfAngleRad;
const endRad = rad + halfAngleRad;
// 外弧逆时针 + 内弧顺时针,闭合后就是一个环形扇区
ctx.beginPath();
ctx.arc(cx, cy, r2, startRad, endRad);
ctx.arc(cx, cy, r1, endRad, startRad, true);
ctx.closePath();
ctx.fill();
r1 是本距离门的半径,r2 是下一个距离门的半径:
ts
const r1 = (dist / maxDistance) * radius;
const nextDist = i + 1 < distances.length ? distances[i + 1] : dist + gateDist;
const r2 = Math.min((nextDist / maxDistance) * radius, radius);
两个 arc 一个正一个反,这是画"环扇区"的标准写法,比 fillRect 或手算多边形省事得多。
3.4 速度色标
速度采用固定的绝对色标,范围 -50 ~ +50 m/s,负值表示朝向雷达,正值表示远离:
ts
const VELOCITY_COLOR_STOPS = [
{ speed: -50, rgb: [59, 15, 111] }, // 深紫
{ speed: -30, rgb: [0, 128, 255] }, // 天蓝
{ speed: 0, rgb: [160, 160, 160] },// 灰(零速)
{ speed: 30, rgb: [255, 60, 0] }, // 橙红
{ speed: 50, rgb: [139, 0, 0] }, // 紫红
];
颜色采样做了 Map 缓存,避免每帧重复插值:
ts
const key = Math.round(speed * 10);
const cached = velocityColorCache.get(key);
if (cached) return cached;
同目录下的 ScanChart1.vue 则是另一种做法:按当前帧的 speedMin/speedMax 做归一化,再用蓝→青→绿→黄→红映射。固定色标适合对比多帧,动态色标适合突出单帧细节,按业务选。
3.5 DPR 适配
高分屏下必须处理 devicePixelRatio,否则图会糊:
ts
const dpr = window.devicePixelRatio || 1;
canvas.width = containerWidth * dpr;
canvas.height = containerHeight * dpr;
canvas.style.width = '100%';
canvas.style.height = '100%';
ctx.scale(dpr, dpr);
注意 ctx.scale 只调用一次,绘制逻辑里的坐标仍然按 CSS 像素算。
PPIChart.vue 完整源码
vue
<template>
<div class="radar-ppi-container">
<div class="radar-canvas-wrapper">
<canvas ref="canvasRef" class="radar-canvas"></canvas>
<!-- 左上角实时扫描雷达 -->
<div class="realtime-radar-panel">
<RealTimePPIChart />
</div>
<!-- 信息面板(左上角) -->
<div class="radar-info-panel">
<div>模式:{{ scanParams.mode }}</div>
<div>
俯仰角:{{
formatRange(scanParams.elevationMin, scanParams.elevationMax)
}}
</div>
<div>
方位角:{{
formatRange(scanParams.azimuthMin, scanParams.azimuthMax)
}}
</div>
<div>
步长:{{ scanParams.step !== null ? scanParams.step + "°" : "--" }}
</div>
<div v-if="currentData">时间:{{ currentData.time }}</div>
</div>
<!-- 图例(右下角) -->
<div class="radar-legend">
<canvas ref="legendCanvas" class="legend-canvas"></canvas>
<div class="legend-labels">
<span>{{ legendMinSpeed }} m/s</span>
<span>{{ legendMaxSpeed }} m/s</span>
</div>
</div>
<!-- 缩放控件(右下角) -->
<div class="zoom-controls">
<button
class="zoom-btn"
@click="handleZoomOut"
:disabled="zoomLevel <= ZOOM_MIN"
title="缩小"
>
−
</button>
<span class="zoom-level">{{ zoomLevel.toFixed(1) }}</span>
<button
class="zoom-btn"
@click="handleZoomIn"
:disabled="zoomLevel >= ZOOM_MAX"
title="放大"
>
+
</button>
<span class="zoom-divider"></span>
<button
class="zoom-btn reset-btn"
@click="resetZoom"
:disabled="panX === 0 && panY === 0 && zoomLevel === 1"
title="回到原点"
>
<el-icon><Aim /></el-icon>
</button>
</div>
<!-- ===== 时间轴(使用 el-slider) ===== -->
<div class="timeline-container" v-if="frames.length > 0">
<div class="timeline-header">
<span class="timeline-label-left">{{
getFullTimeLabel(frames[0])
}}</span>
<div class="timeline-current-group">
<button
class="time-nav-btn"
:disabled="currentFrameIndex <= 0"
title="上一帧"
@click="stepFrame(-1)"
>
<el-icon><ArrowLeft /></el-icon>
</button>
<span class="timeline-current">{{ currentTimeLabel }}</span>
<button
class="time-nav-btn"
:disabled="currentFrameIndex >= frames.length - 1"
title="下一帧"
@click="stepFrame(1)"
>
<el-icon><ArrowRight /></el-icon>
</button>
</div>
<span class="timeline-label-right">{{
getFullTimeLabel(frames[frames.length - 1])
}}</span>
</div>
<el-slider
v-model="currentFrameIndex"
:min="0"
:max="frames.length - 1"
:marks="timeMarks"
@change="onSliderChange"
size="small"
:show-tooltip="false"
class="timeline-slider"
/>
</div>
<!-- Tooltip -->
<div
v-if="tooltip.visible"
class="radar-tooltip"
:style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"
>
<div>
距离:{{ tooltip.distance !== null ? tooltip.distance + "m" : "--" }}
</div>
<div>
角度:{{ tooltip.angle !== null ? tooltip.angle + "°" : "--" }}
</div>
<div>
速度:{{
tooltip.speed !== null ? tooltip.speed.toFixed(1) + " m/s" : "--"
}}
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import {
ref,
computed,
watch,
onMounted,
onBeforeUnmount,
inject,
nextTick,
type Ref,
} from "vue";
import { Aim, ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import RealTimePPIChart from "./RealTimePPIChart.vue";
// ============================================================
// 注入数据(提供默认值,避免 undefined)
// ============================================================
const deviceInfo = inject<Ref<any[]>>("minuteData", ref([]));
// ============================================================
// 引用与动画
// ============================================================
const canvasRef = ref<HTMLCanvasElement | null>(null);
const legendCanvas = ref<HTMLCanvasElement | null>(null);
let animationId: number | null = null;
// ============================================================
// 缩放与平移状态
// ============================================================
const zoomLevel = ref(1);
const panX = ref(0);
const panY = ref(0);
// ============================================================
// 拖拽状态
// ============================================================
const isDragging = ref(false);
let dragStartX = 0;
let dragStartY = 0;
let dragStartPanX = 0;
let dragStartPanY = 0;
// ============================================================
// Tooltip 状态
// ============================================================
interface TooltipInfo {
x: number;
y: number;
visible: boolean;
distance: number | null;
angle: number | null;
speed: number | null;
}
const tooltip = ref<TooltipInfo>({
x: 0,
y: 0,
visible: false,
distance: null,
angle: null,
speed: null,
});
// ============================================================
// 颜色方案(绝对速度色标,单位 m/s)
// ============================================================
interface ColorStop {
speed: number;
rgb: [number, number, number];
}
const VELOCITY_COLOR_STOPS: ColorStop[] = [
{ speed: -50, rgb: [59, 15, 111] }, // 深紫
{ speed: -40, rgb: [0, 0, 255] }, // 蓝 极强朝向
{ speed: -30, rgb: [0, 128, 255] }, // 天蓝 强朝向
{ speed: -20, rgb: [0, 224, 255] }, // 青 较强朝向
{ speed: -10, rgb: [0, 255, 128] }, // 青绿 中等朝向
{ speed: 0, rgb: [160, 160, 160] }, // 灰 零速
{ speed: 10, rgb: [255, 240, 0] }, // 黄 中等远离
{ speed: 20, rgb: [255, 160, 0] }, // 橙 较强远离
{ speed: 30, rgb: [255, 60, 0] }, // 橙红 强远离
{ speed: 40, rgb: [220, 0, 0] }, // 红 极强远离
{ speed: 50, rgb: [139, 0, 0] }, // 紫红 极端远离
];
const COLOR_SPEED_MIN = VELOCITY_COLOR_STOPS[0].speed;
const COLOR_SPEED_MAX =
VELOCITY_COLOR_STOPS[VELOCITY_COLOR_STOPS.length - 1].speed;
const velocityColorCache = new Map<number, string>();
function getVelocityColor(speed: number): string {
if (isNaN(speed)) return "rgba(110, 122, 145, 0.35)";
const key = Math.round(speed * 10);
const cached = velocityColorCache.get(key);
if (cached) return cached;
const stops = VELOCITY_COLOR_STOPS;
let color: string;
if (speed <= stops[0].speed) {
const c = stops[0].rgb;
color = `rgb(${c[0]},${c[1]},${c[2]})`;
} else if (speed >= stops[stops.length - 1].speed) {
const c = stops[stops.length - 1].rgb;
color = `rgb(${c[0]},${c[1]},${c[2]})`;
} else {
color = "rgb(160,160,160)";
for (let i = 0; i < stops.length - 1; i++) {
const a = stops[i];
const b = stops[i + 1];
if (speed >= a.speed && speed <= b.speed) {
const t = (speed - a.speed) / (b.speed - a.speed);
const r = Math.round(a.rgb[0] + t * (b.rgb[0] - a.rgb[0]));
const g = Math.round(a.rgb[1] + t * (b.rgb[1] - a.rgb[1]));
const bl = Math.round(a.rgb[2] + t * (b.rgb[2] - a.rgb[2]));
color = `rgb(${r},${g},${bl})`;
break;
}
}
}
velocityColorCache.set(key, color);
return color;
}
// ============================================================
// 工具函数
// ============================================================
const formatTime = (rtc: string) => {
try {
const dt = new Date(rtc);
if (!isNaN(dt.getTime()))
return dt.toLocaleString("zh-CN", { hour12: false });
} catch {}
return rtc || "";
};
// ============================================================
// 数据结构定义
// ============================================================
interface GroupData {
distances: number[];
speeds: number[];
}
interface ParsedData {
groups: Map<number, GroupData>;
time: string;
maxDistance: number;
startDist: number;
gateDist: number;
gateTotal: number;
mode: string;
elevationMin: number | null;
elevationMax: number | null;
azimuthMin: number | null;
azimuthMax: number | null;
azimuthCurrent: number | null;
step: number | null;
speedMin: number;
speedMax: number;
}
// ============================================================
// 解析缓存(基于 RTC)
// ============================================================
const parsedCache = new Map<string, ParsedData>();
// ============================================================
// 单帧数据提取(带缓存)
// ============================================================
function extractFrameData(frame: any): ParsedData {
const rtc = frame?.Scan?.RTC;
if (rtc && parsedCache.has(rtc)) {
return parsedCache.get(rtc)!;
}
const scans = frame?.Scans || [];
const emptyResult = (): ParsedData => ({
groups: new Map(),
time: "",
maxDistance: 1000,
startDist: 0,
gateDist: 100,
gateTotal: 0,
mode: "PPI",
elevationMin: null,
elevationMax: null,
azimuthMin: null,
azimuthMax: null,
azimuthCurrent: null,
step: null,
speedMin: -30,
speedMax: 30,
});
if (scans.length === 0) return emptyResult();
const firstScan = scans[0];
const mode = firstScan?.Mode ?? "PPI";
let startDist = firstScan?.StartDistance ?? 0;
let gateDist = firstScan?.GateDistance ?? 100;
// 优先取顶层 frame.Scan.RTC,若无则回退到第一个扫描的 RTC
const frameRTC = frame?.Scan?.RTC;
const time = frameRTC
? formatTime(frameRTC)
: firstScan?.RTC
? formatTime(firstScan.RTC)
: "";
const groups = new Map<number, GroupData>();
let globalMin = Infinity;
let globalMax = -Infinity;
let maxLen = 0;
let elevationMin: number | null = null;
let elevationMax: number | null = null;
let azimuthMin: number | null = null;
let azimuthMax: number | null = null;
scans.forEach((scan: any) => {
const az = scan.AzimuthCurrent;
if (typeof az !== "number" || isNaN(az)) return;
const speeds = scan.SpeedRadial || [];
const scanStartDist = scan.StartDistance ?? startDist;
const scanGateDist = scan.GateDistance ?? gateDist;
maxLen = Math.max(maxLen, speeds.length);
const angle = Math.round(az);
const normalized = ((angle % 360) + 360) % 360;
const distances: number[] = [];
const allSpeeds: number[] = [];
for (let j = 0; j < speeds.length; j++) {
const speed = speeds[j];
const distance = scanStartDist + j * scanGateDist;
distances.push(distance);
const numSpeed = typeof speed === "number" && !isNaN(speed) ? speed : NaN;
allSpeeds.push(numSpeed);
if (!isNaN(numSpeed) && numSpeed !== 999) {
if (numSpeed < globalMin) globalMin = numSpeed;
if (numSpeed > globalMax) globalMax = numSpeed;
}
}
groups.set(normalized, { distances, speeds: allSpeeds });
const el = scan?.ElevationCurrent;
if (typeof el === "number" && !isNaN(el)) {
if (elevationMin === null || el < elevationMin) elevationMin = el;
if (elevationMax === null || el > elevationMax) elevationMax = el;
}
const azCur = scan?.AzimuthCurrent;
if (typeof azCur === "number" && !isNaN(azCur)) {
if (azimuthMin === null || azCur < azimuthMin) azimuthMin = azCur;
if (azimuthMax === null || azCur > azimuthMax) azimuthMax = azCur;
}
});
if (!isFinite(globalMin)) globalMin = -30;
if (!isFinite(globalMax)) globalMax = 30;
if (globalMax - globalMin < 1) {
globalMin -= 10;
globalMax += 10;
}
let maxDistance = startDist + (maxLen - 1) * gateDist;
groups.forEach((entry) => {
if (entry.distances.length > 0) {
const maxD = entry.distances[entry.distances.length - 1];
if (maxD > maxDistance) maxDistance = maxD;
}
});
maxDistance = Math.max(maxDistance, 1000);
const latestScan = scans[scans.length - 1];
const azimuthCurrent = latestScan?.AzimuthCurrent ?? null;
let step: number | null = null;
if (scans.length >= 2) {
const az1 = scans[0]?.AzimuthCurrent;
const az2 = scans[1]?.AzimuthCurrent;
if (
typeof az1 === "number" &&
!isNaN(az1) &&
typeof az2 === "number" &&
!isNaN(az2)
) {
let diff = Math.abs(az2 - az1);
if (diff > 180) diff = 360 - diff;
if (diff > 0) step = diff;
}
}
const result: ParsedData = {
groups,
time,
maxDistance,
startDist,
gateDist,
gateTotal: maxLen,
mode,
elevationMin,
elevationMax,
azimuthMin,
azimuthMax,
azimuthCurrent,
step,
speedMin: globalMin,
speedMax: globalMax,
};
if (rtc) {
parsedCache.set(rtc, result);
}
return result;
}
// ============================================================
// 帧历史管理(保留最新 11 帧)
// ============================================================
const frames = ref<any[]>([]);
const currentFrameIndex = ref(-1);
const MAX_FRAMES = 11;
// 当前帧解析数据(使用缓存)
const currentData = computed<ParsedData | null>(() => {
if (
currentFrameIndex.value < 0 ||
currentFrameIndex.value >= frames.value.length
)
return null;
return extractFrameData(frames.value[currentFrameIndex.value]);
});
// ============================================================
// 时间轴辅助
// ============================================================
function getTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (rtc) {
const dt = new Date(rtc);
return dt.toLocaleTimeString("zh-CN", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
});
}
return "--";
}
/** 顶部时间标签:时:分:秒 */
function getFullTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (rtc) {
const dt = new Date(rtc);
return dt.toLocaleTimeString("zh-CN", { hour12: false });
}
return "--";
}
const currentTimeLabel = computed(() => {
if (
currentFrameIndex.value < 0 ||
currentFrameIndex.value >= frames.value.length
)
return "--";
return getFullTimeLabel(frames.value[currentFrameIndex.value]);
});
// 为每一帧生成标记(显示所有帧的时间)
const timeMarks = computed(() => {
const marks: Record<number, string> = {};
frames.value.forEach((frame, idx) => {
marks[idx] = getTimeLabel(frame);
});
return marks;
});
function onSliderChange(val: number) {
scheduleRender();
}
/** 左右按钮逐帧切换 */
function stepFrame(delta: number) {
const fs = frames.value;
if (fs.length === 0) return;
const next = Math.min(
Math.max(currentFrameIndex.value + delta, 0),
fs.length - 1,
);
if (next === currentFrameIndex.value) return;
currentFrameIndex.value = next;
scheduleRender();
}
// ============================================================
// 监听 deviceInfo 更新(保留选中状态 + 智能跳过)
// ============================================================
watch(
() => deviceInfo.value,
(newVal) => {
console.log(newVal);
// 防御:如果 deviceInfo 未定义或新值不是数组,重置
if (!deviceInfo || !Array.isArray(newVal) || newVal.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
// 过滤出有效的帧(含有 Scans 且非空)
const validFrames = newVal.filter((frame) => frame?.Scans?.length > 0);
if (validFrames.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
// 帧内去重:同一帧里方位角完全相同的射线只保留第一条
const dedupedFrames = validFrames.map((frame) => {
const scans = frame?.Scans;
if (!Array.isArray(scans) || scans.length < 2) return frame;
const seenAzimuths = new Set<number>();
const uniqueScans: any[] = [];
for (const scan of scans) {
const az = scan?.AzimuthCurrent;
if (typeof az !== "number" || isNaN(az)) {
// 无角度的射线交给解析层处理,这里不参与去重
uniqueScans.push(scan);
continue;
}
if (seenAzimuths.has(az)) continue;
seenAzimuths.add(az);
uniqueScans.push(scan);
}
// 按方位角升序排列
uniqueScans.sort((a, b) => {
const av = a?.AzimuthCurrent;
const bv = b?.AzimuthCurrent;
const aValid = typeof av === "number" && !isNaN(av);
const bValid = typeof bv === "number" && !isNaN(bv);
if (aValid && bValid) return av - bv;
if (aValid) return -1;
if (bValid) return 1;
return 0;
});
// 没有重复且顺序未变时复用原对象,避免无意义的拷贝
const changed =
uniqueScans.length !== scans.length ||
uniqueScans.some((scan, i) => scan !== scans[i]);
return changed ? { ...frame, Scans: uniqueScans } : frame;
});
// 去重:基于 frame.Scan.RTC
const seen = new Set<string>();
const uniqueFrames: any[] = [];
for (const frame of dedupedFrames) {
const rtc = frame?.Scan?.RTC;
if (rtc && !seen.has(rtc)) {
seen.add(rtc);
uniqueFrames.push(frame);
}
}
// 按时间排序
uniqueFrames.sort((a, b) => {
const t1 = a?.Scan?.RTC || "";
const t2 = b?.Scan?.RTC || "";
return t1.localeCompare(t2);
});
// 只保留最新的 MAX_FRAMES 个(取尾部)
if (uniqueFrames.length > MAX_FRAMES) {
uniqueFrames.splice(0, uniqueFrames.length - MAX_FRAMES);
}
// ---- 智能跳过:如果 RTC 列表完全相同,不做任何更新 ----
const newRTCs = uniqueFrames
.map((f) => f?.Scan?.RTC)
.filter(Boolean) as string[];
const oldRTCs = frames.value
.map((f) => f?.Scan?.RTC)
.filter(Boolean) as string[];
if (
newRTCs.length === oldRTCs.length &&
newRTCs.every((rtc, i) => rtc === oldRTCs[i])
) {
// 数据无变化,跳过更新
return;
}
// ---- 保存当前选中帧的状态 ----
let currentRTC: string | null = null;
let wasLatest = false;
if (
currentFrameIndex.value >= 0 &&
currentFrameIndex.value < frames.value.length
) {
const currentFrame = frames.value[currentFrameIndex.value];
if (currentFrame?.Scan?.RTC) {
currentRTC = currentFrame.Scan.RTC;
// 判断是否是最新帧(索引等于旧数组最后一个)
if (currentFrameIndex.value === frames.value.length - 1) {
wasLatest = true;
}
}
}
// 更新 frames
frames.value = uniqueFrames;
// ---- 设置新的索引 ----
if (frames.value.length === 0) {
currentFrameIndex.value = -1;
} else if (wasLatest) {
// 之前选中最新 → 跳到新最新
currentFrameIndex.value = frames.value.length - 1;
} else if (currentRTC) {
// 非最新,尝试查找原帧
const foundIndex = frames.value.findIndex(
(f) => f?.Scan?.RTC === currentRTC,
);
if (foundIndex !== -1) {
currentFrameIndex.value = foundIndex;
} else {
// 原帧已被移除 → 跳到新的最旧帧(第一个)
currentFrameIndex.value = 0;
}
} else {
// 没有之前的选中 → 选最新
currentFrameIndex.value = frames.value.length - 1;
}
scheduleRender();
},
{ deep: true, immediate: true },
);
// ============================================================
// 核心绘制函数
// ============================================================
function drawRadar(canvas: HTMLCanvasElement, data: ParsedData) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const { groups, maxDistance, startDist, gateDist, step } = data;
const dpr = window.devicePixelRatio || 1;
const rect = canvas.parentElement?.getBoundingClientRect();
const containerWidth = rect?.width || 600;
const containerHeight = rect?.height || 600;
canvas.width = containerWidth * dpr;
canvas.height = containerHeight * dpr;
canvas.style.width = "100%";
canvas.style.height = "100%";
ctx.scale(dpr, dpr);
const cx = containerWidth / 2;
const cy = containerHeight / 2;
const radius = Math.min(containerWidth, containerHeight) / 2 - 40;
ctx.clearRect(0, 0, containerWidth, containerHeight);
ctx.fillStyle = "#0a0e1a";
ctx.fillRect(0, 0, containerWidth, containerHeight);
ctx.save();
ctx.translate(cx + panX.value, cy + panY.value);
ctx.scale(zoomLevel.value, zoomLevel.value);
ctx.translate(-cx, -cy);
// 同心圆网格
const gridStep = Math.max(1000, Math.ceil(maxDistance / 10 / 1000) * 1000);
const gridCount = Math.floor(maxDistance / gridStep);
for (let i = 1; i <= gridCount; i++) {
const dist = i * gridStep;
const r = (dist / maxDistance) * radius;
if (r <= radius) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.strokeStyle =
i === gridCount ? "rgba(255,255,255,0.4)" : "rgba(255,255,255,0.28)";
ctx.lineWidth = i === gridCount ? 1.0 : 0.5;
ctx.stroke();
}
}
// 径向线
for (let i = 0; i < 8; i++) {
const angle = i * 45;
const rad = ((angle - 90) * Math.PI) / 180;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.lineTo(cx + radius * Math.cos(rad), cy + radius * Math.sin(rad));
ctx.strokeStyle =
i === 0 ? "rgba(255,255,255,0.4)" : "rgba(255,255,255,0.28)";
ctx.lineWidth = i === 0 ? 1.0 : 0.5;
ctx.stroke();
}
// 绘制彩色扇形
if (groups.size > 0 && maxDistance > 0) {
ctx.globalAlpha = 0.9;
const halfAngleDeg = step && step > 0 ? step / 2 : 0.5;
const halfAngleRad = (halfAngleDeg * Math.PI) / 180;
const toScreenX = (lx: number, ly: number) =>
(lx - cx) * zoomLevel.value + (cx + panX.value);
const toScreenY = (lx: number, ly: number) =>
(ly - cy) * zoomLevel.value + (cy + panY.value);
const margin = 20;
groups.forEach((entry, angle) => {
const { distances, speeds } = entry;
if (distances.length === 0) return;
for (let i = 0; i < distances.length; i++) {
const dist = distances[i];
const speed = speeds[i];
if (dist === undefined || speed === undefined || isNaN(speed)) continue;
const r1 = (dist / maxDistance) * radius;
const nextDist =
i + 1 < distances.length ? distances[i + 1] : dist + gateDist;
const r2 = Math.min((nextDist / maxDistance) * radius, radius);
const midDist = (r1 + r2) / 2;
const midAngleRad = ((angle - 90) * Math.PI) / 180;
const logicX = cx + midDist * Math.cos(midAngleRad);
const logicY = cy + midDist * Math.sin(midAngleRad);
const screenX = toScreenX(logicX, logicY);
const screenY = toScreenY(logicX, logicY);
if (
screenX < -margin ||
screenX > containerWidth + margin ||
screenY < -margin ||
screenY > containerHeight + margin
) {
continue;
}
const rad = ((angle - 90) * Math.PI) / 180;
const startRad = rad - halfAngleRad;
const endRad = rad + halfAngleRad;
if (speed === 999 || isNaN(speed)) {
ctx.fillStyle = "rgba(110, 122, 145, 0.35)";
} else {
ctx.fillStyle = getVelocityColor(speed);
}
ctx.beginPath();
ctx.arc(cx, cy, r2, startRad, endRad);
ctx.arc(cx, cy, r1, endRad, startRad, true);
ctx.closePath();
ctx.fill();
}
});
ctx.globalAlpha = 1.0;
}
// 角度标注
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "11px sans-serif";
ctx.fillStyle = "rgba(255,255,255,0.7)";
for (let i = 0; i < 8; i++) {
const angle = i * 45;
const rad = ((angle - 90) * Math.PI) / 180;
const labelR = radius + 18;
ctx.fillText(
angle + "°",
cx + labelR * Math.cos(rad),
cy + labelR * Math.sin(rad),
);
}
// 距离标注
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.font = "10px sans-serif";
ctx.fillStyle = "rgba(255,255,255,0.5)";
const labelStep = Math.max(1000, Math.ceil(maxDistance / 10 / 1000) * 1000);
const labelCount = Math.floor(maxDistance / labelStep);
for (let i = 1; i <= labelCount; i++) {
const dist = i * labelStep;
const r = (dist / maxDistance) * radius;
if (r <= radius) {
ctx.fillText(dist + "m", cx + 22, cy - r + 3);
}
}
// 中心点
ctx.beginPath();
ctx.arc(cx, cy, 1, 0, Math.PI * 2);
ctx.fillStyle = "rgba(255,255,255,0.6)";
ctx.fill();
ctx.restore();
drawLegend(legendCanvas.value);
}
// ============================================================
// 图例绘制(固定 -50 ~ +50 绝对速度色标)
// ============================================================
function drawLegend(canvas: HTMLCanvasElement | null) {
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const rect = canvas.parentElement?.getBoundingClientRect();
const width = Math.round(rect?.width || 200);
const height = 20;
if (
canvas.width !== Math.round(width * dpr) ||
canvas.height !== Math.round(height * dpr)
) {
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
canvas.style.width = width + "px";
canvas.style.height = height + "px";
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const grad = ctx.createLinearGradient(0, 0, width, 0);
const span = COLOR_SPEED_MAX - COLOR_SPEED_MIN || 1;
VELOCITY_COLOR_STOPS.forEach((s) => {
let pos = (s.speed - COLOR_SPEED_MIN) / span;
pos = pos < 0 ? 0 : pos > 1 ? 1 : pos;
grad.addColorStop(pos, `rgb(${s.rgb[0]},${s.rgb[1]},${s.rgb[2]})`);
});
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = "rgba(255,255,255,0.3)";
ctx.lineWidth = 1;
ctx.strokeRect(0.5, 0.5, width - 1, height - 1);
}
// ============================================================
// 缩放控制
// ============================================================
const ZOOM_STEP = 1;
const ZOOM_MIN = 0.5;
const ZOOM_MAX = 15;
function handleZoomIn() {
const newZoom = Math.min(zoomLevel.value + ZOOM_STEP, ZOOM_MAX);
if (newZoom !== zoomLevel.value) {
zoomLevel.value = newZoom;
scheduleRender();
}
}
function handleZoomOut() {
const newZoom = Math.max(zoomLevel.value - ZOOM_STEP, ZOOM_MIN);
if (newZoom !== zoomLevel.value) {
zoomLevel.value = newZoom;
scheduleRender();
}
}
function resetZoom() {
zoomLevel.value = 1;
panX.value = 0;
panY.value = 0;
scheduleRender();
}
// ============================================================
// 鼠标交互(拖拽 + Tooltip)
// ============================================================
function handleMouseDown(e: MouseEvent) {
if (e.button !== 0) return;
const canvas = canvasRef.value;
if (!canvas) return;
isDragging.value = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
dragStartPanX = panX.value;
dragStartPanY = panY.value;
canvas.style.cursor = "grabbing";
tooltip.value.visible = false;
}
function handleMouseMove(e: MouseEvent) {
const canvas = canvasRef.value;
if (!canvas) return;
if (isDragging.value) {
panX.value = dragStartPanX + (e.clientX - dragStartX);
panY.value = dragStartPanY + (e.clientY - dragStartY);
scheduleRender();
return;
}
// Tooltip 悬停逻辑
const rect = canvas.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const containerWidth = rect.width;
const containerHeight = rect.height;
const cx = containerWidth / 2;
const cy = containerHeight / 2;
const radarRadius = Math.min(containerWidth, containerHeight) / 2 - 40;
const logicX = (mouseX - (cx + panX.value)) / zoomLevel.value + cx;
const logicY = (mouseY - (cy + panY.value)) / zoomLevel.value + cy;
const dx = logicX - cx;
const dy = logicY - cy;
const distFromCenter = Math.sqrt(dx * dx + dy * dy);
const data = currentData.value;
if (
!data ||
data.groups.size === 0 ||
data.maxDistance <= 0 ||
distFromCenter > radarRadius ||
distFromCenter < 5
) {
tooltip.value.visible = false;
return;
}
const { groups, maxDistance, step, gateDist } = data;
let angleRad = Math.atan2(dy, dx);
let angleDeg = ((angleRad * 180) / Math.PI + 90) % 360;
if (angleDeg < 0) angleDeg += 360;
const distance = (distFromCenter / radarRadius) * maxDistance;
let closestAngle: number | null = null;
let closestAngleDiff = Infinity;
const angles = Array.from(groups.keys());
for (const a of angles) {
let diff = Math.abs(a - angleDeg);
diff = Math.min(diff, 360 - diff);
if (diff < closestAngleDiff) {
closestAngleDiff = diff;
closestAngle = a;
}
}
const angleThreshold = Math.max(step ? step / 2 : 1, 1.0);
if (closestAngle === null || closestAngleDiff > angleThreshold) {
tooltip.value.visible = false;
return;
}
const entry = groups.get(closestAngle);
if (!entry || entry.distances.length === 0) {
tooltip.value.visible = false;
return;
}
let matchedIdx = -1;
for (let i = 0; i < entry.distances.length; i++) {
const start = entry.distances[i];
let end: number;
if (i + 1 < entry.distances.length) {
end = entry.distances[i + 1];
} else {
end = start + gateDist;
}
if (distance >= start && distance < end) {
matchedIdx = i;
break;
}
}
if (matchedIdx === -1) {
tooltip.value.visible = false;
return;
}
const matchedDistance = entry.distances[matchedIdx];
const matchedSpeed = entry.speeds[matchedIdx];
if (
matchedSpeed === undefined ||
isNaN(matchedSpeed) ||
matchedSpeed === 999
) {
tooltip.value.visible = false;
return;
}
const wrapperRect = canvas.parentElement?.getBoundingClientRect();
if (!wrapperRect) return;
const wrapperX = e.clientX - wrapperRect.left;
const wrapperY = e.clientY - wrapperRect.top;
const offsetX = 12;
const offsetY = 12;
tooltip.value = {
x: wrapperX + offsetX,
y: wrapperY + offsetY,
visible: true,
distance: Math.round(matchedDistance),
angle: closestAngle,
speed: matchedSpeed,
};
}
function handleMouseUp(e: MouseEvent) {
if (isDragging.value) {
isDragging.value = false;
if (canvasRef.value) canvasRef.value.style.cursor = "default";
}
}
function handleMouseLeave() {
if (isDragging.value) {
isDragging.value = false;
if (canvasRef.value) canvasRef.value.style.cursor = "default";
}
tooltip.value.visible = false;
}
function handleWheel(e: WheelEvent) {
e.preventDefault();
const delta = e.deltaY > 0 ? 0.9 : 1.1;
let newZoom = zoomLevel.value * delta;
if (newZoom < ZOOM_MIN) newZoom = ZOOM_MIN;
if (newZoom > ZOOM_MAX) newZoom = ZOOM_MAX;
if (newZoom !== zoomLevel.value) {
zoomLevel.value = newZoom;
scheduleRender();
}
}
// ============================================================
// 渲染调度
// ============================================================
let resizeObserver: ResizeObserver | null = null;
function render() {
const canvas = canvasRef.value;
if (!canvas) return;
const data = currentData.value;
if (!data) {
const ctx = canvas.getContext("2d");
if (ctx) {
const rect = canvas.parentElement?.getBoundingClientRect();
const w = rect?.width || 600,
h = rect?.height || 600;
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "#0a0e1a";
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = "rgba(255,255,255,0.3)";
ctx.font = "16px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("无数据", w / 2, h / 2);
}
drawLegend(legendCanvas.value);
return;
}
drawRadar(canvas, data);
}
function scheduleRender() {
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
animationId = requestAnimationFrame(() => {
render();
animationId = null;
});
}
// ============================================================
// 生命周期
// ============================================================
onMounted(() => {
nextTick(() => {
render();
const canvas = canvasRef.value;
if (canvas && canvas.parentElement) {
resizeObserver = new ResizeObserver(() => {
resetZoom();
scheduleRender();
});
resizeObserver.observe(canvas.parentElement);
}
const canvasEl = canvasRef.value;
if (canvasEl) {
canvasEl.addEventListener("mousedown", handleMouseDown);
canvasEl.addEventListener("mousemove", handleMouseMove);
canvasEl.addEventListener("mouseup", handleMouseUp);
canvasEl.addEventListener("mouseleave", handleMouseLeave);
canvasEl.addEventListener("wheel", handleWheel, { passive: false });
}
});
});
onBeforeUnmount(() => {
if (resizeObserver) {
resizeObserver.disconnect();
resizeObserver = null;
}
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
const canvasEl = canvasRef.value;
if (canvasEl) {
canvasEl.removeEventListener("mousedown", handleMouseDown);
canvasEl.removeEventListener("mousemove", handleMouseMove);
canvasEl.removeEventListener("mouseup", handleMouseUp);
canvasEl.removeEventListener("mouseleave", handleMouseLeave);
canvasEl.removeEventListener("wheel", handleWheel);
}
});
// ============================================================
// 计算属性(信息面板、图例)
// ============================================================
const formatRange = (min: number | null, max: number | null): string => {
if (min === null || max === null) return "--";
return min === max ? min + "°" : min + "°~" + max + "°";
};
const scanParams = computed(() => {
const data = currentData.value;
if (!data)
return {
mode: "PPI",
elevationMin: null,
elevationMax: null,
azimuthMin: null,
azimuthMax: null,
azimuthCurrent: null,
step: null,
};
const {
mode,
elevationMin,
elevationMax,
azimuthMin,
azimuthMax,
azimuthCurrent,
step,
} = data;
return {
mode,
elevationMin,
elevationMax,
azimuthMin,
azimuthMax,
azimuthCurrent,
step,
};
});
const legendMinSpeed = computed(() => COLOR_SPEED_MIN.toFixed(0));
const legendMaxSpeed = computed(() => "+" + COLOR_SPEED_MAX.toFixed(0));
</script>
<style scoped lang="less">
.radar-ppi-container {
position: relative;
width: 100%;
height: 100%;
border-right: 1px solid #243049;
padding: 0 10px;
display: flex;
flex-direction: column;
background: #0a0e1a;
.radar-canvas-wrapper {
flex: 1;
min-height: 0;
position: relative;
.radar-canvas {
display: block;
width: 100%;
height: 100%;
cursor: default;
user-select: none;
}
.realtime-radar-panel {
position: absolute;
top: 16px;
right: 16px;
width: 300px;
height: 260px;
// z-index: 5;
// overflow: hidden;
// border: 1px solid rgba(255, 255, 255, 0.12);
// border-radius: 4px;
// background: #0a0e1a;
}
.radar-info-panel {
position: absolute;
top: 16px;
left: 8px;
font-size: 14px;
color: rgba(255, 255, 255, 0.85);
line-height: 1.6;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
}
.radar-legend {
position: absolute;
right: 16px;
bottom: 16px;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
.legend-canvas {
display: block;
width: 200px;
height: 20px;
border-radius: 2px;
margin-bottom: 2px;
}
.legend-labels {
display: flex;
justify-content: space-between;
font-size: 11px;
color: rgba(255, 255, 255, 0.7);
}
}
.radar-tooltip {
position: absolute;
background: rgba(0, 0, 0, 0.85);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
padding: 8px 12px;
font-size: 12px;
color: #fff;
line-height: 1.6;
pointer-events: none;
white-space: nowrap;
z-index: 10;
}
.zoom-controls {
position: absolute;
bottom: 16px;
left: 16px;
display: flex;
align-items: center;
gap: 6px;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
padding: 4px 6px;
user-select: none;
.zoom-btn {
width: 28px;
height: 28px;
background: transparent;
border: none;
color: #fff;
font-size: 18px;
font-weight: bold;
cursor: pointer;
border-radius: 2px;
transition: background 0.15s;
display: flex;
align-items: center;
justify-content: center;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.1);
}
&:disabled {
color: rgba(255, 255, 255, 0.25);
cursor: not-allowed;
}
}
.zoom-level {
min-width: 44px;
text-align: center;
font-size: 13px;
color: rgba(255, 255, 255, 0.85);
font-variant-numeric: tabular-nums;
}
.zoom-divider {
width: 1px;
height: 16px;
background: rgba(255, 255, 255, 0.2);
}
.zoom-btn.reset-btn {
font-size: 15px;
}
}
// ===== 时间轴样式 =====
.timeline-container {
position: absolute;
bottom: 8px;
left: 50%;
transform: translateX(-50%);
width: 70%;
max-width: 700px;
// background: rgba(10, 14, 26, 0.6);
backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
padding: 4px 12px 20px 12px;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 4px;
.timeline-header {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
font-size: 11px;
color: rgba(255, 255, 255, 0.8);
.timeline-label-left {
justify-self: start;
}
.timeline-label-right {
justify-self: end;
}
.timeline-current-group {
display: flex;
align-items: center;
gap: 8px;
.timeline-current {
min-width: 64px;
text-align: center;
color: var(--el-color-primary);
font-weight: bold;
font-size: 13px;
}
}
}
.time-nav-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 50%;
background: rgba(255, 255, 255, 0.06);
color: rgba(255, 255, 255, 0.8);
font-size: 14px;
cursor: pointer;
transition:
background-color 0.15s,
border-color 0.15s,
color 0.15s;
&:hover:not(:disabled) {
background: rgba(64, 158, 255, 0.3);
border-color: var(--el-color-primary);
color: #fff;
}
&:disabled {
opacity: 0.3;
cursor: not-allowed;
}
}
.timeline-slider {
width: 100%;
margin: 0;
:deep(.el-slider__marks-text) {
color: rgba(255, 255, 255, 0.7);
font-size: 9px;
// margin-top: 4px;
white-space: nowrap;
}
}
}
}
}
:deep(.el-slider__button) {
height: 15px;
width: 15px;
&:hover {
height: 15px;
width: 15px;
}
}
</style>
ScanChart1.vue 完整源码(动态色标版本)
vue
<template>
<div class="radar-ppi-container">
<div class="radar-canvas-wrapper">
<canvas ref="canvasRef" class="radar-canvas"></canvas>
<!-- 信息面板(左上角) -->
<div class="radar-info-panel">
<div>模式:{{ scanParams.mode }}</div>
<div>俯仰角:{{ formatRange(scanParams.elevationMin, scanParams.elevationMax) }}</div>
<div>方位角:{{ formatRange(scanParams.azimuthMin, scanParams.azimuthMax) }}</div>
<div>步长:{{ scanParams.step !== null ? scanParams.step + '°' : '--' }}</div>
<div v-if="currentData">时间:{{ currentData.time }}</div>
</div>
<!-- 图例(右下角) -->
<div class="radar-legend">
<canvas ref="legendCanvas" class="legend-canvas"></canvas>
<div class="legend-labels">
<span>{{ legendMinSpeed }} m/s</span>
<span>{{ legendMaxSpeed }} m/s</span>
</div>
</div>
<!-- 缩放控件(右上角) -->
<div class="zoom-controls">
<button
class="zoom-btn"
@click="handleZoomOut"
:disabled="zoomLevel <= ZOOM_MIN"
title="缩小"
>−</button>
<span class="zoom-level">{{ zoomLevel.toFixed(1) }}</span>
<button
class="zoom-btn"
@click="handleZoomIn"
:disabled="zoomLevel >= ZOOM_MAX"
title="放大"
>+</button>
<span class="zoom-divider"></span>
<button
class="zoom-btn reset-btn"
@click="resetZoom"
:disabled="panX === 0 && panY === 0 && zoomLevel === 1"
title="回到原点"
>
<el-icon><Aim /></el-icon>
</button>
</div>
<!-- ===== 时间轴(使用 el-slider) ===== -->
<div class="timeline-container" v-if="frames.length > 0">
<div class="timeline-header">
<span class="timeline-label-left">{{ getTimeLabel(frames[0]) }}</span>
<span class="timeline-current">{{ currentTimeLabel }}</span>
<span class="timeline-label-right">{{ getTimeLabel(frames[frames.length - 1]) }}</span>
</div>
<el-slider
v-model="currentFrameIndex"
:min="0"
:max="frames.length - 1"
:marks="timeMarks"
@change="onSliderChange"
size="small"
:show-tooltip="false"
class="timeline-slider"
/>
<div class="timeline-index">{{ currentFrameIndex + 1 }} / {{ frames.length }}</div>
</div>
<!-- Tooltip -->
<div
v-if="tooltip.visible"
class="radar-tooltip"
:style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"
>
<div>距离:{{ tooltip.distance !== null ? tooltip.distance + 'm' : '--' }}</div>
<div>角度:{{ tooltip.angle !== null ? tooltip.angle + '°' : '--' }}</div>
<div>速度:{{ tooltip.speed !== null ? tooltip.speed.toFixed(1) + ' m/s' : '--' }}</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount, inject, nextTick, type Ref } from 'vue'
import { Aim } from '@element-plus/icons-vue'
// ============================================================
// 注入数据(提供默认值,避免 undefined)
// ============================================================
const deviceInfo = inject<Ref<any[]>>('minuteData', ref([]))
// ============================================================
// 引用与动画
// ============================================================
const canvasRef = ref<HTMLCanvasElement | null>(null)
const legendCanvas = ref<HTMLCanvasElement | null>(null)
let animationId: number | null = null
// ============================================================
// 缩放与平移状态
// ============================================================
const zoomLevel = ref(1)
const panX = ref(0)
const panY = ref(0)
// ============================================================
// 拖拽状态
// ============================================================
const isDragging = ref(false)
let dragStartX = 0
let dragStartY = 0
let dragStartPanX = 0
let dragStartPanY = 0
// ============================================================
// Tooltip 状态
// ============================================================
interface TooltipInfo {
x: number
y: number
visible: boolean
distance: number | null
angle: number | null
speed: number | null
}
const tooltip = ref<TooltipInfo>({ x: 0, y: 0, visible: false, distance: null, angle: null, speed: null })
// ============================================================
// 颜色方案
// ============================================================
const colorStops = [
{ pos: 0.0, color: [0, 0, 255] },
{ pos: 0.25, color: [0, 255, 255] },
{ pos: 0.5, color: [0, 255, 0] },
{ pos: 0.75, color: [255, 255, 0] },
{ pos: 1.0, color: [255, 0, 0] },
]
const colorCache = new Map<string, string>()
function getSpeedColor(normalized: number): string {
if (normalized < 0) normalized = 0
if (normalized > 1) normalized = 1
const key = normalized.toFixed(4)
if (colorCache.has(key)) return colorCache.get(key)!
for (let i = 0; i < colorStops.length - 1; i++) {
const left = colorStops[i]
const right = colorStops[i + 1]
if (normalized >= left.pos && normalized <= right.pos) {
const t = (normalized - left.pos) / (right.pos - left.pos)
const r = Math.round(left.color[0] + t * (right.color[0] - left.color[0]))
const g = Math.round(left.color[1] + t * (right.color[1] - left.color[1]))
const b = Math.round(left.color[2] + t * (right.color[2] - left.color[2]))
const color = `rgb(${r},${g},${b})`
colorCache.set(key, color)
return color
}
}
return 'rgb(255,0,0)'
}
// ============================================================
// 工具函数
// ============================================================
const formatTime = (rtc: string) => {
try {
const dt = new Date(rtc)
if (!isNaN(dt.getTime())) return dt.toLocaleString('zh-CN', { hour12: false })
} catch {}
return rtc || ''
}
// ============================================================
// 数据结构定义
// ============================================================
interface GroupData {
distances: number[]
speeds: number[]
}
interface ParsedData {
groups: Map<number, GroupData>
time: string
maxDistance: number
startDist: number
gateDist: number
gateTotal: number
mode: string
elevationMin: number | null
elevationMax: number | null
azimuthMin: number | null
azimuthMax: number | null
azimuthCurrent: number | null
step: number | null
speedMin: number
speedMax: number
}
// ============================================================
// 单帧数据提取
// ============================================================
function extractFrameData(frame: any): ParsedData {
const scans = frame?.Scans || []
const emptyResult = (): ParsedData => ({
groups: new Map(),
time: '',
maxDistance: 1000,
startDist: 0,
gateDist: 100,
gateTotal: 0,
mode: 'PPI',
elevationMin: null,
elevationMax: null,
azimuthMin: null,
azimuthMax: null,
azimuthCurrent: null,
step: null,
speedMin: -30,
speedMax: 30,
})
if (scans.length === 0) return emptyResult()
const firstScan = scans[0]
const mode = firstScan?.Mode ?? 'PPI'
let startDist = firstScan?.StartDistance ?? 0
let gateDist = firstScan?.GateDistance ?? 100
// 优先取顶层 frame.Scan.RTC,若无则回退到第一个扫描的 RTC
const frameRTC = frame?.Scan?.RTC
const time = frameRTC ? formatTime(frameRTC) : (firstScan?.RTC ? formatTime(firstScan.RTC) : '')
const groups = new Map<number, GroupData>()
let globalMin = Infinity
let globalMax = -Infinity
let maxLen = 0
let elevationMin: number | null = null
let elevationMax: number | null = null
let azimuthMin: number | null = null
let azimuthMax: number | null = null
scans.forEach((scan: any) => {
const az = scan.AzimuthCurrent
if (typeof az !== 'number' || isNaN(az)) return
const speeds = scan.SpeedRadial || []
const scanStartDist = scan.StartDistance ?? startDist
const scanGateDist = scan.GateDistance ?? gateDist
maxLen = Math.max(maxLen, speeds.length)
const angle = Math.round(az)
const normalized = ((angle % 360) + 360) % 360
const distances: number[] = []
const allSpeeds: number[] = []
for (let j = 0; j < speeds.length; j++) {
const speed = speeds[j]
const distance = scanStartDist + j * scanGateDist
distances.push(distance)
const numSpeed = typeof speed === 'number' && !isNaN(speed) ? speed : NaN
allSpeeds.push(numSpeed)
if (!isNaN(numSpeed) && numSpeed !== 999) {
if (numSpeed < globalMin) globalMin = numSpeed
if (numSpeed > globalMax) globalMax = numSpeed
}
}
groups.set(normalized, { distances, speeds: allSpeeds })
const el = scan?.ElevationCurrent
if (typeof el === 'number' && !isNaN(el)) {
if (elevationMin === null || el < elevationMin) elevationMin = el
if (elevationMax === null || el > elevationMax) elevationMax = el
}
const azCur = scan?.AzimuthCurrent
if (typeof azCur === 'number' && !isNaN(azCur)) {
if (azimuthMin === null || azCur < azimuthMin) azimuthMin = azCur
if (azimuthMax === null || azCur > azimuthMax) azimuthMax = azCur
}
})
if (!isFinite(globalMin)) globalMin = -30
if (!isFinite(globalMax)) globalMax = 30
if (globalMax - globalMin < 1) {
globalMin -= 10
globalMax += 10
}
let maxDistance = startDist + (maxLen - 1) * gateDist
groups.forEach((entry) => {
if (entry.distances.length > 0) {
const maxD = entry.distances[entry.distances.length - 1]
if (maxD > maxDistance) maxDistance = maxD
}
})
maxDistance = Math.max(maxDistance, 1000)
const latestScan = scans[scans.length - 1]
const azimuthCurrent = latestScan?.AzimuthCurrent ?? null
let step: number | null = null
if (scans.length >= 2) {
const az1 = scans[0]?.AzimuthCurrent
const az2 = scans[1]?.AzimuthCurrent
if (typeof az1 === 'number' && !isNaN(az1) && typeof az2 === 'number' && !isNaN(az2)) {
let diff = Math.abs(az2 - az1)
if (diff > 180) diff = 360 - diff
if (diff > 0) step = diff
}
}
return {
groups,
time,
maxDistance,
startDist,
gateDist,
gateTotal: maxLen,
mode,
elevationMin,
elevationMax,
azimuthMin,
azimuthMax,
azimuthCurrent,
step,
speedMin: globalMin,
speedMax: globalMax,
}
}
// ============================================================
// 帧历史管理(保留最新 11 帧)
// ============================================================
const frames = ref<any[]>([])
const currentFrameIndex = ref(-1)
const MAX_FRAMES = 11
// 当前帧解析数据
const currentData = computed<ParsedData | null>(() => {
if (currentFrameIndex.value < 0 || currentFrameIndex.value >= frames.value.length) return null
return extractFrameData(frames.value[currentFrameIndex.value])
})
// ============================================================
// 时间轴辅助
// ============================================================
function getTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC
if (rtc) {
const dt = new Date(rtc)
return dt.toLocaleTimeString('zh-CN', { hour12: false })
}
return '--'
}
const currentTimeLabel = computed(() => {
if (currentFrameIndex.value < 0 || currentFrameIndex.value >= frames.value.length) return '--'
return getTimeLabel(frames.value[currentFrameIndex.value])
})
// 为每一帧生成标记(显示所有帧的时间)
const timeMarks = computed(() => {
const marks: Record<number, string> = {}
frames.value.forEach((frame, idx) => {
marks[idx] = getTimeLabel(frame)
})
return marks
})
function onSliderChange(val: number) {
scheduleRender()
}
// ============================================================
// 监听 deviceInfo 更新(保留选中状态)
// ============================================================
watch(
() => deviceInfo.value,
(newVal) => {
// 防御:如果 deviceInfo 未定义或新值不是数组,重置
if (!deviceInfo || !Array.isArray(newVal) || newVal.length === 0) {
frames.value = []
currentFrameIndex.value = -1
scheduleRender()
return
}
// 过滤出有效的帧(含有 Scans 且非空)
const validFrames = newVal.filter(frame => frame?.Scans?.length > 0)
if (validFrames.length === 0) {
frames.value = []
currentFrameIndex.value = -1
scheduleRender()
return
}
// 去重:基于 frame.Scan.RTC
const seen = new Set<string>()
const uniqueFrames: any[] = []
for (const frame of validFrames) {
const rtc = frame?.Scan?.RTC
if (rtc && !seen.has(rtc)) {
seen.add(rtc)
uniqueFrames.push(frame)
}
}
// 按时间排序
uniqueFrames.sort((a, b) => {
const t1 = a?.Scan?.RTC || ''
const t2 = b?.Scan?.RTC || ''
return t1.localeCompare(t2)
})
// 只保留最新的 MAX_FRAMES 个(取尾部)
if (uniqueFrames.length > MAX_FRAMES) {
uniqueFrames.splice(0, uniqueFrames.length - MAX_FRAMES)
}
// ---- 保存当前选中帧的状态 ----
let currentRTC: string | null = null
let wasLatest = false
if (currentFrameIndex.value >= 0 && currentFrameIndex.value < frames.value.length) {
const currentFrame = frames.value[currentFrameIndex.value]
if (currentFrame?.Scan?.RTC) {
currentRTC = currentFrame.Scan.RTC
// 判断是否是最新帧(索引等于旧数组最后一个)
if (currentFrameIndex.value === frames.value.length - 1) {
wasLatest = true
}
}
}
// 更新 frames
frames.value = uniqueFrames
// ---- 设置新的索引 ----
if (frames.value.length === 0) {
currentFrameIndex.value = -1
} else if (wasLatest) {
// 之前选中最新 → 跳到新最新
currentFrameIndex.value = frames.value.length - 1
} else if (currentRTC) {
// 非最新,尝试查找原帧
const foundIndex = frames.value.findIndex(f => f?.Scan?.RTC === currentRTC)
if (foundIndex !== -1) {
currentFrameIndex.value = foundIndex
} else {
// 原帧已被移除 → 跳到新的最旧帧(第一个)
currentFrameIndex.value = 0
}
} else {
// 没有之前的选中 → 选最新
currentFrameIndex.value = frames.value.length - 1
}
scheduleRender()
},
{ deep: true, immediate: true }
)
// ============================================================
// 核心绘制函数
// ============================================================
function drawRadar(canvas: HTMLCanvasElement, data: ParsedData) {
const ctx = canvas.getContext('2d')
if (!ctx) return
const { groups, maxDistance, startDist, gateDist, speedMin, speedMax, step } = data
const dpr = window.devicePixelRatio || 1
const rect = canvas.parentElement?.getBoundingClientRect()
const containerWidth = rect?.width || 600
const containerHeight = rect?.height || 600
canvas.width = containerWidth * dpr
canvas.height = containerHeight * dpr
canvas.style.width = '100%'
canvas.style.height = '100%'
ctx.scale(dpr, dpr)
const cx = containerWidth / 2
const cy = containerHeight / 2
const radius = Math.min(containerWidth, containerHeight) / 2 - 40
ctx.clearRect(0, 0, containerWidth, containerHeight)
ctx.fillStyle = '#0a0e1a'
ctx.fillRect(0, 0, containerWidth, containerHeight)
ctx.save()
ctx.translate(cx + panX.value, cy + panY.value)
ctx.scale(zoomLevel.value, zoomLevel.value)
ctx.translate(-cx, -cy)
// 同心圆网格
const gridStep = Math.max(1000, Math.ceil(maxDistance / 10 / 1000) * 1000)
const gridCount = Math.floor(maxDistance / gridStep)
for (let i = 1; i <= gridCount; i++) {
const dist = i * gridStep
const r = (dist / maxDistance) * radius
if (r <= radius) {
ctx.beginPath()
ctx.arc(cx, cy, r, 0, Math.PI * 2)
ctx.strokeStyle = i === gridCount ? 'rgba(255,255,255,0.4)' : 'rgba(255,255,255,0.28)'
ctx.lineWidth = i === gridCount ? 1.0 : 0.5
ctx.stroke()
}
}
// 径向线
for (let i = 0; i < 8; i++) {
const angle = i * 45
const rad = (angle - 90) * Math.PI / 180
ctx.beginPath()
ctx.moveTo(cx, cy)
ctx.lineTo(cx + radius * Math.cos(rad), cy + radius * Math.sin(rad))
ctx.strokeStyle = i === 0 ? 'rgba(255,255,255,0.4)' : 'rgba(255,255,255,0.28)'
ctx.lineWidth = i === 0 ? 1.0 : 0.5
ctx.stroke()
}
// 绘制彩色扇形
if (groups.size > 0 && maxDistance > 0) {
ctx.globalAlpha = 0.9
const halfAngleDeg = (step && step > 0) ? step / 2 : 0.5
const halfAngleRad = halfAngleDeg * Math.PI / 180
const toScreenX = (lx: number, ly: number) => (lx - cx) * zoomLevel.value + (cx + panX.value)
const toScreenY = (lx: number, ly: number) => (ly - cy) * zoomLevel.value + (cy + panY.value)
const margin = 20
groups.forEach((entry, angle) => {
const { distances, speeds } = entry
if (distances.length === 0) return
for (let i = 0; i < distances.length; i++) {
const dist = distances[i]
const speed = speeds[i]
if (dist === undefined || speed === undefined || isNaN(speed)) continue
const r1 = (dist / maxDistance) * radius
const nextDist = i + 1 < distances.length ? distances[i + 1] : dist + gateDist
const r2 = Math.min((nextDist / maxDistance) * radius, radius)
const midDist = (r1 + r2) / 2
const midAngleRad = (angle - 90) * Math.PI / 180
const logicX = cx + midDist * Math.cos(midAngleRad)
const logicY = cy + midDist * Math.sin(midAngleRad)
const screenX = toScreenX(logicX, logicY)
const screenY = toScreenY(logicX, logicY)
if (screenX < -margin || screenX > containerWidth + margin ||
screenY < -margin || screenY > containerHeight + margin) {
continue
}
const rad = (angle - 90) * Math.PI / 180
const startRad = rad - halfAngleRad
const endRad = rad + halfAngleRad
if (speed === 999 || isNaN(speed)) {
ctx.fillStyle = 'rgba(120, 130, 150, 0.1)'
} else {
const norm = (speed - speedMin) / (speedMax - speedMin)
ctx.fillStyle = getSpeedColor(norm)
}
ctx.beginPath()
ctx.arc(cx, cy, r2, startRad, endRad)
ctx.arc(cx, cy, r1, endRad, startRad, true)
ctx.closePath()
ctx.fill()
}
})
ctx.globalAlpha = 1.0
}
// 角度标注
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.font = '11px sans-serif'
ctx.fillStyle = 'rgba(255,255,255,0.7)'
for (let i = 0; i < 8; i++) {
const angle = i * 45
const rad = (angle - 90) * Math.PI / 180
const labelR = radius + 18
ctx.fillText(angle + '°', cx + labelR * Math.cos(rad), cy + labelR * Math.sin(rad))
}
// 距离标注
ctx.textAlign = 'center'
ctx.textBaseline = 'bottom'
ctx.font = '10px sans-serif'
ctx.fillStyle = 'rgba(255,255,255,0.5)'
const labelStep = Math.max(1000, Math.ceil(maxDistance / 10 / 1000) * 1000)
const labelCount = Math.floor(maxDistance / labelStep)
for (let i = 1; i <= labelCount; i++) {
const dist = i * labelStep
const r = (dist / maxDistance) * radius
if (r <= radius) {
ctx.fillText(dist + 'm', cx + 22, cy - r + 3)
}
}
// 中心点
ctx.beginPath()
ctx.arc(cx, cy, 1, 0, Math.PI * 2)
ctx.fillStyle = 'rgba(255,255,255,0.6)'
ctx.fill()
ctx.restore()
drawLegend(legendCanvas.value, speedMin, speedMax)
}
// ============================================================
// 图例绘制
// ============================================================
function drawLegend(canvas: HTMLCanvasElement | null, minSpeed: number, maxSpeed: number) {
if (!canvas) return
const ctx = canvas.getContext('2d')
if (!ctx) return
const dpr = window.devicePixelRatio || 1
const rect = canvas.parentElement?.getBoundingClientRect()
const width = rect?.width || 200
const height = 20
canvas.width = width * dpr
canvas.height = height * dpr
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
ctx.scale(dpr, dpr)
const grad = ctx.createLinearGradient(0, 0, width, 0)
colorStops.forEach(stop => {
grad.addColorStop(stop.pos, `rgb(${stop.color[0]},${stop.color[1]},${stop.color[2]})`)
})
ctx.fillStyle = grad
ctx.fillRect(0, 0, width, height)
ctx.strokeStyle = 'rgba(255,255,255,0.3)'
ctx.lineWidth = 1
ctx.strokeRect(0, 0, width, height)
}
// ============================================================
// 缩放控制
// ============================================================
const ZOOM_STEP = 1
const ZOOM_MIN = 0.5
const ZOOM_MAX = 15
function handleZoomIn() {
const newZoom = Math.min(zoomLevel.value + ZOOM_STEP, ZOOM_MAX)
if (newZoom !== zoomLevel.value) { zoomLevel.value = newZoom; scheduleRender() }
}
function handleZoomOut() {
const newZoom = Math.max(zoomLevel.value - ZOOM_STEP, ZOOM_MIN)
if (newZoom !== zoomLevel.value) { zoomLevel.value = newZoom; scheduleRender() }
}
function resetZoom() {
zoomLevel.value = 1; panX.value = 0; panY.value = 0; scheduleRender()
}
// ============================================================
// 鼠标交互(拖拽 + Tooltip)
// ============================================================
function handleMouseDown(e: MouseEvent) {
if (e.button !== 0) return
const canvas = canvasRef.value
if (!canvas) return
isDragging.value = true
dragStartX = e.clientX; dragStartY = e.clientY
dragStartPanX = panX.value; dragStartPanY = panY.value
canvas.style.cursor = 'grabbing'
tooltip.value.visible = false
}
function handleMouseMove(e: MouseEvent) {
const canvas = canvasRef.value
if (!canvas) return
if (isDragging.value) {
panX.value = dragStartPanX + (e.clientX - dragStartX)
panY.value = dragStartPanY + (e.clientY - dragStartY)
scheduleRender()
return
}
// Tooltip 悬停逻辑
const rect = canvas.getBoundingClientRect()
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
const containerWidth = rect.width
const containerHeight = rect.height
const cx = containerWidth / 2
const cy = containerHeight / 2
const radarRadius = Math.min(containerWidth, containerHeight) / 2 - 40
const logicX = (mouseX - (cx + panX.value)) / zoomLevel.value + cx
const logicY = (mouseY - (cy + panY.value)) / zoomLevel.value + cy
const dx = logicX - cx
const dy = logicY - cy
const distFromCenter = Math.sqrt(dx * dx + dy * dy)
const data = currentData.value
if (!data || data.groups.size === 0 || data.maxDistance <= 0 || distFromCenter > radarRadius || distFromCenter < 5) {
tooltip.value.visible = false
return
}
const { groups, maxDistance, step, gateDist } = data
let angleRad = Math.atan2(dy, dx)
let angleDeg = (angleRad * 180 / Math.PI + 90) % 360
if (angleDeg < 0) angleDeg += 360
const distance = (distFromCenter / radarRadius) * maxDistance
let closestAngle: number | null = null
let closestAngleDiff = Infinity
const angles = Array.from(groups.keys())
for (const a of angles) {
let diff = Math.abs(a - angleDeg)
diff = Math.min(diff, 360 - diff)
if (diff < closestAngleDiff) {
closestAngleDiff = diff
closestAngle = a
}
}
const angleThreshold = Math.max(step ? step / 2 : 1, 1.0)
if (closestAngle === null || closestAngleDiff > angleThreshold) {
tooltip.value.visible = false
return
}
const entry = groups.get(closestAngle)
if (!entry || entry.distances.length === 0) {
tooltip.value.visible = false
return
}
let matchedIdx = -1
for (let i = 0; i < entry.distances.length; i++) {
const start = entry.distances[i]
let end: number
if (i + 1 < entry.distances.length) {
end = entry.distances[i + 1]
} else {
end = start + gateDist
}
if (distance >= start && distance < end) {
matchedIdx = i
break
}
}
if (matchedIdx === -1) {
tooltip.value.visible = false
return
}
const matchedDistance = entry.distances[matchedIdx]
const matchedSpeed = entry.speeds[matchedIdx]
if (matchedSpeed === undefined || isNaN(matchedSpeed) || matchedSpeed === 999) {
tooltip.value.visible = false
return
}
const wrapperRect = canvas.parentElement?.getBoundingClientRect()
if (!wrapperRect) return
const wrapperX = e.clientX - wrapperRect.left
const wrapperY = e.clientY - wrapperRect.top
const offsetX = 12
const offsetY = 12
tooltip.value = {
x: wrapperX + offsetX,
y: wrapperY + offsetY,
visible: true,
distance: Math.round(matchedDistance),
angle: closestAngle,
speed: matchedSpeed,
}
}
function handleMouseUp(e: MouseEvent) {
if (isDragging.value) {
isDragging.value = false
if (canvasRef.value) canvasRef.value.style.cursor = 'default'
}
}
function handleMouseLeave() {
if (isDragging.value) {
isDragging.value = false
if (canvasRef.value) canvasRef.value.style.cursor = 'default'
}
tooltip.value.visible = false
}
function handleWheel(e: WheelEvent) {
e.preventDefault()
const delta = e.deltaY > 0 ? 0.9 : 1.1
let newZoom = zoomLevel.value * delta
if (newZoom < ZOOM_MIN) newZoom = ZOOM_MIN
if (newZoom > ZOOM_MAX) newZoom = ZOOM_MAX
if (newZoom !== zoomLevel.value) { zoomLevel.value = newZoom; scheduleRender() }
}
// ============================================================
// 渲染调度
// ============================================================
let resizeObserver: ResizeObserver | null = null
function render() {
const canvas = canvasRef.value
if (!canvas) return
const data = currentData.value
if (!data) {
const ctx = canvas.getContext('2d')
if (ctx) {
const rect = canvas.parentElement?.getBoundingClientRect()
const w = rect?.width || 600, h = rect?.height || 600
ctx.clearRect(0, 0, w, h)
ctx.fillStyle = '#0a0e1a'
ctx.fillRect(0, 0, w, h)
ctx.fillStyle = 'rgba(255,255,255,0.3)'
ctx.font = '16px sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText('无数据', w/2, h/2)
}
return
}
drawRadar(canvas, data)
}
function scheduleRender() {
if (animationId) { cancelAnimationFrame(animationId); animationId = null }
animationId = requestAnimationFrame(() => { render(); animationId = null })
}
// ============================================================
// 生命周期
// ============================================================
onMounted(() => {
nextTick(() => {
render()
const canvas = canvasRef.value
if (canvas && canvas.parentElement) {
resizeObserver = new ResizeObserver(() => { resetZoom(); scheduleRender() })
resizeObserver.observe(canvas.parentElement)
}
const canvasEl = canvasRef.value
if (canvasEl) {
canvasEl.addEventListener('mousedown', handleMouseDown)
canvasEl.addEventListener('mousemove', handleMouseMove)
canvasEl.addEventListener('mouseup', handleMouseUp)
canvasEl.addEventListener('mouseleave', handleMouseLeave)
canvasEl.addEventListener('wheel', handleWheel, { passive: false })
}
})
})
onBeforeUnmount(() => {
if (resizeObserver) { resizeObserver.disconnect(); resizeObserver = null }
if (animationId) { cancelAnimationFrame(animationId); animationId = null }
const canvasEl = canvasRef.value
if (canvasEl) {
canvasEl.removeEventListener('mousedown', handleMouseDown)
canvasEl.removeEventListener('mousemove', handleMouseMove)
canvasEl.removeEventListener('mouseup', handleMouseUp)
canvasEl.removeEventListener('mouseleave', handleMouseLeave)
canvasEl.removeEventListener('wheel', handleWheel)
}
})
// ============================================================
// 计算属性(信息面板、图例)
// ============================================================
const formatRange = (min: number | null, max: number | null): string => {
if (min === null || max === null) return '--'
return min === max ? min + '°' : min + '°~' + max + '°'
}
const scanParams = computed(() => {
const data = currentData.value
if (!data) return { mode: 'PPI', elevationMin: null, elevationMax: null, azimuthMin: null, azimuthMax: null, azimuthCurrent: null, step: null }
const { mode, elevationMin, elevationMax, azimuthMin, azimuthMax, azimuthCurrent, step } = data
return { mode, elevationMin, elevationMax, azimuthMin, azimuthMax, azimuthCurrent, step }
})
const legendMinSpeed = computed(() => currentData.value ? currentData.value.speedMin.toFixed(1) : '-30.0')
const legendMaxSpeed = computed(() => currentData.value ? currentData.value.speedMax.toFixed(1) : '30.0')
</script>
<style scoped lang="less">
.radar-ppi-container {
position: relative;
width: 100%;
height: 100%;
border-right: 1px solid #243049;
padding: 0 10px;
display: flex;
flex-direction: column;
background: #0a0e1a;
.radar-canvas-wrapper {
flex: 1;
min-height: 0;
position: relative;
.radar-canvas {
display: block;
width: 100%;
height: 100%;
cursor: default;
user-select: none;
}
.radar-info-panel {
position: absolute;
top: 8px;
left: 8px;
font-size: 14px;
color: rgba(255,255,255,0.85);
line-height: 1.6;
pointer-events: none;
text-shadow: 0 0 4px rgba(0,0,0,0.8);
}
.radar-legend {
position: absolute;
right: 16px;
bottom: 16px;
pointer-events: none;
text-shadow: 0 0 4px rgba(0,0,0,0.8);
.legend-canvas { display: block; width: 200px; height: 20px; border-radius: 2px; margin-bottom: 2px; }
.legend-labels { display: flex; justify-content: space-between; font-size: 11px; color: rgba(255,255,255,0.7); }
}
.radar-tooltip {
position: absolute;
background: rgba(0,0,0,0.85);
border: 1px solid rgba(255,255,255,0.3);
border-radius: 4px;
padding: 8px 12px;
font-size: 12px;
color: #fff;
line-height: 1.6;
pointer-events: none;
white-space: nowrap;
z-index: 10;
}
.zoom-controls {
position: absolute;
top: 24px;
right: 16px;
display: flex;
align-items: center;
gap: 6px;
background: rgba(10,14,26,0.8);
backdrop-filter: blur(4px);
border: 1px solid rgba(255,255,255,0.15);
border-radius: 4px;
padding: 4px 6px;
user-select: none;
.zoom-btn {
width: 28px; height: 28px;
background: transparent; border: none; color: #fff; font-size: 18px; font-weight: bold;
cursor: pointer; border-radius: 2px; transition: background 0.15s;
display: flex; align-items: center; justify-content: center;
&:hover:not(:disabled) { background: rgba(255,255,255,0.1); }
&:disabled { color: rgba(255,255,255,0.25); cursor: not-allowed; }
}
.zoom-level { min-width: 44px; text-align: center; font-size: 13px; color: rgba(255,255,255,0.85); font-variant-numeric: tabular-nums; }
.zoom-divider { width: 1px; height: 16px; background: rgba(255,255,255,0.2); }
.zoom-btn.reset-btn { font-size: 15px; }
}
// ===== 时间轴样式 =====
.timeline-container {
position: absolute;
bottom: 40px;
left: 50%;
transform: translateX(-50%);
width: 70%;
max-width: 700px;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
border: 1px solid rgba(255,255,255,0.15);
border-radius: 8px;
padding: 10px 20px 14px 20px;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 4px;
.timeline-header {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 11px;
color: rgba(255,255,255,0.6);
.timeline-current {
color: var(--el-color-primary);
font-weight: bold;
font-size: 13px;
}
}
.timeline-slider {
width: 100%;
margin: 0;
:deep(.el-slider__marks-text) {
color: rgba(255,255,255,0.5);
font-size: 9px;
margin-top: 4px;
white-space: nowrap;
}
}
.timeline-index {
text-align: center;
font-size: 11px;
color: rgba(255,255,255,0.4);
margin-top: 2px;
}
}
}
}
</style>
四、RHI:垂直剖面
RHI 和 PPI 的差别集中在三处:几何、角度字段、扇区方向。
4.1 圆心在底部,只画上半圆
ts
function getRadarGeometry(width: number, height: number) {
const cx = width / 2;
const cy = height - 90; // 圆心贴近底部
const radius = Math.min((width - 80) / 2, height - 60);
return { cx, cy, radius };
}
网格只画 -π ~ 0 的上半圆:
ts
ctx.arc(cx, cy, r, -Math.PI, 0);
4.2 角度字段要跟着模式走
RHI 变化的是俯仰角,所以解析时要动态选字段:
ts
const mode = firstScan?.Mode ?? 'PPI';
const isRHI = mode === 'RHI';
const angleField = isRHI ? 'ElevationCurrent' : 'AzimuthCurrent';
俯仰角 0° 在右、90° 在上、180° 在左,对应画布弧度就是取负:
ts
function azimuthToCanvasRad(azimuth: number): number {
return (-azimuth * Math.PI) / 180;
}
4.3 扇区覆盖 angle, angle + step
PPI 是以当前角为中心向两侧各展开半个步长;RHI 则是从当前角往后覆盖一个步长,所以弧线起止要对调:
ts
const startRad = azimuthToCanvasRad(angle + step);
const endRad = azimuthToCanvasRad(angle);
ctx.beginPath();
ctx.arc(cx, cy, r2, startRad, endRad);
ctx.arc(cx, cy, r1, endRad, startRad, true);
ctx.closePath();
ctx.fill();
步长优先取数据里的 ElevationStep,没有就取 AzimuthStep,再退化为相邻俯仰角差值,最后兜底 1°:
ts
function getEffectiveStep(sortedAngles: number[], stepFromData: number | null) {
if (stepFromData && stepFromData > 0) return stepFromData;
if (sortedAngles.length < 2) return 1;
let minDiff = Infinity;
for (let i = 1; i < sortedAngles.length; i++) {
const d = sortedAngles[i] - sortedAngles[i - 1];
if (d > 0 && d < minDiff) minDiff = d;
}
return isFinite(minDiff) && minDiff > 0 ? minDiff : 1;
}
4.4 Tooltip 只在上半圆生效
RHI 的鼠标拾取比 PPI 多一个判断:dy > 0 直接不命中,因为下半圆没有数据。
ts
if (dy > 0) { tooltip.visible = false; return; }
然后按 [angle, angle + step) 区间反查扇区,再按距离门找索引。
RHIChart.vue 完整源码
vue
<template>
<div class="radar-ppi-container">
<div class="radar-canvas-wrapper">
<canvas ref="canvasRef" class="radar-canvas"></canvas>
<!-- 实时扫描雷达(左上角) -->
<div class="realtime-rhi-panel">
<RealTimeRHIChart />
</div>
<!-- 信息面板(左上角) -->
<div class="radar-info-panel">
<div>模式:{{ scanParams.mode }}</div>
<div>
俯仰角:{{
formatRange(scanParams.elevationMin, scanParams.elevationMax)
}}
</div>
<div>
方位角:{{
formatRange(scanParams.azimuthMin, scanParams.azimuthMax)
}}
</div>
<div>
步长:{{ scanParams.step !== null ? scanParams.step + "°" : "--" }}
</div>
<div v-if="currentData">时间:{{ currentData.time }}</div>
</div>
<!-- 图例(右下角) -->
<div class="radar-legend">
<canvas ref="legendCanvas" class="legend-canvas"></canvas>
<div class="legend-labels">
<span>{{ legendMinSpeed }} m/s</span>
<span>{{ legendMaxSpeed }} m/s</span>
</div>
</div>
<!-- 缩放控件(右上角) -->
<div class="zoom-controls">
<button
class="zoom-btn"
@click="handleZoomOut"
:disabled="zoomLevel <= ZOOM_MIN"
title="缩小"
>
−
</button>
<span class="zoom-level">{{ zoomLevel.toFixed(1) }}</span>
<button
class="zoom-btn"
@click="handleZoomIn"
:disabled="zoomLevel >= ZOOM_MAX"
title="放大"
>
+
</button>
<span class="zoom-divider"></span>
<button
class="zoom-btn reset-btn"
@click="resetZoom"
:disabled="panX === 0 && panY === 0 && zoomLevel === 1"
title="回到原点"
>
<el-icon><Aim /></el-icon>
</button>
</div>
<!-- ===== 时间轴(使用 el-slider) ===== -->
<div class="timeline-container" v-if="frames.length > 0">
<div class="timeline-header">
<span class="timeline-label-left">{{
getFullTimeLabel(frames[0])
}}</span>
<div class="timeline-current-group">
<button
class="time-nav-btn"
:disabled="currentFrameIndex <= 0"
title="上一帧"
@click="stepFrame(-1)"
>
<el-icon><ArrowLeft /></el-icon>
</button>
<span class="timeline-current">{{ currentTimeLabel }}</span>
<button
class="time-nav-btn"
:disabled="currentFrameIndex >= frames.length - 1"
title="下一帧"
@click="stepFrame(1)"
>
<el-icon><ArrowRight /></el-icon>
</button>
</div>
<span class="timeline-label-right">{{
getFullTimeLabel(frames[frames.length - 1])
}}</span>
</div>
<el-slider
v-model="currentFrameIndex"
:min="0"
:max="frames.length - 1"
:marks="timeMarks"
@change="onSliderChange"
size="small"
:show-tooltip="false"
class="timeline-slider"
/>
</div>
<!-- Tooltip -->
<div
v-if="tooltip.visible"
class="radar-tooltip"
:style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"
>
<div>
距离:{{ tooltip.distance !== null ? tooltip.distance + "m" : "--" }}
</div>
<div>
角度:{{ tooltip.angle !== null ? tooltip.angle + "°" : "--" }}
</div>
<div>
速度:{{
tooltip.speed !== null ? tooltip.speed.toFixed(1) + " m/s" : "--"
}}
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import {
ref,
computed,
watch,
onMounted,
onBeforeUnmount,
inject,
nextTick,
type Ref,
} from "vue";
import { Aim, ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import RealTimeRHIChart from "./RealTimeRHIChart.vue";
// ============================================================
// 注入数据(提供默认值,避免 undefined)
// ============================================================
const deviceInfo = inject<Ref<any[]>>("minuteData", ref([]));
// ============================================================
// 引用与动画
// ============================================================
const canvasRef = ref<HTMLCanvasElement | null>(null);
const legendCanvas = ref<HTMLCanvasElement | null>(null);
let animationId: number | null = null;
// ============================================================
// 缩放与平移状态
// ============================================================
const zoomLevel = ref(1);
const panX = ref(0);
const panY = ref(0);
// ============================================================
// 拖拽状态
// ============================================================
const isDragging = ref(false);
let dragStartX = 0;
let dragStartY = 0;
let dragStartPanX = 0;
let dragStartPanY = 0;
// ============================================================
// Tooltip 状态
// ============================================================
interface TooltipInfo {
x: number;
y: number;
visible: boolean;
distance: number | null;
angle: number | null;
speed: number | null;
}
const tooltip = ref<TooltipInfo>({
x: 0,
y: 0,
visible: false,
distance: null,
angle: null,
speed: null,
});
// ============================================================
// 颜色方案(绝对速度色标,单位 m/s)
// ============================================================
interface ColorStop {
speed: number;
rgb: [number, number, number];
}
const VELOCITY_COLOR_STOPS: ColorStop[] = [
{ speed: -50, rgb: [59, 15, 111] }, // 深紫
{ speed: -40, rgb: [0, 0, 255] }, // 蓝 极强朝向
{ speed: -30, rgb: [0, 128, 255] }, // 天蓝 强朝向
{ speed: -20, rgb: [0, 224, 255] }, // 青 较强朝向
{ speed: -10, rgb: [0, 255, 128] }, // 青绿 中等朝向
{ speed: 0, rgb: [160, 160, 160] }, // 灰 零速
{ speed: 10, rgb: [255, 240, 0] }, // 黄 中等远离
{ speed: 20, rgb: [255, 160, 0] }, // 橙 较强远离
{ speed: 30, rgb: [255, 60, 0] }, // 橙红 强远离
{ speed: 40, rgb: [220, 0, 0] }, // 红 极强远离
{ speed: 50, rgb: [139, 0, 0] }, // 紫红 极端远离
];
const COLOR_SPEED_MIN = VELOCITY_COLOR_STOPS[0].speed;
const COLOR_SPEED_MAX =
VELOCITY_COLOR_STOPS[VELOCITY_COLOR_STOPS.length - 1].speed;
const velocityColorCache = new Map<number, string>();
function getVelocityColor(speed: number): string {
if (isNaN(speed)) return "rgba(110, 122, 145, 0.35)";
const key = Math.round(speed * 10);
const cached = velocityColorCache.get(key);
if (cached) return cached;
const stops = VELOCITY_COLOR_STOPS;
let color: string;
if (speed <= stops[0].speed) {
const c = stops[0].rgb;
color = `rgb(${c[0]},${c[1]},${c[2]})`;
} else if (speed >= stops[stops.length - 1].speed) {
const c = stops[stops.length - 1].rgb;
color = `rgb(${c[0]},${c[1]},${c[2]})`;
} else {
color = "rgb(160,160,160)";
for (let i = 0; i < stops.length - 1; i++) {
const a = stops[i];
const b = stops[i + 1];
if (speed >= a.speed && speed <= b.speed) {
const t = (speed - a.speed) / (b.speed - a.speed);
const r = Math.round(a.rgb[0] + t * (b.rgb[0] - a.rgb[0]));
const g = Math.round(a.rgb[1] + t * (b.rgb[1] - a.rgb[1]));
const bl = Math.round(a.rgb[2] + t * (b.rgb[2] - a.rgb[2]));
color = `rgb(${r},${g},${bl})`;
break;
}
}
}
velocityColorCache.set(key, color);
return color;
}
// ============================================================
// 工具函数
// ============================================================
const formatTime = (rtc: string) => {
try {
const dt = new Date(rtc);
if (!isNaN(dt.getTime()))
return dt.toLocaleString("zh-CN", { hour12: false });
} catch {}
return rtc || "";
};
// 方位角/仰角 → canvas 弧度:从右到左 0°~180°,即 0° 在右,90° 在上,180° 在左
function azimuthToCanvasRad(azimuth: number): number {
return (-azimuth * Math.PI) / 180;
}
// ★ 统一的雷达几何参数,draw 与 tooltip 共用
function getRadarGeometry(width: number, height: number) {
const cx = width / 2;
const cy = height - 90;
const radius = Math.min((width - 80) / 2, height - 60);
return { cx, cy, radius };
}
// ★ 计算扇区宽度用的有效步长
// 优先用解析出的 step(相邻扫描角度差);
// 否则取相邻角度最小差;再兜底 1°。
function getEffectiveStep(
sortedAngles: number[],
stepFromData: number | null,
): number {
if (stepFromData && stepFromData > 0) return stepFromData;
if (sortedAngles.length < 2) return 1;
let minDiff = Infinity;
for (let i = 1; i < sortedAngles.length; i++) {
const d = sortedAngles[i] - sortedAngles[i - 1];
if (d > 0 && d < minDiff) minDiff = d;
}
return isFinite(minDiff) && minDiff > 0 ? minDiff : 1;
}
// ============================================================
// 数据结构定义
// ============================================================
interface GroupData {
distances: number[];
speeds: number[];
}
interface ParsedData {
groups: Map<number, GroupData>;
time: string;
maxDistance: number;
startDist: number;
gateDist: number;
gateTotal: number;
mode: string;
elevationMin: number | null;
elevationMax: number | null;
azimuthMin: number | null;
azimuthMax: number | null;
azimuthCurrent: number | null;
step: number | null;
speedMin: number;
speedMax: number;
}
// ============================================================
// 解析缓存(基于 RTC)
// ============================================================
const parsedCache = new Map<string, ParsedData>();
// ============================================================
// 单帧数据提取(带缓存)
// ============================================================
function extractFrameData(frame: any): ParsedData {
const rtc = frame?.Scan?.RTC;
if (rtc && parsedCache.has(rtc)) {
return parsedCache.get(rtc)!;
}
const scans = frame?.Scans || [];
const emptyResult = (): ParsedData => ({
groups: new Map(),
time: "",
maxDistance: 1000,
startDist: 0,
gateDist: 100,
gateTotal: 0,
mode: "PPI",
elevationMin: null,
elevationMax: null,
azimuthMin: null,
azimuthMax: null,
azimuthCurrent: null,
step: null,
speedMin: -30,
speedMax: 30,
});
if (scans.length === 0) return emptyResult();
const firstScan = scans[0];
const mode = firstScan?.Mode ?? "PPI";
const isRHI = mode === "RHI";
const angleField = isRHI ? "ElevationCurrent" : "AzimuthCurrent";
let startDist = firstScan?.StartDistance ?? 0;
let gateDist = firstScan?.GateDistance ?? 100;
const frameRTC = frame?.Scan?.RTC;
const time = frameRTC
? formatTime(frameRTC)
: firstScan?.RTC
? formatTime(firstScan.RTC)
: "";
const groups = new Map<number, GroupData>();
let globalMin = Infinity;
let globalMax = -Infinity;
let maxLen = 0;
let elevationMin: number | null = null;
let elevationMax: number | null = null;
let azimuthMin: number | null = null;
let azimuthMax: number | null = null;
scans.forEach((scan: any) => {
const angleRaw = scan[angleField];
if (typeof angleRaw !== "number" || isNaN(angleRaw)) return;
const speeds = scan.SpeedRadial || [];
const scanStartDist = scan.StartDistance ?? startDist;
const scanGateDist = scan.GateDistance ?? gateDist;
maxLen = Math.max(maxLen, speeds.length);
const angle = Math.round(angleRaw);
const normalized = ((angle % 360) + 360) % 360;
const distances: number[] = [];
const allSpeeds: number[] = [];
for (let j = 0; j < speeds.length; j++) {
const speed = speeds[j];
const distance = scanStartDist + j * scanGateDist;
distances.push(distance);
const numSpeed = typeof speed === "number" && !isNaN(speed) ? speed : NaN;
allSpeeds.push(numSpeed);
if (!isNaN(numSpeed) && numSpeed !== 999) {
if (numSpeed < globalMin) globalMin = numSpeed;
if (numSpeed > globalMax) globalMax = numSpeed;
}
}
groups.set(normalized, { distances, speeds: allSpeeds });
const el = scan?.ElevationCurrent;
if (typeof el === "number" && !isNaN(el)) {
if (elevationMin === null || el < elevationMin) elevationMin = el;
if (elevationMax === null || el > elevationMax) elevationMax = el;
}
const azCur = scan?.AzimuthCurrent;
if (typeof azCur === "number" && !isNaN(azCur)) {
if (azimuthMin === null || azCur < azimuthMin) azimuthMin = azCur;
if (azimuthMax === null || azCur > azimuthMax) azimuthMax = azCur;
}
});
if (!isFinite(globalMin)) globalMin = -30;
if (!isFinite(globalMax)) globalMax = 30;
if (globalMax - globalMin < 1) {
globalMin -= 10;
globalMax += 10;
}
let maxDistance = startDist + (maxLen - 1) * gateDist;
groups.forEach((entry) => {
if (entry.distances.length > 0) {
const maxD = entry.distances[entry.distances.length - 1];
if (maxD > maxDistance) maxDistance = maxD;
}
});
maxDistance = Math.max(maxDistance, 1000);
const latestScan = scans[scans.length - 1];
const azimuthCurrent = latestScan?.AzimuthCurrent ?? null;
let step: number | null = null;
if (scans.length >= 2) {
const a1 = scans[0]?.[angleField];
const a2 = scans[1]?.[angleField];
if (
typeof a1 === "number" &&
!isNaN(a1) &&
typeof a2 === "number" &&
!isNaN(a2)
) {
let diff = Math.abs(a2 - a1);
if (diff > 180) diff = 360 - diff;
if (diff > 0) step = diff;
}
}
const result: ParsedData = {
groups,
time,
maxDistance,
startDist,
gateDist,
gateTotal: maxLen,
mode,
elevationMin,
elevationMax,
azimuthMin,
azimuthMax,
azimuthCurrent,
step,
speedMin: globalMin,
speedMax: globalMax,
};
if (rtc) {
parsedCache.set(rtc, result);
}
return result;
}
// ============================================================
// 帧历史管理(保留最新 11 帧)
// ============================================================
const frames = ref<any[]>([]);
const currentFrameIndex = ref(-1);
const MAX_FRAMES = 11;
const currentData = computed<ParsedData | null>(() => {
if (
currentFrameIndex.value < 0 ||
currentFrameIndex.value >= frames.value.length
)
return null;
return extractFrameData(frames.value[currentFrameIndex.value]);
});
// ============================================================
// 时间轴辅助
// ============================================================
function getTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (rtc) {
const dt = new Date(rtc);
return dt.toLocaleTimeString("zh-CN", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
});
}
return "--";
}
/** 顶部时间标签:时:分:秒 */
function getFullTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (rtc) {
const dt = new Date(rtc);
return dt.toLocaleTimeString("zh-CN", { hour12: false });
}
return "--";
}
const currentTimeLabel = computed(() => {
if (
currentFrameIndex.value < 0 ||
currentFrameIndex.value >= frames.value.length
)
return "--";
return getFullTimeLabel(frames.value[currentFrameIndex.value]);
});
const timeMarks = computed(() => {
const marks: Record<number, string> = {};
frames.value.forEach((frame, idx) => {
marks[idx] = getTimeLabel(frame);
});
return marks;
});
function onSliderChange(val: number) {
scheduleRender();
}
/** 左右按钮逐帧切换 */
function stepFrame(delta: number) {
const fs = frames.value;
if (fs.length === 0) return;
const next = Math.min(
Math.max(currentFrameIndex.value + delta, 0),
fs.length - 1,
);
if (next === currentFrameIndex.value) return;
currentFrameIndex.value = next;
scheduleRender();
}
// ============================================================
// 监听 deviceInfo 更新
// ============================================================
watch(
() => deviceInfo.value,
(newVal) => {
if (!deviceInfo || !Array.isArray(newVal) || newVal.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
const validFrames = newVal.filter((frame) => frame?.Scans?.length > 0);
if (validFrames.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
// 帧内去重:RHI 按俯仰角、PPI 按方位角,完全相同的射线只保留第一条
const dedupedFrames = validFrames.map((frame) => {
const scans = frame?.Scans;
if (!Array.isArray(scans) || scans.length < 2) return frame;
const angleField =
(scans[0]?.Mode ?? "PPI") === "RHI"
? "ElevationCurrent"
: "AzimuthCurrent";
const seenAngles = new Set<number>();
const uniqueScans: any[] = [];
for (const scan of scans) {
const angle = scan?.[angleField];
if (typeof angle !== "number" || isNaN(angle)) {
// 无角度的射线交给解析层处理,这里不参与去重
uniqueScans.push(scan);
continue;
}
if (seenAngles.has(angle)) continue;
seenAngles.add(angle);
uniqueScans.push(scan);
}
// 按俯仰角(PPI 为方位角)升序排列
uniqueScans.sort((a, b) => {
const av = a?.[angleField];
const bv = b?.[angleField];
const aValid = typeof av === "number" && !isNaN(av);
const bValid = typeof bv === "number" && !isNaN(bv);
if (aValid && bValid) return av - bv;
if (aValid) return -1;
if (bValid) return 1;
return 0;
});
// 没有重复且顺序未变时复用原对象,避免无意义的拷贝
const changed =
uniqueScans.length !== scans.length ||
uniqueScans.some((scan, i) => scan !== scans[i]);
return changed ? { ...frame, Scans: uniqueScans } : frame;
});
const seen = new Set<string>();
const uniqueFrames: any[] = [];
for (const frame of dedupedFrames) {
const rtc = frame?.Scan?.RTC;
if (rtc && !seen.has(rtc)) {
seen.add(rtc);
uniqueFrames.push(frame);
}
}
uniqueFrames.sort((a, b) => {
const t1 = a?.Scan?.RTC || "";
const t2 = b?.Scan?.RTC || "";
return t1.localeCompare(t2);
});
if (uniqueFrames.length > MAX_FRAMES) {
uniqueFrames.splice(0, uniqueFrames.length - MAX_FRAMES);
}
const newRTCs = uniqueFrames
.map((f) => f?.Scan?.RTC)
.filter(Boolean) as string[];
const oldRTCs = frames.value
.map((f) => f?.Scan?.RTC)
.filter(Boolean) as string[];
if (
newRTCs.length === oldRTCs.length &&
newRTCs.every((rtc, i) => rtc === oldRTCs[i])
) {
return;
}
let currentRTC: string | null = null;
let wasLatest = false;
if (
currentFrameIndex.value >= 0 &&
currentFrameIndex.value < frames.value.length
) {
const currentFrame = frames.value[currentFrameIndex.value];
if (currentFrame?.Scan?.RTC) {
currentRTC = currentFrame.Scan.RTC;
if (currentFrameIndex.value === frames.value.length - 1) {
wasLatest = true;
}
}
}
frames.value = uniqueFrames;
if (frames.value.length === 0) {
currentFrameIndex.value = -1;
} else if (wasLatest) {
currentFrameIndex.value = frames.value.length - 1;
} else if (currentRTC) {
const foundIndex = frames.value.findIndex(
(f) => f?.Scan?.RTC === currentRTC,
);
if (foundIndex !== -1) {
currentFrameIndex.value = foundIndex;
} else {
currentFrameIndex.value = 0;
}
} else {
currentFrameIndex.value = frames.value.length - 1;
}
scheduleRender();
},
{ deep: true, immediate: true },
);
// ============================================================
// 核心绘制函数
// ============================================================
function drawRadar(canvas: HTMLCanvasElement, data: ParsedData) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const { groups, maxDistance, gateDist } = data;
const dpr = window.devicePixelRatio || 1;
const rect = canvas.parentElement?.getBoundingClientRect();
const containerWidth = rect?.width || 600;
const containerHeight = rect?.height || 600;
canvas.width = containerWidth * dpr;
canvas.height = containerHeight * dpr;
canvas.style.width = "100%";
canvas.style.height = "100%";
ctx.scale(dpr, dpr);
const { cx, cy, radius } = getRadarGeometry(containerWidth, containerHeight);
ctx.clearRect(0, 0, containerWidth, containerHeight);
ctx.fillStyle = "#0a0e1a";
ctx.fillRect(0, 0, containerWidth, containerHeight);
ctx.save();
ctx.translate(cx + panX.value, cy + panY.value);
ctx.scale(zoomLevel.value, zoomLevel.value);
ctx.translate(-cx, -cy);
// 同心圆网格(上半圆:-π ~ 0)
const gridStep = Math.max(1000, Math.ceil(maxDistance / 10 / 1000) * 1000);
const gridCount = Math.floor(maxDistance / gridStep);
for (let i = 1; i <= gridCount; i++) {
const dist = i * gridStep;
const r = (dist / maxDistance) * radius;
if (r <= radius) {
ctx.beginPath();
ctx.arc(cx, cy, r, -Math.PI, 0);
ctx.strokeStyle =
i === gridCount ? "rgba(255,255,255,0.4)" : "rgba(255,255,255,0.28)";
ctx.lineWidth = i === gridCount ? 1.0 : 0.5;
ctx.stroke();
}
}
// 径向线(0°~180°,每 45° 一条)
for (let i = 0; i <= 4; i++) {
const angle = i * 45;
const rad = azimuthToCanvasRad(angle);
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.lineTo(cx + radius * Math.cos(rad), cy + radius * Math.sin(rad));
ctx.strokeStyle =
i === 0 ? "rgba(255,255,255,0.4)" : "rgba(255,255,255,0.28)";
ctx.lineWidth = i === 0 ? 1.0 : 0.5;
ctx.stroke();
}
// 绘制彩色扇形
if (groups.size > 0 && maxDistance > 0) {
ctx.globalAlpha = 0.9;
const toScreenX = (lx: number, ly: number) =>
(lx - cx) * zoomLevel.value + (cx + panX.value);
const toScreenY = (lx: number, ly: number) =>
(ly - cy) * zoomLevel.value + (cy + panY.value);
const margin = 20;
// ★ 等宽扇区:以角度为起点,宽度 = step
const sortedAngles = Array.from(groups.keys()).sort((a, b) => a - b);
const step = getEffectiveStep(sortedAngles, data.step);
sortedAngles.forEach((angle) => {
const entry = groups.get(angle);
if (!entry) return;
const { distances, speeds } = entry;
if (distances.length === 0) return;
// ★ 扇区覆盖 [angle, angle + step](角度越大越偏左,故弧线起止需对调)
const startRad = azimuthToCanvasRad(angle + step);
const endRad = azimuthToCanvasRad(angle);
const midAngleRad = azimuthToCanvasRad(angle + step / 2);
for (let i = 0; i < distances.length; i++) {
const dist = distances[i];
const speed = speeds[i];
if (dist === undefined || speed === undefined || isNaN(speed)) continue;
const r1 = (dist / maxDistance) * radius;
const nextDist =
i + 1 < distances.length ? distances[i + 1] : dist + gateDist;
const r2 = Math.min((nextDist / maxDistance) * radius, radius);
const midDist = (r1 + r2) / 2;
const logicX = cx + midDist * Math.cos(midAngleRad);
const logicY = cy + midDist * Math.sin(midAngleRad);
const screenX = toScreenX(logicX, logicY);
const screenY = toScreenY(logicX, logicY);
if (
screenX < -margin ||
screenX > containerWidth + margin ||
screenY < -margin ||
screenY > containerHeight + margin
) {
continue;
}
if (speed === 999 || isNaN(speed)) {
ctx.fillStyle = "rgba(110, 122, 145, 0.35)";
} else {
ctx.fillStyle = getVelocityColor(speed);
}
ctx.beginPath();
ctx.arc(cx, cy, r2, startRad, endRad);
ctx.arc(cx, cy, r1, endRad, startRad, true);
ctx.closePath();
ctx.fill();
}
});
ctx.globalAlpha = 1.0;
}
// 角度标注
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "11px sans-serif";
ctx.fillStyle = "rgba(255,255,255,0.7)";
for (let i = 0; i <= 4; i++) {
const angle = i * 45;
const rad = azimuthToCanvasRad(angle);
const labelR = radius + 18;
ctx.fillText(
angle + "°",
cx + labelR * Math.cos(rad),
cy + labelR * Math.sin(rad),
);
}
// 距离标注
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.font = "10px sans-serif";
ctx.fillStyle = "rgba(255,255,255,0.5)";
const labelStep = Math.max(1000, Math.ceil(maxDistance / 10 / 1000) * 1000);
const labelCount = Math.floor(maxDistance / labelStep);
for (let i = 1; i <= labelCount; i++) {
const dist = i * labelStep;
const r = (dist / maxDistance) * radius;
if (r <= radius) {
ctx.fillText(dist + "m", cx + 22, cy - r + 3);
}
}
// 中心点
ctx.beginPath();
ctx.arc(cx, cy, 1, 0, Math.PI * 2);
ctx.fillStyle = "rgba(255,255,255,0.6)";
ctx.fill();
ctx.restore();
drawLegend(legendCanvas.value);
}
// ============================================================
// 图例绘制(固定 -50 ~ +50 绝对速度色标)
// ============================================================
function drawLegend(canvas: HTMLCanvasElement | null) {
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const rect = canvas.parentElement?.getBoundingClientRect();
const width = Math.round(rect?.width || 200);
const height = 20;
if (
canvas.width !== Math.round(width * dpr) ||
canvas.height !== Math.round(height * dpr)
) {
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
canvas.style.width = width + "px";
canvas.style.height = height + "px";
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const grad = ctx.createLinearGradient(0, 0, width, 0);
const span = COLOR_SPEED_MAX - COLOR_SPEED_MIN || 1;
VELOCITY_COLOR_STOPS.forEach((s) => {
let pos = (s.speed - COLOR_SPEED_MIN) / span;
pos = pos < 0 ? 0 : pos > 1 ? 1 : pos;
grad.addColorStop(pos, `rgb(${s.rgb[0]},${s.rgb[1]},${s.rgb[2]})`);
});
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = "rgba(255,255,255,0.3)";
ctx.lineWidth = 1;
ctx.strokeRect(0.5, 0.5, width - 1, height - 1);
}
// ============================================================
// 缩放控制
// ============================================================
const ZOOM_STEP = 1;
const ZOOM_MIN = 0.5;
const ZOOM_MAX = 15;
function handleZoomIn() {
const newZoom = Math.min(zoomLevel.value + ZOOM_STEP, ZOOM_MAX);
if (newZoom !== zoomLevel.value) {
zoomLevel.value = newZoom;
scheduleRender();
}
}
function handleZoomOut() {
const newZoom = Math.max(zoomLevel.value - ZOOM_STEP, ZOOM_MIN);
if (newZoom !== zoomLevel.value) {
zoomLevel.value = newZoom;
scheduleRender();
}
}
function resetZoom() {
zoomLevel.value = 1;
panX.value = 0;
panY.value = 0;
scheduleRender();
}
// ============================================================
// 鼠标交互(拖拽 + Tooltip)
// ============================================================
function handleMouseDown(e: MouseEvent) {
if (e.button !== 0) return;
const canvas = canvasRef.value;
if (!canvas) return;
isDragging.value = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
dragStartPanX = panX.value;
dragStartPanY = panY.value;
canvas.style.cursor = "grabbing";
tooltip.value.visible = false;
}
function handleMouseMove(e: MouseEvent) {
const canvas = canvasRef.value;
if (!canvas) return;
if (isDragging.value) {
panX.value = dragStartPanX + (e.clientX - dragStartX);
panY.value = dragStartPanY + (e.clientY - dragStartY);
scheduleRender();
return;
}
// Tooltip 悬停逻辑
const rect = canvas.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const containerWidth = rect.width;
const containerHeight = rect.height;
const { cx, cy, radius: radarRadius } = getRadarGeometry(
containerWidth,
containerHeight,
);
const logicX = (mouseX - (cx + panX.value)) / zoomLevel.value + cx;
const logicY = (mouseY - (cy + panY.value)) / zoomLevel.value + cy;
const dx = logicX - cx;
const dy = logicY - cy;
const distFromCenter = Math.sqrt(dx * dx + dy * dy);
const data = currentData.value;
if (
!data ||
data.groups.size === 0 ||
data.maxDistance <= 0 ||
distFromCenter > radarRadius ||
distFromCenter < 5
) {
tooltip.value.visible = false;
return;
}
// 仅在上半圆(0°~180°)内有效
if (dy > 0) {
tooltip.value.visible = false;
return;
}
const { groups, maxDistance, gateDist } = data;
// 0° 在右、90° 在上、180° 在左(与 azimuthToCanvasRad 保持一致)
const mathAngle = Math.atan2(-dy, dx);
let angleDeg = (mathAngle * 180) / Math.PI;
angleDeg = ((angleDeg % 360) + 360) % 360;
const distance = (distFromCenter / radarRadius) * maxDistance;
// ★ 等宽扇区反查:找覆盖鼠标角度的扇区 [angle, angle + step)
const sortedAngles = Array.from(groups.keys()).sort((a, b) => a - b);
const step = getEffectiveStep(sortedAngles, data.step);
let closestAngle: number | null = null;
for (const a of sortedAngles) {
if (angleDeg >= a && angleDeg < a + step) {
closestAngle = a;
break;
}
}
// 越界角度(< 0 或 > 180)不命中
if (closestAngle === null || angleDeg < 0 || angleDeg > 180) {
tooltip.value.visible = false;
return;
}
const entry = groups.get(closestAngle);
if (!entry || entry.distances.length === 0) {
tooltip.value.visible = false;
return;
}
let matchedIdx = -1;
for (let i = 0; i < entry.distances.length; i++) {
const start = entry.distances[i];
let end: number;
if (i + 1 < entry.distances.length) {
end = entry.distances[i + 1];
} else {
end = start + gateDist;
}
if (distance >= start && distance < end) {
matchedIdx = i;
break;
}
}
if (matchedIdx === -1) {
tooltip.value.visible = false;
return;
}
const matchedDistance = entry.distances[matchedIdx];
const matchedSpeed = entry.speeds[matchedIdx];
if (
matchedSpeed === undefined ||
isNaN(matchedSpeed) ||
matchedSpeed === 999
) {
tooltip.value.visible = false;
return;
}
const wrapperRect = canvas.parentElement?.getBoundingClientRect();
if (!wrapperRect) return;
const wrapperX = e.clientX - wrapperRect.left;
const wrapperY = e.clientY - wrapperRect.top;
const offsetX = 12;
const offsetY = 12;
tooltip.value = {
x: wrapperX + offsetX,
y: wrapperY + offsetY,
visible: true,
distance: Math.round(matchedDistance),
angle: closestAngle,
speed: matchedSpeed,
};
}
function handleMouseUp(e: MouseEvent) {
if (isDragging.value) {
isDragging.value = false;
if (canvasRef.value) canvasRef.value.style.cursor = "default";
}
}
function handleMouseLeave() {
if (isDragging.value) {
isDragging.value = false;
if (canvasRef.value) canvasRef.value.style.cursor = "default";
}
tooltip.value.visible = false;
}
function handleWheel(e: WheelEvent) {
e.preventDefault();
const delta = e.deltaY > 0 ? 0.9 : 1.1;
let newZoom = zoomLevel.value * delta;
if (newZoom < ZOOM_MIN) newZoom = ZOOM_MIN;
if (newZoom > ZOOM_MAX) newZoom = ZOOM_MAX;
if (newZoom !== zoomLevel.value) {
zoomLevel.value = newZoom;
scheduleRender();
}
}
// ============================================================
// 渲染调度
// ============================================================
let resizeObserver: ResizeObserver | null = null;
function render() {
const canvas = canvasRef.value;
if (!canvas) return;
const data = currentData.value;
if (!data) {
const ctx = canvas.getContext("2d");
if (ctx) {
const rect = canvas.parentElement?.getBoundingClientRect();
const w = rect?.width || 600,
h = rect?.height || 600;
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "#0a0e1a";
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = "rgba(255,255,255,0.3)";
ctx.font = "16px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("无数据", w / 2, h / 2);
}
drawLegend(legendCanvas.value);
return;
}
drawRadar(canvas, data);
}
function scheduleRender() {
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
animationId = requestAnimationFrame(() => {
render();
animationId = null;
});
}
// ============================================================
// 生命周期
// ============================================================
onMounted(() => {
nextTick(() => {
if (
!deviceInfo.value ||
!Array.isArray(deviceInfo.value) ||
deviceInfo.value.length === 0
)
render();
const canvas = canvasRef.value;
if (canvas && canvas.parentElement) {
resizeObserver = new ResizeObserver(() => {
resetZoom();
scheduleRender();
});
resizeObserver.observe(canvas.parentElement);
}
const canvasEl = canvasRef.value;
if (canvasEl) {
canvasEl.addEventListener("mousedown", handleMouseDown);
canvasEl.addEventListener("mousemove", handleMouseMove);
canvasEl.addEventListener("mouseup", handleMouseUp);
canvasEl.addEventListener("mouseleave", handleMouseLeave);
canvasEl.addEventListener("wheel", handleWheel, { passive: false });
}
});
});
onBeforeUnmount(() => {
if (resizeObserver) {
resizeObserver.disconnect();
resizeObserver = null;
}
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
const canvasEl = canvasRef.value;
if (canvasEl) {
canvasEl.removeEventListener("mousedown", handleMouseDown);
canvasEl.removeEventListener("mousemove", handleMouseMove);
canvasEl.removeEventListener("mouseup", handleMouseUp);
canvasEl.removeEventListener("mouseleave", handleMouseLeave);
canvasEl.removeEventListener("wheel", handleWheel);
}
});
// ============================================================
// 计算属性(信息面板、图例)
// ============================================================
const formatRange = (min: number | null, max: number | null): string => {
if (min === null || max === null) return "--";
return min === max ? min + "°" : min + "°~" + max + "°";
};
const scanParams = computed(() => {
const data = currentData.value;
if (!data)
return {
mode: "PPI",
elevationMin: null,
elevationMax: null,
azimuthMin: null,
azimuthMax: null,
azimuthCurrent: null,
step: null,
};
const {
mode,
elevationMin,
elevationMax,
azimuthMin,
azimuthMax,
azimuthCurrent,
step,
} = data;
return {
mode,
elevationMin,
elevationMax,
azimuthMin,
azimuthMax,
azimuthCurrent,
step,
};
});
const legendMinSpeed = computed(() => COLOR_SPEED_MIN.toFixed(0));
const legendMaxSpeed = computed(() => "+" + COLOR_SPEED_MAX.toFixed(0));
</script>
<style scoped lang="less">
.radar-ppi-container {
position: relative;
width: 100%;
height: 100%;
border-right: 1px solid #243049;
padding: 0 10px;
display: flex;
flex-direction: column;
background: #0a0e1a;
.radar-canvas-wrapper {
flex: 1;
min-height: 0;
position: relative;
.radar-canvas {
display: block;
width: 100%;
height: 100%;
cursor: default;
user-select: none;
}
.realtime-rhi-panel {
position: absolute;
top: 8px;
right: 8px;
width: 300px;
height: 150px;
background-color: #0a0e1a;
}
.radar-info-panel {
position: absolute;
top: 8px;
left: 8px;
font-size: 14px;
color: rgba(255, 255, 255, 0.85);
line-height: 1.6;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
}
.radar-legend {
position: absolute;
right: 16px;
bottom: 16px;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
.legend-canvas {
display: block;
width: 200px;
height: 20px;
border-radius: 2px;
margin-bottom: 2px;
}
.legend-labels {
display: flex;
justify-content: space-between;
font-size: 11px;
color: rgba(255, 255, 255, 0.7);
}
}
.radar-tooltip {
position: absolute;
background: rgba(0, 0, 0, 0.85);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
padding: 8px 12px;
font-size: 12px;
color: #fff;
line-height: 1.6;
pointer-events: none;
white-space: nowrap;
z-index: 10;
}
.zoom-controls {
position: absolute;
bottom: 16px;
left: 16px;
display: flex;
align-items: center;
gap: 6px;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
padding: 4px 6px;
user-select: none;
.zoom-btn {
width: 28px;
height: 28px;
background: transparent;
border: none;
color: #fff;
font-size: 18px;
font-weight: bold;
cursor: pointer;
border-radius: 2px;
transition: background 0.15s;
display: flex;
align-items: center;
justify-content: center;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.1);
}
&:disabled {
color: rgba(255, 255, 255, 0.25);
cursor: not-allowed;
}
}
.zoom-level {
min-width: 44px;
text-align: center;
font-size: 13px;
color: rgba(255, 255, 255, 0.85);
font-variant-numeric: tabular-nums;
}
.zoom-divider {
width: 1px;
height: 16px;
background: rgba(255, 255, 255, 0.2);
}
.zoom-btn.reset-btn {
font-size: 15px;
}
}
.timeline-container {
position: absolute;
bottom: 8px;
left: 50%;
transform: translateX(-50%);
width: 70%;
max-width: 700px;
backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
padding: 4px 12px 20px 12px;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 4px;
.timeline-header {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
font-size: 11px;
color: rgba(255, 255, 255, 0.8);
.timeline-label-left {
justify-self: start;
}
.timeline-label-right {
justify-self: end;
}
.timeline-current-group {
display: flex;
align-items: center;
gap: 8px;
.timeline-current {
min-width: 64px;
text-align: center;
color: var(--el-color-primary);
font-weight: bold;
font-size: 13px;
}
}
}
.time-nav-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 50%;
background: rgba(255, 255, 255, 0.06);
color: rgba(255, 255, 255, 0.8);
font-size: 14px;
cursor: pointer;
transition:
background-color 0.15s,
border-color 0.15s,
color 0.15s;
&:hover:not(:disabled) {
background: rgba(64, 158, 255, 0.3);
border-color: var(--el-color-primary);
color: #fff;
}
&:disabled {
opacity: 0.3;
cursor: not-allowed;
}
}
.timeline-slider {
width: 100%;
margin: 0;
:deep(.el-slider__marks-text) {
color: rgba(255, 255, 255, 0.7);
font-size: 9px;
white-space: nowrap;
}
}
}
}
}
:deep(.el-slider__button) {
height: 15px;
width: 15px;
&:hover {
height: 15px;
width: 15px;
}
}
</style>
五、VOL:多俯仰层堆成 3D 体扫
VOL 的本质是"很多层 PPI"。实现上不再用 Canvas 2D 逐个扇区画,而是先构建顶点数据,再用 WebGL2 渲染。
5.1 按俯仰角分层
ts
const elMap = new Map<number, ParsedScan[]>();
for (const scan of scans) {
const el = scan.ElevationCurrent ?? 0;
const elKey = Math.round(el * 10) / 10; // 保留一位小数作为层 key
if (!elMap.has(elKey)) elMap.set(elKey, []);
elMap.get(elKey)!.push(parsedScan);
}
每层内的扫描再按方位角排序,保证相邻扫描可以两两拼接。
5.2 每个距离门生成一个四边形
VOL 的每个 cell 是一个四边形:相邻两条方位射线 × 相邻两个距离门。
ts
const cr1 = r1 * cosEl, cr2 = r2 * cosEl;
const z1 = r1 * sinEl, z2 = r2 * sinEl;
// 四个顶点:p0 p1 p2 p3,每个 3 个 float
cells[o + 0] = cr1 * s1sx; cells[o + 1] = cr1 * s1cx; cells[o + 2] = z1;
cells[o + 3] = cr1 * s2sx; cells[o + 4] = cr1 * s2cx; cells[o + 5] = z1;
cells[o + 6] = cr2 * s2sx; cells[o + 7] = cr2 * s2cx; cells[o + 8] = z2;
cells[o + 9] = cr2 * s1sx; cells[o + 10] = cr2 * s1cx; cells[o + 11] = z2;
这里把极坐标先转成三维直角坐标:
ts
x = r * cosEl * sinAz;
y = r * cosEl * cosAz;
z = r * sinEl;
每个 cell 用 16 个 float 描述:12 个顶点坐标 + 速度 + 方位角 + 俯仰角 + 距离。速度取相邻两条射线的平均值,任一无效则退化到有效那条。
5.3 透视投影
相机用 yaw / pitch / zoom / panX / panY 五个参数控制,核心投影公式:
ts
const t = -x * sinY - y * cosY;
const zc = t * cosP - z * sinP + dist;
if (zc < 1) return null; // 相机后方剔除
const s = focal / zc;
return {
x: cx + (-x * cosY + y * sinY) * s,
y: cy - (t * sinP + z * cosP) * s,
z: zc,
};
zc 同时用于深度测试和透明度排序,非常关键。
5.4 颜色用纹理查表
3D 场景里逐顶点插值颜色开销大,做法是生成一张色标纹理,着色器里按速度采样:
ts
gl.texImage2D(
gl.TEXTURE_2D, 0, gl.RGBA, 256, 1, 0,
gl.RGBA, gl.UNSIGNED_BYTE, colorData
);
这样改色标只需要重建这张 256×1 的纹理,不用动顶点数据。
5.5 层筛选
VOL 支持只看某几个俯仰层。选中集合为空表示"全部",非空则只渲染对应层:
ts
const selectedElevations = ref<number[]>([]); // 空 = 全部
const isAllLayersSelected = computed(() => selectedElevations.value.length === 0);
层数少时用按钮列表,超过 10 层自动切换成带搜索的弹出面板,避免按钮把画布挤爆。
VOLChart.vue 完整源码
vue
<template>
<div class="radar-ppi-container">
<div class="radar-canvas-wrapper">
<canvas
ref="canvasRef"
class="radar-canvas"
:class="{ dragging: isDragging }"
@mousedown="onMouseDown"
@mousemove="onMouseMove"
@mouseup="onMouseUp"
@mouseleave="onMouseLeave"
@wheel.prevent="onWheel"
@dblclick="resetView"
@contextmenu.prevent
></canvas>
<canvas ref="gridOverlayRef" class="radar-grid-overlay"></canvas>
<!-- 实时体扫雷达(左上角) -->
<div class="realtime-vol-panel">
<RealTimeVOLChart />
</div>
<div class="radar-info-panel">
<div v-for="row in infoRows" :key="row.k" class="info-row">
<span class="k">{{ row.k }}:</span>
<span class="v" :class="{ highlight: row.hl }">{{ row.v }}</span>
</div>
</div>
<div class="radar-legend">
<canvas ref="legendCanvasRef" class="legend-canvas"></canvas>
<div class="legend-labels">
<span>{{ legendMin }} m/s</span>
<span>{{ legendMax }} m/s</span>
</div>
</div>
<div class="view-controls">
<el-tooltip content="缩小" placement="bottom" :show-after="300">
<button class="view-btn" :disabled="cam.zoom <= ZOOM_MIN" @click="zoomOut">
<el-icon><Minus /></el-icon>
</button>
</el-tooltip>
<span class="zoom-level">{{ cam.zoom.toFixed(1) }}</span>
<el-tooltip content="放大" placement="bottom" :show-after="300">
<button class="view-btn" :disabled="cam.zoom >= ZOOM_MAX" @click="zoomIn">
<el-icon><Plus /></el-icon>
</button>
</el-tooltip>
<span class="zoom-divider"></span>
<el-tooltip content="重置视角(双击画布同效)" placement="bottom" :show-after="300">
<button class="view-btn reset-btn" :disabled="isDefaultView" @click="resetView">
<el-icon><Aim /></el-icon>
</button>
</el-tooltip>
</div>
<!-- ================= 俯仰层选择 ================= -->
<template v-if="elevationOptions.length > 1">
<!-- 少量层:按钮列表 -->
<div v-if="elevationOptions.length <= LAYER_BUTTON_THRESHOLD" class="layer-switcher">
<div class="layer-list">
<button
class="layer-btn all-btn"
:class="{ active: isAllLayersSelected }"
@click="selectAllLayers"
title="显示全部层"
>
全部
</button>
<button
v-for="el in elevationOptions"
:key="el"
class="layer-btn"
:class="{ active: isLayerSelected(el) }"
@click="toggleLayer(el)"
:title="`切换 ${formatEl(el)}° 俯仰层显示(可多选)`"
>
{{ formatEl(el) }}°
</button>
</div>
</div>
<!-- 大量层:弹出面板 -->
<div v-else class="layer-switcher-popover">
<button
class="layer-trigger"
:class="{ active: !isAllLayersSelected }"
@click.stop="layerPanelOpen = !layerPanelOpen"
:title="layerTriggerTitle"
>
{{ currentLayerLabel }}
</button>
<div
v-if="layerPanelOpen"
class="layer-panel"
@click.stop
>
<div class="layer-panel-head">
<span class="layer-panel-title">
俯仰层 <span class="layer-panel-count">{{ selectionSummary }}</span>
</span>
<button
class="mini-btn"
:disabled="isAllLayersSelected"
@click="selectAllLayers"
>
全部
</button>
</div>
<input
v-if="elevationOptions.length > 12"
v-model="layerSearch"
class="layer-search"
type="text"
placeholder="搜索角度"
@keydown.esc="layerSearch = ''"
/>
<div class="layer-panel-list">
<label
v-for="el in filteredElevationOptions"
:key="el"
class="layer-check-item"
:class="{ checked: isLayerSelected(el) }"
>
<input
type="checkbox"
:checked="isLayerSelected(el)"
@change="toggleLayer(el)"
/>
<span>{{ formatEl(el) }}°</span>
</label>
<div v-if="filteredElevationOptions.length === 0" class="layer-empty">
无匹配角度
</div>
</div>
</div>
</div>
</template>
<!-- ================= /俯仰层选择 ================= -->
<div v-show="frames.length > 0" class="timeline-container">
<div class="timeline-header">
<span class="timeline-label-left">{{ leftTimeLabel }}</span>
<div class="timeline-current-group">
<button
class="time-nav-btn"
:disabled="currentFrameIndex <= 0"
title="上一帧"
@click="stepFrame(-1)"
>
<el-icon><ArrowLeft /></el-icon>
</button>
<span class="timeline-current">{{ currentTimeLabel }}</span>
<button
class="time-nav-btn"
:disabled="currentFrameIndex >= frames.length - 1"
title="下一帧"
@click="stepFrame(1)"
>
<el-icon><ArrowRight /></el-icon>
</button>
</div>
<span class="timeline-label-right">{{ rightTimeLabel }}</span>
</div>
<el-slider
v-model="currentFrameIndex"
:min="0"
:max="Math.max(0, frames.length - 1)"
:marks="timeMarks"
:show-tooltip="false"
size="small"
class="timeline-slider"
@change="onSliderChange"
/>
</div>
<div
v-show="tooltip.visible"
class="radar-tooltip"
:style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"
>
<div>距离:<span class="tv">{{ tooltip.distance }} m</span></div>
<div>方位角:<span class="tv">{{ tooltip.azimuth }}°</span></div>
<div>俯仰角:<span class="tv">{{ tooltip.elevation }}°</span></div>
<div>速度:<span class="tv">{{ tooltip.speed.toFixed(1) }} m/s</span></div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import {
ref, shallowRef, reactive, computed, watch,
onMounted, onBeforeUnmount, nextTick, inject, type Ref,
} from "vue";
import { Plus, Minus, Aim, ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import RealTimeVOLChart from "./RealTimeVOLChart.vue";
/* ============================================================
* 1. 常量与类型
* ============================================================ */
const MAX_FRAMES = 11;
const ZOOM_STEP = 0.25;
const ZOOM_MIN = 0.4;
const ZOOM_MAX = 20;
const PITCH_MIN = 0.05;
const PITCH_MAX = 1.52;
const DEFAULT_CAM = { yaw: Math.PI, pitch: 0.55, zoom: 0.7, panX: 0, panY: 0 };
const NO_DATA = 999;
/** 层数 ≤ 该值用按钮列表,超过则用弹出面板 */
const LAYER_BUTTON_THRESHOLD = 10;
/* ============================================================
* 2. 速度色标(含缓存)
* ============================================================ */
interface ColorStop { speed: number; rgb: [number, number, number]; }
const VELOCITY_COLOR_STOPS: ColorStop[] = [
{ speed: -50, rgb: [59, 15, 111] },
{ speed: -40, rgb: [0, 0, 255] },
{ speed: -30, rgb: [0, 128, 255] },
{ speed: -20, rgb: [0, 224, 255] },
{ speed: -10, rgb: [0, 255, 128] },
{ speed: 0, rgb: [160, 160, 160] },
{ speed: 10, rgb: [255, 240, 0] },
{ speed: 20, rgb: [255, 160, 0] },
{ speed: 30, rgb: [255, 60, 0] },
{ speed: 40, rgb: [220, 0, 0] },
{ speed: 50, rgb: [139, 0, 0] },
];
const COLOR_SPEED_MIN = VELOCITY_COLOR_STOPS[0].speed;
const COLOR_SPEED_MAX = VELOCITY_COLOR_STOPS[VELOCITY_COLOR_STOPS.length - 1].speed;
function sampleVelocityRGB(speed: number): [number, number, number] {
const stops = VELOCITY_COLOR_STOPS;
if (speed <= stops[0].speed) return [...stops[0].rgb] as [number, number, number];
if (speed >= stops[stops.length - 1].speed) return [...stops[stops.length - 1].rgb] as [number, number, number];
for (let i = 0; i < stops.length - 1; i++) {
const a = stops[i], b = stops[i + 1];
if (speed >= a.speed && speed <= b.speed) {
const t = (speed - a.speed) / (b.speed - a.speed);
return [
Math.round(a.rgb[0] + t * (b.rgb[0] - a.rgb[0])),
Math.round(a.rgb[1] + t * (b.rgb[1] - a.rgb[1])),
Math.round(a.rgb[2] + t * (b.rgb[2] - a.rgb[2])),
];
}
}
return [160, 160, 160];
}
/* ============================================================
* 3. 工具函数
* ============================================================ */
function formatTime(rtc: string): string {
if (!rtc) return "";
const dt = new Date(rtc);
return isNaN(dt.getTime())
? rtc
: dt.toLocaleString("zh-CN", { hour12: false });
}
function getTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (!rtc) return "--";
const dt = new Date(rtc);
return isNaN(dt.getTime())
? "--"
: dt.toLocaleTimeString("zh-CN", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
});
}
/** 顶部时间标签:时:分:秒 */
function getFullTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (!rtc) return "--";
const dt = new Date(rtc);
return isNaN(dt.getTime())
? "--"
: dt.toLocaleTimeString("zh-CN", { hour12: false });
}
function formatRange(min: number | null, max: number | null): string {
if (min === null || max === null) return "--";
return Math.abs(max - min) < 0.001
? `${min.toFixed(0)}°`
: `${min.toFixed(0)}°~${max.toFixed(0)}°`;
}
function formatEl(el: number): string {
return Number.isInteger(el) ? el.toFixed(0) : el.toFixed(1);
}
/* ============================================================
* 4. 帧解析
* ============================================================ */
interface ParsedScan {
az: number; sinAz: number; cosAz: number;
distances: number[]; speeds: number[];
}
interface ParsedLayer {
el: number;
scans: ParsedScan[];
cellCount: number;
cells: Float32Array;
}
interface ParsedData {
layers: ParsedLayer[];
time: string;
maxDistance: number;
gateDist: number;
startDist: number;
speedMin: number;
speedMax: number;
elMin: number | null;
elMax: number | null;
azMin: number | null;
azMax: number | null;
azStep: number;
elStep: number;
mode: string;
maxLen: number;
}
/** 每 cell 16 float:[0..2]p0 [3..5]p1 [6..8]p2 [9..11]p3 [12]speed [13]az [14]el [15]r */
const CELL_STRIDE_W = 16;
function buildLayerCells(layer: ParsedLayer, gateDist: number) {
const scans = layer.scans;
const n = scans.length;
if (n < 2) {
layer.cells = new Float32Array(0);
layer.cellCount = 0;
return;
}
const elRad = (layer.el * Math.PI) / 180;
const sinEl = Math.sin(elRad);
const cosEl = Math.cos(elRad);
let total = 0;
for (let i = 0; i < n; i++) total += scans[i].distances.length;
const cells = new Float32Array(total * CELL_STRIDE_W);
let k = 0;
for (let i = 0; i < n; i++) {
const s1 = scans[i];
const s2 = scans[(i + 1) % n];
const dist1 = s1.distances;
const sp1 = s1.speeds;
const sp2 = s2.speeds;
const len = dist1.length;
const s1sx = s1.sinAz, s1cx = s1.cosAz;
const s2sx = s2.sinAz, s2cx = s2.cosAz;
for (let g = 0; g < len; g++) {
const r1 = dist1[g];
const r2 = g + 1 < len ? dist1[g + 1] : r1 + gateDist;
const cr1 = r1 * cosEl, cr2 = r2 * cosEl;
const z1 = r1 * sinEl, z2 = r2 * sinEl;
const o = k * CELL_STRIDE_W;
cells[o + 0] = cr1 * s1sx; cells[o + 1] = cr1 * s1cx; cells[o + 2] = z1;
cells[o + 3] = cr1 * s2sx; cells[o + 4] = cr1 * s2cx; cells[o + 5] = z1;
cells[o + 6] = cr2 * s2sx; cells[o + 7] = cr2 * s2cx; cells[o + 8] = z2;
cells[o + 9] = cr2 * s1sx; cells[o + 10] = cr2 * s1cx; cells[o + 11] = z2;
const v1 = sp1[g];
const v2 = sp2[g];
const v1ok = typeof v1 === "number" && v1 === v1 && v1 !== NO_DATA;
const v2ok = typeof v2 === "number" && v2 === v2 && v2 !== NO_DATA;
cells[o + 12] = v1ok && v2ok ? (v1 + v2) * 0.5
: v1ok ? v1 : v2ok ? v2 : NO_DATA;
cells[o + 13] = s1.az;
cells[o + 14] = layer.el;
cells[o + 15] = (r1 + r2) * 0.5;
k++;
}
}
layer.cells = cells;
layer.cellCount = total;
}
const parseCache = new WeakMap<object, ParsedData>();
function extractFrameData(frame: any): ParsedData | null {
if (!frame || typeof frame !== "object") return null;
const cached = parseCache.get(frame);
if (cached) return cached;
const scans: any[] = frame?.Scans || [];
if (scans.length === 0) return null;
const first = scans[0];
const mode = first?.Mode ?? "PPI";
const startDist = first?.StartDistance ?? 0;
const gateDist = first?.GateDistance ?? 100;
const time = frame?.Scan?.RTC
? formatTime(frame.Scan.RTC)
: first?.RTC
? formatTime(first.RTC)
: "";
const elMap = new Map<number, ParsedScan[]>();
let gMin = Infinity, gMax = -Infinity, maxLen = 0;
let elMin: number | null = null, elMax: number | null = null;
let azMin: number | null = null, azMax: number | null = null;
for (const scan of scans) {
const az = scan?.AzimuthCurrent;
if (typeof az !== "number" || isNaN(az)) continue;
const elRaw = scan?.ElevationCurrent;
const el = typeof elRaw === "number" && !isNaN(elRaw) ? elRaw : 0;
const speeds: number[] = scan?.SpeedRadial || [];
if (speeds.length > maxLen) maxLen = speeds.length;
const sd = scan?.StartDistance ?? startDist;
const gd = scan?.GateDistance ?? gateDist;
const elKey = Math.round(el * 10) / 10;
let list = elMap.get(elKey);
if (!list) elMap.set(elKey, (list = []));
const distances = new Array<number>(speeds.length);
const parsedSpeeds = new Array<number>(speeds.length);
for (let j = 0; j < speeds.length; j++) {
distances[j] = sd + j * gd;
const s = typeof speeds[j] === "number" && !isNaN(speeds[j]) ? speeds[j] : NaN;
parsedSpeeds[j] = s;
if (!isNaN(s) && s !== NO_DATA) {
if (s < gMin) gMin = s;
if (s > gMax) gMax = s;
}
}
const azNorm = ((az % 360) + 360) % 360;
const azRad = (azNorm * Math.PI) / 180;
list.push({
az: azNorm,
sinAz: Math.sin(azRad),
cosAz: Math.cos(azRad),
distances,
speeds: parsedSpeeds,
});
if (elMin === null || el < elMin) elMin = el;
if (elMax === null || el > elMax) elMax = el;
if (azMin === null || az < azMin) azMin = az;
if (azMax === null || az > azMax) azMax = az;
}
if (elMap.size === 0) return null;
const elKeys = Array.from(elMap.keys()).sort((a, b) => a - b);
const layers: ParsedLayer[] = elKeys.map((k) => {
const list = elMap.get(k)!;
list.sort((a, b) => a.az - b.az);
const layer: ParsedLayer = { el: k, scans: list, cellCount: 0, cells: new Float32Array(0) };
buildLayerCells(layer, gateDist);
return layer;
});
if (!isFinite(gMin)) gMin = -30;
if (!isFinite(gMax)) gMax = 30;
if (gMax - gMin < 1) { gMin -= 10; gMax += 10; }
let maxDistance = startDist + (maxLen - 1) * gateDist;
if (maxDistance < 1000) maxDistance = 1000;
let azStep = 0;
const l0 = layers[0];
if (l0 && l0.scans.length >= 2) {
let d = Math.abs(l0.scans[1].az - l0.scans[0].az);
if (d > 180) d = 360 - d;
if (d > 0) azStep = d;
}
let elStep = 0;
if (elKeys.length >= 2) {
const d = Math.abs(elKeys[1] - elKeys[0]);
if (d > 0) elStep = d;
}
const result: ParsedData = {
layers, time, maxDistance, gateDist, startDist,
speedMin: gMin, speedMax: gMax,
elMin, elMax, azMin, azMax,
azStep, elStep, mode, maxLen,
};
parseCache.set(frame, result);
return result;
}
/* ============================================================
* 5. 响应式状态
* ============================================================ */
const deviceInfo = inject<Ref<any[]>>("minuteData", ref([]));
const canvasRef = ref<HTMLCanvasElement | null>(null);
const gridOverlayRef = ref<HTMLCanvasElement | null>(null);
const legendCanvasRef = ref<HTMLCanvasElement | null>(null);
const frames = shallowRef<any[]>([]);
const currentFrameIndex = ref(-1);
const cam = reactive({ ...DEFAULT_CAM });
const isDragging = ref(false);
interface TooltipState {
visible: boolean; x: number; y: number;
distance: number; azimuth: number; elevation: number; speed: number;
}
const tooltip = reactive<TooltipState>({
visible: false, x: 0, y: 0,
distance: 0, azimuth: 0, elevation: 0, speed: 0,
});
const currentData = computed<ParsedData | null>(() => {
const idx = currentFrameIndex.value;
const fs = frames.value;
if (idx < 0 || idx >= fs.length) return null;
return extractFrameData(fs[idx]);
});
const infoRows = computed(() => {
const d = currentData.value;
const rows = d
? [
{ k: "模式", v: d.mode },
{ k: "俯仰角", v: formatRange(d.elMin, d.elMax) },
{ k: "方位角", v: formatRange(d.azMin, d.azMax) },
{ k: "俯仰步长", v: d.elStep > 0 ? `${d.elStep.toFixed(0)}°` : "--" },
{ k: "方位步长", v: d.azStep > 0 ? `${d.azStep.toFixed(0)}°` : "--" },
{ k: "时间", v: d.time || "--" },
]
: [
{ k: "模式", v: "--" }, { k: "俯仰角", v: "--" },
{ k: "方位角", v: "--" }, { k: "俯仰步长", v: "--" },
{ k: "方位步长", v: "--" }, { k: "时间", v: "--" },
];
return rows;
});
const legendMin = computed(() => COLOR_SPEED_MIN.toFixed(0));
const legendMax = computed(() => `+${COLOR_SPEED_MAX.toFixed(0)}`);
const leftTimeLabel = computed(() =>
frames.value.length ? getFullTimeLabel(frames.value[0]) : "--",
);
const rightTimeLabel = computed(() => {
const fs = frames.value;
return fs.length ? getFullTimeLabel(fs[fs.length - 1]) : "--";
});
const currentTimeLabel = computed(() => {
const idx = currentFrameIndex.value;
const fs = frames.value;
return idx < 0 || idx >= fs.length ? "--" : getFullTimeLabel(fs[idx]);
});
const timeMarks = computed<Record<number, string>>(() => {
const marks: Record<number, string> = {};
frames.value.forEach((frame, idx) => { marks[idx] = getTimeLabel(frame); });
return marks;
});
const isDefaultView = computed(() =>
cam.panX === 0 && cam.panY === 0 &&
Math.abs(cam.zoom - DEFAULT_CAM.zoom) < 1e-6 &&
Math.abs(cam.yaw - DEFAULT_CAM.yaw) < 1e-6 &&
Math.abs(cam.pitch - DEFAULT_CAM.pitch) < 1e-6,
);
/* ============================================================
* 6. 俯仰层筛选(多选,自适应 UI)
* ============================================================ */
/** 已选中的俯仰层;空数组 = 全部 */
const selectedElevations = ref<number[]>([]);
/** 弹出面板的开关与搜索词 */
const layerPanelOpen = ref(false);
const layerSearch = ref("");
const elevationOptions = computed<number[]>(() =>
currentData.value?.layers.map((l) => l.el) ?? [],
);
const isAllLayersSelected = computed(() => selectedElevations.value.length === 0);
function isLayerSelected(el: number): boolean {
return selectedElevations.value.includes(el);
}
/** 顶栏/触发器显示的文本 */
const currentLayerLabel = computed(() => {
const sel = selectedElevations.value;
if (sel.length === 0) return "全部";
if (sel.length === 1) return `${formatEl(sel[0])}°`;
return `${sel.length} 层`;
});
/** 面板标题右侧的摘要 */
const selectionSummary = computed(() => {
const sel = selectedElevations.value;
return sel.length === 0 ? "全部" : `${sel.length}/${elevationOptions.value.length}`;
});
const layerTriggerTitle = computed(() => {
const sel = selectedElevations.value;
return sel.length === 0
? "俯仰层:全部"
: `俯仰层:${sel.map(formatEl).join("°、")}°`;
});
/** 搜索过滤(用于大列表) */
const filteredElevationOptions = computed(() => {
const q = layerSearch.value.trim();
if (!q) return elevationOptions.value;
return elevationOptions.value.filter((el) => formatEl(el).includes(q));
});
// 数据刷新后剔除已不存在的层
watch(elevationOptions, (opts) => {
const cur = selectedElevations.value;
if (cur.length === 0) return;
const next = cur.filter((el) => opts.includes(el));
if (next.length !== cur.length) selectedElevations.value = next;
});
watch(
selectedElevations,
() => {
hideTooltip();
scheduleRender();
},
{ deep: true },
);
// 面板关闭时清理搜索词
watch(layerPanelOpen, (v) => {
if (!v) layerSearch.value = "";
});
/** 切换单层选中状态;清空后自动回到"全部" */
function toggleLayer(el: number) {
const cur = selectedElevations.value;
if (cur.includes(el)) {
selectedElevations.value = cur.filter((v) => v !== el);
} else {
selectedElevations.value = [...cur, el].sort((a, b) => a - b);
}
}
function selectAllLayers() {
selectedElevations.value = [];
}
/** 点击画布外关闭弹出面板 */
function onDocMousedown(e: MouseEvent) {
if (!layerPanelOpen.value) return;
const t = e.target as HTMLElement | null;
if (t && t.closest(".layer-switcher-popover")) return;
layerPanelOpen.value = false;
}
/* ============================================================
* 7. 投影
* ============================================================ */
interface Projection {
cosY: number; sinY: number; cosP: number; sinP: number;
dist: number; focal: number; cx: number; cy: number;
}
interface ScreenPoint { x: number; y: number; z: number; }
function buildProjection(W: number, H: number, maxDistance: number): Projection {
const cx = W / 2;
const cy = H * 0.52;
const radius = Math.max(40, Math.min(W * 0.4, H * 0.52));
return {
cosY: Math.cos(cam.yaw),
sinY: Math.sin(cam.yaw),
cosP: Math.cos(cam.pitch),
sinP: Math.sin(cam.pitch),
dist: 2.6 * maxDistance,
focal: radius * 2.6 * cam.zoom,
cx: cx + cam.panX,
cy: cy + cam.panY,
};
}
/** 投影并返回 { x, y, z };z<1 表示在相机后方。 */
function project(x: number, y: number, z: number, P: Projection): ScreenPoint | null {
const t = -x * P.sinY - y * P.cosY;
const zc = t * P.cosP - z * P.sinP + P.dist;
if (zc < 1) return null;
const s = P.focal / zc;
return {
x: P.cx + (-x * P.cosY + y * P.sinY) * s,
y: P.cy - (t * P.sinP + z * P.cosP) * s,
z: zc,
};
}
/** 直接写入 out[offset..offset+1],返回 zc(<1 表示失败)。 */
function projectInto(
x: number, y: number, z: number, P: Projection,
out: Float32Array, offset: number,
): number {
const t = -x * P.sinY - y * P.cosY;
const zc = t * P.cosP - z * P.sinP + P.dist;
if (zc < 1) return 0;
const s = P.focal / zc;
out[offset] = P.cx + (-x * P.cosY + y * P.sinY) * s;
out[offset + 1] = P.cy - (t * P.sinP + z * P.cosP) * s;
return zc;
}
/* ============================================================
* 8. Tooltip 拾取缓冲(从 layer.cells 按需构建)
* 每个单元 13 个浮点:p0(x,y) p1(x,y) p2(x,y) p3(x,y) depth speed az el r
* ============================================================ */
const CELL_STRIDE = 13;
let cellBuf = new Float32Array(4096 * CELL_STRIDE);
let cellCount = 0;
function ensureCellCapacity(n: number) {
if (cellBuf.length >= n * CELL_STRIDE) return;
const size = Math.max(n * CELL_STRIDE * 2, 4096 * CELL_STRIDE);
const next = new Float32Array(size);
next.set(cellBuf);
cellBuf = next;
}
const PICK_GRID = 64;
const pickBuckets: (number[] | null)[] = new Array(PICK_GRID * PICK_GRID).fill(null);
function buildPickBuffer() {
const canvas = canvasRef.value;
const data = currentData.value;
if (!canvas || !data) { cellCount = 0; pickDirty = false; return; }
const rect = canvas.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) { cellCount = 0; pickDirty = false; return; }
const W = rect.width, H = rect.height;
const P = buildProjection(W, H, data.maxDistance);
const sel = selectedElevations.value;
const layers = sel.length === 0
? data.layers
: data.layers.filter((l) => sel.includes(l.el));
let maxCells = 0;
for (const layer of layers) {
if (layer.el >= 89) continue;
maxCells += layer.cellCount;
}
if (maxCells === 0) { cellCount = 0; pickDirty = false; return; }
ensureCellCapacity(maxCells);
cellCount = 0;
const buf = cellBuf;
for (const layer of layers) {
if (layer.el >= 89) continue;
const cells = layer.cells;
const n = layer.cellCount;
if (n === 0) continue;
for (let i = 0; i < n; i++) {
const src = i * CELL_STRIDE_W;
const speed = cells[src + 12];
if (speed === NO_DATA || speed !== speed) continue;
const x0 = cells[src], y0 = cells[src + 1], z0 = cells[src + 2];
const x1 = cells[src + 3], y1 = cells[src + 4], z1 = cells[src + 5];
const x2 = cells[src + 6], y2 = cells[src + 7], z2 = cells[src + 8];
const x3 = cells[src + 9], y3 = cells[src + 10], z3 = cells[src + 11];
const off = cellCount * CELL_STRIDE;
const zz0 = projectInto(x0, y0, z0, P, buf, off);
if (!zz0) continue;
const zz1 = projectInto(x1, y1, z1, P, buf, off + 2);
if (!zz1) continue;
const zz2 = projectInto(x2, y2, z2, P, buf, off + 4);
if (!zz2) continue;
const zz3 = projectInto(x3, y3, z3, P, buf, off + 6);
if (!zz3) continue;
const p0x = buf[off], p0y = buf[off + 1];
const p1x = buf[off + 2], p1y = buf[off + 3];
const p2x = buf[off + 4], p2y = buf[off + 5];
const p3x = buf[off + 6], p3y = buf[off + 7];
if (Math.max(p0x, p1x, p2x, p3x) < 0) continue;
if (Math.min(p0x, p1x, p2x, p3x) > W) continue;
if (Math.max(p0y, p1y, p2y, p3y) < 0) continue;
if (Math.min(p0y, p1y, p2y, p3y) > H) continue;
buf[off + 8] = (zz0 + zz1 + zz2 + zz3) * 0.25;
buf[off + 9] = speed;
buf[off + 10] = cells[src + 13];
buf[off + 11] = cells[src + 14];
buf[off + 12] = cells[src + 15];
cellCount++;
}
}
buildPickGrid(W, H);
pickDirty = false;
}
function buildPickGrid(W: number, H: number) {
const buckets = pickBuckets;
for (let i = 0; i < buckets.length; i++) buckets[i] = null;
const cw = W / PICK_GRID;
const ch = H / PICK_GRID;
const buf = cellBuf;
for (let i = 0; i < cellCount; i++) {
const off = i * CELL_STRIDE;
let x0 = buf[off], x1 = x0;
let y0 = buf[off + 1], y1 = y0;
for (let p = 2; p <= 6; p += 2) {
const px = buf[off + p], py = buf[off + p + 1];
if (px < x0) x0 = px; else if (px > x1) x1 = px;
if (py < y0) y0 = py; else if (py > y1) y1 = py;
}
const gx0 = Math.max(0, Math.floor(x0 / cw));
const gx1 = Math.min(PICK_GRID - 1, Math.floor(x1 / cw));
const gy0 = Math.max(0, Math.floor(y0 / ch));
const gy1 = Math.min(PICK_GRID - 1, Math.floor(y1 / ch));
if (gx1 < gx0 || gy1 < gy0) continue;
for (let gy = gy0; gy <= gy1; gy++) {
const base = gy * PICK_GRID;
for (let gx = gx0; gx <= gx1; gx++) {
const key = base + gx;
let arr = buckets[key];
if (!arr) buckets[key] = arr = [];
arr.push(i);
}
}
}
}
/* ============================================================
* 9. WebGL2 初始化
* ============================================================ */
let gl: WebGL2RenderingContext | null = null;
let prog: WebGLProgram | null = null;
let colorTex: WebGLTexture | null = null;
let indexBuffer: WebGLBuffer | null = null;
let glReady = false;
const VS_SRC = `#version 300 es
precision highp float;
layout(location = 0) in vec3 a_p0;
layout(location = 1) in vec3 a_p1;
layout(location = 2) in vec3 a_p2;
layout(location = 3) in vec3 a_p3;
layout(location = 4) in float a_speed;
uniform float u_cosY, u_sinY, u_cosP, u_sinP;
uniform float u_dist, u_focal, u_cx, u_cy, u_maxDist;
uniform vec2 u_viewport;
out float v_speed;
out vec2 v_uv;
void main() {
int id = gl_VertexID;
vec3 p = id == 0 ? a_p0 : id == 1 ? a_p1 : id == 2 ? a_p2 : a_p3;
v_speed = a_speed;
int localId = id % 4;
if (localId == 0) v_uv = vec2(0.0, 0.0);
else if (localId == 1) v_uv = vec2(1.0, 0.0);
else if (localId == 2) v_uv = vec2(1.0, 1.0);
else v_uv = vec2(0.0, 1.0);
float t = -p.x * u_sinY - p.y * u_cosY;
float zc = t * u_cosP - p.z * u_sinP + u_dist;
if (zc < 1.0) {
gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
return;
}
float s = u_focal / zc;
float sx = u_cx + (-p.x * u_cosY + p.y * u_sinY) * s;
float sy = u_cy - (t * u_sinP + p.z * u_cosP) * s;
vec2 ndc = vec2(sx / u_viewport.x * 2.0 - 1.0,
1.0 - sy / u_viewport.y * 2.0);
float ndcZ = (zc - u_dist) / max(u_maxDist, 1.0);
gl_Position = vec4(ndc.x * zc, ndc.y * zc, ndcZ * zc, zc);
}`;
const FS_SRC = `#version 300 es
precision highp float;
in float v_speed;
in vec2 v_uv;
uniform sampler2D u_colormap;
uniform float u_speedMin, u_speedMax;
out vec4 fragColor;
void main() {
bool noData = (v_speed > 900.0 || v_speed != v_speed);
if (noData) {
discard;
}
float t = clamp((v_speed - u_speedMin) / max(u_speedMax - u_speedMin, 0.001), 0.0, 1.0);
vec3 rgb = texture(u_colormap, vec2(t, 0.5)).rgb;
rgb = pow(rgb, vec3(0.7));
fragColor = vec4(rgb, 1.0);
}`;
let u_cosY: WebGLUniformLocation | null = null;
let u_sinY: WebGLUniformLocation | null = null;
let u_cosP: WebGLUniformLocation | null = null;
let u_sinP: WebGLUniformLocation | null = null;
let u_dist: WebGLUniformLocation | null = null;
let u_focal: WebGLUniformLocation | null = null;
let u_cx: WebGLUniformLocation | null = null;
let u_cy: WebGLUniformLocation | null = null;
let u_viewport: WebGLUniformLocation | null = null;
let u_colormap: WebGLUniformLocation | null = null;
let u_speedMin: WebGLUniformLocation | null = null;
let u_speedMax: WebGLUniformLocation | null = null;
let u_maxDist: WebGLUniformLocation | null = null;
function compileShader(type: number, src: string): WebGLShader | null {
if (!gl) return null;
const sh = gl.createShader(type);
if (!sh) return null;
gl.shaderSource(sh, src);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
console.error("[radar] shader compile error:", gl.getShaderInfoLog(sh), src);
gl.deleteShader(sh);
return null;
}
return sh;
}
function buildColorMapTexture(): WebGLTexture | null {
if (!gl) return null;
const N = 256;
const data = new Uint8Array(N * 4);
const span = COLOR_SPEED_MAX - COLOR_SPEED_MIN || 1;
for (let i = 0; i < N; i++) {
const t = i / (N - 1);
const speed = COLOR_SPEED_MIN + t * span;
const [r, g, b] = sampleVelocityRGB(speed);
data[i * 4 + 0] = r;
data[i * 4 + 1] = g;
data[i * 4 + 2] = b;
data[i * 4 + 3] = 255;
}
const tex = gl.createTexture();
if (!tex) return null;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, N, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return tex;
}
function initGL(): boolean {
const canvas = canvasRef.value;
if (!canvas) return false;
gl = canvas.getContext("webgl2", {
alpha: true,
premultipliedAlpha: false,
antialias: true,
depth: true,
}) as WebGL2RenderingContext | null;
if (!gl) {
console.warn("[radar] WebGL2 不可用");
return false;
}
const vs = compileShader(gl.VERTEX_SHADER, VS_SRC);
const fs = compileShader(gl.FRAGMENT_SHADER, FS_SRC);
if (!vs || !fs) return false;
prog = gl.createProgram();
if (!prog) return false;
gl.attachShader(prog, vs);
gl.attachShader(prog, fs);
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
console.error("[radar] link error:", gl.getProgramInfoLog(prog));
return false;
}
gl.deleteShader(vs);
gl.deleteShader(fs);
u_cosY = gl.getUniformLocation(prog, "u_cosY");
u_sinY = gl.getUniformLocation(prog, "u_sinY");
u_cosP = gl.getUniformLocation(prog, "u_cosP");
u_sinP = gl.getUniformLocation(prog, "u_sinP");
u_dist = gl.getUniformLocation(prog, "u_dist");
u_focal = gl.getUniformLocation(prog, "u_focal");
u_cx = gl.getUniformLocation(prog, "u_cx");
u_cy = gl.getUniformLocation(prog, "u_cy");
u_viewport = gl.getUniformLocation(prog, "u_viewport");
u_colormap = gl.getUniformLocation(prog, "u_colormap");
u_speedMin = gl.getUniformLocation(prog, "u_speedMin");
u_speedMax = gl.getUniformLocation(prog, "u_speedMax");
u_maxDist = gl.getUniformLocation(prog, "u_maxDist");
colorTex = buildColorMapTexture();
indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 0, 2, 3]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.enableVertexAttribArray(1);
gl.enableVertexAttribArray(2);
gl.enableVertexAttribArray(3);
gl.enableVertexAttribArray(4);
gl.vertexAttribDivisor(0, 1);
gl.vertexAttribDivisor(1, 1);
gl.vertexAttribDivisor(2, 1);
gl.vertexAttribDivisor(3, 1);
gl.vertexAttribDivisor(4, 1);
gl.disable(gl.CULL_FACE);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LESS);
gl.depthMask(false);
gl.clearDepth(1.0);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
glReady = true;
return true;
}
/* ---------- VBO 缓存(按 layer 缓存一次上传) ---------- */
const STRIDE_BYTES = CELL_STRIDE_W * 4; // 64
const layerVBO = new WeakMap<ParsedLayer, WebGLBuffer>();
function getLayerVBO(layer: ParsedLayer): WebGLBuffer | null {
if (!gl || layer.cellCount === 0) return null;
let vbo = layerVBO.get(layer);
if (vbo) return vbo;
vbo = gl.createBuffer() ?? undefined;
if (!vbo) return null;
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, layer.cells, gl.STATIC_DRAW);
layerVBO.set(layer, vbo);
return vbo;
}
/* ============================================================
* 9. 渲染管线
* ============================================================ */
let rafId: number | null = null;
let pickDirty = true;
function scheduleRender() {
if (rafId !== null) return;
rafId = requestAnimationFrame(() => {
rafId = null;
render();
});
}
function sizeGLCanvas(cv: HTMLCanvasElement) {
const dpr = window.devicePixelRatio || 1;
const rect = cv.parentElement?.getBoundingClientRect();
const W = rect?.width || 600;
const H = rect?.height || 600;
const pw = Math.round(W * dpr);
const ph = Math.round(H * dpr);
if (cv.width !== pw || cv.height !== ph) {
cv.width = pw;
cv.height = ph;
}
return { W, H, dpr };
}
function render() {
const canvas = canvasRef.value;
if (!canvas || !gl || !glReady) return;
const data = currentData.value;
if (!data) {
drawEmpty();
return;
}
const { W, H } = sizeGLCanvas(canvas);
const P = buildProjection(W, H, data.maxDistance);
drawWebGLVolume(canvas, W, H, P, data);
drawGridOverlay(W, H, P, data);
drawLegend();
pickDirty = true;
}
function drawEmpty() {
const canvas = canvasRef.value;
if (!canvas || !gl) return;
const { W, H, dpr } = sizeGLCanvas(canvas);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const overlay = gridOverlayRef.value;
if (overlay) {
const pw = Math.round(W * dpr), ph = Math.round(H * dpr);
if (overlay.width !== pw || overlay.height !== ph) {
overlay.width = pw;
overlay.height = ph;
}
const octx = overlay.getContext("2d")!;
octx.setTransform(dpr, 0, 0, dpr, 0, 0);
octx.clearRect(0, 0, W, H);
octx.fillStyle = "rgba(255,255,255,0.3)";
octx.font = "16px sans-serif";
octx.textAlign = "center";
octx.textBaseline = "middle";
octx.fillText("无数据", W / 2, H / 2);
}
cellCount = 0;
drawLegend();
pickDirty = true;
}
function drawWebGLVolume(
canvas: HTMLCanvasElement,
W: number,
H: number,
P: Projection,
data: ParsedData,
) {
if (!gl || !prog) return;
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LESS);
gl.depthMask(false);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.useProgram(prog);
gl.uniform1f(u_cosY, P.cosY);
gl.uniform1f(u_sinY, P.sinY);
gl.uniform1f(u_cosP, P.cosP);
gl.uniform1f(u_sinP, P.sinP);
gl.uniform1f(u_dist, P.dist);
gl.uniform1f(u_focal, P.focal);
gl.uniform1f(u_cx, P.cx);
gl.uniform1f(u_cy, P.cy);
gl.uniform2f(u_viewport, W, H);
gl.uniform1f(u_speedMin, COLOR_SPEED_MIN);
gl.uniform1f(u_speedMax, COLOR_SPEED_MAX);
gl.uniform1f(u_maxDist, data.maxDistance);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, colorTex);
gl.uniform1i(u_colormap, 0);
if (indexBuffer) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
}
const sel = selectedElevations.value;
const layers = sel.length === 0
? data.layers
: data.layers.filter((l) => sel.includes(l.el));
for (const layer of layers) {
if (layer.el >= 89) continue;
if (layer.cellCount === 0) continue;
const vbo = getLayerVBO(layer);
if (!vbo) continue;
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, STRIDE_BYTES, 0);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, STRIDE_BYTES, 12);
gl.vertexAttribPointer(2, 3, gl.FLOAT, false, STRIDE_BYTES, 24);
gl.vertexAttribPointer(3, 3, gl.FLOAT, false, STRIDE_BYTES, 36);
gl.vertexAttribPointer(4, 1, gl.FLOAT, false, STRIDE_BYTES, 48);
gl.drawElementsInstanced(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0, layer.cellCount);
}
}
/* ---------- 网格叠加(离屏缓存 + 平移偏移) ---------- */
let gridCanvas: HTMLCanvasElement | null = null;
let gridKey = "";
function drawGridOverlay(W: number, H: number, P: Projection, data: ParsedData) {
const overlay = gridOverlayRef.value;
if (!overlay) return;
const dpr = window.devicePixelRatio || 1;
const pw = Math.round(W * dpr);
const ph = Math.round(H * dpr);
if (overlay.width !== pw || overlay.height !== ph) {
overlay.width = pw;
overlay.height = ph;
}
const octx = overlay.getContext("2d")!;
octx.setTransform(dpr, 0, 0, dpr, 0, 0);
octx.clearRect(0, 0, W, H);
const key =
`${W}|${H}|${dpr}|` +
`${P.cosY.toFixed(5)}|${P.sinY.toFixed(5)}|` +
`${P.cosP.toFixed(5)}|${P.sinP.toFixed(5)}|` +
`${P.focal.toFixed(2)}|${data.maxDistance}`;
if (key !== gridKey || !gridCanvas) {
if (!gridCanvas) gridCanvas = document.createElement("canvas");
const c = gridCanvas;
c.width = pw;
c.height = ph;
const ctx = c.getContext("2d")!;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, W, H);
const Pg: Projection = { ...P, cx: W / 2, cy: H * 0.52 };
drawGroundGrid(ctx, Pg, data);
drawLabels(ctx, Pg, data);
gridKey = key;
}
if (cam.panX !== 0 || cam.panY !== 0) {
octx.drawImage(gridCanvas, cam.panX, cam.panY, W, H);
} else {
octx.drawImage(gridCanvas, 0, 0, W, H);
}
}
function drawGroundGrid(ctx: CanvasRenderingContext2D, P: Projection, data: ParsedData) {
const maxD = data.maxDistance;
const step = Math.max(500, Math.ceil(maxD / 6 / 500) * 500);
ctx.lineWidth = 1;
ctx.strokeStyle = "rgba(110, 160, 220, 0.22)";
for (let r = step; r <= maxD + 1; r += step) {
ctx.beginPath();
let started = false;
for (let a = 0; a <= 360; a += 6) {
const rad = (a * Math.PI) / 180;
const p = project(r * Math.sin(rad), r * Math.cos(rad), 0, P);
if (!p) { started = false; continue; }
if (!started) { ctx.moveTo(p.x, p.y); started = true; }
else ctx.lineTo(p.x, p.y);
}
ctx.stroke();
}
ctx.strokeStyle = "rgba(110, 160, 220, 0.16)";
const center = project(0, 0, 0, P);
if (center) {
for (let a = 0; a < 360; a += 30) {
const rad = (a * Math.PI) / 180;
const p = project(maxD * Math.sin(rad), maxD * Math.cos(rad), 0, P);
if (!p) continue;
ctx.beginPath();
ctx.moveTo(center.x, center.y);
ctx.lineTo(p.x, p.y);
ctx.stroke();
}
}
ctx.strokeStyle = "rgba(110, 160, 220, 0.35)";
const pz0 = project(0, 0, 0, P);
const pz1 = project(0, 0, maxD * 0.75, P);
if (pz0 && pz1) {
ctx.beginPath();
ctx.moveTo(pz0.x, pz0.y);
ctx.lineTo(pz1.x, pz1.y);
ctx.stroke();
}
ctx.strokeStyle = "rgba(140, 190, 255, 0.4)";
ctx.lineWidth = 1.4;
ctx.beginPath();
let st = false;
for (let a = 0; a <= 360; a += 4) {
const rad = (a * Math.PI) / 180;
const p = project(maxD * Math.sin(rad), maxD * Math.cos(rad), 0, P);
if (!p) { st = false; continue; }
if (!st) { ctx.moveTo(p.x, p.y); st = true; }
else ctx.lineTo(p.x, p.y);
}
ctx.closePath();
ctx.stroke();
}
function drawLabels(ctx: CanvasRenderingContext2D, P: Projection, data: ParsedData) {
const maxD = data.maxDistance;
ctx.font = "11px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const rOut = maxD * 1.09;
const dirName: Record<number, string> = { 0: "N", 90: "E", 180: "S", 270: "W" };
for (let a = 0; a < 360; a += 30) {
const rad = (a * Math.PI) / 180;
const p = project(rOut * Math.sin(rad), rOut * Math.cos(rad), 0, P);
if (!p) continue;
ctx.fillStyle = dirName[a]
? "rgba(160, 220, 255, 0.9)"
: "rgba(150, 180, 215, 0.6)";
ctx.fillText(dirName[a] || `${a}°`, p.x, p.y);
}
const step = Math.max(500, Math.ceil(maxD / 6 / 500) * 500);
ctx.textAlign = "left";
ctx.font = "10px sans-serif";
ctx.fillStyle = "rgba(150, 190, 235, 0.65)";
for (let r = step; r <= maxD + 1; r += step) {
const p = project(r, 0, 0, P);
if (p) ctx.fillText(`${r}m`, p.x + 5, p.y - 2);
}
ctx.textAlign = "right";
ctx.fillStyle = "rgba(150, 190, 235, 0.55)";
for (let e = 0; e <= 90; e += 30) {
const z = maxD * 0.75 * Math.sin((e * Math.PI) / 180);
const p = project(0, 0, z, P);
if (p) ctx.fillText(`${e}°`, p.x - 6, p.y);
}
const o = project(0, 0, 0, P);
if (o) {
ctx.beginPath();
ctx.arc(o.x, o.y, 2.5, 0, Math.PI * 2);
ctx.fillStyle = "rgba(160, 220, 255, 0.9)";
ctx.fill();
}
}
/* ---------- 图例 ---------- */
function drawLegend() {
const c = legendCanvasRef.value;
if (!c) return;
const ctx = c.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const rect = c.parentElement?.getBoundingClientRect();
const width = Math.round(rect?.width || 200);
const height = 20;
const pw = Math.round(width * dpr);
const ph = Math.round(height * dpr);
if (c.width !== pw || c.height !== ph) {
c.width = pw;
c.height = ph;
c.style.width = width + "px";
c.style.height = height + "px";
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const grad = ctx.createLinearGradient(0, 0, width, 0);
const span = COLOR_SPEED_MAX - COLOR_SPEED_MIN || 1;
for (const s of VELOCITY_COLOR_STOPS) {
let pos = (s.speed - COLOR_SPEED_MIN) / span;
if (pos < 0) pos = 0;
else if (pos > 1) pos = 1;
grad.addColorStop(pos, `rgb(${s.rgb[0]},${s.rgb[1]},${s.rgb[2]})`);
}
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = "rgba(255,255,255,0.3)";
ctx.lineWidth = 1;
ctx.strokeRect(0.5, 0.5, width - 1, height - 1);
}
/* ============================================================
* 10. 交互
* ============================================================ */
let isRotating = false;
let isPanning = false;
let lastMX = 0;
let lastMY = 0;
function onMouseDown(e: MouseEvent) {
if (e.button === 0) {
// 左键:平移视图
isPanning = true;
isDragging.value = true;
lastMX = e.clientX; lastMY = e.clientY;
hideTooltip();
} else if (e.button === 1) {
// 中键:旋转视图(阻止浏览器默认自动滚动)
e.preventDefault();
isRotating = true;
isDragging.value = true;
lastMX = e.clientX; lastMY = e.clientY;
hideTooltip();
} else if (e.button === 2) {
// 右键:平移视图
e.preventDefault();
isPanning = true;
isDragging.value = true;
lastMX = e.clientX; lastMY = e.clientY;
hideTooltip();
}
}
function onMouseMove(e: MouseEvent) {
const dx = e.clientX - lastMX;
const dy = e.clientY - lastMY;
if (isRotating) {
cam.yaw -= dx * 0.008;
cam.pitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX, cam.pitch - dy * 0.006));
lastMX = e.clientX; lastMY = e.clientY;
scheduleRender();
return;
}
if (isPanning) {
cam.panX += dx;
cam.panY += dy;
lastMX = e.clientX; lastMY = e.clientY;
scheduleRender();
return;
}
updateTooltip(e);
}
function onMouseUp() {
isRotating = false;
isPanning = false;
isDragging.value = false;
}
function onMouseLeave() {
isRotating = false;
isPanning = false;
isDragging.value = false;
hideTooltip();
}
function onWheel(e: WheelEvent) {
const canvas = canvasRef.value;
const factor = e.deltaY > 0 ? 0.9 : 1.1;
const nz = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, cam.zoom * factor));
if (nz === cam.zoom) return;
if (canvas) {
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const cx0 = rect.width / 2 + cam.panX;
const cy0 = rect.height * 0.52 + cam.panY;
const k = nz / cam.zoom;
// 保持鼠标下的世界点不动:cx' = mx - k*(mx - cx)
cam.panX = mx - (mx - cx0) * k - rect.width / 2;
cam.panY = my - (my - cy0) * k - rect.height * 0.52;
}
cam.zoom = nz;
scheduleRender();
}
function zoomIn() {
const nz = Math.min(cam.zoom + ZOOM_STEP, ZOOM_MAX);
if (nz !== cam.zoom) { cam.zoom = nz; scheduleRender(); }
}
function zoomOut() {
const nz = Math.max(cam.zoom - ZOOM_STEP, ZOOM_MIN);
if (nz !== cam.zoom) { cam.zoom = nz; scheduleRender(); }
}
function resetView() {
Object.assign(cam, DEFAULT_CAM);
scheduleRender();
}
/* ---------- Tooltip ---------- */
let tooltipRaf: number | null = null;
let pendingMouse: MouseEvent | null = null;
function updateTooltip(e: MouseEvent) {
pendingMouse = e;
if (tooltipRaf !== null) return;
tooltipRaf = requestAnimationFrame(() => {
tooltipRaf = null;
const m = pendingMouse;
pendingMouse = null;
if (m) doTooltip(m);
});
}
function doTooltip(m: MouseEvent) {
const canvas = canvasRef.value;
if (!canvas) return;
if (pickDirty) buildPickBuffer();
if (cellCount === 0) { hideTooltip(); return; }
const rect = canvas.getBoundingClientRect();
const mx = m.clientX - rect.left;
const my = m.clientY - rect.top;
if (mx < 0 || my < 0 || mx > rect.width || my > rect.height) {
hideTooltip();
return;
}
const cw = rect.width / PICK_GRID;
const ch = rect.height / PICK_GRID;
const gx = Math.min(PICK_GRID - 1, Math.max(0, Math.floor(mx / cw)));
const gy = Math.min(PICK_GRID - 1, Math.max(0, Math.floor(my / ch)));
const candidates = pickBuckets[gy * PICK_GRID + gx];
if (!candidates || candidates.length === 0) { hideTooltip(); return; }
let bestIdx = -1;
let bestDepth = Infinity;
const buf = cellBuf;
for (let ci = 0; ci < candidates.length; ci++) {
const i = candidates[ci];
const off = i * CELL_STRIDE;
if (!pointInQuad(mx, my, buf, off)) continue;
const d = buf[off + 8];
if (d < bestDepth) { bestDepth = d; bestIdx = i; }
}
if (bestIdx < 0) { hideTooltip(); return; }
const off = bestIdx * CELL_STRIDE;
const wrapperRect = canvas.parentElement?.getBoundingClientRect();
if (!wrapperRect) return;
const wx = m.clientX - wrapperRect.left;
const wy = m.clientY - wrapperRect.top;
let tx = wx + 14;
let ty = wy + 14;
if (tx + 160 > wrapperRect.width) tx = wx - 160;
if (ty + 120 > wrapperRect.height) ty = wy - 120;
if (tx < 0) tx = 4;
if (ty < 0) ty = 4;
tooltip.visible = true;
tooltip.x = tx;
tooltip.y = ty;
tooltip.distance = Math.round(buf[off + 12]);
tooltip.azimuth = Math.round(buf[off + 10]);
tooltip.elevation = Math.round(buf[off + 11]);
tooltip.speed = buf[off + 9];
}
function hideTooltip() {
if (tooltip.visible) tooltip.visible = false;
}
function pointInQuad(
px: number, py: number, buf: Float32Array, off: number,
): boolean {
const p0x = buf[off], p0y = buf[off + 1];
const p1x = buf[off + 2], p1y = buf[off + 3];
const p2x = buf[off + 4], p2y = buf[off + 5];
const p3x = buf[off + 6], p3y = buf[off + 7];
const c1 = (p1x - p0x) * (py - p0y) - (p1y - p0y) * (px - p0x);
const c2 = (p2x - p1x) * (py - p1y) - (p2y - p1y) * (px - p1x);
const c3 = (p3x - p2x) * (py - p2y) - (p3y - p2y) * (px - p2x);
const c4 = (p0x - p3x) * (py - p3y) - (p0y - p3y) * (px - p3x);
const hasNeg = c1 < 0 || c2 < 0 || c3 < 0 || c4 < 0;
const hasPos = c1 > 0 || c2 > 0 || c3 > 0 || c4 > 0;
return !(hasNeg && hasPos);
}
/* ============================================================
* 11. 帧数据流
* ============================================================ */
function dedupeAndSortFrames(input: any[]): any[] {
const seen = new Set<string>();
const out: any[] = [];
for (const f of input) {
const rtc = f?.Scan?.RTC;
if (!rtc || seen.has(rtc)) continue;
seen.add(rtc);
out.push(f);
}
out.sort((a, b) =>
(a?.Scan?.RTC || "").localeCompare(b?.Scan?.RTC || ""),
);
if (out.length > MAX_FRAMES) out.splice(0, out.length - MAX_FRAMES);
return out;
}
function pickIndexAfterUpdate(
next: any[],
prevRTC: string | null,
wasLatest: boolean,
): number {
if (next.length === 0) return -1;
if (wasLatest || prevRTC === null) return next.length - 1;
const idx = next.findIndex((f) => f?.Scan?.RTC === prevRTC);
return idx !== -1 ? idx : 0;
}
function applyFrames(input: any[]) {
const valid = (input || []).filter((f) => f?.Scans?.length > 0);
if (valid.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
const unique = dedupeAndSortFrames(valid);
const newRTCs = unique.map((f) => f?.Scan?.RTC).filter(Boolean) as string[];
const oldRTCs = frames.value.map((f) => f?.Scan?.RTC).filter(Boolean) as string[];
if (
newRTCs.length === oldRTCs.length &&
newRTCs.every((r, i) => r === oldRTCs[i])
) {
return;
}
const idx = currentFrameIndex.value;
const prevFrame = idx >= 0 && idx < frames.value.length ? frames.value[idx] : null;
const prevRTC = prevFrame?.Scan?.RTC || null;
const wasLatest = idx === frames.value.length - 1 && idx >= 0;
frames.value = unique;
currentFrameIndex.value = pickIndexAfterUpdate(unique, prevRTC, wasLatest);
scheduleRender();
}
watch(
() => deviceInfo.value,
(val) => {
if (!Array.isArray(val) || val.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
applyFrames(val);
},
{ deep: true, immediate: true },
);
function onSliderChange() {
hideTooltip();
scheduleRender();
}
/** 左右按钮逐帧切换 */
function stepFrame(delta: number) {
const fs = frames.value;
if (fs.length === 0) return;
const next = Math.min(
Math.max(currentFrameIndex.value + delta, 0),
fs.length - 1,
);
if (next === currentFrameIndex.value) return;
currentFrameIndex.value = next;
hideTooltip();
scheduleRender();
}
function pushFrame(frame: any) {
if (!frame?.Scans?.length) return;
const rtc = frame?.Scan?.RTC;
if (!rtc) return;
const fs = frames.value;
if (fs.some((f) => f?.Scan?.RTC === rtc)) return;
const idx = currentFrameIndex.value;
const wasLatest = idx >= fs.length - 1;
const prevRTC = idx >= 0 && idx < fs.length ? fs[idx].Scan.RTC : null;
const next = dedupeAndSortFrames(fs.concat(frame));
frames.value = next;
currentFrameIndex.value = pickIndexAfterUpdate(next, prevRTC, wasLatest);
scheduleRender();
}
/* ============================================================
* 12. 生命周期
* ============================================================ */
let resizeObserver: ResizeObserver | null = null;
function onContextLost(e: Event) {
e.preventDefault();
glReady = false;
}
function onContextRestored() {
if (initGL()) scheduleRender();
}
onMounted(() => {
nextTick(() => {
const canvas = canvasRef.value;
if (canvas) {
canvas.addEventListener("webglcontextlost", onContextLost, false);
canvas.addEventListener("webglcontextrestored", onContextRestored, false);
}
if (initGL() === false) {
console.warn("[radar] WebGL 初始化失败");
}
if (canvas?.parentElement && typeof ResizeObserver !== "undefined") {
resizeObserver = new ResizeObserver(() => scheduleRender());
resizeObserver.observe(canvas.parentElement);
}
scheduleRender();
});
document.addEventListener("mousedown", onDocMousedown, true);
});
onBeforeUnmount(() => {
if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
if (tooltipRaf !== null) { cancelAnimationFrame(tooltipRaf); tooltipRaf = null; }
resizeObserver?.disconnect();
resizeObserver = null;
document.removeEventListener("mousedown", onDocMousedown, true);
const canvas = canvasRef.value;
if (canvas) {
canvas.removeEventListener("webglcontextlost", onContextLost, false);
canvas.removeEventListener("webglcontextrestored", onContextRestored, false);
}
if (gl) {
if (colorTex) gl.deleteTexture(colorTex);
if (prog) gl.deleteProgram(prog);
if (indexBuffer) gl.deleteBuffer(indexBuffer);
}
glReady = false;
});
defineExpose({
resetView,
zoomIn,
zoomOut,
pushFrame,
get frames() { return frames.value; },
});
</script>
<style scoped lang="less">
.radar-ppi-container {
position: relative;
width: 100%;
height: 100%;
border-right: 1px solid #243049;
padding: 0 10px;
box-sizing: border-box;
display: flex;
flex-direction: column;
background: #0a0e1a;
.radar-canvas-wrapper {
flex: 1;
min-height: 0;
position: relative;
background: radial-gradient(circle at 50% 52%, #0e1424 0%, #070a12 100%);
.radar-canvas {
display: block;
width: 100%;
height: 100%;
position: absolute;
inset: 0;
cursor: grab;
user-select: none;
&.dragging { cursor: grabbing; }
}
.radar-grid-overlay {
display: block;
width: 100%;
height: 100%;
position: absolute;
inset: 0;
pointer-events: none;
}
.realtime-vol-panel {
position: absolute;
top: 8px;
left: 8px;
width: 300px;
height: 260px;
z-index: 5;
overflow: hidden;
}
.radar-info-panel {
position: absolute;
top: 274px;
left: 8px;
font-size: 14px;
color: rgba(255, 255, 255, 0.85);
line-height: 1.6;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
.highlight {
color: var(--el-color-primary);
font-weight: bold;
}
}
.radar-legend {
position: absolute;
right: 16px;
bottom: 16px;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
.legend-canvas {
display: block;
width: 200px;
height: 20px;
border-radius: 2px;
margin-bottom: 2px;
}
.legend-labels {
display: flex;
justify-content: space-between;
font-size: 11px;
color: rgba(255, 255, 255, 0.7);
}
}
.radar-tooltip {
position: absolute;
background: rgba(0, 0, 0, 0.85);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
padding: 8px 12px;
font-size: 12px;
color: #fff;
line-height: 1.6;
pointer-events: none;
white-space: nowrap;
z-index: 10;
}
.view-controls {
position: absolute;
top: 24px;
right: 16px;
display: flex;
align-items: center;
gap: 6px;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
padding: 4px 6px;
user-select: none;
.view-btn {
width: 28px;
height: 28px;
background: transparent;
border: none;
color: #fff;
font-size: 18px;
font-weight: bold;
cursor: pointer;
border-radius: 2px;
transition: background 0.15s;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.1);
color: #7fd4ff;
}
&:disabled {
color: rgba(255, 255, 255, 0.25);
cursor: not-allowed;
}
:deep(.el-icon) { font-size: 15px; }
}
.zoom-level {
min-width: 44px;
text-align: center;
font-size: 13px;
color: rgba(255, 255, 255, 0.85);
font-variant-numeric: tabular-nums;
}
.zoom-divider {
width: 1px;
height: 16px;
background: rgba(255, 255, 255, 0.2);
}
}
/* ============ 少量层:按钮列表 ============ */
.layer-switcher {
position: absolute;
right: 16px;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-direction: column;
width: 62px;
max-height: 78%;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
overflow: hidden;
z-index: 5;
user-select: none;
.layer-list {
display: flex;
flex-direction: column;
gap: 4px;
padding: 6px;
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
&::-webkit-scrollbar { width: 3px; }
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 2px;
&:hover { background: rgba(255, 255, 255, 0.35); }
}
&::-webkit-scrollbar-track { background: transparent; }
}
.layer-btn {
flex-shrink: 0;
height: 28px;
padding: 0 6px;
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.7);
font-size: 12px;
border-radius: 2px;
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease;
font-variant-numeric: tabular-nums;
text-align: center;
white-space: nowrap;
line-height: 1;
outline: none;
&:hover {
background: rgba(255, 255, 255, 0.1);
color: #fff;
}
&.active {
background: var(--el-color-primary);
color: #fff;
}
}
}
/* ============ 大量层:弹出面板 ============ */
.layer-switcher-popover {
position: absolute;
right: 16px;
top: 50%;
transform: translateY(-50%);
z-index: 6;
user-select: none;
.layer-trigger {
width: 62px;
height: 32px;
padding: 0 6px;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
color: rgba(255, 255, 255, 0.85);
font-size: 12px;
cursor: pointer;
transition: all 0.15s;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-variant-numeric: tabular-nums;
&:hover {
border-color: rgba(127, 212, 255, 0.6);
color: #7fd4ff;
}
&.active {
border-color: var(--el-color-primary);
color: var(--el-color-primary);
}
}
.layer-panel {
position: absolute;
right: calc(100% + 8px);
top: 50%;
transform: translateY(-50%);
width: 190px;
max-height: 340px;
background: rgba(10, 14, 26, 0.96);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 6px;
padding: 8px;
display: flex;
flex-direction: column;
gap: 6px;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.6);
box-sizing: border-box;
}
.layer-panel-head {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
.layer-panel-title { font-weight: 500; }
.layer-panel-count {
color: var(--el-color-primary);
font-variant-numeric: tabular-nums;
margin-left: 4px;
}
.mini-btn {
background: transparent;
border: none;
color: var(--el-color-primary);
font-size: 11px;
cursor: pointer;
padding: 2px 6px;
border-radius: 2px;
transition: background 0.15s;
&:hover:not(:disabled) { background: rgba(127, 212, 255, 0.12); }
&:disabled {
color: rgba(255, 255, 255, 0.3);
cursor: not-allowed;
}
}
}
.layer-search {
width: 100%;
height: 24px;
padding: 0 6px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 3px;
color: #fff;
font-size: 12px;
outline: none;
box-sizing: border-box;
transition: border-color 0.15s;
&::placeholder { color: rgba(255, 255, 255, 0.35); }
&:focus { border-color: var(--el-color-primary); }
}
.layer-panel-list {
flex: 1;
min-height: 0;
overflow-y: auto;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 2px 6px;
padding-right: 2px;
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
&::-webkit-scrollbar { width: 4px; }
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 2px;
&:hover { background: rgba(255, 255, 255, 0.35); }
}
&::-webkit-scrollbar-track { background: transparent; }
}
.layer-check-item {
display: flex;
align-items: center;
gap: 4px;
padding: 3px 4px;
font-size: 12px;
color: rgba(255, 255, 255, 0.75);
cursor: pointer;
border-radius: 2px;
font-variant-numeric: tabular-nums;
transition: background 0.1s, color 0.1s;
input[type="checkbox"] {
margin: 0;
cursor: pointer;
accent-color: var(--el-color-primary);
flex-shrink: 0;
width: 13px;
height: 13px;
}
&:hover {
background: rgba(255, 255, 255, 0.07);
color: #fff;
}
&.checked {
color: var(--el-color-primary);
}
}
.layer-empty {
grid-column: 1 / -1;
text-align: center;
padding: 14px 0;
font-size: 12px;
color: rgba(255, 255, 255, 0.4);
}
}
.timeline-container {
position: absolute;
bottom: 8px;
left: 50%;
transform: translateX(-50%);
width: 70%;
max-width: 700px;
box-sizing: border-box;
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
padding: 4px 12px 20px 12px;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 4px;
.timeline-header {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
font-size: 11px;
color: rgba(255, 255, 255, 0.8);
.timeline-label-left {
justify-self: start;
}
.timeline-label-right {
justify-self: end;
}
.timeline-current-group {
display: flex;
align-items: center;
gap: 8px;
.timeline-current {
min-width: 64px;
text-align: center;
color: var(--el-color-primary);
font-weight: bold;
font-size: 13px;
}
}
}
.time-nav-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 50%;
background: rgba(255, 255, 255, 0.06);
color: rgba(255, 255, 255, 0.8);
font-size: 14px;
cursor: pointer;
transition:
background-color 0.15s,
border-color 0.15s,
color 0.15s;
&:hover:not(:disabled) {
background: rgba(64, 158, 255, 0.3);
border-color: var(--el-color-primary);
color: #fff;
}
&:disabled {
opacity: 0.3;
cursor: not-allowed;
}
}
.timeline-slider {
width: 100%;
margin: 0;
:deep(.el-slider__runway) { background-color: rgba(255, 255, 255, 0.18); }
:deep(.el-slider__bar) { background-color: var(--el-color-primary); }
:deep(.el-slider__marks-text) {
color: rgba(255, 255, 255, 0.7);
font-size: 9px;
white-space: nowrap;
}
}
}
}
}
:deep(.el-slider__button) {
height: 15px;
width: 15px;
&:hover { height: 15px; width: 15px; }
}
</style>
六、SVOL 与 VOL 的关键差异
两者代码结构几乎一样,差异就在拼接方式。
VOL 是整圈扫描,首尾相连:
ts
const s2 = scans[(i + 1) % n]; // 最后一条接回第一条
SVOL 是扇区扫描,不闭合,只拼 n - 1 段:
ts
for (let i = 0; i < n - 1; i++) {
const s1 = scans[i];
const s2 = scans[i + 1];
}
如果扇区数据强行用 % n 闭合,会在扇区缺口处拉出一条横跨全图的错误面片。这是实际开发中最容易踩的坑之一。
另外 SVOL 对高度做了纵向拉伸:
ts
const Z_SCALE = 2;
const z1 = r1 * sinEl * Z_SCALE;
因为雷达俯仰角通常很小,真实高度差在屏幕上几乎看不出来,拉伸后立体感才明显。
SVOLChart.vue 完整源码
vue
<template>
<div class="radar-ppi-container">
<div class="radar-canvas-wrapper">
<canvas
ref="canvasRef"
class="radar-canvas"
:class="{ dragging: isDragging }"
@mousedown="onMouseDown"
@mousemove="onCanvasMouseMove"
@mouseleave="onCanvasMouseLeave"
@wheel.prevent="onWheel"
@dblclick="resetView"
@contextmenu.prevent
></canvas>
<canvas ref="gridOverlayRef" class="radar-grid-overlay"></canvas>
<!-- 实时体扫雷达(左上角) -->
<div class="realtime-svol-panel">
<RealTimeSVOLChart />
</div>
<!-- 信息面板(左上角) -->
<div class="radar-info-panel">
<div>模式:{{ info.mode }}</div>
<div>俯仰角:{{ info.elevationRange }}</div>
<div>方位角:{{ info.azimuthRange }}</div>
<div>俯仰步长:{{ info.elStep }}</div>
<div>方位步长:{{ info.azStep }}</div>
<div>时间:{{ info.time }}</div>
</div>
<!-- 图例(右下角) -->
<div class="radar-legend">
<canvas ref="legendCanvasRef" class="legend-canvas"></canvas>
<div class="legend-labels">
<span>{{ legendMin }} m/s</span>
<span>{{ legendMax }} m/s</span>
</div>
</div>
<!-- 缩放控件(右上角) -->
<div class="zoom-controls">
<button
class="zoom-btn"
@click="zoomOut"
:disabled="cam.zoom <= ZOOM_MIN"
title="缩小"
>
−
</button>
<span class="zoom-level">{{ cam.zoom.toFixed(1) }}</span>
<button
class="zoom-btn"
@click="zoomIn"
:disabled="cam.zoom >= ZOOM_MAX"
title="放大"
>
+
</button>
<span class="zoom-divider"></span>
<button
class="zoom-btn reset-btn"
@click="resetView"
:disabled="isDefaultView"
title="回到原点"
>
<el-icon><Aim /></el-icon>
</button>
</div>
<!-- ================= 俯仰层选择 ================= -->
<template v-if="elevationOptions.length > 1">
<!-- 少量层:按钮列表 -->
<div
v-if="elevationOptions.length <= LAYER_BUTTON_THRESHOLD"
class="layer-switcher"
>
<div class="layer-list">
<button
class="layer-btn all-btn"
:class="{ active: isAllLayersSelected }"
@click="selectAllLayers"
title="显示全部层"
>
全部
</button>
<button
v-for="el in elevationOptions"
:key="el"
class="layer-btn"
:class="{ active: isLayerSelected(el) }"
@click="toggleLayer(el)"
:title="`切换 ${formatEl(el)}° 俯仰层显示(可多选)`"
>
{{ formatEl(el) }}°
</button>
</div>
</div>
<!-- 大量层:弹出面板 -->
<div v-else class="layer-switcher-popover">
<button
class="layer-trigger"
:class="{ active: !isAllLayersSelected }"
@click.stop="layerPanelOpen = !layerPanelOpen"
:title="layerTriggerTitle"
>
{{ currentLayerLabel }}
</button>
<div v-if="layerPanelOpen" class="layer-panel" @click.stop>
<div class="layer-panel-head">
<span class="layer-panel-title">
俯仰层
<span class="layer-panel-count">{{ selectionSummary }}</span>
</span>
<button
class="mini-btn"
:disabled="isAllLayersSelected"
@click="selectAllLayers"
>
全部
</button>
</div>
<input
v-if="elevationOptions.length > 12"
v-model="layerSearch"
class="layer-search"
type="text"
placeholder="搜索角度"
@keydown.esc="layerSearch = ''"
/>
<div class="layer-panel-list">
<label
v-for="el in filteredElevationOptions"
:key="el"
class="layer-check-item"
:class="{ checked: isLayerSelected(el) }"
>
<input
type="checkbox"
:checked="isLayerSelected(el)"
@change="toggleLayer(el)"
/>
<span>{{ formatEl(el) }}°</span>
</label>
<div
v-if="filteredElevationOptions.length === 0"
class="layer-empty"
>
无匹配角度
</div>
</div>
</div>
</div>
</template>
<!-- ================= /俯仰层选择 ================= -->
<!-- 时间轴 -->
<div v-if="frames.length > 0" class="timeline-container">
<div class="timeline-header">
<span class="timeline-label-left">{{ leftTimeLabel }}</span>
<div class="timeline-current-group">
<button
class="time-nav-btn"
:disabled="currentFrameIndex <= 0"
title="上一帧"
@click="stepFrame(-1)"
>
<el-icon><ArrowLeft /></el-icon>
</button>
<span class="timeline-current">{{ currentTimeLabel }}</span>
<button
class="time-nav-btn"
:disabled="currentFrameIndex >= frames.length - 1"
title="下一帧"
@click="stepFrame(1)"
>
<el-icon><ArrowRight /></el-icon>
</button>
</div>
<span class="timeline-label-right">{{ rightTimeLabel }}</span>
</div>
<el-slider
v-model="currentFrameIndex"
:min="0"
:max="Math.max(0, frames.length - 1)"
:marks="timeMarks"
@change="onSliderChange"
size="small"
:show-tooltip="false"
class="timeline-slider"
/>
</div>
<!-- Tooltip -->
<div
v-if="tooltip.visible"
class="radar-tooltip"
:style="{ left: tooltip.x + 'px', top: tooltip.y + 'px' }"
>
<div>距离:{{ tooltip.distance }} m</div>
<div>方位角:{{ tooltip.azimuth }}°</div>
<div>俯仰角:{{ tooltip.elevation }}°</div>
<div>速度:{{ tooltip.speed.toFixed(1) }} m/s</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import {
ref,
shallowRef,
reactive,
computed,
watch,
onMounted,
onBeforeUnmount,
nextTick,
inject,
type Ref,
} from "vue";
import { Aim, ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import RealTimeSVOLChart from "./RealTimeSVOLChart.vue";
/* ============================================================
* 1. 常量 / 相机
* ============================================================ */
const MAX_FRAMES = 11;
const NO_DATA = 999;
/** 垂直方向夸张系数:低俯仰层(如 0°/10°/20°)高度差很小,放大后更易辨认立体形态 */
const Z_SCALE = 2;
const ZOOM_STEP = 0.25;
const ZOOM_MIN = 0.5;
const ZOOM_MAX = 20;
const PITCH_MIN = 0.05;
const PITCH_MAX = 1.52;
const DEFAULT_CAM = { yaw: Math.PI, pitch: 0.55, zoom: 0.7, panX: 0, panY: 0 };
/* ============================================================
* 2. 速度色标(-50 ~ +50 m/s 连续渐变)
* ============================================================ */
interface ColorStop {
speed: number;
rgb: [number, number, number];
}
const VELOCITY_COLOR_STOPS: ColorStop[] = [
{ speed: -50, rgb: [59, 15, 111] }, // 深紫
{ speed: -40, rgb: [0, 0, 255] }, // 蓝 极强朝向
{ speed: -30, rgb: [0, 128, 255] }, // 天蓝 强朝向
{ speed: -20, rgb: [0, 224, 255] }, // 青 较强朝向
{ speed: -10, rgb: [0, 255, 128] }, // 青绿 中等朝向
{ speed: 0, rgb: [160, 160, 160] }, // 灰 零速
{ speed: 10, rgb: [255, 240, 0] }, // 黄 中等远离
{ speed: 20, rgb: [255, 160, 0] }, // 橙 较强远离
{ speed: 30, rgb: [255, 60, 0] }, // 橙红 强远离
{ speed: 40, rgb: [220, 0, 0] }, // 红 极强远离
{ speed: 50, rgb: [139, 0, 0] }, // 紫红 极端远离
];
const COLOR_SPEED_MIN = VELOCITY_COLOR_STOPS[0].speed;
const COLOR_SPEED_MAX =
VELOCITY_COLOR_STOPS[VELOCITY_COLOR_STOPS.length - 1].speed;
/** 采样速度颜色(用于颜色表纹理) */
function sampleVelocityRGB(speed: number): [number, number, number] {
const stops = VELOCITY_COLOR_STOPS;
if (speed <= stops[0].speed)
return [...stops[0].rgb] as [number, number, number];
if (speed >= stops[stops.length - 1].speed)
return [...stops[stops.length - 1].rgb] as [number, number, number];
for (let i = 0; i < stops.length - 1; i++) {
const a = stops[i];
const b = stops[i + 1];
if (speed >= a.speed && speed <= b.speed) {
const t = (speed - a.speed) / (b.speed - a.speed);
return [
Math.round(a.rgb[0] + t * (b.rgb[0] - a.rgb[0])),
Math.round(a.rgb[1] + t * (b.rgb[1] - a.rgb[1])),
Math.round(a.rgb[2] + t * (b.rgb[2] - a.rgb[2])),
];
}
}
return [160, 160, 160];
}
/* ============================================================
* 3. 工具函数
* ============================================================ */
function formatTime(rtc: string): string {
try {
const dt = new Date(rtc);
if (!isNaN(dt.getTime()))
return dt.toLocaleString("zh-CN", { hour12: false });
} catch {}
return rtc || "";
}
function getTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (rtc) {
const dt = new Date(rtc);
if (!isNaN(dt.getTime()))
return dt.toLocaleTimeString("zh-CN", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
});
}
return "--";
}
/** 顶部时间标签:时:分:秒 */
function getFullTimeLabel(frame: any): string {
const rtc = frame?.Scan?.RTC;
if (rtc) {
const dt = new Date(rtc);
if (!isNaN(dt.getTime()))
return dt.toLocaleTimeString("zh-CN", { hour12: false });
}
return "--";
}
function formatRange(min: number | null, max: number | null): string {
if (min === null || max === null) return "--";
if (Math.abs(max - min) < 0.001) return min.toFixed(0) + "°";
return min.toFixed(0) + "°~" + max.toFixed(0) + "°";
}
const clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);
function formatEl(el: number): string {
return Number.isInteger(el) ? el.toFixed(0) : el.toFixed(1);
}
/* ============================================================
* 4. 帧解析(按俯仰分层,数据格式与 2D PPI 组件一致)
* ============================================================ */
interface ParsedScan {
az: number;
sinAz: number;
cosAz: number;
distances: number[];
speeds: number[];
}
interface ParsedLayer {
el: number;
scans: ParsedScan[];
cellCount: number;
cells: Float32Array;
}
interface ParsedData {
layers: ParsedLayer[];
time: string;
maxDistance: number;
gateDist: number;
startDist: number;
speedMin: number;
speedMax: number;
elMin: number | null;
elMax: number | null;
azMin: number | null;
azMax: number | null;
azStep: number;
elStep: number;
mode: string;
}
/** 每 cell 16 float:[0..2]p0 [3..5]p1 [6..8]p2 [9..11]p3 [12]speed [13]az [14]el [15]r */
const CELL_STRIDE_W = 16;
/** 按 SVOL 原有拼接方式(相邻扫描,n-1 段)生成 WebGL 顶点数据 */
function buildLayerCells(layer: ParsedLayer, gateDist: number) {
const scans = layer.scans;
const n = scans.length;
if (n < 2) {
layer.cells = new Float32Array(0);
layer.cellCount = 0;
return;
}
const elRad = (layer.el * Math.PI) / 180;
const sinEl = Math.sin(elRad);
const cosEl = Math.cos(elRad);
let total = 0;
for (let i = 0; i < n - 1; i++) total += scans[i].distances.length;
const cells = new Float32Array(total * CELL_STRIDE_W);
let k = 0;
for (let i = 0; i < n - 1; i++) {
const s1 = scans[i];
const s2 = scans[i + 1];
const dist1 = s1.distances;
const sp1 = s1.speeds;
const sp2 = s2.speeds;
const len = dist1.length;
const s1sx = s1.sinAz,
s1cx = s1.cosAz;
const s2sx = s2.sinAz,
s2cx = s2.cosAz;
for (let g = 0; g < len; g++) {
const r1 = dist1[g];
const r2 = g + 1 < len ? dist1[g + 1] : r1 + gateDist;
const cr1 = r1 * cosEl,
cr2 = r2 * cosEl;
const z1 = r1 * sinEl * Z_SCALE,
z2 = r2 * sinEl * Z_SCALE;
const o = k * CELL_STRIDE_W;
cells[o + 0] = cr1 * s1sx;
cells[o + 1] = cr1 * s1cx;
cells[o + 2] = z1;
cells[o + 3] = cr1 * s2sx;
cells[o + 4] = cr1 * s2cx;
cells[o + 5] = z1;
cells[o + 6] = cr2 * s2sx;
cells[o + 7] = cr2 * s2cx;
cells[o + 8] = z2;
cells[o + 9] = cr2 * s1sx;
cells[o + 10] = cr2 * s1cx;
cells[o + 11] = z2;
const v1 = sp1[g];
const v2 = sp2 ? sp2[g] : undefined;
const v1ok = typeof v1 === "number" && v1 === v1 && v1 !== NO_DATA;
const v2ok = typeof v2 === "number" && v2 === v2 && v2 !== NO_DATA;
cells[o + 12] =
v1ok && v2ok ? (v1 + v2) * 0.5 : v1ok ? v1 : v2ok ? v2 : NO_DATA;
cells[o + 13] = s1.az;
cells[o + 14] = layer.el;
cells[o + 15] = (r1 + r2) * 0.5;
k++;
}
}
layer.cells = cells;
layer.cellCount = total;
}
const parsedCache = new Map<string, ParsedData>();
function extractFrameData(frame: any): ParsedData | null {
const rtc = frame?.Scan?.RTC;
if (rtc && parsedCache.has(rtc)) {
return parsedCache.get(rtc)!;
}
const scans: any[] = frame?.Scans || [];
if (scans.length === 0) return null;
const firstScan = scans[0];
const mode = firstScan?.Mode ?? "PPI";
const startDist = firstScan?.StartDistance ?? 0;
const gateDist = firstScan?.GateDistance ?? 100;
const time = rtc
? formatTime(rtc)
: firstScan?.RTC
? formatTime(firstScan.RTC)
: "";
const elMap = new Map<number, ParsedScan[]>();
let globalMin = Infinity;
let globalMax = -Infinity;
let maxLen = 0;
let elMin: number | null = null;
let elMax: number | null = null;
let azMin: number | null = null;
let azMax: number | null = null;
for (const scan of scans) {
const az = scan?.AzimuthCurrent;
if (typeof az !== "number" || isNaN(az)) continue;
// 俯仰角缺失时按 0 处理,兼容纯 PPI 数据
const elRaw = scan?.ElevationCurrent;
const el = typeof elRaw === "number" && !isNaN(elRaw) ? elRaw : 0;
const speeds: number[] = scan?.SpeedRadial || [];
if (speeds.length > maxLen) maxLen = speeds.length;
const scanStartDist = scan?.StartDistance ?? startDist;
const scanGateDist = scan?.GateDistance ?? gateDist;
const elKey = Math.round(el * 10) / 10;
let list = elMap.get(elKey);
if (!list) {
list = [];
elMap.set(elKey, list);
}
const distances = new Array<number>(speeds.length);
const allSpeeds = new Array<number>(speeds.length);
for (let j = 0; j < speeds.length; j++) {
distances[j] = scanStartDist + j * scanGateDist;
const s =
typeof speeds[j] === "number" && !isNaN(speeds[j]) ? speeds[j] : NaN;
allSpeeds[j] = s;
if (!isNaN(s) && s !== 999) {
if (s < globalMin) globalMin = s;
if (s > globalMax) globalMax = s;
}
}
const azNorm = ((az % 360) + 360) % 360;
const azRad = (azNorm * Math.PI) / 180;
list.push({
az: azNorm,
sinAz: Math.sin(azRad),
cosAz: Math.cos(azRad),
distances,
speeds: allSpeeds,
});
if (elMin === null || el < elMin) elMin = el;
if (elMax === null || el > elMax) elMax = el;
if (azMin === null || az < azMin) azMin = az;
if (azMax === null || az > azMax) azMax = az;
}
if (elMap.size === 0) return null;
const elKeys = Array.from(elMap.keys()).sort((a, b) => a - b);
const layers: ParsedLayer[] = [];
for (const k of elKeys) {
const list = elMap.get(k)!;
list.sort((a, b) => a.az - b.az);
const layer: ParsedLayer = {
el: k,
scans: list,
cellCount: 0,
cells: new Float32Array(0),
};
buildLayerCells(layer, gateDist);
layers.push(layer);
}
if (!isFinite(globalMin)) globalMin = -30;
if (!isFinite(globalMax)) globalMax = 30;
if (globalMax - globalMin < 1) {
globalMin -= 10;
globalMax += 10;
}
let maxDistance = startDist + (maxLen - 1) * gateDist;
if (maxDistance < 1000) maxDistance = 1000;
// 方位步长:取首层前两个扫描的角差
let azStep = 0;
const layer0 = layers[0];
if (layer0 && layer0.scans.length >= 2) {
let d = Math.abs(layer0.scans[1].az - layer0.scans[0].az);
if (d > 180) d = 360 - d;
if (d > 0) azStep = d;
}
// 俯仰步长:取相邻两层的角差
let elStep = 0;
if (elKeys.length >= 2) {
const d = Math.abs(elKeys[1] - elKeys[0]);
if (d > 0) elStep = d;
}
const result: ParsedData = {
layers,
time,
maxDistance,
gateDist,
startDist,
speedMin: globalMin,
speedMax: globalMax,
elMin,
elMax,
azMin,
azMax,
azStep,
elStep,
mode,
};
if (rtc) parsedCache.set(rtc, result);
return result;
}
/* ============================================================
* 5. 响应式状态
* ============================================================ */
const deviceInfo = inject<Ref<any[]>>("minuteData", ref([]));
const canvasRef = ref<HTMLCanvasElement | null>(null);
const gridOverlayRef = ref<HTMLCanvasElement | null>(null);
const legendCanvasRef = ref<HTMLCanvasElement | null>(null);
const frames = shallowRef<any[]>([]);
const currentFrameIndex = ref(-1);
const cam = reactive({ ...DEFAULT_CAM });
const isDragging = ref(false);
interface TooltipState {
visible: boolean;
x: number;
y: number;
distance: number;
azimuth: number;
elevation: number;
speed: number;
}
const tooltip = reactive<TooltipState>({
visible: false,
x: 0,
y: 0,
distance: 0,
azimuth: 0,
elevation: 0,
speed: 0,
});
const currentData = computed<ParsedData | null>(() => {
const fs = frames.value;
const idx = currentFrameIndex.value;
if (idx < 0 || idx >= fs.length) return null;
return extractFrameData(fs[idx]);
});
const info = computed(() => {
const d = currentData.value;
if (!d) {
return {
mode: "--",
elevationRange: "--",
azimuthRange: "--",
elStep: "--",
azStep: "--",
time: "--",
};
}
return {
mode: d.mode,
elevationRange: formatRange(d.elMin, d.elMax),
azimuthRange: formatRange(d.azMin, d.azMax),
elStep: d.elStep > 0 ? d.elStep.toFixed(0) + "°" : "--",
azStep: d.azStep > 0 ? d.azStep.toFixed(0) + "°" : "--",
time: d.time || "--",
};
});
const legendMin = computed(() => COLOR_SPEED_MIN.toFixed(0));
const legendMax = computed(() => "+" + COLOR_SPEED_MAX.toFixed(0));
const leftTimeLabel = computed(() =>
frames.value.length ? getFullTimeLabel(frames.value[0]) : "--",
);
const rightTimeLabel = computed(() =>
frames.value.length
? getFullTimeLabel(frames.value[frames.value.length - 1])
: "--",
);
const currentTimeLabel = computed(() => {
const fs = frames.value;
const idx = currentFrameIndex.value;
if (idx < 0 || idx >= fs.length) return "--";
return getFullTimeLabel(fs[idx]);
});
const timeMarks = computed<Record<number, string>>(() => {
const marks: Record<number, string> = {};
frames.value.forEach((frame, idx) => {
marks[idx] = getTimeLabel(frame);
});
return marks;
});
const isDefaultView = computed(
() =>
cam.panX === 0 &&
cam.panY === 0 &&
Math.abs(cam.zoom - DEFAULT_CAM.zoom) < 1e-6 &&
Math.abs(cam.yaw - DEFAULT_CAM.yaw) < 1e-6 &&
Math.abs(cam.pitch - DEFAULT_CAM.pitch) < 1e-6,
);
/* ============================================================
* 5.1 俯仰层切换(多选,自适应 UI)
* ============================================================ */
/** 层数 ≤ 该值用按钮列表,超过则用弹出面板 */
const LAYER_BUTTON_THRESHOLD = 10;
/** 已选中的俯仰层;空数组 = 全部 */
const selectedElevations = ref<number[]>([]);
/** 弹出面板的开关与搜索词 */
const layerPanelOpen = ref(false);
const layerSearch = ref("");
/** 当前帧所有可用的俯仰层(已排序) */
const elevationOptions = computed<number[]>(() => {
const d = currentData.value;
if (!d) return [];
return d.layers.map((l) => l.el);
});
const isAllLayersSelected = computed(() => selectedElevations.value.length === 0);
function isLayerSelected(el: number): boolean {
return selectedElevations.value.includes(el);
}
/** 触发器显示文本 */
const currentLayerLabel = computed(() => {
const sel = selectedElevations.value;
if (sel.length === 0) return "全部";
if (sel.length === 1) return formatEl(sel[0]) + "°";
return sel.length + " 层";
});
/** 面板标题右侧的摘要 */
const selectionSummary = computed(() => {
const sel = selectedElevations.value;
return sel.length === 0
? "全部"
: `${sel.length}/${elevationOptions.value.length}`;
});
const layerTriggerTitle = computed(() => {
const sel = selectedElevations.value;
return sel.length === 0
? "俯仰层:全部"
: `俯仰层:${sel.map(formatEl).join("°、")}°`;
});
/** 搜索过滤(用于大列表) */
const filteredElevationOptions = computed(() => {
const q = layerSearch.value.trim();
if (!q) return elevationOptions.value;
return elevationOptions.value.filter((el) => formatEl(el).includes(q));
});
/** 切换帧后剔除已不存在的层 */
watch(elevationOptions, (opts) => {
const cur = selectedElevations.value;
if (cur.length === 0) return;
const next = cur.filter((el) => opts.includes(el));
if (next.length !== cur.length) selectedElevations.value = next;
});
/** 选中变化后重新渲染 */
watch(
selectedElevations,
() => {
hideTooltip();
scheduleRender();
},
{ deep: true },
);
/** 面板关闭时清理搜索词 */
watch(layerPanelOpen, (v) => {
if (!v) layerSearch.value = "";
});
/** 切换单层选中状态;清空后自动回到「全部」 */
function toggleLayer(el: number) {
const cur = selectedElevations.value;
if (cur.includes(el)) {
selectedElevations.value = cur.filter((v) => v !== el);
} else {
selectedElevations.value = [...cur, el].sort((a, b) => a - b);
}
}
function selectAllLayers() {
selectedElevations.value = [];
}
/** 点击画布外关闭弹出面板 */
function onDocMousedown(e: MouseEvent) {
if (!layerPanelOpen.value) return;
const t = e.target as HTMLElement | null;
if (t && t.closest(".layer-switcher-popover")) return;
layerPanelOpen.value = false;
}
/* ============================================================
* 6. 投影
* ============================================================ */
interface Projection {
cosY: number;
sinY: number;
cosP: number;
sinP: number;
dist: number;
focal: number;
cx: number;
cy: number;
}
interface ProjectedPoint {
x: number;
y: number;
z: number;
}
function getViewGeometry(W: number, H: number) {
return {
cx: W / 2,
cy: H * 0.55,
radius: Math.max(50, Math.min(W * 0.4, H * 0.52)),
};
}
function buildProjection(
W: number,
H: number,
maxDistance: number,
): Projection {
const g = getViewGeometry(W, H);
const dist = 2.6 * maxDistance;
return {
cosY: Math.cos(cam.yaw),
sinY: Math.sin(cam.yaw),
cosP: Math.cos(cam.pitch),
sinP: Math.sin(cam.pitch),
dist,
focal: g.radius * 2.6 * cam.zoom,
cx: g.cx + cam.panX,
cy: g.cy + cam.panY,
};
}
function project(
x: number,
y: number,
z: number,
P: Projection,
): ProjectedPoint | null {
const t = -x * P.sinY - y * P.cosY;
const zc = t * P.cosP - z * P.sinP + P.dist;
if (zc < 1) return null;
const s = P.focal / zc;
return {
x: P.cx + (-x * P.cosY + y * P.sinY) * s,
y: P.cy - (t * P.sinP + z * P.cosP) * s,
z: zc,
};
}
/** 投影两个顶点到 out 缓冲区,返回 zc(<1 表示失败) */
function projectInto(
x: number,
y: number,
z: number,
P: Projection,
out: Float32Array,
offset: number,
): number {
const t = -x * P.sinY - y * P.cosY;
const zc = t * P.cosP - z * P.sinP + P.dist;
if (zc < 1) return 0;
const s = P.focal / zc;
out[offset] = P.cx + (-x * P.cosY + y * P.sinY) * s;
out[offset + 1] = P.cy - (t * P.sinP + z * P.cosP) * s;
return zc;
}
/* ============================================================
* 7. WebGL2 初始化
* ============================================================ */
let gl: WebGL2RenderingContext | null = null;
let prog: WebGLProgram | null = null;
let colorTex: WebGLTexture | null = null;
let indexBuffer: WebGLBuffer | null = null;
let glReady = false;
const VS_SRC = `#version 300 es
precision highp float;
layout(location = 0) in vec3 a_p0;
layout(location = 1) in vec3 a_p1;
layout(location = 2) in vec3 a_p2;
layout(location = 3) in vec3 a_p3;
layout(location = 4) in float a_speed;
uniform float u_cosY, u_sinY, u_cosP, u_sinP;
uniform float u_dist, u_focal, u_cx, u_cy, u_maxDist;
uniform vec2 u_viewport;
out float v_speed;
out vec2 v_uv;
void main() {
int id = gl_VertexID;
vec3 p = id == 0 ? a_p0 : id == 1 ? a_p1 : id == 2 ? a_p2 : a_p3;
v_speed = a_speed;
int localId = id % 4;
if (localId == 0) v_uv = vec2(0.0, 0.0);
else if (localId == 1) v_uv = vec2(1.0, 0.0);
else if (localId == 2) v_uv = vec2(1.0, 1.0);
else v_uv = vec2(0.0, 1.0);
float t = -p.x * u_sinY - p.y * u_cosY;
float zc = t * u_cosP - p.z * u_sinP + u_dist;
if (zc < 1.0) {
gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
return;
}
float s = u_focal / zc;
float sx = u_cx + (-p.x * u_cosY + p.y * u_sinY) * s;
float sy = u_cy - (t * u_sinP + p.z * u_cosP) * s;
vec2 ndc = vec2(sx / u_viewport.x * 2.0 - 1.0,
1.0 - sy / u_viewport.y * 2.0);
float ndcZ = (zc - u_dist) / max(u_maxDist, 1.0);
gl_Position = vec4(ndc.x * zc, ndc.y * zc, ndcZ * zc, zc);
}`;
const FS_SRC = `#version 300 es
precision highp float;
in float v_speed;
in vec2 v_uv;
uniform sampler2D u_colormap;
uniform float u_speedMin, u_speedMax;
out vec4 fragColor;
void main() {
bool noData = (v_speed > 900.0 || v_speed != v_speed);
if (noData) {
discard;
}
float t = clamp((v_speed - u_speedMin) / max(u_speedMax - u_speedMin, 0.001), 0.0, 1.0);
vec3 rgb = texture(u_colormap, vec2(t, 0.5)).rgb;
rgb = pow(rgb, vec3(0.7));
fragColor = vec4(rgb, 1.0);
}`;
let u_cosY: WebGLUniformLocation | null = null;
let u_sinY: WebGLUniformLocation | null = null;
let u_cosP: WebGLUniformLocation | null = null;
let u_sinP: WebGLUniformLocation | null = null;
let u_dist: WebGLUniformLocation | null = null;
let u_focal: WebGLUniformLocation | null = null;
let u_cx: WebGLUniformLocation | null = null;
let u_cy: WebGLUniformLocation | null = null;
let u_viewport: WebGLUniformLocation | null = null;
let u_colormap: WebGLUniformLocation | null = null;
let u_speedMin: WebGLUniformLocation | null = null;
let u_speedMax: WebGLUniformLocation | null = null;
let u_maxDist: WebGLUniformLocation | null = null;
function compileShader(type: number, src: string): WebGLShader | null {
if (!gl) return null;
const sh = gl.createShader(type);
if (!sh) return null;
gl.shaderSource(sh, src);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
console.error(
"[radar] shader compile error:",
gl.getShaderInfoLog(sh),
src,
);
gl.deleteShader(sh);
return null;
}
return sh;
}
function buildColorMapTexture(): WebGLTexture | null {
if (!gl) return null;
const N = 256;
const data = new Uint8Array(N * 4);
const span = COLOR_SPEED_MAX - COLOR_SPEED_MIN || 1;
for (let i = 0; i < N; i++) {
const t = i / (N - 1);
const speed = COLOR_SPEED_MIN + t * span;
const [r, g, b] = sampleVelocityRGB(speed);
data[i * 4 + 0] = r;
data[i * 4 + 1] = g;
data[i * 4 + 2] = b;
data[i * 4 + 3] = 255;
}
const tex = gl.createTexture();
if (!tex) return null;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
N,
1,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
data,
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return tex;
}
function initGL(): boolean {
const canvas = canvasRef.value;
if (!canvas) return false;
gl = canvas.getContext("webgl2", {
alpha: true,
premultipliedAlpha: false,
antialias: true,
depth: true,
}) as WebGL2RenderingContext | null;
if (!gl) {
console.warn("[radar] WebGL2 不可用");
return false;
}
const vs = compileShader(gl.VERTEX_SHADER, VS_SRC);
const fs = compileShader(gl.FRAGMENT_SHADER, FS_SRC);
if (!vs || !fs) return false;
prog = gl.createProgram();
if (!prog) return false;
gl.attachShader(prog, vs);
gl.attachShader(prog, fs);
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
console.error("[radar] link error:", gl.getProgramInfoLog(prog));
return false;
}
gl.deleteShader(vs);
gl.deleteShader(fs);
u_cosY = gl.getUniformLocation(prog, "u_cosY");
u_sinY = gl.getUniformLocation(prog, "u_sinY");
u_cosP = gl.getUniformLocation(prog, "u_cosP");
u_sinP = gl.getUniformLocation(prog, "u_sinP");
u_dist = gl.getUniformLocation(prog, "u_dist");
u_focal = gl.getUniformLocation(prog, "u_focal");
u_cx = gl.getUniformLocation(prog, "u_cx");
u_cy = gl.getUniformLocation(prog, "u_cy");
u_viewport = gl.getUniformLocation(prog, "u_viewport");
u_colormap = gl.getUniformLocation(prog, "u_colormap");
u_speedMin = gl.getUniformLocation(prog, "u_speedMin");
u_speedMax = gl.getUniformLocation(prog, "u_speedMax");
u_maxDist = gl.getUniformLocation(prog, "u_maxDist");
colorTex = buildColorMapTexture();
indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array([0, 1, 2, 0, 2, 3]),
gl.STATIC_DRAW,
);
gl.enableVertexAttribArray(0);
gl.enableVertexAttribArray(1);
gl.enableVertexAttribArray(2);
gl.enableVertexAttribArray(3);
gl.enableVertexAttribArray(4);
gl.vertexAttribDivisor(0, 1);
gl.vertexAttribDivisor(1, 1);
gl.vertexAttribDivisor(2, 1);
gl.vertexAttribDivisor(3, 1);
gl.vertexAttribDivisor(4, 1);
gl.disable(gl.CULL_FACE);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LESS);
gl.depthMask(false);
gl.clearDepth(1.0);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
glReady = true;
return true;
}
/* ---------- VBO 缓存(按 layer 缓存一次上传) ---------- */
const STRIDE_BYTES = CELL_STRIDE_W * 4; // 64
const layerVBO = new WeakMap<ParsedLayer, WebGLBuffer>();
function getLayerVBO(layer: ParsedLayer): WebGLBuffer | null {
if (!gl || layer.cellCount === 0) return null;
let vbo = layerVBO.get(layer);
if (vbo) return vbo;
vbo = gl.createBuffer() ?? undefined;
if (!vbo) return null;
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, layer.cells, gl.STATIC_DRAW);
layerVBO.set(layer, vbo);
return vbo;
}
/* ============================================================
* 8. Tooltip 拾取缓冲(从 layer.cells 按需构建)
* 每个单元 13 个浮点:p0(x,y) p1(x,y) p2(x,y) p3(x,y) depth speed az el r
* ============================================================ */
const CELL_STRIDE = 13;
let cellBuf = new Float32Array(4096 * CELL_STRIDE);
let cellCount = 0;
let pickDirty = true;
function ensureCellCapacity(n: number) {
if (cellBuf.length >= n * CELL_STRIDE) return;
const size = Math.max(n * CELL_STRIDE * 2, 4096 * CELL_STRIDE);
const next = new Float32Array(size);
next.set(cellBuf);
cellBuf = next;
}
const PICK_GRID = 64;
const pickBuckets: (number[] | null)[] = new Array(
PICK_GRID * PICK_GRID,
).fill(null);
function buildPickBuffer() {
const canvas = canvasRef.value;
const data = currentData.value;
if (!canvas || !data) {
cellCount = 0;
pickDirty = false;
return;
}
const rect = canvas.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) {
cellCount = 0;
pickDirty = false;
return;
}
const W = rect.width,
H = rect.height;
const P = buildProjection(W, H, data.maxDistance);
const sel = selectedElevations.value;
const layers =
sel.length === 0
? data.layers
: data.layers.filter((l) => sel.includes(l.el));
let maxCells = 0;
for (const layer of layers) {
if (layer.el >= 89) continue;
maxCells += layer.cellCount;
}
if (maxCells === 0) {
cellCount = 0;
pickDirty = false;
return;
}
ensureCellCapacity(maxCells);
cellCount = 0;
const buf = cellBuf;
for (const layer of layers) {
if (layer.el >= 89) continue;
const cells = layer.cells;
const n = layer.cellCount;
if (n === 0) continue;
for (let i = 0; i < n; i++) {
const src = i * CELL_STRIDE_W;
const speed = cells[src + 12];
if (speed === NO_DATA || speed !== speed) continue;
const x0 = cells[src],
y0 = cells[src + 1],
z0 = cells[src + 2];
const x1 = cells[src + 3],
y1 = cells[src + 4],
z1 = cells[src + 5];
const x2 = cells[src + 6],
y2 = cells[src + 7],
z2 = cells[src + 8];
const x3 = cells[src + 9],
y3 = cells[src + 10],
z3 = cells[src + 11];
const off = cellCount * CELL_STRIDE;
const zz0 = projectInto(x0, y0, z0, P, buf, off);
if (!zz0) continue;
const zz1 = projectInto(x1, y1, z1, P, buf, off + 2);
if (!zz1) continue;
const zz2 = projectInto(x2, y2, z2, P, buf, off + 4);
if (!zz2) continue;
const zz3 = projectInto(x3, y3, z3, P, buf, off + 6);
if (!zz3) continue;
const p0x = buf[off],
p0y = buf[off + 1];
const p1x = buf[off + 2],
p1y = buf[off + 3];
const p2x = buf[off + 4],
p2y = buf[off + 5];
const p3x = buf[off + 6],
p3y = buf[off + 7];
if (Math.max(p0x, p1x, p2x, p3x) < 0) continue;
if (Math.min(p0x, p1x, p2x, p3x) > W) continue;
if (Math.max(p0y, p1y, p2y, p3y) < 0) continue;
if (Math.min(p0y, p1y, p2y, p3y) > H) continue;
buf[off + 8] = (zz0 + zz1 + zz2 + zz3) * 0.25;
buf[off + 9] = speed;
buf[off + 10] = cells[src + 13];
buf[off + 11] = cells[src + 14];
buf[off + 12] = cells[src + 15];
cellCount++;
}
}
buildPickGrid(W, H);
pickDirty = false;
}
function buildPickGrid(W: number, H: number) {
const buckets = pickBuckets;
for (let i = 0; i < buckets.length; i++) buckets[i] = null;
const cw = W / PICK_GRID;
const ch = H / PICK_GRID;
const buf = cellBuf;
for (let i = 0; i < cellCount; i++) {
const off = i * CELL_STRIDE;
let x0 = buf[off],
x1 = x0;
let y0 = buf[off + 1],
y1 = y0;
for (let p = 2; p <= 6; p += 2) {
const px = buf[off + p],
py = buf[off + p + 1];
if (px < x0) x0 = px;
else if (px > x1) x1 = px;
if (py < y0) y0 = py;
else if (py > y1) y1 = py;
}
const gx0 = Math.max(0, Math.floor(x0 / cw));
const gx1 = Math.min(PICK_GRID - 1, Math.floor(x1 / cw));
const gy0 = Math.max(0, Math.floor(y0 / ch));
const gy1 = Math.min(PICK_GRID - 1, Math.floor(y1 / ch));
if (gx1 < gx0 || gy1 < gy0) continue;
for (let gy = gy0; gy <= gy1; gy++) {
const base = gy * PICK_GRID;
for (let gx = gx0; gx <= gx1; gx++) {
const key = base + gx;
let arr = buckets[key];
if (!arr) buckets[key] = arr = [];
arr.push(i);
}
}
}
}
/* ============================================================
* 9. 渲染管线
* ============================================================ */
let rafId: number | null = null;
let resizeObserver: ResizeObserver | null = null;
function scheduleRender() {
if (rafId !== null) return;
rafId = requestAnimationFrame(() => {
rafId = null;
render();
});
}
function sizeGLCanvas(cv: HTMLCanvasElement) {
const dpr = window.devicePixelRatio || 1;
const rect = cv.parentElement?.getBoundingClientRect();
const W = rect?.width || 600;
const H = rect?.height || 600;
const pw = Math.round(W * dpr);
const ph = Math.round(H * dpr);
if (cv.width !== pw || cv.height !== ph) {
cv.width = pw;
cv.height = ph;
}
return { W, H, dpr };
}
function render() {
const canvas = canvasRef.value;
if (!canvas || !gl || !glReady) return;
const data = currentData.value;
if (!data) {
drawEmpty();
return;
}
const { W, H } = sizeGLCanvas(canvas);
const P = buildProjection(W, H, data.maxDistance);
drawWebGLVolume(canvas, W, H, P, data);
drawGridOverlay(W, H, P, data);
drawLegend();
pickDirty = true;
}
function drawEmpty() {
const canvas = canvasRef.value;
if (!canvas || !gl) return;
const { W, H, dpr } = sizeGLCanvas(canvas);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const overlay = gridOverlayRef.value;
if (overlay) {
const pw = Math.round(W * dpr),
ph = Math.round(H * dpr);
if (overlay.width !== pw || overlay.height !== ph) {
overlay.width = pw;
overlay.height = ph;
}
const octx = overlay.getContext("2d")!;
octx.setTransform(dpr, 0, 0, dpr, 0, 0);
octx.clearRect(0, 0, W, H);
octx.fillStyle = "rgba(255,255,255,0.3)";
octx.font = "16px sans-serif";
octx.textAlign = "center";
octx.textBaseline = "middle";
octx.fillText("无数据", W / 2, H / 2);
}
cellCount = 0;
drawLegend();
pickDirty = true;
}
function drawWebGLVolume(
canvas: HTMLCanvasElement,
W: number,
H: number,
P: Projection,
data: ParsedData,
) {
if (!gl || !prog) return;
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LESS);
gl.depthMask(false);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.useProgram(prog);
gl.uniform1f(u_cosY, P.cosY);
gl.uniform1f(u_sinY, P.sinY);
gl.uniform1f(u_cosP, P.cosP);
gl.uniform1f(u_sinP, P.sinP);
gl.uniform1f(u_dist, P.dist);
gl.uniform1f(u_focal, P.focal);
gl.uniform1f(u_cx, P.cx);
gl.uniform1f(u_cy, P.cy);
gl.uniform2f(u_viewport, W, H);
gl.uniform1f(u_speedMin, COLOR_SPEED_MIN);
gl.uniform1f(u_speedMax, COLOR_SPEED_MAX);
gl.uniform1f(u_maxDist, data.maxDistance);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, colorTex);
gl.uniform1i(u_colormap, 0);
if (indexBuffer) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
}
const sel = selectedElevations.value;
const layers =
sel.length === 0
? data.layers
: data.layers.filter((l) => sel.includes(l.el));
for (const layer of layers) {
if (layer.el >= 89) continue;
if (layer.cellCount === 0) continue;
const vbo = getLayerVBO(layer);
if (!vbo) continue;
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, STRIDE_BYTES, 0);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, STRIDE_BYTES, 12);
gl.vertexAttribPointer(2, 3, gl.FLOAT, false, STRIDE_BYTES, 24);
gl.vertexAttribPointer(3, 3, gl.FLOAT, false, STRIDE_BYTES, 36);
gl.vertexAttribPointer(4, 1, gl.FLOAT, false, STRIDE_BYTES, 48);
gl.drawElementsInstanced(
gl.TRIANGLES,
6,
gl.UNSIGNED_SHORT,
0,
layer.cellCount,
);
}
}
/* ---------- 网格叠加(离屏缓存 + 平移偏移) ---------- */
let gridCanvas: HTMLCanvasElement | null = null;
let gridKey = "";
function drawGridOverlay(
W: number,
H: number,
P: Projection,
data: ParsedData,
) {
const overlay = gridOverlayRef.value;
if (!overlay) return;
const dpr = window.devicePixelRatio || 1;
const pw = Math.round(W * dpr);
const ph = Math.round(H * dpr);
if (overlay.width !== pw || overlay.height !== ph) {
overlay.width = pw;
overlay.height = ph;
}
const octx = overlay.getContext("2d")!;
octx.setTransform(dpr, 0, 0, dpr, 0, 0);
octx.clearRect(0, 0, W, H);
const key =
`${W}|${H}|${dpr}|` +
`${P.cosY.toFixed(5)}|${P.sinY.toFixed(5)}|` +
`${P.cosP.toFixed(5)}|${P.sinP.toFixed(5)}|` +
`${P.focal.toFixed(2)}|${data.maxDistance}|` +
`${data.azMin}|${data.azMax}|${data.elMin}|${data.elMax}`;
if (key !== gridKey || !gridCanvas) {
if (!gridCanvas) gridCanvas = document.createElement("canvas");
const c = gridCanvas;
c.width = pw;
c.height = ph;
const ctx = c.getContext("2d")!;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, W, H);
const Pg: Projection = { ...P, cx: W / 2, cy: H * 0.55 };
drawGroundGrid(ctx, Pg, data);
drawLabels(ctx, Pg, data);
gridKey = key;
}
if (cam.panX !== 0 || cam.panY !== 0) {
octx.drawImage(gridCanvas, cam.panX, cam.panY, W, H);
} else {
octx.drawImage(gridCanvas, 0, 0, W, H);
}
}
/* ---------- 地面网格 ---------- */
function drawGroundGrid(
ctx: CanvasRenderingContext2D,
P: Projection,
data: ParsedData,
) {
const maxD = data.maxDistance;
const azMin = data.azMin ?? 0;
const azMax = data.azMax ?? 180;
const step = Math.max(500, Math.ceil(maxD / 6 / 500) * 500);
// 同心弧
ctx.lineWidth = 1;
ctx.strokeStyle = "rgba(110, 160, 220, 0.22)";
for (let r = step; r <= maxD + 1; r += step) {
ctx.beginPath();
let started = false;
for (let a = azMin; a <= azMax; a += 4) {
const rad = (a * Math.PI) / 180;
const p = project(r * Math.sin(rad), r * Math.cos(rad), 0, P);
if (!p) {
started = false;
continue;
}
if (!started) {
ctx.moveTo(p.x, p.y);
started = true;
} else ctx.lineTo(p.x, p.y);
}
ctx.stroke();
}
// 径向线
ctx.strokeStyle = "rgba(110, 160, 220, 0.16)";
const span = Math.max(1, azMax - azMin);
const radialStep = Math.max(15, Math.round(span / 8));
for (let a = azMin; a <= azMax; a += radialStep) {
const rad = (a * Math.PI) / 180;
const p0 = project(0, 0, 0, P);
const p1 = project(maxD * Math.sin(rad), maxD * Math.cos(rad), 0, P);
if (p0 && p1) {
ctx.beginPath();
ctx.moveTo(p0.x, p0.y);
ctx.lineTo(p1.x, p1.y);
ctx.stroke();
}
}
// 垂直轴(高度参考)
ctx.strokeStyle = "rgba(110, 160, 220, 0.35)";
const pz0 = project(0, 0, 0, P);
const pz1 = project(0, 0, maxD * 0.75 * Z_SCALE, P);
if (pz0 && pz1) {
ctx.beginPath();
ctx.moveTo(pz0.x, pz0.y);
ctx.lineTo(pz1.x, pz1.y);
ctx.stroke();
}
// 外弧
ctx.strokeStyle = "rgba(140, 190, 255, 0.4)";
ctx.lineWidth = 1.4;
ctx.beginPath();
let st = false;
for (let a = azMin; a <= azMax; a += 2) {
const rad = (a * Math.PI) / 180;
const p = project(maxD * Math.sin(rad), maxD * Math.cos(rad), 0, P);
if (!p) {
st = false;
continue;
}
if (!st) {
ctx.moveTo(p.x, p.y);
st = true;
} else ctx.lineTo(p.x, p.y);
}
ctx.stroke();
// 两侧边界线
ctx.strokeStyle = "rgba(140, 190, 255, 0.25)";
ctx.lineWidth = 1;
[azMin, azMax].forEach((a) => {
const rad = (a * Math.PI) / 180;
const p0 = project(0, 0, 0, P);
const p1 = project(maxD * Math.sin(rad), maxD * Math.cos(rad), 0, P);
if (p0 && p1) {
ctx.beginPath();
ctx.moveTo(p0.x, p0.y);
ctx.lineTo(p1.x, p1.y);
ctx.stroke();
}
});
}
function drawLabels(
ctx: CanvasRenderingContext2D,
P: Projection,
data: ParsedData,
) {
const maxD = data.maxDistance;
const azMin = data.azMin ?? 0;
const azMax = data.azMax ?? 180;
ctx.font = "11px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const rOut = maxD * 1.09;
const dirName: Record<number, string> = {
0: "N",
90: "E",
180: "S",
270: "W",
};
// 方位标注
const span = Math.max(1, azMax - azMin);
const labelStep = Math.max(15, Math.round(span / 6));
for (let a = azMin; a <= azMax; a += labelStep) {
const rad = (a * Math.PI) / 180;
const p = project(rOut * Math.sin(rad), rOut * Math.cos(rad), 0, P);
if (!p) continue;
const label = dirName[a] || a + "°";
ctx.fillStyle = dirName[a]
? "rgba(160, 220, 255, 0.9)"
: "rgba(150, 180, 215, 0.6)";
ctx.fillText(label, p.x, p.y);
}
// 距离标注(沿方位角中间方向)
const step = Math.max(500, Math.ceil(maxD / 6 / 500) * 500);
ctx.textAlign = "left";
ctx.font = "10px sans-serif";
ctx.fillStyle = "rgba(150, 190, 235, 0.65)";
const midAz = ((azMin + azMax) / 2) * (Math.PI / 180);
for (let r = step; r <= maxD + 1; r += step) {
const p = project(r * Math.sin(midAz), r * Math.cos(midAz), 0, P);
if (p) ctx.fillText(r + "m", p.x + 5, p.y - 2);
}
// 俯仰标注(沿竖直轴)
ctx.textAlign = "right";
ctx.fillStyle = "rgba(150, 190, 235, 0.55)";
for (let e = 0; e <= 90; e += 30) {
const z = maxD * 0.75 * Z_SCALE * Math.sin((e * Math.PI) / 180);
const p = project(0, 0, z, P);
if (p) ctx.fillText(e + "°", p.x - 6, p.y);
}
// 原点
const o = project(0, 0, 0, P);
if (o) {
ctx.beginPath();
ctx.arc(o.x, o.y, 2.5, 0, Math.PI * 2);
ctx.fillStyle = "rgba(160, 220, 255, 0.9)";
ctx.fill();
}
}
/* ---------- 图例 ---------- */
function drawLegend() {
const c = legendCanvasRef.value;
if (!c) return;
const ctx = c.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const parentRect = c.parentElement?.getBoundingClientRect();
const width = Math.round(parentRect?.width || 200);
const height = 20;
if (
c.width !== Math.round(width * dpr) ||
c.height !== Math.round(height * dpr)
) {
c.width = Math.round(width * dpr);
c.height = Math.round(height * dpr);
c.style.width = width + "px";
c.style.height = height + "px";
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const grad = ctx.createLinearGradient(0, 0, width, 0);
const span = COLOR_SPEED_MAX - COLOR_SPEED_MIN || 1;
for (const s of VELOCITY_COLOR_STOPS) {
let pos = (s.speed - COLOR_SPEED_MIN) / span;
pos = clamp(pos, 0, 1);
grad.addColorStop(pos, `rgb(${s.rgb[0]},${s.rgb[1]},${s.rgb[2]})`);
}
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = "rgba(255,255,255,0.3)";
ctx.lineWidth = 1;
ctx.strokeRect(0.5, 0.5, width - 1, height - 1);
}
/* ============================================================
* 10. 交互
* ============================================================ */
let isRotating = false;
let isPanning = false;
let lastMX = 0;
let lastMY = 0;
function onMouseDown(e: MouseEvent) {
if (e.button === 0) {
// 左键:平移视图
isPanning = true;
isDragging.value = true;
lastMX = e.clientX;
lastMY = e.clientY;
hideTooltip();
} else if (e.button === 1) {
// 中键:旋转视图(阻止浏览器默认自动滚动)
e.preventDefault();
isRotating = true;
isDragging.value = true;
lastMX = e.clientX;
lastMY = e.clientY;
hideTooltip();
} else if (e.button === 2) {
// 右键:平移视图
e.preventDefault();
isPanning = true;
isDragging.value = true;
lastMX = e.clientX;
lastMY = e.clientY;
hideTooltip();
}
}
function onCanvasMouseMove(e: MouseEvent) {
if (isRotating || isPanning) return;
updateTooltip(e);
}
function onCanvasMouseLeave() {
if (isRotating || isPanning) {
isRotating = false;
isPanning = false;
isDragging.value = false;
}
hideTooltip();
}
function onWindowMouseMove(e: MouseEvent) {
if (isRotating) {
const dx = e.clientX - lastMX;
const dy = e.clientY - lastMY;
cam.yaw -= dx * 0.008;
cam.pitch = clamp(cam.pitch - dy * 0.006, PITCH_MIN, PITCH_MAX);
lastMX = e.clientX;
lastMY = e.clientY;
scheduleRender();
return;
}
if (isPanning) {
const dx = e.clientX - lastMX;
const dy = e.clientY - lastMY;
cam.panX += dx;
cam.panY += dy;
lastMX = e.clientX;
lastMY = e.clientY;
scheduleRender();
return;
}
}
function onWindowMouseUp() {
if (isRotating || isPanning) {
isRotating = false;
isPanning = false;
isDragging.value = false;
}
}
function onWheel(e: WheelEvent) {
const canvas = canvasRef.value;
const factor = e.deltaY > 0 ? 0.9 : 1.1;
const nz = clamp(cam.zoom * factor, ZOOM_MIN, ZOOM_MAX);
if (nz === cam.zoom) return;
// 以鼠标为锚点缩放
if (canvas) {
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const cx0 = rect.width / 2 + cam.panX;
const cy0 = rect.height * 0.55 + cam.panY;
const k = nz / cam.zoom;
// 保持鼠标下的世界点不动:cx' = mx - k*(mx - cx)
cam.panX = mx - (mx - cx0) * k - rect.width / 2;
cam.panY = my - (my - cy0) * k - rect.height * 0.55;
}
cam.zoom = nz;
scheduleRender();
}
function zoomIn() {
const nz = Math.min(cam.zoom + ZOOM_STEP, ZOOM_MAX);
if (nz !== cam.zoom) {
cam.zoom = nz;
scheduleRender();
}
}
function zoomOut() {
const nz = Math.max(cam.zoom - ZOOM_STEP, ZOOM_MIN);
if (nz !== cam.zoom) {
cam.zoom = nz;
scheduleRender();
}
}
function resetView() {
cam.yaw = DEFAULT_CAM.yaw;
cam.pitch = DEFAULT_CAM.pitch;
cam.zoom = DEFAULT_CAM.zoom;
cam.panX = 0;
cam.panY = 0;
scheduleRender();
}
/* ---------- Tooltip ---------- */
let tooltipRaf: number | null = null;
let pendingMouse: MouseEvent | null = null;
function updateTooltip(e: MouseEvent) {
pendingMouse = e;
if (tooltipRaf !== null) return;
tooltipRaf = requestAnimationFrame(() => {
tooltipRaf = null;
const m = pendingMouse;
pendingMouse = null;
if (m) doTooltip(m);
});
}
function pointInQuad(
px: number,
py: number,
buf: Float32Array,
off: number,
): boolean {
const p0x = buf[off],
p0y = buf[off + 1];
const p1x = buf[off + 2],
p1y = buf[off + 3];
const p2x = buf[off + 4],
p2y = buf[off + 5];
const p3x = buf[off + 6],
p3y = buf[off + 7];
const c1 = (p1x - p0x) * (py - p0y) - (p1y - p0y) * (px - p0x);
const c2 = (p2x - p1x) * (py - p1y) - (p2y - p1y) * (px - p1x);
const c3 = (p3x - p2x) * (py - p2y) - (p3y - p2y) * (px - p2x);
const c4 = (p0x - p3x) * (py - p3y) - (p0y - p3y) * (px - p3x);
const hasNeg = c1 < 0 || c2 < 0 || c3 < 0 || c4 < 0;
const hasPos = c1 > 0 || c2 > 0 || c3 > 0 || c4 > 0;
return !(hasNeg && hasPos);
}
function doTooltip(m: MouseEvent) {
const canvas = canvasRef.value;
if (!canvas) return;
if (pickDirty) buildPickBuffer();
if (cellCount === 0) {
hideTooltip();
return;
}
const rect = canvas.getBoundingClientRect();
const mx = m.clientX - rect.left;
const my = m.clientY - rect.top;
if (mx < 0 || my < 0 || mx > rect.width || my > rect.height) {
hideTooltip();
return;
}
const cw = rect.width / PICK_GRID;
const ch = rect.height / PICK_GRID;
const gx = Math.min(PICK_GRID - 1, Math.max(0, Math.floor(mx / cw)));
const gy = Math.min(PICK_GRID - 1, Math.max(0, Math.floor(my / ch)));
const candidates = pickBuckets[gy * PICK_GRID + gx];
if (!candidates || candidates.length === 0) {
hideTooltip();
return;
}
// 取最近(depth 最小)的单元
let bestIdx = -1;
let bestDepth = Infinity;
const buf = cellBuf;
for (let ci = 0; ci < candidates.length; ci++) {
const i = candidates[ci];
const off = i * CELL_STRIDE;
if (!pointInQuad(mx, my, buf, off)) continue;
const d = buf[off + 8];
if (d < bestDepth) {
bestDepth = d;
bestIdx = i;
}
}
if (bestIdx < 0) {
hideTooltip();
return;
}
const off = bestIdx * CELL_STRIDE;
const wrapperRect = canvas.parentElement?.getBoundingClientRect();
if (!wrapperRect) return;
const wx = m.clientX - wrapperRect.left;
const wy = m.clientY - wrapperRect.top;
let tx = wx + 14;
let ty = wy + 14;
if (tx + 170 > wrapperRect.width) tx = wx - 170;
if (ty + 130 > wrapperRect.height) ty = wy - 130;
if (tx < 0) tx = 4;
if (ty < 0) ty = 4;
tooltip.visible = true;
tooltip.x = tx;
tooltip.y = ty;
tooltip.distance = Math.round(buf[off + 12]);
tooltip.azimuth = Math.round(buf[off + 10]);
tooltip.elevation = Math.round(buf[off + 11]);
tooltip.speed = buf[off + 9];
}
function hideTooltip() {
if (tooltip.visible) tooltip.visible = false;
}
/* ============================================================
* 11. 帧数据更新(与 2D PPI 组件完全一致)
* ============================================================ */
function applyFrames(newVal: any[]) {
const validFrames = newVal.filter((frame) => frame?.Scans?.length > 0);
if (validFrames.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
// 去重(基于 frame.Scan.RTC)
const seen = new Set<string>();
const uniqueFrames: any[] = [];
for (const frame of validFrames) {
const rtc = frame?.Scan?.RTC;
if (rtc && !seen.has(rtc)) {
seen.add(rtc);
uniqueFrames.push(frame);
}
}
// 按时间升序
uniqueFrames.sort((a, b) => {
const t1 = a?.Scan?.RTC || "";
const t2 = b?.Scan?.RTC || "";
return t1.localeCompare(t2);
});
// 只保留最新 MAX_FRAMES 帧
if (uniqueFrames.length > MAX_FRAMES) {
uniqueFrames.splice(0, uniqueFrames.length - MAX_FRAMES);
}
// 智能跳过:RTC 列表完全相同则不做任何更新
const newRTCs = uniqueFrames
.map((f) => f?.Scan?.RTC)
.filter(Boolean) as string[];
const oldRTCs = frames.value
.map((f) => f?.Scan?.RTC)
.filter(Boolean) as string[];
if (
newRTCs.length === oldRTCs.length &&
newRTCs.every((rtc, i) => rtc === oldRTCs[i])
) {
return;
}
// 保存当前选中帧状态
let currentRTC: string | null = null;
let wasLatest = false;
if (
currentFrameIndex.value >= 0 &&
currentFrameIndex.value < frames.value.length
) {
const cur = frames.value[currentFrameIndex.value];
if (cur?.Scan?.RTC) {
currentRTC = cur.Scan.RTC;
if (currentFrameIndex.value === frames.value.length - 1) {
wasLatest = true;
}
}
}
frames.value = uniqueFrames;
if (frames.value.length === 0) {
currentFrameIndex.value = -1;
} else if (wasLatest) {
currentFrameIndex.value = frames.value.length - 1;
} else if (currentRTC) {
const idx = frames.value.findIndex((f) => f?.Scan?.RTC === currentRTC);
// 原帧被移除时回退到最旧帧
currentFrameIndex.value = idx !== -1 ? idx : 0;
} else {
currentFrameIndex.value = frames.value.length - 1;
}
scheduleRender();
}
watch(
() => deviceInfo.value,
(newVal) => {
if (!Array.isArray(newVal) || newVal.length === 0) {
frames.value = [];
currentFrameIndex.value = -1;
scheduleRender();
return;
}
applyFrames(newVal);
},
{ deep: true, immediate: true },
);
function onSliderChange() {
scheduleRender();
}
/** 左右按钮逐帧切换 */
function stepFrame(delta: number) {
const fs = frames.value;
if (fs.length === 0) return;
const next = clamp(currentFrameIndex.value + delta, 0, fs.length - 1);
if (next === currentFrameIndex.value) return;
currentFrameIndex.value = next;
scheduleRender();
}
/* ============================================================
* 12. 生命周期
* ============================================================ */
function onContextLost(e: Event) {
e.preventDefault();
glReady = false;
}
function onContextRestored() {
if (initGL()) scheduleRender();
}
onMounted(() => {
nextTick(() => {
const canvas = canvasRef.value;
if (canvas) {
canvas.addEventListener("webglcontextlost", onContextLost, false);
canvas.addEventListener("webglcontextrestored", onContextRestored, false);
}
if (initGL() === false) {
console.warn("[radar] WebGL 初始化失败");
}
if (
canvas &&
canvas.parentElement &&
typeof ResizeObserver !== "undefined"
) {
resizeObserver = new ResizeObserver(() => {
scheduleRender();
});
resizeObserver.observe(canvas.parentElement);
}
window.addEventListener("mousemove", onWindowMouseMove);
window.addEventListener("mouseup", onWindowMouseUp);
document.addEventListener("mousedown", onDocMousedown, true);
scheduleRender();
});
});
onBeforeUnmount(() => {
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
if (tooltipRaf !== null) {
cancelAnimationFrame(tooltipRaf);
tooltipRaf = null;
}
if (resizeObserver) {
resizeObserver.disconnect();
resizeObserver = null;
}
window.removeEventListener("mousemove", onWindowMouseMove);
window.removeEventListener("mouseup", onWindowMouseUp);
document.removeEventListener("mousedown", onDocMousedown, true);
const canvas = canvasRef.value;
if (canvas) {
canvas.removeEventListener("webglcontextlost", onContextLost, false);
canvas.removeEventListener("webglcontextrestored", onContextRestored, false);
}
if (gl) {
if (colorTex) gl.deleteTexture(colorTex);
if (prog) gl.deleteProgram(prog);
if (indexBuffer) gl.deleteBuffer(indexBuffer);
}
glReady = false;
});
defineExpose({
resetView,
zoomIn,
zoomOut,
get frames() {
return frames.value;
},
});
</script>
<style scoped lang="less">
.radar-ppi-container {
position: relative;
width: 100%;
height: 100%;
border-right: 1px solid #243049;
padding: 0 10px;
box-sizing: border-box;
display: flex;
flex-direction: column;
background: #0a0e1a;
.radar-canvas-wrapper {
flex: 1;
min-height: 0;
position: relative;
background: radial-gradient(circle at 50% 55%, #0e1424 0%, #070a12 100%);
.radar-canvas {
display: block;
width: 100%;
height: 100%;
position: absolute;
inset: 0;
cursor: grab;
user-select: none;
&.dragging {
cursor: grabbing;
}
}
.radar-grid-overlay {
display: block;
width: 100%;
height: 100%;
position: absolute;
inset: 0;
pointer-events: none;
}
.realtime-svol-panel {
position: absolute;
top: 8px;
right: 8px;
width: 300px;
height: 260px;
background-color: #0a0e1a;
}
.radar-info-panel {
position: absolute;
top: 8px;
left: 8px;
font-size: 14px;
color: rgba(255, 255, 255, 0.85);
line-height: 1.6;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
.highlight {
color: var(--el-color-primary);
font-weight: bold;
}
}
.radar-legend {
position: absolute;
right: 16px;
bottom: 16px;
pointer-events: none;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
.legend-canvas {
display: block;
width: 200px;
height: 20px;
border-radius: 2px;
margin-bottom: 2px;
}
.legend-labels {
display: flex;
justify-content: space-between;
font-size: 11px;
color: rgba(255, 255, 255, 0.7);
}
}
.radar-tooltip {
position: absolute;
background: rgba(0, 0, 0, 0.85);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
padding: 8px 12px;
font-size: 12px;
color: #fff;
line-height: 1.6;
pointer-events: none;
white-space: nowrap;
z-index: 10;
}
.zoom-controls {
position: absolute;
bottom: 16px;
left: 8px;
display: flex;
align-items: center;
gap: 6px;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
padding: 4px 6px;
user-select: none;
.zoom-btn {
width: 28px;
height: 28px;
background: transparent;
border: none;
color: #fff;
font-size: 18px;
font-weight: bold;
cursor: pointer;
border-radius: 2px;
transition: background 0.15s;
display: flex;
align-items: center;
justify-content: center;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.1);
}
&:disabled {
color: rgba(255, 255, 255, 0.25);
cursor: not-allowed;
}
}
.zoom-level {
min-width: 44px;
text-align: center;
font-size: 13px;
color: rgba(255, 255, 255, 0.85);
font-variant-numeric: tabular-nums;
}
.zoom-divider {
width: 1px;
height: 16px;
background: rgba(255, 255, 255, 0.2);
}
.zoom-btn.reset-btn {
font-size: 15px;
}
}
/* ================= 少量层:按钮列表 ================= */
.layer-switcher {
position: absolute;
right: 16px;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-direction: column;
width: 62px;
max-height: 78%;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
overflow: hidden;
z-index: 5;
user-select: none;
/* 顶部标题栏(当前模板未使用,保留备选) */
.layer-title {
flex-shrink: 0;
padding: 6px 8px;
font-size: 12px;
text-align: center;
color: rgba(255, 255, 255, 0.8);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
/* 按钮列表 */
.layer-list {
display: flex;
flex-direction: column;
gap: 4px;
padding: 6px;
overflow-y: auto;
overflow-x: hidden;
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
&::-webkit-scrollbar {
width: 3px;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 2px;
&:hover {
background: rgba(255, 255, 255, 0.35);
}
}
&::-webkit-scrollbar-track {
background: transparent;
}
}
/* 按钮基础 */
.layer-btn {
flex-shrink: 0;
height: 28px;
padding: 0 6px;
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.7);
font-size: 12px;
border-radius: 2px;
cursor: pointer;
transition:
background 0.15s ease,
color 0.15s ease;
font-variant-numeric: tabular-nums;
text-align: center;
white-space: nowrap;
line-height: 1;
outline: none;
&:hover {
background: rgba(255, 255, 255, 0.1);
color: #fff;
}
/* 选中态 */
&.active {
background: var(--el-color-primary);
color: #fff;
}
}
}
/* ================= 大量层:弹出面板 ================= */
.layer-switcher-popover {
position: absolute;
right: 16px;
top: 50%;
transform: translateY(-50%);
z-index: 6;
user-select: none;
.layer-trigger {
width: 62px;
height: 32px;
padding: 0 6px;
background: rgba(10, 14, 26, 0.8);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
color: rgba(255, 255, 255, 0.85);
font-size: 12px;
cursor: pointer;
transition: all 0.15s;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-variant-numeric: tabular-nums;
&:hover {
border-color: rgba(127, 212, 255, 0.6);
color: #7fd4ff;
}
&.active {
border-color: var(--el-color-primary);
color: var(--el-color-primary);
}
}
.layer-panel {
position: absolute;
right: calc(100% + 8px);
top: 50%;
transform: translateY(-50%);
width: 190px;
max-height: 340px;
background: rgba(10, 14, 26, 0.96);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 6px;
padding: 8px;
display: flex;
flex-direction: column;
gap: 6px;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.6);
box-sizing: border-box;
}
.layer-panel-head {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
.layer-panel-title {
font-weight: 500;
}
.layer-panel-count {
color: var(--el-color-primary);
font-variant-numeric: tabular-num