import { axialToPixel, hexPath, pixelToAxial, type AxialCoord, type HexCell } from "./hex.ts"; export interface ViewportGridOptions { width: number; height: number; radius: number; cameraX?: number; cameraY?: number; padding?: number; } export interface VisibleGridCell extends HexCell { edgeFactor: number; } function clamp(value: number, minimum: number, maximum: number) { return Math.min(maximum, Math.max(minimum, value)); } function calculateEdgeFactor( x: number, y: number, width: number, height: number, fadeDistance: number, ): number { const distanceToEdge = Math.min( x, width - x, y, height - y, ); return clamp(distanceToEdge / Math.max(1, fadeDistance), 0, 1); } export function generateViewportCells({ width, height, radius, cameraX = 0, cameraY = 0, padding = radius * 3, }: ViewportGridOptions): VisibleGridCell[] { const halfWidth = width / 2; const halfHeight = height / 2; const left = cameraX - halfWidth - padding; const right = cameraX + halfWidth + padding; const top = cameraY - halfHeight - padding; const bottom = cameraY + halfHeight + padding; const corners: AxialCoord[] = [ pixelToAxial({ x: left, y: top }, radius), pixelToAxial({ x: right, y: top }, radius), pixelToAxial({ x: left, y: bottom }, radius), pixelToAxial({ x: right, y: bottom }, radius), ]; const minQ = Math.floor(Math.min(...corners.map((cell) => cell.q)) - 3); const maxQ = Math.ceil(Math.max(...corners.map((cell) => cell.q)) + 3); const minR = Math.floor(Math.min(...corners.map((cell) => cell.r)) - 3); const maxR = Math.ceil(Math.max(...corners.map((cell) => cell.r)) + 3); const cells: VisibleGridCell[] = []; for (let q = minQ; q <= maxQ; q += 1) { for (let r = minR; r <= maxR; r += 1) { const worldPosition = axialToPixel({ q, r }, radius); const screenX = worldPosition.x - cameraX + halfWidth; const screenY = worldPosition.y - cameraY + halfHeight; const insidePaddedViewport = screenX >= -padding && screenX <= width + padding && screenY >= -padding && screenY <= height + padding; if (!insidePaddedViewport) { continue; } cells.push({ id: `hex-${q}-${r}`, q, r, center: { x: screenX, y: screenY }, path: hexPath({ x: screenX, y: screenY }, radius), edgeFactor: calculateEdgeFactor(screenX, screenY, width, height, padding), }); } } return cells; } export function createViewportFitHexGrid(options: ViewportGridOptions): HexCell[] { return generateViewportCells(options); }