DebugCanvas.ts 17 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
/**
 * 调试覆盖画布:把"看不见的机制"画在地图上。
 *
 * 为什么是又一块 canvas,而不是复用某个层的画布:这一层不参与地图出帧,也不属于任何图层,
 * 它只说事实。它自己走一条 rAF,视图与调试内容都没变时整帧跳过 —— 和四个自绘层同一个规矩,
 * 这样"调试视图本身在给页面添多少活"这件事也是可观察的(面板上报它自己的落笔/跳过帧数)。
 *
 * 投影复用 `Frame`:与四个层问同一个问题(每帧一次 lngLatToContainer 定原点 + 两次乘加),
 * 而且用的是同一份 `APP_SCALE`,所以画出来的格子和层里画的数字一定对得上。
 * 要是这里自己另写一套换算,就会出现"调试线跟真格子差几像素"那种最害人的假证据。
 */
import { Frame, mercY } from '@hm/map-overlay';
import { APP_SCALE } from '../map/appOverlay';
import { mapGesture } from '../map/gesture';
import { GRID } from '../aggregate/grid';
import { debugVersion, getAggregateDebug, getDebugLayers, type AggregateDebug } from './debugBus';

export interface DebugCanvasOptions {
  /** 48px 聚合网格的经纬度分界线 */
  grid: boolean;
  /** 每个桶:自己那一格的方框 + 格内案件均值(数字实际落点) */
  buckets: boolean;
  /** 聚合请求用的外扩框 vs 真实视口 */
  requestBox: boolean;
  /** 每帧唯一一次官方投影的那个锚点 */
  anchor: boolean;
  /** 悬停某一图层行时高亮它那块画布;null 不高亮 */
  highlight: string | null;
}

export const DEFAULT_DEBUG_OPTIONS: DebugCanvasOptions = {
  grid: true,
  buckets: true,
  requestBox: true,
  anchor: true,
  highlight: null,
};

const INK = {
  grid: 'rgba(10, 201, 245, 0.22)',
  gridMajor: 'rgba(10, 201, 245, 0.42)',
  cell: 'rgba(10, 201, 245, 0.55)',
  mean: '#ff2d78',
  view: 'rgba(255, 255, 255, 0.85)',
  request: '#fcc929',
  anchor: '#28a7e1',
  text: 'rgba(16, 24, 40, 0.9)',
  textHalo: 'rgba(255, 255, 255, 0.9)',
  warn: 'rgba(255, 45, 120, 0.9)',
};

const FONT = '10px "SF Mono", Consolas, Menlo, monospace';

/** 一帧的现场:给面板复用的读数,避免面板再去问地图 */
export interface DebugFrameReadout {
  zoom: number;
  lng: number;
  lat: number;
  pxPerDegLng: number;
  pxPerMeter: number;
  cssW: number;
  cssH: number;
  dpr: number;
  gesture: boolean;
  light: boolean;
  painted: number;
  skipped: number;
}

export class DebugCanvas {
  readonly canvas: HTMLCanvasElement;

  private ctx: CanvasRenderingContext2D | null = null;
  private readonly frame = new Frame();
  private opts: DebugCanvasOptions = { ...DEFAULT_DEBUG_OPTIONS };
  private raf = 0;
  private painted = 0;
  private skipped = 0;
  private last: DebugFrameReadout | null = null;

  /** 上一次开帧的判定依据。跟 Frame 用的是同一批数:缩放、中心、尺寸、DPR */
  private seenZoom = Number.NaN;
  private seenLng = Number.NaN;
  private seenLat = Number.NaN;
  private seenW = -1;
  private seenH = -1;
  private seenDpr = -1;
  /** 调试内容(事件、聚合快照)换了也得出帧,按总线版本号判 */
  private seenVersion = -1;
  private seenOptsKey = '';

