1
0
Fork 0
polaris-task-force/src/lib/map/grid.ts
Z8MB1E 12cb62b487 feat(map): add Arma-style coordinate grid config, overlay and mission-map wiring
Per-map grid config (gridEnabled, easting/northing origin, spacing, label
digits, over-lines) rides on the Maps collection and surfaces via
/api/map-features. Pure math in src/lib/map/grid.ts mirrors CfgWorlds Grid
(floor truncation, mod-10^digits wrapping, nested levels). GridLayer renders
hairlines + edge labels on the world map and mission planning maps, and
armaGridRef now delegates to gridRef. Migration 20261005_001212_add_map_grid_config.
2026-10-05 03:17:52 -04:00

273 lines
11 KiB
TypeScript

/**
* Arma-style coordinate grid: per-map configuration, label math, zoom level
* selection, and grid references. Pure module (client-safe, no Payload).
*
* The model mirrors CfgWorlds `class Grid` on A3 terrains. Vanilla terrains
* place the grid zero line on the south-west world corner so labels equal raw
* world meters; the config below can shift that origin (placement), renumber
* the first line (starting numbers), and resize the base cell, so each map
* can reproduce its in-game grid exactly.
*
* Coordinate spaces: our maps store meters with origin top-left and y running
* south. Arma world coordinates run origin bottom-left, y north. Grid math
* happens in Arma space (y north); conversion is `armaY = worldHeight - mapY`.
*
* Label rules (verified against in-game anchors on Altis/Stratis/Malden/Tanoa):
* values are floor-truncated cell indices, wrapped modulo 10^digits and
* zero-padded (negative indices wrap the same way, e.g. -1 at 3 digits reads
* "999"). Zoom levels step by powers of ten and nest exactly: the 1 km cell
* labeled "10" contains the 100 m lines "100" through "109".
*/
import type { MapPoint } from "./points";
export interface MapGridConfig {
/** Master switch: overlay + configured grid references. */
enabled: boolean;
/** Arma-space meters from the west edge to the grid zero line (in-game X). */
originEasting: number;
/** Arma-space meters from the south edge to the grid zero line (in-game Y). */
originNorthing: number;
/** Label value shown on the zero line at the base spacing (eastings). */
startEasting: number;
/** Label value shown on the zero line at the base spacing (northings). */
startNorthing: number;
/** Base cell size in meters (Arma's 1 km level by default). */
spacingMeters: number;
/** Digits shown per axis at the base spacing (Arma shows 2 at 1 km). */
labelDigits: number;
/** Tanoa style: draw numbers over the lines instead of centered in cells. */
numbersOverLines: boolean;
}
/**
* Default grid: zero line on the south-west corner, 1 km base cells, numbers
* from zero. gridRef with these values reproduces the legacy armaGridRef
* output exactly (100 m cells at 6 digits, 10 m at 8).
*/
export const DEFAULT_MAP_GRID: MapGridConfig = {
enabled: false,
originEasting: 0,
originNorthing: 0,
startEasting: 0,
startNorthing: 0,
spacingMeters: 1000,
labelDigits: 2,
numbersOverLines: false,
};
function finite(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
function clampInt(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, Math.round(value)));
}
/** Coerce a maps collection row into a grid config, tolerating nulls. */
export function gridConfigFromMapDoc(doc: Record<string, unknown> | null | undefined): MapGridConfig {
const raw = doc ?? {};
const spacing = finite(raw.gridSpacingMeters) && raw.gridSpacingMeters >= 1
? raw.gridSpacingMeters
: DEFAULT_MAP_GRID.spacingMeters;
return {
enabled: raw.gridEnabled === true,
originEasting: finite(raw.gridOriginEasting) ? raw.gridOriginEasting : 0,
originNorthing: finite(raw.gridOriginNorthing) ? raw.gridOriginNorthing : 0,
startEasting: finite(raw.gridStartEasting) ? Math.trunc(raw.gridStartEasting) : 0,
startNorthing: finite(raw.gridStartNorthing) ? Math.trunc(raw.gridStartNorthing) : 0,
spacingMeters: spacing,
labelDigits: finite(raw.gridLabelDigits)
? clampInt(raw.gridLabelDigits, 1, 6)
: DEFAULT_MAP_GRID.labelDigits,
numbersOverLines: raw.gridNumbersOverLines === true,
};
}
/** Floor-modulo that wraps negatives into [0, modulus), matching Arma. */
function wrapMod(value: number, modulus: number): number {
return ((value % modulus) + modulus) % modulus;
}
/**
* Zero-padded label for a cell index at `digits` precision, wrapped modulo
* 10^digits with leading zeros ("7" at 3 digits reads "007", -1 reads "999").
*/
export function gridLabel(cellIndex: number, digits: number): string {
const modulus = 10 ** digits;
return String(wrapMod(Math.trunc(cellIndex), modulus)).padStart(digits, "0");
}
/**
* Cell index of an Arma-space coordinate at a given spacing, including the
* configured origin and starting-number offset. Starting numbers are defined
* at the base spacing and scale into finer levels (a base start of 5 reads
* "05" at 1 km and "050" at 100 m); at coarser-than-base levels the start
* contribution floors out and is ignored.
*/
function cellValue(armaCoord: number, origin: number, start: number, spacing: number, baseSpacing: number): number {
const index = Math.floor((armaCoord - origin) / spacing);
const scale = baseSpacing / spacing;
return index + (scale >= 1 ? Math.floor(start * scale) : 0);
}
export interface GridLevel {
/** Cell size of the active level in meters. */
spacing: number;
/** Label digits per axis at this level. */
digits: number;
}
/**
* On-screen cell size below which a finer level is chosen instead. Sized so a
* typical viewport shows roughly 15-40 lines, close to the in-game map.
*/
export const GRID_MIN_CELL_PX = 56;
/**
* Pick the zoom level for a meters-per-pixel scale. The ladder runs from
* 100x coarser to 100x finer than the base spacing in power-of-ten steps
* (with default config: 10 km/1 digit, 1 km/2, 100 m/3, 10 m/4, the A3
* ladder). The finest level whose on-screen cell stays readable wins; zooming
* out past the coarsest level just keeps it.
*/
export function gridLevelFor(metersPerPxValue: number, config: MapGridConfig): GridLevel {
const base = config.spacingMeters;
const levels: GridLevel[] = [];
for (let k = -2; k <= 2; k++) {
const digits = config.labelDigits + k;
if (digits < 1 || digits > 8) continue;
levels.push({ spacing: base / 10 ** k, digits });
}
if (levels.length === 0) return { spacing: base, digits: config.labelDigits };
// levels run coarse to fine; take the finest that still reads on screen.
let chosen = levels[0];
for (const level of levels) {
if (level.spacing / metersPerPxValue >= GRID_MIN_CELL_PX) chosen = level;
}
return chosen;
}
export interface GridLabel {
/** Line index (or cell index in cell-centered mode) this label shows. */
value: string;
/** Anchor position on the label's axis, in map meters. */
at: number;
}
export interface GridLineSet {
level: GridLevel;
/** Vertical line positions, map meters (x, measured from the west edge). */
verticalLines: number[];
/** Horizontal line positions, map meters (y, measured from the north edge). */
horizontalLines: number[];
/** Easting labels (top/bottom edges), x in map meters. */
eastingLabels: GridLabel[];
/** Northing labels (left/right edges), y in map meters. */
northingLabels: GridLabel[];
}
export interface GridBounds {
minX: number;
minY: number;
maxX: number;
maxY: number;
}
/**
* Lines and labels covering a viewport, in map meters (origin top-left, y
* south). Labels are cell-centered by default (Arma draws numbers between the
* lines) and sit on the lines when `numbersOverLines` is set (Tanoa style).
* Bounds are padded by one cell so labels do not pop while panning.
*/
export function gridLinesForBounds(
config: MapGridConfig,
worldHeight: number,
bounds: GridBounds,
metersPerPxValue: number,
): GridLineSet {
const level = gridLevelFor(metersPerPxValue, config);
const { spacing, digits } = level;
const pad = spacing;
const firstV = Math.floor((bounds.minX - config.originEasting - pad) / spacing);
const lastV = Math.ceil((bounds.maxX - config.originEasting + pad) / spacing);
const verticalLines: number[] = [];
const eastingLabels: GridLabel[] = [];
for (let k = firstV; k <= lastV; k++) {
const x = config.originEasting + k * spacing;
verticalLines.push(x);
if (x < bounds.minX - pad || x > bounds.maxX + pad) continue;
if (config.numbersOverLines) {
eastingLabels.push({ value: gridLabel(cellValue(x, config.originEasting, config.startEasting, spacing, config.spacingMeters), digits), at: x });
}
}
if (!config.numbersOverLines) {
for (let k = firstV; k <= lastV; k++) {
const center = config.originEasting + (k + 0.5) * spacing;
if (center < bounds.minX - pad || center > bounds.maxX + pad) continue;
eastingLabels.push({
value: gridLabel(
cellValue(config.originEasting + k * spacing, config.originEasting, config.startEasting, spacing, config.spacingMeters),
digits,
),
at: center,
});
}
}
// Arma-space northing of the viewport: map y runs south, so flip.
const armaMin = worldHeight - bounds.maxY;
const armaMax = worldHeight - bounds.minY;
const firstH = Math.floor((armaMin - config.originNorthing - pad) / spacing);
const lastH = Math.ceil((armaMax - config.originNorthing + pad) / spacing);
const horizontalLines: number[] = [];
const northingLabels: GridLabel[] = [];
for (let k = firstH; k <= lastH; k++) {
const armaY = config.originNorthing + k * spacing;
horizontalLines.push(worldHeight - armaY);
if (armaY < armaMin - pad || armaY > armaMax + pad) continue;
if (config.numbersOverLines) {
northingLabels.push({ value: gridLabel(cellValue(armaY, config.originNorthing, config.startNorthing, spacing, config.spacingMeters), digits), at: worldHeight - armaY });
}
}
if (!config.numbersOverLines) {
for (let k = firstH; k <= lastH; k++) {
const armaY = config.originNorthing + (k + 0.5) * spacing;
if (armaY < armaMin - pad || armaY > armaMax + pad) continue;
northingLabels.push({
value: gridLabel(
cellValue(config.originNorthing + k * spacing, config.originNorthing, config.startNorthing, spacing, config.spacingMeters),
digits,
),
at: worldHeight - armaY,
});
}
}
return { level, verticalLines, horizontalLines, eastingLabels, northingLabels };
}
/**
* Arma grid reference for a map-meter point: easting group then northing
* group, 6 digits (3+3, 100 m cells with default config) or 8 digits (4+4,
* 10 m). Values wrap at the digit width like the in-game readout. With
* DEFAULT_MAP_GRID this reproduces the legacy armaGridRef output for any
* in-world point.
*/
export function gridRef(
point: MapPoint,
worldHeight: number,
config: MapGridConfig = DEFAULT_MAP_GRID,
digits: 6 | 8 = 6,
): string {
const per = digits / 2;
// Precision relative to the base level: default config lands on 100 m at
// 6 digits and 10 m at 8, matching Arma's finest zoom classes.
const spacing = config.spacingMeters / 10 ** (per - config.labelDigits);
const armaX = point[0];
const armaY = worldHeight - point[1];
const easting = cellValue(armaX, config.originEasting, config.startEasting, spacing, config.spacingMeters);
const northing = cellValue(armaY, config.originNorthing, config.startNorthing, spacing, config.spacingMeters);
return `${gridLabel(easting, per)} ${gridLabel(northing, per)}`;
}