grid

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2026 License: MIT Imports: 12 Imported by: 0

README

Grid

Latest Stable Version Build Status Coverage Status Go Report Card Go Dev Reference Software License

Generic 2D grid library for game development with rectangular and hexagonal layouts, spatial queries, and pathfinding.

Installation

go get github.com/gravitton/grid

Usage

Rectangular grid:

import (
	geom "github.com/gravitton/geometry"
	"github.com/gravitton/grid"
)

type Tile struct {
	Walkable bool
	Cost     float64
}

g := grid.NewRectGrid[Tile](geom.Sz(100, 100), geom.Sz(32.0, 32.0))

g.Fill(Tile{Walkable: true, Cost: 1.0})

cell := g.At(geom.Pt(499.0, 123.4))
cell.Set(Tile{Walkable: false})

Hexagonal grid:

g := grid.NewHexagonFlatTopGrid[Tile](geom.Sz(20, 20), geom.SzU(32.0))

Pathfinding:

path := g.Path(
	geom.Pt(0, 0),
	geom.Pt(10, 10),
	func(c *grid.Cell[Tile]) bool {
		return c.Get().Walkable
	},
	func(current, next *grid.Cell[Tile]) float64 {
		return next.Get().Cost
	},
)

Iterating a viewport:

for cell := range g.Iter(&grid.IterConfig{Bounds: viewport}) {
	draw(cell)
}