  constructor(
    private readonly map: AMap.Map,
    host: HTMLElement,
  ) {
    const canvas = document.createElement('canvas');
    canvas.className = 'hm-debug__canvas';
    canvas.style.position = 'absolute';
    canvas.style.inset = '0';
    // 与四个自绘层同一条规矩:这块画布不许把拖动、缩放、点击吃掉
    canvas.style.pointerEvents = 'none';
    host.appendChild(canvas);
    this.canvas = canvas;
  }

  setOptions(next: Partial<DebugCanvasOptions>): void {
    this.opts = { ...this.opts, ...next };
  }

  /** 面板随时取这一帧的现场读数 */
  readout(): DebugFrameReadout | null {
    return this.last;
  }

  stats(): { painted: number; skipped: number } {
    return { painted: this.painted, skipped: this.skipped };
  }

  start(): void {
    if (this.raf) return;
    // 尺寸先归零:让第一次 open 一定判成"变了",第一帧必然落笔
    this.seenW = -1;
    const step = () => {
      this.raf = requestAnimationFrame(step);
      this.tick();
    };
    this.raf = requestAnimationFrame(step);
  }

  stop(): void {
    if (this.raf) cancelAnimationFrame(this.raf);
    this.raf = 0;
    this.clearHighlight();
    // 下次 start 一定要出一帧:这一帧的判定依据全部作废
    this.seenW = -1;
    const ctx = this.ctx;
    if (ctx) {
      // 变换还是 DPR 那一档,按设备像素整块擦干净再交还给页面
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
  }

  destroy(): void {
    this.stop();
    this.canvas.remove();
    this.ctx = null;
  }

  /**
   * 每帧开场。视图与调试内容都没变就整帧跳过 —— 空闲时省下的是这一层自己的整屏落笔。
   *
   * @returns null 表示这一帧不必重画
   */
  private begin(): Frame | null {
    const size = this.map.getSize();
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const center = this.map.getCenter();
    const zoom = this.map.getZoom();
    const lng = center.getLng();
    const lat = center.getLat();
    const version = debugVersion();
    const optsKey = `${this.opts.grid}${this.opts.buckets}${this.opts.requestBox}${this.opts.anchor}${this.opts.highlight}`;

    const unchanged =
      zoom === this.seenZoom &&
      lng === this.seenLng &&
      lat === this.seenLat &&
      size.width === this.seenW &&
      size.height === this.seenH &&
      dpr === this.seenDpr &&
      version === this.seenVersion &&
      optsKey === this.seenOptsKey;
    if (unchanged) {
      this.skipped += 1;
      return null;
    }

    this.seenZoom = zoom;
    this.seenLng = lng;
    this.seenLat = lat;
    this.seenW = size.width;
    this.seenH = size.height;
    this.seenDpr = dpr;
    this.seenVersion = version;
    this.seenOptsKey = optsKey;
    this.painted += 1;

    const ctx = this.ctx ?? this.canvas.getContext('2d');
    if (!ctx) return null;
    this.ctx = ctx;

    const px = Math.round(size.width * dpr);
    const py = Math.round(size.height * dpr);
    if (this.canvas.width !== px || this.canvas.height !== py) {
      this.canvas.width = px;
      this.canvas.height = py;
      this.canvas.style.width = `${size.width}px`;
      this.canvas.style.height = `${size.height}px`;
    }
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, size.width, size.height);

    this.frame.set(this.map, zoom, lng, lat, APP_SCALE);
    this.last = {
      zoom,
      lng,
      lat,
      pxPerDegLng: this.frame.pxPerDegLng,
      pxPerMeter: this.frame.pxPerMeter,
      cssW: size.width,
      cssH: size.height,
      dpr,
      gesture: mapGesture.active(),
      light: mapGesture.light(),
      painted: this.painted,
      skipped: this.skipped,
    };
    return this.frame;
  }

