/** * Mission planning-map markers: shape model, input validation, geometry and * SQF export. Pure module (client-safe, no Payload imports). * * The model deliberately mirrors Arma's marker API (shape / type / color / * brush / text / size / dir / alpha / polyline) so a plan can be exported as a * `createMarker` script and pasted into the game. * * Coordinates are map meters (origin top-left, y runs south, like the rest of * the map system). Arma positions are origin bottom-left with y north, so the * export flips y against the world height. */ import { isPointArray, type MapPoint } from "@/lib/map/points"; import { DEFAULT_MAP_GRID, gridRef } from "@/lib/map/grid"; import { DEFAULT_MARKER_BRUSH, DEFAULT_MARKER_COLOR, markerBrushOf, markerColorOf, markerTypeOf, type ArmaBrushPattern, } from "./index"; export const MISSION_MARKER_SHAPES = ["icon", "rectangle", "ellipse", "polyline"] as const; export type MissionMarkerShape = (typeof MISSION_MARKER_SHAPES)[number]; export const MAX_MARKER_TEXT = 200; export const MAX_POLYLINE_POINTS = 500; export const MAX_MARKERS_PER_MISSION = 1000; /** Area half-extent bounds in meters (Arma markerSize for areas). */ export const MIN_AREA_SIZE = 1; export const MAX_AREA_SIZE = 50_000; /** Icon size is a scale multiplier (Arma markerSize for icons, default [1, 1]). */ export const MIN_ICON_SCALE = 0.25; export const MAX_ICON_SCALE = 8; /** Matches the map's maxBounds padding: markers may sit slightly off-world. */ const WORLD_MARGIN = 2000; export interface MissionMarkerData { shape: MissionMarkerShape; /** CfgMarkers class (icons only). */ markerType: string | null; /** CfgMarkerColors class. */ color: string; /** CfgMarkerBrushes class (areas only). */ brush: string | null; text: string; /** Icon/area center; first vertex for polylines. */ position: MapPoint; /** Area half-extents in meters, or icon scale. */ size: [number, number]; /** Degrees clockwise from north (Arma markerDir). */ direction: number; alpha: number; /** Polyline vertices (empty for other shapes). */ points: MapPoint[]; } export interface MissionMarker extends MissionMarkerData { id: number; } export interface WorldSize { width: number; height: number; } function finite(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value); } function clamp(value: number, min: number, max: number): number { return Math.min(max, Math.max(min, value)); } function round(value: number, places = 2): number { const factor = 10 ** places; return Math.round(value * factor) / factor; } function inWorld(point: MapPoint, world: WorldSize): boolean { return ( point[0] >= -WORLD_MARGIN && point[0] <= world.width + WORLD_MARGIN && point[1] >= -WORLD_MARGIN && point[1] <= world.height + WORLD_MARGIN ); } function asPoint(value: unknown): MapPoint | null { if (!Array.isArray(value) || value.length !== 2) return null; const [x, y] = value; return finite(x) && finite(y) ? [round(x), round(y)] : null; } export function normalizeDirection(value: unknown): number { if (!finite(value)) return 0; const wrapped = value % 360; return round(wrapped < 0 ? wrapped + 360 : wrapped); } export function sanitizeMarkerText(value: unknown): string { if (typeof value !== "string") return ""; return value .replace(/[\r\n\t]+/g, " ") .trim() .slice(0, MAX_MARKER_TEXT); } /** * Validate and normalize untrusted marker input (server-side gate; the editor * runs it too for instant feedback). Returns the clean data or an error string. */ export function normalizeMarkerInput( input: unknown, world: WorldSize, ): { ok: true; data: MissionMarkerData } | { ok: false; error: string } { if (!input || typeof input !== "object") return { ok: false, error: "Invalid marker." }; const raw = input as Record; const shape = raw.shape; if (typeof shape !== "string" || !MISSION_MARKER_SHAPES.includes(shape as MissionMarkerShape)) { return { ok: false, error: "Unknown marker shape." }; } const kind = shape as MissionMarkerShape; const colorClass = typeof raw.color === "string" && raw.color ? raw.color : DEFAULT_MARKER_COLOR; const color = markerColorOf(colorClass); if (!color) return { ok: false, error: `Unknown marker color "${colorClass}".` }; const alpha = finite(raw.alpha) ? round(clamp(raw.alpha, 0, 1)) : 1; const direction = normalizeDirection(raw.direction); const text = sanitizeMarkerText(raw.text); if (kind === "polyline") { if (!isPointArray(raw.points, 2)) { return { ok: false, error: "A line needs at least two points." }; } if (raw.points.length > MAX_POLYLINE_POINTS) { return { ok: false, error: `A line can have at most ${MAX_POLYLINE_POINTS} points.` }; } const points = raw.points.map(([x, y]) => [round(x), round(y)] as MapPoint); if (!points.every((point) => inWorld(point, world))) { return { ok: false, error: "Line points must be on the map." }; } return { ok: true, data: { shape: kind, markerType: null, color: color.className, brush: null, text, position: points[0], size: [1, 1], direction: 0, alpha, points, }, }; } const position = asPoint(raw.position); if (!position) return { ok: false, error: "Marker position is required." }; if (!inWorld(position, world)) return { ok: false, error: "Marker must be on the map." }; const size = Array.isArray(raw.size) ? raw.size : []; const sizeA = finite(size[0]) ? size[0] : kind === "icon" ? 1 : 100; const sizeB = finite(size[1]) ? size[1] : sizeA; if (kind === "icon") { const typeClass = typeof raw.markerType === "string" ? raw.markerType : ""; const type = markerTypeOf(typeClass); if (!type) return { ok: false, error: `Unknown marker type "${typeClass}".` }; return { ok: true, data: { shape: kind, markerType: type.className, color: color.className, brush: null, text, position, size: [ round(clamp(sizeA, MIN_ICON_SCALE, MAX_ICON_SCALE)), round(clamp(sizeB, MIN_ICON_SCALE, MAX_ICON_SCALE)), ], direction, alpha, points: [], }, }; } if (sizeA < MIN_AREA_SIZE || sizeB < MIN_AREA_SIZE) { return { ok: false, error: `Area size must be at least ${MIN_AREA_SIZE} m.` }; } if (sizeA > MAX_AREA_SIZE || sizeB > MAX_AREA_SIZE) { return { ok: false, error: `Area size must be at most ${MAX_AREA_SIZE} m.` }; } const brushClass = typeof raw.brush === "string" && raw.brush ? raw.brush : DEFAULT_MARKER_BRUSH; const brush = markerBrushOf(brushClass); if (!brush) return { ok: false, error: `Unknown marker brush "${brushClass}".` }; return { ok: true, data: { shape: kind, markerType: null, color: color.className, brush: brush.className, text, position, size: [round(sizeA), round(sizeB)], direction, alpha, points: [], }, }; } /** * Coerce a stored document into the marker model, tolerating legacy/partial * rows (bad geometry yields null so one broken row never blanks the map). */ export function markerFromDoc(doc: { id: number; shape?: string | null; markerType?: string | null; color?: string | null; brush?: string | null; text?: string | null; position?: unknown; sizeA?: number | null; sizeB?: number | null; direction?: number | null; alpha?: number | null; points?: unknown; }): MissionMarker | null { const shape = MISSION_MARKER_SHAPES.includes(doc.shape as MissionMarkerShape) ? (doc.shape as MissionMarkerShape) : null; if (!shape) return null; const points = isPointArray(doc.points, 2) ? doc.points : []; const position = asPoint(doc.position) ?? points[0] ?? null; if (!position) return null; if (shape === "polyline" && points.length < 2) return null; return { id: doc.id, shape, markerType: doc.markerType ?? null, color: doc.color || DEFAULT_MARKER_COLOR, brush: doc.brush ?? null, text: doc.text ?? "", position, size: [doc.sizeA ?? 1, doc.sizeB ?? doc.sizeA ?? 1], direction: doc.direction ?? 0, alpha: doc.alpha ?? 1, points, }; } /** Flat column shape for persisting a validated marker. */ export function markerToDocFields(data: MissionMarkerData) { return { shape: data.shape, markerType: data.markerType, color: data.color, brush: data.brush, text: data.text, position: data.position, sizeA: data.size[0], sizeB: data.size[1], direction: data.direction, alpha: data.alpha, points: data.shape === "polyline" ? data.points : null, }; } // --------------------------------------------------------------------------- // Geometry // --------------------------------------------------------------------------- /** * Rotate a local offset (east, north meters) by an Arma direction (degrees * clockwise from north) and place it around a map-meter center (y south). */ function placeOffset( center: MapPoint, east: number, north: number, directionDeg: number, ): MapPoint { const rad = (directionDeg * Math.PI) / 180; const cos = Math.cos(rad); const sin = Math.sin(rad); const rotatedEast = east * cos + north * sin; const rotatedNorth = -east * sin + north * cos; return [center[0] + rotatedEast, center[1] - rotatedNorth]; } /** * Outline ring of a rectangle/ellipse area marker in map meters. size is the * half-extent pair [a (east-west), b (north-south)] before rotation, matching * Arma's markerSize semantics. */ export function areaOutline( shape: "rectangle" | "ellipse", center: MapPoint, size: [number, number], directionDeg: number, segments = 64, ): MapPoint[] { const [a, b] = size; if (shape === "rectangle") { return [ placeOffset(center, -a, b, directionDeg), placeOffset(center, a, b, directionDeg), placeOffset(center, a, -b, directionDeg), placeOffset(center, -a, -b, directionDeg), ]; } const ring: MapPoint[] = []; for (let i = 0; i < segments; i++) { const t = (i / segments) * Math.PI * 2; ring.push(placeOffset(center, a * Math.cos(t), b * Math.sin(t), directionDeg)); } return ring; } /** * Hatch line directions per brush pattern, in degrees on the map plane * (0 = east, 90 = south since y runs south) before marker rotation. */ export function hatchAngles(pattern: ArmaBrushPattern): number[] { switch (pattern) { case "horizontal": return [0]; case "vertical": return [90]; case "fdiagonal": return [-45]; case "bdiagonal": return [45]; case "grid": return [0, 90]; case "diaggrid": return [45, -45]; case "cross": return [0, 90, 45, -45]; default: return []; } } /** * Parallel hatch segments clipped to a CONVEX ring (rectangles and ellipses * are convex). `angleDeg` is the line direction on the map plane, `spacing` * the gap between lines in meters. Capped so a tiny spacing on a huge area * cannot explode the render. */ export function hatchSegments( ring: MapPoint[], angleDeg: number, spacing: number, maxLines = 400, ): [MapPoint, MapPoint][] { if (ring.length < 3 || !(spacing > 0)) return []; const rad = (angleDeg * Math.PI) / 180; const dir: MapPoint = [Math.cos(rad), Math.sin(rad)]; const normal: MapPoint = [-dir[1], dir[0]]; let minN = Infinity; let maxN = -Infinity; for (const [x, y] of ring) { const n = x * normal[0] + y * normal[1]; minN = Math.min(minN, n); maxN = Math.max(maxN, n); } const span = maxN - minN; const step = Math.max(spacing, span / maxLines); const segments: [MapPoint, MapPoint][] = []; // Offset the first line by half a step so lines never hug the edge. for (let offset = minN + step / 2; offset < maxN; offset += step) { let tMin = Infinity; let tMax = -Infinity; for (let i = 0; i < ring.length; i++) { const p = ring[i]; const q = ring[(i + 1) % ring.length]; const np = p[0] * normal[0] + p[1] * normal[1] - offset; const nq = q[0] * normal[0] + q[1] * normal[1] - offset; if ((np > 0 && nq > 0) || (np < 0 && nq < 0) || np === nq) continue; const k = np / (np - nq); const hit: MapPoint = [p[0] + (q[0] - p[0]) * k, p[1] + (q[1] - p[1]) * k]; const t = hit[0] * dir[0] + hit[1] * dir[1]; tMin = Math.min(tMin, t); tMax = Math.max(tMax, t); } if (!Number.isFinite(tMin) || tMax - tMin <= 0) continue; const base: MapPoint = [normal[0] * offset, normal[1] * offset]; segments.push([ [base[0] + dir[0] * tMin, base[1] + dir[1] * tMin], [base[0] + dir[0] * tMax, base[1] + dir[1] * tMax], ]); } return segments; } // --------------------------------------------------------------------------- // SQF export // --------------------------------------------------------------------------- function sqfString(value: string): string { return `"${value.replace(/"/g, '""')}"`; } function sqfNumber(value: number): string { return String(round(value)); } /** Map meters (y south) to an Arma world position (y north). */ export function toArmaPosition(point: MapPoint, worldHeight: number): [number, number] { return [round(point[0]), round(worldHeight - point[1])]; } /** * Arma map grid reference (6 digits = 100 m squares, 8 digits = 10 m), the * same numbers the in-game map shows: easting then northing, from the * bottom-left origin. Thin wrapper over gridRef with the default (vanilla) * grid; off-world points wrap at the digit width like the in-game readout. */ export function armaGridRef(point: MapPoint, worldHeight: number, digits: 6 | 8 = 6): string { return gridRef(point, worldHeight, DEFAULT_MAP_GRID, digits); } /** * A `createMarker` script that recreates the plan in-game (paste into the * debug console or an init file). Marker names are prefixed and id-suffixed so * a re-run collides instead of duplicating; existing ones are deleted first. */ export function markersToSqf( markers: MissionMarker[], worldHeight: number, prefix = "ptf_plan", ): string { const lines: string[] = [ `// Generated by Polaris Task Force (${markers.length} markers).`, 'private _m = "";', ]; for (const marker of markers) { const name = sqfString(`${prefix}_${marker.id}`); const [x, y] = toArmaPosition(marker.position, worldHeight); lines.push(`deleteMarker ${name};`); lines.push(`_m = createMarker [${name}, [${sqfNumber(x)}, ${sqfNumber(y)}]];`); if (marker.shape === "icon") { lines.push(`_m setMarkerShape "ICON";`); lines.push(`_m setMarkerType ${sqfString(marker.markerType ?? "mil_dot")};`); } else if (marker.shape === "polyline") { const flat = marker.points .map((point) => toArmaPosition(point, worldHeight).map(sqfNumber).join(", ")) .join(", "); lines.push(`_m setMarkerShape "POLYLINE";`); lines.push(`_m setMarkerPolyline [${flat}];`); } else { lines.push(`_m setMarkerShape ${sqfString(marker.shape.toUpperCase())};`); lines.push(`_m setMarkerBrush ${sqfString(marker.brush ?? "Solid")};`); } if (marker.shape !== "polyline") { lines.push(`_m setMarkerSize [${sqfNumber(marker.size[0])}, ${sqfNumber(marker.size[1])}];`); if (marker.direction) lines.push(`_m setMarkerDir ${sqfNumber(marker.direction)};`); } lines.push(`_m setMarkerColor ${sqfString(marker.color)};`); if (marker.alpha !== 1) lines.push(`_m setMarkerAlpha ${sqfNumber(marker.alpha)};`); if (marker.text) lines.push(`_m setMarkerText ${sqfString(marker.text)};`); } return `${lines.join("\n")}\n`; }