GitHubGet started

package pathfind

import "github.com/nsgo-dev/game/pkg/pathfind"

Overview

Package pathfind provides deterministic 2D pathfinding: grid A* (with line-of-sight smoothing, bounded expansion budgets, partial paths, incremental searches, and budgeted request queues), HPA* hierarchical pathfinding with incremental cluster updates, Jump Point Search (JPS) for uniform-cost grids, generic graph A*/Dijkstra/range search with hex tilemap adapters and 2D/3D waypoint graphs, square, hexagonal and staggered grid topologies read from tilemaps, and 2D navigation meshes (single or tiled, with dynamic obstacles) with funnel smoothing, polygon areas/filters, off-mesh links, reusable zero-allocation queries, and path-corridor navigation agents.

Everything runs cleanly on game.Loop's fixed steps with no background goroutines and no hidden global randomness.

Index

Constants

const (
	// DefaultHPAClusterSize is the default width and height in cells of each HPA* cluster.
	DefaultHPAClusterSize = 16
	// DefaultHPAMaxEntranceSpan is the maximum contiguous walkable border span represented by a single entrance before splitting into endpoint entrances.
	DefaultHPAMaxEntranceSpan = 6
)
const NavLinkOffMesh uint32 = 1 << 0

NavLinkOffMesh is a link flag marking a portal as an off-mesh connection (such as a jump, drop-down, ladder, or teleport) rather than a shared polygon edge.

Functions

func GridLineOfSight(g Grid, a, b core.Point, opts GridPathOptions) bool

GridLineOfSight reports whether a circular body of radius opts.Radius can move straight from a to b on g without passing within opts.Radius of any blocked cell (!g.Walkable(col, row)).

Returns false when g is nil, has non-positive dimensions, or either endpoint lies outside the grid's world bounds.

func SmoothGridPath(g Grid, path []Cell, opts GridPathOptions) []core.Point

SmoothGridPath converts a grid cell path (such as from AStar.Find) into world-space waypoints, dropping intermediate cells whenever a body of radius opts.Radius can walk straight between kept waypoints without passing within opts.Radius of any blocked cell.

SmoothGridPath checks walkability via g.Walkable and ignores CostGrid terrain weights. When smoothing with a positive opts.Radius, pair it with standard cell-by-cell AStar (AnyAngle: false) so corner cells remain available when the body radius cannot clear a corner directly.

It allocates only the returned waypoint slice; use SmoothGridPathInto to reuse a caller-owned slice with zero allocations.

func SmoothGridPathInto(dst []core.Point, g Grid, path []Cell, opts GridPathOptions) []core.Point

SmoothGridPathInto behaves like SmoothGridPath but appends the smoothed waypoints into dst[:0], avoiding heap allocations when dst has enough capacity.

Types

type AStar struct {
	// Diagonal allows 8-way movement with step distance sqrt(2) on diagonals; false restricts movement to 4 cardinal directions.
	// On hexagonal topologies Diagonal has no effect; TopologySquare4 and TopologySquare8 override Diagonal.
	Diagonal bool
	// NoCornerCutting prevents diagonal moves when either adjacent cardinal cell is blocked. It only takes effect when diagonal moves are enabled, and also prevents Theta* any-angle lines of sight from grazing blocked cell corners when AnyAngle is true.
	NoCornerCutting bool
	// AnyAngle enables Theta*-style any-angle pathfinding on square grids (TopologySquare, TopologySquare4, TopologySquare8),
	// linking neighbors directly to an ancestor cell whenever line of sight between cell centers is unobstructed across uniform-cost cells.
	// AnyAngle is ignored on hexagonal or staggered topologies and on EdgeCostGrid maps.
	// When smoothing a path for a body with positive clearance radius, prefer standard cell-by-cell A* (AnyAngle: false) followed by SmoothGridPath or SmoothGridPathInto.
	AnyAngle bool
	// Topology selects the cell adjacency and admissible distance heuristic. The zero value (TopologySquare) preserves square-grid behavior.
	Topology GridTopology
	// MaxExpansions caps the number of cells expanded per Find or FindInto call.
	// Zero or negative means unlimited expansions. FindWithOptions uses this limit when PathOptions.MaxExpansions is zero.
	MaxExpansions int
	// contains filtered or unexported fields
}

AStar finds lowest-cost paths on a Grid, reusing its internal search buffers across calls.

NewAStar returns a searcher with NoCornerCutting enabled by default. An AStar is not safe for concurrent use by multiple goroutines.

func NewAStar() *AStar

NewAStar returns an AStar searcher with 4-way movement and NoCornerCutting enabled by default.

func (a *AStar) Find(g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)

Find searches g for a minimum-cost path from start to goal, returning the cells from start to goal inclusive and the total path cost.

It reuses all internal search buffers and allocates only the returned path slice.

func (a *AStar) FindInto(dst []Cell, g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)

FindInto behaves like Find but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.

func (a *AStar) FindWithOptions(g Grid, start, goal Cell, opts PathOptions) GridPathResult

FindWithOptions searches g from start to goal under opts, supporting an expansion budget and optional partial paths to the closest explored cell when the goal is unreachable or the budget runs out.

func (a *AStar) FindWithOptionsInto(dst []Cell, g Grid, start, goal Cell, opts PathOptions) GridPathResult

FindWithOptionsInto behaves like FindWithOptions but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.

func (a *AStar) MovementRange(g Grid, start Cell, budget float64) []ReachableCell

MovementRange runs a Dijkstra search from start on g under a.Topology (and a.Diagonal / a.NoCornerCutting) and returns every reachable cell whose minimum traversal cost is at most budget, ordered by ascending cost then row-major cell index.

It reuses a's internal search buffers and allocates only the returned slice.

func (a *AStar) MovementRangeInto(dst []ReachableCell, g Grid, start Cell, budget float64) []ReachableCell

MovementRangeInto behaves like MovementRange but writes results into dst[:0], avoiding heap allocations when dst has enough capacity.

func (a *AStar) MovementRangeWithCost(dst []ReachableCell, g Grid, start Cell, budget float64, edgeCost func(from, to Cell) float64) []ReachableCell

MovementRangeWithCost behaves like MovementRangeInto, and when edgeCost is non-nil uses edgeCost(from, to) as the step cost multiplier instead of CostGrid or EdgeCostGrid.

Returning a negative, NaN or infinite value from edgeCost forbids moving along that edge. Non-negative finite values (including costs between 0 and 1, such as roads) are multiplied by the step's geometric length (1 for cardinal/hex/staggered edges, sqrt(2) for diagonals).

func (a *AStar) StartSearch(g Grid, start, goal Cell, opts PathOptions) *AStarSearch

StartSearch begins an incremental grid A* search using a's configuration (Diagonal, NoCornerCutting, Topology, MaxExpansions). The returned AStarSearch owns independent search buffers so multiple searches may run across frames concurrently.

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

AStarSearch runs a deterministic grid A* search incrementally across bounded Step calls.

Stepping a search with any positive per-step expansion budget produces the exact same path, cost, partial flag, and expansion count as a single-shot AStar.FindWithOptions call. *AStarSearch implements IncrementalSearch.

func NewAStarSearch(a *AStar, g Grid, start, goal Cell, opts PathOptions) *AStarSearch

NewAStarSearch initializes an incremental grid A* search copying configuration from a (when a is nil, defaults to 4-way TopologySquare with NoCornerCutting enabled).

func (s *AStarSearch) Expansions() int

Expansions returns the cumulative number of grid cells expanded so far.

func (s *AStarSearch) Reset(a *AStar, g Grid, start, goal Cell, opts PathOptions)

Reset reinitializes s for a new query, reusing its internal search buffers.

func (s *AStarSearch) Result() GridPathResult

Result returns the search outcome once finished (or a result with Found == false while still in progress).

func (s *AStarSearch) ResultInto(dst []Cell) GridPathResult

ResultInto behaves like Result but writes the path into dst[:0] when finished.

func (s *AStarSearch) Status() SearchStatus

Status returns the search's current status.

func (s *AStarSearch) Step(maxExpansions int) (status SearchStatus, expansions int)

Step advances the search by at most maxExpansions grid cell expansions and returns the updated status and exact number of expansions performed. When maxExpansions <= 0 or the search is already finished, Step performs 0 expansions.

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

BoolGrid is a Grid backed by a flat boolean slice. All cells start walkable.

func NewBoolGrid(cols, rows int) *BoolGrid

NewBoolGrid returns a cols-by-rows grid with every cell walkable.

func (g *BoolGrid) GridSize() (cols, rows int)

GridSize returns the grid's columns and rows.

func (g *BoolGrid) SetWalkable(col, row int, walkable bool)

SetWalkable marks (col, row) as walkable or blocked. Out-of-bounds coordinates are ignored.

func (g *BoolGrid) Walkable(col, row int) bool

Walkable reports whether (col, row) is in bounds and unblocked.

type Cell struct {
	Col, Row int
}

Cell is a column and row coordinate on a grid.

type ClusterID struct {
	Col, Row int
}

ClusterID identifies a cluster in an HPA grid by its cluster column and row.

type ClusterRect struct {
	ID     ClusterID
	MinCol int
	MinRow int
	MaxCol int
	MaxRow int
}

ClusterRect describes the inclusive-exclusive cell bounds [MinCol, MaxCol) x [MinRow, MaxRow) of an HPA cluster.

type CostGrid interface {
	Grid
	MoveCost(col, row int) float64
}

CostGrid is a Grid whose walkable cells carry individual traversal costs.

MoveCost returns the cost multiplier for entering (col, row), at least 1 so the distance heuristic remains admissible; values less than or equal to 0 are treated as 1.

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

CostMap is a CostGrid backed by a flat cost slice. All cells start walkable with cost 1.

func NewCostMap(cols, rows int) *CostMap

NewCostMap returns a cols-by-rows CostMap with every cell walkable at cost 1.

func (m *CostMap) GridSize() (cols, rows int)

GridSize returns the map's columns and rows.

func (m *CostMap) MoveCost(col, row int) float64

MoveCost returns the traversal cost of entering (col, row), or 1 if unset. Costs below 1 are clamped to 1 so a cheaper cell cannot make the distance heuristic overestimate and break A*'s optimality.

func (m *CostMap) SetCost(col, row int, cost float64)

SetCost sets the traversal cost for (col, row). Negative, infinite or NaN costs mark the cell unwalkable; 0 or a cost below 1 restores the default cost of 1, as the distance heuristic assumes every step costs at least 1.

func (m *CostMap) SetWalkable(col, row int, walkable bool)

SetWalkable marks (col, row) as walkable or blocked. Unblocking a cell restores its cost to 1.

func (m *CostMap) Walkable(col, row int) bool

Walkable reports whether (col, row) is in bounds and not blocked.

type EdgeCostGrid interface {
	Grid
	EdgeCost(fromCol, fromRow, toCol, toRow int) float64
}

EdgeCostGrid is a Grid whose traversal cost depends on both the source and destination cells (for example elevation steps, river crossings or zone-of-control penalties).

EdgeCost returns the step cost multiplier for moving from (fromCol, fromRow) into (toCol, toRow). Negative, NaN or infinite values forbid that transition. During AStar searches, positive costs below 1 are clamped to 1 so the distance heuristic stays admissible; MovementRange accepts any non-negative finite cost.

type Graph[N comparable] interface {
	AppendNeighbors(dst []GraphEdge[N], node N) []GraphEdge[N]
}

Graph defines weighted directed adjacency over nodes of comparable type N.

AppendNeighbors appends all outgoing edges from node onto dst and returns the extended slice. Reusing dst lets GraphSearch expand nodes without heap allocations on repeated searches. Edges with negative, NaN, or infinite Cost are ignored.

type GraphEdge[N comparable] struct {
	To   N
	Cost float64
}

GraphEdge is a directed outgoing edge from a graph node with a finite non-negative step cost.

type GraphFunc[N comparable] struct {
	// Neighbors appends outgoing edges from node onto dst.
	Neighbors func(dst []GraphEdge[N], node N) []GraphEdge[N]
	// Estimate optionally returns an admissible heuristic from -> goal (nil uses 0 / Dijkstra).
	Estimate func(from, goal N) float64
	// Valid optionally checks whether a start or goal node is valid (nil accepts all nodes).
	Valid func(node N) bool
	// Less optionally defines a strict total order on nodes for tie-breaking.
	Less func(a, b N) bool
}

GraphFunc adapts callback functions to HeuristicGraph[N].

func (f GraphFunc[N]) AppendNeighbors(dst []GraphEdge[N], node N) []GraphEdge[N]

AppendNeighbors delegates to Neighbors when non-nil.

func (f GraphFunc[N]) Heuristic(from, goal N) float64

