spotlightGeometry.ts 8.33 KB
import { M_PER_DEG_LAT, M_PER_EQUATOR } from './hotspotGeometry';
import type { SpotlightCell } from '../aggregate/types';

/**
 * 聚焦展示的形状几何 —— 把「某几档的出险落点格子」摆成地图上读得出的形状。
 *
 * 这一层为什么单独存在:数据里没有道路线形,也没有街道边界,只有落点。
 * 那么「高亮这条路」能诚实做到的只有一件事 —— 照这些落点自己描出走向。
 * 描法是几何,不是统计:格子归并和每格几起都由 Worker 报(见 aggregate.worker 的
 * handleSpotlight),这里只负责「这些带数量的格子连成什么样」。
 * 分成两个模块的用处是能被单测钉住:走向、断口、段内起数这些都能拿造的点位算出来核对,
 * 而它们只要和榜上的数搭不上,界面上就是一个查得出来的乌龙。
 */

/**
 * 一格:中心(真实度数)+ 格内起数。
 *
 * 类型本身住在数据契约里(aggregate/types),这里只是转出来给本模块与图层用同一支名字 ——
 * 「聚焦的一格」在 store、图层、Worker 三处是同一个东西,各定义一遍就会在某一处悄悄多一个字段。
 */
export type { SpotlightCell };

/** 走廊上的一段:落在一格上的读数就是这一格的起数,段与段连着画就是走向 */
export interface CorridorNode {
  lng: number;
  lat: number;
  n: number;
}

/**
 * 一条连续的走廊。
 *
 * 为什么要拆成多条:一条路的落点中间断了 500 米(那条街根本没案子、或者地址写法换了一档),
 * 硬连成一条就是把「不连着」画成「连着」。断口见 CORRIDOR_GAP_CELLS。
 */
export interface CorridorPath {
  nodes: CorridorNode[];
  /** 路径内段起数之和,等于这些格子背后那批案件的起数 */
  total: number;
}

/** 1° 经线在这一纬度上的米数(等距圆柱近似,与 hotspotSpan 同一口径) */
export function metersPerDegLng(latDeg: number): number {
  return M_PER_EQUATOR * Math.cos((latDeg * Math.PI) / 180);
}

/**
 * 落点均值中心:按格内起数加权。
 *
 * 这是「这一档大概在哪儿」的唯一算法 —— 标签锚点、走廊局部坐标的原点都取它。
 * 不用格子集合的几何中心:一格 1 起和一格 200 起在形状上不该等重。
 */
export function weightedCenter(cells: SpotlightCell[]): SpotlightCell | null {
  let w = 0;
  let sx = 0;
  let sy = 0;
  for (const c of cells) {
    w += c.n;
    sx += c.lng * c.n;
    sy += c.lat * c.n;
  }
  if (w <= 0) return null;
  return { lng: sx / w, lat: sy / w, n: w };
}

/** 起数最多的那一格(并列取先出现的那一格,Worker 已按起数倒序回传) */
export function hottestCell(cells: SpotlightCell[]): SpotlightCell | null {
  let best: SpotlightCell | null = null;
  for (const c of cells) {
    if (best === null || c.n > best.n) best = c;
  }
  return best;
}

/**
 * 一条路的走向:把格子沿主方向排成连续的走廊。
 *
 * 主方向不是猜的,也不是拿首末两点连线(那样一有拐弯就被拉直):
 * 用起数加权的协方差取主轴(2×2 的闭式解),所以「案子多的那几格」对走向的影响更大,
 * 而拐弯处只要格子还在,段就跟着转 —— 因为每一段都落在格子自己的位置上,
 * 主轴只决定「按哪个方向切片」,不决定点画在哪儿。
 *
 * 切片宽度 = 一格边长:这一段说的就是「这约 cellM 米里出了几起」,
 * 与反复出险那张榜「约 N 米一处」是同一把尺,读数不用换直觉。
 *
 * 断口:相邻两片的间隔超过 CORRIDOR_GAP_CELLS 格就断开成两条走廊。
 * 3 格(约 300 米)是「同一条路上还连得上」和「两段各是各的」的分界:
 * 小于它多半是地址写法造成的空洞,大于它就已经是两处地方了。
 */
const CORRIDOR_GAP_CELLS = 3;

