ClassicCanvasHeatLayer.ts 12.7 KB
/**
 * 经典 heatmap.js 口径热力层(2026-11-25 第三十四轮,超人给的高德同视角图):
 *
 * 那张图和之前那张整片红橙 blob 是两种形态 —— 这一种是**一颗颗独立的同心圆光斑**:
 * 中心饱和红,向外橙→黄→绿→青渐隐到地图底色;数字写在光斑中心,连 1、2、5
 * 都清楚可读。量测:光斑直径约 60px(= heatmap.js 默认 radius 30px 的两倍)、
 * 红心直径约占 1/3、外缘渐隐无硬边。
 *
 * 这正是 heatmap.js / AMap.HeatMap 的**原生单笔**形态,不需要双尺度、椭圆偏瓣
 * 或流场扰动。但第三十五轮(超人:「满屏数字,热力图感觉都消失了」)发现严格照搬
 * 默认常量在**全市视野**下会失效 —— 高德参考图是局部放大视野(桶少、案量都 300+),
 * 全市视野却是从 1 到 714 的长尾,三个尺度全部错配:
 *   1) 高德光斑直径≈聚合格距 60px,我们格距 72px 却用 30px 半径(直径 60px)——
 *      每斑之间留 12px 冷缝,连不成场 → 半径改 36px,直径 72px 正好铺满一格;
 *   2) `globalAlpha = (count/max)^0.6`(max 仍走 P82):平方级压下中段不是高德的
 *      口径,但全市长尾里 count=50 的桶线性权重只有 0.2、查到青色就停了;0.6 次幂
 *      把中段抬到 0.38(青→绿黄),头部仍封顶,热力面才重新看得见;
 *   3) heatmap.js `_getPointTemplate` 用 shadowBlur 生成的模板**中心有饱和平台**,
 *      不是纯线性锥。纯线性时 alpha≥0.9 的红区只剩半径 10%(3px),被 8~11px 的
 *      白盘整个盖住 → 平台改 30% 半径(10.8px),红心露在白盘外一圈。
 * 灰度字节仍直接索引 palette(heatmap.js `_colorize` 口径),每桶仍只有一笔。
 *
 * 与数字层严格同源同圆:吃的是同一批桶(桶心已由 Worker 错落),数字圆心 = 热核圆心。
 *
 * 回退:`?heat=bucket` 旧双尺度自绘、`?heat=raw` 原始点逐笔、`?heat=official` 百度内置层。
 */

import { APP_SCALE, defineAppOverlay } from '../../appOverlay';
import {
  DEFAULT_HEAT_STYLE,
  HEAT_MIN_OPACITY,
  reference,
  type HeatLayerStyle,
} from '../../heatReference';
import { Frame, mercY, type PaintEnv } from '@hm/map-overlay';
import type { Overlay } from '@hm/map-overlay';
import type { Basemap, HeatLayerLike } from '../types';
import { unregisterDebugLayer } from '../../../debug/debugBus';
import { buildLut, densityToStop } from './CanvasHeatLayer';

/**
 * 光斑半径(绝对像素):高德参考图量出光斑直径≈聚合格距;我们格距 72px,
 * 所以半径取半格 36px(heatmap.js 默认 30px 对应它自己 60px 的聚合网格)。
 * 30px 时直径 60px < 格距 72px,每斑之间 12px 冷缝,全市视野下热力看着像消失。
 */
export const CLASSIC_RADIUS_PX = 36;
/** 权重开方指数:全市长尾把中段压到 0.2 以下会只剩淡青,0.6 次幂抬回绿黄、头部仍封顶 */
export const CLASSIC_GAMMA = 0.6;
/** 笔刷中心饱和平台占半径比例:heatmap.js shadowBlur 模板的中心平顶;保证红心大过白盘 */
export const CLASSIC_FLAT = 0.3;
/** 灰度图与主画布同比:同心环边界要利落,不靠 1/2 分辨率省像素 */
const GRAY_SCALE = 1;

const LUT = buildLut();

const MAX_EASE = 0.35;
const MAX_EASE_EPS = 0.005;
export function smoothMax(current: number, target: number): { value: number; settled: boolean } {
  const t = Math.max(1, target);
  const c = Math.max(1, current);
  if (Math.abs(t - c) / t <= MAX_EASE_EPS) return { value: t, settled: true };
  const next = Math.max(1, Math.round(c + (t - c) * MAX_EASE));
  if (next === c) return { value: t, settled: true };
  return { value: next, settled: next === t };
}

/**
 * 单桶案量 → 笔刷 globalAlpha:(count/max)^0.6,封顶 1。
 * 纯恒等在局部高案量视野没问题,但全市长尾里 P82 抬到 200+ 后,count=50 的桶
 * 权重 0.2 只到青色,热力面就「消失」了;0.6 次幂把 0.2→0.38(绿黄)、0.5→0.66
 * (黄橙),头部仍封顶红,中段获得可见色阶。不是 heatmap.js 原始口径,是针对
 * 长尾数据的标定,与数字层分母(reference P82)保持同源。
 */