Heuristic delegates to Estimate when non-nil, returning 0 otherwise.

func (f GraphFunc[N]) NodeLess(a, b N) bool

NodeLess delegates to Less when non-nil.

func (f GraphFunc[N]) ValidNode(node N) bool

ValidNode delegates to Valid when non-nil, returning true otherwise.

type GraphRange[N comparable] struct {
	// contains filtered or unexported fields
}

GraphRange holds the shortest-path tree produced by GraphSearch.Range or GraphSearch.RangeInto: every node reachable from Start within Budget, its minimum cost, and the parent links needed to reconstruct the optimal path to any reached node.

func (r *GraphRange[N]) Budget() float64

Budget returns the maximum path cost budget used to compute this range.

func (r *GraphRange[N]) Contains(node N) bool

Contains reports whether node is reachable within the query's budget.

func (r *GraphRange[N]) Cost(node N) (float64, bool)

Cost returns the minimum path cost from Start to node, or (0, false) if node is not in the range.

func (r *GraphRange[N]) Len() int

Len returns the number of reachable nodes in the range.

func (r *GraphRange[N]) Nodes() []ReachableNode[N]

Nodes returns all reachable nodes and their minimum costs in deterministic order (ascending Cost, then deterministic tie-breaking order). The returned slice aliases r's internal storage and is overwritten by a subsequent RangeInto call on r.

func (r *GraphRange[N]) Parent(node N) (N, bool)

Parent returns the predecessor of node on its shortest path from Start. It returns (zero, false) for Start itself or for nodes outside the range.

func (r *GraphRange[N]) Path(node N) ([]N, bool)

Path returns the shortest path from Start to node inclusive, or (nil, false) if node is not reachable.

func (r *GraphRange[N]) PathInto(dst []N, node N) ([]N, bool)

PathInto writes the shortest path from Start to node inclusive into dst[:0], allocating zero times when dst has enough capacity.

func (r *GraphRange[N]) Start() (N, bool)

Start returns the origin node of the range query and whether the range is non-empty.

type GraphSearch[N comparable] struct {
	// MaxExpansions caps the number of node expansions per search. Zero or negative means unlimited.
	MaxExpansions int
	// Less optionally defines a strict total order on N for tie-breaking equal (f, h) nodes.
	// When nil, GraphSearch checks whether the graph implements NodeOrder[N] and falls back
	// to deterministic discovery order.
	Less func(a, b N) bool
	// contains filtered or unexported fields
}

GraphSearch performs deterministic A*, Dijkstra, and budgeted range searches over any Graph[N], reusing its internal search buffers across calls.

Tie-breaking matches AStar: lowest f, then lowest h, then Less (or the graph's NodeOrder[N]), and finally deterministic node discovery order. A GraphSearch is not safe for concurrent use.

func NewGraphSearch[N comparable]() *GraphSearch[N]

NewGraphSearch returns a new reusable GraphSearch for nodes of type N.

func (s *GraphSearch[N]) Find(g Graph[N], start, goal N) (path []N, cost float64, ok bool)

Find runs A* from start to goal on g (using g.Heuristic when g implements HeuristicGraph[N], or Dijkstra otherwise), returning the lowest-cost path inclusive of endpoints and its total cost.

Internal search buffers are reused across calls; only the returned path slice is allocated.

func (s *GraphSearch[N]) FindDijkstra(g Graph[N], start, goal N) (path []N, cost float64, ok bool)

FindDijkstra runs Dijkstra's algorithm from start to goal on g (ignoring any HeuristicGraph method), returning the lowest-cost path inclusive of endpoints and its total cost.

Internal search buffers are reused across calls; only the returned path slice is allocated.

func (s *GraphSearch[N]) FindDijkstraInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)

FindDijkstraInto behaves like FindDijkstra but writes the path into dst[:0], avoiding allocations when dst has enough capacity.

func (s *GraphSearch[N]) FindInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)

FindInto behaves like Find but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.

func (s *GraphSearch[N]) FindWithHeuristic(g Graph[N], start, goal N, h func(from, goal N) float64) (path []N, cost float64, ok bool)

FindWithHeuristic runs A* from start to goal on g using heuristic h (nil runs Dijkstra). Internal search buffers are reused across calls; only the returned path slice is allocated.

func (s *GraphSearch[N]) FindWithHeuristicInto(dst []N, g Graph[N], start, goal N, h func(from, goal N) float64) (path []N, cost float64, ok bool)

FindWithHeuristicInto behaves like FindWithHeuristic but writes the path into dst[:0], avoiding allocations when dst has enough capacity.

func (s *GraphSearch[N]) Range(g Graph[N], start N, budget float64) *GraphRange[N]

Range runs a budgeted Dijkstra search from start on g and returns a GraphRange containing every node reachable within budget, its minimum cost, and parent links for path reconstruction.

Internal search buffers are reused across calls; only the returned GraphRange is allocated.

func (s *GraphSearch[N]) RangeInto(dst *GraphRange[N], g Graph[N], start N, budget float64) *GraphRange[N]

RangeInto behaves like Range but reuses dst's storage when dst is non-nil, avoiding heap allocations after warm-up.

type Grid interface {
	// GridSize returns the grid's width in columns and height in rows.
	GridSize() (cols, rows int)
	// Walkable reports whether the cell at (col, row) can be entered.
	Walkable(col, row int) bool
}

Grid is a two-dimensional tile grid that AStar searches.

type GridFunc struct {
	Cols, Rows int
	// Walk reports whether (col, row) is walkable; a nil Walk treats all in-bounds cells as walkable.
	Walk func(col, row int) bool
	// Cost returns the traversal cost of entering (col, row); a nil Cost uses 1 everywhere.
	Cost func(col, row int) float64
}

GridFunc adapts callback functions to CostGrid, letting any tilemap or custom map plug into AStar in a few lines.

func (f GridFunc) GridSize() (cols, rows int)

GridSize returns Cols and Rows.

func (f GridFunc) MoveCost(col, row int) float64

MoveCost returns Cost(col, row) or 1 when Cost is nil or returns a value below 1: the distance heuristic assumes every step costs at least 1.

func (f GridFunc) Walkable(col, row int) bool

Walkable reports whether (col, row) is in bounds and Walk allows it.

type GridPathOptions struct {
	// Origin is the world-space coordinate of cell (0, 0)'s top-left corner.
	Origin core.Point
	// CellSize is the width and height of one square grid cell in world units.
	// Positive CellWidth or CellHeight values override CellSize on their respective axes.
	// When no positive size is set on an axis, that axis defaults to 1.
	CellSize float32
	// CellWidth overrides CellSize along the X axis when positive, supporting rectangular tiles.
	CellWidth float32
	// CellHeight overrides CellSize along the Y axis when positive, supporting rectangular tiles.
	CellHeight float32
	// Radius is the circular body radius in world units that smoothed segments must keep clear of every blocked cell.
	// Values less than or equal to 0 test a zero-width ray that still rejects corner-cutting through blocked cells.
	Radius float32
}

GridPathOptions configures world-space conversion and body clearance for SmoothGridPath, SmoothGridPathInto, and GridLineOfSight.

The zero value uses 1x1 world-unit cells rooted at (0, 0) with a zero-width line-of-sight ray (still preventing corner cuts across blocked cells).

func (o GridPathOptions) CellCenter(c Cell) core.Point

CellCenter returns the world-space center of cell c under o.

type GridPathResult struct {
	Path       []Cell
	Cost       float64
	Found      bool // true when a complete or partial path was produced
	Partial    bool // true when Path ends at the closest explored cell rather than goal
	Exhausted  bool // true when the search stopped because MaxExpansions was reached
	Expansions int  // total number of grid cells expanded during the search
}

GridPathResult is the outcome of a bounded or incremental grid A* search.

type GridTopology uint8

GridTopology selects the cell adjacency and admissible distance heuristic used by AStar and movement-range queries.

The zero value (TopologySquare) uses the square grid (4-way or 8-way depending on AStar.Diagonal), preserving backward compatibility with existing AStar callers.

const (
	// TopologySquare is an orthogonal (or diamond isometric) square grid.
	// With AStar.Diagonal false it uses 4-way cardinal neighbors and Manhattan distance;
	// with AStar.Diagonal true it uses 8-way neighbors (respecting NoCornerCutting) and octile distance.
	TopologySquare GridTopology = iota
	// TopologySquare4 forces 4-way cardinal adjacency and Manhattan distance regardless of AStar.Diagonal.
	TopologySquare4
	// TopologySquare8 forces 8-way adjacency (respecting AStar.NoCornerCutting) and octile distance regardless of AStar.Diagonal.
	TopologySquare8
	// TopologyHexPointyOdd is a pointy-top hexagonal grid with odd rows shifted right (StaggerY, StaggerOdd; Tiled default).
	TopologyHexPointyOdd
	// TopologyHexPointyEven is a pointy-top hexagonal grid with even rows shifted right (StaggerY, StaggerEven).
	TopologyHexPointyEven
	// TopologyHexFlatOdd is a flat-top hexagonal grid with odd columns shifted down (StaggerX, StaggerOdd).
	TopologyHexFlatOdd
	// TopologyHexFlatEven is a flat-top hexagonal grid with even columns shifted down (StaggerX, StaggerEven).
	TopologyHexFlatEven
	// TopologyStaggeredYOdd is a staggered isometric grid with odd rows shifted right (StaggerY, StaggerOdd).
	// With AStar.Diagonal false it moves along the 4 diamond edges; with AStar.Diagonal true it also allows the 4 vertex-adjacent diagonals.
	TopologyStaggeredYOdd
	// TopologyStaggeredYEven is a staggered isometric grid with even rows shifted right (StaggerY, StaggerEven).
	TopologyStaggeredYEven
	// TopologyStaggeredXOdd is a staggered isometric grid with odd columns shifted down (StaggerX, StaggerOdd).
	TopologyStaggeredXOdd
	// TopologyStaggeredXEven is a staggered isometric grid with even columns shifted down (StaggerX, StaggerEven).
	TopologyStaggeredXEven
)
func TopologyFromTilemap(m *tilemap.Tilemap) GridTopology

TopologyFromTilemap returns the GridTopology matching m's Orientation, StaggerAxis and StaggerIndex.

A nil tilemap, OrientationOrthogonal or OrientationIsometric returns TopologySquare (diamond isometric cells share the same 4/8-way (col, row) adjacency as orthogonal squares).

func (t GridTopology) Distance(a, b Cell) float64

Distance returns the exact open-ground step distance (and admissible A* heuristic) between a and b under t.

For TopologySquare and TopologyStaggered* it computes 4-way distance; TopologySquare8 computes octile distance; hexagonal topologies compute exact cube distance matching tilemap.Tilemap.HexDistance.

func (t GridTopology) IsHex() bool

IsHex reports whether t is one of the four hexagonal grid topologies.

func (t GridTopology) IsStaggered() bool

IsStaggered reports whether t is one of the four staggered isometric grid topologies.

func (t GridTopology) Neighbors(c Cell) []Cell

Neighbors returns the adjacent cells of c under t in deterministic order.

For TopologySquare and TopologyStaggered* it returns the 4 edge-adjacent neighbors; use TopologySquare8 for 8-way square neighbors, or NeighborsInto with an explicit diagonal flag via AStar.

func (t GridTopology) NeighborsInto(dst []Cell, c Cell) []Cell

NeighborsInto appends the adjacent cells of c under t into dst[:0].

func (t GridTopology) String() string

String returns the topology's canonical name.

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

HPA implements Hierarchical Pathfinding A* (HPA*) over a square Grid, CostGrid, or EdgeCostGrid.

It partitions the grid into fixed-size square clusters, places entrance nodes along shared cluster borders, precomputes intra-cluster shortest paths between entrances, and supports O(affected clusters) incremental updates via UpdateCell, UpdateRect, and RebuildDirty.

All search and refinement buffers are reused across calls. An HPA is not safe for concurrent use by multiple goroutines.

func NewHPA(g Grid, opts HPAOptions) *HPA

NewHPA builds an HPA* hierarchy over g with opts.

If g is nil or empty, the returned HPA is valid but all searches return ok=false.

func (h *HPA) AllowCornerCutting() bool

AllowCornerCutting reports whether diagonal moves may cut blocked corners.

func (h *HPA) ClusterAt(c Cell) (ClusterID, bool)

ClusterAt returns the ClusterID containing cell c and whether c is in bounds.

func (h *HPA) ClusterGridSize() (cols, rows int)

ClusterGridSize returns the number of cluster columns and cluster rows.

func (h *HPA) ClusterRect(id ClusterID) (ClusterRect, bool)

ClusterRect returns the cell bounds of cluster id and whether id is in bounds.

func (h *HPA) ClusterSize() int

