UNPKG

@rickosborne/hexgrid

Version:

Rick Osborne's collection of hexagonal grid-related code.

60 lines (59 loc) 2.48 kB
var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); import { minMax, roundTo } from "@rickosborne/foundation"; import { cubeRound } from "./cube-round.mjs"; import { cubeFromQR } from "./cube.mjs"; import { hexContainsChecker } from "./hex-contains-point.mjs"; import { hexCorners, pixelFromQRS } from "./pixel-from-qrs.mjs"; import { qrsFromPixel } from "./qrs-from-pixel.mjs"; const coverRect = /* @__PURE__ */ __name((width, height, layout) => { const rectCorners = [ { x: 0, y: 0 }, { x: width, y: 0 }, { x: width, y: height }, { x: 0, y: height } ]; const cubeCorners = rectCorners.map((xy) => cubeRound(qrsFromPixel(xy, layout, cubeFromQR))); const points = []; const [rMin, rMax] = minMax(cubeCorners.map(({ r }) => r)); const [qMin, qMax] = minMax(cubeCorners.map(({ q }) => q)); const originCube = cubeCorners[0]; const hexContains = hexContainsChecker(hexCorners(originCube, layout)); const inRect = /* @__PURE__ */ __name((p) => p.x >= 0 && p.x <= width && p.y >= 0 && p.y <= height, "inRect"); const rectIn = /* @__PURE__ */ __name(({ x: px, y: py }) => rectCorners.some(({ x: rcx, y: rcy }) => hexContains({ x: rcx - px, y: rcy - py })), "rectIn"); for (let q = qMin; q <= qMax; q++) { for (let r = rMin; r <= rMax; r++) { const px = pixelFromQRS({ q, r }, layout); const corners = hexCorners({ q, r }, layout); if (corners.some(inRect) || rectIn(px)) { points.push({ corners, q, r, x: px.x, y: px.y }); } } } return points; }, "coverRect"); const svgForHexGrid = /* @__PURE__ */ __name((grid, layout) => { const { height, hexes, width } = grid; const { resolution } = layout; const lines = [ `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">`, `<style>path { fill: #FFFFFF; stroke: #000000; stroke-width: 1; }</style>` ]; for (const hex of hexes) { const path = [ "M", roundTo(hex.corners[0].x, resolution), roundTo(hex.corners[0].y, resolution), ...hex.corners.slice(1).map(({ x, y }) => `L ${roundTo(x, resolution)},${roundTo(y, resolution)}`), "Z" ].join(" "); lines.push(`<path d="${path}" id="q-${hex.q}-r-${hex.r}" />`); } lines.push("</svg>"); return lines.join("\n"); }, "svgForHexGrid"); export { coverRect, svgForHexGrid }; //# sourceMappingURL=covering-grid.mjs.map