Documentation
¶
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
- func GridLineOfSight(g Grid, a, b core.Point, opts GridPathOptions) bool
- func SmoothGridPath(g Grid, path []Cell, opts GridPathOptions) []core.Point
- func SmoothGridPathInto(dst []core.Point, g Grid, path []Cell, opts GridPathOptions) []core.Point
- type AStar
- func (a *AStar) Find(g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (a *AStar) FindInto(dst []Cell, g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (a *AStar) FindWithOptions(g Grid, start, goal Cell, opts PathOptions) GridPathResult
- func (a *AStar) FindWithOptionsInto(dst []Cell, g Grid, start, goal Cell, opts PathOptions) GridPathResult
- func (a *AStar) MovementRange(g Grid, start Cell, budget float64) []ReachableCell
- func (a *AStar) MovementRangeInto(dst []ReachableCell, g Grid, start Cell, budget float64) []ReachableCell
- func (a *AStar) MovementRangeWithCost(dst []ReachableCell, g Grid, start Cell, budget float64, ...) []ReachableCell
- func (a *AStar) StartSearch(g Grid, start, goal Cell, opts PathOptions) *AStarSearch
- type AStarSearch
- func (s *AStarSearch) Expansions() int
- func (s *AStarSearch) Reset(a *AStar, g Grid, start, goal Cell, opts PathOptions)
- func (s *AStarSearch) Result() GridPathResult
- func (s *AStarSearch) ResultInto(dst []Cell) GridPathResult
- func (s *AStarSearch) Status() SearchStatus
- func (s *AStarSearch) Step(maxExpansions int) (status SearchStatus, expansions int)
- type BoolGrid
- type Cell
- type ClusterID
- type ClusterRect
- type CostGrid
- type CostMap
- type EdgeCostGrid
- type Graph
- type GraphEdge
- type GraphFunc
- type GraphRange
- func (r *GraphRange[N]) Budget() float64
- func (r *GraphRange[N]) Contains(node N) bool
- func (r *GraphRange[N]) Cost(node N) (float64, bool)
- func (r *GraphRange[N]) Len() int
- func (r *GraphRange[N]) Nodes() []ReachableNode[N]
- func (r *GraphRange[N]) Parent(node N) (N, bool)
- func (r *GraphRange[N]) Path(node N) ([]N, bool)
- func (r *GraphRange[N]) PathInto(dst []N, node N) ([]N, bool)
- func (r *GraphRange[N]) Start() (N, bool)
- type GraphSearch
- func (s *GraphSearch[N]) Find(g Graph[N], start, goal N) (path []N, cost float64, ok bool)
- func (s *GraphSearch[N]) FindDijkstra(g Graph[N], start, goal N) (path []N, cost float64, ok bool)
- func (s *GraphSearch[N]) FindDijkstraInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)
- func (s *GraphSearch[N]) FindInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)
- func (s *GraphSearch[N]) FindWithHeuristic(g Graph[N], start, goal N, h func(from, goal N) float64) (path []N, cost float64, ok bool)
- 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)
- func (s *GraphSearch[N]) Range(g Graph[N], start N, budget float64) *GraphRange[N]
- func (s *GraphSearch[N]) RangeInto(dst *GraphRange[N], g Graph[N], start N, budget float64) *GraphRange[N]
- type Grid
- type GridFunc
- type GridPathOptions
- type GridPathResult
- type GridTopology
- type HPA
- func (h *HPA) AllowCornerCutting() bool
- func (h *HPA) ClusterAt(c Cell) (ClusterID, bool)
- func (h *HPA) ClusterGridSize() (cols, rows int)
- func (h *HPA) ClusterRect(id ClusterID) (ClusterRect, bool)
- func (h *HPA) ClusterSize() int
- func (h *HPA) Diagonal() bool
- func (h *HPA) Find(start, goal Cell) (path []Cell, cost float64, ok bool)
- func (h *HPA) FindAbstract(start, goal Cell) (waypoints []Cell, cost float64, ok bool)
- func (h *HPA) FindAbstractInto(dst []Cell, start, goal Cell) (waypoints []Cell, cost float64, ok bool)
- func (h *HPA) FindClusters(start, goal Cell) (clusters []ClusterID, cost float64, ok bool)
- func (h *HPA) FindClustersInto(dst []ClusterID, start, goal Cell) (clusters []ClusterID, cost float64, ok bool)
- func (h *HPA) FindInto(dst []Cell, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (h *HPA) Grid() Grid
- func (h *HPA) GridSize() (cols, rows int)
- func (h *HPA) RebuildDirty() int
- func (h *HPA) Stats() HPAStats
- func (h *HPA) UpdateCell(col, row int)
- func (h *HPA) UpdateRect(minCol, minRow, maxCol, maxRow int)
- type HPAOptions
- type HPAStats
- type HeuristicGraph
- type HexGrid
- func (h *HexGrid) AppendNeighbors(dst []GraphEdge[Cell], c Cell) []GraphEdge[Cell]
- func (h *HexGrid) EdgeCost(fromCol, fromRow, toCol, toRow int) float64
- func (h *HexGrid) GridSize() (cols, rows int)
- func (h *HexGrid) Heuristic(from, goal Cell) float64
- func (h *HexGrid) MoveCost(col, row int) float64
- func (h *HexGrid) NodeLess(a, b Cell) bool
- func (h *HexGrid) ValidNode(c Cell) bool
- func (h *HexGrid) Walkable(col, row int) bool
- type IncrementalSearch
- type JPS
- func (j *JPS) Find(g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (j *JPS) FindInto(dst []Cell, g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (j *JPS) FindJumpPoints(g Grid, start, goal Cell) (waypoints []Cell, cost float64, ok bool)
- func (j *JPS) FindJumpPointsInto(dst []Cell, g Grid, start, goal Cell) (waypoints []Cell, cost float64, ok bool)
- type NavAgent
- func (a *NavAgent) ClearTarget()
- func (a *NavAgent) Config() NavAgentConfig
- func (a *NavAgent) Corridor() []int
- func (a *NavAgent) ForceReplan() bool
- func (a *NavAgent) HasTarget() bool
- func (a *NavAgent) LocalRepairCount() int
- func (a *NavAgent) NeedsReplan() bool
- func (a *NavAgent) NextCorner() (core.Point, bool)
- func (a *NavAgent) Path() []core.Point
- func (a *NavAgent) Pos() core.Point
- func (a *NavAgent) ReplanCount() int
- func (a *NavAgent) SetMesh(mesh *NavMesh)
- func (a *NavAgent) SetPosition(pos core.Point)
- func (a *NavAgent) SetTarget(target core.Point)
- func (a *NavAgent) SetVelocity(v core.Point)
- func (a *NavAgent) State() NavAgentState
- func (a *NavAgent) Step(dt time.Duration)
- func (a *NavAgent) Target() core.Point
- func (a *NavAgent) TraversingLink() (NavLinkEvent, bool)
- func (a *NavAgent) Vel() core.Point
- type NavAgentConfig
- type NavAgentGroup
- func (g *NavAgentGroup) Add(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgent
- func (g *NavAgentGroup) AddAgent(a *NavAgent)
- func (g *NavAgentGroup) Agents() []*NavAgent
- func (g *NavAgentGroup) LastStepReplans() int
- func (g *NavAgentGroup) Len() int
- func (g *NavAgentGroup) Remove(a *NavAgent) bool
- func (g *NavAgentGroup) Step(dt time.Duration)
- func (g *NavAgentGroup) Steps() uint64
- func (g *NavAgentGroup) TotalReplans() int
- type NavAgentGroupConfig
- type NavAgentState
- type NavArea
- type NavFilter
- type NavFlags
- type NavLinkEvent
- type NavListenerID
- type NavMesh
- func (m *NavMesh) AddOffMeshLink(link NavOffMeshLink) bool
- func (m *NavMesh) AddPolygonFlags(index int, flags NavFlags)
- func (m *NavMesh) AppendSamples(dst []core.Point, center core.Point, maxRadius, spacing float32) []core.Point
- func (m *NavMesh) BumpRevision()
- func (m *NavMesh) ClearOffMeshLinks()
- func (m *NavMesh) ClearPolygonFlags(index int, flags NavFlags)
- func (m *NavMesh) Contains(p core.Point) bool
- func (m *NavMesh) ContainsWithFilter(p core.Point, filter NavFilter) bool
- func (m *NavMesh) FindCorridor(start, goal core.Point) ([]int, bool)
- func (m *NavMesh) FindCorridorInto(dst []int, start, goal core.Point) ([]int, bool)
- func (m *NavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]int, bool)
- func (m *NavMesh) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)
- func (m *NavMesh) FindPath(start, goal core.Point) ([]core.Point, bool)
- func (m *NavMesh) FindPathInto(dst []core.Point, start, goal core.Point) ([]core.Point, bool)
- func (m *NavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)
- func (m *NavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult
- func (m *NavMesh) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult
- func (m *NavMesh) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)
- func (m *NavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) NavPathResult
- func (m *NavMesh) FindPolygon(p core.Point) int
- func (m *NavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) int
- func (m *NavMesh) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)
- func (m *NavMesh) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)
- func (m *NavMesh) NearestPoint(p, extent core.Point) (point core.Point, poly int, ok bool)
- func (m *NavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (point core.Point, poly int, ok bool)
- func (m *NavMesh) NearestPolygon(p core.Point) (index int, point core.Point, ok bool)
- func (m *NavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (index int, point core.Point, ok bool)
- func (m *NavMesh) Neighbors(index int) []int
- func (m *NavMesh) OffMeshLinks() []NavOffMeshLink
- func (m *NavMesh) Polygon(index int) []core.Point
- func (m *NavMesh) PolygonArea(index int) NavArea
- func (m *NavMesh) PolygonCount() int
- func (m *NavMesh) PolygonFlags(index int) NavFlags
- func (m *NavMesh) RandomPoint(rng *random.Stream) (point core.Point, poly int, ok bool)
- func (m *NavMesh) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (point core.Point, poly int, ok bool)
- func (m *NavMesh) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)
- func (m *NavMesh) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)
- func (m *NavMesh) Raycast(start, target core.Point) (NavRaycastHit, bool)
- func (m *NavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)
- func (m *NavMesh) Revision() uint64
- func (m *NavMesh) SetEdgeFlags(fromPoly, toPoly int, flags uint32) bool
- func (m *NavMesh) SetPolygonArea(index int, area NavArea)
- func (m *NavMesh) SetPolygonFlags(index int, flags NavFlags)
- func (m *NavMesh) StartSearch(start, goal core.Point, opts PathOptions) *NavMeshSearch
- func (m *NavMesh) StartSearchWithFilter(start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearch
- type NavMeshQuery
- func (q *NavMeshQuery) FindCorridorInto(dst []int, start, goal core.Point) ([]int, bool)
- func (q *NavMeshQuery) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)
- func (q *NavMeshQuery) FindPathInto(dst []core.Point, start, goal core.Point) ([]core.Point, bool)
- func (q *NavMeshQuery) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult
- func (q *NavMeshQuery) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)
- func (q *NavMeshQuery) Mesh() *NavMesh
- func (q *NavMeshQuery) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)
- func (q *NavMeshQuery) MoveAlongSurfaceInto(visitedDst []int, start, target core.Point) (NavMoveResult, bool)
- func (q *NavMeshQuery) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)
- func (q *NavMeshQuery) MoveAlongSurfaceWithFilterInto(visitedDst []int, start, target core.Point, filter NavFilter) (NavMoveResult, bool)
- func (q *NavMeshQuery) NearestPoint(p, extent core.Point) (core.Point, int, bool)
- func (q *NavMeshQuery) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, int, bool)
- func (q *NavMeshQuery) PathLength(start, goal core.Point) (float64, bool)
- func (q *NavMeshQuery) RandomPoint(rng *random.Stream) (core.Point, int, bool)
- func (q *NavMeshQuery) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (core.Point, int, bool)
- func (q *NavMeshQuery) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (core.Point, int, bool)
- func (q *NavMeshQuery) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (core.Point, int, bool)
- func (q *NavMeshQuery) Raycast(start, target core.Point) (NavRaycastHit, bool)
- func (q *NavMeshQuery) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)
- func (q *NavMeshQuery) SetMesh(mesh *NavMesh)
- type NavMeshSearch
- type NavMoveResult
- type NavObstacle
- type NavObstacleID
- type NavObstacleKind
- type NavObstacleMode
- type NavOffMeshLink
- type NavPathLink
- type NavPathResult
- type NavPathWatchID
- type NavPolyRef
- type NavPolygonInput
- type NavRaycastHit
- type NavTile
- type NavTileChange
- type NavTileChangeKind
- type NavTileCoord
- type NavTileVersion
- type NodeOrder
- type PathOptions
- type PathQueue
- func (q *PathQueue) Cancel(id PathRequestID) bool
- func (q *PathQueue) Clear()
- func (q *PathQueue) Completed() int
- func (q *PathQueue) IsPending(id PathRequestID) bool
- func (q *PathQueue) Pending() int
- func (q *PathQueue) Step(budget int) int
- func (q *PathQueue) StepDefault() int
- func (q *PathQueue) Submit(search IncrementalSearch, priority int, ...) PathRequestID
- func (q *PathQueue) SubmitGrid(a *AStar, g Grid, start, goal Cell, opts PathOptions, priority int, ...) (PathRequestID, *AStarSearch)
- func (q *PathQueue) SubmitNavMesh(m *NavMesh, start, goal core.Point, opts PathOptions, priority int, ...) (PathRequestID, *NavMeshSearch)
- func (q *PathQueue) TotalExpansions() int
- type PathQueueConfig
- type PathQueuePolicy
- type PathRequestID
- type ReachableCell
- type ReachableNode
- type SearchStatus
- type TiledNavMesh
- func (tm *TiledNavMesh) AddObstacle(obs NavObstacle) (NavObstacleID, bool)
- func (tm *TiledNavMesh) AddOffMeshLink(link NavOffMeshLink) bool
- func (tm *TiledNavMesh) AddTile(coord NavTileCoord, tile *NavTile) bool
- func (tm *TiledNavMesh) AddTileListener(fn func(NavTileChange)) NavListenerID
- func (tm *TiledNavMesh) BakeTile(coord NavTileCoord, polys []NavPolygonInput) *NavTile
- func (tm *TiledNavMesh) Batch(fn func())
- func (tm *TiledNavMesh) ClearObstacles()
- func (tm *TiledNavMesh) ClearOffMeshLinks()
- func (tm *TiledNavMesh) Contains(p core.Point) bool
- func (tm *TiledNavMesh) ContainsWithFilter(p core.Point, filter NavFilter) bool
- func (tm *TiledNavMesh) FindCorridor(start, goal core.Point) ([]NavPolyRef, bool)
- func (tm *TiledNavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]NavPolyRef, bool)
- func (tm *TiledNavMesh) FindPath(start, goal core.Point) ([]core.Point, bool)
- func (tm *TiledNavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)
- func (tm *TiledNavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) TiledNavPathResult
- func (tm *TiledNavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) TiledNavPathResult
- func (tm *TiledNavMesh) FindPolygon(p core.Point) (NavPolyRef, bool)
- func (tm *TiledNavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, bool)
- func (tm *TiledNavMesh) HasTile(coord NavTileCoord) bool
- func (tm *TiledNavMesh) IsPathValid(res TiledNavPathResult) bool
- func (tm *TiledNavMesh) NearestPoint(p, extent core.Point) (core.Point, NavPolyRef, bool)
- func (tm *TiledNavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, NavPolyRef, bool)
- func (tm *TiledNavMesh) NearestPolygon(p core.Point) (NavPolyRef, core.Point, bool)
- func (tm *TiledNavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, core.Point, bool)
- func (tm *TiledNavMesh) Neighbors(ref NavPolyRef) []NavPolyRef
- func (tm *TiledNavMesh) ObstacleCount() int
- func (tm *TiledNavMesh) OffMeshLinks() []NavOffMeshLink
- func (tm *TiledNavMesh) Origin() core.Point
- func (tm *TiledNavMesh) Polygon(ref NavPolyRef) []core.Point
- func (tm *TiledNavMesh) PolygonArea(ref NavPolyRef) NavArea
- func (tm *TiledNavMesh) PolygonCount() int
- func (tm *TiledNavMesh) PolygonFlags(ref NavPolyRef) NavFlags
- func (tm *TiledNavMesh) Raycast(start, target core.Point) (TiledNavRaycastHit, bool)
- func (tm *TiledNavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (TiledNavRaycastHit, bool)
- func (tm *TiledNavMesh) RebuildTile(coord NavTileCoord) bool
- func (tm *TiledNavMesh) RemoveObstacle(id NavObstacleID) bool
- func (tm *TiledNavMesh) RemoveTile(coord NavTileCoord) bool
- func (tm *TiledNavMesh) RemoveTileListener(id NavListenerID) bool
- func (tm *TiledNavMesh) ReplaceTile(coord NavTileCoord, tile *NavTile) bool
- func (tm *TiledNavMesh) Revision() uint64
- func (tm *TiledNavMesh) SetTile(coord NavTileCoord, tile *NavTile) bool
- func (tm *TiledNavMesh) TileBounds(coord NavTileCoord) (minPt, maxPt core.Point)
- func (tm *TiledNavMesh) TileCoordAt(p core.Point) NavTileCoord
- func (tm *TiledNavMesh) TileCoords() []NavTileCoord
- func (tm *TiledNavMesh) TileCount() int
- func (tm *TiledNavMesh) TilePolygonCount(coord NavTileCoord) int
- func (tm *TiledNavMesh) TileSize() float32
- func (tm *TiledNavMesh) TileVersion(coord NavTileCoord) uint64
- func (tm *TiledNavMesh) UnwatchPath(id NavPathWatchID) bool
- func (tm *TiledNavMesh) UpdateObstacle(id NavObstacleID, obs NavObstacle) bool
- func (tm *TiledNavMesh) WatchPath(tiles []NavTileCoord, onInvalidate func(NavTileChange)) NavPathWatchID
- type TiledNavMeshConfig
- type TiledNavPathLink
- type TiledNavPathResult
- type TiledNavRaycastHit
- type ValidatedGraph
- type Vec3
- type WaypointEdge
- type WaypointGraph
- func (g *WaypointGraph) Add(pos core.Point) int
- func (g *WaypointGraph) Add3D(pos Vec3) int
- func (g *WaypointGraph) AddEdge(from, to int, cost float64) bool
- func (g *WaypointGraph) AddUndirectedEdge(a, b int, cost float64) bool
- func (g *WaypointGraph) AppendNeighbors(dst []GraphEdge[int], id int) []GraphEdge[int]
- func (g *WaypointGraph) Connect(from, to int) bool
- func (g *WaypointGraph) ConnectUndirected(a, b int) bool
- func (g *WaypointGraph) Edges(id int) []WaypointEdge
- func (g *WaypointGraph) Enabled(id int) bool
- func (g *WaypointGraph) Heuristic(from, goal int) float64
- func (g *WaypointGraph) Nearest(pos core.Point) (int, bool)
- func (g *WaypointGraph) Nearest3D(pos Vec3) (int, bool)
- func (g *WaypointGraph) NodeCount() int
- func (g *WaypointGraph) NodeLess(a, b int) bool
- func (g *WaypointGraph) Points(ids []int) []core.Point
- func (g *WaypointGraph) Points3D(ids []int) []Vec3
- func (g *WaypointGraph) Points3DInto(dst []Vec3, ids []int) []Vec3
- func (g *WaypointGraph) PointsInto(dst []core.Point, ids []int) []core.Point
- func (g *WaypointGraph) Pos(id int) (core.Point, bool)
- func (g *WaypointGraph) Pos3D(id int) (Vec3, bool)
- func (g *WaypointGraph) Remove(id int) bool
- func (g *WaypointGraph) RemoveEdge(from, to int) bool
- func (g *WaypointGraph) RemoveUndirectedEdge(a, b int) bool
- func (g *WaypointGraph) SetEnabled(id int, enabled bool)
- func (g *WaypointGraph) SetPos(id int, pos core.Point)
- func (g *WaypointGraph) SetPos3D(id int, pos Vec3)
- func (g *WaypointGraph) ValidNode(id int) bool
Examples ¶
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 )
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.
Variables ¶
This section is empty.
Functions ¶
func GridLineOfSight ¶
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 ¶
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.
Example ¶
SmoothGridPath turns a grid A* path into world-space waypoints while keeping a body radius clear of blocked cells.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/pathfind"
)
func main() {
grid := pathfind.NewBoolGrid(6, 4)
path, _, _ := pathfind.NewAStar().Find(grid, pathfind.Cell{Col: 0, Row: 0}, pathfind.Cell{Col: 5, Row: 3})
waypoints := pathfind.SmoothGridPath(grid, path, pathfind.GridPathOptions{CellSize: 16, Radius: 5})
fmt.Println(len(path), "->", len(waypoints), waypoints)
}
Output: 9 -> 2 [{8 8} {88 56}]
func SmoothGridPathInto ¶
SmoothGridPathInto behaves like SmoothGridPath but appends the smoothed waypoints into dst[:0], avoiding heap allocations when dst has enough capacity.
Types ¶
type AStar ¶
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.
Example ¶
AStar finds the cheapest path around the walls of a BoolGrid.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/pathfind"
)
func main() {
grid := pathfind.NewBoolGrid(5, 3)
for row := range 2 {
grid.SetWalkable(2, row, false)
}
path, cost, ok := pathfind.NewAStar().Find(grid, pathfind.Cell{Col: 0, Row: 0}, pathfind.Cell{Col: 4, Row: 0})
fmt.Println(ok, cost)
fmt.Println(path)
}
Output: true 8 [{0 0} {1 0} {1 1} {1 2} {2 2} {3 2} {3 1} {3 0} {4 0}]
func NewAStar ¶
func NewAStar() *AStar
NewAStar returns an AStar searcher with 4-way movement and NoCornerCutting enabled by default.
func (*AStar) Find ¶
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 (*AStar) FindInto ¶
FindInto behaves like Find but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.
func (*AStar) FindWithOptions ¶
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 (*AStar) FindWithOptionsInto ¶
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 (*AStar) MovementRange ¶
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 (*AStar) MovementRangeInto ¶
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 (*AStar) MovementRangeWithCost ¶
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 (*AStar) StartSearch ¶
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 ¶
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 ¶
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 (*AStarSearch) Expansions ¶
func (s *AStarSearch) Expansions() int
Expansions returns the cumulative number of grid cells expanded so far.
func (*AStarSearch) Reset ¶
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 (*AStarSearch) Result ¶
func (s *AStarSearch) Result() GridPathResult
Result returns the search outcome once finished (or a result with Found == false while still in progress).
func (*AStarSearch) ResultInto ¶
func (s *AStarSearch) ResultInto(dst []Cell) GridPathResult
ResultInto behaves like Result but writes the path into dst[:0] when finished.
func (*AStarSearch) Status ¶
func (s *AStarSearch) Status() SearchStatus
Status returns the search's current status.
func (*AStarSearch) Step ¶
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 ¶
type BoolGrid struct {
// contains filtered or unexported fields
}
BoolGrid is a Grid backed by a flat boolean slice. All cells start walkable.
func NewBoolGrid ¶
NewBoolGrid returns a cols-by-rows grid with every cell walkable.
func (*BoolGrid) SetWalkable ¶
SetWalkable marks (col, row) as walkable or blocked. Out-of-bounds coordinates are ignored.
type ClusterID ¶
type ClusterID struct {
Col, Row int
}
ClusterID identifies a cluster in an HPA grid by its cluster column and row.
type ClusterRect ¶
ClusterRect describes the inclusive-exclusive cell bounds [MinCol, MaxCol) x [MinRow, MaxRow) of an HPA cluster.
type CostGrid ¶
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 ¶
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.
Example ¶
A CostMap makes some cells dearer to cross, so AStar goes around them when that is cheaper.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/pathfind"
)
func main() {
m := pathfind.NewCostMap(3, 3)
m.SetCost(1, 1, 10)
path, cost, _ := pathfind.NewAStar().Find(m, pathfind.Cell{Col: 1, Row: 0}, pathfind.Cell{Col: 1, Row: 2})
fmt.Println(len(path), cost)
}
Output: 5 4
func NewCostMap ¶
NewCostMap returns a cols-by-rows CostMap with every cell walkable at cost 1.
func (*CostMap) MoveCost ¶
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 (*CostMap) SetCost ¶
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 (*CostMap) SetWalkable ¶
SetWalkable marks (col, row) as walkable or blocked. Unblocking a cell restores its cost to 1.
type EdgeCostGrid ¶
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 ¶
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 ¶
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 ¶
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 (GraphFunc[N]) AppendNeighbors ¶
AppendNeighbors delegates to Neighbors when non-nil.
func (GraphFunc[N]) Heuristic ¶
Heuristic delegates to Estimate when non-nil, returning 0 otherwise.
type GraphRange ¶
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 (*GraphRange[N]) Budget ¶
func (r *GraphRange[N]) Budget() float64
Budget returns the maximum path cost budget used to compute this range.
func (*GraphRange[N]) Contains ¶
func (r *GraphRange[N]) Contains(node N) bool
Contains reports whether node is reachable within the query's budget.
func (*GraphRange[N]) Cost ¶
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 (*GraphRange[N]) Len ¶
func (r *GraphRange[N]) Len() int
Len returns the number of reachable nodes in the range.
func (*GraphRange[N]) Nodes ¶
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 (*GraphRange[N]) Parent ¶
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 (*GraphRange[N]) Path ¶
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 (*GraphRange[N]) PathInto ¶
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 (*GraphRange[N]) Start ¶
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 ¶
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 ¶
func NewGraphSearch[N comparable]() *GraphSearch[N]
NewGraphSearch returns a new reusable GraphSearch for nodes of type N.
func (*GraphSearch[N]) Find ¶
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 (*GraphSearch[N]) FindDijkstra ¶
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 (*GraphSearch[N]) FindDijkstraInto ¶
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 (*GraphSearch[N]) FindInto ¶
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 (*GraphSearch[N]) FindWithHeuristic ¶
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 (*GraphSearch[N]) FindWithHeuristicInto ¶
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 (*GraphSearch[N]) Range ¶
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 (*GraphSearch[N]) RangeInto ¶
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 ¶
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 ¶
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.
Example ¶
GridFunc adapts a game's own map to Grid without copying it.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/pathfind"
)
func main() {
level := []string{
"..#",
".##",
"...",
}
g := pathfind.GridFunc{
Cols: 3, Rows: 3,
Walk: func(col, row int) bool { return level[row][col] == '.' },
}
path, _, ok := pathfind.NewAStar().Find(g, pathfind.Cell{Col: 1, Row: 0}, pathfind.Cell{Col: 2, Row: 2})
fmt.Println(ok, path)
}
Output: true [{1 0} {0 0} {0 1} {0 2} {1 2} {2 2}]
type GridPathOptions ¶
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 (GridPathOptions) CellCenter ¶
func (o GridPathOptions) CellCenter(c Cell) core.Point
CellCenter returns the world-space center of cell c under o.
type GridPathResult ¶
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 ¶
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 ¶
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 (GridTopology) Distance ¶
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 (GridTopology) IsHex ¶
func (t GridTopology) IsHex() bool
IsHex reports whether t is one of the four hexagonal grid topologies.
func (GridTopology) IsStaggered ¶
func (t GridTopology) IsStaggered() bool
IsStaggered reports whether t is one of the four staggered isometric grid topologies.
func (GridTopology) Neighbors ¶
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 (GridTopology) NeighborsInto ¶
func (t GridTopology) NeighborsInto(dst []Cell, c Cell) []Cell
NeighborsInto appends the adjacent cells of c under t into dst[:0].
func (GridTopology) String ¶
func (t GridTopology) String() string
String returns the topology's canonical name.
type HPA ¶
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 ¶
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 (*HPA) AllowCornerCutting ¶
AllowCornerCutting reports whether diagonal moves may cut blocked corners.
func (*HPA) ClusterAt ¶
ClusterAt returns the ClusterID containing cell c and whether c is in bounds.
func (*HPA) ClusterGridSize ¶
ClusterGridSize returns the number of cluster columns and cluster rows.
func (*HPA) ClusterRect ¶
func (h *HPA) ClusterRect(id ClusterID) (ClusterRect, bool)
ClusterRect returns the cell bounds of cluster id and whether id is in bounds.
func (*HPA) ClusterSize ¶
ClusterSize returns the configured cluster width and height in cells.
func (*HPA) Find ¶
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 (*HPA) FindAbstract ¶
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 (*HPA) FindAbstractInto ¶
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 (*HPA) FindClusters ¶
FindClusters searches only the hierarchical abstract graph and returns the ordered list of clusters traversed from start to goal.
func (*HPA) FindClustersInto ¶
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 (*HPA) FindInto ¶
FindInto behaves like Find but writes the refined cell path into dst[:0], avoiding heap allocations when dst has enough capacity.
func (*HPA) RebuildDirty ¶
RebuildDirty incrementally rebuilds only the borders and clusters marked dirty by UpdateCell or UpdateRect.
It returns the number of clusters rebuilt.
func (*HPA) UpdateCell ¶
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 (*HPA) UpdateRect ¶
UpdateRect marks every cluster and shared border overlapping the inclusive cell rectangle [minCol..maxCol] x [minRow..maxRow] as dirty.
type HPAOptions ¶
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 ¶
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 ¶
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 ¶
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.
Example ¶
HexGrid adapts a hexagonal tilemap.Tilemap to GraphSearch for both A* paths and budgeted movement ranges with reconstructed paths.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/pathfind"
"github.com/nsgo-dev/game/pkg/tilemap"
)
func main() {
m := tilemap.New(5, 5, 32, 36)
m.Orientation = tilemap.OrientationHexagonal
m.StaggerAxis = tilemap.StaggerY
m.StaggerIndex = tilemap.StaggerOdd
m.SetCellFlags(2, 2, tilemap.TileSolid)
hex := pathfind.NewHexGrid(m)
search := pathfind.NewGraphSearch[pathfind.Cell]()
rng := search.Range(hex, pathfind.Cell{Col: 1, Row: 2}, 3)
path, ok := rng.Path(pathfind.Cell{Col: 3, Row: 2})
cost, _ := rng.Cost(pathfind.Cell{Col: 3, Row: 2})
fmt.Println(ok, cost, len(path))
}
Output: true 3 4
func NewHexGrid ¶
NewHexGrid returns a HexGrid over m blocking tiles with tilemap.TileSolid and using unit step cost 1.
func (*HexGrid) AppendNeighbors ¶
AppendNeighbors appends all passable hexagonal neighbor transitions of c onto dst using Map.HexNeighbors in deterministic order.
func (*HexGrid) EdgeCost ¶
EdgeCost returns the directed traversal cost from (fromCol, fromRow) to (toCol, toRow) for EdgeCostGrid compatibility. Negative, NaN, or infinite values forbid the transition.
func (*HexGrid) Heuristic ¶
Heuristic returns the exact hexagonal step distance between from and goal via Map.HexDistance.
func (*HexGrid) MoveCost ¶
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 (*HexGrid) NodeLess ¶
NodeLess orders cells in row-major order, matching AStar's deterministic cell-ID tie-breaking.
type IncrementalSearch ¶
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 ¶
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 ¶
func NewJPS() *JPS
NewJPS returns a JPS searcher with NoCornerCutting enabled by default.
func (*JPS) Find ¶
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 (*JPS) FindInto ¶
FindInto behaves like Find but writes the expanded cell path into dst[:0], avoiding allocations when dst has enough capacity.
func (*JPS) FindJumpPoints ¶
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.
type NavAgent ¶
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 ¶
func NewNavAgent(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgent
NewNavAgent constructs a 2D navigation agent placed at pos on mesh.
func (*NavAgent) ClearTarget ¶
func (a *NavAgent) ClearTarget()
ClearTarget clears the agent's goal, resets its corridor, stops velocity, and sets state to NavAgentIdle.
func (*NavAgent) Config ¶
func (a *NavAgent) Config() NavAgentConfig
Config returns the sanitized configuration of the agent.
func (*NavAgent) ForceReplan ¶
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 (*NavAgent) LocalRepairCount ¶
LocalRepairCount returns the number of cheap local corridor repairs performed without a full A* replan.
func (*NavAgent) NeedsReplan ¶
NeedsReplan reports whether the agent is waiting for a full A* replan.
func (*NavAgent) NextCorner ¶
NextCorner returns the next funnel steering corner along the agent's remaining corridor. Returns (zero, false) when the agent has no valid corridor.
func (*NavAgent) Path ¶
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 (*NavAgent) ReplanCount ¶
ReplanCount returns the total number of full A* replans performed by this agent.
func (*NavAgent) SetMesh ¶
SetMesh attaches a new NavMesh to the agent, invalidating any existing corridor so the agent replans.
func (*NavAgent) SetPosition ¶
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 (*NavAgent) SetTarget ¶
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 (*NavAgent) SetVelocity ¶
SetVelocity overrides the agent's current velocity. Non-finite values are ignored.
func (*NavAgent) State ¶
func (a *NavAgent) State() NavAgentState
State returns the agent's current navigation state.
func (*NavAgent) Step ¶
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 (*NavAgent) TraversingLink ¶
func (a *NavAgent) TraversingLink() (NavLinkEvent, bool)
TraversingLink returns the active link event while the agent is traversing an off-mesh or flagged link.
type NavAgentConfig ¶
type NavAgentConfig struct {
MaxSpeed float32
// Defaults to 4 * MaxSpeed when <= 0.
MaxAcceleration float32
Radius float32
// Defaults to max(Radius, 0.25) when <= 0.
StoppingDistance float32
// Defaults to max(StoppingDistance*3, MaxSpeed*MaxSpeed/(2*MaxAcceleration)*2) when <= 0.
ArrivalRadius float32
// Zero allows immediate replanning whenever the corridor becomes invalid.
ReplanInterval time.Duration
// repairing a displaced corridor start or moved target before falling back to a full A* replan.
// Defaults to 2 when <= 0.
MaxRepairDepth int
// When nil, DefaultNavFilter() is used (all walkable non-disabled polygons at unit cost).
Filter *NavFilter
// 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 ¶
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 ¶
func NewNavAgentGroup(cfg NavAgentGroupConfig) *NavAgentGroup
NewNavAgentGroup constructs a NavAgentGroup with the given replan budget and staggering settings.
func (*NavAgentGroup) Add ¶
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 (*NavAgentGroup) AddAgent ¶
func (g *NavAgentGroup) AddAgent(a *NavAgent)
AddAgent attaches an existing NavAgent to the group.
func (*NavAgentGroup) Agents ¶
func (g *NavAgentGroup) Agents() []*NavAgent
Agents returns the group's agents in deterministic registration order.
func (*NavAgentGroup) LastStepReplans ¶
func (g *NavAgentGroup) LastStepReplans() int
LastStepReplans returns how many full A* replans executed during the most recent Step.
func (*NavAgentGroup) Len ¶
func (g *NavAgentGroup) Len() int
Len returns the number of agents in the group.
func (*NavAgentGroup) Remove ¶
func (g *NavAgentGroup) Remove(a *NavAgent) bool
Remove detaches a from the group while preserving deterministic ordering of remaining agents.
func (*NavAgentGroup) Step ¶
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 (*NavAgentGroup) Steps ¶
func (g *NavAgentGroup) Steps() uint64
Steps returns the number of times Step has advanced this group.
func (*NavAgentGroup) TotalReplans ¶
func (g *NavAgentGroup) TotalReplans() int
TotalReplans returns the cumulative number of full A* replans executed by Step across all agents.
type NavAgentGroupConfig ¶
type NavAgentGroupConfig struct {
// Defaults to 4 when <= 0.
MaxReplansPerStep int
// NavAgentConfig.ReplanInterval is 0.
ReplanInterval time.Duration
// 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 ¶
type NavAgentState uint8
NavAgentState reports the navigation status of a 2D NavAgent.
const ( NavAgentIdle NavAgentState = iota NavAgentMoving NavAgentArrived NavAgentUnreachable )
func (NavAgentState) String ¶
func (s NavAgentState) String() string
String returns a human-readable state name.
type NavArea ¶
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.
type NavFilter ¶
type NavFilter struct {
// when non-zero. When zero, no inclusion bit is required.
IncludeFlags NavFlags
ExcludeFlags NavFlags
// Omitted areas default to 1.0. Values <= 0, NaN, or ±Inf forbid traversal
// of that area.
AreaCosts map[NavArea]float64
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 ¶
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 (NavFilter) Allows ¶
Allows reports whether a polygon with the given area and flags passes the filter.
func (NavFilter) AreaCost ¶
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 (*NavFilter) ExcludeArea ¶
ExcludeArea marks area as non-traversable on f regardless of polygon flags.
func (*NavFilter) IncludeArea ¶
IncludeArea removes area from f's ExcludedAreas set.
func (*NavFilter) SetAreaCost ¶
SetAreaCost sets the traversal cost multiplier for area on f.
type NavFlags ¶
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).
type NavLinkEvent ¶
type NavLinkEvent struct {
}
NavLinkEvent describes a flagged shared-edge or off-mesh link transition encountered by a NavAgent.
type NavListenerID ¶
type NavListenerID uint64
NavListenerID identifies a tile-change listener registered on a TiledNavMesh.
type NavMesh ¶
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 ¶
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 ¶
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 (*NavMesh) AddOffMeshLink ¶
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 (*NavMesh) AddPolygonFlags ¶
AddPolygonFlags sets the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) AppendSamples ¶
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 (*NavMesh) BumpRevision ¶
func (m *NavMesh) BumpRevision()
BumpRevision increments the mesh revision so NavAgents watching this mesh invalidate cached corridors and replan.
func (*NavMesh) ClearOffMeshLinks ¶
func (m *NavMesh) ClearOffMeshLinks()
ClearOffMeshLinks removes all off-mesh links from m and bumps the mesh revision when any were present.
func (*NavMesh) ClearPolygonFlags ¶
ClearPolygonFlags clears the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) Contains ¶
Contains reports whether p lies inside or on the boundary of any polygon in the mesh.
func (*NavMesh) ContainsWithFilter ¶
ContainsWithFilter reports whether p lies inside or on the boundary of any polygon passing filter.
func (*NavMesh) FindCorridor ¶
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 (*NavMesh) FindCorridorInto ¶
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 (*NavMesh) FindCorridorWithFilter ¶
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 (*NavMesh) FindCorridorWithFilterInto ¶
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 (*NavMesh) FindPath ¶
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 (*NavMesh) FindPathInto ¶
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 (*NavMesh) FindPathWithFilter ¶
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 (*NavMesh) FindPathWithFilterAndOptions ¶
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 (*NavMesh) FindPathWithFilterAndOptionsInto ¶
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 (*NavMesh) FindPathWithFilterInto ¶
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 (*NavMesh) FindPathWithOptions ¶
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 (*NavMesh) FindPolygon ¶
FindPolygon returns the lowest index of a polygon containing p (including its edges and vertices), or -1 if p lies outside the mesh.
func (*NavMesh) FindPolygonWithFilter ¶
FindPolygonWithFilter returns the lowest index of a polygon passing filter that contains p (including its edges and vertices), or -1 if none match.
func (*NavMesh) MoveAlongSurface ¶
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 (*NavMesh) MoveAlongSurfaceWithFilter ¶
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 (*NavMesh) NearestPoint ¶
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 (*NavMesh) NearestPointWithFilter ¶
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 (*NavMesh) NearestPolygon ¶
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 (*NavMesh) NearestPolygonWithFilter ¶
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 (*NavMesh) Neighbors ¶
Neighbors returns the indices of polygons sharing an edge with polygon index.
func (*NavMesh) OffMeshLinks ¶
func (m *NavMesh) OffMeshLinks() []NavOffMeshLink
OffMeshLinks returns a copy of all off-mesh links registered on m in insertion order.
func (*NavMesh) Polygon ¶
Polygon returns a copy of the vertices of polygon index, or nil if index is out of range.
func (*NavMesh) PolygonArea ¶
PolygonArea returns the area ID of polygon index, or NavAreaDefault if index is out of range.
func (*NavMesh) PolygonCount ¶
PolygonCount returns the number of valid convex polygons in the mesh.
func (*NavMesh) PolygonFlags ¶
PolygonFlags returns the runtime traversal flags of polygon index, or 0 if index is out of range.
func (*NavMesh) RandomPoint ¶
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 (*NavMesh) RandomPointAround ¶
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 (*NavMesh) RandomPointAroundWithFilter ¶
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 (*NavMesh) RandomPointWithFilter ¶
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 (*NavMesh) Raycast ¶
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 (*NavMesh) RaycastWithFilter ¶
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 (*NavMesh) Revision ¶
Revision returns a monotonically increasing number bumped whenever the mesh topology, area costs/flags, or link flags change.
func (*NavMesh) SetEdgeFlags ¶
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 (*NavMesh) SetPolygonArea ¶
SetPolygonArea updates the area ID of polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) SetPolygonFlags ¶
SetPolygonFlags replaces the runtime traversal flags of polygon index without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) StartSearch ¶
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 (*NavMesh) StartSearchWithFilter ¶
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 ¶
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 ¶
func NewNavMeshQuery(mesh *NavMesh) *NavMeshQuery
NewNavMeshQuery creates a reusable query instance bound to mesh.
func (*NavMeshQuery) FindCorridorInto ¶
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 (*NavMeshQuery) FindCorridorWithFilterInto ¶
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 (*NavMeshQuery) FindPathInto ¶
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 (*NavMeshQuery) FindPathWithFilterAndOptionsInto ¶
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 (*NavMeshQuery) FindPathWithFilterInto ¶
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 (*NavMeshQuery) Mesh ¶
func (q *NavMeshQuery) Mesh() *NavMesh
Mesh returns the NavMesh currently bound to q.
func (*NavMeshQuery) MoveAlongSurface ¶
func (q *NavMeshQuery) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)
MoveAlongSurface delegates to q's NavMesh.MoveAlongSurface.
func (*NavMeshQuery) MoveAlongSurfaceInto ¶
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 (*NavMeshQuery) MoveAlongSurfaceWithFilter ¶
func (q *NavMeshQuery) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)
MoveAlongSurfaceWithFilter delegates to q's NavMesh.MoveAlongSurfaceWithFilter.
func (*NavMeshQuery) MoveAlongSurfaceWithFilterInto ¶
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 (*NavMeshQuery) NearestPoint ¶
NearestPoint delegates to q's NavMesh.NearestPoint.
func (*NavMeshQuery) NearestPointWithFilter ¶
func (q *NavMeshQuery) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, int, bool)
NearestPointWithFilter delegates to q's NavMesh.NearestPointWithFilter.
func (*NavMeshQuery) PathLength ¶
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 (*NavMeshQuery) RandomPoint ¶
RandomPoint delegates to q's NavMesh.RandomPoint.
func (*NavMeshQuery) RandomPointAround ¶
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 (*NavMeshQuery) RandomPointAroundWithFilter ¶
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 (*NavMeshQuery) RandomPointWithFilter ¶
func (q *NavMeshQuery) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (core.Point, int, bool)
RandomPointWithFilter delegates to q's NavMesh.RandomPointWithFilter.
func (*NavMeshQuery) Raycast ¶
func (q *NavMeshQuery) Raycast(start, target core.Point) (NavRaycastHit, bool)
Raycast delegates to q's NavMesh.Raycast.
func (*NavMeshQuery) RaycastWithFilter ¶
func (q *NavMeshQuery) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)
RaycastWithFilter delegates to q's NavMesh.RaycastWithFilter.
func (*NavMeshQuery) SetMesh ¶
func (q *NavMeshQuery) SetMesh(mesh *NavMesh)
SetMesh rebinds q to mesh while keeping its allocated scratch capacity for reuse.
type NavMeshSearch ¶
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 ¶
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 ¶
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 (*NavMeshSearch) Expansions ¶
func (s *NavMeshSearch) Expansions() int
Expansions returns the cumulative number of portal nodes expanded so far.
func (*NavMeshSearch) Result ¶
func (s *NavMeshSearch) Result() NavPathResult
Result returns the search outcome once finished (or a result with Found == false while still in progress).
func (*NavMeshSearch) Status ¶
func (s *NavMeshSearch) Status() SearchStatus
Status returns the search's current status.
func (*NavMeshSearch) Step ¶
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 ¶
NavMoveResult describes the outcome of sliding a position across a 2D NavMesh surface.
type NavObstacle ¶
type NavObstacle struct {
}
NavObstacle describes a temporary runtime obstacle applied to a 2D TiledNavMesh.
func NavBoxObstacle ¶
func NavBoxObstacle(minPt, maxPt core.Point) NavObstacle
NavBoxObstacle constructs an axis-aligned 2D box obstacle spanning [minPt, maxPt].
func NavCircleObstacle ¶
func NavCircleObstacle(center core.Point, radius float32) NavObstacle
NavCircleObstacle constructs a 2D circular obstacle centered at center with radius.
func NavOrientedBoxObstacle ¶
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 ¶
func NavPolygonObstacle(verts []core.Point) NavObstacle
NavPolygonObstacle constructs a 2D polygonal obstacle (convex or concave) from verts.
type NavObstacleID ¶
type NavObstacleID uint64
NavObstacleID identifies a dynamic obstacle registered on a TiledNavMesh.
type NavObstacleKind ¶
type NavObstacleKind uint8
NavObstacleKind selects the geometric shape of a 2D NavObstacle.
const ( NavObstacleBox NavObstacleKind = iota NavObstacleCircle NavObstaclePolygon )
type NavObstacleMode ¶
type NavObstacleMode uint8
NavObstacleMode selects how a dynamic obstacle modifies walkable polygons in touched tiles.
const ( NavObstacleCarve NavObstacleMode = iota // (defaulting to NavFlagDisabled when both Area and Flags are zero) to the covered polygons. NavObstacleMark )
type NavOffMeshLink ¶
type NavOffMeshLink struct {
// Start and End are the world-space endpoints on (or within Radius of) the mesh.
// 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 bool
Flags uint32
ID int
Cost float32
// Defaults to NavAreaDefault (0).
Area NavArea
// 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 ¶
type NavPathLink struct {
StartIndex int
EndIndex int
// FromPoly and ToPoly are the source and destination polygon indices connected by the link.
// Start and End are the world-space entry and exit positions of the traversed link direction.
Radius float32
Area NavArea
Flags uint32
LinkID int
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 ¶
type NavPathResult struct {
// 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.
}
NavPathResult is the outcome of a bounded or incremental 2D NavMesh search.
func (NavPathResult) HasLinks ¶
func (r NavPathResult) HasLinks() bool
HasLinks reports whether r traverses at least one off-mesh link.
func (NavPathResult) LinkAt ¶
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 ¶
type NavPathWatchID uint64
NavPathWatchID identifies a path-invalidation watcher registered on a TiledNavMesh.
type NavPolyRef ¶
type NavPolyRef struct {
}
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 (NavPolyRef) Valid ¶
func (r NavPolyRef) Valid() bool
Valid reports whether r holds a non-zero tile salt and non-negative polygon index.
type NavPolygonInput ¶
type NavPolygonInput struct {
}
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 ¶
type NavRaycastHit struct {
// or target when the ray reaches target unobstructed (Hit is false).
Point core.Point
// (pointing back into the walkable polygon, opposing the ray direction), or zero when Hit is false or Poly < 0.
Normal core.Point
Poly int
// T is 1 when target is reached unobstructed; T is 0 when start is outside the allowed mesh.
T float32
Hit bool
}
NavRaycastHit describes the result of casting a segment along a 2D NavMesh surface.
type NavTile ¶
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 ¶
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 (*NavTile) BasePolygonCount ¶
BasePolygonCount returns the number of base walkable polygons baked into this tile.
func (*NavTile) Coord ¶
func (t *NavTile) Coord() NavTileCoord
Coord returns the tile coordinate this tile was baked for.
type NavTileChange ¶
type NavTileChange struct {
}
NavTileChange describes a single tile mutation event delivered to tile listeners and path watchers.
type NavTileChangeKind ¶
type NavTileChangeKind uint8
NavTileChangeKind classifies why a tile in a TiledNavMesh changed.
const ( NavTileAdded NavTileChangeKind = iota NavTileUpdated NavTileRemoved )
type NavTileCoord ¶
type NavTileCoord struct {
NavTileCoord identifies a fixed-size tile in a 2D TiledNavMesh.
type NavTileVersion ¶
type NavTileVersion struct {
}
NavTileVersion records a tile coordinate together with its revision number when a path was computed.
type NodeOrder ¶
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 ¶
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 ¶
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 ¶
func NewPathQueue(cfg PathQueueConfig) *PathQueue
NewPathQueue returns a new PathQueue with the given configuration.
func (*PathQueue) Cancel ¶
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 (*PathQueue) Clear ¶
func (q *PathQueue) Clear()
Clear removes all pending requests without invoking callbacks.
func (*PathQueue) Completed ¶
Completed returns the cumulative number of requests that finished (complete, partial, or failed).
func (*PathQueue) IsPending ¶
func (q *PathQueue) IsPending(id PathRequestID) bool
IsPending reports whether id is currently queued and has not finished or been canceled.
func (*PathQueue) Pending ¶
Pending returns the number of active requests currently waiting in the queue.
func (*PathQueue) Step ¶
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 (*PathQueue) StepDefault ¶
StepDefault advances queued requests using the queue's configured DefaultBudget.
func (*PathQueue) Submit ¶
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 (*PathQueue) SubmitGrid ¶
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 (*PathQueue) SubmitNavMesh ¶
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 (*PathQueue) TotalExpansions ¶
TotalExpansions returns the cumulative number of node expansions performed across all Step calls.
type PathQueueConfig ¶
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 ¶
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 ¶
type PathRequestID uint64
PathRequestID uniquely identifies a request submitted to a PathQueue. Zero is never assigned to a valid request.
type ReachableCell ¶
ReachableCell is one cell returned by a movement-range query together with its minimum path cost from the start cell.
func ReachableCells ¶
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 ¶
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 ¶
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 (SearchStatus) Done ¶
func (s SearchStatus) Done() bool
Done reports whether the search has reached a terminal state (complete, partial, or failed).
func (SearchStatus) String ¶
func (s SearchStatus) String() string
String returns a human-readable status name.
type TiledNavMesh ¶
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 ¶
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 ¶
func BuildTiledNavMeshWithAreas(polys []NavPolygonInput, tileSize float32) *TiledNavMesh
BuildTiledNavMeshWithAreas constructs a 2D TiledNavMesh from convex polygons carrying per-polygon areas and flags.
func NewTiledNavMesh ¶
func NewTiledNavMesh(cfg TiledNavMeshConfig) *TiledNavMesh
NewTiledNavMesh creates an empty 2D TiledNavMesh with cfg.
func (*TiledNavMesh) AddObstacle ¶
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 (*TiledNavMesh) AddOffMeshLink ¶
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 (*TiledNavMesh) AddTile ¶
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 (*TiledNavMesh) AddTileListener ¶
func (tm *TiledNavMesh) AddTileListener(fn func(NavTileChange)) NavListenerID
AddTileListener registers fn to be invoked whenever any tile is added, updated, or removed.
func (*TiledNavMesh) BakeTile ¶
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 (*TiledNavMesh) Batch ¶
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 (*TiledNavMesh) ClearObstacles ¶
func (tm *TiledNavMesh) ClearObstacles()
ClearObstacles removes all dynamic obstacles and rebuilds only tiles that had obstacles.
func (*TiledNavMesh) ClearOffMeshLinks ¶
func (tm *TiledNavMesh) ClearOffMeshLinks()
ClearOffMeshLinks removes all off-mesh links from tm and bumps the mesh revision when any were present.
func (*TiledNavMesh) Contains ¶
func (tm *TiledNavMesh) Contains(p core.Point) bool
Contains reports whether p lies inside any polygon of the tiled mesh.
func (*TiledNavMesh) ContainsWithFilter ¶
func (tm *TiledNavMesh) ContainsWithFilter(p core.Point, filter NavFilter) bool
ContainsWithFilter reports whether p lies inside any polygon passing filter.
func (*TiledNavMesh) FindCorridor ¶
func (tm *TiledNavMesh) FindCorridor(start, goal core.Point) ([]NavPolyRef, bool)
FindCorridor finds the sequence of NavPolyRefs from start to goal using DefaultNavFilter.
func (*TiledNavMesh) FindCorridorWithFilter ¶
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 (*TiledNavMesh) FindPath ¶
FindPath finds the shortest path inside tm from start to goal using DefaultNavFilter.
func (*TiledNavMesh) FindPathWithFilter ¶
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 (*TiledNavMesh) FindPathWithFilterAndOptions ¶
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 (*TiledNavMesh) FindPathWithOptions ¶
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 (*TiledNavMesh) FindPolygon ¶
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 (*TiledNavMesh) FindPolygonWithFilter ¶
func (tm *TiledNavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, bool)
FindPolygonWithFilter locates a polygon passing filter that contains p.
func (*TiledNavMesh) HasTile ¶
func (tm *TiledNavMesh) HasTile(coord NavTileCoord) bool
HasTile reports whether a tile is currently installed at coord.
func (*TiledNavMesh) IsPathValid ¶
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 (*TiledNavMesh) NearestPoint ¶
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 (*TiledNavMesh) NearestPointWithFilter ¶
func (tm *TiledNavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, NavPolyRef, bool)
NearestPointWithFilter behaves like NearestPoint restricted to filter.
func (*TiledNavMesh) NearestPolygon ¶
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 (*TiledNavMesh) NearestPolygonWithFilter ¶
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 (*TiledNavMesh) Neighbors ¶
func (tm *TiledNavMesh) Neighbors(ref NavPolyRef) []NavPolyRef
Neighbors returns the polygon references sharing an edge (intra-tile or cross-tile) with ref.
func (*TiledNavMesh) ObstacleCount ¶
func (tm *TiledNavMesh) ObstacleCount() int
ObstacleCount returns the number of active dynamic obstacles.
func (*TiledNavMesh) OffMeshLinks ¶
func (tm *TiledNavMesh) OffMeshLinks() []NavOffMeshLink
OffMeshLinks returns a copy of all off-mesh links registered on tm in insertion order.
func (*TiledNavMesh) Origin ¶
func (tm *TiledNavMesh) Origin() core.Point
Origin returns the world-space origin of tile (0, 0).
func (*TiledNavMesh) Polygon ¶
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 (*TiledNavMesh) PolygonArea ¶
func (tm *TiledNavMesh) PolygonArea(ref NavPolyRef) NavArea
PolygonArea returns the area of ref, or NavAreaDefault if ref is invalid.
func (*TiledNavMesh) PolygonCount ¶
func (tm *TiledNavMesh) PolygonCount() int
PolygonCount returns the total number of active walkable polygons across all installed tiles.
func (*TiledNavMesh) PolygonFlags ¶
func (tm *TiledNavMesh) PolygonFlags(ref NavPolyRef) NavFlags
PolygonFlags returns the runtime flags of ref, or 0 if ref is invalid.
func (*TiledNavMesh) Raycast ¶
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 (*TiledNavMesh) RaycastWithFilter ¶
func (tm *TiledNavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (TiledNavRaycastHit, bool)
RaycastWithFilter behaves like Raycast restricted to polygons allowed by filter.
func (*TiledNavMesh) RebuildTile ¶
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 (*TiledNavMesh) RemoveObstacle ¶
func (tm *TiledNavMesh) RemoveObstacle(id NavObstacleID) bool
RemoveObstacle removes dynamic obstacle id and rebuilds only the tiles it touched, restoring their uncarved geometry.
func (*TiledNavMesh) RemoveTile ¶
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 (*TiledNavMesh) RemoveTileListener ¶
func (tm *TiledNavMesh) RemoveTileListener(id NavListenerID) bool
RemoveTileListener unregisters a listener previously added with AddTileListener.
func (*TiledNavMesh) ReplaceTile ¶
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 (*TiledNavMesh) Revision ¶
func (tm *TiledNavMesh) Revision() uint64
Revision returns a monotonically increasing number bumped on any tile or obstacle mutation.
func (*TiledNavMesh) SetTile ¶
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 (*TiledNavMesh) TileBounds ¶
func (tm *TiledNavMesh) TileBounds(coord NavTileCoord) (minPt, maxPt core.Point)
TileBounds returns the exact world-space [min, max] bounds of tile coord.
func (*TiledNavMesh) TileCoordAt ¶
func (tm *TiledNavMesh) TileCoordAt(p core.Point) NavTileCoord
TileCoordAt returns the tile coordinate containing p.
func (*TiledNavMesh) TileCoords ¶
func (tm *TiledNavMesh) TileCoords() []NavTileCoord
TileCoords returns all installed tile coordinates in deterministic sorted order.
func (*TiledNavMesh) TileCount ¶
func (tm *TiledNavMesh) TileCount() int
TileCount returns the number of currently installed tiles.
func (*TiledNavMesh) TilePolygonCount ¶
func (tm *TiledNavMesh) TilePolygonCount(coord NavTileCoord) int
TilePolygonCount returns the number of active polygons currently inside tile coord.
func (*TiledNavMesh) TileSize ¶
func (tm *TiledNavMesh) TileSize() float32
TileSize returns the configured tile size in world units.
func (*TiledNavMesh) TileVersion ¶
func (tm *TiledNavMesh) TileVersion(coord NavTileCoord) uint64
TileVersion returns the current revision number of tile coord (0 if never modified).
func (*TiledNavMesh) UnwatchPath ¶
func (tm *TiledNavMesh) UnwatchPath(id NavPathWatchID) bool
UnwatchPath cancels a path watcher previously registered with WatchPath.
func (*TiledNavMesh) UpdateObstacle ¶
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 (*TiledNavMesh) WatchPath ¶
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 ¶
TiledNavMeshConfig configures a 2D TiledNavMesh.
type TiledNavPathLink ¶
type TiledNavPathLink struct {
StartIndex int
EndIndex int
// FromPoly and ToPoly are the source and destination polygon references connected by the link.
// Start and End are the world-space entry and exit positions of the traversed link direction.
Radius float32
Area NavArea
Flags uint32
LinkID int
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 ¶
type TiledNavPathResult struct {
// 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.
}
TiledNavPathResult is the outcome of a 2D TiledNavMesh path search, including the tile footprint and tile versions crossed so callers can detect invalidation.
func (TiledNavPathResult) CrossesTile ¶
func (r TiledNavPathResult) CrossesTile(coord NavTileCoord) bool
CrossesTile reports whether r's corridor passes through coord.
func (TiledNavPathResult) HasLinks ¶
func (r TiledNavPathResult) HasLinks() bool
HasLinks reports whether r traverses at least one off-mesh link.
func (TiledNavPathResult) LinkAt ¶
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 (TiledNavPathResult) TileCoords ¶
func (r TiledNavPathResult) TileCoords() []NavTileCoord
TileCoords returns the deduplicated list of tile coordinates crossed by r.
type TiledNavRaycastHit ¶
type TiledNavRaycastHit struct {
}
TiledNavRaycastHit describes the result of casting a segment across a 2D TiledNavMesh.
type ValidatedGraph ¶
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 ¶
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 ¶
WaypointEdge is a directed outgoing edge in a WaypointGraph.
type 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.
Example ¶
WaypointGraph stores hand-placed 2D or 3D waypoints with weighted edges searched by GraphSearch.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/pathfind"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
g := pathfind.NewWaypointGraph()
a := g.Add(core.Point{X: 0, Y: 0})
b := g.Add(core.Point{X: 30, Y: 0})
c := g.Add(core.Point{X: 30, Y: 40})
g.ConnectUndirected(a, b)
g.ConnectUndirected(b, c)
g.ConnectUndirected(a, c)
path, cost, ok := pathfind.NewGraphSearch[int]().Find(g, a, c)
fmt.Println(ok, cost, path)
}
Output: true 50 [0 2]
func NewWaypointGraph ¶
func NewWaypointGraph() *WaypointGraph
NewWaypointGraph returns an empty WaypointGraph.
func (*WaypointGraph) Add ¶
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 (*WaypointGraph) Add3D ¶
func (g *WaypointGraph) Add3D(pos Vec3) int
Add3D adds a 3D waypoint at pos and returns its stable node ID.
func (*WaypointGraph) AddEdge ¶
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 (*WaypointGraph) AddUndirectedEdge ¶
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 (*WaypointGraph) AppendNeighbors ¶
AppendNeighbors appends all outgoing edges from id to enabled destination waypoints onto dst in deterministic ascending destination ID order.
func (*WaypointGraph) Connect ¶
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 (*WaypointGraph) ConnectUndirected ¶
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 (*WaypointGraph) Edges ¶
func (g *WaypointGraph) Edges(id int) []WaypointEdge
Edges returns a copy of waypoint id's outgoing edges ordered by ascending destination ID.
func (*WaypointGraph) Enabled ¶
func (g *WaypointGraph) Enabled(id int) bool
Enabled reports whether id is an active, enabled waypoint.
func (*WaypointGraph) Heuristic ¶
func (g *WaypointGraph) Heuristic(from, goal int) float64
Heuristic returns the Euclidean distance between waypoints from and goal.
func (*WaypointGraph) Nearest ¶
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 (*WaypointGraph) Nearest3D ¶
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 (*WaypointGraph) NodeCount ¶
func (g *WaypointGraph) NodeCount() int
NodeCount returns the number of active (non-removed) waypoints in g.
func (*WaypointGraph) NodeLess ¶
func (g *WaypointGraph) NodeLess(a, b int) bool
NodeLess breaks search ties deterministically by ascending waypoint ID.
func (*WaypointGraph) Points ¶
func (g *WaypointGraph) Points(ids []int) []core.Point
Points converts a slice of waypoint IDs into their 2D positions.
func (*WaypointGraph) Points3D ¶
func (g *WaypointGraph) Points3D(ids []int) []Vec3
Points3D converts a slice of waypoint IDs into their 3D positions.
func (*WaypointGraph) Points3DInto ¶
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 (*WaypointGraph) PointsInto ¶
PointsInto writes the 2D positions of ids into dst[:0], avoiding allocations when dst has enough capacity.
func (*WaypointGraph) Pos ¶
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 (*WaypointGraph) Pos3D ¶
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 (*WaypointGraph) Remove ¶
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 (*WaypointGraph) RemoveEdge ¶
func (g *WaypointGraph) RemoveEdge(from, to int) bool
RemoveEdge removes the directed edge from -> to, returning true if it existed.
func (*WaypointGraph) RemoveUndirectedEdge ¶
func (g *WaypointGraph) RemoveUndirectedEdge(a, b int) bool
RemoveUndirectedEdge removes both a -> b and b -> a, returning true if either existed.
func (*WaypointGraph) SetEnabled ¶
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 (*WaypointGraph) SetPos ¶
func (g *WaypointGraph) SetPos(id int, pos core.Point)
SetPos updates the 2D position of waypoint id (setting Z = 0).
func (*WaypointGraph) SetPos3D ¶
func (g *WaypointGraph) SetPos3D(id int, pos Vec3)
SetPos3D updates the 3D position of waypoint id.
func (*WaypointGraph) ValidNode ¶
func (g *WaypointGraph) ValidNode(id int) bool
ValidNode reports whether id is an active, enabled waypoint in g.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package navbake bakes 2D navigation meshes for game/pathfind from level geometry: an outline with concave obstacles and holes, or a tilemap's solid cells, shrunk by an agent's radius and divided into the convex polygons pathfind.NavMesh searches.
|
Package navbake bakes 2D navigation meshes for game/pathfind from level geometry: an outline with concave obstacles and holes, or a tilemap's solid cells, shrunk by an agent's radius and divided into the convex polygons pathfind.NavMesh searches. |