ClusterSize returns the configured cluster width and height in cells.

func (h *HPA) Diagonal() bool

Diagonal reports whether 8-way diagonal movement is enabled.

func (h *HPA) Find(start, goal Cell) (path []Cell, cost float64, ok bool)

Find searches the hierarchical graph for a near-optimal path from start to goal, refining it into a contiguous concrete slice of walkable cells and returning the exact path cost.

func (h *HPA) FindAbstract(start, goal Cell) (waypoints []Cell, cost float64, ok bool)

FindAbstract searches only the hierarchical abstract graph without refining intra-cluster segments, returning the sequence of entrance waypoints from start to goal inclusive and the path cost.

func (h *HPA) FindAbstractInto(dst []Cell, start, goal Cell) (waypoints []Cell, cost float64, ok bool)

FindAbstractInto behaves like FindAbstract but writes the abstract waypoints into dst[:0].

func (h *HPA) FindClusters(start, goal Cell) (clusters []ClusterID, cost float64, ok bool)

FindClusters searches only the hierarchical abstract graph and returns the ordered list of clusters traversed from start to goal.

func (h *HPA) FindClustersInto(dst []ClusterID, start, goal Cell) (clusters []ClusterID, cost float64, ok bool)

FindClustersInto behaves like FindClusters but writes the traversed ClusterIDs into dst[:0].

func (h *HPA) FindInto(dst []Cell, start, goal Cell) (path []Cell, cost float64, ok bool)

FindInto behaves like Find but writes the refined cell path into dst[:0], avoiding heap allocations when dst has enough capacity.

func (h *HPA) Grid() Grid

Grid returns the underlying Grid this HPA hierarchy was built over.

func (h *HPA) GridSize() (cols, rows int)

GridSize returns the width and height of the underlying grid in cells.

func (h *HPA) RebuildDirty() int

RebuildDirty incrementally rebuilds only the borders and clusters marked dirty by UpdateCell or UpdateRect.

It returns the number of clusters rebuilt.

func (h *HPA) Stats() HPAStats

Stats returns current graph size and cluster rebuild counters.

func (h *HPA) UpdateCell(col, row int)

UpdateCell marks the cluster containing (col, row), and any shared border and neighboring cluster it touches, as dirty.

Call RebuildDirty to apply pending updates immediately, or let the next Find / FindAbstract / FindClusters call rebuild them automatically.

func (h *HPA) UpdateRect(minCol, minRow, maxCol, maxRow int)

UpdateRect marks every cluster and shared border overlapping the inclusive cell rectangle [minCol..maxCol] x [minRow..maxRow] as dirty.

type HPAOptions struct {
	// ClusterSize is the width and height of each cluster in cells.
	// Values <= 0 use DefaultHPAClusterSize (16); 1 is clamped to 2.
	ClusterSize int
	// MaxEntranceSpan is the maximum contiguous walkable border run represented by a single entrance.
	// Longer runs receive two entrances at their endpoints (plus a lowest-cost cell on weighted grids when cheaper).
	// Values <= 0 use DefaultHPAMaxEntranceSpan (6).
	MaxEntranceSpan int
	// Diagonal allows 8-way movement with step distance sqrt(2) on diagonals; false restricts movement to 4 cardinal directions.
	Diagonal bool
	// AllowCornerCutting permits diagonal moves when one or both adjacent cardinal cells are blocked.
	// When false (the default), diagonal moves never cut corners, matching NewAStar.
	AllowCornerCutting bool
}

HPAOptions configures an HPA hierarchical pathfinder.

type HPAStats struct {
	ClusterCols          int
	ClusterRows          int
	ClusterSize          int
	NodeCount            int
	DirtyClusters        int
	TotalClusterRebuilds int
	LastRebuiltClusters  int
}

HPAStats reports structural and incremental-rebuild metrics for an HPA instance.

type HeuristicGraph[N comparable] interface {
	Graph[N]
	Heuristic(from, goal N) float64
}

HeuristicGraph is a Graph that supplies an admissible lower-bound cost estimate between two nodes for A* search.

type HexGrid struct {
	// Map is the backing hexagonal tilemap. Must be non-nil with positive Width and Height.
	Map *tilemap.Tilemap
	// SolidMask selects which tilemap.TileFlags block entry into a cell.
	// When 0, defaults to tilemap.TileSolid unless Walk is set.
	SolidMask tilemap.TileFlags
	// Walk optionally overrides cell walkability for in-bounds cells.
	// When nil, a cell is walkable iff Map.FlagsAt(col, row)&effectiveSolidMask == 0.
	Walk func(col, row int) bool
	// Cost optionally returns the traversal cost of entering (col, row).
	// Negative, NaN, or infinite values mark the cell unwalkable when StepCost is nil.
	// When nil, every walkable cell has cost 1.
	Cost func(col, row int) float64
	// StepCost optionally returns the directed traversal cost from -> to, taking precedence over Cost.
	// Negative, NaN, or infinite values forbid moving along that edge.
	StepCost func(from, to Cell) float64
}

HexGrid adapts a hexagonal tilemap.Tilemap to HeuristicGraph[Cell] (and Grid / EdgeCostGrid) using tilemap.Tilemap.HexNeighbors and tilemap.Tilemap.HexDistance across all stagger axes (StaggerX, StaggerY) and stagger indices (StaggerOdd, StaggerEven).

Heuristic returns the exact cube step distance (Map.HexDistance), which is admissible whenever every step costs at least 1. When using sub-unit road costs (< 1), prefer GraphSearch.FindDijkstra, GraphSearch.Range, or GraphSearch.FindWithHeuristic with a scaled distance heuristic.

func NewHexGrid(m *tilemap.Tilemap) *HexGrid

NewHexGrid returns a HexGrid over m blocking tiles with tilemap.TileSolid and using unit step cost 1.

func (h *HexGrid) AppendNeighbors(dst []GraphEdge[Cell], c Cell) []GraphEdge[Cell]

AppendNeighbors appends all passable hexagonal neighbor transitions of c onto dst using Map.HexNeighbors in deterministic order.

func (h *HexGrid) EdgeCost(fromCol, fromRow, toCol, toRow int) float64

EdgeCost returns the directed traversal cost from (fromCol, fromRow) to (toCol, toRow) for EdgeCostGrid compatibility. Negative, NaN, or infinite values forbid the transition.

func (h *HexGrid) GridSize() (cols, rows int)

GridSize returns the underlying tilemap's width and height in cells.

func (h *HexGrid) Heuristic(from, goal Cell) float64

Heuristic returns the exact hexagonal step distance between from and goal via Map.HexDistance.

func (h *HexGrid) MoveCost(col, row int) float64

MoveCost returns the traversal cost of entering (col, row) for CostGrid compatibility, clamping values below 1 to 1 so AStar's distance heuristic remains admissible.

func (h *HexGrid) NodeLess(a, b Cell) bool

NodeLess orders cells in row-major order, matching AStar's deterministic cell-ID tie-breaking.

func (h *HexGrid) ValidNode(c Cell) bool

ValidNode reports whether c is in bounds and passable.

func (h *HexGrid) Walkable(col, row int) bool

Walkable reports whether (col, row) is in bounds and passable.

type IncrementalSearch interface {
	// Step advances the search by at most maxExpansions node expansions and returns
	// the updated status along with the exact number of expansions performed.
	// When maxExpansions <= 0 or the search is already done, Step performs 0 expansions.
	Step(maxExpansions int) (status SearchStatus, expansions int)
	// Status returns the search's current status.
	Status() SearchStatus
	// Expansions returns the cumulative number of node expansions performed so far.
	Expansions() int
}

IncrementalSearch is a deterministic path search that advances in bounded expansion steps.

*AStarSearch, *NavMeshSearch, and *pathfind3d.NavMeshSearch all implement IncrementalSearch so a single PathQueue can service mixed 2D grid, 2D NavMesh, and 3D NavMesh requests within one shared per-step expansion budget.

type JPS struct {
	// NoCornerCutting prevents diagonal moves when either adjacent cardinal cell is blocked.
	// NewJPS sets this to true, matching NewAStar.
	NoCornerCutting bool
	// contains filtered or unexported fields
}

JPS implements Jump Point Search for 8-way uniform-cost square grids, returning exact optimal paths matching AStar with Diagonal=true while skipping symmetric open-space nodes.

JPS assumes every walkable cell has uniform traversal cost 1 (ignoring CostGrid and EdgeCostGrid). Use NewJPS for a searcher with NoCornerCutting enabled by default. All internal search buffers are reused across calls; a JPS is not safe for concurrent use by multiple goroutines.

func NewJPS() *JPS

NewJPS returns a JPS searcher with NoCornerCutting enabled by default.

func (j *JPS) Find(g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)

Find searches uniform-cost square grid g for an optimal 8-way path from start to goal, returning every cell along the path from start to goal inclusive and the exact octile path cost.

func (j *JPS) FindInto(dst []Cell, g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)

FindInto behaves like Find but writes the expanded cell path into dst[:0], avoiding allocations when dst has enough capacity.

func (j *JPS) FindJumpPoints(g Grid, start, goal Cell) (waypoints []Cell, cost float64, ok bool)

FindJumpPoints searches uniform-cost square grid g and returns only the jump-point waypoints (start, turning points, and goal) together with the exact optimal 8-way cost.

func (j *JPS) FindJumpPointsInto(dst []Cell, g Grid, start, goal Cell) (waypoints []Cell, cost float64, ok bool)

FindJumpPointsInto behaves like FindJumpPoints but writes the jump points into dst[:0].

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

NavAgent navigates a 2D pathfind.NavMesh by maintaining an active polygon corridor, steering smoothly toward the next funnel corner, slowing cleanly to arrive, repairing its corridor locally when pushed or when the target shifts, and invoking callbacks for off-mesh or flagged links.

NavAgent is deterministic on fixed game.Loop steps and is not safe for concurrent use.