export function classicWeightToAlpha(count: number, max: number): number {
  const linear = Math.min(1, Math.max(0, count / Math.max(1, max)));
  return Math.pow(linear, CLASSIC_GAMMA);
}

/**
 * 经典单笔软刷的剖面:中心 30% 半径是饱和平台(heatmap.js shadowBlur 模板的平顶),
 * 之后线性衰减到边缘 0。平台是红心能露出白盘的关键:36px 半径 × 30% = 10.8px
 * 饱和区,比 8~11px 的白盘略大,数字仍钉在圆心但外圈能看见红色。
 * 注意这与旧 `CanvasHeatLayer.brushAlphaAt` 的 6% 小平台 + 0.94 长软边不是同一剖面。
 */
export function classicBrushAlphaAt(t: number): number {
  if (t <= CLASSIC_FLAT) return 1;
  return Math.min(1, Math.max(0, (1 - t) / (1 - CLASSIC_FLAT)));
}

export class ClassicCanvasHeatLayer implements HeatLayerLike {
  private readonly overlay: Overlay;
  private style: HeatLayerStyle = { ...DEFAULT_HEAT_STYLE };
  private visible = true;
  private lng = new Int32Array(0);
  private lat = new Int32Array(0);
  private weights = new Int32Array(0);

  private max = 1;
  private targetMax = 1;
  private maxReady = false;
  private maxSettled = true;
  private lastMax = 1;

  private gray = document.createElement('canvas');
  private grayCtx: CanvasRenderingContext2D | null = null;
  private grayW = 0;
  private grayH = 0;
  private brush: HTMLCanvasElement | null = null;
  private brushR = -1;

  constructor(private readonly map: Basemap) {
    this.overlay = defineAppOverlay(map, {
      id: 'heat',
      name: '经典热力层 · heatmap.js 单笔软刷',
      zIndex: 110,
      zooms: [3, 20],
      runtime: this.map.overlayRuntime,
      canPaint: () => this.visible && this.lng.length > 0,
      paint: (env) => this.paint(env),
      extras: () => ({
        built: this.overlay.mounted,
        visible: this.visible,
        note: `桶 ${this.lng.length} · 笔刷半径 ${this.brushR}px · 灰度 ${this.grayW}×${this.grayH} · max=${Math.round(this.lastMax)}`,
      }),
    });
    if (import.meta.env.DEV) {
      (window as unknown as { __hmHeat?: ClassicCanvasHeatLayer }).__hmHeat = this;
    }
  }

  snapshot() {
    return {
      visible: this.visible,
      buckets: this.lng.length,
      brushRadius: this.brushR,
      max: this.lastMax,
      gray: `${this.grayW}×${this.grayH}`,
      mounted: this.overlay.mounted,
    };
  }

  /** 数字全部写、全部清楚:高德那张图连 1、2、5 都看得见 */
  get quietNumbers(): boolean {
    return false;
  }

  /** 每桶一笔:半径按格距标定,圆心必须保持格距 —— 所以它要格心,不要数字那套重心 */
  readonly wantsLatticeCenters = true;

  setDataset(
    lng: Int32Array,
    lat: Int32Array,
    count: Int32Array,
    keep?: Uint8Array | null,
  ): void {
    const n = Math.min(lng.length, lat.length, count.length);
    const keptLng: number[] = [];
    const keptLat: number[] = [];
    const keptCount: number[] = [];
    for (let i = 0; i < n; i += 1) {
      if (keep && keep[i] !== 1) continue;
      keptLng.push(lng[i]);
      keptLat.push(lat[i]);
      keptCount.push(count[i]);
    }
    this.lng = Int32Array.from(keptLng);
    this.lat = Int32Array.from(keptLat);
    this.weights = Int32Array.from(keptCount);

    const size = this.map.getSize();
    const center = this.map.getCenter();
    const frame = new Frame();
    frame.set(
      this.map,
      this.map.getZoom(),
      center.getLng(),
      center.getLat(),
      this.map.frameScale ?? APP_SCALE,
    );
    const inView: number[] = [];
    for (let i = 0; i < this.weights.length; i += 1) {
      const x = frame.x(this.lng[i] / 1e6);
      const y = frame.y(mercY(this.lat[i] / 1e6));
      if (x >= 0 && x <= size.width && y >= 0 && y <= size.height) inView.push(this.weights[i]);
    }
    const next = reference(inView.length ? Int32Array.from(inView) : this.weights);
    this.targetMax = next;
    if (!this.maxReady) {
      this.max = next;
      this.lastMax = next;
      this.maxReady = true;
      this.maxSettled = true;
    } else {
      this.maxSettled = false;
    }
    if (this.weights.length > 0) this.overlay.invalidate();
    else this.overlay.release();
  }

  clear(): void {
    this.lng = new Int32Array(0);
    this.lat = new Int32Array(0);
    this.weights = new Int32Array(0);
    this.maxReady = false;
    this.grayW = 0;
    this.grayH = 0;
    this.overlay.release();
  }

