Commit 734e4e87 by liimin

添加自绘图层辅助界面

1 parent eaa0db0e
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState, lazy, Suspense } from 'react';
import { Button, Modal, Tooltip } from 'antd'; import { Button, Modal, Tooltip } from 'antd';
import { AimOutlined, InfoCircleOutlined } from '@ant-design/icons'; import { AimOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { CollapseButton } from '@hm/ui'; import { CollapseButton } from '@hm/ui';
...@@ -38,6 +38,12 @@ import { M_PER_EQUATOR } from './map/hotspotGeometry'; ...@@ -38,6 +38,12 @@ import { M_PER_EQUATOR } from './map/hotspotGeometry';
import { Frame, FAST_MOVE_PX, viewPos, viewShiftPx, type ViewPos } from './map/viewFrame'; import { Frame, FAST_MOVE_PX, viewPos, viewShiftPx, type ViewPos } from './map/viewFrame';
import { BucketCard } from './detail/BucketCard'; import { BucketCard } from './detail/BucketCard';
import { MapKeyGuide } from './MapKeyGuide'; import { MapKeyGuide } from './MapKeyGuide';
import {
debugAvailable,
debugEnabled,
pushDebugEvent,
setAggregateDebug,
} from './debug/debugBus';
import { drawerWidth } from '@/layout/drawerWidth'; import { drawerWidth } from '@/layout/drawerWidth';
import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format'; import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format';
...@@ -45,6 +51,25 @@ import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format'; ...@@ -45,6 +51,25 @@ import { fmtCompact, fmtInt, fmtMs, placeNameOf } from '@/utils/format';
const REFRESH_DEBOUNCE_MS = 90; const REFRESH_DEBOUNCE_MS = 90;
/** /**
* 开发者调试视图整块走**动态 import**:它是可选观察者,不该占业务首屏。
*
* 关闭态的代价因此分两段,都是量出来的(`npm run build` 后 dist 实测):
* - 正式构建且 URL 不带 `?debug=1`:这一句根本不执行,面板 + 覆盖画布 + 那份 CSS
* 连下载都没有 —— `DebugHud-*.js` 14.30 kB(gzip 5.51)加 `DebugHud-*.css` 3.98 kB
* (gzip 1.17),合计 6.68 kB gzip,业务用户一个字节都拿不到;
* - 唯一留在主块里的调试件是 `debug/debugBus.ts`(四个层要往里写遥测,静态依赖断不掉):
* 去注释 3.57 kB 源码、gzip 上限 1.22 kB。主块里另外还剩三条事件正文的字符串常量
* ("定档为快拖…"那几句,几十字节),调用点已被 `debugEnabled()` 守住,不再构造模板串。
*
* ⚠️ 要整块剔除这部分功能,动手范围就三处:删 `src/features/heatmap/debug/` 目录、
* 删上面那一句 `import` 与 `DebugHudLazy`、删各层与 MapStage 里以 `debugEnabled()` /
* `pushDebugEvent` / `setAggregateDebug` / `registerDebugLayer` / `finishPaint` /
* `setDebugTotal` 为名字的调用点(全局搜这几个词一次列全)。
* 逐层遥测都写成"一次整数赋值"的形状,删掉不会牵动画法逻辑。
*/
const DebugHudLazy = lazy(() => import('./debug/DebugHud').then((m) => ({ default: m.DebugHud })));
/**
* 筛选变化后重算统计的防抖时长。比聚合那 90ms 长一点: * 筛选变化后重算统计的防抖时长。比聚合那 90ms 长一点:
* 统计是「命中几十万点重归一遍维度」,多选区连点两下、时间档连切两下, * 统计是「命中几十万点重归一遍维度」,多选区连点两下、时间档连切两下,
* 中间那一次的结果本来就不该给人看,而扫一遍的几十到几百毫秒是实打实的主线程占用。 * 中间那一次的结果本来就不该给人看,而扫一遍的几十到几百毫秒是实打实的主线程占用。
...@@ -353,6 +378,9 @@ export function MapStage() { ...@@ -353,6 +378,9 @@ export function MapStage() {
const statsTimerRef = useRef<number | null>(null); const statsTimerRef = useRef<number | null>(null);
const [mapReady, setMapReady] = useState(false); const [mapReady, setMapReady] = useState(false);
// 调试视图的入口判定:只在挂载时算一次。它决定的是「要不要发起那次动态 import」,
// false 时那一块代码连请求都不会发出
const showDebug = useMemo(debugAvailable, []);
// 空态引导弹窗:进入 EMPTY 时默认弹出,点「稍后再说」后才收起(收起后地图区保留轻提示) // 空态引导弹窗:进入 EMPTY 时默认弹出,点「稍后再说」后才收起(收起后地图区保留轻提示)
const [emptyDismissed, setEmptyDismissed] = useState(false); const [emptyDismissed, setEmptyDismissed] = useState(false);
/** /**
...@@ -565,6 +593,13 @@ export function MapStage() { ...@@ -565,6 +593,13 @@ export function MapStage() {
try { try {
const token = ++aggTokenRef.current; const token = ++aggTokenRef.current;
if (debugEnabled()) {
pushDebugEvent(
'aggregate',
'发起聚合(Worker)',
`zoom ${zoom} · 框 ${bbox.minLng.toFixed(3)}~${bbox.maxLng.toFixed(3)} × ${bbox.minLat.toFixed(3)}~${bbox.maxLat.toFixed(3)}`,
);
}
const res = await aggregateClient.aggregate({ const res = await aggregateClient.aggregate({
zoom, zoom,
bbox, bbox,
...@@ -584,6 +619,34 @@ export function MapStage() { ...@@ -584,6 +619,34 @@ export function MapStage() {
maxLng: ne.getLng(), maxLng: ne.getLng(),
maxLat: ne.getLat(), maxLat: ne.getLat(),
}; };
// 这两笔都带模板字符串与一个十六字段对象字面量。调试关着时它们一行都不该构造 ——
// 守卫放在调用点而不是函数内,就是因为参数在进函数之前已经求过值了。
if (debugEnabled()) {
pushDebugEvent(
'aggregate',
'聚合回包,喂给各层',
`桶 ${res.bucketCount} · 参与 ${res.used} · 命中 ${res.matched} · ${res.ms.toFixed(1)}ms`,
);
// 调试视图要拿这批桶把格子与"均值落点"画出来,所以整份结果连同两个框一起交给它。
setAggregateDebug({
zoom,
bbox,
view: box,
bucketCount: res.bucketCount,
matched: res.matched,
used: res.used,
ms: res.ms,
gridPx: res.gridPx,
dLng: res.dLng,
dLat: res.dLat,
maxCount: res.maxCount,
lng: res.lng,
lat: res.lat,
gx: res.gx,
gy: res.gy,
count: res.count,
});
}
const st = useHeatmapStore.getState(); const st = useHeatmapStore.getState();
const prev = st.viewportBBox; const prev = st.viewportBBox;
if ( if (
...@@ -897,6 +960,7 @@ export function MapStage() { ...@@ -897,6 +960,7 @@ export function MapStage() {
releaseTimer = 0; releaseTimer = 0;
} }
if (isMapGesture()) { if (isMapGesture()) {
pushDebugEvent('gesture', '停下:逐层点名补一帧全量');
resetPace(); resetPace();
setMapGesture(false); setMapGesture(false);
repaintLayers(); repaintLayers();
...@@ -918,6 +982,9 @@ export function MapStage() { ...@@ -918,6 +982,9 @@ export function MapStage() {
* 那是"数字一闪一闪"的另一个现场,跟档位抖动同一个病。 * 那是"数字一闪一闪"的另一个现场,跟档位抖动同一个病。
*/ */
const released = () => { const released = () => {
if (debugEnabled()) {
pushDebugEvent('gesture', '抬手:先不当场收尾,等惯性结束', `${RELEASE_SETTLE_MS}ms 窗口`);
}
if (releaseTimer) window.clearTimeout(releaseTimer); if (releaseTimer) window.clearTimeout(releaseTimer);
releaseTimer = window.setTimeout(() => { releaseTimer = window.setTimeout(() => {
releaseTimer = 0; releaseTimer = 0;
...@@ -973,6 +1040,13 @@ export function MapStage() { ...@@ -973,6 +1040,13 @@ export function MapStage() {
// 进入减载之后只进不出:整趟保持摘掉,停下才一次性补画 // 进入减载之后只进不出:整趟保持摘掉,停下才一次性补画
// (为什么不能"慢下来就翻回去",见上面 RELEASE_SETTLE_MS 前那段迟滞的账) // (为什么不能"慢下来就翻回去",见上面 RELEASE_SETTLE_MS 前那段迟滞的账)
latched = true; latched = true;
if (debugEnabled()) {
pushDebugEvent(
'gesture',
'定档为快拖:这一趟各层都不落笔(坐标照算)',
`本帧位移 ${Math.round(moved)}px,门限 ${FAST_MOVE_PX}px × ${FAST_LATCH_FRAMES} 帧`,
);
}
setMapGesture(true, true); setMapGesture(true, true);
}); });
} }
...@@ -985,23 +1059,27 @@ export function MapStage() { ...@@ -985,23 +1059,27 @@ export function MapStage() {
// 终点认 moveend / zoomend(高德确认停下的那一下),抬手那一路走 released 的确认窗口, // 终点认 moveend / zoomend(高德确认停下的那一下),抬手那一路走 released 的确认窗口,
// 保险丝兜住"未必给出 moveend"的那些交互。 // 保险丝兜住"未必给出 moveend"的那些交互。
// 事件本身是每帧一次的函数调用,多挂三个不占什么,少挂一个就会掉一整段减载。 // 事件本身是每帧一次的函数调用,多挂三个不占什么,少挂一个就会掉一整段减载。
map.on('dragstart', busy); //
map.on('zoomstart', busy); // `track` 只为调试视图记一行事件名:调试关着时 pushDebugEvent 自己立刻返回,
map.on('mapmove', busy); // 所以这里没有额外判断,代价是一次函数调用。handler 存在同一份引用上,
map.on('drag', busy); // 卸载时按同一份引用摘掉 —— 图省事写成 `map.off(name, busy)` 会留下摘不掉的监听。
map.on('zoomchange', busy); const track = (name: string, fn: () => void) => () => {
map.on('moveend', finishGesture); pushDebugEvent('event', name);
map.on('zoomend', finishGesture); fn();
map.on('dragend', released); };
const handlers = {
dragstart: track('dragstart', busy),
zoomstart: track('zoomstart', busy),
mapmove: track('mapmove', busy),
drag: track('drag', busy),
zoomchange: track('zoomchange', busy),
moveend: track('moveend', finishGesture),
zoomend: track('zoomend', finishGesture),
dragend: track('dragend', released),
} as const;
for (const [name, fn] of Object.entries(handlers)) map.on(name, fn);
return () => { return () => {
map.off('dragstart', busy); for (const [name, fn] of Object.entries(handlers)) map.off(name, fn);
map.off('zoomstart', busy);
map.off('mapmove', busy);
map.off('drag', busy);
map.off('zoomchange', busy);
map.off('moveend', finishGesture);
map.off('zoomend', finishGesture);
map.off('dragend', released);
if (glassTimer) window.clearTimeout(glassTimer); if (glassTimer) window.clearTimeout(glassTimer);
if (fuse) window.clearTimeout(fuse); if (fuse) window.clearTimeout(fuse);
if (releaseTimer) window.clearTimeout(releaseTimer); if (releaseTimer) window.clearTimeout(releaseTimer);
...@@ -1554,6 +1632,14 @@ export function MapStage() { ...@@ -1554,6 +1632,14 @@ export function MapStage() {
{/* 右下那颗讲的是热力权重与背景淡化:聚焦期间热力层本来就收着, {/* 右下那颗讲的是热力权重与背景淡化:聚焦期间热力层本来就收着,
留着会出现「底色不见了,读数还在报底色由多少个点画出来」 */} 留着会出现「底色不见了,读数还在报底色由多少个点画出来」 */}
{mapReady && !spotlight && <HeatReadouts analysisOn={analysisOn} />} {mapReady && !spotlight && <HeatReadouts analysisOn={analysisOn} />}
{/* 开发者调试视图:开发构建自带,任何构建下 URL 带 ?debug=1 直接打开,其余情况
这一整块(面板 + 覆盖画布 + CSS)连下载都没有,业务界面因此一个字都不变。 */}
{mapReady && showDebug && (
<Suspense fallback={null}>
<DebugHudLazy map={mapRef.current} />
</Suspense>
)}
</div> </div>
); );
} }
......
/**
* 调试覆盖画布的几何守卫。
*
* 这一层是给开发者看的"证据",而证据最怕的是假:它画的格子必须与 Worker 真正分桶用的
* 那一套边界是同一支公式(aggregate/grid.ts 的 toGrid:按经纬度等分,y 方向再过墨卡托),
* 它报的均值落点必须真的落在自己画的那一格里面。一旦这里为了"看着顺眼"改用屏幕像素等分,
* 屏幕上就是调试线跟着走、真格子不跟 —— 用户会据此判定图层画错了,而错的是调试视图。
*
* 观察手法与 frameBudget.test.ts 一致:jsdom 没有 canvas 实现,把 getContext 换成一份
* 记账的假上下文,落笔坐标即为断言对象;出帧由测试推进 rAF(高德就是这么驱动的)。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GRID, gridDegAtZoom, toGrid } from '../aggregate/grid';
import { setAggregateDebug, setDebugEnabled, pushDebugEvent, registerDebugLayer, unregisterDebugLayer } from './debugBus';
import { DebugCanvas } from './DebugCanvas';
interface Op {
name: string;
args: number[];
}
function fakeCtx() {
const ops: Op[] = [];
const rec = (name: string) => (...args: number[]) => {
ops.push({ name, args });
};
const ctx: Record<string, unknown> = { ops };
for (const name of [
'setTransform',
'clearRect',
'beginPath',
'moveTo',
'lineTo',
'arc',
'fill',
'stroke',
'fillRect',
'strokeRect',
'save',
'restore',
'setLineDash',
]) {
ctx[name] = rec(name);
}
ctx.strokeText = () => undefined;
ctx.fillText = () => undefined;
return ctx as unknown as CanvasRenderingContext2D & { ops: Op[] };
}
const ZOOM = 12;
const LNG = 114.05;
const LAT = 22.54;
const W = 800;
const H = 600;
function fakeMap() {
return {
getSize: () => ({ width: W, height: H }),
getCenter: () => ({ getLng: () => LNG, getLat: () => LAT }),
getZoom: () => ZOOM,
// 原点交给"地图本身":这里给画布正中,与真地图一致
lngLatToContainer: () => ({ x: W / 2, y: H / 2 }),
} as unknown as AMap.Map;
}
const cell = gridDegAtZoom(ZOOM, GRID.gridPx, LAT);
/** 与 Frame 同一支换算:经度线性,纬度先过墨卡托 */
function expectedX(lng: number): number {
return W / 2 + (lng - LNG) * ((GRID.tileSize * Math.pow(2, ZOOM)) / 360);
}
const alive: DebugCanvas[] = [];
let ctx!: CanvasRenderingContext2D & { ops: Op[] };
let restoreCanvas: (() => void) | null = null;
beforeEach(() => {
vi.useFakeTimers();
ctx = fakeCtx();
const proto = window.HTMLCanvasElement.prototype as unknown as {
getContext: (id: string) => unknown;
};
const original = proto.getContext;
proto.getContext = () => ctx;
restoreCanvas = () => {
proto.getContext = original;
};
setDebugEnabled(true);
});
afterEach(() => {
while (alive.length) alive.pop()?.destroy();
restoreCanvas?.();
setDebugEnabled(false);
vi.useRealTimers();
vi.restoreAllMocks();
});
function flush(frames = 3): void {
for (let i = 0; i < frames; i += 1) vi.advanceTimersByTime(17);
}
function makeCanvas(): DebugCanvas {
const host = document.createElement('div');
document.body.appendChild(host);
const dc = new DebugCanvas(fakeMap(), host);
alive.push(dc);
dc.start();
return dc;
}
describe('调试画布画的格子就是聚合用的那一套网格', () => {
it('格子的左右边界由 gx 与 dLng 还原,且均值落点落在自己那一格内', () => {
const lng = LNG + 0.0004;
const lat = LAT + 0.0002;
const g = toGrid(lng, lat, cell);
setAggregateDebug({
zoom: ZOOM,
bbox: { minLng: LNG - 0.02, maxLng: LNG + 0.02, minLat: LAT - 0.02, maxLat: LAT + 0.02 },
view: { minLng: LNG - 0.01, maxLng: LNG + 0.01, minLat: LAT - 0.01, maxLat: LAT + 0.01 },
bucketCount: 1,
matched: 9,
used: 9,
ms: 4,
gridPx: GRID.gridPx,
dLng: cell.dLng,
dLat: cell.dLat,
maxCount: 9,
lng: Int32Array.from([Math.round(lng * 1e6)]),
lat: Int32Array.from([Math.round(lat * 1e6)]),
gx: Int32Array.from([g.gx]),
gy: Int32Array.from([g.gy]),
count: Int32Array.from([9]),
});
const dc = makeCanvas();
flush();
// 一帧里 strokeRect 有三笔:视口框、请求框、这一格的框。取宽度最接近 48px 的那一笔
const rects = ctx.ops.filter((o) => o.name === 'strokeRect').map((o) => o.args);
const cellRect = rects.find((a) => Math.abs(a[2] - GRID.gridPx) < 4);
expect(cellRect).toBeTruthy();
const [x, , w, h] = cellRect!;
expect(x).toBeCloseTo(expectedX(g.gx * cell.dLng - 180), 1);
expect(x + w).toBeCloseTo(expectedX((g.gx + 1) * cell.dLng - 180), 1);
expect(w).toBeGreaterThan(1);
expect(h).toBeGreaterThan(1);
// 均值点(数字真正落笔的地方)必须落在这一格里,否则画出来的格子和报出来的数各说各话
const meanX = expectedX(lng);
expect(meanX).toBeGreaterThan(x);
expect(meanX).toBeLessThan(x + w);
expect(dc.readout()).not.toBeNull();
});
it('网格线与格子边界重合:同一个 gx 只有一支尺子', () => {
const g = toGrid(LNG + 0.0004, LAT + 0.0002, cell);
setAggregateDebug({
zoom: ZOOM,
bbox: { minLng: LNG - 0.02, maxLng: LNG + 0.02, minLat: LAT - 0.02, maxLat: LAT + 0.02 },
view: { minLng: LNG - 0.01, maxLng: LNG + 0.01, minLat: LAT - 0.01, maxLat: LAT + 0.01 },
bucketCount: 0,
matched: 0,
used: 0,
ms: 0,
gridPx: GRID.gridPx,
dLng: cell.dLng,
dLat: cell.dLat,
maxCount: 0,
lng: null,
lat: null,
gx: null,
gy: null,
count: null,
});
makeCanvas();
flush();
const lineXs = ctx.ops.filter((o) => o.name === 'moveTo').map((o) => o.args[0]);
const boundary = expectedX(g.gx * cell.dLng - 180);
// 画线时对齐到半像素,所以差值只会来自取整
expect(lineXs.some((x) => Math.abs(x - (Math.round(boundary) + 0.5)) < 0.01)).toBe(true);
});
});
describe('调试画布自己也要省帧', () => {
it('视图与调试内容都没变就整帧跳过', () => {
makeCanvas();
flush(1);
const first = ctx.ops.length;
expect(first).toBeGreaterThan(0);
ctx.ops.length = 0;
flush(3);
expect(ctx.ops).toHaveLength(0);
});
it('总线一变(事件、聚合、开关项)就补一帧,不然读数看着像卡住', () => {
const dc = makeCanvas();
flush(1);
ctx.ops.length = 0;
pushDebugEvent('event', 'mapmove');
flush(2);
expect(ctx.ops.length).toBeGreaterThan(0);
expect(dc.stats().painted).toBeGreaterThan(1);
});
});
describe('图层高亮描的是那块画布本身', () => {
it('点名某一行 → 给它的 canvas 上描边;关掉调试必须收掉', () => {
const target = document.createElement('canvas');
registerDebugLayer({
id: 'cluster',
name: 'ClusterLayer · 聚合方格层',
zIndex: 130,
kind: 'canvas',
canvas: target,
read: () => ({
built: true,
visible: true,
released: false,
cssW: W,
cssH: H,
dpr: 1,
total: 1,
painted: 1,
drawn: 1,
skipped: 0,
lastMs: 1,
light: false,
}),
});
const dc = makeCanvas();
dc.setOptions({ highlight: 'cluster' });
flush(2);
expect(target.style.outline).not.toBe('');
setDebugEnabled(false);
expect(target.style.outline).toBe('');
unregisterDebugLayer('cluster');
});
});
/* 开发者调试视图。只在开发构建或 URL 带 ?debug=1 时挂载,不参与正式界面的让位阈值计算
(design.css 里 760 / 974 / 1140 那几段量的都是产品浮层,这块不算)。 */
.hm-debug {
position: absolute;
inset: 0;
/* 压在地图与自绘层之上、产品浮层(z-index 12)之下 */
z-index: 10;
pointer-events: none;
}
.hm-debug__canvas {
position: absolute;
inset: 0;
pointer-events: none;
}
.hm-debug__toggle {
position: absolute;
left: var(--hm-rail-gap);
top: var(--hm-rail-gap);
z-index: 13;
display: flex;
align-items: center;
gap: 6px;
padding: 5px 10px;
border-radius: 999px;
border: 1px dashed rgba(255, 255, 255, 0.7);
background: rgba(16, 24, 40, 0.55);
color: #fff;
font: 11px/1 'SF Mono', Consolas, Menlo, monospace;
cursor: pointer;
pointer-events: auto;
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
}
.hm-debug__toggle:hover {
background: rgba(16, 24, 40, 0.72);
}
.hm-debug__toggle.is-on {
border-style: solid;
border-color: #ff2d78;
background: rgba(255, 45, 120, 0.88);
}
.hm-debug__panel {
position: absolute;
left: var(--hm-rail-gap);
top: var(--hm-rail-gap);
z-index: 13;
pointer-events: auto;
display: flex;
flex-direction: column;
width: 372px;
max-height: calc(100% - var(--hm-rail-gap) * 2);
background: var(--hm-glass-side-strong);
border: 1px solid var(--hm-glass-border);
border-radius: 12px;
box-shadow: var(--hm-glass-shadow);
backdrop-filter: var(--hm-glass-blur);
-webkit-backdrop-filter: var(--hm-glass-blur);
font: 11px/1.5 'SF Mono', Consolas, Menlo, monospace;
color: var(--hm-text-2);
}
.hm-debug__head {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border-bottom: 1px solid var(--hm-glass-border);
font-weight: 600;
color: var(--hm-text-1);
}
.hm-debug__head-badge {
padding: 1px 6px;
border-radius: 999px;
background: #ff2d78;
color: #fff;
font-size: 10px;
letter-spacing: 0.04em;
}
.hm-debug__head button {
margin-left: auto;
border: none;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
padding: 2px 6px;
border-radius: 6px;
}
.hm-debug__head button:hover {
background: rgba(16, 24, 40, 0.08);
}
.hm-debug__body {
overflow: auto;
padding: 8px 10px 10px;
display: flex;
flex-direction: column;
gap: 10px;
}
.hm-debug__sec-title {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 4px;
font-weight: 600;
letter-spacing: 0.02em;
color: var(--hm-text-1);
}
.hm-debug__sec-title span {
font-weight: 400;
color: rgba(16, 24, 40, 0.5);
}
.hm-debug__row {
display: flex;
align-items: baseline;
gap: 6px;
padding: 2px 0;
}
.hm-debug__row b {
margin-left: auto;
font-weight: 600;
color: var(--hm-text-1);
}
.hm-debug__grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 2px 10px;
}
.hm-debug__grid .hm-debug__row b {
font-variant-numeric: tabular-nums;
}
/* 图层行:悬停那一行会把对应画布描边。左侧竖条是它的 zIndex 序位 */
.hm-debug__layer {
display: grid;
grid-template-columns: 4px 1fr auto;
gap: 0 8px;
padding: 4px 6px 4px 0;
border-radius: 8px;
border: 1px solid transparent;
}
.hm-debug__layer:hover,
.hm-debug__layer.is-active {
background: rgba(16, 24, 40, 0.06);
border-color: rgba(255, 45, 120, 0.5);
}
.hm-debug__layer-bar {
border-radius: 0 2px 2px 0;
background: var(--hm-accent-cyan);
}
.hm-debug__layer.is-hidden .hm-debug__layer-bar {
background: rgba(16, 24, 40, 0.2);
}
.hm-debug__layer-name {
font-weight: 600;
color: var(--hm-text-1);
}
.hm-debug__layer-note {
grid-column: 2 / span 2;
color: rgba(16, 24, 40, 0.55);
}
.hm-debug__layer-nums {
grid-column: 2 / span 2;
display: flex;
flex-wrap: wrap;
gap: 4px 10px;
color: rgba(16, 24, 40, 0.72);
}
.hm-debug__tag {
padding: 0 5px;
border-radius: 4px;
background: rgba(40, 167, 225, 0.16);
color: #0d7bb0;
}
.hm-debug__tag.is-warn {
background: rgba(255, 45, 120, 0.14);
color: #c9155c;
}
.hm-debug__tag.is-idle {
background: rgba(16, 24, 40, 0.08);
color: rgba(16, 24, 40, 0.6);
}
/* 事件时间轴。左边那一格是相对上一条的间隔,看的就是"什么时候真的发生了什么" */
.hm-debug__events {
display: flex;
flex-direction: column;
gap: 1px;
max-height: 168px;
overflow: auto;
padding-right: 2px;
}
.hm-debug__event {
display: grid;
grid-template-columns: 46px 8px 1fr;
gap: 6px;
align-items: center;
padding: 1px 2px;
border-radius: 4px;
}
.hm-debug__event:nth-child(odd) {
background: rgba(16, 24, 40, 0.035);
}
.hm-debug__event-time {
text-align: right;
color: rgba(16, 24, 40, 0.45);
}
.hm-debug__event-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--hm-accent-cyan);
}
.hm-debug__event-dot.k-gesture {
background: var(--hm-accent-gold-deep);
}
.hm-debug__event-dot.k-aggregate {
background: #7b61ff;
}
.hm-debug__event-dot.k-layer {
background: #12a86e;
}
.hm-debug__event-dot.k-frame {
background: #ff2d78;
}
.hm-debug__event-detail {
color: rgba(16, 24, 40, 0.55);
}
.hm-debug__event-n {
color: #c9155c;
font-weight: 600;
}
.hm-debug__opts {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
}
.hm-debug__opts label {
display: flex;
align-items: center;
gap: 4px;
cursor: pointer;
}
.hm-debug__hint {
color: rgba(16, 24, 40, 0.55);
}
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
clearDebugEvents,
debugEnabled,
getAggregateDebug,
getDebugEvents,
getDebugLayers,
pushDebugEvent,
registerDebugLayer,
setAggregateDebug,
setDebugEnabled,
subscribeDebug,
unregisterDebugLayer,
type AggregateDebug,
type LayerDebugRecord,
} from './debugBus';
/**
* 调试总线的守卫。
*
* 这一屏的全部意义是「报出来的就是真的」,所以钉死三件事:
* 1. 关掉调试时写入必须一条都不留 —— 热路径上的计数一旦在正式界面里继续累加,
* 读到的帧数就是假的,比看不到更糟;
* 2. 密集事件必须合并成一行并带次数 —— 时间轴是给人读的,不是给人刷屏的;
* 3. 层的读数走闭包而不是快照 —— 注册那一次的数字下一秒就旧了。
*/
let clock = 0;
beforeEach(() => {
clock = 0;
vi.spyOn(performance, 'now').mockImplementation(() => (clock += 10));
// 先关再开:关的那一下会把现场清空,每个用例都从干净状态起
setDebugEnabled(false);
setDebugEnabled(true);
});
afterEach(() => {
vi.restoreAllMocks();
setDebugEnabled(false);
});
function agg(over: Partial<AggregateDebug> = {}): AggregateDebug {
return {
zoom: 12,
bbox: { minLng: 113.9, maxLng: 114.3, minLat: 22.4, maxLat: 22.7 },
view: { minLng: 114.0, maxLng: 114.2, minLat: 22.5, maxLat: 22.6 },
bucketCount: 812,
matched: 5000,
used: 4200,
ms: 6.5,
gridPx: 48,
dLng: 0.0003,
dLat: 0.0003,
maxCount: 37,
lng: null,
lat: null,
gx: null,
gy: null,
count: null,
...over,
};
}
describe('关掉调试时总线不记账', () => {
it('事件、聚合读数与开关状态一起归零', () => {
setDebugEnabled(false);
expect(debugEnabled()).toBe(false);
pushDebugEvent('event', 'drag');
setAggregateDebug(agg());
expect(getDebugEvents()).toHaveLength(0);
expect(getAggregateDebug()).toBeNull();
// 重新打开看到的是「从现在起」,不是上一次留下的陈年帧数
setDebugEnabled(true);
expect(getDebugEvents()).toHaveLength(0);
});
it('调用点不必自己加判断:关掉时写入直接落空', () => {
setDebugEnabled(false);
for (let i = 0; i < 300; i += 1) pushDebugEvent('aggregate', `聚合 ${i}`);
expect(getDebugEvents()).toHaveLength(0);
});
});
describe('同名事件在合并窗口内压成一行', () => {
it('同类同文累加次数,换文或过窗另起一行', () => {
// beforeEach 里 clock 起步,每次 push 前进 10ms,三次都在 240ms 窗口内
pushDebugEvent('event', 'mapmove');
pushDebugEvent('event', 'mapmove');
pushDebugEvent('event', 'mapmove');
clock += 300;
pushDebugEvent('event', 'mapmove');
const rows = getDebugEvents();
expect(rows).toHaveLength(2);
expect(rows[0].n).toBe(3);
expect(rows[1].n).toBe(1);
});
it('不同类型不合并;同一行连续写入时细节取最近一条', () => {
pushDebugEvent('event', 'zoomchange', '第一遍');
pushDebugEvent('gesture', 'zoomchange', '第二遍');
expect(getDebugEvents()).toHaveLength(2);
// 合并只跟最后那一行比:隔开了就是两次不同的事,各占一行才对读的人有用
pushDebugEvent('gesture', 'zoomchange', '第三遍');
expect(getDebugEvents()).toHaveLength(2);
expect(getDebugEvents()[1].n).toBe(2);
expect(getDebugEvents()[1].detail).toBe('第三遍');
});
it('时间轴有上限,且留下的是最近的那些', () => {
for (let i = 0; i < 200; i += 1) pushDebugEvent('frame', `第 ${i} 帧`);
const rows = getDebugEvents();
expect(rows).toHaveLength(120);
expect(rows[rows.length - 1].text).toBe('第 199 帧');
expect(rows[0].text).toBe('第 80 帧');
});
it('清空只清时间轴,不动聚合读数', () => {
setAggregateDebug(agg());
pushDebugEvent('layer', '建层');
clearDebugEvents();
expect(getDebugEvents()).toHaveLength(0);
expect(getAggregateDebug()?.bucketCount).toBe(812);
});
});
describe('层注册表', () => {
function rec(id: string, zIndex: number): LayerDebugRecord {
return {
id,
name: `${id} 层`,
zIndex,
kind: 'canvas',
canvas: null,
read: () => ({
built: true,
visible: true,
released: false,
cssW: 800,
cssH: 600,
dpr: 2,
total: 1,
painted: 1,
drawn: 1,
skipped: 0,
lastMs: 0.5,
light: false,
note: '口径',
}),
};
}
// 注册表是模块级的:不清干净的话下一条用例数到的是上一条留下的层
afterEach(() => {
for (const r of getDebugLayers()) unregisterDebugLayer(r.id);
});
it('按叠放次序返回,正是屏幕上从底到顶的那个数法', () => {
registerDebugLayer(rec('casepin', 150));
registerDebugLayer(rec('heat', 110));
registerDebugLayer(rec('cluster', 130));
expect(getDebugLayers().map((r) => r.id)).toEqual(['heat', 'cluster', 'casepin']);
unregisterDebugLayer('cluster');
expect(getDebugLayers().map((r) => r.id)).toEqual(['heat', 'casepin']);
});
it('读数在取的那一刻才计算,所以不会是建层时的旧照片', () => {
let painted = 0;
registerDebugLayer({
...rec('hotspot', 140),
read: () => ({
built: true,
visible: true,
released: false,
cssW: 0,
cssH: 0,
dpr: 1,
total: 3,
painted,
drawn: 1,
skipped: 0,
lastMs: 0,
light: false,
}),
});
expect(getDebugLayers()[0].read().painted).toBe(0);
painted = 7;
expect(getDebugLayers()[0].read().painted).toBe(7);
});
it('关掉调试时把高亮描边收掉,不然画布上留一圈没人负责的粉框', () => {
const canvas = document.createElement('canvas');
canvas.style.outline = '3px solid rgba(255,45,120,.9)';
registerDebugLayer({ ...rec('spotlight', 145), canvas });
setDebugEnabled(false);
expect(canvas.style.outline).toBe('');
});
});
describe('订阅', () => {
it('写入会喊订阅者,注销之后不再被打扰', () => {
const calls: number[] = [];
const off = subscribeDebug(() => calls.push(1));
pushDebugEvent('event', 'moveend');
off();
pushDebugEvent('event', 'dragend');
expect(calls).toHaveLength(1);
});
it('同一行重复写入也要喊一次,否则「×N」看着像卡住', () => {
const seen: string[] = [];
const off = subscribeDebug(() => seen.push(String(getDebugEvents()[0]?.n ?? '-')));
pushDebugEvent('event', 'mapmove');
pushDebugEvent('event', 'mapmove');
off();
expect(seen).toEqual(['1', '2']);
});
});
/**
* 开发者调试视图的数据总线。
*
* 为什么要单独一层:调试视图的读者是"看机制的人",而它要读的东西散在三个地方 ——
* 出帧热路径(viewFrame / 各层 draw)、地图事件(MapStage 的手势 effect)、取数结果
* (runAggregate)。把这些都挂进 zustand 就等于让"每帧一次的落笔计数"驱动 React 重渲染,
* 正是这套界面一直在躲的开销。所以这里和 gesture.ts 一样用模块级状态:
*
* - 写的人(层、MapStage)先问一次 `debugEnabled()`,关掉时一帧只多一个布尔判断;
* - 读的人(面板、覆盖画布)按自己的节律取,不参与地图出帧。
*
* ⚠️ 这里不许 import 任何图层模块:各层会 import 本模块,反向依赖会成环。
* 层的现状由层自己在建层时注册一个 `read()` 闭包进来。
*/
/** 一条调试记录的类型。它决定面板与时间轴上的颜色。 */
export type DebugEventKind = 'event' | 'gesture' | 'frame' | 'aggregate' | 'layer';
export interface DebugEvent {
/** 记下那一刻的 performance.now() */
at: number;
kind: DebugEventKind;
/** 正文。同名同类的事件在合并窗口内只累加 `n`,不新增行 */
text: string;
/** 附带读数,面板把它写在行尾(如 `桶 812 / 耗时 6ms`) */
detail?: string;
/** 合并计数:这一个窗口里同样的事发生了几次 */
n: number;
}
/**
* 同名事件合并的窗口(毫秒)。
*
* 拖动一次会发出上百个 drag/mapmove,逐条记录等于把真正要看的那几行(定档、收尾、
* 聚合发起与回包)冲出缓冲区。合并在同一个窗口内发生多次只写一行并累加 `n` ——
* "这一拍事件有多密"本身就是想看到的信息。
*/
const MERGE_WINDOW_MS = 240;
/** 时间轴保留的条数上限。再多也没法在一屏里读完。 */
const MAX_EVENTS = 120;
/**
* 一层的现状快照。字段都是"看得见的机制":画布有多大、这一帧落没落笔、欠不欠帧。
* `painted`/`total` 分开是因为快拖那一拍只画 0 笔但数据一条不少 —— 那正是本项目最容易被
* 误读成"数字没了=数据没了"的一格。
*/
export interface LayerDebugStats {
/** CustomLayer 是否已创建(四层都是懒建,没建就等于这一层此刻不花钱) */
built: boolean;
visible: boolean;
/** backing store 是否已交还(画布宽高归零) */
released: boolean;
/** 画布 CSS 尺寸与 DPR;热力层没有自己的 2d 画布,这三项为 0 */
cssW: number;
cssH: number;
dpr: number;
/** 本层数据量(桶数 / 盘数 / 形状数) */
total: number;
/** 上一帧真正落笔的个数 */
painted: number;
/** 累计:落笔帧数与被"视图与数据都没变"挡掉的帧数 */
drawn: number;
skipped: number;
/** 上一帧落笔用了多久 */
lastMs: number;
/** 上一帧是不是减载帧(isLightFrame 为真) */
light: boolean;
/** 这一层自己的补充口径(如热力的归一化上限、聚焦层的形状种类) */
note?: string;
}
export interface LayerDebugRecord {
id: string;
/** 类名 + 中文职责,面板直接念这串 */
name: string;
zIndex: number;
kind: 'canvas' | 'webgl';
/** 调试视图描边用;热力层为 null */
canvas: HTMLCanvasElement | null;
read: () => LayerDebugStats;
}
export interface DebugBBox {
minLng: number;
maxLng: number;
minLat: number;
maxLat: number;
}
/** 最近一次聚合的口径。覆盖画布画网格、面板报数都读这一份。 */
export interface AggregateDebug {
zoom: number;
/** 请求用的外扩框 */
bbox: DebugBBox;
/** 真实可见范围(没外扩的) */
view: DebugBBox;
bucketCount: number;
matched: number;
used: number;
ms: number;
gridPx: number;
dLng: number;
dLat: number;
maxCount: number;
/** 桶中心(×1e6)与网格坐标:覆盖画布画格子与错位连线用它 */
lng: Int32Array | null;
lat: Int32Array | null;
gx: Int32Array | null;
gy: Int32Array | null;
count: Int32Array | null;
}
let enabled = false;
let events: DebugEvent[] = [];
let version = 0;
const listeners = new Set<() => void>();
const records = new Map<string, LayerDebugRecord>();
let aggregate: AggregateDebug | null = null;
/**
* 通知订阅者。
*
* 只在"确实有人要看"时才做:没人订阅时数组与版本号照旧维护,代价是几次赋值,
* 而写的人那一头始终只多一个布尔判断。
*/
function bump(): void {
version += 1;
for (const fn of listeners) fn();
}
/** 模块级开关。React 侧的 store 只负责记住用户的选择,真正的门在这里。 */
export function debugEnabled(): boolean {
return enabled;
}
export function setDebugEnabled(on: boolean): void {
if (enabled === on) return;
enabled = on;
if (!on) {
// 关掉时把计数清零:下次打开看到的应当是"从现在起"的现场,而不是一堆陈年帧数
for (const r of records.values()) r.canvas?.style.removeProperty('outline');
events = [];
aggregate = null;
}
bump();
}
/** 写一条记录。关掉调试时立刻返回,调用点不必各自加 if。 */
export function pushDebugEvent(
kind: DebugEventKind,
text: string,
detail?: string,
): void {
if (!enabled) return;
const now = performance.now();
const last = events[events.length - 1];
if (last && last.kind === kind && last.text === text && now - last.at < MERGE_WINDOW_MS) {
last.n += 1;
last.detail = detail ?? last.detail;
// 合并也要让面板跟上:不然"×N"这个数字看着是停住的
bump();
return;
}
events.push({ at: now, kind, text, detail, n: 1 });
if (events.length > MAX_EVENTS) events.splice(0, events.length - MAX_EVENTS);
bump();
}
export function getDebugEvents(): DebugEvent[] {
return events;
}
export function clearDebugEvents(): void {
if (!enabled) return;
events = [];
bump();
}
export function getAggregateDebug(): AggregateDebug | null {
return aggregate;
}
export function setAggregateDebug(next: AggregateDebug): void {
if (!enabled) return;
aggregate = next;
bump();
}
/** 层在建层时注册;`canvas` 传进来只为描边高亮,读数走 `read()`。 */
export function registerDebugLayer(record: LayerDebugRecord): void {
records.set(record.id, record);
bump();
}
export function unregisterDebugLayer(id: string): void {
if (!records.delete(id)) return;
bump();
}
export function getDebugLayers(): LayerDebugRecord[] {
return [...records.values()].sort((a, b) => a.zIndex - b.zIndex);
}
/** 面板与覆盖画布的订阅口。返回注销函数。 */
export function subscribeDebug(fn: () => void): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
/** 快照版本号。useSyncExternalStore 用它做变化判定,避免每次复制数组。 */
export function debugVersion(): number {
return version;
}
/** URL 明确要了调试视图:`?debug=1`。任何构建下都认这一条。 */
export function debugWantedByUrl(): boolean {
return new URLSearchParams(window.location.search).get('debug') === '1';
}
/**
* 调试视图可用吗:开发构建,或 URL 带了 `?debug=1`。
*
* 正式构建默认整块不进界面 —— 业务用户不会看到一个「调试」小牌。
*/
export function debugAvailable(): boolean {
return import.meta.env.DEV || debugWantedByUrl();
}
/** 打开时的初始态:URL 要就直接开,开发构建默认收着(免得每次起服务都得先关一下) */
export function debugInitialOn(): boolean {
return debugWantedByUrl();
}
...@@ -140,7 +140,15 @@ export class CasePinLayer { ...@@ -140,7 +140,15 @@ export class CasePinLayer {
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const surface = new CanvasSurface(); const surface = new CanvasSurface(
{ id: 'casepin', name: 'CasePinLayer · 定位标记层', zIndex: 150 },
() => ({
built: this.layer !== null,
// 这一层没有 setVisible:有没有标记就是它的开关(光圈靠自己的 33ms rAF 出帧)
visible: this.pin !== null,
note: this.pin ? '有标记:这一帧不落笔也要出帧(光圈在转)' : '无标记:不接点名、不占画布',
}),
);
this.surface = surface; this.surface = surface;
const layer = new AMap.CustomLayer(surface.canvas, { const layer = new AMap.CustomLayer(surface.canvas, {
...@@ -163,11 +171,13 @@ export class CasePinLayer { ...@@ -163,11 +171,13 @@ export class CasePinLayer {
this.stopHalo(); this.stopHalo();
this.pin = null; this.pin = null;
this.hasDirty = false; this.hasDirty = false;
this.surface?.setDebugTotal(0);
// release 一次做掉两件事:画布清零(标记当场消失),并把这块全屏 backing store 交还 // release 一次做掉两件事:画布清零(标记当场消失),并把这块全屏 backing store 交还
this.surface?.release(); this.surface?.release();
return; return;
} }
this.pin = { lng: pin.lng, my: mercY(pin.lat), address: pin.address }; this.pin = { lng: pin.lng, my: mercY(pin.lat), address: pin.address };
this.surface?.setDebugTotal(1);
// 牌子上的字只由地址与画布宽度决定,与地图无关:重新定位就重算一次 // 牌子上的字只由地址与画布宽度决定,与地图无关:重新定位就重算一次
this.chipMain.fittedW = -1; this.chipMain.fittedW = -1;
this.chipSub.fittedW = -1; this.chipSub.fittedW = -1;
...@@ -254,7 +264,10 @@ export class CasePinLayer { ...@@ -254,7 +264,10 @@ export class CasePinLayer {
const y = surface.frame.y(pin.my); const y = surface.frame.y(pin.my);
const w = surface.width; const w = surface.width;
const h = surface.height; const h = surface.height;
if (x < -40 || y < -60 || x > w + 40 || y > h + 60) return; if (x < -40 || y < -60 || x > w + 40 || y > h + 60) {
surface.finishPaint(0, false);
return;
}
this.drawHalo(ctx, x, y, now); this.drawHalo(ctx, x, y, now);
const main = this.fitChip(this.chipMain, pin.address, CHIP_FONT_MAIN, w); const main = this.fitChip(this.chipMain, pin.address, CHIP_FONT_MAIN, w);
...@@ -284,6 +297,7 @@ export class CasePinLayer { ...@@ -284,6 +297,7 @@ export class CasePinLayer {
this.dirty[2] = Math.min(w, x1) - this.dirty[0]; this.dirty[2] = Math.min(w, x1) - this.dirty[0];
this.dirty[3] = Math.min(h, y1) - this.dirty[1]; this.dirty[3] = Math.min(h, y1) - this.dirty[1];
this.hasDirty = true; this.hasDirty = true;
surface.finishPaint(1, false);
} }
/** 那一团呼吸柔光的渐变缓存(键是整像素半径) */ /** 那一团呼吸柔光的渐变缓存(键是整像素半径) */
......
...@@ -163,7 +163,14 @@ export class ClusterLayer { ...@@ -163,7 +163,14 @@ export class ClusterLayer {
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const surface = new CanvasSurface(); const surface = new CanvasSurface(
{ id: 'cluster', name: 'ClusterLayer · 聚合数字层', zIndex: 130 },
() => ({
built: this.layer !== null,
visible: this.visible,
note: this.opts.showNumbers ? '写数字' : '只留定位点(数字关)',
}),
);
this.surface = surface; this.surface = surface;
const layer = new AMap.CustomLayer(surface.canvas, { const layer = new AMap.CustomLayer(surface.canvas, {
...@@ -208,6 +215,7 @@ export class ClusterLayer { ...@@ -208,6 +215,7 @@ export class ClusterLayer {
this.recomputeLabels(lng, lat); this.recomputeLabels(lng, lat);
this.recomputeKeep(); this.recomputeKeep();
this.recomputeUnder(); this.recomputeUnder();
this.surface?.setDebugTotal(count.length);
this.scheduleDraw(); this.scheduleDraw();
} }
...@@ -511,6 +519,8 @@ export class ClusterLayer { ...@@ -511,6 +519,8 @@ export class ClusterLayer {
// ctx.font 赋值要重新解析字体串,几百个格子各设一次就是几百次解析。 // ctx.font 赋值要重新解析字体串,几百个格子各设一次就是几百次解析。
// 字号只有两档,相邻格子大多同档,所以按「档变了才设」处理。 // 字号只有两档,相邻格子大多同档,所以按「档变了才设」处理。
let fontWide = -1; let fontWide = -1;
// 调试视图的读数:这一帧真的落了几笔。整数自增,不开调试也没成本
let painted = 0;
for (let i = 0; i < this.count.length; i += 1) { for (let i = 0; i < this.count.length; i += 1) {
const x = frame.x(this.lngDeg[i]); const x = frame.x(this.lngDeg[i]);
...@@ -542,6 +552,7 @@ export class ClusterLayer { ...@@ -542,6 +552,7 @@ export class ClusterLayer {
ctx.fillStyle = this.ink[i]; ctx.fillStyle = this.ink[i];
ctx.fill(); ctx.fill();
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
painted += 1;
continue; continue;
} }
...@@ -578,7 +589,9 @@ export class ClusterLayer { ...@@ -578,7 +589,9 @@ export class ClusterLayer {
ctx.fillStyle = this.ink[i]; ctx.fillStyle = this.ink[i];
ctx.fillText(label, x, y + 0.5); ctx.fillText(label, x, y + 0.5);
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
painted += 1;
} }
surface.finishPaint(painted, light);
} }
/** /**
......
import { HEAT_GRADIENT } from './palette'; import { HEAT_GRADIENT } from './palette';
import { resolveHeatMapCtor } from './loadAmap'; import { resolveHeatMapCtor } from './loadAmap';
import { Frame, mercY } from './viewFrame'; import { Frame, mercY } from './viewFrame';
import { registerDebugLayer, unregisterDebugLayer } from '../debug/debugBus';
export interface HeatLayerStyle { export interface HeatLayerStyle {
/** 热力扩散半径,像素 */ /** 热力扩散半径,像素 */
...@@ -117,7 +118,32 @@ export class HeatLayer { ...@@ -117,7 +118,32 @@ export class HeatLayer {
private inViewBuf = new Int32Array(0); private inViewBuf = new Int32Array(0);
private allBuf = new Int32Array(0); private allBuf = new Int32Array(0);
constructor(private readonly map: AMap.Map) {} constructor(private readonly map: AMap.Map) {
// 调试视图里这一层报的是"喂进去多少个权重点"。帧计数留空是诚实的:
// 底色由高德自己的 WebGL 场景逐帧重绘,没有我们这一侧的开帧判定可数。
registerDebugLayer({
id: 'heat',
name: 'AMap.HeatMap · 热力底色层',
zIndex: 110,
kind: 'webgl',
canvas: null,
read: () => ({
built: this.heat !== null,
visible: this.visible,
released: false,
cssW: 0,
cssH: 0,
dpr: 0,
total: this.count,
painted: this.heat && this.visible ? this.count : 0,
drawn: 0,
skipped: 0,
lastMs: 0,
light: false,
note: `归一化上限 ${Math.round(this.maxWeight)} · 半径 ${this.style.radius}px · 逐帧由 WebGL 重绘`,
}),
});
}
private ensure(): AMap.HeatMap { private ensure(): AMap.HeatMap {
if (!this.heat) { if (!this.heat) {
...@@ -260,6 +286,7 @@ export class HeatLayer { ...@@ -260,6 +286,7 @@ export class HeatLayer {
} }
destroy() { destroy() {
unregisterDebugLayer('heat');
this.heat?.setMap(null); this.heat?.setMap(null);
this.heat?.destroy(); this.heat?.destroy();
this.heat = null; this.heat = null;
......
...@@ -216,7 +216,14 @@ export class HotspotLayer { ...@@ -216,7 +216,14 @@ export class HotspotLayer {
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const surface = new CanvasSurface(); const surface = new CanvasSurface(
{ id: 'hotspot', name: 'HotspotLayer · 黑点范围盘层', zIndex: 140 },
() => ({
built: this.layer !== null,
visible: this.visible,
note: this.opts.active === null ? '未选中任何一盘' : `选中第 ${this.opts.active + 1} 盘`,
}),
);
this.surface = surface; this.surface = surface;
const layer = new AMap.CustomLayer(surface.canvas, { const layer = new AMap.CustomLayer(surface.canvas, {
...@@ -270,6 +277,7 @@ export class HotspotLayer { ...@@ -270,6 +277,7 @@ export class HotspotLayer {
], ],
}; };
}); });
this.surface?.setDebugTotal(rows.length);
this.scheduleDraw(); this.scheduleDraw();
} }
...@@ -378,6 +386,8 @@ export class HotspotLayer { ...@@ -378,6 +386,8 @@ export class HotspotLayer {
// ⚠️ 只收「画」,不收「算」:屏幕坐标与命中半径照旧写进缓存, // ⚠️ 只收「画」,不收「算」:屏幕坐标与命中半径照旧写进缓存,
// 松手后紧接着的那一次点击仍按盘的真实范围命中,不会出现「看不见就点不动」。 // 松手后紧接着的那一次点击仍按盘的真实范围命中,不会出现「看不见就点不动」。
const light = isLightFrame(); const light = isLightFrame();
// 调试视图的读数:这一帧真的落了几笔(与聚合层同一口径 —— 出屏与减载的那些都不算)
let painted = 0;
ctx.textAlign = 'center'; ctx.textAlign = 'center';
ctx.textBaseline = 'middle'; ctx.textBaseline = 'middle';
...@@ -501,7 +511,9 @@ export class HotspotLayer { ...@@ -501,7 +511,9 @@ export class HotspotLayer {
ctx.fillStyle = '#ffffff'; ctx.fillStyle = '#ffffff';
ctx.fillText(p.rankLabel, cx + cw / 2, cy + ch / 2 + 0.5); ctx.fillText(p.rankLabel, cx + cw / 2, cy + ch / 2 + 0.5);
painted += 1;
} }
surface.finishPaint(painted, light);
} }
/** 命中行的下标,未命中返回 -1。缓存的屏幕坐标由 draw 维护,与 ClusterLayer 同一套做法 */ /** 命中行的下标,未命中返回 -1。缓存的屏幕坐标由 draw 维护,与 ClusterLayer 同一套做法 */
......
...@@ -324,7 +324,14 @@ export class SpotlightLayer { ...@@ -324,7 +324,14 @@ export class SpotlightLayer {
private ensure() { private ensure() {
if (this.layer) return; if (this.layer) return;
const surface = new CanvasSurface(); const surface = new CanvasSurface(
{ id: 'spotlight', name: 'SpotlightLayer · 聚焦形状层', zIndex: 145 },
() => ({
built: this.layer !== null,
visible: this.visible,
note: `形状 ${this.variant} · 方格 ${Math.round(this.cellPx)}px`,
}),
);
this.surface = surface; this.surface = surface;
const layer = new AMap.CustomLayer(surface.canvas, { const layer = new AMap.CustomLayer(surface.canvas, {
...@@ -354,6 +361,7 @@ export class SpotlightLayer { ...@@ -354,6 +361,7 @@ export class SpotlightLayer {
// 层已经存在时照旧要点名 —— begin 会把那一片像素清空,形状才是真的收掉了。 // 层已经存在时照旧要点名 —— begin 会把那一片像素清空,形状才是真的收掉了。
this.units = []; this.units = [];
this.boxes = []; this.boxes = [];
this.surface?.setDebugTotal(0);
this.scheduleDraw(); this.scheduleDraw();
return; return;
} }
...@@ -368,6 +376,7 @@ export class SpotlightLayer { ...@@ -368,6 +376,7 @@ export class SpotlightLayer {
x1: 0, x1: 0,
y1: 0, y1: 0,
})); }));
this.surface?.setDebugTotal(this.units.length);
this.scheduleDraw(); this.scheduleDraw();
} }
...@@ -707,6 +716,8 @@ export class SpotlightLayer { ...@@ -707,6 +716,8 @@ export class SpotlightLayer {
box.x1 = Number.isFinite(x1) ? x1 + HIT_PAD : 0; box.x1 = Number.isFinite(x1) ? x1 + HIT_PAD : 0;
box.y1 = Number.isFinite(y1) ? y1 + HIT_PAD : 0; box.y1 = Number.isFinite(y1) ? y1 + HIT_PAD : 0;
} }
// 这一层按"档"报落笔数:一层里一格一格地铺,逐格计数不值得为调试视图去动热点循环
surface.finishPaint(this.units.length, light);
} }
/** 牌子高度:两行还是单行只由「有没有第二行读数」决定 */ /** 牌子高度:两行还是单行只由「有没有第二行读数」决定 */
......
import { GRID } from '../aggregate/grid'; import { GRID } from '../aggregate/grid';
import { M_PER_EQUATOR } from './hotspotGeometry'; import { M_PER_EQUATOR } from './hotspotGeometry';
import {
debugEnabled,
registerDebugLayer,
unregisterDebugLayer,
type LayerDebugStats,
} from '../debug/debugBus';
/** /**
* 自绘层的每帧开场:视图变化判定、画布尺寸对齐、投影基准。 * 自绘层的每帧开场:视图变化判定、画布尺寸对齐、投影基准。
...@@ -212,7 +218,26 @@ export class CanvasSurface { ...@@ -212,7 +218,26 @@ export class CanvasSurface {
/** 视图没变但数据/选项变了,下一帧仍要重画 */ /** 视图没变但数据/选项变了,下一帧仍要重画 */
private dirty = true; private dirty = true;
constructor() { /* 调试视图的读数。只有 debugEnabled() 为真时才写,见 debug/debugBus.ts。
帧计数与耗时用来回答"停着不动到底有没有在画";painted 与 total 分开记,
是因为减载那一帧 total 一条不少而 painted 是 0 —— 那正是最容易读成"数据没了"的一格。 */
private dbgDrawn = 0;
private dbgSkipped = 0;
private dbgLastMs = 0;
private dbgPainted = 0;
private dbgTotal = 0;
private dbgLight = false;
private dbgT0 = 0;
private readonly debugId: string | null;
/**
* @param meta 层身份。传了它才会向调试视图注册一条记录(调试面板与画布描边用它)。
* @param extras 这一层才知道的部分:建没建、收没收起、以及自己那句口径说明。
*/
constructor(
meta?: { id: string; name: string; zIndex: number },
extras?: () => Partial<LayerDebugStats> & { note?: string },
) {
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.style.position = 'absolute'; canvas.style.position = 'absolute';
canvas.style.left = '0'; canvas.style.left = '0';
...@@ -220,6 +245,31 @@ export class CanvasSurface { ...@@ -220,6 +245,31 @@ export class CanvasSurface {
// 必须让地图继续接收鼠标事件,否则 canvas 会把拖动、缩放全部吃掉 // 必须让地图继续接收鼠标事件,否则 canvas 会把拖动、缩放全部吃掉
canvas.style.pointerEvents = 'none'; canvas.style.pointerEvents = 'none';
this.canvas = canvas; this.canvas = canvas;
this.debugId = meta?.id ?? null;
if (meta) {
registerDebugLayer({
id: meta.id,
name: meta.name,
zIndex: meta.zIndex,
kind: 'canvas',
canvas,
read: () => ({
built: true,
visible: true,
released: canvas.width === 0,
cssW: this.w < 0 ? 0 : this.w,
cssH: this.h < 0 ? 0 : this.h,
dpr: this.dpr < 0 ? 0 : this.dpr,
total: this.dbgTotal,
painted: this.dbgPainted,
drawn: this.dbgDrawn,
skipped: this.dbgSkipped,
lastMs: this.dbgLastMs,
light: this.dbgLight,
...extras?.(),
}),
});
}
} }
/** /**
...@@ -237,6 +287,24 @@ export class CanvasSurface { ...@@ -237,6 +287,24 @@ export class CanvasSurface {
this.dirty = true; this.dirty = true;
} }
/** 本层数据量。喂数据那一次写一次,帧里不再碰(关掉调试时是一次整数赋值,可忽略) */
setDebugTotal(n: number): void {
this.dbgTotal = n;
}
/**
* 这一帧落笔完了:记下实际画了几笔、是不是减载帧、以及这一帧花了多久。
*
* 各层在自己的 draw 末尾叫一次。耗时用 performance.now() 夹一下,
* 只在调试开着时取,生产路径上这两次读数不必付。
*/
finishPaint(painted: number, light: boolean): void {
this.dbgPainted = painted;
this.dbgLight = light;
if (!debugEnabled()) return;
this.dbgLastMs = performance.now() - this.dbgT0;
}
/** /**
* 每帧开场。 * 每帧开场。
* *
...@@ -279,10 +347,18 @@ export class CanvasSurface { ...@@ -279,10 +347,18 @@ export class CanvasSurface {
dpr === this.dpr; dpr === this.dpr;
if (unchanged) { if (unchanged) {
// 动画层继续用上一帧的投影基准:视图一动没动,原点与比例尺还是那一套 // 动画层继续用上一帧的投影基准:视图一动没动,原点与比例尺还是那一套
if (!animated || !this.ctx) return null; if (!animated || !this.ctx) {
if (debugEnabled()) this.dbgSkipped += 1;
return null;
}
return { frame: this.frame, clearedAll: false }; return { frame: this.frame, clearedAll: false };
} }
if (debugEnabled()) {
this.dbgDrawn += 1;
this.dbgPainted = 0;
this.dbgT0 = performance.now();
}
this.dirty = false; this.dirty = false;
this.zoom = zoom; this.zoom = zoom;
this.lng = lng; this.lng = lng;
...@@ -337,6 +413,8 @@ export class CanvasSurface { ...@@ -337,6 +413,8 @@ export class CanvasSurface {
this.canvas.height = 0; this.canvas.height = 0;
this.w = -1; this.w = -1;
this.h = -1; this.h = -1;
// 屏上一颗像素都不剩了:调试视图里那一层的"落笔数"跟着归零,别留着上一屏的读数
this.dbgPainted = 0;
} }
this.dirty = true; this.dirty = true;
} }
...@@ -364,6 +442,7 @@ export class CanvasSurface { ...@@ -364,6 +442,7 @@ export class CanvasSurface {
} }
destroy(): void { destroy(): void {
if (this.debugId) unregisterDebugLayer(this.debugId);
this.ctx = null; this.ctx = null;
this.canvas.width = 0; this.canvas.width = 0;
this.canvas.height = 0; this.canvas.height = 0;
......
...@@ -15,6 +15,7 @@ import type { ...@@ -15,6 +15,7 @@ import type {
StatsResult, StatsResult,
} from '@/features/heatmap/aggregate/types'; } from '@/features/heatmap/aggregate/types';
import type { ImportManifest } from '@/features/heatmap/data/importedDb'; import type { ImportManifest } from '@/features/heatmap/data/importedDb';
import { debugInitialOn } from '@/features/heatmap/debug/debugBus';
import { DEFAULT_BASEMAP } from '@/features/heatmap/map/palette'; import { DEFAULT_BASEMAP } from '@/features/heatmap/map/palette';
import { DEFAULT_HEAT_STYLE } from '@/features/heatmap/map/HeatLayer'; import { DEFAULT_HEAT_STYLE } from '@/features/heatmap/map/HeatLayer';
import { buildPointRoster } from '@/features/heatmap/aggregate/viewSnapshot'; import { buildPointRoster } from '@/features/heatmap/aggregate/viewSnapshot';
...@@ -499,6 +500,17 @@ interface HeatmapState { ...@@ -499,6 +500,17 @@ interface HeatmapState {
*/ */
legendHidden: boolean; legendHidden: boolean;
/**
* 开发者调试视图(48px 聚合网格、格子与桶均值的错位、请求范围框、各层画布、事件时序)。
*
* ⚠️ 这里存的只是"用户要不要看"。每帧读的那一头(层里的埋点、MapStage 的事件日志)
* 走的是 `debug/debugBus` 那个模块级布尔,不订阅 store —— 理由同 gesture.ts:
* 把界面状态机挂进绘制热路径,等于让观测量自己改变被测对象。
*
* 开关只在开发构建,或 URL 带 `?debug=1` 时出现(判据见 debugAvailable)。
*/
debugOn: boolean;
/* 性能观测 */ /* 性能观测 */
perf: PerfSnapshot; perf: PerfSnapshot;
...@@ -594,6 +606,8 @@ interface HeatmapState { ...@@ -594,6 +606,8 @@ interface HeatmapState {
showDock: () => void; showDock: () => void;
/** 密度图例收成小牌 / 摊开 */ /** 密度图例收成小牌 / 摊开 */
toggleLegend: () => void; toggleLegend: () => void;
/** 开发者调试视图开 / 关(同步写进 debugBus 那个模块级开关) */
toggleDebug: () => void;
patchPerf: (p: Partial<PerfSnapshot>) => void; patchPerf: (p: Partial<PerfSnapshot>) => void;
} }
...@@ -674,6 +688,8 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({ ...@@ -674,6 +688,8 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({
dockHidden: false, dockHidden: false,
legendHidden: true, legendHidden: true,
debugOn: debugInitialOn(),
perf: { perf: {
aggregateMs: 0, aggregateMs: 0,
statsMs: 0, statsMs: 0,
...@@ -961,6 +977,12 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({ ...@@ -961,6 +977,12 @@ export const useHeatmapStore = create<HeatmapState>((set, get) => ({
toggleLegend: () => set((s) => ({ legendHidden: !s.legendHidden })), toggleLegend: () => set((s) => ({ legendHidden: !s.legendHidden })),
/** /**
* 调试视图开关。状态位只改这一格,模块级总线由 DebugHud 那条 effect 同步 ——
* 一个写入口,避免两处各设一次而互相打架。
*/
toggleDebug: () => set((s) => ({ debugOn: !s.debugOn })),
/**
* 读数上报:数值一个都没动就当无事发生。 * 读数上报:数值一个都没动就当无事发生。
* *
* 原来这里无条件 `perf: { ...perf, ...p }`,于是每次聚合、每次取数都会换一个新对象 —— * 原来这里无条件 `perf: { ...perf, ...p }`,于是每次聚合、每次取数都会换一个新对象 ——
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!