func NewNavAgent(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgent

NewNavAgent constructs a 2D navigation agent placed at pos on mesh.

func (a *NavAgent) ClearTarget()

ClearTarget clears the agent's goal, resets its corridor, stops velocity, and sets state to NavAgentIdle.

func (a *NavAgent) Config() NavAgentConfig

Config returns the sanitized configuration of the agent.

func (a *NavAgent) Corridor() []int

Corridor returns a copy of the agent's active polygon index corridor.

func (a *NavAgent) ForceReplan() bool

ForceReplan immediately executes a full A* replan from the agent's current position to its target, ignoring ReplanInterval and group throttling, and reports whether a valid corridor was found.

func (a *NavAgent) HasTarget() bool

HasTarget reports whether the agent currently has a target.

func (a *NavAgent) LocalRepairCount() int

LocalRepairCount returns the number of cheap local corridor repairs performed without a full A* replan.

func (a *NavAgent) NeedsReplan() bool

NeedsReplan reports whether the agent is waiting for a full A* replan.

func (a *NavAgent) NextCorner() (core.Point, bool)

NextCorner returns the next funnel steering corner along the agent's remaining corridor. Returns (zero, false) when the agent has no valid corridor.

func (a *NavAgent) Path() []core.Point

Path returns the full string-pulled waypoint path from the agent's current position to its target along its active corridor, or nil when no valid corridor exists.

func (a *NavAgent) Pos() core.Point

Pos returns the agent's current 2D position.

func (a *NavAgent) ReplanCount() int

ReplanCount returns the total number of full A* replans performed by this agent.

func (a *NavAgent) SetMesh(mesh *NavMesh)

SetMesh attaches a new NavMesh to the agent, invalidating any existing corridor so the agent replans.

func (a *NavAgent) SetPosition(pos core.Point)

SetPosition updates the agent's position (for example after physics knockback or external push). When the agent has an active corridor and is not mid-link, it attempts cheap local corridor repair immediately without running a full A* replan.

func (a *NavAgent) SetTarget(target core.Point)

SetTarget sets or updates the agent's destination.

When the agent already holds a valid corridor, SetTarget tries cheap local end-of-corridor repair (same polygon, corridor truncation, or bounded bridge extension) before scheduling a full A* replan. Agents managed by a NavAgentGroup defer full replans to NavAgentGroup.Step so MaxReplansPerStep is strictly respected.

func (a *NavAgent) SetVelocity(v core.Point)

SetVelocity overrides the agent's current velocity. Non-finite values are ignored.

func (a *NavAgent) State() NavAgentState

State returns the agent's current navigation state.

func (a *NavAgent) Step(dt time.Duration)

Step advances the agent by fixed duration dt: ticks replan cooldown, detects mesh changes, repairs the corridor locally or replans if needed, steers toward the next funnel corner, traverses off-mesh/flagged links, and settles cleanly on arrival.

func (a *NavAgent) Target() core.Point

Target returns the agent's current target position (zero when idle).

func (a *NavAgent) TraversingLink() (NavLinkEvent, bool)

TraversingLink returns the active link event while the agent is traversing an off-mesh or flagged link.

func (a *NavAgent) Vel() core.Point

Vel returns the agent's current 2D velocity.

type NavAgentConfig struct {
	// MaxSpeed is the maximum movement speed in world units per second. Defaults to 100 when <= 0.
	MaxSpeed float32
	// MaxAcceleration caps how fast velocity changes in world units per second squared.
	// Defaults to 4 * MaxSpeed when <= 0.
	MaxAcceleration float32
	// Radius is the agent's body radius in world units. Defaults to 0.5 when <= 0.
	Radius float32
	// StoppingDistance is the distance from the goal within which the agent counts as arrived.
	// Defaults to max(Radius, 0.25) when <= 0.
	StoppingDistance float32
	// ArrivalRadius is the distance from the goal inside which the agent slows down smoothly.
	// Defaults to max(StoppingDistance*3, MaxSpeed*MaxSpeed/(2*MaxAcceleration)*2) when <= 0.
	ArrivalRadius float32
	// ReplanInterval is the minimum simulation duration between automatic full A* replans.
	// Zero allows immediate replanning whenever the corridor becomes invalid.
	ReplanInterval time.Duration
	// MaxRepairDepth is the maximum number of adjacent bridge polygons searched locally when
	// repairing a displaced corridor start or moved target before falling back to a full A* replan.
	// Defaults to 2 when <= 0.
	MaxRepairDepth int
	// Filter optionally restricts which polygons this agent may traverse and sets per-area costs.
	// When nil, DefaultNavFilter() is used (all walkable non-disabled polygons at unit cost).
	Filter *NavFilter
	// OnLink is an optional callback invoked on each step while traversing an off-mesh link or
	// crossing a flagged shared-edge portal. Return true when the transition is complete; return
	// false to keep control of the agent on subsequent steps. When nil, off-mesh links traverse
	// linearly at MaxSpeed and flagged shared-edge portals are crossed automatically.
	OnLink func(agent *NavAgent, link NavLinkEvent, dt time.Duration) bool
}

NavAgentConfig configures steering, arrival, corridor repair, replan throttling, and off-mesh link traversal for a 2D NavAgent.

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

NavAgentGroup coordinates multiple 2D NavAgents with throttled, round-robin budgeted, and optionally staggered replanning so large groups chasing moving targets never spike a single frame.

func NewNavAgentGroup(cfg NavAgentGroupConfig) *NavAgentGroup

NewNavAgentGroup constructs a NavAgentGroup with the given replan budget and staggering settings.

func (g *NavAgentGroup) Add(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgent

Add creates a new NavAgent, registers it in the group, and returns it.

func (g *NavAgentGroup) AddAgent(a *NavAgent)

AddAgent attaches an existing NavAgent to the group.

func (g *NavAgentGroup) Agents() []*NavAgent

Agents returns the group's agents in deterministic registration order.

func (g *NavAgentGroup) LastStepReplans() int

LastStepReplans returns how many full A* replans executed during the most recent Step.

func (g *NavAgentGroup) Len() int

Len returns the number of agents in the group.

func (g *NavAgentGroup) Remove(a *NavAgent) bool

Remove detaches a from the group while preserving deterministic ordering of remaining agents.

func (g *NavAgentGroup) Step(dt time.Duration)

Step advances every agent in the group by dt while strictly bounding full A* replans to MaxReplansPerStep in deterministic round-robin order.

func (g *NavAgentGroup) Steps() uint64

Steps returns the number of times Step has advanced this group.

func (g *NavAgentGroup) TotalReplans() int

TotalReplans returns the cumulative number of full A* replans executed by Step across all agents.

type NavAgentGroupConfig struct {
	// MaxReplansPerStep caps how many agents perform a full A* replan in a single Step.
	// Defaults to 4 when <= 0.
	MaxReplansPerStep int
	// ReplanInterval sets the minimum duration between full replans for agents whose own
	// NavAgentConfig.ReplanInterval is 0.
	ReplanInterval time.Duration
	// StaggerStride spreads full replan eligibility across steps using agentID%stride == step%stride.
	// Defaults to 1 (every agent is eligible in round-robin order up to MaxReplansPerStep).
	StaggerStride int
}

NavAgentGroupConfig configures budgeted and staggered replanning across a group of 2D NavAgents.

type NavAgentState uint8

NavAgentState reports the navigation status of a 2D NavAgent.

const (
	// NavAgentIdle indicates the agent has no active navigation target.
	NavAgentIdle NavAgentState = iota
	// NavAgentMoving indicates the agent is actively following its polygon corridor toward its target.
	NavAgentMoving
	// NavAgentArrived indicates the agent reached its target within StoppingDistance.
	NavAgentArrived
	// NavAgentUnreachable indicates no valid corridor connects the agent to its target.
	NavAgentUnreachable
)
func (s NavAgentState) String() string

String returns a human-readable state name.

type NavArea uint8

NavArea identifies the surface or terrain category of a navigation polygon (for example road, grass, mud, water, or a door threshold). Area 0 is NavAreaDefault. Games may assign any custom uint8 ID up to 255.

const (
	// NavAreaDefault is the default walkable area assigned by BuildNavMesh.
	NavAreaDefault NavArea = 0
	// NavAreaRoad marks fast-travel surfaces such as roads or paved paths.
	NavAreaRoad NavArea = 1
	// NavAreaGrass marks ordinary open ground.
	NavAreaGrass NavArea = 2
	// NavAreaMud marks slow or difficult terrain.
	NavAreaMud NavArea = 3
	// NavAreaWater marks water surfaces typically paired with NavFlagSwim.
	NavAreaWater NavArea = 4
	// NavAreaDoor marks dynamic doorway or gate polygons.
	NavAreaDoor NavArea = 5
	// NavAreaHazard marks hazardous ground such as traps, fire, or lava.
	NavAreaHazard NavArea = 6
	// NavAreaJump marks jump or drop-off off-mesh links and landing surfaces.
	NavAreaJump NavArea = 7
	// NavAreaClimb marks climbable off-mesh links such as ladders and ledges.
	NavAreaClimb NavArea = 8
	// NavAreaTeleport marks teleporter or portal off-mesh links.
	NavAreaTeleport NavArea = 9
)
type NavFilter struct {
	// IncludeFlags requires a polygon to have at least one matching flag bit
	// when non-zero. When zero, no inclusion bit is required.
	IncludeFlags NavFlags

	// ExcludeFlags forbids any polygon with any matching flag bit set.
	ExcludeFlags NavFlags

	// AreaCosts overrides the traversal cost multiplier per NavArea.
	// Omitted areas default to 1.0. Values <= 0, NaN, or ±Inf forbid traversal
	// of that area.
	AreaCosts map[NavArea]float64

	// ExcludedAreas optionally forbids specific NavArea IDs regardless of flags.
	ExcludedAreas map[NavArea]bool
}

NavFilter controls which navigation polygons a query may traverse and how each polygon's area scales traversal cost.

A polygon with (area, flags) is traversable when:

  • area is not marked excluded in ExcludedAreas,
  • flags has no bits in common with ExcludeFlags (flags & ExcludeFlags == 0),
  • when IncludeFlags is non-zero, flags shares at least one bit with IncludeFlags (flags & IncludeFlags != 0),
  • its effective area cost multiplier is positive and finite.

Areas omitted from AreaCosts default to a cost multiplier of 1.0. Use DefaultNavFilter for a filter matching BuildNavMesh defaults (IncludeFlags: NavFlagAll, ExcludeFlags: NavFlagDisabled, unit cost for all areas).

func DefaultNavFilter() NavFilter

DefaultNavFilter returns the default query filter matching BuildNavMesh defaults: every non-zero, non-disabled polygon is traversable at unit cost (1.0).

func (f NavFilter) Allows(area NavArea, flags NavFlags) bool

Allows reports whether a polygon with the given area and flags passes the filter.

func (f NavFilter) AreaCost(area NavArea) float64

AreaCost returns the traversal cost multiplier for area. Omitted areas return 1.0. Excluded areas or areas with non-positive, NaN, or infinite configured costs return +Inf.

func (f NavFilter) Clone() NavFilter

Clone returns an independent deep copy of f.

func (f *NavFilter) ExcludeArea(area NavArea)

ExcludeArea marks area as non-traversable on f regardless of polygon flags.

func (f *NavFilter) IncludeArea(area NavArea)

IncludeArea removes area from f's ExcludedAreas set.

func (f *NavFilter) SetAreaCost(area NavArea, cost float64)

SetAreaCost sets the traversal cost multiplier for area on f.

type NavFlags uint32

NavFlags is a bitmask of runtime traversal capabilities and states on a navigation polygon (such as walk, swim, door, jump, climb, teleport, or disabled).

const (
	// NavFlagWalk marks standard ground-walkable polygons (default for BuildNavMesh).
	NavFlagWalk NavFlags = 1 << 0
	// NavFlagSwim marks water polygons traversable by swimming agents.
	NavFlagSwim NavFlags = 1 << 1
	// NavFlagDoor marks doorway or gate polygons that may open or close at runtime.
	NavFlagDoor NavFlags = 1 << 2
	// NavFlagJump marks jump or drop-off traversal polygons and off-mesh links.
	NavFlagJump NavFlags = 1 << 3
	// NavFlagClimb marks climbable off-mesh links such as ladders.
	NavFlagClimb NavFlags = 1 << 4
	// NavFlagTeleport marks teleporter or portal off-mesh links.
	NavFlagTeleport NavFlags = 1 << 5
	// NavFlagDisabled marks polygons or links disabled at runtime (excluded by DefaultNavFilter).
	NavFlagDisabled NavFlags = 1 << 31
	// NavFlagAll matches any non-zero flag bitmask.
	NavFlagAll NavFlags = ^NavFlags(0)
)
type NavLinkEvent struct {
	FromPoly int
	ToPoly   int
	Start    core.Point
	End      core.Point
	Radius   float32
	Area     NavArea
	Flags    uint32
	LinkID   int
	UserData any
	OffMesh  bool
}

NavLinkEvent describes a flagged shared-edge or off-mesh link transition encountered by a NavAgent.

type NavListenerID uint64

NavListenerID identifies a tile-change listener registered on a TiledNavMesh.

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

NavMesh is a 2D navigation mesh built from convex polygons connected across shared edges and optional point-to-point off-mesh links.

func BuildNavMesh(polys [][]core.Point) *NavMesh

BuildNavMesh constructs a NavMesh from convex 2D polygons, normalizing winding order and automatically connecting adjacent polygons along shared edges (including partial collinear overlaps).

Each polygon is assigned NavAreaDefault and NavFlagWalk. Degenerate polygons with fewer than three vertices or near-zero area are skipped.

func BuildNavMeshWithAreas(polys []NavPolygonInput) *NavMesh

BuildNavMeshWithAreas constructs a NavMesh from convex 2D polygons carrying per-polygon area IDs and runtime traversal flags, normalizing winding order and automatically connecting adjacent polygons along shared edges (including partial collinear overlaps).

Polygons with zero Flags default to NavFlagWalk. Degenerate polygons with fewer than three vertices or near-zero area are skipped.

func (m *NavMesh) AddOffMeshLink(link NavOffMeshLink) bool

AddOffMeshLink connects the polygons containing (or within link.Radius of) link.Start and link.End with a directed (or bidirectional) off-mesh portal and bumps the mesh revision. Returns false if the mesh is nil, link coordinates or Radius are invalid, either endpoint cannot attach to the mesh, or both endpoints collapse to the same point on the same polygon.

func (m *NavMesh) AddPolygonFlags(index int, flags NavFlags)

AddPolygonFlags sets the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.

func (m *NavMesh) AppendSamples(dst []core.Point, center core.Point, maxRadius, spacing float32) []core.Point

AppendSamples appends deterministic sample points lying inside m to dst and returns the extended slice.

When spacing > 0, it samples a regular grid of that world spacing, aligned to multiples of spacing and clipped to the mesh bounds (and to the square around center when maxRadius > 0), keeping every point contained in some polygon. When spacing <= 0 or is infinite, it appends each polygon's vertex centroid instead. A positive, finite maxRadius drops points farther than maxRadius from center; otherwise the whole mesh is sampled. Points are ordered row by row (increasing Y, then X) or by polygon index, and appending allocates only when dst lacks capacity.

func (m *NavMesh) BumpRevision()

BumpRevision increments the mesh revision so NavAgents watching this mesh invalidate cached corridors and replan.

func (m *NavMesh) ClearOffMeshLinks()

ClearOffMeshLinks removes all off-mesh links from m and bumps the mesh revision when any were present.

func (m *NavMesh) ClearPolygonFlags(index int, flags NavFlags)

ClearPolygonFlags clears the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.

func (m *NavMesh) Contains(p core.Point) bool

Contains reports whether p lies inside or on the boundary of any polygon in the mesh.

func (m *NavMesh) ContainsWithFilter(p core.Point, filter NavFilter) bool

ContainsWithFilter reports whether p lies inside or on the boundary of any polygon passing filter.

func (m *NavMesh) FindCorridor(start, goal core.Point) ([]int, bool)

FindCorridor finds the sequence of polygon indices from start to goal using DefaultNavFilter and portal-graph A*. Returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.

func (m *NavMesh) FindCorridorInto(dst []int, start, goal core.Point) ([]int, bool)

FindCorridorInto behaves like FindCorridor but writes polygon indices into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.

FindCorridorInto is not safe for concurrent use on the same NavMesh; use NewNavMeshQuery per goroutine.

func (m *NavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]int, bool)

FindCorridorWithFilter finds the minimum-cost sequence of polygon indices from start to goal restricted to filter. Returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.

func (m *NavMesh) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)