  private tick(): void {
    const frame = this.begin();
    const agg = getAggregateDebug();
    if (!frame || !this.ctx) return;
    const size = this.map.getSize();
    const w = size.width;
    const h = size.height;

    this.applyHighlight();
    if (this.opts.requestBox) this.drawBoxes(frame, w, h, agg);
    if (agg && this.opts.grid) this.drawGrid(frame, w, h, agg);
    if (agg && this.opts.buckets) this.drawBuckets(frame, w, h, agg);
    if (this.opts.anchor) this.drawAnchor(frame, w, h);
    this.drawStateStrip(w, h);
  }

  /**
   * 请求框与真实视口框。
   *
   * 这两只框的差就是拖动时那段"提前算好的缓冲":外扩 0.5 倍视口,所以框比屏幕大一圈。
   * 框画在屏幕外的那一段看不见 —— 于是在它与屏幕边缘相交处补一个箭头与一句说明,
   * 不然读起来像"数据只画到这里为止"。
   */
  private drawBoxes(frame: Frame, w: number, h: number, agg: AggregateDebug | null): void {
    // 调试画布本身铺满容器,所以视口框就是画布边缘那一圈
    this.strokeRect(0, 0, w, h, INK.view, 1.5, []);
    if (agg) {
      const x0 = frame.x(agg.bbox.minLng);
      const x1 = frame.x(agg.bbox.maxLng);
      // 纬度要过 mercY:格子的 y 方向是墨卡托,直接按度数线性映射会对不上层里的位置
      const yTop = frame.y(mercY(agg.bbox.maxLat));
      const yBot = frame.y(mercY(agg.bbox.minLat));
      this.strokeRect(x0, yTop, x1 - x0, yBot - yTop, INK.request, 1.4, [6, 4]);
      if (x0 < 0 || yTop < 0 || x1 > w || yBot > h) {
        this.label(
          8,
          44,
          `黄色虚框 = 聚合请求范围(视口外扩 ${GRID.viewportPadRatio} 倍),比屏幕大一圈`,
          INK.request,
        );
      }
    }
    this.label(
      8,
      30,
      `白框 = 真实视口 ${Math.round(w)}×${Math.round(h)},出屏的格子不落笔`,
      INK.view,
    );
  }

  private strokeRect(
    x: number,
    y: number,
    w: number,
    h: number,
    color: string,
    lineWidth: number,
    dash: number[],
  ): void {
    if (!Number.isFinite(x) || !Number.isFinite(y)) return;
    const ctx = this.ctx!;
    ctx.save();
    ctx.setLineDash(dash);
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    ctx.strokeRect(x, y, w, h);
    ctx.restore();
  }