  setStyle(style: Partial<HeatLayerStyle>): void {
    const next = { ...this.style, ...style };
    if (next.radius !== this.style.radius) this.brushR = -1;
    this.style = next;
    this.overlay.invalidate();
  }

  setVisible(visible: boolean): void {
    this.visible = visible;
    if (visible) this.overlay.show();
    else this.overlay.hide();
  }

  get countPoints(): number {
    return this.weights.length;
  }

  get count(): number {
    return this.weights.length;
  }

  get maxWeight(): number {
    return this.lastMax;
  }

  /**
   * 单笔软刷:中心 30% 半径饱和平台、外面线性淡到 0。一个笔刷自己就画出
   * 红心→橙→黄→绿→青的同心环。heatmap.js v2.0.5 的 `_getPointTemplate`
   * 用 shadowBlur 画出的模板中心就是这一枚平顶。
   */
  private ensureBrush(radiusPx: number): HTMLCanvasElement {
    const r = Math.max(2, Math.round(radiusPx * GRAY_SCALE));
    if (this.brush && this.brushR === r) return this.brush;
    const b = document.createElement('canvas');
    b.width = b.height = r * 2;
    const c = b.getContext('2d');
    if (c) {
      const g = c.createRadialGradient(r, r, 0, r, r, r);
      g.addColorStop(0, 'rgba(0,0,0,1)');
      g.addColorStop(CLASSIC_FLAT, 'rgba(0,0,0,1)');
      g.addColorStop(1, 'rgba(0,0,0,0)');
      c.fillStyle = g;
      c.fillRect(0, 0, r * 2, r * 2);
    }
    this.brush = b;
    this.brushR = r;
    return b;
  }

  private paint(env: PaintEnv): number {
    const main = env.ctx;
    const w = env.width;
    const h = env.height;
    if (w <= 0 || h <= 0 || this.weights.length === 0) return 0;

    if (!this.maxSettled) {
      const next = smoothMax(this.max, this.targetMax);
      this.max = next.value;
      this.lastMax = next.value;
      this.maxSettled = next.settled;
      if (!next.settled) this.overlay.invalidate();
    }

    const gw = Math.max(1, Math.round(w * GRAY_SCALE));
    const gh = Math.max(1, Math.round(h * GRAY_SCALE));
    if (this.grayW !== gw || this.grayH !== gh) {
      this.gray.width = gw;
      this.gray.height = gh;
      this.grayW = gw;
      this.grayH = gh;
      this.grayCtx = this.gray.getContext('2d', { willReadFrequently: true });
    }
    const gc = this.grayCtx;
    if (!gc) return 0;

    const gear = Math.max(0.1, this.style.radius / DEFAULT_HEAT_STYLE.radius);
    const brush = this.ensureBrush(CLASSIC_RADIUS_PX * gear);
    const r = this.brushR;

    // 1) 每桶一笔软刷,globalAlpha = count/max;source-over 在灰度 alpha 通道累积。
    gc.setTransform(1, 0, 0, 1, 0, 0);
    gc.clearRect(0, 0, gw, gh);
    gc.globalCompositeOperation = 'source-over';
    let drawn = 0;
    for (let i = 0; i < this.weights.length; i += 1) {
      const x = env.frame.x(this.lng[i] / 1e6) * GRAY_SCALE;
      const y = env.frame.y(mercY(this.lat[i] / 1e6)) * GRAY_SCALE;
      if (x < -r || y < -r || x > gw + r || y > gh + r) continue;
      const a = classicWeightToAlpha(this.weights[i], this.max);
      gc.globalAlpha = a < 0.01 ? 0.01 : a;
      gc.drawImage(brush, x - r, y - r, r * 2, r * 2);
      drawn += 1;
    }
    gc.globalAlpha = 1;

    // 2) heatmap.js `_colorize`:灰度 alpha 字节直接索引 palette;输出 alpha clamp。
    const img = gc.getImageData(0, 0, gw, gh);
    const data = img.data;
    const minA = Math.round(255 * HEAT_MIN_OPACITY);
    const maxA = Math.round(255 * this.style.opacity);
    for (let p = 0; p < data.length; p += 4) {
      const a = data[p + 3];
      if (a === 0) continue;
      const k = Math.round(densityToStop(a) * 255) * 3;
      data[p] = LUT[k];
      data[p + 1] = LUT[k + 1];
      data[p + 2] = LUT[k + 2];
      data[p + 3] = a < minA ? minA : a > maxA ? maxA : a;
    }
    gc.putImageData(img, 0, 0);

    main.save();
    main.imageSmoothingEnabled = true;
    main.drawImage(this.gray, 0, 0, gw, gh, 0, 0, w, h);
    main.restore();
    return drawn;
  }

  destroy(): void {
    unregisterDebugLayer('heat');
    if (import.meta.env.DEV) {
      const w = window as unknown as { __hmHeat?: ClassicCanvasHeatLayer };
      if (w.__hmHeat === this) delete w.__hmHeat;
    }
    this.overlay.destroy();
    this.gray.width = 0;
    this.gray.height = 0;
  }
}