FindCorridorWithFilterInto behaves like FindCorridorWithFilter but writes polygon indices into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.

func (m *NavMesh) FindPath(start, goal core.Point) ([]core.Point, bool)

FindPath finds the shortest path inside the navigation mesh from start to goal using DefaultNavFilter, portal-graph A*, and Simple Stupid Funnel Algorithm string-pulling.

It returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.

func (m *NavMesh) FindPathInto(dst []core.Point, start, goal core.Point) ([]core.Point, bool)

FindPathInto behaves like FindPath but writes waypoints into dst[:0] and reuses the mesh's internal search buffers so repeated calls allocate zero heap memory once warmed up.

FindPathInto is not safe for concurrent use on the same NavMesh; construct separate NewNavMeshQuery instances when running concurrent path searches against a shared read-only NavMesh.

func (m *NavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)

FindPathWithFilter finds the minimum-cost path inside the navigation mesh from start to goal restricted to polygons allowed by filter, weighting traversal through each polygon by filter.AreaCost(area) and using an admissible distance heuristic scaled by the minimum allowed area cost.

It returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.

func (m *NavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult

FindPathWithFilterAndOptions finds a minimum-cost path inside the navigation mesh restricted to polygons allowed by filter under opts, supporting an expansion budget and optional partial paths.

func (m *NavMesh) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult

FindPathWithFilterAndOptionsInto behaves like FindPathWithFilterAndOptions but writes waypoints into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up. The returned res.Links slice reuses the mesh's internal query buffer (like dst) and is overwritten on subsequent queries.

func (m *NavMesh) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)

FindPathWithFilterInto behaves like FindPathWithFilter but writes waypoints into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.

FindPathWithFilterInto is not safe for concurrent use on the same NavMesh; use NewNavMeshQuery per goroutine.

func (m *NavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) NavPathResult

FindPathWithOptions finds a path inside the navigation mesh under DefaultNavFilter and opts, supporting an expansion budget and optional partial paths to the closest reachable point when goal is outside the mesh, in a disconnected region, or beyond MaxExpansions.

func (m *NavMesh) FindPolygon(p core.Point) int

FindPolygon returns the lowest index of a polygon containing p (including its edges and vertices), or -1 if p lies outside the mesh.

func (m *NavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) int

FindPolygonWithFilter returns the lowest index of a polygon passing filter that contains p (including its edges and vertices), or -1 if none match.

func (m *NavMesh) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)

MoveAlongSurface slides an agent from start toward target while staying on polygons allowed by DefaultNavFilter.

Returns (NavMoveResult{Point: start, Poly: -1}, false) if start lies outside the allowed mesh.

func (m *NavMesh) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)

MoveAlongSurfaceWithFilter slides an agent from start toward target while staying on polygons allowed by filter.

Returns (NavMoveResult{Point: start, Poly: -1}, false) if start lies outside the allowed mesh.

func (m *NavMesh) NearestPoint(p, extent core.Point) (point core.Point, poly int, ok bool)

NearestPoint returns the closest point on any polygon allowed by DefaultNavFilter within the axis-aligned search half-extents [p.X-extent.X, p.X+extent.X] x [p.Y-extent.Y, p.Y+extent.Y], together with that polygon's index.

Returns (zero, -1, false) if m is empty, inputs are invalid/negative, or no allowed polygon point lies within extent.

func (m *NavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (point core.Point, poly int, ok bool)

NearestPointWithFilter returns the closest point on any polygon allowed by filter within the axis-aligned search half-extents [p.X-extent.X, p.X+extent.X] x [p.Y-extent.Y, p.Y+extent.Y], together with that polygon's index.

Returns (zero, -1, false) if m is empty, inputs are invalid/negative, or no allowed polygon point lies within extent.

func (m *NavMesh) NearestPolygon(p core.Point) (index int, point core.Point, ok bool)

NearestPolygon returns the polygon closest to p and the closest point on or inside that polygon. When p lies inside a polygon, NearestPolygon returns that polygon and p itself.

func (m *NavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (index int, point core.Point, ok bool)

NearestPolygonWithFilter returns the polygon passing filter closest to p and the closest point on or inside that polygon. When p lies inside a matching polygon, NearestPolygonWithFilter returns that polygon and p itself.

func (m *NavMesh) Neighbors(index int) []int

Neighbors returns the indices of polygons sharing an edge with polygon index.

func (m *NavMesh) OffMeshLinks() []NavOffMeshLink

OffMeshLinks returns a copy of all off-mesh links registered on m in insertion order.

func (m *NavMesh) Polygon(index int) []core.Point

Polygon returns a copy of the vertices of polygon index, or nil if index is out of range.

func (m *NavMesh) PolygonArea(index int) NavArea

PolygonArea returns the area ID of polygon index, or NavAreaDefault if index is out of range.

func (m *NavMesh) PolygonCount() int

PolygonCount returns the number of valid convex polygons in the mesh.

func (m *NavMesh) PolygonFlags(index int) NavFlags

PolygonFlags returns the runtime traversal flags of polygon index, or 0 if index is out of range.

func (m *NavMesh) RandomPoint(rng *random.Stream) (point core.Point, poly int, ok bool)

RandomPoint picks an area-weighted uniformly random point anywhere on polygons allowed by DefaultNavFilter, using rng. Results are bit-identical across runs and platforms for the same seed.

Returns (zero, -1, false) if m is empty, rng is nil, or no polygons are allowed.

func (m *NavMesh) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (point core.Point, poly int, ok bool)

RandomPointAround picks an area-weighted uniformly random point within Euclidean distance radius of center on polygons allowed by DefaultNavFilter that are reachable from center's polygon. Disconnected islands are never returned, and results are bit-identical across runs and platforms for the same seed.

Returns (zero, -1, false) if m is empty, rng is nil, radius < 0, or center lies outside the allowed mesh.

func (m *NavMesh) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)

RandomPointAroundWithFilter behaves like RandomPointAround while restricting reachability and sampling to polygons allowed by filter.

func (m *NavMesh) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)

RandomPointWithFilter picks an area-weighted uniformly random point anywhere on polygons allowed by filter, using rng. Results are bit-identical across runs and platforms for the same seed.

Returns (zero, -1, false) if m is empty, rng is nil, or no polygons pass filter.

func (m *NavMesh) Raycast(start, target core.Point) (NavRaycastHit, bool)

Raycast casts a segment along the mesh surface from start toward target using DefaultNavFilter, walking shared-edge portals across allowed polygons until reaching target or hitting a boundary edge or disallowed polygon.

The second return value equals hit.Hit: false means unobstructed line of sight across the mesh (hit.T == 1, hit.Point == target, hit.Poly >= 0); true means the segment was obstructed (or start lies outside the allowed mesh, in which case hit.Poly == -1 and hit.T == 0).

func (m *NavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)

RaycastWithFilter behaves like Raycast while restricting traversal to polygons allowed by filter.

func (m *NavMesh) Revision() uint64

Revision returns a monotonically increasing number bumped whenever the mesh topology, area costs/flags, or link flags change.

func (m *NavMesh) SetEdgeFlags(fromPoly, toPoly int, flags uint32) bool

SetEdgeFlags sets custom flags on the shared-edge portal from fromPoly to toPoly and bumps the mesh revision. Returns false if no shared-edge portal connects fromPoly to toPoly.

func (m *NavMesh) SetPolygonArea(index int, area NavArea)

SetPolygonArea updates the area ID of polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.

func (m *NavMesh) SetPolygonFlags(index int, flags NavFlags)

SetPolygonFlags replaces the runtime traversal flags of polygon index without rebuilding the mesh. Out-of-range indices are ignored.

func (m *NavMesh) StartSearch(start, goal core.Point, opts PathOptions) *NavMeshSearch

StartSearch begins an incremental 2D NavMesh path search from start to goal under DefaultNavFilter and opts.

func (m *NavMesh) StartSearchWithFilter(start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearch

StartSearchWithFilter begins an incremental 2D NavMesh path search from start to goal under filter and opts.

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

NavMeshQuery holds reusable generation-stamped scratch buffers for zero-allocation pathfinding and spatial queries over a 2D NavMesh.

Create one NavMeshQuery per worker or system with NewNavMeshQuery(mesh) when running repeated queries or querying a shared read-only NavMesh from separate goroutines. A NavMeshQuery is not safe for concurrent use by multiple goroutines.

func NewNavMeshQuery(mesh *NavMesh) *NavMeshQuery

NewNavMeshQuery creates a reusable query instance bound to mesh.

func (q *NavMeshQuery) FindCorridorInto(dst []int, start, goal core.Point) ([]int, bool)

FindCorridorInto finds the polygon corridor from start to goal under DefaultNavFilter, writing polygon indices into dst[:0] with zero heap allocations after warm-up.

func (q *NavMeshQuery) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)

FindCorridorWithFilterInto finds the minimum-cost polygon corridor from start to goal restricted to filter, writing polygon indices into dst[:0] with zero heap allocations after warm-up.

func (q *NavMeshQuery) FindPathInto(dst []core.Point, start, goal core.Point) ([]core.Point, bool)

FindPathInto finds the shortest path inside q's mesh from start to goal using DefaultNavFilter, writing waypoints into dst[:0] and reusing q's internal buffers so repeated calls perform zero heap allocations once dst and q are warmed up.

func (q *NavMeshQuery) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult

FindPathWithFilterAndOptionsInto runs a bounded or partial 2D NavMesh search restricted to filter under opts, writing the resulting waypoints into dst[:0] and reusing q's internal buffers with zero heap allocations after warm-up. The returned res.Links slice reuses q's internal buffer (like dst) and is overwritten on subsequent queries on q.

func (q *NavMeshQuery) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)

FindPathWithFilterInto finds the minimum-cost path inside q's mesh from start to goal restricted to filter, writing waypoints into dst[:0] and reusing q's internal buffers with zero heap allocations after warm-up.

func (q *NavMeshQuery) Mesh() *NavMesh

Mesh returns the NavMesh currently bound to q.

func (q *NavMeshQuery) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)

MoveAlongSurface delegates to q's NavMesh.MoveAlongSurface.

func (q *NavMeshQuery) MoveAlongSurfaceInto(visitedDst []int, start, target core.Point) (NavMoveResult, bool)

MoveAlongSurfaceInto slides from start toward target under DefaultNavFilter, appending visited polygon IDs into visitedDst[:0].

func (q *NavMeshQuery) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)

MoveAlongSurfaceWithFilter delegates to q's NavMesh.MoveAlongSurfaceWithFilter.

func (q *NavMeshQuery) MoveAlongSurfaceWithFilterInto(visitedDst []int, start, target core.Point, filter NavFilter) (NavMoveResult, bool)

MoveAlongSurfaceWithFilterInto slides from start toward target under filter, appending visited polygon IDs into visitedDst[:0].

func (q *NavMeshQuery) NearestPoint(p, extent core.Point) (core.Point, int, bool)

NearestPoint delegates to q's NavMesh.NearestPoint.

func (q *NavMeshQuery) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, int, bool)

NearestPointWithFilter delegates to q's NavMesh.NearestPointWithFilter.

func (q *NavMeshQuery) PathLength(start, goal core.Point) (float64, bool)

PathLength returns the geometric length of the funnel-smoothed path inside q's mesh from start to goal. The search may use off-mesh links (their costs weigh the search, not the returned length) and ignores area costs and filters. It reports false when q has no mesh, either point lies outside every polygon, or no path connects them. Repeated calls reuse q's scratch buffers and perform zero heap allocations after warm-up.

func (q *NavMeshQuery) RandomPoint(rng *random.Stream) (core.Point, int, bool)