Iter resolves the draw order automatically from the grid type so tiles are always yielded back-to-front (painter's algorithm):

Grid type Iteration order
Rectangular (SquareFlat) Row-major, top-to-bottom
Isometric (SquareIsometric) Diagonal depth (col+row) ascending
Hex flat-top (HexFlatTop) Two-pass columns — even then odd
Hex pointy-top (HexPointyTop) Row-major (row offset is X-only)

One extra row and column are included at every edge of the bounds so partially visible tiles are never culled. Border cells may lie outside the grid — check cell.Valid() before reading data.

API

Full documentation is available at pkg.go.dev/github.com/gravitton/grid.

Types
Type Description
Grid[T] 2D grid with spatial mapping and graph operations
Cell[T] Single cell — provides value access, spatial info, and pathfinding
Array[T] Low-level flat 2D array
Point Grid coordinate with spatial query methods (Range, FieldOfView, HasLineOfSight)
Direction One of eight neighbor directions: E, NE, N, NW, W, SW, S, SE
System Movement connectivity: Cardinal (4-dir) or Diagonal (8-dir)
Constructors
Constructor Description
NewRectGrid[T](size, cellSize, opts...) Rectangular grid, 4-directional movement
NewRectGrid[T](..., RectGridOpts.DiagonalMovement()) Rectangular grid, 8-directional movement
NewIsometricRectGrid[T](size, cellSize, opts...) Isometric (diamond) grid
NewHexagonPointyTopGrid[T](size, hexSize, opts...) Hexagonal grid, pointy-top orientation
NewHexagonFlatTopGrid[T](size, hexSize, opts...) Hexagonal grid, flat-top orientation
Arr[T](size ints.Size) Standalone 2D array
Cell size helpers

These functions compute the cellSize / hexSize argument for the grid constructors.

Function Use with Description
RectCellSize(width) NewRectGrid Square tile, width px wide and tall (1:1)
IsometricRectCellSize(width) NewIsometricRectGrid Diamond tile, width px wide at true 30° angle (height ≈ width·0.577)
IsometricPixelPerfectRectCellSize(width) NewIsometricRectGrid Diamond tile, width px wide, width/2 px tall (2:1)
HexFlatTopCellSize(width) NewHexagonFlatTopGrid Flat-top hex, width px wide, width·√3/2 px tall
HexPointyTopCellSize(width) NewHexagonPointyTopGrid Pointy-top hex, width px wide, width·2/√3 px tall
HexFlatTopIsometricPixelPerfectCellSize(width) NewHexagonFlatTopGrid Flat-top hex, width px wide, width·3/4 px tall (4:3)
HexPointyTopIsometricPixelPerfectCellSize(width) NewHexagonPointyTopGrid Pointy-top hex, width px wide, width px tall (1:1)
Grid
// Size
g.Size() ints.Size
g.Width() int
g.Height() int

// Spatial
g.Bounds() floats.Rectangle
g.CellBounds() floats.Size
g.CellSpacing() floats.Size

// Access
g.Get(index ints.Point) *Cell[T]
g.Has(index ints.Point) bool
g.Set(index ints.Point, value T)
g.At(point floats.Point) *Cell[T] // world-space → cell
g.IndexAt(point floats.Point) ints.Point

// Mutation
g.Fill(value T)
g.Clear()
g.Clone() *Grid[T]

// Iteration (draw order resolved automatically from grid type)
g.Iter(config *IterConfig) iter.Seq[*Cell[T]] // config nil = full grid bounds
Cell
c.Index() ints.Point
c.Valid() bool
c.Get() *T
c.Set(value T)
c.Center() floats.Point
c.Bounds() floats.Rectangle
c.Polygon() floats.RegularPolygon
c.Neighbors() []ints.Point
c.DistanceTo(to ints.Point) int
c.Range(n int, valid ValidFunc[T]) []ints.Point
c.PathTo(to ints.Point, valid ValidFunc[T], cost CostFunc[T]) []*Cell[T]
Pathfinding

All algorithms accept an optional ValidFunc to mark cells as passable and an optional CostFunc for weighted traversal. Path uses A* internally.

Method Algorithm Field variant
Path(from, to, valid, cost) A*
AStar(from, to, valid, cost) A*
GreedyBestFirstSearch(from, to, valid) Greedy Best-First
UniformCostSearch(from, to, valid, cost) Dijkstra UniformCostSearchField
BreadthFirstSearch(from, to, valid) BFS BreadthFirstSearchField

*Field variants return the full map[ints.Point]ints.Point came-from map instead of a single path.

Array
a.Size() ints.Size
a.Width() int
a.Height() int
a.Len() int
a.Has(index ints.Point) bool
a.Get(index ints.Point) *T
a.Set(index ints.Point, value T)
a.Fill(value T)
a.Clear()
a.Clone() Array[T]
a.Iter() iter.Seq[ints.Point]
a.Iter2() iter.Seq2[ints.Point, *T]
Spatial range
g.Distance(from, to ints.Point) int
g.Range(index ints.Point, n int, valid ValidFunc[T]) []ints.Point

Both rectangular and hexagonal grids apply a field-of-view algorithm to Range — blocked cells occlude cells behind them. On rectangular grids this uses Bresenham line-of-sight; on hexagonal grids it uses the hex FoV algorithm.

Directions
// Direction constants (ordered counterclockwise from East)
E, NE, N, NW, W, SW, S, SE Direction

// Direction vectors
CardinalDirections [4]ints.Vector  // E, N, W, S
DiagonalDirections [4]ints.Vector  // NE, NW, SW, SE
Directions         [8]ints.Vector  // all 8, indexed by Direction constant

d.Opposite() Direction
d.String() string

NeighborOffsets(system System) []ints.Vector
NeighborOffset(system System, direction Direction) ints.Vector
DistanceTo(from, to ints.Point, system System) int
Point

Point is a grid coordinate with spatial query methods, mirroring the hex grid API:

p := grid.Pt(x, y)
p.Range(n int) []ints.Point
p.FieldOfView(candidates, blocking []ints.Point) []ints.Point
p.HasLineOfSight(target ints.Point, blocking []ints.Point) bool
p.Neighbors(system System) []ints.Point
p.DistanceTo(to ints.Point, system System) int
p.Point() ints.Point
Callbacks
type ValidFunc[T any]  func(current *Cell[T]) bool
type CostFunc[T any]   func(current, next *Cell[T]) float64

Credits

License

The MIT License (MIT). Please see License File for more information.

Documentation

Overview

Package grid provides generic 2D grid data structures with support for rectangular and hexagonal layouts, spatial queries, and pathfinding algorithms (BFS, UCS/Dijkstra, Greedy Best-First, A*).

Index

Constants

This section is empty.

Variables

View Source
var (
	// SquareFlat maps grid (col, row) directly to screen (x, y). Each cell is a square
	// with circumradius = size * sqrt2/2 (the half-diagonal of the bounding box).
	SquareFlat = &Transform{
		sides:       4,
		orientation: geom.FlatTop,
		toPoint:     floats.IdentityMatrix(),
		fromPoint:   floats.IdentityMatrix(),
		bounds:      floats.Vec(1.0, 1.0),
		spacing:     floats.Vec(1.0, 1.0),
		polygon:     floats.Vec(geom.Sqrt2/2, geom.Sqrt2/2),
	}

	// SquareIsometric maps grid (col, row) to an isometric (diamond) projection:
	//   screen_x = (col - row) * 0.5 * size.W
	//   screen_y = (col + row) * 0.5 * size.H
	// For the classic ~30° game-iso look use size.W = 2 * size.H.
	SquareIsometric = &Transform{
		sides:       4,
		orientation: geom.PointyTop,
		toPoint:     floats.Mat(0.5, -0.5, 0, 0.5, 0.5, 0),
		fromPoint:   floats.Mat(1, 1, 0, -1, 1, 0),
		bounds:      floats.Vec(1.0, 1.0),
		spacing:     floats.Vec(0.5, 0.5),
		polygon:     floats.Vec(0.5, 0.5),
	}

	// HexFlatTop maps axial hex (q, r) to pixel for flat-top hexagons.
	HexFlatTop = &Transform{
		sides:       6,
		orientation: geom.FlatTop,
		toPoint:     floats.Mat(3.0/2, 0, 0, geom.Sqrt3/2, geom.Sqrt3, 0),
		fromPoint:   floats.Mat(2.0/3, 0, 0, -1.0/3, geom.Sqrt3/3, 0),
		bounds:      floats.Vec(2.0, geom.Sqrt3),
		spacing:     floats.Vec(3.0/2, geom.Sqrt3),
		polygon:     floats.Vec(1.0, 1.0),
	}

	// HexPointyTop maps axial hex (q, r) to pixel for pointy-top hexagons.
	HexPointyTop = &Transform{
		sides:       6,
		orientation: geom.PointyTop,
		toPoint:     floats.Mat(geom.Sqrt3, geom.Sqrt3/2, 0, 0, 3.0/2, 0),
		fromPoint:   floats.Mat(geom.Sqrt3/3, -1.0/3, 0, 0, 2.0/3, 0),
		bounds:      floats.Vec(geom.Sqrt3, 2.0),
		spacing:     floats.Vec(geom.Sqrt3, 3.0/2),
		polygon:     floats.Vec(1.0, 1.0),
	}
)

Predefined grid layout transforms.

View Source
var CardinalDirections = [4]ints.Vector{
	geom.Vec(1, 0),
	geom.Vec(0, -1),
	geom.Vec(-1, 0),
	geom.Vec(0, 1),
}

CardinalDirections lists the 4 cardinal direction vectors: E, N, W, S.

View Source
var DiagonalDirections = [4]ints.Vector{
	geom.Vec(1, -1),
	geom.Vec(-1, -1),
	geom.Vec(-1, 1),
	geom.Vec(1, 1),
}

DiagonalDirections lists the 4 diagonal direction vectors: NE, NW, SW, SE.

View Source
var Directions = [8]ints.Vector{
	geom.Vec(1, 0),
	geom.Vec(1, -1),
	geom.Vec(0, -1),
	geom.Vec(-1, -1),
	geom.Vec(-1, 0),
	geom.Vec(-1, 1),
	geom.Vec(0, 1),
	geom.Vec(1, 1),
}

Directions lists all 8 direction vectors ordered counterclockwise from E.

View Source
var HexGridOpts hexGridOptions

HexGridOpts is the namespace for hexagonal grid options.

View Source
var LayoutOpts layoutOptions
View Source
var RectGridOpts rectGridOptions

RectGridOpts is the namespace for rectangular grid options.

Functions

func DistanceTo

func DistanceTo(from, to ints.Point, system System) int

DistanceTo returns the grid distance between two points for the given System. Cardinal uses Manhattan distance; Diagonal uses Chebyshev distance.

func HexFlatTopCellSize added in v1.1.0

func HexFlatTopCellSize(width float64) floats.Size

HexFlatTopCellSize returns the circumradius for NewHexagonFlatTopGrid where each tile is exactly width pixels wide and width·√3/2 pixels tall (2:√3 ratio).

func HexFlatTopIsometricPixelPerfectCellSize added in v1.1.0

func HexFlatTopIsometricPixelPerfectCellSize(width float64) floats.Size

HexFlatTopIsometricPixelPerfectCellSize returns the circumradius for NewHexagonFlatTopGrid where each tile is exactly width pixels wide and width·3/4 pixels tall (4:3 ratio), suitable for pixel-perfect isometric rendering.

func HexPointyTopCellSize added in v1.1.0

func HexPointyTopCellSize(width float64) floats.Size

HexPointyTopCellSize returns the circumradius for NewHexagonPointyTopGrid where each tile is exactly width pixels wide and width·2/√3 pixels tall (√3:2 ratio).

func HexPointyTopIsometricPixelPerfectCellSize added in v1.1.0

func HexPointyTopIsometricPixelPerfectCellSize(width float64) floats.Size

HexPointyTopIsometricPixelPerfectCellSize returns the circumradius for NewHexagonPointyTopGrid where each tile is exactly width pixels wide and width pixels tall (1:1 ratio), suitable for pixel-perfect isometric rendering.

func IsometricPixelPerfectRectCellSize added in v1.1.0

func IsometricPixelPerfectRectCellSize(width float64) floats.Size

IsometricPixelPerfectRectCellSize returns the cell size for NewIsometricRectGrid where each diamond tile is width pixels wide and width/2 pixels tall (2:1 ratio). The 2:1 ratio is the classic pixel-art isometric convention — tile edges land on exact pixel boundaries for crisp rendering. For a geometrically accurate 30° angle use IsometricRectCellSize.

func IsometricRectCellSize added in v1.1.0

func IsometricRectCellSize(width float64) floats.Size

IsometricRectCellSize returns the cell size for NewIsometricRectGrid where each diamond tile is width pixels wide at a geometrically accurate 30° isometric angle (height = width·tan30° ≈ width·0.577). For a pixel-art-friendly 2:1 ratio use IsometricPixelPerfectRectCellSize.

func NeighborOffset

func NeighborOffset(system System, direction Direction) ints.Vector

NeighborOffset returns the unit vector for direction in the given system. For Cardinal, only even Direction values (E, N, W, S) are valid — passing a diagonal direction returns a wrong vector or panics with index out of range.

func NeighborOffsets

func NeighborOffsets(system System) []ints.Vector

NeighborOffsets returns neighbor direction vectors for the given System. Cardinal returns 4 vectors (E, N, W, S); Diagonal returns all 8.

func RectCellSize added in v1.1.0

func RectCellSize(width float64) floats.Size

RectCellSize returns the cell size for NewRectGrid where each tile is exactly width pixels wide and width pixels tall (1:1 ratio).

Types

type Array

type Array[T any] struct {
	// contains filtered or unexported fields
}

Array is a 2D array.

func Arr

func Arr[T any](size ints.Size) Array[T]

Arr makes a new Array from Size.

func (Array[T]) Clear

func (a Array[T]) Clear()

Clear resets every element to the zero value.

func (Array[T]) Clone

func (a Array[T]) Clone() Array[T]

Clone returns a deep copy of the array.

func (Array[T]) Fill

func (a Array[T]) Fill(value T)

Fill sets every element to value.

func (Array[T]) Get

func (a Array[T]) Get(index ints.Point) *T

Get returns a pointer to the value at index. Panics if index is out of bounds.

func (Array[T]) Has

func (a Array[T]) Has(index ints.Point) bool

Has reports whether the index is within bounds.

func (Array[T]) Height

func (a Array[T]) Height() int

Height returns Array height.

func (Array[T]) Iter

func (a Array[T]) Iter() iter.Seq[ints.Point]

Iter returns iterator over all points.

func (Array[T]) Iter2

func (a Array[T]) Iter2() iter.Seq2[ints.Point, *T]

Iter2 returns an iterator over all (point, value) pairs.

func (Array[T]) Len

func (a Array[T]) Len() int

Len returns Array length.

func (Array[T]) Set

func (a Array[T]) Set(index ints.Point, value T)

Set stores value at index. Panics if index is out of bounds.

func (Array[T]) Size

func (a Array[T]) Size() ints.Size

Size returns Array size.

func (Array[T]) Width

func (a Array[T]) Width() int

Width returns Array width.

type Cell

type Cell[T any] struct {
	// contains filtered or unexported fields
}

Cell is a single cell in a Grid, identified by its index. It provides access to the cell's value, spatial properties, and graph operations.

func (Cell[T]) Bounds

func (c Cell[T]) Bounds() floats.Rectangle

Bounds returns the world-space bounding rectangle of the cell.

func (Cell[T]) Center

func (c Cell[T]) Center() floats.Point

Center returns the world-space center point of the cell.

func (Cell[T]) DistanceTo

func (c Cell[T]) DistanceTo(to ints.Point) int

DistanceTo returns the grid distance from the cell to the given index.

func (Cell[T]) Get

func (c Cell[T]) Get() *T

Get returns a pointer to the cell's value.

func (Cell[T]) Index

func (c Cell[T]) Index() ints.Point

Index returns the grid index of the cell.

func (Cell[T]) Neighbors

func (c Cell[T]) Neighbors() []ints.Point

Neighbors returns the grid indices of all valid neighbors of the cell.

func (Cell[T]) PathTo

func (c Cell[T]) PathTo(to ints.Point, valid ValidFunc[T], cost CostFunc[T]) []*Cell[T]

PathTo returns a path from the cell to the given index using A*. valid and cost are forwarded to Grid.Path.

func (Cell[T]) Polygon

func (c Cell[T]) Polygon() floats.RegularPolygon

Polygon returns the regular polygon representing the cell's shape.

func (Cell[T]) Range

func (c Cell[T]) Range(n int, valid ValidFunc[T]) []ints.Point

Range returns all cell indices within n steps that satisfy valid.

func (Cell[T]) Set

func (c Cell[T]) Set(value T)

Set sets the cell's value.

func (Cell[T]) Size

func (c Cell[T]) Size() floats.Size

Size returns the size of the cell.

func (Cell[T]) Valid

func (c Cell[T]) Valid() bool

Valid reports whether the cell's index is within the grid bounds.

type CostFunc

type CostFunc[T any] func(current, next *Cell[T]) float64

CostFunc is a function that returns the cost of moving from one cell to another.

type Direction

type Direction int

Direction represents one of the eight neighbor directions around a square cell. Directions are ordered counterclockwise starting from East (right), matching the convention used in the hexagon package.

const (
	E  Direction = iota // (1,  0)
	NE                  // (1, -1)
	N                   // (0, -1)
	NW                  // (-1,-1)
	W                   // (-1, 0)
	SW                  // (-1, 1)
	S                   // (0,  1)
	SE                  // (1,  1)
)

func (Direction) Opposite

func (d Direction) Opposite() Direction

Opposite returns the direction directly opposite to d (rotated 180°).

func (Direction) String

func (d Direction) String() string

String returns the name of the direction constant.

type Grid

type Grid[T any] struct {
	// contains filtered or unexported fields
}

Grid is a 2D grid.

func NewGrid

func NewGrid[T any](
	layout Layout,
	distance func(from, to ints.Point) int,
	toRange func(index ints.Point, n int, valid ValidIndexFunc) []ints.Point,
	neighbors func(index ints.Point) []ints.Vector,
) *Grid[T]

NewGrid creates a new grid.

func NewHexagonFlatTopGrid

func NewHexagonFlatTopGrid[T any](size ints.Size, hexSize floats.Size, opts ...HexGridOption) *Grid[T]

NewHexagonFlatTopGrid creates a new hexagon grid with a flat-top layout.

hexSize is the circumradius of each hex cell — the distance from the center to any vertex, which equals the edge length for a regular hexagon. Use equal W and H for an undistorted hex; different values skew the cell independently along each axis (e.g. Sz(0.5, 1) produces a hex that is compressed horizontally). The pixel bounding box of each cell is hexSize.W*2 wide and hexSize.H*√3 tall.

Grid cell (0, 0) is placed at the top-left: even columns are unshifted and odd columns are offset half a cell downward, so no cell center has a negative y coordinate.

func NewHexagonPointyTopGrid

func NewHexagonPointyTopGrid[T any](size ints.Size, hexSize floats.Size, opts ...HexGridOption) *Grid[T]

NewHexagonPointyTopGrid creates a new hexagon grid with a pointy-top layout.

hexSize is the circumradius of each hex cell — the distance from the center to any vertex, which equals the edge length for a regular hexagon. Use equal W and H for an undistorted hex; different values skew the cell independently along each axis (e.g. Sz(1, 0.5) produces a hex that is compressed vertically). The pixel bounding box of each cell is hexSize.W*√3 wide and hexSize.H*2 tall.

Grid cell (0, 0) is placed at the top-left: even rows are unshifted and odd rows are offset half a cell to the right, so no cell center has a negative x coordinate.

func NewIsometricRectGrid

func NewIsometricRectGrid[T any](grid ints.Size, size floats.Size, opts ...RectGridOption) *Grid[T]

NewIsometricRectGrid constructs a new isometric (diamond-projection) grid with 4-directional movement. Pass RectGridOpts.DiagonalMovement() to enable 8-directional movement.

func NewRectGrid

func NewRectGrid[T any](grid ints.Size, size floats.Size, opts ...RectGridOption) *Grid[T]

NewRectGrid constructs a new rectangular grid with 4-directional (cardinal) movement. Pass RectGridOpts.DiagonalMovement() to enable 8-directional movement.

func (*Grid[T]) AStar

func (g *Grid[T]) AStar(start, goal ints.Point, valid ValidFunc[T], cost CostFunc[T]) []ints.Point

AStar returns a path from start to goal.

func (*Grid[T]) At

func (g *Grid[T]) At(point floats.Point) *Cell[T]

At returns the cell at a given point.

func (*Grid[T]) Bounds

func (g *Grid[T]) Bounds() floats.Rectangle

Bounds returns the bounds of the grid.

func (*Grid[T]) BreadthFirstSearch

func (g *Grid[T]) BreadthFirstSearch(start, goal ints.Point, valid ValidFunc[T]) []ints.Point

BreadthFirstSearch returns a path from start to goal.

func (*Grid[T]) BreadthFirstSearchField

func (g *Grid[T]) BreadthFirstSearchField(start ints.Point, valid ValidFunc[T]) map[ints.Point]ints.Point

BreadthFirstSearchField returns a map of points to the previous point in the path.

func (*Grid[T]) CellBounds

func (g *Grid[T]) CellBounds() floats.Size

CellBounds returns the size of a cell.

func (*Grid[T]) CellHeight

func (g *Grid[T]) CellHeight() float64

CellHeight returns the height of a cell.

func (*Grid[T]) CellSpacing

func (g *Grid[T]) CellSpacing() floats.Size

CellSpacing returns the spacing between cell centers.

func (*Grid[T]) CellWidth

func (g *Grid[T]) CellWidth() float64

CellWidth returns the width of a cell.

func (*Grid[T]) Clear

func (g *Grid[T]) Clear()

Clear resets every cell to the zero value.

func (*Grid[T]) Clone

func (g *Grid[T]) Clone() *Grid[T]

Clone returns a deep copy of the grid with the same layout and cell values.

func (*Grid[T]) Distance

func (g *Grid[T]) Distance(from, to ints.Point) int

Distance returns the distance between two points.

func (*Grid[T]) Fill

func (g *Grid[T]) Fill(value T)

Fill sets every cell to value.

func (*Grid[T]) Get

func (g *Grid[T]) Get(index ints.Point) *Cell[T]

Get returns a cell.

func (*Grid[T]) GreedyBestFirstSearch

func (g *Grid[T]) GreedyBestFirstSearch(start, goal ints.Point, valid ValidFunc[T]) []ints.Point

GreedyBestFirstSearch returns a path from start to goal.

func (*Grid[T]) Has

func (g *Grid[T]) Has(index ints.Point) bool

Has reports whether the index is within the grid bounds.

func (*Grid[T]) Height

func (g *Grid[T]) Height() int

Height returns the height of the grid.

func (*Grid[T]) IndexAt

func (g *Grid[T]) IndexAt(point floats.Point) ints.Point

IndexAt returns the index of the cell at a given point.

func (*Grid[T]) Iter

func (g *Grid[T]) Iter(config *IterConfig) iter.Seq[*Cell[T]]

Iter returns an iterator over grid cells in draw order (painter's algorithm). Pass nil to iterate every cell using the full grid bounds. Pass an IterConfig to restrict iteration to a viewport subset. The iteration strategy is resolved automatically from the grid layout, so tiles are always yielded back-to-front regardless of grid type. Cells at the boundary of the bounds may lie outside the grid (cell.Valid() == false).

func (*Grid[T]) Path

func (g *Grid[T]) Path(from, to ints.Point, valid ValidFunc[T], cost CostFunc[T]) []*Cell[T]

Path returns a path from start to goal. ValidFunc and CostFunc are optional.

func (*Grid[T]) Range

func (g *Grid[T]) Range(index ints.Point, n int, valid ValidFunc[T]) []ints.Point

Range returns a slice of points in a range.

func (*Grid[T]) Set

func (g *Grid[T]) Set(index ints.Point, value T)

Set stores value at the given index. Out-of-bounds writes are no-ops.

func (*Grid[T]) Size

func (g *Grid[T]) Size() ints.Size

Size returns the size of the grid.

func (*Grid[T]) UniformCostSearch

func (g *Grid[T]) UniformCostSearch(start, goal ints.Point, valid ValidFunc[T], cost CostFunc[T]) []ints.Point

UniformCostSearch returns a path from start to goal.

func (*Grid[T]) UniformCostSearchField

func (g *Grid[T]) UniformCostSearchField(start ints.Point, valid ValidFunc[T], cost CostFunc[T]) map[ints.Point]ints.Point

UniformCostSearchField returns a map of points to the previous point in the path.

func (*Grid[T]) Width

func (g *Grid[T]) Width() int

Width returns the width of the grid.

type HexGridOption

type HexGridOption func(*hexGridOptions)

HexGridOption configures a hexagonal grid constructor.

type IterConfig

type IterConfig struct {
	Bounds floats.Rectangle
}

IterConfig configures bounds-based grid iteration. Pass a Bounds to restrict iteration to cells near the visible rectangle; one extra row and column are included on every edge so partially visible tiles are not culled. Border cells may lie outside the grid (cell.Valid() == false).

Draw order is resolved automatically from the grid layout:

  • Rectangular (SquareFlat): row-major, top-to-bottom.
  • Isometric (SquareIsometric): diagonal depth order (painter's algorithm) — depths (col+row) are visited in ascending screen-Y order.
  • Hex flat-top (HexFlatTop): two-pass column iteration — even columns then odd — so tiles in the same visual row are drawn back-to-front.
  • Hex pointy-top (HexPointyTop): row-major; the row offset is along X only, so a single pass is sufficient for correct draw order.

type Layout

type Layout struct {
	// contains filtered or unexported fields
}

Layout describes the mapping between grid coordinates and pixel space. Create one via NewLayout using a predefined transform (SquareFlat, HexFlatTop, etc.).

func NewLayout

func NewLayout(t *Transform, opts ...LayoutOption) Layout

NewLayout creates a Layout with the given transform and cell size, with the origin at (0, 0).

func (Layout) Add

func (l Layout) Add(change floats.Vector) Layout

Add returns a copy of the layout with origin shifted by change.

func (Layout) AlignTopLeft

func (l Layout) AlignTopLeft() Layout

AlignTopLeft shifts the origin so the top-left corner of cell (0, 0) sits at the world origin.

func (Layout) Bounds

func (l Layout) Bounds() floats.Rectangle

Bounds returns the pixel bounding box for the whole grid of cells. Grid size must be set via WithGridSize. If an index mapper was set via WithIndexMapper it is applied via ToPoint automatically.

func (Layout) CellBounds

func (l Layout) CellBounds() floats.Size

CellBounds returns the pixel bounding box of a single cell.

func (Layout) CellPolygon

func (l Layout) CellPolygon(index ints.Point) floats.RegularPolygon

CellPolygon returns the regular polygon representing the cell at the given grid coordinates.

func (Layout) CellSpacing

func (l Layout) CellSpacing() floats.Size

CellSpacing returns the pixel distance between adjacent cell centers along each axis.

func (Layout) FromPoint

func (l Layout) FromPoint(point floats.Point) ints.Point

FromPoint converts a pixel coordinate to the nearest grid index.

func (Layout) MoveTo

func (l Layout) MoveTo(origin floats.Point) Layout

MoveTo returns a copy of the layout with origin set to the given point.

func (Layout) Resize

func (l Layout) Resize(size floats.Size) Layout

Resize returns a copy of the layout with the cell size replaced.

func (Layout) Size

func (l Layout) Size() ints.Size

Size returns the grid dimensions.

func (Layout) ToPoint

func (l Layout) ToPoint(index ints.Point) floats.Point

ToPoint converts offset grid coordinates to the pixel center of the cell. If an index mapper was set via WithIndexMapper, it is applied first.

func (Layout) With

func (l Layout) With(opts ...LayoutOption) Layout

With returns a copy of the layout with the given options applied.

type LayoutOption

type LayoutOption func(*Layout)

LayoutOption configures a Layout.

type Point

type Point ints.Point

Point is a grid cell coordinate with spatial query methods (Range, FieldOfView, HasLineOfSight).

func Pt

func Pt(x, y int) Point

Pt constructs a Point at column x, row y.

func (Point) DistanceTo

func (p Point) DistanceTo(to ints.Point, system System) int

DistanceTo returns the grid distance between two points for the given System. Cardinal uses Manhattan distance; Diagonal uses Chebyshev distance.

func (Point) FieldOfView

func (p Point) FieldOfView(candidates []ints.Point, blocking []ints.Point) []ints.Point

FieldOfView returns the subset of candidates visible from center, given a set of blocking points. Adjacent cells (Chebyshev distance ≤ 1) are always visible.

func (Point) HasLineOfSight

func (p Point) HasLineOfSight(target ints.Point, blocking []ints.Point) bool

HasLineOfSight reports whether there is a clear line of sight from src to dst, given a set of blocking points. All intermediate cells (excluding src and dst) must not be in blocking. The destination itself may be a blocker — it is visible but does not allow sight through it.

func (Point) Neighbors

func (p Point) Neighbors(system System) []ints.Point

Neighbors returns the neighbor coordinates for every direction in system.

func (Point) Point

func (p Point) Point() ints.Point

Point returns the underlying coordinate as an ints.Point.

func (Point) Range

func (p Point) Range(n int) []ints.Point

Range returns all cells within Euclidean distance n from s, inclusive.

type RectGridOption

type RectGridOption func(*rectGridOptions)

RectGridOption configures a rectangular grid constructor.

type System

type System int

System lists the supported neighbor connectivity modes for a square grid.

const (
	// Cardinal uses 4-directional movement: N, E, S, W.
	Cardinal System = iota

	// Diagonal uses 8-directional movement: N, NE, E, SE, S, SW, W, NW.
	Diagonal
)

type Transform

type Transform struct {
	// contains filtered or unexported fields
}

Transform holds the predefined coordinate mapping data for a grid layout type. Use the package-level variables (SquareFlat, SquareIsometric, HexFlatTop, HexPointyTop) or NewTransform to construct a Layout.

func NewTransform

func NewTransform(sides int, orientation geom.Orientation, toPoint, fromPoint floats.Matrix, bounds, spacing, polygon floats.Vector) *Transform

NewTransform creates a custom transform for use with NewLayout. toPoint and fromPoint must be inverses of each other. bounds, spacing, and polygon are unit-space vectors scaled by the cell size at layout creation.

type ValidFunc

type ValidFunc[T any] func(current *Cell[T]) bool

ValidFunc is a function that returns true if a cell is valid.

type ValidIndexFunc

type ValidIndexFunc func(index ints.Point) bool

ValidIndexFunc is a function that returns true if an index is valid.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL