Hexagonal grid math

Uniform hexagonal grid is a recurring pattern in computer games and graphics applications.
There are few operations one might need to perform:

  • finding hexagon’s position by its index in the grid;
  • picking a hexagon by mouse;
  • finding neighbor cells;
  • finding hexagon’s corner coordinates etc.

While these things do not appear hard at all (something like primary school-level geometry/arithmetics), it’s not as straightforward as with a rectangular grid, however.

What have confused me, though, is that presented solution (and code) seemed to be more complex than one could expect:

  • hexagon positions are found iteratively, based on the previously computed positions;
  • a bunch of corner cases are treated in the process;
  • a whole lot of state is stored for each hexagon;
  • there is a separate codepath for the alternative hexagon orientation mode (aka “pointy” orientation), which interwines with the main one;
  • to pick a hexagon by mouse, the code iterates on the array of hexagons, and performs generic “point-in-polygon” test for each, using stored corners’ coordinates.