  /**
   * 网格的分界线。
   *
   * 格子的边界在**经纬度**里等分(aggregate/grid.ts 的 toGrid:gx = floor((lng+180)/dLng)),
   * 而落到屏幕上映射要过 mercY,所以纬线之间的间距会随纬度慢慢变 —— 这不是画歪了,
   * 正是"网格按度分、投影按墨卡托走"这件事的现场。
   */
  private drawGrid(frame: Frame, w: number, h: number, agg: AggregateDebug): void {
    const ctx = this.ctx!;
    const b = agg.view;
    ctx.save();
    ctx.lineWidth = 1;
    // 经线
    const k0 = Math.floor((b.minLng + 180) / agg.dLng) - 1;
    const k1 = Math.ceil((b.maxLng + 180) / agg.dLng) + 1;
    for (let k = k0; k <= k1; k += 1) {
      const x = Math.round(frame.x(k * agg.dLng - 180)) + 0.5;
      if (x < -2 || x > w + 2) continue;
      ctx.strokeStyle = k % 5 === 0 ? INK.gridMajor : INK.grid;
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, h);
      ctx.stroke();
    }
    // 纬线
    const j0 = Math.floor((b.minLat + 90) / agg.dLat) - 1;
    const j1 = Math.ceil((b.maxLat + 90) / agg.dLat) + 1;
    for (let j = j0; j <= j1; j += 1) {
      const y = frame.y(mercY(j * agg.dLat - 90));
      if (y < -2 || y > h + 2) continue;
      ctx.strokeStyle = j % 5 === 0 ? INK.gridMajor : INK.grid;
      ctx.beginPath();
      ctx.moveTo(0, Math.round(y) + 0.5);
      ctx.lineTo(w, Math.round(y) + 0.5);
      ctx.stroke();
    }
    ctx.restore();
  }

  /**
   * 每个桶两样东西:它负责的那一格(方框),和数字实际落笔的位置(均值点)。
   *
   * 这两点不重合是设计使然:桶中心取的是**格内所有案件的经纬度均值**,不是格子几何中心。
   * 一格只有一起时两者重合(看起来就是"散点"),多起时均值偏向案件扎堆的那一侧。
   * 中间那条连线就是"数字为什么不在格子正中央"的答案,也是注释里反复警告的
   * "两层各用一套网格会错位几十像素"的可视化版本。
   */
  private drawBuckets(frame: Frame, w: number, h: number, agg: AggregateDebug): void {
    const ctx = this.ctx!;
    const n = agg.bucketCount;
    if (!agg.lng || !agg.lat || !agg.gx || !agg.gy || !agg.count || agg.gx.length !== n) return;
    const showText = agg.gridPx >= 26;
    ctx.save();
    ctx.lineWidth = 1;
    for (let i = 0; i < n; i += 1) {
      const lng = agg.lng[i] / 1e6;
      const lat = agg.lat[i] / 1e6;
      const x = frame.x(lng);
      const y = frame.y(mercY(lat));
      if (x < -60 || y < -60 || x > w + 60 || y > h + 60) continue;

      const gx = agg.gx[i];
      const gy = agg.gy[i];
      // 这一格的四个角。y 方向过 mercY,所以方框上下边在屏幕上的间距与 x 方向不完全等宽
      const left = frame.x(gx * agg.dLng - 180);
      const right = frame.x((gx + 1) * agg.dLng - 180);
      const south = frame.y(mercY(gy * agg.dLat - 90));
      const north = frame.y(mercY((gy + 1) * agg.dLat - 90));
      const top = Math.min(south, north);
      const cellW = right - left;
      const cellH = Math.max(south, north) - top;

      ctx.strokeStyle = INK.cell;
      ctx.strokeRect(left, top, cellW, cellH);

      // 格子几何中心:空心小圈
      const mcx = left + cellW / 2;
      const mcy = top + cellH / 2;
      ctx.beginPath();
      ctx.arc(mcx, mcy, 2, 0, Math.PI * 2);
      ctx.strokeStyle = INK.cell;
      ctx.stroke();

      // 均值点 = 数字真正落笔处:实心十字 + 与几何中心的连线
      const off = Math.hypot(x - mcx, y - mcy);
      if (off > 1.5) {
        ctx.beginPath();
        ctx.moveTo(mcx, mcy);
        ctx.lineTo(x, y);
        ctx.strokeStyle = INK.mean;
        ctx.stroke();
      }
      ctx.beginPath();
      ctx.moveTo(x - 4, y);
      ctx.lineTo(x + 4, y);
      ctx.moveTo(x, y - 4);
      ctx.lineTo(x, y + 4);
      ctx.strokeStyle = INK.mean;
      ctx.stroke();

      if (showText) {
        const c = String(agg.count[i]);
        ctx.font = FONT;
        ctx.textAlign = 'left';
        ctx.textBaseline = 'middle';
        ctx.lineWidth = 3;
        ctx.strokeStyle = INK.textHalo;
        ctx.strokeText(c, x + 6, y);
        ctx.fillStyle = INK.mean;
        ctx.fillText(c, x + 6, y);
      }
    }
    ctx.restore();
  }

  /**
   * 投影锚点:每帧唯一一次问地图的那个屏幕位置。
   *
   * 它是地图中心换算到屏幕上的像素,之后每个点只剩两次乘加。把它画出来,
   * "描图纸不会跟着地图动,靠的是每帧重新问一次原点"这件事就不是口头解释了。
   * 锚点通常正好落在屏幕正中;地图容器带偏移、或有控件占位时它会偏 —— 那正是要看得到的情形。
   */
  private drawAnchor(frame: Frame, w: number, h: number): void {
    const ctx = this.ctx!;
    const readout = this.last!;
    // 中心点过 frame.x / frame.y 必然回到原点,所以这里问的就是"高德那一次换算给的位置"
    const cx = frame.x(readout.lng);
    const cy = frame.y(mercY(readout.lat));
    ctx.save();
    ctx.strokeStyle = INK.anchor;
    ctx.lineWidth = 1;
    ctx.setLineDash([3, 4]);
    ctx.beginPath();
    ctx.moveTo(0, cy);
    ctx.lineTo(w, cy);
    ctx.moveTo(cx, 0);
    ctx.lineTo(cx, h);
    ctx.stroke();
    ctx.setLineDash([]);
    ctx.beginPath();
    ctx.arc(cx, cy, 6, 0, Math.PI * 2);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(cx - 10, cy);
    ctx.lineTo(cx + 10, cy);
    ctx.moveTo(cx, cy - 10);
    ctx.lineTo(cx, cy + 10);
    ctx.stroke();
    ctx.restore();
    this.label(cx + 12, cy - 12, '投影锚点:本帧唯一一次 lngLatToContainer(中心)', INK.anchor);
  }

  /** 顶部状态条:一眼看出这一帧处在"空闲 / 手势中 / 快拖减载"哪一档 */
  private drawStateStrip(w: number, h: number): void {
    const ctx = this.ctx!;
    const light = mapGesture.light();
    const busy = mapGesture.active();
    const color = light ? INK.warn : busy ? INK.request : INK.anchor;
    const text = light
      ? '减载帧:自绘层不落笔(屏幕坐标与命中半径照算)'
      : busy
        ? '手势中:这一帧按全量画(慢速拖动不减载)'
        : '空闲:视图与本层都没变 → 整帧跳过';
    ctx.save();
    ctx.fillStyle = 'rgba(255,255,255,.86)';
    ctx.fillRect(0, 0, w, 16);
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, 3, 16);
    ctx.font = FONT;
    ctx.textAlign = 'left';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = INK.text;
    ctx.fillText(text, 8, 8);
    ctx.restore();
    void h;
  }

  private label(x: number, y: number, text: string, color: string): void {
    const ctx = this.ctx!;
    ctx.save();
    ctx.font = FONT;
    ctx.textAlign = 'left';
    ctx.textBaseline = 'middle';
    ctx.lineWidth = 3;
    ctx.strokeStyle = INK.textHalo;
    ctx.strokeText(text, x, y);
    ctx.fillStyle = color;
    ctx.fillText(text, x, y);
    ctx.restore();
  }

  /**
   * 高亮某一层的画布。
   *
   * 四张自绘画布长得一模一样(同一尺寸、同一位置、都透明),肉眼分不出屏幕上这一块像素
   * 归谁。描边写在 DOM 上而不是画在这块调试画布里,因为要描的那张布本身就在地图容器内,
   * 我们这块布压在它上面 —— 画在自己这里只能画个"外框的位置",不如直接给它加 outline。
   */
  private applyHighlight(): void {
    const target = this.opts.highlight;
    for (const rec of getDebugLayers()) {
      if (!rec.canvas) continue;
      if (rec.id === target) {
        rec.canvas.style.outline = '3px solid rgba(255, 45, 120, 0.9)';
        rec.canvas.style.outlineOffset = '-3px';
      } else if (rec.canvas.style.outline) {
        rec.canvas.style.outline = '';
        rec.canvas.style.outlineOffset = '';
      }
    }
  }

  private clearHighlight(): void {
    for (const rec of getDebugLayers()) {
      if (rec.canvas && rec.canvas.style.outline) {
        rec.canvas.style.outline = '';
        rec.canvas.style.outlineOffset = '';
      }
    }
  }
}