All files / lib hex.ts

100% Statements 64/64
100% Branches 22/22
100% Functions 24/24
100% Lines 55/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161                                                            2x     682x         674x 674x 674x 674x         822x 822x 4932x 4932x 4932x 4932x   822x                 5x 5x               7138x 7138x 7138x 7138x       3548x         1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x 1774x                   1572x 1572x     1262x       1572x 949x       10x 9x 9x 71x 672x 672x 672x                       9x       11218x               257x 113x 4x 4x 4x 300x 66x 66x   234x     4x    
/**
 * Geometry and generation for the hero's hex field.
 * Pure functions, rendered on the server, so the hero ships no JavaScript.
 *
 * Layout is pointy-top hexes in "odd-r" offset coordinates:
 * odd rows are pushed right by half a hex.
 */
 
export type TileKind = "water" | "land" | "forest" | "panel";
 
export interface HexTile {
  key: string;
  col: number;
  row: number;
  x: number;
  y: number;
  points: string;
  /** Panel tiles draw a smaller module on top of the ground hex. */
  module: string | null;
  kind: TileKind;
}
 
export interface HexFieldOptions {
  cols: number;
  rows: number;
  /** Distance from centre to corner. */
  size: number;
  seed: number;
}
 
const SQRT3 = Math.sqrt(3);
 
export function hexWidth(size: number): number {
  return SQRT3 * size;
}
 
/** Centre of the hex at an odd-r offset coordinate. */
export function offsetToPixel(col: number, row: number, size: number): { x: number; y: number } {
  const w = hexWidth(size);
  const x = w * (col + 0.5 * (row & 1)) + w / 2;
  const y = size * 1.5 * row + size;
  return { x, y };
}
 
/** SVG polygon points for a pointy-top hex, rounded to keep markup small. */
export function hexCorners(cx: number, cy: number, size: number): string {
  const corners: string[] = [];
  for (let i = 0; i < 6; i++) {
    const angle = (Math.PI / 180) * (60 * i - 30);
    const px = round(cx + size * Math.cos(angle));
    const py = round(cy + size * Math.sin(angle));
    corners.push(`${px},${py}`);
  }
  return corners.join(" ");
}
 
/** Pixel size of a field, for the SVG viewBox. */
export function fieldSize(
  cols: number,
  rows: number,
  size: number,
): { width: number; height: number } {
  const w = hexWidth(size);
  return {
    width: round(w * cols + (rows > 1 ? w / 2 : 0)),
    height: round(size * 1.5 * (rows - 1) + size * 2),
  };
}
 
/** Deterministic hash of a lattice point into [0, 1). */
export function hash2(x: number, y: number, seed: number): number {
  let h = (x * 374761393 + y * 668265263 + seed * 2147483647) | 0;
  h = Math.imul(h ^ (h >>> 13), 1274126177);
  h = h ^ (h >>> 16);
  return (h >>> 0) / 4294967296;
}
 
function smooth(t: number): number {
  return t * t * (3 - 2 * t);
}
 
/** Smooth value noise in [0, 1). Same inputs always give the same output. */
export function valueNoise(x: number, y: number, seed: number): number {
  const x0 = Math.floor(x);
  const y0 = Math.floor(y);
  const tx = smooth(x - x0);
  const ty = smooth(y - y0);
  const a = hash2(x0, y0, seed);
  const b = hash2(x0 + 1, y0, seed);
  const c = hash2(x0, y0 + 1, seed);
  const d = hash2(x0 + 1, y0 + 1, seed);
  const top = a + (b - a) * tx;
  const bottom = c + (d - c) * tx;
  return top + (bottom - top) * ty;
}
 
export function classifyTile(
  col: number,
  row: number,
  cols: number,
  rows: number,
  seed: number,
): TileKind {
  const n = valueNoise(col / 3.2, row / 3.2, seed);
  if (n < 0.34) return "water";
  // A solar array on the dry ground in the right half of the map.
  const inArray =
    col >= Math.floor(cols * 0.55) &&
    col < cols - 1 &&
    row >= Math.floor(rows * 0.25) &&
    row < Math.ceil(rows * 0.75);
  if (inArray) return "panel";
  return n > 0.62 ? "forest" : "land";
}
 
export function buildHexField({ cols, rows, size, seed }: HexFieldOptions): HexTile[] {
  if (cols < 1 || rows < 1) return [];
  const tiles: HexTile[] = [];
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      const { x, y } = offsetToPixel(col, row, size);
      const kind = classifyTile(col, row, cols, rows, seed);
      tiles.push({
        key: `${col}:${row}`,
        col,
        row,
        x: round(x),
        y: round(y),
        points: hexCorners(x, y, size * 0.94),
        module: kind === "panel" ? hexCorners(x, y, size * 0.62) : null,
        kind,
      });
    }
  }
  return tiles;
}
 
function round(n: number): number {
  return Math.round(n * 10) / 10;
}
 
/**
 * The field as SVG markup: the whole map, and the panel modules alone (for the reveal layer).
 * Built only from numbers and the fixed terrain names, so it is safe to insert as HTML.
 */
export function hexFieldMarkup(tiles: HexTile[]): { map: string; panels: string } {
  const polygon = (points: string, kind: TileKind) =>
    `<polygon points="${points}" data-kind="${kind}" class="hex-tile"></polygon>`;
  let map = "";
  let panels = "";
  for (const tile of tiles) {
    if (tile.module) {
      map += `<g>${polygon(tile.points, "land")}${polygon(tile.module, "panel")}</g>`;
      panels += `<polygon points="${tile.module}"></polygon>`;
    } else {
      map += polygon(tile.points, tile.kind);
    }
  }
  return { map, panels };
}