RandomPoint delegates to q's NavMesh.RandomPoint.

func (q *NavMeshQuery) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (core.Point, int, bool)

RandomPointAround picks a random reachable point within radius of center using q's reusable BFS and clipping buffers.

func (q *NavMeshQuery) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (core.Point, int, bool)

RandomPointAroundWithFilter picks a random reachable point within radius of center allowed by filter using q's reusable buffers.

func (q *NavMeshQuery) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (core.Point, int, bool)

RandomPointWithFilter delegates to q's NavMesh.RandomPointWithFilter.

func (q *NavMeshQuery) Raycast(start, target core.Point) (NavRaycastHit, bool)

Raycast delegates to q's NavMesh.Raycast.

func (q *NavMeshQuery) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)

RaycastWithFilter delegates to q's NavMesh.RaycastWithFilter.

func (q *NavMeshQuery) SetMesh(mesh *NavMesh)

SetMesh rebinds q to mesh while keeping its allocated scratch capacity for reuse.

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

NavMeshSearch runs a deterministic 2D NavMesh portal A* search incrementally across bounded Step calls.

Stepping a search with any positive per-step expansion budget produces the exact same path, links, partial flag, and expansion count as NavMesh.FindPathWithOptions / FindPathWithFilterAndOptions. *NavMeshSearch implements IncrementalSearch.

func NewNavMeshSearch(m *NavMesh, start, goal core.Point, opts PathOptions) *NavMeshSearch

NewNavMeshSearch initializes an incremental 2D NavMesh search from start to goal under DefaultNavFilter and opts.

func NewNavMeshSearchWithFilter(m *NavMesh, start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearch

NewNavMeshSearchWithFilter initializes an incremental 2D NavMesh search from start to goal under filter and opts.

func (s *NavMeshSearch) Expansions() int

Expansions returns the cumulative number of portal nodes expanded so far.

func (s *NavMeshSearch) Result() NavPathResult

Result returns the search outcome once finished (or a result with Found == false while still in progress).

func (s *NavMeshSearch) Status() SearchStatus

Status returns the search's current status.

func (s *NavMeshSearch) Step(maxExpansions int) (status SearchStatus, expansions int)

Step advances the search by at most maxExpansions portal node expansions and returns the updated status and exact number of expansions performed. When maxExpansions <= 0 or the search is already finished, Step performs 0 expansions.

type NavMoveResult struct {
	// Point is the final position clamped onto the mesh surface.
	Point core.Point
	// Poly is the index of the final polygon containing Point, or -1 if start lies outside the allowed mesh.
	Poly int
	// Visited is the ordered sequence of polygon indices traversed from start to Point.
	Visited []int
	// HitBoundary is true if movement was constrained by a mesh boundary edge or disallowed polygon.
	HitBoundary bool
}

NavMoveResult describes the outcome of sliding a position across a 2D NavMesh surface.

type NavObstacle struct {
	Kind        NavObstacleKind
	Mode        NavObstacleMode
	Center      core.Point   // Box and Circle center
	HalfExtents core.Point   // Box half-width and half-height (must be > 0)
	Angle       float32      // Optional Box rotation in radians (CCW)
	Radius      float32      // Circle radius (must be > 0)
	Segments    int          // Circle approximation segments (default 12, clamped to [6, 64])
	Vertices    []core.Point // Polygon vertices (at least 3; convex or concave, any winding)
	Margin      float32      // Optional outward inflation in world units (e.g. agent radius); >= 0
	Area        NavArea      // Applied in NavObstacleMark mode when non-zero (or when Flags is set)
	Flags       NavFlags     // Applied in NavObstacleMark mode (defaults to NavFlagDisabled when both Area and Flags are 0)
}

NavObstacle describes a temporary runtime obstacle applied to a 2D TiledNavMesh.

func NavBoxObstacle(minPt, maxPt core.Point) NavObstacle

NavBoxObstacle constructs an axis-aligned 2D box obstacle spanning [minPt, maxPt].

func NavCircleObstacle(center core.Point, radius float32) NavObstacle

NavCircleObstacle constructs a 2D circular obstacle centered at center with radius.

func NavOrientedBoxObstacle(center, halfExtents core.Point, angleRad float32) NavObstacle

NavOrientedBoxObstacle constructs a rotated 2D box obstacle centered at center with halfExtents and rotation angleRad.

func NavPolygonObstacle(verts []core.Point) NavObstacle

NavPolygonObstacle constructs a 2D polygonal obstacle (convex or concave) from verts.

type NavObstacleID uint64

NavObstacleID identifies a dynamic obstacle registered on a TiledNavMesh.

type NavObstacleKind uint8

NavObstacleKind selects the geometric shape of a 2D NavObstacle.

const (
	// NavObstacleBox is an axis-aligned or rotated 2D box (Center, HalfExtents, Angle).
	NavObstacleBox NavObstacleKind = iota
	// NavObstacleCircle is a 2D circle approximated by a circumscribed regular polygon (Center, Radius, Segments).
	NavObstacleCircle
	// NavObstaclePolygon is an arbitrary simple 2D polygon (Vertices, convex or concave).
	NavObstaclePolygon
)
type NavObstacleMode uint8

NavObstacleMode selects how a dynamic obstacle modifies walkable polygons in touched tiles.

const (
	// NavObstacleCarve subtracts the obstacle footprint from walkable polygons so paths detour around it.
	NavObstacleCarve NavObstacleMode = iota
	// NavObstacleMark splits walkable polygons along the obstacle footprint and applies Area/Flags
	// (defaulting to NavFlagDisabled when both Area and Flags are zero) to the covered polygons.
	NavObstacleMark
)
type NavOffMeshLink struct {
	// Start and End are the world-space endpoints on (or within Radius of) the mesh.
	Start core.Point
	End   core.Point
	// Radius is the optional endpoint snap and agent entry tolerance in world units.
	// When positive, an endpoint outside a polygon snaps to the nearest polygon point within Radius,
	// and NavAgent uses max(entryRadius, Radius) when entering the link.
	// When zero, endpoints must lie on or inside a polygon. Negative or non-finite values are rejected.
	Radius float32
	// Bidirectional adds portals in both Start->End and End->Start directions when true.
	Bidirectional bool
	// Flags stores game-defined link flags; NavLinkOffMesh is always set automatically.
	Flags uint32
	// ID is an optional game-defined link identifier delivered in NavLinkEvent.LinkID and NavPathLink.LinkID.
	ID int
	// Cost overrides the A* traversal cost when positive; <= 0 uses Euclidean distance.
	Cost float32
	// Area assigns a NavArea to the link so NavFilter can exclude it or scale its traversal cost.
	// Defaults to NavAreaDefault (0).
	Area NavArea
	// UserData holds optional game-defined metadata (such as "jump", "ladder", "teleport", or a custom value)
	// carried through to NavPathLink and NavLinkEvent.
	UserData any
}

NavOffMeshLink describes a custom off-mesh connection between two points on a 2D NavMesh (such as a jump, drop-down, ladder, door, or teleporter).

type NavPathLink struct {
	// StartIndex is the index in NavPathResult.Path where the off-mesh link begins.
	StartIndex int
	// EndIndex is the index in NavPathResult.Path where the off-mesh link ends (StartIndex + 1).
	EndIndex int
	// FromPoly and ToPoly are the source and destination polygon indices connected by the link.
	FromPoly int
	ToPoly   int
	// Start and End are the world-space entry and exit positions of the traversed link direction.
	Start core.Point
	End   core.Point
	// Radius is the link's configured connection/entry radius.
	Radius float32
	// Area is the link's navigation area.
	Area NavArea
	// Flags are the link's flags (including NavLinkOffMesh).
	Flags uint32
	// LinkID is the link's configured identifier.
	LinkID int
	// UserData is the link's configured custom metadata.
	UserData any
}

NavPathLink marks a segment in NavPathResult.Path that traverses an off-mesh link. Path[StartIndex] is the link's entry point on the mesh and Path[EndIndex] is its exit point (with EndIndex == StartIndex + 1).

type NavPathResult struct {
	Path []core.Point
	// Links lists each segment of Path that traverses an off-mesh link, in path order.
	// For each link, Path[link.StartIndex] is the entry point and Path[link.EndIndex]
	// (with EndIndex == StartIndex + 1) is the exit point.
	Links      []NavPathLink
	Found      bool // true when a complete or partial path was produced
	Partial    bool // true when Path ends at the closest reachable point rather than goal
	Exhausted  bool // true when the search stopped because MaxExpansions was reached
	Expansions int  // total number of portal nodes expanded during the search
}

NavPathResult is the outcome of a bounded or incremental 2D NavMesh search.

func (r NavPathResult) HasLinks() bool

HasLinks reports whether r traverses at least one off-mesh link.

func (r NavPathResult) LinkAt(segmentIndex int) (NavPathLink, bool)

LinkAt returns the off-mesh link traversed by path segment segmentIndex (from Path[segmentIndex] to Path[segmentIndex+1]), or (zero, false) when that segment is ordinary walking movement.

type NavPathWatchID uint64

NavPathWatchID identifies a path-invalidation watcher registered on a TiledNavMesh.

type NavPolyRef struct {
	Tile NavTileCoord
	Poly int32
	Salt uint32
}

NavPolyRef uniquely identifies a walkable convex polygon inside a 2D TiledNavMesh. Salt increments whenever the owning tile is replaced, rebuilt, or removed so stale references are detected in O(1).

func (r NavPolyRef) Valid() bool

Valid reports whether r holds a non-zero tile salt and non-negative polygon index.

type NavPolygonInput struct {
	Vertices []core.Point `yaml:"vertices"`
	Area     NavArea      `yaml:"area,omitempty"`
	Flags    NavFlags     `yaml:"flags,omitempty"`
}

NavPolygonInput describes a single convex 2D polygon together with its initial area ID and runtime traversal flags for BuildNavMeshWithAreas. A zero Flags value defaults to NavFlagWalk.

type NavRaycastHit struct {
	// Point is the impact point on the obstructing edge when Hit is true,
	// or target when the ray reaches target unobstructed (Hit is false).
	Point core.Point
	// Normal is the unit inward normal of the boundary edge that stopped the ray
	// (pointing back into the walkable polygon, opposing the ray direction), or zero when Hit is false or Poly < 0.
	Normal core.Point
	// Poly is the index of the polygon containing Point, or -1 if start lies outside the allowed mesh.
	Poly int
	// T is the normalized distance along start->target in [0, 1].
	// T is 1 when target is reached unobstructed; T is 0 when start is outside the allowed mesh.
	T float32
	// Hit is true if a mesh boundary edge or disallowed polygon obstructed the ray (or if start is outside the allowed mesh).
	Hit bool
}

NavRaycastHit describes the result of casting a segment along a 2D NavMesh surface.

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

NavTile is an independently baked 2D navigation tile covering a fixed square region [minX, maxX] x [minY, maxY]. A NavTile may be baked off the main thread with BakeNavTile and installed into a TiledNavMesh with AddTile, ReplaceTile, or SetTile.

func BakeNavTile(coord NavTileCoord, tileSize float32, origin core.Point, polys []NavPolygonInput) *NavTile

BakeNavTile bakes an independent 2D NavTile for coord from convex walkable polygons polys, clipping every polygon to the tile's exact bounds [origin + coord*tileSize, origin + (coord+1)*tileSize]. Degenerate polygons or polygons outside the tile bounds are omitted. BakeNavTile is pure and safe to call concurrently from worker goroutines.

func (t *NavTile) BasePolygonCount() int

BasePolygonCount returns the number of base walkable polygons baked into this tile.

func (t *NavTile) Bounds() (minPt, maxPt core.Point)

Bounds returns the world-space [min, max] rectangle of this tile.

func (t *NavTile) Coord() NavTileCoord

Coord returns the tile coordinate this tile was baked for.

type NavTileChange struct {
	Coord   NavTileCoord
	Kind    NavTileChangeKind
	Version uint64
}

NavTileChange describes a single tile mutation event delivered to tile listeners and path watchers.

type NavTileChangeKind uint8

NavTileChangeKind classifies why a tile in a TiledNavMesh changed.

const (
	// NavTileAdded indicates a tile was inserted into a previously empty coordinate.
	NavTileAdded NavTileChangeKind = iota
	// NavTileUpdated indicates an existing tile was replaced or rebuilt (for example due to a dynamic obstacle).
	NavTileUpdated
	// NavTileRemoved indicates an existing tile was removed from the mesh.
	NavTileRemoved
)
type NavTileCoord struct {
	X, Y int32
}

NavTileCoord identifies a fixed-size tile in a 2D TiledNavMesh.

type NavTileVersion struct {
	Coord   NavTileCoord
	Version uint64
}

NavTileVersion records a tile coordinate together with its revision number when a path was computed.

type NodeOrder[N comparable] interface {
	NodeLess(a, b N) bool
}

NodeOrder is an optional interface a Graph may implement to define a strict total order on nodes for deterministic tie-breaking when f and h scores are equal.

type PathOptions struct {
	// MaxExpansions caps the number of search nodes expanded before stopping.
	// Zero means unlimited expansions (for AStar, zero falls back to AStar.MaxExpansions when > 0);
	// a negative value always forces unlimited expansions.
	MaxExpansions int
	// AllowPartial returns a path to the explored node closest to the goal when
	// the goal is unreachable or MaxExpansions is reached, flagged with Partial = true.
	AllowPartial bool
}

PathOptions configures bounded and partial pathfinding queries across grid A* and 2D/3D navigation meshes.

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

PathQueue services multiple incremental path searches within a strict per-step node-expansion budget.

All scheduling is deterministic, single-threaded, and free of background goroutines.

func NewPathQueue(cfg PathQueueConfig) *PathQueue

NewPathQueue returns a new PathQueue with the given configuration.

func (q *PathQueue) Cancel(id PathRequestID) bool

Cancel removes a pending request from the queue. It returns true if the request was found and removed; canceled requests are not stepped again and their callbacks are not invoked.

func (q *PathQueue) Clear()

Clear removes all pending requests without invoking callbacks.

func (q *PathQueue) Completed() int

Completed returns the cumulative number of requests that finished (complete, partial, or failed).

func (q *PathQueue) IsPending(id PathRequestID) bool

IsPending reports whether id is currently queued and has not finished or been canceled.

func (q *PathQueue) Pending() int

Pending returns the number of active requests currently waiting in the queue.

func (q *PathQueue) Step(budget int) int

Step advances queued requests using at most budget total node expansions, returning the exact number of expansions performed (always in [0, budget] when budget > 0, or 0 when budget <= 0).

func (q *PathQueue) StepDefault() int

StepDefault advances queued requests using the queue's configured DefaultBudget.

func (q *PathQueue) Submit(search IncrementalSearch, priority int, onDone func(PathRequestID, SearchStatus)) PathRequestID

Submit enqueues search with the given priority (higher values run first; ties break in FIFO submission order). When the search reaches a terminal status during Step, onDone (if non-nil) is invoked synchronously with the request ID and final status.

Submitting a nil search is ignored and returns 0.

func (q *PathQueue) SubmitGrid(a *AStar, g Grid, start, goal Cell, opts PathOptions, priority int, onDone func(PathRequestID, GridPathResult)) (PathRequestID, *AStarSearch)

SubmitGrid creates an incremental AStarSearch and enqueues it on q, returning the request ID (for Cancel) and the search handle (for polling Status/Result). If onDone is non-nil, it is called with the completed GridPathResult once the search finishes.

func (q *PathQueue) SubmitNavMesh(m *NavMesh, start, goal core.Point, opts PathOptions, priority int, onDone func(PathRequestID, NavPathResult)) (PathRequestID, *NavMeshSearch)

SubmitNavMesh creates an incremental NavMeshSearch and enqueues it on q, returning the request ID (for Cancel) and the search handle (for polling Status/Result). If onDone is non-nil, it is called with the completed NavPathResult once the search finishes.

func (q *PathQueue) TotalExpansions() int

TotalExpansions returns the cumulative number of node expansions performed across all Step calls.

type PathQueueConfig struct {
	// DefaultBudget is the per-step expansion budget used by StepDefault.
	DefaultBudget int
	// Policy selects FIFO (default) or fair round-robin scheduling within each priority tier.
	Policy PathQueuePolicy
	// SliceSize caps the expansions granted per turn in PathQueueRoundRobin mode.
	// Zero or negative divides the remaining step budget evenly across requests in the active priority tier.
	SliceSize int
}

PathQueueConfig configures a PathQueue.

type PathQueuePolicy uint8

PathQueuePolicy controls how a PathQueue divides its per-step expansion budget among active requests within the same priority tier.

const (
	// PathQueueFIFO runs the highest-priority earliest-submitted request until it
	// completes or the step's remaining expansion budget is spent.
	PathQueueFIFO PathQueuePolicy = iota
	// PathQueueRoundRobin shares the step budget fairly across all active requests
	// in the highest pending priority tier in deterministic rotation order.
	PathQueueRoundRobin
)
type PathRequestID uint64

PathRequestID uniquely identifies a request submitted to a PathQueue. Zero is never assigned to a valid request.

type ReachableCell struct {
	Cell Cell
	Cost float64
}

ReachableCell is one cell returned by a movement-range query together with its minimum path cost from the start cell.

func ReachableCells(g Grid, topology GridTopology, start Cell, budget float64, edgeCost func(from, to Cell) float64) []ReachableCell

ReachableCells returns every cell reachable from start on g within budget under topology, ordered by ascending cost then row-major cell index.

When edgeCost is non-nil it overrides CostGrid and EdgeCostGrid with a custom step cost multiplier. For repeated zero-allocation queries, configure an AStar with Topology and call MovementRangeInto or MovementRangeWithCost.

type ReachableNode[N comparable] struct {
	Node N
	Cost float64
}

ReachableNode pairs a node reached by GraphSearch.Range with its minimum path cost from start.

type SearchStatus uint8

SearchStatus reports the lifecycle state of an incremental path search.

const (
	// SearchInProgress indicates the search still has work remaining and has not reached the goal or its expansion budget.
	SearchInProgress SearchStatus = iota
	// SearchComplete indicates a complete path to the goal was found.
	SearchComplete
	// SearchPartial indicates a partial path to the closest explored node was produced
	// because the goal was unreachable or MaxExpansions was reached with AllowPartial enabled.
	SearchPartial
	// SearchFailed indicates no path was produced (invalid endpoints, unreachable goal without AllowPartial, or budget exhausted without AllowPartial).
	SearchFailed
)
func (s SearchStatus) Done() bool

Done reports whether the search has reached a terminal state (complete, partial, or failed).

func (s SearchStatus) String() string

String returns a human-readable status name.

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

TiledNavMesh is a 2D navigation mesh partitioned into fixed-size square tiles that can be baked, added, removed, and replaced independently at runtime. Polygons are automatically linked across tile borders, dynamic obstacles rebuild only the touched tiles, a two-level spatial index avoids whole-mesh scans, and per-tile versions + watchers invalidate paths crossing changed tiles.

TiledNavMesh is deterministic and is not safe for concurrent mutation.

func BuildTiledNavMesh(polys [][]core.Point, tileSize float32) *TiledNavMesh

BuildTiledNavMesh constructs a 2D TiledNavMesh from convex polygons using fixed square tiles of size tileSize.

func BuildTiledNavMeshWithAreas(polys []NavPolygonInput, tileSize float32) *TiledNavMesh

BuildTiledNavMeshWithAreas constructs a 2D TiledNavMesh from convex polygons carrying per-polygon areas and flags.

func NewTiledNavMesh(cfg TiledNavMeshConfig) *TiledNavMesh

NewTiledNavMesh creates an empty 2D TiledNavMesh with cfg.

func (tm *TiledNavMesh) AddObstacle(obs NavObstacle) (NavObstacleID, bool)

AddObstacle registers a dynamic obstacle and immediately rebuilds only the touched tiles (or defers rebuild until Batch returns if called inside Batch). Returns (0, false) if tm is nil or obs has invalid geometry.

func (tm *TiledNavMesh) AddOffMeshLink(link NavOffMeshLink) bool

AddOffMeshLink connects the polygons containing (or within link.Radius of) link.Start and link.End with a directed (or bidirectional) off-mesh portal and automatically re-attaches it whenever touched tiles are replaced, rebuilt, or carved by dynamic obstacles. Returns false if tm is nil or empty, link coordinates or Radius are invalid, either endpoint cannot attach to the mesh, or both endpoints collapse to the same point on the same polygon.

func (tm *TiledNavMesh) AddTile(coord NavTileCoord, tile *NavTile) bool

AddTile installs tile at coord only if no tile currently exists at coord. Returns false if tm or tile is nil or coord is already occupied.

func (tm *TiledNavMesh) AddTileListener(fn func(NavTileChange)) NavListenerID

AddTileListener registers fn to be invoked whenever any tile is added, updated, or removed.

func (tm *TiledNavMesh) BakeTile(coord NavTileCoord, polys []NavPolygonInput) *NavTile

BakeTile bakes polys into a NavTile for coord using tm's TileSize and Origin and installs it into tm.

func (tm *TiledNavMesh) Batch(fn func())

Batch groups multiple tile or obstacle mutations so each touched tile is rebuilt at most once in deterministic sorted order when fn returns, and notifications fire once per changed tile.

func (tm *TiledNavMesh) ClearObstacles()

ClearObstacles removes all dynamic obstacles and rebuilds only tiles that had obstacles.

func (tm *TiledNavMesh) ClearOffMeshLinks()

ClearOffMeshLinks removes all off-mesh links from tm and bumps the mesh revision when any were present.

func (tm *TiledNavMesh) Contains(p core.Point) bool

Contains reports whether p lies inside any polygon of the tiled mesh.

func (tm *TiledNavMesh) ContainsWithFilter(p core.Point, filter NavFilter) bool

ContainsWithFilter reports whether p lies inside any polygon passing filter.

func (tm *TiledNavMesh) FindCorridor(start, goal core.Point) ([]NavPolyRef, bool)

FindCorridor finds the sequence of NavPolyRefs from start to goal using DefaultNavFilter.

func (tm *TiledNavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]NavPolyRef, bool)