export function corridorOf(cells: SpotlightCell[], cellMeters: number): CorridorPath[] {
  const anchor = weightedCenter(cells);
  if (!anchor || cells.length === 0) return [];
  if (cells.length === 1) {
    // 一格描不出走向,就按它自己当一条只有锚点的走廊(图层会画成一枚短段)
    return [{ nodes: [{ ...cells[0] }], total: cells[0].n }];
  }

  // 局部平面坐标(米):原点取加权中心,东西按该纬度换算
  const kx = metersPerDegLng(anchor.lat);
  const xs = cells.map((c) => (c.lng - anchor.lng) * kx);
  const ys = cells.map((c) => (c.lat - anchor.lat) * M_PER_DEG_LAT);
  const ws = cells.map((c) => c.n);
  const w = ws.reduce((a, b) => a + b, 0);
  if (w <= 0) return [];

  // 加权后仍回到以原点为中心:数值上等价,但避免了大坐标相减的精度损失
  let mx = 0;
  let my = 0;
  for (let i = 0; i < cells.length; i += 1) {
    mx += xs[i] * ws[i];
    my += ys[i] * ws[i];
  }
  mx /= w;
  my /= w;

  let cxx = 0;
  let cyy = 0;
  let cxy = 0;
  for (let i = 0; i < cells.length; i += 1) {
    const dx = xs[i] - mx;
    const dy = ys[i] - my;
    cxx += dx * dx * ws[i];
    cyy += dy * dy * ws[i];
    cxy += dx * dy * ws[i];
  }
  // 2×2 实对称矩阵的主特征向量:theta = ½·atan2(2cxy, cxx−cyy)。
  // 全同一点时协方差为 0,atan2(0,0) 给 0,主轴退成东西向,切片照样能连成一条线。
  const theta = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
  const ax = Math.cos(theta);
  const ay = Math.sin(theta);

  // 沿主轴切片:along 定序、perp 定形(每片取自己的加权横向位置,走廊就跟着拐弯)
  const bins = new Map<number, { along: number; perp: number; w: number }>();
  for (let i = 0; i < cells.length; i += 1) {
    const px = xs[i] - mx;
    const py = ys[i] - my;
    const along = px * ax + py * ay;
    const perp = -px * ay + py * ax;
    const b = Math.round(along / cellMeters);
    const cur = bins.get(b) ?? { along: 0, perp: 0, w: 0 };
    cur.along += along * ws[i];
    cur.perp += perp * ws[i];
    cur.w += ws[i];
    bins.set(b, cur);
  }

  const order = [...bins.keys()].sort((a, b) => a - b);
  const paths: CorridorPath[] = [];
  let nodes: CorridorNode[] = [];
  let total = 0;
  let prev: number | null = null;
  for (const b of order) {
    if (prev !== null && b - prev > CORRIDOR_GAP_CELLS) {
      if (nodes.length > 0) paths.push({ nodes, total });
      nodes = [];
      total = 0;
    }
    const bin = bins.get(b)!;
    const along = bin.along / bin.w;
    const perp = bin.perp / bin.w;
    // 逆投影回经纬度:先转回局部平面,再按锚点换算,两步都是上面那两个乘法的逆
    const lx = along * ax - perp * ay + mx;
    const ly = along * ay + perp * ax + my;
    nodes.push({ lng: anchor.lng + lx / kx, lat: anchor.lat + ly / M_PER_DEG_LAT, n: bin.w });
    total += bin.w;
    prev = b;
  }
  if (nodes.length > 0) paths.push({ nodes, total });
  return paths;
}

/** 一屏聚焦里所有格子/走廊的并集范围(取景用) */
export interface BoundsAccumulator {
  minLng: number;
  maxLng: number;
  minLat: number;
  maxLat: number;
}

export function emptyBounds(): BoundsAccumulator {
  return { minLng: Infinity, maxLng: -Infinity, minLat: Infinity, maxLat: -Infinity };
}

/** 把一格并进范围。格子按边长占地方,所以取的是它的四条边而不是中心 */
export function addCell(bounds: BoundsAccumulator, cell: SpotlightCell, cellMeters: number): void {
  const halfLng = cellMeters / 2 / metersPerDegLng(cell.lat);
  const halfLat = cellMeters / 2 / M_PER_DEG_LAT;
  if (cell.lng - halfLng < bounds.minLng) bounds.minLng = cell.lng - halfLng;
  if (cell.lng + halfLng > bounds.maxLng) bounds.maxLng = cell.lng + halfLng;
  if (cell.lat - halfLat < bounds.minLat) bounds.minLat = cell.lat - halfLat;
  if (cell.lat + halfLat > bounds.maxLat) bounds.maxLat = cell.lat + halfLat;
}

export function addPoint(bounds: BoundsAccumulator, lng: number, lat: number): void {
  if (lng < bounds.minLng) bounds.minLng = lng;
  if (lng > bounds.maxLng) bounds.maxLng = lng;
  if (lat < bounds.minLat) bounds.minLat = lat;
  if (lat > bounds.maxLat) bounds.maxLat = lat;
}

/** 范围为空(一个格子都没并进来)时给 null,调用方据此不改视野 */
export function finishBounds(bounds: BoundsAccumulator) {
  return Number.isFinite(bounds.minLng)
    ? {
        minLng: bounds.minLng,
        maxLng: bounds.maxLng,
        minLat: bounds.minLat,
        maxLat: bounds.maxLat,
      }
    : null;
}