FindCorridorWithFilter finds the sequence of NavPolyRefs from start to goal restricted to filter.

func (tm *TiledNavMesh) FindPath(start, goal core.Point) ([]core.Point, bool)

FindPath finds the shortest path inside tm from start to goal using DefaultNavFilter.

func (tm *TiledNavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)

FindPathWithFilter finds the minimum-cost path inside tm restricted to filter.

func (tm *TiledNavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) TiledNavPathResult

FindPathWithFilterAndOptions finds a minimum-cost path across tm restricted to filter and opts. Portal A* touches only visited portals (sparse state, independent of total mesh size) and runs Simple Stupid Funnel Algorithm string-pulling across tile borders so paths match an untiled NavMesh for the same geometry.

func (tm *TiledNavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) TiledNavPathResult

FindPathWithOptions finds a path using DefaultNavFilter and opts, returning the full TiledNavPathResult with tile footprint and version stamps for invalidation checking.

func (tm *TiledNavMesh) FindPolygon(p core.Point) (NavPolyRef, bool)

FindPolygon locates a polygon containing p in O(1) tile lookup + O(log P_tile) local BVH.

func (tm *TiledNavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, bool)

FindPolygonWithFilter locates a polygon passing filter that contains p.

func (tm *TiledNavMesh) HasTile(coord NavTileCoord) bool

HasTile reports whether a tile is currently installed at coord.

func (tm *TiledNavMesh) IsPathValid(res TiledNavPathResult) bool

IsPathValid reports whether every tile crossed by res is still present and unchanged since res was computed.

func (tm *TiledNavMesh) NearestPoint(p, extent core.Point) (core.Point, NavPolyRef, bool)

NearestPoint returns the closest point on any polygon allowed by DefaultNavFilter within half-extents [p - extent, p + extent], together with its NavPolyRef.

func (tm *TiledNavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, NavPolyRef, bool)

NearestPointWithFilter behaves like NearestPoint restricted to filter.

func (tm *TiledNavMesh) NearestPolygon(p core.Point) (NavPolyRef, core.Point, bool)

NearestPolygon returns the polygon closest to p and the closest point on or inside it, using the two-level spatial index (coarse tile BVH + per-tile BVH).

func (tm *TiledNavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, core.Point, bool)

NearestPolygonWithFilter returns the closest polygon passing filter and the closest point on it.

func (tm *TiledNavMesh) Neighbors(ref NavPolyRef) []NavPolyRef

Neighbors returns the polygon references sharing an edge (intra-tile or cross-tile) with ref.

func (tm *TiledNavMesh) ObstacleCount() int

ObstacleCount returns the number of active dynamic obstacles.

func (tm *TiledNavMesh) OffMeshLinks() []NavOffMeshLink

OffMeshLinks returns a copy of all off-mesh links registered on tm in insertion order.

func (tm *TiledNavMesh) Origin() core.Point

Origin returns the world-space origin of tile (0, 0).

func (tm *TiledNavMesh) Polygon(ref NavPolyRef) []core.Point

Polygon returns a copy of the vertices of ref, or nil if ref is stale or invalid.

func (tm *TiledNavMesh) PolygonArea(ref NavPolyRef) NavArea

PolygonArea returns the area of ref, or NavAreaDefault if ref is invalid.

func (tm *TiledNavMesh) PolygonCount() int

PolygonCount returns the total number of active walkable polygons across all installed tiles.

func (tm *TiledNavMesh) PolygonFlags(ref NavPolyRef) NavFlags

PolygonFlags returns the runtime flags of ref, or 0 if ref is invalid.

func (tm *TiledNavMesh) Raycast(start, target core.Point) (TiledNavRaycastHit, bool)

Raycast casts a segment along the 2D TiledNavMesh surface from start toward target using DefaultNavFilter.

func (tm *TiledNavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (TiledNavRaycastHit, bool)

RaycastWithFilter behaves like Raycast restricted to polygons allowed by filter.

func (tm *TiledNavMesh) RebuildTile(coord NavTileCoord) bool

RebuildTile rebuilds the existing tile at coord from its base polygons and active dynamic obstacles. Returns false if no tile exists at coord.

func (tm *TiledNavMesh) RemoveObstacle(id NavObstacleID) bool

RemoveObstacle removes dynamic obstacle id and rebuilds only the tiles it touched, restoring their uncarved geometry.

func (tm *TiledNavMesh) RemoveTile(coord NavTileCoord) bool

RemoveTile unloads the tile at coord, removes cross-tile border links from neighboring tiles, bumps coord's tile version, and notifies listeners / invalidates paths crossing coord.

func (tm *TiledNavMesh) RemoveTileListener(id NavListenerID) bool

RemoveTileListener unregisters a listener previously added with AddTileListener.

func (tm *TiledNavMesh) ReplaceTile(coord NavTileCoord, tile *NavTile) bool

ReplaceTile replaces the existing tile at coord with tile. Returns false if tm or tile is nil or no tile currently exists at coord.

func (tm *TiledNavMesh) Revision() uint64

Revision returns a monotonically increasing number bumped on any tile or obstacle mutation.

func (tm *TiledNavMesh) SetTile(coord NavTileCoord, tile *NavTile) bool

SetTile installs or replaces tile at coord, applying any active dynamic obstacles touching coord and linking polygons across borders with neighboring tiles.

func (tm *TiledNavMesh) TileBounds(coord NavTileCoord) (minPt, maxPt core.Point)

TileBounds returns the exact world-space [min, max] bounds of tile coord.

func (tm *TiledNavMesh) TileCoordAt(p core.Point) NavTileCoord

TileCoordAt returns the tile coordinate containing p.

func (tm *TiledNavMesh) TileCoords() []NavTileCoord

TileCoords returns all installed tile coordinates in deterministic sorted order.

func (tm *TiledNavMesh) TileCount() int

TileCount returns the number of currently installed tiles.

func (tm *TiledNavMesh) TilePolygonCount(coord NavTileCoord) int

TilePolygonCount returns the number of active polygons currently inside tile coord.

func (tm *TiledNavMesh) TileSize() float32

TileSize returns the configured tile size in world units.

func (tm *TiledNavMesh) TileVersion(coord NavTileCoord) uint64

TileVersion returns the current revision number of tile coord (0 if never modified).

func (tm *TiledNavMesh) UnwatchPath(id NavPathWatchID) bool

UnwatchPath cancels a path watcher previously registered with WatchPath.

func (tm *TiledNavMesh) UpdateObstacle(id NavObstacleID, obs NavObstacle) bool

UpdateObstacle replaces the geometry or mode of an existing dynamic obstacle id, rebuilding only tiles touched by either its old or new footprint.

func (tm *TiledNavMesh) WatchPath(tiles []NavTileCoord, onInvalidate func(NavTileChange)) NavPathWatchID

WatchPath registers a one-shot invalidation callback invoked when any tile in tiles changes. Because watchers are indexed per tile, changing a tile notifies only paths crossing that tile. Once triggered, the watch is automatically removed.

type TiledNavMeshConfig struct {
	// TileSize is the width and height of each square tile in world units.
	// Defaults to 64 when <= 0.
	TileSize float32
	// Origin is the world-space origin of tile (0, 0). Defaults to (0, 0).
	Origin core.Point
}

TiledNavMeshConfig configures a 2D TiledNavMesh.

type TiledNavPathLink struct {
	// StartIndex is the index in TiledNavPathResult.Path where the off-mesh link begins.
	StartIndex int
	// EndIndex is the index in TiledNavPathResult.Path where the off-mesh link ends (StartIndex + 1).
	EndIndex int
	// FromPoly and ToPoly are the source and destination polygon references connected by the link.
	FromPoly NavPolyRef
	ToPoly   NavPolyRef
	// Start and End are the world-space entry and exit positions of the traversed link direction.
	Start core.Point
	End   core.Point
	// Radius is the link's configured connection/entry radius.
	Radius float32
	// Area is the link's navigation area.
	Area NavArea
	// Flags are the link's flags (including NavLinkOffMesh).
	Flags uint32
	// LinkID is the link's configured identifier.
	LinkID int
	// UserData is the link's configured custom metadata.
	UserData any
}

TiledNavPathLink marks a segment in TiledNavPathResult.Path that traverses an off-mesh link. Path[StartIndex] is the link's entry point on the mesh and Path[EndIndex] is its exit point (with EndIndex == StartIndex + 1).

type TiledNavPathResult struct {
	Path     []core.Point
	Corridor []NavPolyRef
	Tiles    []NavTileVersion
	// Links lists each segment of Path that traverses an off-mesh link, in path order.
	// For each link, Path[link.StartIndex] is the entry point and Path[link.EndIndex]
	// (with EndIndex == StartIndex + 1) is the exit point.
	Links      []TiledNavPathLink
	Found      bool
	Partial    bool
	Exhausted  bool
	Expansions int
}

TiledNavPathResult is the outcome of a 2D TiledNavMesh path search, including the tile footprint and tile versions crossed so callers can detect invalidation.

func (r TiledNavPathResult) CrossesTile(coord NavTileCoord) bool

CrossesTile reports whether r's corridor passes through coord.

func (r TiledNavPathResult) HasLinks() bool

HasLinks reports whether r traverses at least one off-mesh link.

func (r TiledNavPathResult) LinkAt(segmentIndex int) (TiledNavPathLink, bool)

LinkAt returns the off-mesh link traversed by path segment segmentIndex (from Path[segmentIndex] to Path[segmentIndex+1]), or (zero, false) when that segment is ordinary walking movement.

func (r TiledNavPathResult) TileCoords() []NavTileCoord

TileCoords returns the deduplicated list of tile coordinates crossed by r.

type TiledNavRaycastHit struct {
	Point  core.Point
	Normal core.Point
	Poly   NavPolyRef
	T      float32
	Hit    bool
}

TiledNavRaycastHit describes the result of casting a segment across a 2D TiledNavMesh.

type ValidatedGraph[N comparable] interface {
	ValidNode(node N) bool
}

ValidatedGraph is an optional interface a Graph may implement to reject invalid, out-of-bounds, blocked, or removed nodes before searching.

type Vec3 struct {
	X, Y, Z float32
}

Vec3 is a 3-component float32 vector in right-handed Y-up space (+X right, +Y up, -Z forward). Its field layout matches math3d.Vec3 so callers can convert values with a zero-cost pathfind.Vec3(v) cast without importing the experimental game/math3d package from stable game/pathfind.

type WaypointEdge struct {
	To   int
	Cost float64
}

WaypointEdge is a directed outgoing edge in a WaypointGraph.

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

WaypointGraph is a weighted graph of hand-placed 2D or 3D waypoints implementing HeuristicGraph[int], ValidatedGraph[int], and NodeOrder[int].

Each added waypoint receives a stable integer ID (0, 1, 2, ...). Removing a waypoint invalidates its ID without renumbering remaining waypoints. Edges may be directed or undirected, with either automatic Euclidean-distance costs (Connect / ConnectUndirected) or explicit non-negative weights (AddEdge / AddUndirectedEdge).

Heuristic returns the Euclidean distance between two waypoints, which is admissible when every edge cost is at least Euclidean distance; use GraphSearch.FindDijkstra or FindWithHeuristic when graphs contain shortcut or portal edges cheaper than Euclidean distance.

func NewWaypointGraph() *WaypointGraph

NewWaypointGraph returns an empty WaypointGraph.

func (g *WaypointGraph) Add(pos core.Point) int

Add adds a 2D waypoint at pos (with Z = 0) and returns its stable node ID.

func (g *WaypointGraph) Add3D(pos Vec3) int

Add3D adds a 3D waypoint at pos and returns its stable node ID.

func (g *WaypointGraph) AddEdge(from, to int, cost float64) bool

AddEdge adds or updates a directed edge from -> to with explicit non-negative finite cost. Returns false if either endpoint is invalid/removed or cost is negative, NaN, or infinite.

func (g *WaypointGraph) AddUndirectedEdge(a, b int, cost float64) bool

AddUndirectedEdge adds or updates bidirectional edges between a and b with explicit non-negative finite cost. Returns false if either endpoint is invalid/removed or cost is negative, NaN, or infinite.

func (g *WaypointGraph) AppendNeighbors(dst []GraphEdge[int], id int) []GraphEdge[int]

AppendNeighbors appends all outgoing edges from id to enabled destination waypoints onto dst in deterministic ascending destination ID order.

func (g *WaypointGraph) Connect(from, to int) bool

Connect adds or updates a directed edge from -> to whose cost is the live Euclidean distance between the two waypoints. Returns false if either endpoint is invalid or removed.

func (g *WaypointGraph) ConnectUndirected(a, b int) bool

ConnectUndirected adds or updates bidirectional edges between a and b whose cost is the live Euclidean distance between them. Returns false if either endpoint is invalid or removed.

func (g *WaypointGraph) Edges(id int) []WaypointEdge

Edges returns a copy of waypoint id's outgoing edges ordered by ascending destination ID.

func (g *WaypointGraph) Enabled(id int) bool

Enabled reports whether id is an active, enabled waypoint.

func (g *WaypointGraph) Heuristic(from, goal int) float64

Heuristic returns the Euclidean distance between waypoints from and goal.

func (g *WaypointGraph) Nearest(pos core.Point) (int, bool)

Nearest returns the ID of the enabled waypoint closest to 2D point pos (in XY), breaking distance ties deterministically by lowest waypoint ID.

func (g *WaypointGraph) Nearest3D(pos Vec3) (int, bool)

Nearest3D returns the ID of the enabled waypoint closest to 3D point pos, breaking distance ties deterministically by lowest waypoint ID.

func (g *WaypointGraph) NodeCount() int

NodeCount returns the number of active (non-removed) waypoints in g.

func (g *WaypointGraph) NodeLess(a, b int) bool

NodeLess breaks search ties deterministically by ascending waypoint ID.

func (g *WaypointGraph) Points(ids []int) []core.Point

Points converts a slice of waypoint IDs into their 2D positions.

func (g *WaypointGraph) Points3D(ids []int) []Vec3

Points3D converts a slice of waypoint IDs into their 3D positions.

func (g *WaypointGraph) Points3DInto(dst []Vec3, ids []int) []Vec3

Points3DInto writes the 3D positions of ids into dst[:0], avoiding allocations when dst has enough capacity.

func (g *WaypointGraph) PointsInto(dst []core.Point, ids []int) []core.Point

PointsInto writes the 2D positions of ids into dst[:0], avoiding allocations when dst has enough capacity.

func (g *WaypointGraph) Pos(id int) (core.Point, bool)

Pos returns the 2D position of active waypoint id, or (zero, false) if id is invalid or removed.

func (g *WaypointGraph) Pos3D(id int) (Vec3, bool)

Pos3D returns the 3D position of active waypoint id, or (zero, false) if id is invalid or removed.

func (g *WaypointGraph) Remove(id int) bool

Remove deletes waypoint id and all edges incident to it while keeping all other node IDs stable. It returns false if id is invalid or already removed.

func (g *WaypointGraph) RemoveEdge(from, to int) bool

RemoveEdge removes the directed edge from -> to, returning true if it existed.

func (g *WaypointGraph) RemoveUndirectedEdge(a, b int) bool

RemoveUndirectedEdge removes both a -> b and b -> a, returning true if either existed.

func (g *WaypointGraph) SetEnabled(id int, enabled bool)

SetEnabled enables or disables an active waypoint without removing its edges. Disabled waypoints are skipped during searches and Nearest queries.

func (g *WaypointGraph) SetPos(id int, pos core.Point)

SetPos updates the 2D position of waypoint id (setting Z = 0).

func (g *WaypointGraph) SetPos3D(id int, pos Vec3)

SetPos3D updates the 3D position of waypoint id.

func (g *WaypointGraph) ValidNode(id int) bool

ValidNode reports whether id is an active, enabled waypoint in g.