Die API-Referenz stammt aus den Go-Doc-Kommentaren im Quellcode und ist auf Englisch verfasst.
package ai
import "github.com/nsgo-dev/game/pkg/ai"Übersicht
Package ai provides deterministic game AI building blocks: grid A* pathfinding (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, 2D navigation meshes with funnel smoothing, polygon areas/filters, and path-corridor navigation agents, steering behaviors, velocity-based local avoidance (ORCA) in 2D and 3D XZ, behavior trees, utility AI scoring, goal-oriented action planning (GOAP), attack token pools, engagement slot assignment, squad coordination, spatial influence maps, tactical position queries with cover points, and perception with sight, hearing and memory.
Everything runs cleanly on game.Loop's fixed steps with no background goroutines and no hidden global randomness.
Index
- Konstanten
- Variablen
- func Alignment(a Agent, neighbors []Agent, radius float32) core.Point
- func Arrive(a Agent, target core.Point, slowRadius float32) core.Point
- func Cohesion(a Agent, neighbors []Agent, radius float32) core.Point
- func Combine(maxForce float32, forces ...WeightedForce) core.Point
- func CombinePrioritized(maxForce float32, forces ...WeightedForce) core.Point
- func EncodeBehaviorTree(doc *BehaviorTreeDoc) ([]byte, error)
- func EncodeGOAP(cfg *GOAPConfig) ([]byte, error)
- func EncodeUtility(cfg *UtilityConfig) ([]byte, error)
- func Evade(a, pursuer Agent, panicRadius, maxLookAhead float32) core.Point
- func Flee(a Agent, threat core.Point, panicRadius float32) core.Point
- func FollowPath(a Agent, path []core.Point, state *PathFollowState, waypointRadius float32, loop bool) core.Point
- func FormatBTTrace(nodes []BTNodeTrace) string
- func GridLineOfSight(g Grid, a, b core.Point, opts GridPathOptions) bool
- func Hide(a, pursuer Agent, obstacles []Obstacle, standoff, slowRadius float32) core.Point
- func InfluenceHeatmapEnabled() bool
- func Interpose(a, targetA, targetB Agent, slowRadius float32) core.Point
- func ObstacleAvoidance(a Agent, obstacles []Obstacle, maxAhead float32) core.Point
- func OffsetPursuit(a, leader Agent, localOffset core.Point, slowRadius, maxLookAhead float32) core.Point
- func Pursue(a, target Agent, maxLookAhead float32) core.Point
- func RestoreBehaviorTree(root Node, snap BehaviorTreeSnapshot) error
- func Seek(a Agent, target core.Point) core.Point
- func Separation(a Agent, neighbors []Agent, desiredSep float32) core.Point
- func SmoothGridPath(g Grid, path []Cell, opts GridPathOptions) []core.Point
- func SmoothGridPathInto(dst []core.Point, g Grid, path []Cell, opts GridPathOptions) []core.Point
- func SquadStateGet[T any](s *SquadState, key string) (T, bool)
- func ValidateBehaviorTree(doc *BehaviorTreeDoc) error
- func WallAvoidance(a Agent, walls []Wall, feelerLength float32) core.Point
- func Wander(a Agent, state *WanderState, radius, distance, jitter float32, nextRand func() float32) core.Point
- type AStar
- func NewAStar() *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, edgeCost func(from, to Cell) float64) []ReachableCell
- func (a *AStar) StartSearch(g Grid, start, goal Cell, opts PathOptions) *AStarSearch
- type AStarSearch
- func NewAStarSearch(a *AStar, g Grid, start, goal Cell, opts PathOptions) *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 AbortMode
- type Agent
- type Agent3D
- type AngleMode
- type AngleTest
- type Attitude
- type AttitudeFunc
- type AttitudeMask
- type BTBindings
- type BTBlackboardKeyDoc
- type BTInspector
- func NewBTInspector(root Node) *BTInspector
- func (ins *BTInspector) Format() string
- func (ins *BTInspector) Len() int
- func (ins *BTInspector) Reset()
- func (ins *BTInspector) Root() Node
- func (ins *BTInspector) RunningPath() []BTNodeTrace
- func (ins *BTInspector) String() string
- func (ins *BTInspector) Tick(dt time.Duration) Status
- func (ins *BTInspector) Walk() []BTNodeTrace
- func (ins *BTInspector) WalkInto(dst []BTNodeTrace) []BTNodeTrace
- type BTNodeContext
- type BTNodeDoc
- type BTNodeSnapshot
- type BTNodeTrace
- type BTNodeType
- type BTParallelPolicyName
- type BTParams
- func (p BTParams) Bool(name string) (bool, bool)
- func (p BTParams) Duration(name string) (time.Duration, bool)
- func (p BTParams) Entity(name string) (uint64, bool)
- func (p BTParams) Float(name string) (float64, bool)
- func (p BTParams) Int(name string) (int, bool)
- func (p BTParams) Point(name string) (core.Point, bool)
- func (p BTParams) String(name string) (string, bool)
- func (p BTParams) Vec2(name string) (math2d.Vec2, bool)
- func (p BTParams) Vec3(name string) (Vec3, bool)
- type BehaviorTree
- type BehaviorTreeDoc
- type BehaviorTreeSnapshot
- type Blackboard
- func NewBlackboard() *Blackboard
- func NewChildBlackboard(parent *Blackboard) *Blackboard
- func (b *Blackboard) Bool(key string) (bool, bool)
- func (b *Blackboard) Clear()
- func (b *Blackboard) Delete(key string)
- func (b *Blackboard) DeleteShared(key string)
- func (b *Blackboard) Entity(key string) (uint64, bool)
- func (b *Blackboard) Float(key string) (float64, bool)
- func (b *Blackboard) Get(key string) (BlackboardValue, bool)
- func (b *Blackboard) GetLocal(key string) (BlackboardValue, bool)
- func (b *Blackboard) Has(key string) bool
- func (b *Blackboard) HasLocal(key string) bool
- func (b *Blackboard) Int(key string) (int, bool)
- func (b *Blackboard) KeyRevision(key string) uint64
- func (b *Blackboard) Keys(dst []string) []string
- func (b *Blackboard) Kind(key string) BlackboardKind
- func (b *Blackboard) LocalKeys(dst []string) []string
- func (b *Blackboard) Parent() *Blackboard
- func (b *Blackboard) Point(key string) (core.Point, bool)
- func (b *Blackboard) Revision() uint64
- func (b *Blackboard) Set(key string, val BlackboardValue)
- func (b *Blackboard) SetBool(key string, v bool)
- func (b *Blackboard) SetEntity(key string, id uint64)
- func (b *Blackboard) SetFloat(key string, v float64)
- func (b *Blackboard) SetInt(key string, v int)
- func (b *Blackboard) SetPoint(key string, p core.Point)
- func (b *Blackboard) SetShared(key string, val BlackboardValue)
- func (b *Blackboard) SetSharedBool(key string, v bool)
- func (b *Blackboard) SetSharedEntity(key string, id uint64)
- func (b *Blackboard) SetSharedFloat(key string, v float64)
- func (b *Blackboard) SetSharedInt(key string, v int)
- func (b *Blackboard) SetSharedPoint(key string, p core.Point)
- func (b *Blackboard) SetSharedString(key string, v string)
- func (b *Blackboard) SetSharedVec2(key string, v math2d.Vec2)
- func (b *Blackboard) SetSharedVec3(key string, v Vec3)
- func (b *Blackboard) SetString(key string, v string)
- func (b *Blackboard) SetVec2(key string, v math2d.Vec2)
- func (b *Blackboard) SetVec3(key string, v Vec3)
- func (b *Blackboard) String(key string) (string, bool)
- func (b *Blackboard) Vec2(key string) (math2d.Vec2, bool)
- func (b *Blackboard) Vec3(key string) (Vec3, bool)
- func (b *Blackboard) Watch(key string, fn BlackboardListener) (cancel func())
- type BlackboardChange
- type BlackboardKind
- type BlackboardKindName
- type BlackboardListener
- type BlackboardOp
- type BlackboardValue
- func BBBool(v bool) BlackboardValue
- func BBEntity(id uint64) BlackboardValue
- func BBFloat(v float64) BlackboardValue
- func BBInt(v int) BlackboardValue
- func BBPoint(p core.Point) BlackboardValue
- func BBString(v string) BlackboardValue
- func BBVec2(v math2d.Vec2) BlackboardValue
- func BBVec3(v Vec3) BlackboardValue
- func (v BlackboardValue) Equal(o BlackboardValue) bool
- func (v BlackboardValue) IsZero() bool
- type BoolFact
- type BoolGrid
- type CandidateGenerator
- type Cell
- type ChildNodes
- type ClusterID
- type ClusterRect
- type ColliderCoverOptions
- type Conditions
- func (c Conditions) Empty() bool
- func (c Conditions) RequireBool(f BoolFact, v bool) Conditions
- func (c Conditions) RequireIntEq(f IntFact, v int) Conditions
- func (c Conditions) RequireIntGt(f IntFact, v int) Conditions
- func (c Conditions) RequireIntGte(f IntFact, v int) Conditions
- func (c Conditions) RequireIntLt(f IntFact, v int) Conditions
- func (c Conditions) RequireIntLte(f IntFact, v int) Conditions
- func (c Conditions) RequireIntRange(f IntFact, lo, hi int) Conditions
- func (c Conditions) SatisfiedBy(w WorldState) bool
- type Consideration
- type ConsiderationDef
- type CostGrid
- type CostMap
- type CoverHeight
- type CoverHeightTest
- type CoverPoint
- func GenerateCoverFromBoxes(boxes []physics.Box, opts ColliderCoverOptions) []CoverPoint
- func GenerateCoverFromGrid(g Grid, origin math2d.Vec2, cellWidth, cellHeight float32, opts GridCoverOptions) []CoverPoint
- func GenerateCoverFromSegments(segments []CoverSegment, opts ColliderCoverOptions) []CoverPoint
- func GenerateCoverFromTilemap(m *tilemap.Tilemap, opts TileCoverOptions) []CoverPoint
- func GenerateCoverFromWorld(w *physics.World, opts ColliderCoverOptions) []CoverPoint
- func (c CoverPoint) HasTag(tag string) bool
- type CoverPointGenerator
- type CoverSegment
- type CurveDef
- type CurveEvaluator
- type CurveFunc
- type CurveKind
- type CustomTest
- type DistanceTest
- type EdgeCostGrid
- type Effects
- type EngagementRing
- type EngagementSlot
- type Event
- type EventKind
- type FactSchema
- func NewFactSchema() *FactSchema
- func (s *FactSchema) Bool(name string) (BoolFact, error)
- func (s *FactSchema) BoolCount() int
- func (s *FactSchema) BoolName(f BoolFact) string
- func (s *FactSchema) Clone() *FactSchema
- func (s *FactSchema) Int(name string) (IntFact, error)
- func (s *FactSchema) IntCount() int
- func (s *FactSchema) IntName(f IntFact) string
- func (s *FactSchema) LookupBool(name string) (BoolFact, bool)
- func (s *FactSchema) LookupInt(name string) (IntFact, bool)
- func (s *FactSchema) MustBool(name string) BoolFact
- func (s *FactSchema) MustInt(name string) IntFact
- type FalloffKind
- type FloatRange
- type GOAPAction
- type GOAPActionDef
- type GOAPBindings
- type GOAPBoolFactDef
- type GOAPCompareOp
- type GOAPConditionsDef
- type GOAPConfig
- type GOAPEffectsDef
- type GOAPFactsDef
- type GOAPGoal
- type GOAPGoalDef
- type GOAPIntConditionDef
- type GOAPIntEffectDef
- type GOAPIntEffectOp
- type GOAPPlanner
- func NewGOAPPlanner(actions ...GOAPAction) (*GOAPPlanner, error)
- func (p *GOAPPlanner) Action(index int) GOAPAction
- func (p *GOAPPlanner) ActionCount() int
- func (p *GOAPPlanner) ActionIndex(name string) int
- func (p *GOAPPlanner) ActionName(index int) string
- func (p *GOAPPlanner) Plan(start WorldState, goal GOAPGoal) (plan []int, cost float64, err error)
- func (p *GOAPPlanner) PlanBestGoal(start WorldState, goals []GOAPGoal) (goalIndex int, plan []int, cost float64, err error)
- func (p *GOAPPlanner) PlanBestGoalInto(dst []int, start WorldState, goals []GOAPGoal) (goalIndex int, plan []int, cost float64, err error)
- func (p *GOAPPlanner) PlanInto(dst []int, start WorldState, goal GOAPGoal) (plan []int, cost float64, err error)
- func (p *GOAPPlanner) PlanNames(start WorldState, goal GOAPGoal) (names []string, cost float64, err error)
- type GOAPSet
- 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 NewGraphSearch[N comparable]() *GraphSearch[N]
- 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 GridCoverOptions
- type GridFunc
- type GridGenerator
- type GridPathOptions
- type GridPathResult
- type GridTopology
- func TopologyFromTilemap(m *tilemap.Tilemap) GridTopology
- func (t GridTopology) Distance(a, b Cell) float64
- func (t GridTopology) IsHex() bool
- func (t GridTopology) IsStaggered() bool
- func (t GridTopology) Neighbors(c Cell) []Cell
- func (t GridTopology) NeighborsInto(dst []Cell, c Cell) []Cell
- func (t GridTopology) String() string
- type HPA
- func NewHPA(g Grid, opts HPAOptions) *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 HearingConfig
- type HeatmapOptions
- type HeuristicGraph
- type HexGrid
- func NewHexGrid(m *tilemap.Tilemap) *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 InfluenceLayer
- func NewInfluenceLayer(cols, rows int) *InfluenceLayer
- func NewInfluenceLayerForGrid(g Grid, origin math2d.Vec2, cellSize float32) *InfluenceLayer
- func (l *InfluenceLayer) Abs()
- func (l *InfluenceLayer) Add(a, b *InfluenceLayer)
- func (l *InfluenceLayer) AddScaled(src *InfluenceLayer, weight float32)
- func (l *InfluenceLayer) AddSource(src InfluenceSource) InfluenceSourceID
- func (l *InfluenceLayer) At(col, row int) float32
- func (l *InfluenceLayer) CellAt(p math2d.Vec2) (Cell, bool)
- func (l *InfluenceLayer) CellCenter(c Cell) math2d.Vec2
- func (l *InfluenceLayer) Clamp(minVal, maxVal float32)
- func (l *InfluenceLayer) Clear()
- func (l *InfluenceLayer) ClearSources()
- func (l *InfluenceLayer) Combine(terms ...WeightedLayer)
- func (l *InfluenceLayer) CopyFrom(src *InfluenceLayer)
- func (l *InfluenceLayer) DrawHeatmap(d *core.Drawing, cam *tilemap.Camera, opts HeatmapOptions)
- func (l *InfluenceLayer) Fill(v float32)
- func (l *InfluenceLayer) Gradient(p math2d.Vec2) math2d.Vec2
- func (l *InfluenceLayer) GradientAtCell(col, row int) math2d.Vec2
- func (l *InfluenceLayer) Highest(g Grid) (Cell, float32, bool)
- func (l *InfluenceLayer) HighestInRadius(center Cell, radius float32, q InfluenceQuery) (Cell, float32, bool)
- func (l *InfluenceLayer) Lowest(g Grid) (Cell, float32, bool)
- func (l *InfluenceLayer) LowestInRadius(center Cell, radius float32, q InfluenceQuery) (Cell, float32, bool)
- func (l *InfluenceLayer) MarkDirtyCell(c Cell)
- func (l *InfluenceLayer) MarkDirtyRect(minCol, minRow, maxCol, maxRow int)
- func (l *InfluenceLayer) MoveSource(id InfluenceSourceID, cell Cell) bool
- func (l *InfluenceLayer) Multiply(a, b *InfluenceLayer)
- func (l *InfluenceLayer) Normalize()
- func (l *InfluenceLayer) Rebuild(g Grid)
- func (l *InfluenceLayer) RemoveSource(id InfluenceSourceID) bool
- func (l *InfluenceLayer) Resize(cols, rows int)
- func (l *InfluenceLayer) Sample(p math2d.Vec2) (float32, bool)
- func (l *InfluenceLayer) Scale(s float32)
- func (l *InfluenceLayer) Set(col, row int, v float32)
- func (l *InfluenceLayer) SetSource(id InfluenceSourceID, src InfluenceSource) bool
- func (l *InfluenceLayer) Size() (cols, rows int)
- func (l *InfluenceLayer) Source(id InfluenceSourceID) (InfluenceSource, bool)
- func (l *InfluenceLayer) SourceCount() int
- func (l *InfluenceLayer) Spread(g Grid, opts SpreadOptions)
- func (l *InfluenceLayer) Stamp(g Grid, src InfluenceSource)
- func (l *InfluenceLayer) Subtract(a, b *InfluenceLayer)
- func (l *InfluenceLayer) Update(g Grid)
- func (l *InfluenceLayer) Values() []float32
- type InfluenceQuery
- type InfluenceSource
- type InfluenceSourceID
- type InfluenceTest
- type IntEffectKind
- type IntFact
- type JPS
- func NewJPS() *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 LOSFunc
- type LOSTest
- type LineOfSight
- type Memory
- type NavAgent
- func NewNavAgent(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *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 NewNavAgentGroup(cfg NavAgentGroupConfig) *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
- func DefaultNavFilter() NavFilter
- func (f NavFilter) Allows(area NavArea, flags NavFlags) bool
- func (f NavFilter) AreaCost(area NavArea) float64
- func (f NavFilter) Clone() NavFilter
- func (f *NavFilter) ExcludeArea(area NavArea)
- func (f *NavFilter) IncludeArea(area NavArea)
- func (f *NavFilter) SetAreaCost(area NavArea, cost float64)
- type NavFlags
- type NavLinkEvent
- type NavListenerID
- type NavMesh
- func BuildNavMesh(polys [][]core.Point) *NavMesh
- func BuildNavMeshWithAreas(polys []NavPolygonInput) *NavMesh
- func (m *NavMesh) AddOffMeshLink(link NavOffMeshLink) bool
- func (m *NavMesh) AddPolygonFlags(index int, flags NavFlags)
- 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 NavMeshGenerator
- type NavMeshQuery
- func NewNavMeshQuery(mesh *NavMesh) *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) 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
- func NewNavMeshSearch(m *NavMesh, start, goal core.Point, opts PathOptions) *NavMeshSearch
- func NewNavMeshSearchWithFilter(m *NavMesh, start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearch
- func (s *NavMeshSearch) Expansions() int
- func (s *NavMeshSearch) Result() NavPathResult
- func (s *NavMeshSearch) Status() SearchStatus
- func (s *NavMeshSearch) Step(maxExpansions int) (status SearchStatus, expansions int)
- 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 NeighborGrid
- type NeighborGrid3D
- type Node
- func Action(fn func(dt time.Duration) Status) Node
- func BlackboardCondition(bb *Blackboard, key string, op BlackboardOp, value BlackboardValue, abort AbortMode, child Node) Node
- func BuildBehaviorTree(doc *BehaviorTreeDoc, bind BTBindings) (Node, error)
- func BuildBehaviorTreeFS(fsys fs.FS, name string, bind BTBindings) (Node, error)
- func Condition(fn func() bool) Node
- func Cooldown(d time.Duration, child Node) Node
- func Failer(child Node) Node
- func Guard(cond func() bool, child Node) Node
- func HasAttackToken(pool *TokenPool, agentID uint64) Node
- func Inverter(child Node) Node
- func Named(name string, child Node) Node
- func Parallel(policy ParallelPolicy, children ...Node) Node
- func RandomSelector(stream *random.Stream, children ...Node) Node
- func RandomSequence(stream *random.Stream, children ...Node) Node
- func Repeater(count int, child Node) Node
- func Retry(n int, child Node) Node
- func Selector(children ...Node) Node
- func Sequence(children ...Node) Node
- func Service(interval time.Duration, fn func(dt time.Duration), child Node) Node
- func SquadHasOrder(squad *Squad, kind string) Node
- func SquadHasRole(squad *Squad, agentID uint64, role string) Node
- func SquadOrderAction(squad *Squad, fn func(order SquadOrder, dt time.Duration) Status) Node
- func SquadStateBool(squad *Squad, key string) Node
- func Succeeder(child Node) Node
- func TimeLimit(d time.Duration, child Node) Node
- func UntilFail(child Node) Node
- func UtilitySelector[C any](reasoner *Reasoner[C], ctx func() C, rng *random.Stream, subtrees map[string]Node) Node
- func Wait(d time.Duration) Node
- func WeightedSelector(stream *random.Stream, options ...WeightedNode) Node
- func WithAttackToken(pool *TokenPool, agentID uint64, priority func() float64, child Node) Node
- type NodeOrder
- type Noise
- type ORCAAgent
- type ORCAAgent3D
- type ORCAConfig
- type ORCAObstacle
- type ORCAObstacle3D
- type ORCASolver
- func NewORCASolver(cfg ORCAConfig) *ORCASolver
- func (s *ORCASolver) Config() ORCAConfig
- func (s *ORCASolver) SetConfig(cfg ORCAConfig)
- func (s *ORCASolver) Solve(dst []math2d.Vec2, agents []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration) []math2d.Vec2
- func (s *ORCASolver) SolveAgent(agent ORCAAgent, neighbors []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration) math2d.Vec2
- func (s *ORCASolver) SolveAgentXZ(agent ORCAAgent3D, neighbors []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration) Vec3
- func (s *ORCASolver) SolveXZ(dst []Vec3, agents []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration) []Vec3
- func (s *ORCASolver) Step(agents []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration)
- func (s *ORCASolver) StepXZ(agents []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration)
- type Obstacle
- type Obstacle3D
- type ParallelPolicy
- type PathDistanceTest
- type PathFollowState
- type PathOptions
- type PathQueue
- func NewPathQueue(cfg PathQueueConfig) *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, onDone func(PathRequestID, SearchStatus)) PathRequestID
- func (q *PathQueue) SubmitGrid(a *AStar, g Grid, start, goal Cell, opts PathOptions, priority int, onDone func(PathRequestID, GridPathResult)) (PathRequestID, *AStarSearch)
- func (q *PathQueue) SubmitNavMesh(m *NavMesh, start, goal core.Point, opts PathOptions, priority int, onDone func(PathRequestID, NavPathResult)) (PathRequestID, *NavMeshSearch)
- func (q *PathQueue) TotalExpansions() int
- type PathQueueConfig
- type PathQueuePolicy
- type PathRequestID
- type Perception
- func (p *Perception) AppendMemories(dst []Memory) []Memory
- func (p *Perception) Clear()
- func (p *Perception) Events() []Event
- func (p *Perception) Forget(id StimulusID) bool
- func (p *Perception) Memories() []Memory
- func (p *Perception) Memory(id StimulusID) (Memory, bool)
- func (p *Perception) Sees(id StimulusID) bool
- type PerceptionStats
- type PerceptionSystem
- type PlanRunner
- func NewPlanRunner(planner *GOAPPlanner, world func() WorldState, goals []GOAPGoal, executors map[string]Node) *PlanRunner
- func (r *PlanRunner) ActiveGoal() int
- func (r *PlanRunner) CurrentAction() string
- func (r *PlanRunner) LastError() error
- func (r *PlanRunner) Plans() int
- func (r *PlanRunner) Reset()
- func (r *PlanRunner) Step() int
- func (r *PlanRunner) Tick(dt time.Duration) Status
- type PointReservations
- func NewPointReservations(cfg ReservationConfig) *PointReservations
- func (r *PointReservations) Clear()
- func (r *PointReservations) Config() ReservationConfig
- func (r *PointReservations) Count() int
- func (r *PointReservations) Entries(dst []Reservation) []Reservation
- func (r *PointReservations) Get(agentID uint64) (Reservation, bool)
- func (r *PointReservations) HolderOfCover(coverID uint64) (uint64, bool)
- func (r *PointReservations) IsReservedByOther(agentID, coverID uint64, pos math2d.Vec2) bool
- func (r *PointReservations) Refresh(agentID uint64, timeout time.Duration) bool
- func (r *PointReservations) Release(agentID uint64) bool
- func (r *PointReservations) ReleaseCover(coverID uint64) bool
- func (r *PointReservations) Reserve(agentID uint64, c TacticalCandidate, timeout time.Duration) bool
- func (r *PointReservations) ReserveCover(agentID uint64, cp CoverPoint, timeout time.Duration) bool
- func (r *PointReservations) ReservePos(agentID uint64, pos math2d.Vec2, timeout time.Duration) bool
- func (r *PointReservations) Step(dt time.Duration)
- type QueryBudget
- func NewQueryBudget(maxRaycasts, maxPathQueries int) *QueryBudget
- func (b *QueryBudget) PathQueriesRemaining() int
- func (b *QueryBudget) PathQueriesUsed() int
- func (b *QueryBudget) RaycastsRemaining() int
- func (b *QueryBudget) RaycastsUsed() int
- func (b *QueryBudget) Reset()
- func (b *QueryBudget) TryConsumePathQuery() bool
- func (b *QueryBudget) TryConsumeRaycast() bool
- type QueryOrigin
- type QueryStats
- type ReachableCell
- type ReachableNode
- type Reasoner
- func BuildReasoner[C any](cfg *UtilityConfig, bind UtilityBindings[C]) (*Reasoner[C], error)
- func NewReasoner[C any](actions ...UtilityAction[C]) *Reasoner[C]
- func (r *Reasoner[C]) ActionCount() int
- func (r *Reasoner[C]) ActionIndex(name string) int
- func (r *Reasoner[C]) ActionName(index int) string
- func (r *Reasoner[C]) Choose(ctx C, rng *random.Stream) (int, float64)
- func (r *Reasoner[C]) ChooseWithCurrent(ctx C, current int, rng *random.Stream) (int, float64)
- func (r *Reasoner[C]) Current() int
- func (r *Reasoner[C]) Reset()
- func (r *Reasoner[C]) ScoreAction(index int, ctx C, isCurrent bool) float64
- func (r *Reasoner[C]) ScoreAll(ctx C, current int, dst []float64) []float64
- func (r *Reasoner[C]) SetCurrent(index int)
- type Reservation
- type ReservationConfig
- type ResponseCurve
- func CustomCurve(fn func(float64) float64) ResponseCurve
- func LinearCurve(slope, shiftX, shiftY float64) ResponseCurve
- func LogisticCurve(slope, steepness, midpoint, shiftY float64) ResponseCurve
- func LogitCurve(slope, midpoint, shiftY float64) ResponseCurve
- func PolynomialCurve(slope, exponent, shiftX, shiftY float64) ResponseCurve
- func ResourceCurve(eval CurveEvaluator) ResponseCurve
- func StepCurve(threshold, low, high float64) ResponseCurve
- func (c ResponseCurve) Eval(x float64) float64
- type RingGenerator
- type SearchStatus
- type Sense
- type SightConfig
- type SlotAgent
- type SlotAssigner
- func NewSlotAssigner(rings ...EngagementRing) *SlotAssigner
- func (a *SlotAssigner) Assign(dst []SlotAssignment, target core.Point, agents []SlotAgent) []SlotAssignment
- func (a *SlotAssigner) Assignment(agentID uint64) (SlotAssignment, bool)
- func (a *SlotAssigner) Release(agentID uint64)
- func (a *SlotAssigner) Reset()
- func (a *SlotAssigner) Rings() []EngagementRing
- func (a *SlotAssigner) Slots(dst []EngagementSlot, target core.Point) []EngagementSlot
- func (a *SlotAssigner) TotalSlots() int
- type SlotAssignment
- type SnapshotNode
- type SpreadOptions
- type Squad
- func NewSquad(id uint64, members ...uint64) *Squad
- func (s *Squad) AddMember(agentID uint64) bool
- func (s *Squad) AssignRoles(specs ...SquadRoleSpec) int
- func (s *Squad) ClearOrder()
- func (s *Squad) ClearRoles()
- func (s *Squad) HasMember(agentID uint64) bool
- func (s *Squad) HasRole(agentID uint64, role string) bool
- func (s *Squad) ID() uint64
- func (s *Squad) MemberCount() int
- func (s *Squad) Members(dst []uint64) []uint64
- func (s *Squad) MembersWithRole(dst []uint64, role string) []uint64
- func (s *Squad) Order() SquadOrder
- func (s *Squad) RemoveMember(agentID uint64) bool
- func (s *Squad) Role(agentID uint64) string
- func (s *Squad) SetOrder(order SquadOrder) SquadOrder
- func (s *Squad) SetRole(agentID uint64, role string) bool
- func (s *Squad) State() *SquadState
- type SquadOrder
- type SquadRoleSpec
- type SquadState
- func (s *SquadState) Bool(key string) (bool, bool)
- func (s *SquadState) Clear()
- func (s *SquadState) Delete(key string)
- func (s *SquadState) Float(key string) (float64, bool)
- func (s *SquadState) Get(key string) (any, bool)
- func (s *SquadState) Has(key string) bool
- func (s *SquadState) ID(key string) (uint64, bool)
- func (s *SquadState) Int(key string) (int, bool)
- func (s *SquadState) Keys(dst []string) []string
- func (s *SquadState) Len() int
- func (s *SquadState) Point(key string) (core.Point, bool)
- func (s *SquadState) Set(key string, value any)
- func (s *SquadState) SetBool(key string, v bool)
- func (s *SquadState) SetFloat(key string, v float64)
- func (s *SquadState) SetID(key string, v uint64)
- func (s *SquadState) SetInt(key string, v int)
- func (s *SquadState) SetPoint(key string, v core.Point)
- func (s *SquadState) SetString(key string, v string)
- func (s *SquadState) String(key string) (string, bool)
- type Status
- type StimulusID
- type TacticalCandidate
- type TacticalContext
- type TacticalQuery
- func NewTacticalQuery(generators []CandidateGenerator, tests ...TacticalTest) *TacticalQuery
- func (q *TacticalQuery) Best(ctx TacticalContext) (TacticalCandidate, bool)
- func (q *TacticalQuery) LastStats() QueryStats
- func (q *TacticalQuery) Run(ctx TacticalContext) []TacticalCandidate
- func (q *TacticalQuery) RunAndReserve(ctx TacticalContext, timeout time.Duration) (TacticalCandidate, bool)
- func (q *TacticalQuery) RunInto(dst []TacticalCandidate, ctx TacticalContext) []TacticalCandidate
- type TacticalTest
- type Target
- type Team
- type TestPurpose
- type TileCoverOptions
- type TiledNavMesh
- func BuildTiledNavMesh(polys [][]core.Point, tileSize float32) *TiledNavMesh
- func BuildTiledNavMeshWithAreas(polys []NavPolygonInput, tileSize float32) *TiledNavMesh
- func NewTiledNavMesh(cfg TiledNavMeshConfig) *TiledNavMesh
- func (tm *TiledNavMesh) AddObstacle(obs NavObstacle) (NavObstacleID, 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) 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) 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 TiledNavPathResult
- type TiledNavRaycastHit
- type TokenHolder
- type TokenManager
- func NewTokenManager(defaultCfg TokenPoolConfig) *TokenManager
- func (m *TokenManager) Cancel(targetID, agentID uint64) bool
- func (m *TokenManager) ConfigureTarget(targetID uint64, cfg TokenPoolConfig) *TokenPool
- func (m *TokenManager) HasToken(targetID, agentID uint64) bool
- func (m *TokenManager) Pool(targetID uint64) *TokenPool
- func (m *TokenManager) Release(targetID, agentID uint64) bool
- func (m *TokenManager) RemoveAgent(agentID uint64)
- func (m *TokenManager) RemoveTarget(targetID uint64) bool
- func (m *TokenManager) Request(targetID, agentID uint64, priority float64)
- func (m *TokenManager) Reset()
- func (m *TokenManager) Step(dt time.Duration)
- type TokenPool
- func NewTokenPool(cfg TokenPoolConfig) *TokenPool
- func (p *TokenPool) Available() int
- func (p *TokenPool) Cancel(agentID uint64) bool
- func (p *TokenPool) Capacity() int
- func (p *TokenPool) Config() TokenPoolConfig
- func (p *TokenPool) CoolingDown() int
- func (p *TokenPool) HasToken(agentID uint64) bool
- func (p *TokenPool) HeldCount() int
- func (p *TokenPool) Holder(agentID uint64) (TokenHolder, bool)
- func (p *TokenPool) Holders(dst []TokenHolder) []TokenHolder
- func (p *TokenPool) PendingCount() int
- func (p *TokenPool) Release(agentID uint64) bool
- func (p *TokenPool) Remove(agentID uint64) bool
- func (p *TokenPool) Request(agentID uint64, priority float64)
- func (p *TokenPool) Reset()
- func (p *TokenPool) Step(dt time.Duration)
- type TokenPoolConfig
- type UtilityAction
- type UtilityActionDef
- type UtilityBindings
- type UtilityConfig
- type ValidatedGraph
- type Vec3
- func Alignment3D(a Agent3D, neighbors []Agent3D, radius float32) Vec3
- func Arrive3D(a Agent3D, target Vec3, slowRadius float32) Vec3
- func Cohesion3D(a Agent3D, neighbors []Agent3D, radius float32) Vec3
- func Combine3D(maxForce float32, forces ...WeightedForce3D) Vec3
- func CombinePrioritized3D(maxForce float32, forces ...WeightedForce3D) Vec3
- func Evade3D(a, pursuer Agent3D, panicRadius, maxLookAhead float32) Vec3
- func Flee3D(a Agent3D, threat Vec3, panicRadius float32) Vec3
- func FollowPath3D(a Agent3D, path []Vec3, state *PathFollowState, waypointRadius float32, loop bool) Vec3
- func Hide3D(a, pursuer Agent3D, obstacles []Obstacle3D, standoff, slowRadius float32) Vec3
- func Interpose3D(a, targetA, targetB Agent3D, slowRadius float32) Vec3
- func ObstacleAvoidance3D(a Agent3D, obstacles []Obstacle3D, maxAhead float32) Vec3
- func OffsetPursuit3D(a, leader Agent3D, localOffset Vec3, slowRadius, maxLookAhead float32) Vec3
- func Pursue3D(a, target Agent3D, maxLookAhead float32) Vec3
- func Seek3D(a Agent3D, target Vec3) Vec3
- func Separation3D(a Agent3D, neighbors []Agent3D, desiredSep float32) Vec3
- func WallAvoidance3D(a Agent3D, walls []Wall3D, feelerLength float32) Vec3
- type Wall
- type Wall3D
- type WanderState
- type WaypointEdge
- type WaypointGraph
- func NewWaypointGraph() *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
- type WeightedForce
- type WeightedForce3D
- type WeightedLayer
- type WeightedNode
- type WorldState
- func (w WorldState) Apply(eff Effects) WorldState
- func (w WorldState) Bool(f BoolFact) bool
- func (w WorldState) Int(f IntFact) int
- func (w WorldState) Satisfies(cond Conditions) bool
- func (w *WorldState) SetBool(f BoolFact, v bool)
- func (w *WorldState) SetInt(f IntFact, v int)
- func (w WorldState) WithBool(f BoolFact, v bool) WorldState
- func (w WorldState) WithInt(f IntFact, v int) WorldState
Konstanten
const (
// MaxBoolFacts is the maximum number of named boolean facts a FactSchema and WorldState can store.
MaxBoolFacts = 128
// MaxIntFacts is the maximum number of named small integer facts a FactSchema and WorldState can store.
MaxIntFacts = 16
// DefaultGOAPNodeBudget is the default maximum number of regressive A* search nodes expanded per plan.
DefaultGOAPNodeBudget = 1024
)const (
// DefaultHPAClusterSize is the default width and height in cells of each HPA* cluster.
DefaultHPAClusterSize = 16
// DefaultHPAMaxEntranceSpan is the maximum contiguous walkable border span represented by a single entrance before splitting into endpoint entrances.
DefaultHPAMaxEntranceSpan = 6
)const (
// DefaultORCATimeHorizon is the default look-ahead horizon (in seconds) for agent-agent avoidance.
DefaultORCATimeHorizon float32 = 2.0
// DefaultORCATimeHorizonObst is the default look-ahead horizon (in seconds) for static obstacle edges.
DefaultORCATimeHorizonObst float32 = 1.0
// DefaultORCAMaxNeighbors is the default cap on nearest neighbors per agent contributing ORCA constraints.
DefaultORCAMaxNeighbors = 16
// ORCALayerDefault is the default avoidance layer assigned when an ORCAAgent's Layer is 0.
ORCALayerDefault uint32 = 1
// ORCAMaskAll matches every avoidance layer and is the default when Mask (or obstacle Layer) is 0.
ORCAMaskAll uint32 = ^uint32(0)
)const BTFormatVersion = 1BTFormatVersion is the behavior tree YAML schema version this package reads and writes.
const BTSchemaComment = "# yaml-language-server: $schema=" + BTSchemaURLBTSchemaComment is the first line EncodeBehaviorTree writes so YAML language servers validate and complete behavior tree files automatically.
const BTSchemaURL = "https://game.nsgo.dev/schemas/bt.v1.json"BTSchemaURL is where the JSON Schema of version 1 behavior tree documents is published.
const BTSnapshotVersion = 1BTSnapshotVersion is the BehaviorTreeSnapshot schema version written and read by SnapshotBehaviorTree and RestoreBehaviorTree.
const GOAPVersion = 1GOAPVersion is the GOAP action-set YAML schema version this package reads and writes.
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.
const UtilityVersion = 1UtilityVersion is the utility AI YAML schema version this package reads and writes.
Variablen
var (
// ErrNoPlan is returned when no sequence of usable actions can satisfy the target goal from the current WorldState.
ErrNoPlan = errors.New("ai: no plan found")
// ErrBudgetExceeded is returned when regressive A* exhausts GOAPPlanner.NodeBudget without finding a plan.
ErrBudgetExceeded = errors.New("ai: planner node budget exceeded")
)var ErrInvalidBTSnapshot = errors.New("ai: invalid behavior tree snapshot")ErrInvalidBTSnapshot reports a BehaviorTreeSnapshot that RestoreBehaviorTree refuses because its version, tree structure, node kinds, or state values do not match the target behavior tree.
Funktionen
func Alignment(a Agent, neighbors []Agent, radius float32) core.PointAlignment returns a steering force that steers a toward the average heading of neighbors within radius. When radius is less than or equal to 0, all non-coincident neighbors in the slice are included.
func Arrive(a Agent, target core.Point, slowRadius float32) core.PointArrive returns a steering force toward target that smoothly scales desired speed down to zero inside slowRadius.
func Cohesion(a Agent, neighbors []Agent, radius float32) core.PointCohesion returns a steering force that steers a toward the center of mass of neighbors within radius. When radius is less than or equal to 0, all non-coincident neighbors in the slice are included.
func Combine(maxForce float32, forces ...WeightedForce) core.PointCombine sums weighted steering forces and clamps the result's magnitude to maxForce when maxForce is positive.
func CombinePrioritized(maxForce float32, forces ...WeightedForce) core.PointCombinePrioritized blends steering forces in priority order (earliest entry first), spending at most maxForce total magnitude. Once a force saturates the remaining budget it is truncated to the remainder and lower-priority forces are ignored. When maxForce is less than or equal to 0, forces are summed without truncation.
func EncodeBehaviorTree(doc *BehaviorTreeDoc) ([]byte, error)EncodeBehaviorTree validates doc and serializes it as deterministic 2-space YAML in fixed field order prefixed with BTSchemaComment.
func EncodeGOAP(cfg *GOAPConfig) ([]byte, error)EncodeGOAP validates cfg and encodes it as deterministic 2-space YAML in fixed field order.
func EncodeUtility(cfg *UtilityConfig) ([]byte, error)EncodeUtility validates cfg and encodes it as deterministic 2-space YAML in fixed field order.
func Evade(a, pursuer Agent, panicRadius, maxLookAhead float32) core.PointEvade returns a steering force that flees from the predicted future position of pursuer. When panicRadius is positive, Evade returns the zero force once a is at least panicRadius away from pursuer.Pos. Look-ahead time is capped to maxLookAhead seconds when maxLookAhead is positive.
func Flee(a Agent, threat core.Point, panicRadius float32) core.PointFlee returns the steering force that accelerates a away from threat at MaxSpeed. When panicRadius is positive, Flee returns the zero force once a is at least panicRadius away from threat.
func FollowPath(a Agent, path []core.Point, state *PathFollowState, waypointRadius float32, loop bool) core.PointFollowPath steers a along path, advancing state.Index when a enters waypointRadius of the current waypoint.
When loop is true the path wraps back to index 0; otherwise the agent uses Arrive on the final waypoint and sets state.Done once within waypointRadius.
func FormatBTTrace(nodes []BTNodeTrace) stringFormatBTTrace renders nodes in a deterministic canonical text format suitable for statedump Values and golden-file diffs across runs.
Each line represents one node indented by 2 spaces per depth level, prefixed with "* " when Active (on the running path) or " " otherwise:
- selector "root" = Running sequence "attack" = Failure condition "in_range" = Failure action "swing" = Idle
- action "patrol" = Running
func GridLineOfSight(g Grid, a, b core.Point, opts GridPathOptions) boolGridLineOfSight 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 Hide(a, pursuer Agent, obstacles []Obstacle, standoff, slowRadius float32) core.PointHide picks the closest hiding spot behind a circular obstacle opposite pursuer and steers a toward it using Arrive. Each spot lies obs.Radius + a.Radius + max(0, standoff) past obs.Center along the ray from pursuer.Pos through obs.Center. If no valid obstacle exists, Hide falls back to Evade.
func InfluenceHeatmapEnabled() boolInfluenceHeatmapEnabled reports whether DrawHeatmap is compiled into this build. It is true in default builds and false when built with -tags release.
func Interpose(a, targetA, targetB Agent, slowRadius float32) core.PointInterpose steers a to intercept the predicted midpoint between two moving agents targetA and targetB, slowing smoothly inside slowRadius via Arrive.
func ObstacleAvoidance(a Agent, obstacles []Obstacle, maxAhead float32) core.PointObstacleAvoidance returns a steering force that deflects a around the nearest circular obstacle intersecting its forward detection corridor of length maxAhead. When maxAhead is less than or equal to 0, a default look-ahead is derived from a.Radius and a.MaxSpeed.
func OffsetPursuit(a, leader Agent, localOffset core.Point, slowRadius, maxLookAhead float32) core.PointOffsetPursuit returns a steering force that moves a to localOffset expressed in leader's heading frame (X forward along leader's heading, Y to leader's left perpendicular), predicting leader's motion up to maxLookAhead seconds when positive and slowing smoothly inside slowRadius via Arrive.
func Pursue(a, target Agent, maxLookAhead float32) core.PointPursue returns a steering force that intercepts a moving target by predicting its future position from target.Vel. Look-ahead time is computed from distance divided by combined speed and capped to maxLookAhead seconds when maxLookAhead is positive.
func RestoreBehaviorTree(root Node, snap BehaviorTreeSnapshot) errorRestoreBehaviorTree validates snap against the tree rooted at root and restores every node's runtime state atomically.
If snap has an unsupported version, does not match root's exact structural shape and node kinds, contains out-of-range values, or a custom SnapshotNode refuses its state, RestoreBehaviorTree returns an error wrapping ErrInvalidBTSnapshot naming the mismatch path and leaves root unchanged.
func Seek(a Agent, target core.Point) core.PointSeek returns the steering force that accelerates a toward target at MaxSpeed.
func Separation(a Agent, neighbors []Agent, desiredSep float32) core.PointSeparation returns a steering force that pushes a away from neighbors closer than desiredSep. When desiredSep is less than or equal to 0, a.Radius + neighbor.Radius is used for each neighbor.
func SmoothGridPath(g Grid, path []Cell, opts GridPathOptions) []core.PointSmoothGridPath converts a grid cell path (such as from AStar.Find) into world-space waypoints, dropping intermediate cells whenever a body of radius opts.Radius can walk straight between kept waypoints without passing within opts.Radius of any blocked cell.
SmoothGridPath checks walkability via g.Walkable and ignores CostGrid terrain weights. When smoothing with a positive opts.Radius, pair it with standard cell-by-cell AStar (AnyAngle: false) so corner cells remain available when the body radius cannot clear a corner directly.
It allocates only the returned waypoint slice; use SmoothGridPathInto to reuse a caller-owned slice with zero allocations.
func SmoothGridPathInto(dst []core.Point, g Grid, path []Cell, opts GridPathOptions) []core.PointSmoothGridPathInto behaves like SmoothGridPath but appends the smoothed waypoints into dst[:0], avoiding heap allocations when dst has enough capacity.
func SquadStateGet[T any](s *SquadState, key string) (T, bool)SquadStateGet retrieves a typed value of type T from s, returning (zero, false) when s is nil, the key is missing, or the stored value has a different type.
func ValidateBehaviorTree(doc *BehaviorTreeDoc) errorValidateBehaviorTree checks that doc conforms to the version 1 behavior tree schema.
func WallAvoidance(a Agent, walls []Wall, feelerLength float32) core.PointWallAvoidance returns a steering force that keeps a clear of wall segments using three forward feeler whiskers and direct radius clearance containment. When feelerLength is less than or equal to 0, a default length is derived from a.Radius and a.MaxSpeed.
func Wander(a Agent, state *WanderState, radius, distance, jitter float32, nextRand func() float32) core.PointWander steers a toward a point jittered along a circle of radius placed distance ahead of its heading.
nextRand should return a deterministic value in [0, 1), mapped to [-jitter, +jitter] radians per call; a nil nextRand applies no jitter.
Typen
type AStar struct {
// Diagonal allows 8-way movement with step distance sqrt(2) on diagonals; false restricts movement to 4 cardinal directions.
// On hexagonal topologies Diagonal has no effect; TopologySquare4 and TopologySquare8 override Diagonal.
Diagonal bool
// NoCornerCutting prevents diagonal moves when either adjacent cardinal cell is blocked. It only takes effect when diagonal moves are enabled, and also prevents Theta* any-angle lines of sight from grazing blocked cell corners when AnyAngle is true.
NoCornerCutting bool
// AnyAngle enables Theta*-style any-angle pathfinding on square grids (TopologySquare, TopologySquare4, TopologySquare8),
// linking neighbors directly to an ancestor cell whenever line of sight between cell centers is unobstructed across uniform-cost cells.
// AnyAngle is ignored on hexagonal or staggered topologies and on EdgeCostGrid maps.
// When smoothing a path for a body with positive clearance radius, prefer standard cell-by-cell A* (AnyAngle: false) followed by SmoothGridPath or SmoothGridPathInto.
AnyAngle bool
// Topology selects the cell adjacency and admissible distance heuristic. The zero value (TopologySquare) preserves square-grid behavior.
Topology GridTopology
// MaxExpansions caps the number of cells expanded per Find or FindInto call.
// Zero or negative means unlimited expansions. FindWithOptions uses this limit when PathOptions.MaxExpansions is zero.
MaxExpansions int
// contains filtered or unexported fields
}AStar finds lowest-cost paths on a Grid, reusing its internal search buffers across calls.
NewAStar returns a searcher with NoCornerCutting enabled by default. An AStar is not safe for concurrent use by multiple goroutines.
func NewAStar() *AStarNewAStar returns an AStar searcher with 4-way movement and NoCornerCutting enabled by default.
func (a *AStar) Find(g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)Find searches g for a minimum-cost path from start to goal, returning the cells from start to goal inclusive and the total path cost.
It reuses all internal search buffers and allocates only the returned path slice.
func (a *AStar) FindInto(dst []Cell, g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)FindInto behaves like Find but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.
func (a *AStar) FindWithOptions(g Grid, start, goal Cell, opts PathOptions) GridPathResultFindWithOptions searches g from start to goal under opts, supporting an expansion budget and optional partial paths to the closest explored cell when the goal is unreachable or the budget runs out.
func (a *AStar) FindWithOptionsInto(dst []Cell, g Grid, start, goal Cell, opts PathOptions) GridPathResultFindWithOptionsInto behaves like FindWithOptions but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.
func (a *AStar) MovementRange(g Grid, start Cell, budget float64) []ReachableCellMovementRange runs a Dijkstra search from start on g under a.Topology (and a.Diagonal / a.NoCornerCutting) and returns every reachable cell whose minimum traversal cost is at most budget, ordered by ascending cost then row-major cell index.
It reuses a's internal search buffers and allocates only the returned slice.
func (a *AStar) MovementRangeInto(dst []ReachableCell, g Grid, start Cell, budget float64) []ReachableCellMovementRangeInto behaves like MovementRange but writes results into dst[:0], avoiding heap allocations when dst has enough capacity.
func (a *AStar) MovementRangeWithCost(dst []ReachableCell, g Grid, start Cell, budget float64, edgeCost func(from, to Cell) float64) []ReachableCellMovementRangeWithCost behaves like MovementRangeInto, and when edgeCost is non-nil uses edgeCost(from, to) as the step cost multiplier instead of CostGrid or EdgeCostGrid.
Returning a negative, NaN or infinite value from edgeCost forbids moving along that edge. Non-negative finite values (including costs between 0 and 1, such as roads) are multiplied by the step's geometric length (1 for cardinal/hex/staggered edges, sqrt(2) for diagonals).
func (a *AStar) StartSearch(g Grid, start, goal Cell, opts PathOptions) *AStarSearchStartSearch begins an incremental grid A* search using a's configuration (Diagonal, NoCornerCutting, Topology, MaxExpansions). The returned AStarSearch owns independent search buffers so multiple searches may run across frames concurrently.
type AStarSearch struct {
// contains filtered or unexported fields
}AStarSearch runs a deterministic grid A* search incrementally across bounded Step calls.
Stepping a search with any positive per-step expansion budget produces the exact same path, cost, partial flag, and expansion count as a single-shot AStar.FindWithOptions call. *AStarSearch implements IncrementalSearch.
func NewAStarSearch(a *AStar, g Grid, start, goal Cell, opts PathOptions) *AStarSearchNewAStarSearch initializes an incremental grid A* search copying configuration from a (when a is nil, defaults to 4-way TopologySquare with NoCornerCutting enabled).
func (s *AStarSearch) Expansions() intExpansions returns the cumulative number of grid cells expanded so far.
func (s *AStarSearch) Reset(a *AStar, g Grid, start, goal Cell, opts PathOptions)Reset reinitializes s for a new query, reusing its internal search buffers.
func (s *AStarSearch) Result() GridPathResultResult returns the search outcome once finished (or a result with Found == false while still in progress).
func (s *AStarSearch) ResultInto(dst []Cell) GridPathResultResultInto behaves like Result but writes the path into dst[:0] when finished.
func (s *AStarSearch) Status() SearchStatusStatus returns the search's current status.
func (s *AStarSearch) Step(maxExpansions int) (status SearchStatus, expansions int)Step advances the search by at most maxExpansions grid cell expansions and returns the updated status and exact number of expansions performed. When maxExpansions <= 0 or the search is already finished, Step performs 0 expansions.
type AbortMode stringAbortMode controls how a BlackboardCondition decorator interrupts running branches when its watched blackboard key changes.
const (
// AbortNone checks the condition only on entry into the child.
AbortNone AbortMode = "none"
// AbortSelf aborts the decorator's own running child (or enclosing Sequence's
// subsequent running child when used without a child) when the watched key
// changes and the condition becomes false.
AbortSelf AbortMode = "self"
// AbortLower aborts a running lower-priority sibling in an enclosing Selector
// on the next tick when the watched key changes and the condition becomes true.
AbortLower AbortMode = "lower"
// AbortBoth combines AbortSelf and AbortLower.
AbortBoth AbortMode = "both"
)func (m AbortMode) Valid() boolValid reports whether m is a recognized AbortMode (including empty, which means AbortNone).
type Agent struct {
Pos core.Point
Vel core.Point
MaxSpeed float32
MaxForce float32
Radius float32
}Agent is a 2D steering agent with position, velocity and movement limits.
func (a *Agent) Step(force core.Point, dt time.Duration)Step integrates a by dt under steering acceleration force, clamping force to MaxForce and velocity to MaxSpeed when positive.
type Agent3D struct {
Pos Vec3
Vel Vec3
MaxSpeed float32
MaxForce float32
Radius float32
PlanarXZ bool
}Agent3D is a 3D steering agent with position, velocity, and movement limits.
When PlanarXZ is true, steering forces and Step integration operate on the horizontal XZ plane (force.Y is zeroed and speed limits apply to XZ), which suits grounded agents following world3d.NavMesh paths.
func (a *Agent3D) Step(force Vec3, dt time.Duration)Step integrates a by dt under steering acceleration force, clamping force to MaxForce and velocity to MaxSpeed when positive. When a.PlanarXZ is true, force.Y and Vel.Y are zeroed and a.Pos.Y is preserved.
type AngleMode uint8AngleMode selects which two vectors AngleTest measures the angle between.
const (
// AngleCoverToTarget measures the angle between candidate.Facing and normalize(Target - candidate.Pos).
// 0 radians means the cover directly faces and shields against the target; pi radians means fully exposed.
AngleCoverToTarget AngleMode = iota
// AngleFlank measures the angle between normalize(candidate.Pos - Target) and the reference direction
// (ReferenceDir or ctx.TargetDir): 0 is directly in front of the target, pi/2 is a side flank, pi is behind.
AngleFlank
// AngleToDirection measures the angle between candidate.Facing and the reference direction.
AngleToDirection
// AngleFromTargetToDir measures the angle between normalize(Target - candidate.Pos) and the reference direction.
AngleFromTargetToDir
)type AngleTest struct {
// Mode chooses which vectors are compared (defaults to AngleCoverToTarget).
Mode AngleMode
// Target selects the reference point for AngleCoverToTarget, AngleFlank, and AngleFromTargetToDir.
// Zero value defaults to OriginTarget.
Target QueryOrigin
// CustomTarget is used when Target is OriginCustom.
CustomTarget math2d.Vec2
// ReferenceDir overrides ctx.TargetDir when non-zero for AngleFlank, AngleToDirection, and AngleFromTargetToDir.
ReferenceDir math2d.Vec2
// Purpose selects filtering, scoring, or both (defaults to TestFilterAndScore).
Purpose TestPurpose
// Filter optionally restricts angles in radians (for example, AtMost(math.Pi/3)).
Filter FloatRange
// NormMin and NormMax optionally specify fixed normalization bounds in radians.
// When NormMax <= NormMin, values normalize dynamically across surviving candidates.
NormMin, NormMax float64
// Weight scales the normalized [0, 1] score contribution.
Weight float64
// Invert flips the normalized score (1 - norm) so smaller angles score higher.
Invert bool
}AngleTest measures the angle in radians [0, pi] between two directions.
By default (AngleCoverToTarget), it measures the angle between candidate.Facing and the direction from candidate.Pos toward TargetPos: 0 radians means the cover directly blocks threats from TargetPos.
type Attitude uint8Attitude is how an observer regards another team.
const (
// Hostile marks an enemy.
Hostile Attitude = iota
// Neutral marks something on no side.
Neutral
// Friendly marks an ally.
Friendly
)func DefaultAttitude(observer, other Team) AttitudeDefaultAttitude treats the same team as friendly, NoTeam on either side as neutral, and every other pair of teams as hostile.
func (a Attitude) String() stringString returns the attitude's lower-case name.
type AttitudeFunc func(observer, other Team) AttitudeAttitudeFunc decides how an observer on team observer regards a stimulus on team other.
type AttitudeMask uint8AttitudeMask selects the attitudes a sense detects. A zero AttitudeMask detects hostile stimuli only.
const (
// DetectHostile detects hostile stimuli.
DetectHostile AttitudeMask = 1 << Hostile
// DetectNeutral detects neutral stimuli.
DetectNeutral AttitudeMask = 1 << Neutral
// DetectFriendly detects friendly stimuli.
DetectFriendly AttitudeMask = 1 << Friendly
// DetectAll detects every attitude.
DetectAll = DetectHostile | DetectNeutral | DetectFriendly
)func (m AttitudeMask) Has(a Attitude) boolHas reports whether m detects attitude a, treating a zero mask as DetectHostile.
type BTBindings struct {
// Blackboard is bound to blackboard_condition nodes and passed to leaf factories.
// When nil, BuildBehaviorTree creates a fresh local Blackboard.
Blackboard *Blackboard
// Stream is passed to random_selector, random_sequence, and weighted_selector nodes.
Stream *random.Stream
// Actions maps action names to factories returning a leaf Node.
Actions map[string]func(BTNodeContext) (Node, error)
// Conditions maps condition names to factories returning a predicate func() bool
// (used by condition leaves and guard decorators).
Conditions map[string]func(BTNodeContext) (func() bool, error)
// Services maps service names to factories returning a func(dt time.Duration) callback
// (used by service decorators).
Services map[string]func(BTNodeContext) (func(time.Duration), error)
// FS is an optional filesystem used to load referenced subtree files relative to the parent tree.
FS fs.FS
// LoadSubtree optionally overrides subtree file loading when custom storage is used.
LoadSubtree func(path string) ([]byte, error)
}BTBindings provides the blackboard, deterministic random stream, leaf factories, and optional subtree loader used by BuildBehaviorTree.
type BTBlackboardKeyDoc struct {
// Key is the blackboard key name.
Key string `yaml:"key" schema:"required,minLength=1"`
// Type is the value kind: bool, int, float, string, vec2, vec3, or entity.
Type BlackboardKindName `yaml:"type" schema:"required,enum=bool|int|float|string|vec2|vec3|entity"`
// Shared targets the parent (squad or team) blackboard instead of the agent's local blackboard when seeding Default.
// Default is an optional initial value matching Type (scalar, [x, y] for vec2, or [x, y, z] for vec3).
Default *any `yaml:"default,omitempty"`
}BTBlackboardKeyDoc declares one typed blackboard key and its optional initial default value.
type BTInspector struct {
// contains filtered or unexported fields
}BTInspector provides zero-allocation, read-only inspection of a behavior tree once warmed up.
Construct one inspector per tree with NewBTInspector(root), then call WalkInto(buf) after ticking the tree to populate a reusable slice of BTNodeTrace entries in pre-order.
func NewBTInspector(root Node) *BTInspectorNewBTInspector builds a reusable read-only inspector for root, precomputing its static pre-order traversal and node paths so subsequent WalkInto calls perform zero heap allocations.
func (ins *BTInspector) Format() stringFormat returns a deterministic, human-readable text snapshot of the tree's current state suitable for statedump Values and diffing AI decisions across runs.
func (ins *BTInspector) Len() intLen returns the total number of nodes in the inspected tree.
func (ins *BTInspector) Reset()Reset resets ins's root node and clears any root fallback status.
func (ins *BTInspector) Root() NodeRoot returns the behavior tree root inspected by ins.
func (ins *BTInspector) RunningPath() []BTNodeTraceRunningPath returns a newly allocated slice of the nodes on the tree's currently running path (Active == true) in pre-order. For zero-allocation per-tick inspection, call WalkInto followed by RunningPathInto.
func (ins *BTInspector) String() stringString implements fmt.Stringer by returning ins.Format().
func (ins *BTInspector) Tick(dt time.Duration) StatusTick ticks ins's root node by dt and returns its status.
Callers may tick root directly instead of calling ins.Tick; calling ins.Tick additionally records the root status when root is a bare custom Node not wrapped in Named.
func (ins *BTInspector) Walk() []BTNodeTraceWalk returns a newly allocated pre-order snapshot of every node in the tree. For zero-allocation per-tick inspection, reuse a buffer with WalkInto.
func (ins *BTInspector) WalkInto(dst []BTNodeTrace) []BTNodeTraceWalkInto writes a pre-order snapshot of every node in the tree into dst[:0] and returns the populated slice. Once cap(dst) >= ins.Len(), WalkInto performs zero heap allocations.
type BTNodeContext struct {
// Blackboard is the agent's blackboard bound to this behavior tree instance.
Blackboard *Blackboard
// Stream is the optional deterministic random stream passed in BTBindings.
Stream *random.Stream
// Params holds the node's resolved parameters after any subtree "${param}" substitutions.
Params BTParams
// KeyBindings maps subtree-local blackboard key names to caller blackboard key names.
KeyBindings map[string]string
}BTNodeContext supplies runtime dependencies and resolved parameter and key bindings to game-registered action, condition, and service factories.
func (c BTNodeContext) Key(name string) stringKey resolves a blackboard key name through any enclosing subtree key bindings, returning name unchanged when no remapping applies.
type BTNodeDoc struct {
// Type selects the behavior tree node kind.
Type BTNodeType `yaml:"type" schema:"required,enum=sequence|selector|parallel|random_selector|random_sequence|weighted_selector|guard|cooldown|time_limit|retry|service|inverter|succeeder|failer|repeater|until_fail|blackboard_condition|wait|action|condition|subtree"`
// Name is an optional label for authoring and debugging.
Name string `yaml:"name,omitempty"`
// Weight is the positive relative selection weight when this node is a direct child of weighted_selector.
Weight float64 `yaml:"weight,omitempty" schema:"exclusiveMinimum=0"`
// Policy selects the completion policy for parallel nodes: require_all (default) or require_one.
Policy BTParallelPolicyName `yaml:"policy,omitempty" schema:"enum=require_all|require_one"`
// Action names the game-registered action factory for action leaf nodes.
Action string `yaml:"action,omitempty"`
// Condition names the game-registered condition factory for condition leaves and guard decorators.
Condition string `yaml:"condition,omitempty"`
// Service names the game-registered service factory for service decorators.
Service string `yaml:"service,omitempty"`
// Duration is a Go duration string (such as "500ms" or "1.5s") or "${param}" reference for wait, cooldown, and time_limit nodes.
Duration string `yaml:"duration,omitempty"`
// Interval is a Go duration string or "${param}" reference controlling periodic ticks of a service decorator (omitted or "0s" runs every tick).
Interval string `yaml:"interval,omitempty"`
// Count is the iteration or retry count for repeater (0 repeats indefinitely) and retry (0 disables retries) decorators.
Count int `yaml:"count,omitempty" schema:"minimum=0"`
// Key is the blackboard key inspected by a blackboard_condition node.
Key string `yaml:"key,omitempty"`
// Op is the comparison operator for a blackboard_condition node: eq, ne, lt, lte, gt, gte, set, or unset.
Op BlackboardOp `yaml:"op,omitempty" schema:"enum=eq|ne|lt|lte|gt|gte|set|unset"`
// Value is the comparison operand for a blackboard_condition node (required for eq, ne, lt, lte, gt, gte; omitted for set and unset).
Value *any `yaml:"value,omitempty"`
// ValueType optionally specifies the blackboard type of Value (bool, int, float, string, vec2, vec3, or entity) when disambiguation is needed.
ValueType BlackboardKindName `yaml:"valueType,omitempty" schema:"enum=bool|int|float|string|vec2|vec3|entity"`
// Abort controls observer abort behavior for a blackboard_condition node: none (default), self, lower, or both.
Abort AbortMode `yaml:"abort,omitempty" schema:"enum=none|self|lower|both"`
// Path is the relative or filesystem path to another *.bt.yaml file for a subtree node.
Path string `yaml:"path,omitempty"`
// Params supplies typed parameters to action, condition, guard, service, or subtree nodes.
Params map[string]any `yaml:"params,omitempty"`
// Keys maps subtree-local blackboard key names to caller blackboard key names for a subtree node.
Keys map[string]string `yaml:"keys,omitempty"`
// Child is the wrapped child node for decorator nodes (optional on blackboard_condition).
Child *BTNodeDoc `yaml:"child,omitempty"`
// Children are the ordered child nodes for composite nodes.
Children []BTNodeDoc `yaml:"children,omitempty"`
}BTNodeDoc describes one composite, decorator, leaf, or subtree reference node in a BehaviorTreeDoc.
type BTNodeSnapshot struct {
// Path is the deterministic structural path from the root ("0", "0/0", "0/1/2", ...).
Path string `json:"path" yaml:"path"`
// Kind identifies the node type (such as "sequence", "wait", or "custom:patrol").
Kind string `json:"kind" yaml:"kind"`
// Policy records the completion policy for parallel nodes ("require_all" or "require_one").
Policy BTParallelPolicyName `json:"policy,omitempty" yaml:"policy,omitempty"`
// Active reports whether a parallel, random_selector, random_sequence, weighted_selector,
// or service node is currently mid-run.
Active bool `json:"active,omitempty" yaml:"active,omitempty"`
// Running reports whether a cooldown, guard, blackboard_condition, or attack_token
// decorator currently has a running child.
Running bool `json:"running,omitempty" yaml:"running,omitempty"`
// Index is the current child index for sequence, random_selector, and random_sequence nodes.
Index int `json:"index,omitempty" yaml:"index,omitempty"`
// RunningChild is the currently running child index for selector, weighted_selector,
// and utility_selector nodes (nil when no child is running).
RunningChild *int `json:"runningChild,omitempty" yaml:"runningChild,omitempty"`
// ActiveChild is the currently selected child index for utility_selector nodes
// (nil when no action is active).
ActiveChild *int `json:"activeChild,omitempty" yaml:"activeChild,omitempty"`
// ChildStatuses holds per-child statuses for an active parallel node.
ChildStatuses []Status `json:"childStatuses,omitempty" yaml:"childStatuses,omitempty"`
// Order holds the active shuffled child permutation for random_selector and random_sequence nodes.
Order []int `json:"order,omitempty" yaml:"order,omitempty"`
// RemainingOptions marks which options remain untried in an active weighted_selector node.
RemainingOptions []bool `json:"remainingOptions,omitempty" yaml:"remainingOptions,omitempty"`
// Done is the number of completed iterations in a repeater node.
Done int `json:"done,omitempty" yaml:"done,omitempty"`
// Failures is the number of failed attempts recorded in a retry node.
Failures int `json:"failures,omitempty" yaml:"failures,omitempty"`
// Elapsed is the accumulated time in a wait or time_limit node.
Elapsed time.Duration `json:"elapsed,omitempty" yaml:"elapsed,omitempty"`
// Remaining is the cooldown time left in a cooldown node.
Remaining time.Duration `json:"remaining,omitempty" yaml:"remaining,omitempty"`
// Phase is the periodic phase accumulator in an active service node.
Phase time.Duration `json:"phase,omitempty" yaml:"phase,omitempty"`
// SinceLast is the elapsed time since the last callback in an active service node.
SinceLast time.Duration `json:"sinceLast,omitempty" yaml:"sinceLast,omitempty"`
// SeenRev reports whether a blackboard_condition node has observed a key revision.
SeenRev bool `json:"seenRev,omitempty" yaml:"seenRev,omitempty"`
// LastRev is the last blackboard key revision observed by a blackboard_condition node.
LastRev uint64 `json:"lastRev,omitempty" yaml:"lastRev,omitempty"`
// LastResult is the cached condition result from the last revision check of a blackboard_condition node.
LastResult bool `json:"lastResult,omitempty" yaml:"lastResult,omitempty"`
// State holds custom serializable state returned by a [SnapshotNode].
State any `json:"state,omitempty" yaml:"state,omitempty"`
}BTNodeSnapshot records one node's structural path, kind, and mutable runtime state inside a BehaviorTreeSnapshot.
type BTNodeTrace struct {
// Path is the deterministic structural path from the root ("root", "root/0", "root/0/1", ...).
Path string
// Depth is the node's nesting depth in the tree (0 for the root).
Depth int
// Name is the optional label assigned via Named or YAML's name field.
Name string
// Kind is the node's kind ("selector", "sequence", "action", "wait", ..., or "custom").
Kind string
// LastStatus is the Status returned by this node's most recent Tick since build or Reset.
// Only meaningful when Ticked is true.
LastStatus Status
// Ticked reports whether this node has been ticked since construction or its most recent Reset.
Ticked bool
// Active reports whether this node lies on the tree's currently running path.
Active bool
}BTNodeTrace is a read-only snapshot of one node in a behavior tree.
func InspectBehaviorTree(root Node) []BTNodeTraceInspectBehaviorTree performs a one-shot read-only walk of root and returns each node's trace in pre-order. For repeated per-tick inspection without allocations, construct a BTInspector with NewBTInspector and call WalkInto.
func RunningPathInto(dst []BTNodeTrace, nodes []BTNodeTrace) []BTNodeTraceRunningPathInto appends every node in nodes that lies on the currently running path (Active == true) into dst[:0], performing zero allocations when cap(dst) is sufficient.
func (t BTNodeTrace) StatusString() stringStatusString returns "Idle" when t has not been ticked since construction or Reset, and t.LastStatus.String() otherwise.
type BTNodeType stringBTNodeType identifies the kind of node in a BehaviorTreeDoc.
const (
// BTNodeSequence runs children in order until all succeed or one fails.
BTNodeSequence BTNodeType = "sequence"
// BTNodeSelector tries children in priority order until one succeeds or runs.
BTNodeSelector BTNodeType = "selector"
// BTNodeParallel ticks all running children each step according to Policy.
BTNodeParallel BTNodeType = "parallel"
// BTNodeRandomSelector tries children in a deterministic shuffled order from Stream.
BTNodeRandomSelector BTNodeType = "random_selector"
// BTNodeRandomSequence runs all children in a deterministic shuffled order from Stream.
BTNodeRandomSequence BTNodeType = "random_sequence"
// BTNodeWeightedSelector draws children without replacement by each child's Weight.
BTNodeWeightedSelector BTNodeType = "weighted_selector"
// BTNodeGuard ticks its child only while a registered condition holds, resetting child if it turns false.
BTNodeGuard BTNodeType = "guard"
// BTNodeCooldown blocks re-entry into its child for Duration after success.
BTNodeCooldown BTNodeType = "cooldown"
// BTNodeTimeLimit fails and resets its child if it stays running past Duration.
BTNodeTimeLimit BTNodeType = "time_limit"
// BTNodeRetry reruns a failing child up to Count additional times.
BTNodeRetry BTNodeType = "retry"
// BTNodeService invokes a registered callback on entry and periodically every Interval while its child runs.
BTNodeService BTNodeType = "service"
// BTNodeInverter flips StatusSuccess and StatusFailure from its child.
BTNodeInverter BTNodeType = "inverter"
// BTNodeSucceeder turns both StatusSuccess and StatusFailure from its child into StatusSuccess.
BTNodeSucceeder BTNodeType = "succeeder"
// BTNodeFailer turns both StatusSuccess and StatusFailure from its child into StatusFailure.
BTNodeFailer BTNodeType = "failer"
// BTNodeRepeater repeats its child Count times (or indefinitely when Count is 0).
BTNodeRepeater BTNodeType = "repeater"
// BTNodeUntilFail repeats its child until it returns StatusFailure, then succeeds.
BTNodeUntilFail BTNodeType = "until_fail"
// BTNodeBlackboardCondition checks a blackboard key with optional observer aborts and optional wrapped child.
BTNodeBlackboardCondition BTNodeType = "blackboard_condition"
// BTNodeWait returns StatusRunning until accumulated dt reaches Duration, then succeeds.
BTNodeWait BTNodeType = "wait"
// BTNodeAction invokes a game-registered leaf action factory.
BTNodeAction BTNodeType = "action"
// BTNodeCondition invokes a game-registered leaf condition factory.
BTNodeCondition BTNodeType = "condition"
// BTNodeSubtree includes another *.bt.yaml file by Path with optional Params and Keys bindings.
BTNodeSubtree BTNodeType = "subtree"
)type BTParallelPolicyName stringBTParallelPolicyName names the completion policy of a parallel node in YAML.
const (
// BTParallelRequireAll succeeds when all children succeed and fails as soon as any child fails.
BTParallelRequireAll BTParallelPolicyName = "require_all"
// BTParallelRequireOne succeeds as soon as any child succeeds and fails when every child fails.
BTParallelRequireOne BTParallelPolicyName = "require_one"
)type BTParams map[string]anyBTParams holds resolved typed parameters passed to a leaf or service factory.
func (p BTParams) Bool(name string) (bool, bool)Bool returns the bool parameter name, or (false, false) if absent or not a bool.
func (p BTParams) Duration(name string) (time.Duration, bool)Duration parses a Go duration string parameter name, returning (0, false) if absent or invalid.
func (p BTParams) Entity(name string) (uint64, bool)Entity returns a non-negative integer parameter as a uint64 entity ID.
func (p BTParams) Float(name string) (float64, bool)Float returns the numeric parameter name as float64, accepting int or float values.
func (p BTParams) Int(name string) (int, bool)Int returns the integer parameter name, or (0, false) if absent or not an integer.
func (p BTParams) Point(name string) (core.Point, bool)Point returns a 2-element numeric array parameter as a core.Point.
func (p BTParams) String(name string) (string, bool)String returns the string parameter name, or ("", false) if absent or not a string.
func (p BTParams) Vec2(name string) (math2d.Vec2, bool)Vec2 returns a 2-element numeric array parameter as a math2d.Vec2.
func (p BTParams) Vec3(name string) (Vec3, bool)Vec3 returns a 3-element numeric array parameter as an ai.Vec3.
type BehaviorTree struct {
// contains filtered or unexported fields
}BehaviorTree wraps a root Node and provides BehaviorTree.Snapshot and BehaviorTree.Restore methods alongside Node.Tick and Node.Reset.
func NewBehaviorTree(root Node) *BehaviorTreeNewBehaviorTree wraps root in a BehaviorTree.
func (bt *BehaviorTree) Reset()Reset clears any in-progress state on the root node and its descendants.
func (bt *BehaviorTree) Restore(snap BehaviorTreeSnapshot) errorRestore validates snap against bt's structure and applies it atomically without mutating any node on error.
func (bt *BehaviorTree) Root() NodeRoot returns the tree's root Node, or nil if bt is nil.
func (bt *BehaviorTree) Snapshot() (BehaviorTreeSnapshot, error)Snapshot captures bt's structural shape and mutable runtime state.
func (bt *BehaviorTree) Tick(dt time.Duration) StatusTick advances the root node by dt, returning StatusFailure when bt or its root is nil.
type BehaviorTreeDoc struct {
// Version is the schema version; must equal BTFormatVersion (1).
Version int `yaml:"version" schema:"required"`
// Name is an optional human-readable identifier for this behavior tree.
Name string `yaml:"name,omitempty"`
// Params declares optional default parameter values substituted for "${name}" references in this tree.
Params map[string]any `yaml:"params,omitempty"`
// Blackboard declares typed blackboard keys and optional initial defaults used by this tree.
Blackboard []BTBlackboardKeyDoc `yaml:"blackboard,omitempty"`
// Root is the root node of the behavior tree.
Root BTNodeDoc `yaml:"root" schema:"required"`
// contains filtered or unexported fields
}BehaviorTreeDoc is the root of a versioned YAML behavior tree document (*.bt.yaml).
func LoadBehaviorTreeFS(fsys fs.FS, name string) (*BehaviorTreeDoc, error)LoadBehaviorTreeFS reads, parses, and validates the behavior tree at name in fsys, including checking all transitively referenced subtrees for parse errors and cycles.
func ParseBehaviorTree(data []byte) (*BehaviorTreeDoc, error)ParseBehaviorTree decodes and validates a version 1 YAML behavior tree document. Unknown fields, unknown node types, invalid operators or abort modes, unsupported versions, and trailing YAML documents are refused with a *loaderr.Error.
func ParseBehaviorTreeWith(data []byte, file string) (*BehaviorTreeDoc, error)ParseBehaviorTreeWith is ParseBehaviorTree with a source file name attached to returned errors and checked for direct self-referencing subtree cycles.
type BehaviorTreeSnapshot struct {
// Version is BTSnapshotVersion.
Version int `json:"version" yaml:"version"`
// Nodes lists every node in deterministic pre-order traversal, pairing its
// structural path (such as "0/1/2") and node kind with any active runtime state.
Nodes []BTNodeSnapshot `json:"nodes" yaml:"nodes"`
}BehaviorTreeSnapshot holds the structural shape and mutable runtime state of a behavior tree as plain data that marshals deterministically to YAML and JSON.
func SnapshotBehaviorTree(root Node) (BehaviorTreeSnapshot, error)SnapshotBehaviorTree captures the structural shape and mutable runtime state of the behavior tree rooted at root. The returned snapshot contains only plain data suitable for deterministic YAML and JSON encoding and shares no mutable slices with root.
type Blackboard struct {
// contains filtered or unexported fields
}Blackboard is a typed per-agent key-value store with optional parent scoping (for a squad or team), monotonic revision tracking, and synchronous change notifications.
Reads check local entries first and fall back to Parent when unset locally. Writes via Set* target the local blackboard; SetShared* writes to Parent when present (or locally if Parent is nil). Blackboard is designed for deterministic single-threaded stepping on game.Loop and is not safe for concurrent use.
func NewBlackboard() *BlackboardNewBlackboard creates an empty standalone Blackboard.
func NewChildBlackboard(parent *Blackboard) *BlackboardNewChildBlackboard creates a Blackboard scoped to an agent that falls back to parent for reads not shadowed locally.
func (b *Blackboard) Bool(key string) (bool, bool)Bool returns the bool stored under key, or (false, false) if unset or of another type.
func (b *Blackboard) Clear()Clear removes all local entries from b in deterministic sorted key order, notifying watchers for each key whose effective value changes.
func (b *Blackboard) Delete(key string)Delete removes key from b's local scope, exposing any value stored in Parent.
func (b *Blackboard) DeleteShared(key string)DeleteShared deletes key from b.Parent() when non-nil, or locally from b when b has no parent.
func (b *Blackboard) Entity(key string) (uint64, bool)Entity returns the uint64 entity ID stored under key, or (0, false) if unset or of another type.
func (b *Blackboard) Float(key string) (float64, bool)Float returns the float64 stored under key, or (0, false) if unset or of another type.
func (b *Blackboard) Get(key string) (BlackboardValue, bool)Get returns the effective value for key, falling back to Parent when unset locally.
func (b *Blackboard) GetLocal(key string) (BlackboardValue, bool)GetLocal returns the value stored directly on b without consulting Parent.
func (b *Blackboard) Has(key string) boolHas reports whether key is set on b or any ancestor blackboard.
func (b *Blackboard) HasLocal(key string) boolHasLocal reports whether key is set directly on b.
func (b *Blackboard) Int(key string) (int, bool)Int returns the int stored under key, or (0, false) if unset or of another type.
func (b *Blackboard) KeyRevision(key string) uint64KeyRevision returns a monotonically increasing mutation counter for key across b and any ancestor blackboards. It allocates zero bytes.
func (b *Blackboard) Keys(dst []string) []stringKeys appends all visible keys on b and its ancestors to dst[:0] in deterministic ascending order without duplicates.
func (b *Blackboard) Kind(key string) BlackboardKindKind returns the BlackboardKind of key, or BlackboardNone when unset.
func (b *Blackboard) LocalKeys(dst []string) []stringLocalKeys appends all keys stored directly on b to dst[:0] in deterministic ascending order.
func (b *Blackboard) Parent() *BlackboardParent returns b's shared parent blackboard, or nil when b has no parent.
func (b *Blackboard) Point(key string) (core.Point, bool)Point returns the 2D vector stored under key as a core.Point, or (zero, false) if unset or of another type.
func (b *Blackboard) Revision() uint64Revision returns a monotonically increasing mutation counter covering b and any ancestor blackboards.
func (b *Blackboard) Set(key string, val BlackboardValue)Set stores val under key on b's local scope. Setting a zero (BlackboardNone) value deletes the local key.
func (b *Blackboard) SetBool(key string, v bool)SetBool stores a bool under key on b.
func (b *Blackboard) SetEntity(key string, id uint64)SetEntity stores an entity ID under key on b.
func (b *Blackboard) SetFloat(key string, v float64)SetFloat stores a float64 under key on b.
func (b *Blackboard) SetInt(key string, v int)SetInt stores an int under key on b.
func (b *Blackboard) SetPoint(key string, p core.Point)SetPoint stores a core.Point as a 2D vector under key on b.
func (b *Blackboard) SetShared(key string, val BlackboardValue)SetShared stores val under key on b.Parent() when non-nil, or locally on b when b has no parent.
func (b *Blackboard) SetSharedBool(key string, v bool)SetSharedBool stores a bool on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetSharedEntity(key string, id uint64)SetSharedEntity stores an entity ID on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetSharedFloat(key string, v float64)SetSharedFloat stores a float64 on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetSharedInt(key string, v int)SetSharedInt stores an int on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetSharedPoint(key string, p core.Point)SetSharedPoint stores a core.Point as a 2D vector on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetSharedString(key string, v string)SetSharedString stores a string on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetSharedVec2(key string, v math2d.Vec2)SetSharedVec2 stores a 2D vector on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetSharedVec3(key string, v Vec3)SetSharedVec3 stores a 3D vector on the shared parent blackboard (or b if standalone).
func (b *Blackboard) SetString(key string, v string)SetString stores a string under key on b.
func (b *Blackboard) SetVec2(key string, v math2d.Vec2)SetVec2 stores a 2D vector under key on b.
func (b *Blackboard) SetVec3(key string, v Vec3)SetVec3 stores a 3D vector under key on b.
func (b *Blackboard) String(key string) (string, bool)String returns the string stored under key, or ("", false) if unset or of another type.
func (b *Blackboard) Vec2(key string) (math2d.Vec2, bool)Vec2 returns the 2D vector stored under key, or (zero, false) if unset or of another type.
func (b *Blackboard) Vec3(key string) (Vec3, bool)Vec3 returns the 3D vector stored under key, or (zero, false) if unset or of another type.
func (b *Blackboard) Watch(key string, fn BlackboardListener) (cancel func())Watch registers fn to be called synchronously whenever key changes on b or on an ancestor blackboard (unless shadowed locally). Pass an empty key "" to watch all keys. The returned cancel function unregisters the watcher cleanly.
type BlackboardChange struct {
// Key is the modified blackboard key.
Key string
// Old is the effective value before the mutation (BlackboardNone if previously unset).
Old BlackboardValue
// New is the effective value after the mutation (BlackboardNone if removed).
New BlackboardValue
// Board is the Blackboard where the mutation occurred (which may be a shared parent).
Board *Blackboard
}BlackboardChange describes a single key mutation observed by a BlackboardListener.
type BlackboardKind uint8BlackboardKind identifies the stored value type of a Blackboard entry.
const (
// BlackboardNone represents an unset or absent blackboard key.
BlackboardNone BlackboardKind = iota
// BlackboardBool stores a bool.
BlackboardBool
// BlackboardInt stores an int.
BlackboardInt
// BlackboardFloat stores a float64.
BlackboardFloat
// BlackboardString stores a string.
BlackboardString
// BlackboardVec2 stores a 2D float32 vector (math2d.Vec2 / core.Point).
BlackboardVec2
// BlackboardVec3 stores a 3D float32 vector (ai.Vec3).
BlackboardVec3
// BlackboardEntity stores a uint64 entity identifier.
BlackboardEntity
)func (k BlackboardKind) String() stringString returns the canonical YAML name for k.
type BlackboardKindName stringBlackboardKindName is the string representation of a BlackboardKind in YAML documents.
const (
// BBTypeBool is the YAML type name for bool blackboard keys.
BBTypeBool BlackboardKindName = "bool"
// BBTypeInt is the YAML type name for int blackboard keys.
BBTypeInt BlackboardKindName = "int"
// BBTypeFloat is the YAML type name for float64 blackboard keys.
BBTypeFloat BlackboardKindName = "float"
// BBTypeString is the YAML type name for string blackboard keys.
BBTypeString BlackboardKindName = "string"
// BBTypeVec2 is the YAML type name for 2D vector blackboard keys.
BBTypeVec2 BlackboardKindName = "vec2"
// BBTypeVec3 is the YAML type name for 3D vector blackboard keys.
BBTypeVec3 BlackboardKindName = "vec3"
// BBTypeEntity is the YAML type name for uint64 entity ID blackboard keys.
BBTypeEntity BlackboardKindName = "entity"
)func (n BlackboardKindName) Kind() (BlackboardKind, bool)Kind converts a YAML BlackboardKindName into a BlackboardKind.
type BlackboardListener func(change BlackboardChange)BlackboardListener is invoked synchronously when a watched blackboard key changes.
type BlackboardOp stringBlackboardOp identifies a comparison operator evaluated by BlackboardCondition.
const (
// BBOpEq holds when the blackboard key is set and equals the comparison value.
BBOpEq BlackboardOp = "eq"
// BBOpNe holds when the blackboard key is unset or differs from the comparison value.
BBOpNe BlackboardOp = "ne"
// BBOpLt holds when the blackboard key is set and strictly less than the comparison value.
BBOpLt BlackboardOp = "lt"
// BBOpLte holds when the blackboard key is set and less than or equal to the comparison value.
BBOpLte BlackboardOp = "lte"
// BBOpGt holds when the blackboard key is set and strictly greater than the comparison value.
BBOpGt BlackboardOp = "gt"
// BBOpGte holds when the blackboard key is set and greater than or equal to the comparison value.
BBOpGte BlackboardOp = "gte"
// BBOpSet holds when the blackboard key is present.
BBOpSet BlackboardOp = "set"
// BBOpUnset holds when the blackboard key is absent.
BBOpUnset BlackboardOp = "unset"
)func (op BlackboardOp) NeedsValue() boolNeedsValue reports whether op compares against an explicit operand value.
func (op BlackboardOp) Valid() boolValid reports whether op is a known BlackboardOp.
type BlackboardValue struct {
Kind BlackboardKind
Bool bool
Int int
Float float64
String string
Vec2 math2d.Vec2
Vec3 Vec3
Entity uint64
}BlackboardValue is a typed tagged union stored in a Blackboard without interface boxing.
func BBEntity(id uint64) BlackboardValueBBEntity returns a BlackboardValue holding entity identifier id.
func BBFloat(v float64) BlackboardValueBBFloat returns a BlackboardValue holding v.
func BBPoint(p core.Point) BlackboardValueBBPoint returns a BlackboardValue holding p as a 2D vector.
func BBString(v string) BlackboardValueBBString returns a BlackboardValue holding v.
func BBVec2(v math2d.Vec2) BlackboardValueBBVec2 returns a BlackboardValue holding v.
func (v BlackboardValue) Equal(o BlackboardValue) boolEqual reports whether v and o have the same kind and identical stored value.
func (v BlackboardValue) IsZero() boolIsZero reports whether v represents an unset value (BlackboardNone).
type BoolFact uint8BoolFact identifies a boolean fact slot (0..MaxBoolFacts-1) in a FactSchema and WorldState.
type BoolGrid struct {
// contains filtered or unexported fields
}BoolGrid is a Grid backed by a flat boolean slice. All cells start walkable.
func NewBoolGrid(cols, rows int) *BoolGridNewBoolGrid returns a cols-by-rows grid with every cell walkable.
func (g *BoolGrid) GridSize() (cols, rows int)GridSize returns the grid's columns and rows.
func (g *BoolGrid) SetWalkable(col, row int, walkable bool)SetWalkable marks (col, row) as walkable or blocked. Out-of-bounds coordinates are ignored.
func (g *BoolGrid) Walkable(col, row int) boolWalkable reports whether (col, row) is in bounds and unblocked.
type CandidateGenerator interface {
Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidate
}CandidateGenerator appends deterministic candidate positions to dst and returns the extended slice.
type ChildNodes interface {
Node
Children() []Node
}ChildNodes is an optional interface that custom composite or decorator Node implementations may implement so SnapshotBehaviorTree and RestoreBehaviorTree traverse and preserve the state of their child nodes.
type ClusterID struct {
Col, Row int
}ClusterID identifies a cluster in an HPA grid by its cluster column and row.
type ClusterRect struct {
ID ClusterID
MinCol int
MinRow int
MaxCol int
MaxRow int
}ClusterRect describes the inclusive-exclusive cell bounds [MinCol, MaxCol) x [MinRow, MaxRow) of an HPA cluster.
type ColliderCoverOptions struct {
// Spacing is the distance between cover points along an obstacle edge (defaults to 32 when <= 0).
Spacing float32
// Standoff offsets each cover point away from the obstacle edge into open space (defaults to 8 when <= 0).
Standoff float32
// EdgeInset is the margin from each edge corner (defaults to Spacing * 0.5 when <= 0).
EdgeInset float32
// MinEdgeLength skips obstacle edges shorter than this length (values <= 0 allow any positive edge).
MinEdgeLength float32
// DefaultHeight sets the cover height when not overridden (defaults to CoverFull).
DefaultHeight CoverHeight
// HeightForBody optionally classifies cover height for each body in GenerateCoverFromWorld.
HeightForBody func(*physics.Body) CoverHeight
// LayerMask filters bodies inspected by GenerateCoverFromWorld (0 defaults to physics.LayerAll).
LayerMask physics.LayerMask
// SkipTiles omits World.Tiles when generating from a physics.World.
SkipTiles bool
// StartID is the first CoverPoint.ID assigned (defaults to 1 when 0).
StartID uint64
}ColliderCoverOptions configures cover-point generation from 2D physics boxes, segments, or a physics.World.
type Conditions struct {
// contains filtered or unexported fields
}Conditions specifies required boolean fact values and optional closed integer bounds [lo, hi]. The zero Conditions matches every WorldState.
Canonical invariant: bits outside boolMask are always 0 in boolVals, and intRange[i] is zero whenever bit i of intMask is 0.
func (c Conditions) Empty() boolEmpty reports whether c imposes no boolean or integer constraints.
func (c Conditions) RequireBool(f BoolFact, v bool) ConditionsRequireBool returns a copy of c requiring boolean fact f to equal v.
func (c Conditions) RequireIntEq(f IntFact, v int) ConditionsRequireIntEq returns a copy of c requiring integer fact f == v.
func (c Conditions) RequireIntGt(f IntFact, v int) ConditionsRequireIntGt returns a copy of c requiring integer fact f > v.
func (c Conditions) RequireIntGte(f IntFact, v int) ConditionsRequireIntGte returns a copy of c requiring integer fact f >= v.
func (c Conditions) RequireIntLt(f IntFact, v int) ConditionsRequireIntLt returns a copy of c requiring integer fact f < v.
func (c Conditions) RequireIntLte(f IntFact, v int) ConditionsRequireIntLte returns a copy of c requiring integer fact f <= v.
func (c Conditions) RequireIntRange(f IntFact, lo, hi int) ConditionsRequireIntRange returns a copy of c requiring integer fact f to lie in [lo, hi] inclusive. If f is already constrained in c, the bounds are intersected; an empty intersection (lo > hi) makes c unsatisfiable.
func (c Conditions) SatisfiedBy(w WorldState) boolSatisfiedBy reports whether w satisfies every constraint in c.
type Consideration[C any] struct {
// Name is an optional human-readable label.
Name string
// Input extracts the numeric value from context C. A nil Input evaluates to 0.
Input func(C) float64
// Min and Max optionally define the input range normalized into [0, 1].
Min float64
Max float64
// Curve maps the normalized [0, 1] input to a utility score in [0, 1].
Curve ResponseCurve
}Consideration turns one input reading from context C into a score in [0, 1] through Curve.
When Max > Min, the raw input is linearly mapped from [Min, Max] into [0, 1] and clamped before applying Curve. Otherwise the input is clamped to [0, 1] directly.
func (c Consideration[C]) Eval(ctx C) float64Eval reads Input(ctx), normalizes it to [0, 1], and evaluates Curve.
type ConsiderationDef struct {
// Name is an optional label for this consideration.
Name string `yaml:"name,omitempty"`
// Input names the input function bound through UtilityBindings.Inputs.
Input string `yaml:"input"`
// Min and Max optionally define the input range normalized into [0, 1]. When both are 0, the input is clamped directly to [0, 1].
Min float64 `yaml:"min,omitempty"`
Max float64 `yaml:"max,omitempty"`
// Curve defines the response curve applied to the normalized input.
Curve CurveDef `yaml:"curve"`
}ConsiderationDef defines one consideration in a UtilityConfig file.
type CostGrid interface {
Grid
MoveCost(col, row int) float64
}CostGrid is a Grid whose walkable cells carry individual traversal costs.
MoveCost returns the cost multiplier for entering (col, row), at least 1 so the distance heuristic remains admissible; values less than or equal to 0 are treated as 1.
type CostMap struct {
// contains filtered or unexported fields
}CostMap is a CostGrid backed by a flat cost slice. All cells start walkable with cost 1.
func NewCostMap(cols, rows int) *CostMapNewCostMap returns a cols-by-rows CostMap with every cell walkable at cost 1.
func (m *CostMap) GridSize() (cols, rows int)GridSize returns the map's columns and rows.
func (m *CostMap) MoveCost(col, row int) float64MoveCost returns the traversal cost of entering (col, row), or 1 if unset. Costs below 1 are clamped to 1 so a cheaper cell cannot make the distance heuristic overestimate and break A*'s optimality.
func (m *CostMap) SetCost(col, row int, cost float64)SetCost sets the traversal cost for (col, row). Negative, infinite or NaN costs mark the cell unwalkable; 0 or a cost below 1 restores the default cost of 1, as the distance heuristic assumes every step costs at least 1.
func (m *CostMap) SetWalkable(col, row int, walkable bool)SetWalkable marks (col, row) as walkable or blocked. Unblocking a cell restores its cost to 1.
func (m *CostMap) Walkable(col, row int) boolWalkable reports whether (col, row) is in bounds and not blocked.
type CoverHeight uint8CoverHeight classifies how much vertical protection a CoverPoint provides.
const (
// CoverHalf is crouch- or chest-high cover (agents crouch to hide and can fire or peek over it).
CoverHalf CoverHeight = iota + 1
// CoverFull is full-height cover (blocks line of sight while standing; agents peek around edges).
CoverFull
)func ParseCoverHeight(s string) (CoverHeight, bool)ParseCoverHeight parses "half" or "full" (case-insensitive, trimmed) into a CoverHeight.
func (h CoverHeight) String() stringString returns "half" for CoverHalf, "full" for CoverFull, or "none" for an unset value.
type CoverHeightTest struct {
// MinHeight filters out candidates with Height < MinHeight when Purpose allows filtering (0 disables).
MinHeight CoverHeight
// Prefer selects which CoverHeight earns a score of 1 (defaults to CoverFull when 0).
Prefer CoverHeight
// Purpose selects filtering, scoring, or both (defaults to TestFilterAndScore).
Purpose TestPurpose
// Weight scales the score contribution (1 when candidate.Height == Prefer, 0 otherwise).
Weight float64
}CoverHeightTest filters and/or scores candidates based on their CoverHeight.
type CoverPoint struct {
// ID uniquely identifies this cover point for reservations and deterministic tie-breaking.
// Generators assign sequential non-zero IDs starting from StartID (default 1).
ID uint64
// Pos is the world-space standing position where an agent takes cover (offset into open space).
Pos math2d.Vec2
// Facing is the unit vector pointing from Pos toward the obstacle that blocks incoming fire.
Facing math2d.Vec2
// Height indicates whether this cover is CoverHalf or CoverFull.
Height CoverHeight
// Elevation is the optional 3D vertical floor coordinate (0 for 2D cover points).
Elevation float32
// Tags holds optional user-defined labels such as "window", "flank", or "corner".
Tags []string
}CoverPoint is a tactical cover position beside an obstacle.
Facing is a unit vector pointing from Pos into the cover obstacle — the incoming threat direction that this cover blocks (the obstacle's outward surface normal is Facing.Neg()). Elevation stores the optional 3D floor height (0 in 2D worlds).
func GenerateCoverFromBoxes(boxes []physics.Box, opts ColliderCoverOptions) []CoverPointGenerateCoverFromBoxes generates deterministic cover points along the four exterior edges of each non-empty physics.Box, discarding any point that lands inside another box.
func GenerateCoverFromGrid(g Grid, origin math2d.Vec2, cellWidth, cellHeight float32, opts GridCoverOptions) []CoverPointGenerateCoverFromGrid generates deterministic cover points along exposed edges of blocked cells (!g.Walkable) on g, offset into adjacent walkable cells.
func GenerateCoverFromSegments(segments []CoverSegment, opts ColliderCoverOptions) []CoverPointGenerateCoverFromSegments samples deterministic cover points along straight obstacle segments.
func GenerateCoverFromTilemap(m *tilemap.Tilemap, opts TileCoverOptions) []CoverPointGenerateCoverFromTilemap generates deterministic cover points along exposed solid edges of m.
Contiguous solid edges sharing the same CoverHeight are merged before sampling, and generated positions are verified to lie in an open (non-solid) in-bounds cell.
func GenerateCoverFromWorld(w *physics.World, opts ColliderCoverOptions) []CoverPointGenerateCoverFromWorld generates deterministic cover points from all matching 2D physics bodies (boxes and circular pillars) and, unless opts.SkipTiles is true, solid tiles in w.Tiles. Candidate positions embedded inside any matching collider or solid tile are excluded.
func (c CoverPoint) HasTag(tag string) boolHasTag reports whether c carries tag.
type CoverPointGenerator struct {
// Points is the source list of cover points.
Points []CoverPoint
// Center selects the origin for MaxRadius filtering (defaults to OriginQuerier).
Center QueryOrigin
// CustomCenter is used when Center is OriginCustom.
CustomCenter math2d.Vec2
// MaxRadius restricts candidates to those within MaxRadius of Center (<= 0 includes all points).
MaxRadius float32
// MinHeight restricts candidates to cover points with Height >= MinHeight (0 allows any height).
MinHeight CoverHeight
// RequiredTag restricts candidates to cover points carrying this tag when non-empty.
RequiredTag string
}CoverPointGenerator emits candidates from a slice of CoverPoint values.
func (g *CoverPointGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidateGenerate appends matching cover points to dst in deterministic slice order.
type CoverSegment struct {
// A and B are the endpoints of the cover-providing obstacle edge in world coordinates.
A, B math2d.Vec2
// Facing is the unit vector pointing from the open side into the obstacle.
Facing math2d.Vec2
// Height is CoverHalf or CoverFull (defaults to ColliderCoverOptions.DefaultHeight when unset).
Height CoverHeight
// Elevation is the optional 3D floor coordinate preserved on generated cover points.
Elevation float32
// Tags are optional tags copied onto cover points generated from this segment.
Tags []string
}CoverSegment describes one straight obstacle edge from which cover points can be sampled.
type CurveDef struct {
// Kind selects the response curve: linear, polynomial, logistic, logit, step, or resource.
Kind CurveKind `yaml:"kind"`
// Slope scales the output (or defines high - low for step).
Slope float64 `yaml:"slope,omitempty"`
// Exponent sets the power for polynomial or steepness for logistic.
Exponent float64 `yaml:"exponent,omitempty"`
// ShiftX shifts the input (midpoint for logistic/logit or threshold for step).
ShiftX float64 `yaml:"shiftX,omitempty"`
// ShiftY offsets the output (or defines the low output for step).
ShiftY float64 `yaml:"shiftY,omitempty"`
// File names the resource curve file loaded via UtilityBindings.LoadCurve when Kind is CurveResource.
File string `yaml:"file,omitempty"`
}CurveDef defines a response curve in a UtilityConfig file.
type CurveEvaluator interface {
Eval(t float32) float32
}CurveEvaluator evaluates a curve at a normalized input t in [0, 1].
*resource.Curve satisfies CurveEvaluator directly through its Eval(float32) float32 method, allowing stable package game/ai to use resource curves without importing experimental package game/resource.
type CurveFunc func(t float64) float64CurveFunc adapts a Go function into a CurveEvaluator.
func (f CurveFunc) Eval(t float32) float32Eval calls f(float64(t)) and returns the result as float32, or 0 if f is nil.
type CurveKind stringCurveKind identifies the response curve function used by a Consideration.
const (
// CurveLinear computes y = Slope*(x - ShiftX) + ShiftY, clamped to [0, 1].
CurveLinear CurveKind = "linear"
// CurvePolynomial computes y = Slope*(x - ShiftX)^Exponent + ShiftY, clamped to [0, 1].
CurvePolynomial CurveKind = "polynomial"
// CurveLogistic computes y = Slope/(1 + exp(-Exponent*(x - ShiftX))) + ShiftY, clamped to [0, 1].
CurveLogistic CurveKind = "logistic"
// CurveLogit computes y = Slope*ln(u/(1 - u)) + ShiftY where u = x - ShiftX + 0.5, clamped to [0, 1].
CurveLogit CurveKind = "logit"
// CurveStep returns ShiftY when x < ShiftX and ShiftY + Slope when x >= ShiftX, clamped to [0, 1].
CurveStep CurveKind = "step"
// CurveResource delegates evaluation to a CurveEvaluator, such as a *resource.Curve loaded from a resource curve file.
CurveResource CurveKind = "resource"
)type CustomTest struct {
// Eval returns a raw numeric value and whether the candidate is valid.
Eval func(ctx TacticalContext, c TacticalCandidate) (value float64, ok bool)
// Purpose selects filtering, scoring, or both (defaults to TestFilterAndScore).
Purpose TestPurpose
// Filter optionally restricts acceptable raw values.
Filter FloatRange
// NormMin and NormMax optionally specify fixed normalization bounds.
NormMin, NormMax float64
// Weight scales the normalized [0, 1] score contribution.
Weight float64
// Invert flips the normalized score (1 - norm).
Invert bool
}CustomTest runs a user-supplied scoring/filtering callback on each surviving candidate.
type DistanceTest struct {
// To selects the reference position (defaults to OriginQuerier).
To QueryOrigin
// CustomPos is used when To is OriginCustom.
CustomPos math2d.Vec2
// Purpose selects filtering, scoring, or both (defaults to TestFilterAndScore).
Purpose TestPurpose
// Filter optionally restricts acceptable distances (e.g. Between(40, 200)).
Filter FloatRange
// NormMin and NormMax optionally specify fixed normalization bounds.
// When NormMax <= NormMin, values normalize dynamically across surviving candidates.
NormMin, NormMax float64
// Weight scales the normalized [0, 1] score contribution (0 contributes no score).
Weight float64
// Invert flips the normalized score (1 - norm) so shorter distances score higher.
Invert bool
}DistanceTest measures Euclidean distance from each candidate to a reference point.
type EdgeCostGrid interface {
Grid
EdgeCost(fromCol, fromRow, toCol, toRow int) float64
}EdgeCostGrid is a Grid whose traversal cost depends on both the source and destination cells (for example elevation steps, river crossings or zone-of-control penalties).
EdgeCost returns the step cost multiplier for moving from (fromCol, fromRow) into (toCol, toRow). Negative, NaN or infinite values forbid that transition. During AStar searches, positive costs below 1 are clamped to 1 so the distance heuristic stays admissible; MovementRange accepts any non-negative finite cost.
type Effects struct {
// contains filtered or unexported fields
}Effects describes the boolean and integer fact changes produced when an action completes.
func (e Effects) AddInt(f IntFact, delta int) EffectsAddInt returns a copy of e that adds delta to integer fact f. A zero delta clears any effect on f.
func (e Effects) Apply(w WorldState) WorldStateApply returns a copy of w with all boolean and integer effects in e applied.
func (e Effects) Empty() boolEmpty reports whether e makes no changes to any fact.
func (e Effects) SetBool(f BoolFact, v bool) EffectsSetBool returns a copy of e that sets boolean fact f to v.
func (e Effects) SetInt(f IntFact, v int) EffectsSetInt returns a copy of e that sets integer fact f to v (clamped to int16 range).
type EngagementRing struct {
// Radius is the distance from the target center to each slot on this ring.
Radius float32
// Slots is the number of evenly spaced slots around this ring.
Slots int
// AngleOffset rotates this ring's slots in radians (0 places slot 0 along +X).
AngleOffset float64
}EngagementRing configures one concentric ring of engagement slots around a target.
type EngagementSlot struct {
// Ring is the zero-based ring index (0 is the first/innermost configured ring).
Ring int
// Index is the zero-based slot index within Ring.
Index int
// FlatIndex is the zero-based slot index across all rings.
FlatIndex int
// Pos is the slot's world position around the target.
Pos core.Point
}EngagementSlot is a concrete world-space engagement position around a target.
type Event struct {
// Kind is what happened.
Kind EventKind
// Memory is the memory as the event left it; for EventForgotten it is the memory that was dropped.
Memory Memory
}Event reports a change to one memory during the last step.
type EventKind uint8EventKind is what happened to a memory during a step.
const (
// EventGained reports a stimulus sensed with no memory of it before.
EventGained EventKind = iota + 1
// EventUpdated reports a remembered stimulus sensed again with something new: seen again after being out of sight, seen moving, or heard.
EventUpdated
// EventLost reports a stimulus that was in sight and no longer is. Its memory stays until it is forgotten.
EventLost
// EventForgotten reports a memory dropped because nothing sensed it for ForgetAfter.
EventForgotten
)func (k EventKind) String() stringString returns the event kind's lower-case name.
type FactSchema struct {
// contains filtered or unexported fields
}FactSchema maps human-readable boolean and integer fact names to compact fixed-size slots in a WorldState.
func NewFactSchema() *FactSchemaNewFactSchema creates an empty FactSchema.
func (s *FactSchema) Bool(name string) (BoolFact, error)Bool registers (or returns the existing slot for) a named boolean fact.
func (s *FactSchema) BoolCount() intBoolCount returns the number of registered boolean facts.
func (s *FactSchema) BoolName(f BoolFact) stringBoolName returns the registered name for f, or "" if out of range.
func (s *FactSchema) Clone() *FactSchemaClone returns an independent copy of s.
func (s *FactSchema) Int(name string) (IntFact, error)Int registers (or returns the existing slot for) a named small integer fact.
func (s *FactSchema) IntCount() intIntCount returns the number of registered integer facts.
func (s *FactSchema) IntName(f IntFact) stringIntName returns the registered name for f, or "" if out of range.
func (s *FactSchema) LookupBool(name string) (BoolFact, bool)LookupBool returns the slot for a registered boolean fact.
func (s *FactSchema) LookupInt(name string) (IntFact, bool)LookupInt returns the slot for a registered integer fact.
func (s *FactSchema) MustBool(name string) BoolFactMustBool registers a named boolean fact like Bool and panics on error.
func (s *FactSchema) MustInt(name string) IntFactMustInt registers a named small integer fact like Int and panics on error.
type FalloffKind uint8FalloffKind selects how a stamped InfluenceSource attenuates with Euclidean cell distance from its center cell.
const (
// FalloffLinear decreases linearly from 1 at distance 0 to 0 at Radius: max(0, 1 - dist/Radius).
FalloffLinear FalloffKind = iota
// FalloffExponential decreases as exp(-FalloffRate * dist) for dist <= Radius (FalloffRate defaults to 1 when <= 0).
FalloffExponential
// FalloffCustom delegates to InfluenceSource.CustomFalloff(dist, radius).
FalloffCustom
)type FloatRange struct {
Min float64
Max float64
HasMin bool
HasMax bool
}FloatRange represents an optional inclusive [Min, Max] filter interval for continuous tactical tests.
func AtLeast(minVal float64) FloatRangeAtLeast returns a FloatRange requiring values >= minVal.
func AtMost(maxVal float64) FloatRangeAtMost returns a FloatRange requiring values <= maxVal.
func Between(minVal, maxVal float64) FloatRangeBetween returns a FloatRange requiring values in [minVal, maxVal].
func (r FloatRange) Contains(v float64) boolContains reports whether v satisfies the configured bounds. NaN always returns false.
type GOAPAction struct {
// Name uniquely identifies the action within a planner.
Name string
// Preconditions must hold before the action can execute.
Preconditions Conditions
// Effects are applied to the world state when the action completes.
Effects Effects
// Cost is the positive planning cost of this action; 0 defaults to 1.
Cost float64
// Check is an optional procedural precondition evaluated against the current WorldState.
// Returning false excludes the action from the current plan and invalidates an active plan step.
Check func(WorldState) bool
}GOAPAction is one planning operator in a GOAPPlanner.
type GOAPActionDef struct {
// Name uniquely identifies the action.
Name string `yaml:"name"`
// Cost is the positive planning cost of executing this action; 0 defaults to 1.
Cost float64 `yaml:"cost,omitempty"`
// Check optionally names a procedural precondition callback bound via GOAPBindings.Checks.
Check string `yaml:"check,omitempty"`
// Preconditions are the boolean and integer conditions required before the action can execute.
Preconditions GOAPConditionsDef `yaml:"preconditions,omitempty"`
// Effects are the boolean and integer changes produced when the action completes.
Effects GOAPEffectsDef `yaml:"effects,omitempty"`
}GOAPActionDef defines one GOAP action in a GOAPConfig file.
type GOAPBindings struct {
// Checks maps each GOAPActionDef.Check name to a procedural precondition callback.
Checks map[string]func(WorldState) bool
}GOAPBindings provides the optional procedural precondition callbacks referenced by GOAPActionDef.Check.
type GOAPBoolFactDef struct {
Fact string `yaml:"fact"`
Value bool `yaml:"value"`
}GOAPBoolFactDef binds a named boolean fact to a true/false value.
type GOAPCompareOp stringGOAPCompareOp identifies a comparison operator on an integer fact in a GOAP YAML file.
const (
// GOAPOpEq requires fact == value.
GOAPOpEq GOAPCompareOp = "eq"
// GOAPOpGte requires fact >= value.
GOAPOpGte GOAPCompareOp = "gte"
// GOAPOpLte requires fact <= value.
GOAPOpLte GOAPCompareOp = "lte"
// GOAPOpGt requires fact > value.
GOAPOpGt GOAPCompareOp = "gt"
// GOAPOpLt requires fact < value.
GOAPOpLt GOAPCompareOp = "lt"
)type GOAPConditionsDef struct {
Bools []GOAPBoolFactDef `yaml:"bools,omitempty"`
Ints []GOAPIntConditionDef `yaml:"ints,omitempty"`
}GOAPConditionsDef defines boolean and integer requirements in YAML.
type GOAPConfig struct {
// Version is the schema version; it must equal GOAPVersion (1).
Version int `yaml:"version"`
// NodeBudget overrides DefaultGOAPNodeBudget when greater than 0.
NodeBudget int `yaml:"nodeBudget,omitempty"`
// Facts declares the named boolean and small integer facts referenced by actions and goals.
Facts GOAPFactsDef `yaml:"facts"`
// Actions are the planning operators in fixed declaration order (used for deterministic tie-breaking).
Actions []GOAPActionDef `yaml:"actions"`
// Goals are optional prioritized target conditions compiled by BuildGOAP.
Goals []GOAPGoalDef `yaml:"goals,omitempty"`
}GOAPConfig is a versioned YAML definition of a GOAP fact schema, action set, and optional goals.
func ParseGOAP(data []byte) (*GOAPConfig, error)ParseGOAP decodes and validates a GOAP YAML document. Unknown fields, missing or unsupported versions, duplicate keys, unknown fact references, and trailing YAML documents are refused.
func (cfg *GOAPConfig) Validate() errorValidate checks that cfg has version GOAPVersion, valid facts, unique actions and goals, valid operators/ranges, and no undefined fact references.
type GOAPEffectsDef struct {
Bools []GOAPBoolFactDef `yaml:"bools,omitempty"`
Ints []GOAPIntEffectDef `yaml:"ints,omitempty"`
}GOAPEffectsDef defines boolean and integer effects in YAML.
type GOAPFactsDef struct {
Bools []string `yaml:"bools,omitempty"`
Ints []string `yaml:"ints,omitempty"`
}GOAPFactsDef declares the named boolean and integer facts in a GOAPConfig file.
type GOAPGoal struct {
// Name identifies the goal.
Name string
// Priority ranks competing goals; higher priority is attempted first, with ties broken in declaration order.
Priority float64
// Target is the world condition the planner tries to satisfy.
Target Conditions
}GOAPGoal is a desired world condition with a planning priority.
type GOAPGoalDef struct {
// Name uniquely identifies the goal.
Name string `yaml:"name"`
// Priority ranks competing goals (higher is attempted first; ties break in declaration order).
Priority float64 `yaml:"priority,omitempty"`
// Target specifies the desired world state for this goal.
Target GOAPConditionsDef `yaml:"target"`
}GOAPGoalDef defines one prioritized goal in a GOAPConfig file.
type GOAPIntConditionDef struct {
Fact string `yaml:"fact"`
Op GOAPCompareOp `yaml:"op"`
Value int `yaml:"value"`
}GOAPIntConditionDef compares a named integer fact against Value using Op.
type GOAPIntEffectDef struct {
Fact string `yaml:"fact"`
Op GOAPIntEffectOp `yaml:"op"`
Value int `yaml:"value"`
}GOAPIntEffectDef modifies a named integer fact with Op (set or add) and Value.
type GOAPIntEffectOp stringGOAPIntEffectOp identifies an integer effect operation in a GOAP YAML file.
const (
// GOAPEffectSet sets an integer fact to a constant value.
GOAPEffectSet GOAPIntEffectOp = "set"
// GOAPEffectAdd adds a signed delta to an integer fact.
GOAPEffectAdd GOAPIntEffectOp = "add"
)type GOAPPlanner struct {
// NodeBudget caps how many search nodes regressive A* may expand per Plan call.
// Zero or negative uses DefaultGOAPNodeBudget (1024).
NodeBudget int
// contains filtered or unexported fields
}GOAPPlanner performs deterministic regressive A* search from a goal condition back to the current WorldState.
Ties break in a fixed order (lowest f, lowest h, fewest steps, lowest discovery index in fixed action declaration order). Internal search buffers are reused across calls, making repeated PlanInto calls zero-allocation after warm-up. A GOAPPlanner is not safe for concurrent use by multiple goroutines.
func NewGOAPPlanner(actions ...GOAPAction) (*GOAPPlanner, error)NewGOAPPlanner validates actions and constructs a GOAPPlanner with defensive copies of actions. Each action must have a unique non-empty Name and a finite non-negative Cost (0 defaults to 1).
func (p *GOAPPlanner) Action(index int) GOAPActionAction returns a copy of the action at index, or the zero GOAPAction if index is out of bounds.
func (p *GOAPPlanner) ActionCount() intActionCount returns the number of actions configured on p.
func (p *GOAPPlanner) ActionIndex(name string) intActionIndex returns the index of the action named name, or -1 if none matches.
func (p *GOAPPlanner) ActionName(index int) stringActionName returns the Name of the action at index, or "" if index is out of bounds.
func (p *GOAPPlanner) Plan(start WorldState, goal GOAPGoal) (plan []int, cost float64, err error)Plan finds the minimum-cost sequence of action indices that reaches goal from start. If start already satisfies goal.Target, Plan returns an empty slice, cost 0, and nil error.
func (p *GOAPPlanner) PlanBestGoal(start WorldState, goals []GOAPGoal) (goalIndex int, plan []int, cost float64, err error)PlanBestGoal tries unsatisfied goals in descending Priority order (ties broken in declaration order) and returns the first achievable goal's index, action sequence, and cost. If every goal is already satisfied by start, it returns (-1, nil, 0, nil).
func (p *GOAPPlanner) PlanBestGoalInto(dst []int, start WorldState, goals []GOAPGoal) (goalIndex int, plan []int, cost float64, err error)PlanBestGoalInto behaves like PlanBestGoal while writing the resulting action indices into dst[:0].
func (p *GOAPPlanner) PlanInto(dst []int, start WorldState, goal GOAPGoal) (plan []int, cost float64, err error)PlanInto behaves like Plan but writes the resulting action indices into dst[:0], avoiding allocations when dst has enough capacity.
func (p *GOAPPlanner) PlanNames(start WorldState, goal GOAPGoal) (names []string, cost float64, err error)PlanNames is a convenience wrapper around Plan that returns the planned action names in execution order.
type GOAPSet struct {
Schema *FactSchema
Planner *GOAPPlanner
Goals []GOAPGoal
}GOAPSet holds the compiled FactSchema, GOAPPlanner, and prioritized GOAPGoals produced by BuildGOAP.
func BuildGOAP(cfg *GOAPConfig, bind GOAPBindings) (*GOAPSet, error)BuildGOAP validates cfg and compiles its declared facts, actions, procedural checks, and goals into a GOAPSet.
type Graph[N comparable] interface {
AppendNeighbors(dst []GraphEdge[N], node N) []GraphEdge[N]
}Graph defines weighted directed adjacency over nodes of comparable type N.
AppendNeighbors appends all outgoing edges from node onto dst and returns the extended slice. Reusing dst lets GraphSearch expand nodes without heap allocations on repeated searches. Edges with negative, NaN, or infinite Cost are ignored.
type GraphEdge[N comparable] struct {
To N
Cost float64
}GraphEdge is a directed outgoing edge from a graph node with a finite non-negative step cost.
type GraphFunc[N comparable] struct {
// Neighbors appends outgoing edges from node onto dst.
Neighbors func(dst []GraphEdge[N], node N) []GraphEdge[N]
// Estimate optionally returns an admissible heuristic from -> goal (nil uses 0 / Dijkstra).
Estimate func(from, goal N) float64
// Valid optionally checks whether a start or goal node is valid (nil accepts all nodes).
Valid func(node N) bool
// Less optionally defines a strict total order on nodes for tie-breaking.
Less func(a, b N) bool
}GraphFunc adapts callback functions to HeuristicGraph[N].
func (f GraphFunc[N]) AppendNeighbors(dst []GraphEdge[N], node N) []GraphEdge[N]AppendNeighbors delegates to Neighbors when non-nil.
func (f GraphFunc[N]) Heuristic(from, goal N) float64Heuristic delegates to Estimate when non-nil, returning 0 otherwise.
func (f GraphFunc[N]) NodeLess(a, b N) boolNodeLess delegates to Less when non-nil.
func (f GraphFunc[N]) ValidNode(node N) boolValidNode delegates to Valid when non-nil, returning true otherwise.
type GraphRange[N comparable] struct {
// contains filtered or unexported fields
}GraphRange holds the shortest-path tree produced by GraphSearch.Range or GraphSearch.RangeInto: every node reachable from Start within Budget, its minimum cost, and the parent links needed to reconstruct the optimal path to any reached node.
func (r *GraphRange[N]) Budget() float64Budget returns the maximum path cost budget used to compute this range.
func (r *GraphRange[N]) Contains(node N) boolContains reports whether node is reachable within the query's budget.
func (r *GraphRange[N]) Cost(node N) (float64, bool)Cost returns the minimum path cost from Start to node, or (0, false) if node is not in the range.
func (r *GraphRange[N]) Len() intLen returns the number of reachable nodes in the range.
func (r *GraphRange[N]) Nodes() []ReachableNode[N]Nodes returns all reachable nodes and their minimum costs in deterministic order (ascending Cost, then deterministic tie-breaking order). The returned slice aliases r's internal storage and is overwritten by a subsequent RangeInto call on r.
func (r *GraphRange[N]) Parent(node N) (N, bool)Parent returns the predecessor of node on its shortest path from Start. It returns (zero, false) for Start itself or for nodes outside the range.
func (r *GraphRange[N]) Path(node N) ([]N, bool)Path returns the shortest path from Start to node inclusive, or (nil, false) if node is not reachable.
func (r *GraphRange[N]) PathInto(dst []N, node N) ([]N, bool)PathInto writes the shortest path from Start to node inclusive into dst[:0], allocating zero times when dst has enough capacity.
func (r *GraphRange[N]) Start() (N, bool)Start returns the origin node of the range query and whether the range is non-empty.
type GraphSearch[N comparable] struct {
// MaxExpansions caps the number of node expansions per search. Zero or negative means unlimited.
MaxExpansions int
// Less optionally defines a strict total order on N for tie-breaking equal (f, h) nodes.
// When nil, GraphSearch checks whether the graph implements NodeOrder[N] and falls back
// to deterministic discovery order.
Less func(a, b N) bool
// contains filtered or unexported fields
}GraphSearch performs deterministic A*, Dijkstra, and budgeted range searches over any Graph[N], reusing its internal search buffers across calls.
Tie-breaking matches AStar: lowest f, then lowest h, then Less (or the graph's NodeOrder[N]), and finally deterministic node discovery order. A GraphSearch is not safe for concurrent use.
func NewGraphSearch[N comparable]() *GraphSearch[N]NewGraphSearch returns a new reusable GraphSearch for nodes of type N.
func (s *GraphSearch[N]) Find(g Graph[N], start, goal N) (path []N, cost float64, ok bool)Find runs A* from start to goal on g (using g.Heuristic when g implements HeuristicGraph[N], or Dijkstra otherwise), returning the lowest-cost path inclusive of endpoints and its total cost.
Internal search buffers are reused across calls; only the returned path slice is allocated.
func (s *GraphSearch[N]) FindDijkstra(g Graph[N], start, goal N) (path []N, cost float64, ok bool)FindDijkstra runs Dijkstra's algorithm from start to goal on g (ignoring any HeuristicGraph method), returning the lowest-cost path inclusive of endpoints and its total cost.
Internal search buffers are reused across calls; only the returned path slice is allocated.
func (s *GraphSearch[N]) FindDijkstraInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)FindDijkstraInto behaves like FindDijkstra but writes the path into dst[:0], avoiding allocations when dst has enough capacity.
func (s *GraphSearch[N]) FindInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)FindInto behaves like Find but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.
func (s *GraphSearch[N]) FindWithHeuristic(g Graph[N], start, goal N, h func(from, goal N) float64) (path []N, cost float64, ok bool)FindWithHeuristic runs A* from start to goal on g using heuristic h (nil runs Dijkstra). Internal search buffers are reused across calls; only the returned path slice is allocated.
func (s *GraphSearch[N]) FindWithHeuristicInto(dst []N, g Graph[N], start, goal N, h func(from, goal N) float64) (path []N, cost float64, ok bool)FindWithHeuristicInto behaves like FindWithHeuristic but writes the path into dst[:0], avoiding allocations when dst has enough capacity.
func (s *GraphSearch[N]) Range(g Graph[N], start N, budget float64) *GraphRange[N]Range runs a budgeted Dijkstra search from start on g and returns a GraphRange containing every node reachable within budget, its minimum cost, and parent links for path reconstruction.
Internal search buffers are reused across calls; only the returned GraphRange is allocated.
func (s *GraphSearch[N]) RangeInto(dst *GraphRange[N], g Graph[N], start N, budget float64) *GraphRange[N]RangeInto behaves like Range but reuses dst's storage when dst is non-nil, avoiding heap allocations after warm-up.
type Grid interface {
// GridSize returns the grid's width in columns and height in rows.
GridSize() (cols, rows int)
// Walkable reports whether the cell at (col, row) can be entered.
Walkable(col, row int) bool
}Grid is a two-dimensional tile grid that AStar searches.
type GridCoverOptions struct {
// Spacing is the distance between cover points along a contiguous wall run in world units.
// When <= 0, one cover point is placed at the midpoint of each exposed cell edge.
Spacing float32
// Standoff offsets each cover point from the blocked cell edge into the adjacent walkable cell.
// When <= 0, defaults to half of min(cellWidth, cellHeight).
Standoff float32
// EdgeInset is the margin from each end of a contiguous wall run when Spacing > 0.
// When <= 0, defaults to Spacing * 0.5.
EdgeInset float32
// DefaultHeight sets the height for generated cover points (defaults to CoverFull).
DefaultHeight CoverHeight
// HeightFunc optionally classifies cover height for blocked cell (col, row).
HeightFunc func(col, row int) CoverHeight
// StartID is the first CoverPoint.ID assigned (defaults to 1 when 0).
StartID uint64
}GridCoverOptions configures cover-point generation from any ai.Grid (blocked cells are solid walls).
type GridFunc struct {
Cols, Rows int
// Walk reports whether (col, row) is walkable; a nil Walk treats all in-bounds cells as walkable.
Walk func(col, row int) bool
// Cost returns the traversal cost of entering (col, row); a nil Cost uses 1 everywhere.
Cost func(col, row int) float64
}GridFunc adapts callback functions to CostGrid, letting any tilemap or custom map plug into AStar in a few lines.
func (f GridFunc) GridSize() (cols, rows int)GridSize returns Cols and Rows.
func (f GridFunc) MoveCost(col, row int) float64MoveCost returns Cost(col, row) or 1 when Cost is nil or returns a value below 1: the distance heuristic assumes every step costs at least 1.
func (f GridFunc) Walkable(col, row int) boolWalkable reports whether (col, row) is in bounds and Walk allows it.
type GridGenerator struct {
// Center selects the grid sampling center (defaults to OriginQuerier).
Center QueryOrigin
// CustomCenter is used when Center is OriginCustom.
CustomCenter math2d.Vec2
// HalfExtent is the half-width and half-height of the sampled world region around Center.
// When Grid is non-nil and HalfExtent is zero, all walkable cells in Grid are emitted.
HalfExtent math2d.Vec2
// Spacing is the world distance between samples (defaults to CellSize when Grid != nil, else 16).
Spacing float32
// Grid optionally restricts candidates to walkable cells using GridOrigin and CellSize.
Grid Grid
// GridOrigin is the world origin of cell (0, 0) in Grid.
GridOrigin math2d.Vec2
// CellSize is the world size of one cell in Grid (defaults to 1 when <= 0).
CellSize float32
}GridGenerator emits candidates on a regular 2D grid around Center or across an ai.Grid's walkable cells.
func (g *GridGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidateGenerate appends grid candidates in deterministic row-major order.
type GridPathOptions struct {
// Origin is the world-space coordinate of cell (0, 0)'s top-left corner.
Origin core.Point
// CellSize is the width and height of one square grid cell in world units.
// Positive CellWidth or CellHeight values override CellSize on their respective axes.
// When no positive size is set on an axis, that axis defaults to 1.
CellSize float32
// CellWidth overrides CellSize along the X axis when positive, supporting rectangular tiles.
CellWidth float32
// CellHeight overrides CellSize along the Y axis when positive, supporting rectangular tiles.
CellHeight float32
// Radius is the circular body radius in world units that smoothed segments must keep clear of every blocked cell.
// Values less than or equal to 0 test a zero-width ray that still rejects corner-cutting through blocked cells.
Radius float32
}GridPathOptions configures world-space conversion and body clearance for SmoothGridPath, SmoothGridPathInto, and GridLineOfSight.
The zero value uses 1x1 world-unit cells rooted at (0, 0) with a zero-width line-of-sight ray (still preventing corner cuts across blocked cells).
func (o GridPathOptions) CellCenter(c Cell) core.PointCellCenter returns the world-space center of cell c under o.
type GridPathResult struct {
Path []Cell
Cost float64
Found bool // true when a complete or partial path was produced
Partial bool // true when Path ends at the closest explored cell rather than goal
Exhausted bool // true when the search stopped because MaxExpansions was reached
Expansions int // total number of grid cells expanded during the search
}GridPathResult is the outcome of a bounded or incremental grid A* search.
type GridTopology uint8GridTopology selects the cell adjacency and admissible distance heuristic used by AStar and movement-range queries.
The zero value (TopologySquare) uses the square grid (4-way or 8-way depending on AStar.Diagonal), preserving backward compatibility with existing AStar callers.
const (
// TopologySquare is an orthogonal (or diamond isometric) square grid.
// With AStar.Diagonal false it uses 4-way cardinal neighbors and Manhattan distance;
// with AStar.Diagonal true it uses 8-way neighbors (respecting NoCornerCutting) and octile distance.
TopologySquare GridTopology = iota
// TopologySquare4 forces 4-way cardinal adjacency and Manhattan distance regardless of AStar.Diagonal.
TopologySquare4
// TopologySquare8 forces 8-way adjacency (respecting AStar.NoCornerCutting) and octile distance regardless of AStar.Diagonal.
TopologySquare8
// TopologyHexPointyOdd is a pointy-top hexagonal grid with odd rows shifted right (StaggerY, StaggerOdd; Tiled default).
TopologyHexPointyOdd
// TopologyHexPointyEven is a pointy-top hexagonal grid with even rows shifted right (StaggerY, StaggerEven).
TopologyHexPointyEven
// TopologyHexFlatOdd is a flat-top hexagonal grid with odd columns shifted down (StaggerX, StaggerOdd).
TopologyHexFlatOdd
// TopologyHexFlatEven is a flat-top hexagonal grid with even columns shifted down (StaggerX, StaggerEven).
TopologyHexFlatEven
// TopologyStaggeredYOdd is a staggered isometric grid with odd rows shifted right (StaggerY, StaggerOdd).
// With AStar.Diagonal false it moves along the 4 diamond edges; with AStar.Diagonal true it also allows the 4 vertex-adjacent diagonals.
TopologyStaggeredYOdd
// TopologyStaggeredYEven is a staggered isometric grid with even rows shifted right (StaggerY, StaggerEven).
TopologyStaggeredYEven
// TopologyStaggeredXOdd is a staggered isometric grid with odd columns shifted down (StaggerX, StaggerOdd).
TopologyStaggeredXOdd
// TopologyStaggeredXEven is a staggered isometric grid with even columns shifted down (StaggerX, StaggerEven).
TopologyStaggeredXEven
)func TopologyFromTilemap(m *tilemap.Tilemap) GridTopologyTopologyFromTilemap returns the GridTopology matching m's Orientation, StaggerAxis and StaggerIndex.
A nil tilemap, OrientationOrthogonal or OrientationIsometric returns TopologySquare (diamond isometric cells share the same 4/8-way (col, row) adjacency as orthogonal squares).
func (t GridTopology) Distance(a, b Cell) float64Distance returns the exact open-ground step distance (and admissible A* heuristic) between a and b under t.
For TopologySquare and TopologyStaggered* it computes 4-way distance; TopologySquare8 computes octile distance; hexagonal topologies compute exact cube distance matching tilemap.Tilemap.HexDistance.
func (t GridTopology) IsHex() boolIsHex reports whether t is one of the four hexagonal grid topologies.
func (t GridTopology) IsStaggered() boolIsStaggered reports whether t is one of the four staggered isometric grid topologies.
func (t GridTopology) Neighbors(c Cell) []CellNeighbors returns the adjacent cells of c under t in deterministic order.
For TopologySquare and TopologyStaggered* it returns the 4 edge-adjacent neighbors; use TopologySquare8 for 8-way square neighbors, or NeighborsInto with an explicit diagonal flag via AStar.
func (t GridTopology) NeighborsInto(dst []Cell, c Cell) []CellNeighborsInto appends the adjacent cells of c under t into dst[:0].
func (t GridTopology) String() stringString returns the topology's canonical name.
type HPA struct {
// contains filtered or unexported fields
}HPA implements Hierarchical Pathfinding A* (HPA*) over a square Grid, CostGrid, or EdgeCostGrid.
It partitions the grid into fixed-size square clusters, places entrance nodes along shared cluster borders, precomputes intra-cluster shortest paths between entrances, and supports O(affected clusters) incremental updates via UpdateCell, UpdateRect, and RebuildDirty.
All search and refinement buffers are reused across calls. An HPA is not safe for concurrent use by multiple goroutines.
func NewHPA(g Grid, opts HPAOptions) *HPANewHPA builds an HPA* hierarchy over g with opts.
If g is nil or empty, the returned HPA is valid but all searches return ok=false.
func (h *HPA) AllowCornerCutting() boolAllowCornerCutting reports whether diagonal moves may cut blocked corners.
func (h *HPA) ClusterAt(c Cell) (ClusterID, bool)ClusterAt returns the ClusterID containing cell c and whether c is in bounds.
func (h *HPA) ClusterGridSize() (cols, rows int)ClusterGridSize returns the number of cluster columns and cluster rows.
func (h *HPA) ClusterRect(id ClusterID) (ClusterRect, bool)ClusterRect returns the cell bounds of cluster id and whether id is in bounds.
func (h *HPA) ClusterSize() intClusterSize returns the configured cluster width and height in cells.
func (h *HPA) Diagonal() boolDiagonal reports whether 8-way diagonal movement is enabled.
func (h *HPA) Find(start, goal Cell) (path []Cell, cost float64, ok bool)Find searches the hierarchical graph for a near-optimal path from start to goal, refining it into a contiguous concrete slice of walkable cells and returning the exact path cost.
func (h *HPA) FindAbstract(start, goal Cell) (waypoints []Cell, cost float64, ok bool)FindAbstract searches only the hierarchical abstract graph without refining intra-cluster segments, returning the sequence of entrance waypoints from start to goal inclusive and the path cost.
func (h *HPA) FindAbstractInto(dst []Cell, start, goal Cell) (waypoints []Cell, cost float64, ok bool)FindAbstractInto behaves like FindAbstract but writes the abstract waypoints into dst[:0].
func (h *HPA) FindClusters(start, goal Cell) (clusters []ClusterID, cost float64, ok bool)FindClusters searches only the hierarchical abstract graph and returns the ordered list of clusters traversed from start to goal.
func (h *HPA) FindClustersInto(dst []ClusterID, start, goal Cell) (clusters []ClusterID, cost float64, ok bool)FindClustersInto behaves like FindClusters but writes the traversed ClusterIDs into dst[:0].
func (h *HPA) FindInto(dst []Cell, start, goal Cell) (path []Cell, cost float64, ok bool)FindInto behaves like Find but writes the refined cell path into dst[:0], avoiding heap allocations when dst has enough capacity.
func (h *HPA) Grid() GridGrid returns the underlying Grid this HPA hierarchy was built over.
func (h *HPA) GridSize() (cols, rows int)GridSize returns the width and height of the underlying grid in cells.
func (h *HPA) RebuildDirty() intRebuildDirty incrementally rebuilds only the borders and clusters marked dirty by UpdateCell or UpdateRect.
It returns the number of clusters rebuilt.
func (h *HPA) Stats() HPAStatsStats returns current graph size and cluster rebuild counters.
func (h *HPA) UpdateCell(col, row int)UpdateCell marks the cluster containing (col, row), and any shared border and neighboring cluster it touches, as dirty.
Call RebuildDirty to apply pending updates immediately, or let the next Find / FindAbstract / FindClusters call rebuild them automatically.
func (h *HPA) UpdateRect(minCol, minRow, maxCol, maxRow int)UpdateRect marks every cluster and shared border overlapping the inclusive cell rectangle [minCol..maxCol] x [minRow..maxRow] as dirty.
type HPAOptions struct {
// ClusterSize is the width and height of each cluster in cells.
// Values <= 0 use DefaultHPAClusterSize (16); 1 is clamped to 2.
ClusterSize int
// MaxEntranceSpan is the maximum contiguous walkable border run represented by a single entrance.
// Longer runs receive two entrances at their endpoints (plus a lowest-cost cell on weighted grids when cheaper).
// Values <= 0 use DefaultHPAMaxEntranceSpan (6).
MaxEntranceSpan int
// Diagonal allows 8-way movement with step distance sqrt(2) on diagonals; false restricts movement to 4 cardinal directions.
Diagonal bool
// AllowCornerCutting permits diagonal moves when one or both adjacent cardinal cells are blocked.
// When false (the default), diagonal moves never cut corners, matching NewAStar.
AllowCornerCutting bool
}HPAOptions configures an HPA hierarchical pathfinder.
type HPAStats struct {
ClusterCols int
ClusterRows int
ClusterSize int
NodeCount int
DirtyClusters int
TotalClusterRebuilds int
LastRebuiltClusters int
}HPAStats reports structural and incremental-rebuild metrics for an HPA instance.
type HearingConfig struct {
// Range is how far away a noise of loudness 1 is heard; a noise's loudness scales it. +Inf hears a noise at any finite distance at strength 1, and zero, less or NaN hears nothing.
Range float32
// Detect selects the attitudes hearing detects; zero detects hostile noises only.
Detect AttitudeMask
}HearingConfig describes an agent's hearing. The zero HearingConfig hears nothing.
type HeatmapOptions struct {
// PositiveColor is the tint for positive cell values; defaults to green (0x22C55E) when 0.
PositiveColor core.Color
// NegativeColor is the tint for negative cell values; defaults to red (0xEF4444) when 0.
NegativeColor core.Color
// MaxAbs is the reference magnitude mapped to full MaxAlpha.
// When <= 0, it is computed automatically from the layer's maximum absolute cell value.
MaxAbs float32
// MaxAlpha caps the opacity of peak-magnitude cells in (0, 1]; defaults to 0.65 when <= 0.
MaxAlpha float32
// MinThreshold skips cells whose absolute value is <= MinThreshold; defaults to 1e-4 when <= 0.
MinThreshold float32
// DrawGrid draws subtle cell outlines over the visible grid region when true.
DrawGrid bool
// GridColor is the stroke color when DrawGrid is true; defaults to translucent white when 0.
GridColor core.Color
}HeatmapOptions configures InfluenceLayer.DrawHeatmap.
type HeuristicGraph[N comparable] interface {
Graph[N]
Heuristic(from, goal N) float64
}HeuristicGraph is a Graph that supplies an admissible lower-bound cost estimate between two nodes for A* search.
type HexGrid struct {
// Map is the backing hexagonal tilemap. Must be non-nil with positive Width and Height.
Map *tilemap.Tilemap
// SolidMask selects which tilemap.TileFlags block entry into a cell.
// When 0, defaults to tilemap.TileSolid unless Walk is set.
SolidMask tilemap.TileFlags
// Walk optionally overrides cell walkability for in-bounds cells.
// When nil, a cell is walkable iff Map.FlagsAt(col, row)&effectiveSolidMask == 0.
Walk func(col, row int) bool
// Cost optionally returns the traversal cost of entering (col, row).
// Negative, NaN, or infinite values mark the cell unwalkable when StepCost is nil.
// When nil, every walkable cell has cost 1.
Cost func(col, row int) float64
// StepCost optionally returns the directed traversal cost from -> to, taking precedence over Cost.
// Negative, NaN, or infinite values forbid moving along that edge.
StepCost func(from, to Cell) float64
}HexGrid adapts a hexagonal tilemap.Tilemap to HeuristicGraph[Cell] (and Grid / EdgeCostGrid) using tilemap.Tilemap.HexNeighbors and tilemap.Tilemap.HexDistance across all stagger axes (StaggerX, StaggerY) and stagger indices (StaggerOdd, StaggerEven).
Heuristic returns the exact cube step distance (Map.HexDistance), which is admissible whenever every step costs at least 1. When using sub-unit road costs (< 1), prefer GraphSearch.FindDijkstra, GraphSearch.Range, or GraphSearch.FindWithHeuristic with a scaled distance heuristic.
func NewHexGrid(m *tilemap.Tilemap) *HexGridNewHexGrid returns a HexGrid over m blocking tiles with tilemap.TileSolid and using unit step cost 1.
func (h *HexGrid) AppendNeighbors(dst []GraphEdge[Cell], c Cell) []GraphEdge[Cell]AppendNeighbors appends all passable hexagonal neighbor transitions of c onto dst using Map.HexNeighbors in deterministic order.
func (h *HexGrid) EdgeCost(fromCol, fromRow, toCol, toRow int) float64EdgeCost returns the directed traversal cost from (fromCol, fromRow) to (toCol, toRow) for EdgeCostGrid compatibility. Negative, NaN, or infinite values forbid the transition.
func (h *HexGrid) GridSize() (cols, rows int)GridSize returns the underlying tilemap's width and height in cells.
func (h *HexGrid) Heuristic(from, goal Cell) float64Heuristic returns the exact hexagonal step distance between from and goal via Map.HexDistance.
func (h *HexGrid) MoveCost(col, row int) float64MoveCost returns the traversal cost of entering (col, row) for CostGrid compatibility, clamping values below 1 to 1 so AStar's distance heuristic remains admissible.
func (h *HexGrid) NodeLess(a, b Cell) boolNodeLess orders cells in row-major order, matching AStar's deterministic cell-ID tie-breaking.
func (h *HexGrid) ValidNode(c Cell) boolValidNode reports whether c is in bounds and passable.
func (h *HexGrid) Walkable(col, row int) boolWalkable reports whether (col, row) is in bounds and passable.
type IncrementalSearch interface {
// Step advances the search by at most maxExpansions node expansions and returns
// the updated status along with the exact number of expansions performed.
// When maxExpansions <= 0 or the search is already done, Step performs 0 expansions.
Step(maxExpansions int) (status SearchStatus, expansions int)
// Status returns the search's current status.
Status() SearchStatus
// Expansions returns the cumulative number of node expansions performed so far.
Expansions() int
}IncrementalSearch is a deterministic path search that advances in bounded expansion steps.
*AStarSearch, *NavMeshSearch, and *world3d.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 InfluenceLayer struct {
// Origin is the world position of the top-left corner of cell (0, 0).
Origin math2d.Vec2
// CellSize is the width and height of one cell in world units; values <= 0 or non-finite behave as 1.
CellSize float32
// contains filtered or unexported fields
}InfluenceLayer stores a 2D scalar influence grid matching an ai.Grid's dimensions.
Cells map to world coordinates via Origin and CellSize in the same convention as rts.FlowField: cell (col, row) covers [Origin.X+col*CellSize, Origin.X+(col+1)*CellSize) horizontally and [Origin.Y+row*CellSize, Origin.Y+(row+1)*CellSize) vertically.
Tracked sources registered with AddSource update incrementally on Update or Spread, touching only old and new footprints of changed sources while matching a full Rebuild bit-for-bit. After warm-up, incremental updates, spreading, layer combinations, and spatial queries perform zero heap allocations.
An InfluenceLayer is not safe for concurrent use by multiple goroutines.
func NewInfluenceLayer(cols, rows int) *InfluenceLayerNewInfluenceLayer returns a cols-by-rows InfluenceLayer with CellSize 1 and Origin (0, 0).
func NewInfluenceLayerForGrid(g Grid, origin math2d.Vec2, cellSize float32) *InfluenceLayerNewInfluenceLayerForGrid returns an InfluenceLayer sized to g.GridSize() with the given world origin and cellSize. If g is nil, the returned layer has size (0, 0).
func (l *InfluenceLayer) Abs()Abs replaces every cell value in l with its absolute value in place.
func (l *InfluenceLayer) Add(a, b *InfluenceLayer)Add sets each cell of l to a + b (useful for tension maps combining friendly and enemy presence). Aliasing l with a or b is safe, and reusing a pre-sized l performs zero heap allocations.
func (l *InfluenceLayer) AddScaled(src *InfluenceLayer, weight float32)AddScaled adds src * weight into l in place without allocating. If l and src differ in size, only the overlapping top-left region is updated.
func (l *InfluenceLayer) AddSource(src InfluenceSource) InfluenceSourceIDAddSource registers a tracked source and returns its handle for future MoveSource, SetSource, or RemoveSource calls. The source takes effect on the next Update, Rebuild, or Spread call.
func (l *InfluenceLayer) At(col, row int) float32At returns the value at (col, row), or 0 when out of bounds.
func (l *InfluenceLayer) CellAt(p math2d.Vec2) (Cell, bool)CellAt returns the cell containing world position p and whether p lies inside the grid.
func (l *InfluenceLayer) CellCenter(c Cell) math2d.Vec2CellCenter returns the world position at the center of cell c.
func (l *InfluenceLayer) Clamp(minVal, maxVal float32)Clamp clamps every cell of l into [minVal, maxVal] in place.
func (l *InfluenceLayer) Clear()Clear zeroes all cell values in the layer. If tracked sources exist, they are marked for full recomputation on the next Update or Spread.
func (l *InfluenceLayer) ClearSources()ClearSources removes all tracked sources and marks the layer dirty so the next Update or Spread clears their influence.
func (l *InfluenceLayer) Combine(terms ...WeightedLayer)Combine sets l to the weighted sum of terms (sum of term.Layer * term.Weight). Dimensions follow the first non-nil layer in terms. Aliasing l inside terms is safe, and reusing a pre-sized l performs zero heap allocations.
func (l *InfluenceLayer) CopyFrom(src *InfluenceLayer)CopyFrom copies src's dimensions, Origin, CellSize, and cell values into l without allocating when l already has sufficient capacity.
func (l *InfluenceLayer) DrawHeatmap(d *core.Drawing, cam *tilemap.Camera, opts HeatmapOptions)DrawHeatmap renders the influence layer as a translucent color heatmap in world coordinates, culling cells outside cam.VisibleBounds() when cam is non-nil.
Like tilemap.Tilemap.Draw, DrawHeatmap expects d to already carry the camera's world-to-view transform (via cam.Apply(d)). Positive cells are tinted with opts.PositiveColor and negative cells with opts.NegativeColor, with alpha proportional to |value| / maxAbs up to opts.MaxAlpha. Under -tags release, DrawHeatmap compiles to a no-op stub.
func (l *InfluenceLayer) Fill(v float32)Fill sets every cell in the layer to v (non-finite values are treated as 0).
func (l *InfluenceLayer) Gradient(p math2d.Vec2) math2d.Vec2Gradient returns the smooth 2D gradient vector (d/dx, d/dy in influence per world unit) at world position p, pointing uphill toward higher influence. At CellCenter(c), Gradient agrees with GradientAtCell(c.Col, c.Row). Points outside the grid return the zero vector.
func (l *InfluenceLayer) GradientAtCell(col, row int) math2d.Vec2GradientAtCell returns the 2D gradient vector (d/dx, d/dy in influence per world unit) at (col, row), pointing toward higher influence. Boundary cells use one-sided differences; out-of-bounds cells return zero.
func (l *InfluenceLayer) Highest(g Grid) (Cell, float32, bool)Highest finds the highest-valued cell across the entire layer (restricted to walkable cells when g is non-nil). Ties break deterministically by smaller Row, then smaller Col.
func (l *InfluenceLayer) HighestInRadius(center Cell, radius float32, q InfluenceQuery) (Cell, float32, bool)HighestInRadius finds the candidate cell with the highest value within Euclidean cell distance radius of center. Ties break deterministically by closer distance to center, then smaller Row, then smaller Col.
func (l *InfluenceLayer) Lowest(g Grid) (Cell, float32, bool)Lowest finds the lowest-valued cell across the entire layer (restricted to walkable cells when g is non-nil). Ties break deterministically by smaller Row, then smaller Col.
func (l *InfluenceLayer) LowestInRadius(center Cell, radius float32, q InfluenceQuery) (Cell, float32, bool)LowestInRadius finds the candidate cell with the lowest value within Euclidean cell distance radius of center. Ties break deterministically by closer distance to center, then smaller Row, then smaller Col.
func (l *InfluenceLayer) MarkDirtyCell(c Cell)MarkDirtyCell marks cell c for incremental recomputation on the next Update or Spread, useful when a single obstacle on the underlying Grid toggles walkability.
func (l *InfluenceLayer) MarkDirtyRect(minCol, minRow, maxCol, maxRow int)MarkDirtyRect marks the inclusive cell rectangle [minCol..maxCol] x [minRow..maxRow] for incremental recomputation.
func (l *InfluenceLayer) MoveSource(id InfluenceSourceID, cell Cell) boolMoveSource moves the tracked source id to cell, marking its old and new footprints dirty only if cell changed. It returns false if id is invalid or was already removed.
func (l *InfluenceLayer) Multiply(a, b *InfluenceLayer)Multiply sets each cell of l to a * b (useful for terrain masking or contested overlap maps). Aliasing l with a or b is safe, and reusing a pre-sized l performs zero heap allocations.
func (l *InfluenceLayer) Normalize()Normalize divides every cell of l by the maximum absolute value across the layer, mapping non-negative layers to [0, 1] and signed layers to [-1, 1] while preserving 0 as neutral. It is a no-op if every cell is 0.
func (l *InfluenceLayer) Rebuild(g Grid)Rebuild forces a full recomputation of every cell from all active tracked sources, skipping blocked cells when g is non-nil. Call Rebuild when terrain walkability changes across the whole Grid.
func (l *InfluenceLayer) RemoveSource(id InfluenceSourceID) boolRemoveSource unregisters the tracked source id and schedules its stamped footprint to be cleared on the next Update or Spread. It returns false if id is invalid or was already removed.
func (l *InfluenceLayer) Resize(cols, rows int)Resize changes the layer's dimensions to cols-by-rows, clearing its cell values and reusing backing slices when capacity permits. Any registered tracked sources are retained and marked for full recomputation on the next Update or Spread.
func (l *InfluenceLayer) Sample(p math2d.Vec2) (float32, bool)Sample returns the bilinearly interpolated influence value at world position p and whether p is inside the grid. At a cell's center (CellCenter(c)), Sample returns At(c.Col, c.Row) exactly.
func (l *InfluenceLayer) Scale(s float32)Scale multiplies every cell of l by s in place (non-finite values are treated as 0).
func (l *InfluenceLayer) Set(col, row int, v float32)Set writes v into cell (col, row). Out-of-bounds coordinates are ignored and non-finite values are stored as 0.
func (l *InfluenceLayer) SetSource(id InfluenceSourceID, src InfluenceSource) boolSetSource replaces the parameters of the tracked source id, marking its old and new footprints dirty. It returns false if id is invalid or was already removed.
func (l *InfluenceLayer) Size() (cols, rows int)Size returns the layer's width in columns and height in rows.
func (l *InfluenceLayer) Source(id InfluenceSourceID) (InfluenceSource, bool)Source returns the current parameters of tracked source id, or false if id is invalid or removed.
func (l *InfluenceLayer) SourceCount() intSourceCount returns the number of active tracked sources registered on the layer.
func (l *InfluenceLayer) Spread(g Grid, opts SpreadOptions)Spread propagates influence across walkable cells of g with the given decay and momentum.
When tracked sources are active on the layer, pending source changes are synced incrementally into the internal source buffer without overwriting previous values, and each pass propagates from walkable neighbors while anchoring on the current sources so moved or removed sources smoothly decay according to opts.Momentum. When no tracked sources are active (for example after direct Stamp or Set calls), each cell anchors on its own current value so influence spreads outward around obstacles. Blocked cells (!g.Walkable) always evaluate to 0 and never transmit influence.
func (l *InfluenceLayer) Stamp(g Grid, src InfluenceSource)Stamp additively stamps src directly onto the layer's current cell values, skipping blocked cells when g is non-nil. Direct stamps are not tracked for incremental moves; use AddSource and Update for dynamic tracked sources.
func (l *InfluenceLayer) Subtract(a, b *InfluenceLayer)Subtract sets each cell of l to a - b (useful for control maps: friendly - enemy). Aliasing l with a or b is safe, and reusing a pre-sized l performs zero heap allocations.
func (l *InfluenceLayer) Update(g Grid)Update incrementally applies pending AddSource, MoveSource, SetSource, RemoveSource, and MarkDirty changes to the layer, touching only the dirty cell footprints while matching Rebuild bit-for-bit. When g is non-nil, blocked cells (!g.Walkable) receive 0.
func (l *InfluenceLayer) Values() []float32Values returns the layer's flat row-major cell slice (index row*cols + col). The returned slice aliases the layer's internal storage and changes on subsequent updates.
type InfluenceQuery struct {
// Grid optionally filters candidate cells by walkability (and reachability when Reachable is true).
// When nil, all in-bounds cells within Radius are considered.
Grid Grid
// Reachable, when true and Grid is non-nil, restricts candidates to cells reachable from the center cell
// by walking through Grid.Walkable cells within Radius.
Reachable bool
// Diagonal allows 8-way steps (with no corner-cutting around blocked cells) during reachability search.
// Ignored when Reachable is false.
Diagonal bool
// ExcludeCenter omits the center cell itself from the candidates when true.
ExcludeCenter bool
}InfluenceQuery configures a spatial extremum search (HighestInRadius / LowestInRadius).
type InfluenceSource struct {
// Cell is the grid coordinate at the center of the source.
Cell Cell
// Strength is the peak influence value stamped at Cell. It may be positive or negative.
Strength float32
// Radius is the maximum stamp distance in grid cells. Values <= 0 stamp only Cell.
Radius float32
// Falloff selects the attenuation curve (defaults to FalloffLinear).
Falloff FalloffKind
// FalloffRate controls exponential attenuation speed for FalloffExponential; values <= 0 default to 1.
FalloffRate float32
// CustomFalloff evaluates the attenuation multiplier for FalloffCustom given cell distance and radius.
// If nil, FalloffLinear is used. Non-finite return values are treated as 0.
CustomFalloff func(dist, radius float32) float32
}InfluenceSource describes a point emitter stamped onto an InfluenceLayer.
type InfluenceSourceID uint64InfluenceSourceID identifies a tracked source registered on an InfluenceLayer. The zero value is invalid.
type InfluenceTest struct {
// Layer is the InfluenceLayer sampled at each candidate's world position.
Layer *InfluenceLayer
// OutOfBoundsValue is used when a candidate lies outside Layer and RejectOutOfBounds is false.
OutOfBoundsValue float64
// RejectOutOfBounds filters out candidates outside Layer when Purpose allows filtering.
RejectOutOfBounds bool
// Purpose selects filtering, scoring, or both (defaults to TestFilterAndScore).
Purpose TestPurpose
// Filter optionally restricts acceptable influence values.
Filter FloatRange
// NormMin and NormMax optionally specify fixed normalization bounds.
// When NormMax <= NormMin, values normalize dynamically across surviving candidates.
NormMin, NormMax float64
// Weight scales the normalized [0, 1] score contribution.
Weight float64
// Invert flips the normalized score (1 - norm) so lower influence (e.g. lower threat) scores higher.
Invert bool
}InfluenceTest reads the bilinearly sampled scalar value from an ai.InfluenceLayer at each candidate.
type IntEffectKind uint8IntEffectKind identifies how an action modifies a small integer fact.
const (
// IntEffectNone leaves the integer fact unchanged.
IntEffectNone IntEffectKind = iota
// IntEffectSet assigns a constant value to the integer fact.
IntEffectSet
// IntEffectAdd adds a signed delta to the integer fact (clamped to int16 range).
IntEffectAdd
)type IntFact uint8IntFact identifies a small integer fact slot (0..MaxIntFacts-1) in a FactSchema and WorldState.
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() *JPSNewJPS returns a JPS searcher with NoCornerCutting enabled by default.
func (j *JPS) Find(g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)Find searches uniform-cost square grid g for an optimal 8-way path from start to goal, returning every cell along the path from start to goal inclusive and the exact octile path cost.
func (j *JPS) FindInto(dst []Cell, g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)FindInto behaves like Find but writes the expanded cell path into dst[:0], avoiding allocations when dst has enough capacity.
func (j *JPS) FindJumpPoints(g Grid, start, goal Cell) (waypoints []Cell, cost float64, ok bool)FindJumpPoints searches uniform-cost square grid g and returns only the jump-point waypoints (start, turning points, and goal) together with the exact optimal 8-way cost.
func (j *JPS) FindJumpPointsInto(dst []Cell, g Grid, start, goal Cell) (waypoints []Cell, cost float64, ok bool)FindJumpPointsInto behaves like FindJumpPoints but writes the jump points into dst[:0].
type LOSFunc func(from, to math2d.Vec2) boolLOSFunc reports whether there is an unobstructed line of sight between world points from and to.
type LOSTest struct {
// LOS returns true when there is unobstructed line of sight from from to to.
// If nil, every candidate is treated as having clear line of sight.
LOS LOSFunc
// Target selects the other endpoint of the line-of-sight check (defaults to OriginTarget).
Target QueryOrigin
// CustomTarget is used when Target is OriginCustom.
CustomTarget math2d.Vec2
// FromTarget reverses the ray direction to LOS(target, candidate) instead of LOS(candidate, target).
FromTarget bool
// WantClear selects whether unobstructed sight (true, e.g. firing spot) or blocked sight
// (false, e.g. hidden cover) passes the filter and earns a score of 1.
WantClear bool
// Purpose selects filtering, scoring, or both (defaults to TestFilterAndScore).
Purpose TestPurpose
// Weight scales the score contribution (1 when LOS matches WantClear, 0 otherwise).
Weight float64
}LOSTest evaluates line of sight between each candidate and a target via a game-supplied callback.
Each invocation consumes one raycast from ctx.Budget (when non-nil). When the budget is exhausted, remaining candidates are skipped (dropped if filtering, or scored 0 if TestScoreOnly).
type LineOfSight func(from, to core.Point) boolLineOfSight reports whether nothing blocks the segment from an agent's eye at from to a target at to. PhysicsLineOfSight adapts a physics world and lights2d.LineOfSight adapts lighting occluders; a game may supply its own, and it must be deterministic for perception to be.
func PhysicsLineOfSight(w *physics.World, query physics.QueryMask, layers physics.LayerMask) LineOfSightPhysicsLineOfSight returns a LineOfSight that is blocked by the first hit of w.RaycastFirstLayer with query and layers; zero values select every target and layer, as they do in physics.
A ray starting inside a body hits it, and a ray to a target hits the target's own body, so keep agents' and targets' bodies off the layers that block sight, such as by giving walls a layer of their own.
type Memory struct {
// ID is the stimulus's ID.
ID StimulusID
// Team is the stimulus's team when it was last sensed.
Team Team
// Attitude is how the agent regarded the stimulus when it was last sensed.
Attitude Attitude
// Sense is the sense that last refreshed the memory.
Sense Sense
// Pos is the last known position.
Pos core.Point
// Vel is the last known velocity: the target's velocity when seen, zero when heard.
Vel core.Point
// Age is the time since the stimulus was last sensed; zero while it is in sight.
Age time.Duration
// Strength is 1 when seen, and hearing raises it to at least 1 - distance/reach (1 for an infinite reach); it falls linearly to 0 over ForgetAfter; it ranks memories by how fresh and certain they are.
Strength float32
// Visible reports whether the stimulus is in sight now.
Visible bool
}Memory is what an agent remembers about one stimulus.
type NavAgent struct {
// contains filtered or unexported fields
}NavAgent navigates a 2D ai.NavMesh by maintaining an active polygon corridor, steering smoothly toward the next funnel corner, slowing cleanly to arrive, repairing its corridor locally when pushed or when the target shifts, and invoking callbacks for off-mesh or flagged links.
NavAgent is deterministic on fixed game.Loop steps and is not safe for concurrent use.
func NewNavAgent(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgentNewNavAgent constructs a 2D navigation agent placed at pos on mesh.
func (a *NavAgent) ClearTarget()ClearTarget clears the agent's goal, resets its corridor, stops velocity, and sets state to NavAgentIdle.
func (a *NavAgent) Config() NavAgentConfigConfig returns the sanitized configuration of the agent.
func (a *NavAgent) Corridor() []intCorridor returns a copy of the agent's active polygon index corridor.
func (a *NavAgent) ForceReplan() boolForceReplan immediately executes a full A* replan from the agent's current position to its target, ignoring ReplanInterval and group throttling, and reports whether a valid corridor was found.
func (a *NavAgent) HasTarget() boolHasTarget reports whether the agent currently has a target.
func (a *NavAgent) LocalRepairCount() intLocalRepairCount returns the number of cheap local corridor repairs performed without a full A* replan.
func (a *NavAgent) NeedsReplan() boolNeedsReplan reports whether the agent is waiting for a full A* replan.
func (a *NavAgent) NextCorner() (core.Point, bool)NextCorner returns the next funnel steering corner along the agent's remaining corridor. Returns (zero, false) when the agent has no valid corridor.
func (a *NavAgent) Path() []core.PointPath returns the full string-pulled waypoint path from the agent's current position to its target along its active corridor, or nil when no valid corridor exists.
func (a *NavAgent) Pos() core.PointPos returns the agent's current 2D position.
func (a *NavAgent) ReplanCount() intReplanCount returns the total number of full A* replans performed by this agent.
func (a *NavAgent) SetMesh(mesh *NavMesh)SetMesh attaches a new NavMesh to the agent, invalidating any existing corridor so the agent replans.
func (a *NavAgent) SetPosition(pos core.Point)SetPosition updates the agent's position (for example after physics knockback or external push). When the agent has an active corridor and is not mid-link, it attempts cheap local corridor repair immediately without running a full A* replan.
func (a *NavAgent) SetTarget(target core.Point)SetTarget sets or updates the agent's destination.
When the agent already holds a valid corridor, SetTarget tries cheap local end-of-corridor repair (same polygon, corridor truncation, or bounded bridge extension) before scheduling a full A* replan. Agents managed by a NavAgentGroup defer full replans to NavAgentGroup.Step so MaxReplansPerStep is strictly respected.
func (a *NavAgent) SetVelocity(v core.Point)SetVelocity overrides the agent's current velocity. Non-finite values are ignored.
func (a *NavAgent) State() NavAgentStateState returns the agent's current navigation state.
func (a *NavAgent) Step(dt time.Duration)Step advances the agent by fixed duration dt: ticks replan cooldown, detects mesh changes, repairs the corridor locally or replans if needed, steers toward the next funnel corner, traverses off-mesh/flagged links, and settles cleanly on arrival.
func (a *NavAgent) Target() core.PointTarget returns the agent's current target position (zero when idle).
func (a *NavAgent) TraversingLink() (NavLinkEvent, bool)TraversingLink returns the active link event while the agent is traversing an off-mesh or flagged link.
func (a *NavAgent) Vel() core.PointVel returns the agent's current 2D velocity.
type NavAgentConfig struct {
// MaxSpeed is the maximum movement speed in world units per second. Defaults to 100 when <= 0.
// MaxAcceleration caps how fast velocity changes in world units per second squared.
// Defaults to 4 * MaxSpeed when <= 0.
// Radius is the agent's body radius in world units. Defaults to 0.5 when <= 0.
// StoppingDistance is the distance from the goal within which the agent counts as arrived.
// Defaults to max(Radius, 0.25) when <= 0.
// ArrivalRadius is the distance from the goal inside which the agent slows down smoothly.
// Defaults to max(StoppingDistance*3, MaxSpeed*MaxSpeed/(2*MaxAcceleration)*2) when <= 0.
// ReplanInterval is the minimum simulation duration between automatic full A* replans.
// Zero allows immediate replanning whenever the corridor becomes invalid.
// MaxRepairDepth is the maximum number of adjacent bridge polygons searched locally when
// repairing a displaced corridor start or moved target before falling back to a full A* replan.
// Defaults to 2 when <= 0.
// Filter optionally restricts which polygons this agent may traverse and sets per-area costs.
// When nil, DefaultNavFilter() is used (all walkable non-disabled polygons at unit cost).
// OnLink is an optional callback invoked on each step while traversing an off-mesh link or
// crossing a flagged shared-edge portal. Return true when the transition is complete; return
// false to keep control of the agent on subsequent steps. When nil, off-mesh links traverse
// linearly at MaxSpeed and flagged shared-edge portals are crossed automatically.
}NavAgentConfig configures steering, arrival, corridor repair, replan throttling, and off-mesh link traversal for a 2D NavAgent.
type NavAgentGroup struct {
// contains filtered or unexported fields
}NavAgentGroup coordinates multiple 2D NavAgents with throttled, round-robin budgeted, and optionally staggered replanning so large groups chasing moving targets never spike a single frame.
func NewNavAgentGroup(cfg NavAgentGroupConfig) *NavAgentGroupNewNavAgentGroup constructs a NavAgentGroup with the given replan budget and staggering settings.
func (g *NavAgentGroup) Add(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgentAdd creates a new NavAgent, registers it in the group, and returns it.
func (g *NavAgentGroup) AddAgent(a *NavAgent)AddAgent attaches an existing NavAgent to the group.
func (g *NavAgentGroup) Agents() []*NavAgentAgents returns the group's agents in deterministic registration order.
func (g *NavAgentGroup) LastStepReplans() intLastStepReplans returns how many full A* replans executed during the most recent Step.
func (g *NavAgentGroup) Len() intLen returns the number of agents in the group.
func (g *NavAgentGroup) Remove(a *NavAgent) boolRemove detaches a from the group while preserving deterministic ordering of remaining agents.
func (g *NavAgentGroup) Step(dt time.Duration)Step advances every agent in the group by dt while strictly bounding full A* replans to MaxReplansPerStep in deterministic round-robin order.
func (g *NavAgentGroup) Steps() uint64Steps returns the number of times Step has advanced this group.
func (g *NavAgentGroup) TotalReplans() intTotalReplans returns the cumulative number of full A* replans executed by Step across all agents.
type NavAgentGroupConfig struct {
// MaxReplansPerStep caps how many agents perform a full A* replan in a single Step.
// Defaults to 4 when <= 0.
// ReplanInterval sets the minimum duration between full replans for agents whose own
// NavAgentConfig.ReplanInterval is 0.
// StaggerStride spreads full replan eligibility across steps using agentID%stride == step%stride.
// Defaults to 1 (every agent is eligible in round-robin order up to MaxReplansPerStep).
}NavAgentGroupConfig configures budgeted and staggered replanning across a group of 2D NavAgents.
type NavAgentState uint8NavAgentState reports the navigation status of a 2D NavAgent.
const (
// NavAgentIdle indicates the agent has no active navigation target.
// NavAgentMoving indicates the agent is actively following its polygon corridor toward its target.
// NavAgentArrived indicates the agent reached its target within StoppingDistance.
// NavAgentUnreachable indicates no valid corridor connects the agent to its target.
)func (s NavAgentState) String() stringString returns a human-readable state name.
type NavArea uint8NavArea identifies the surface or terrain category of a navigation polygon (for example road, grass, mud, water, or a door threshold). Area 0 is NavAreaDefault. Games may assign any custom uint8 ID up to 255.
const (
// NavAreaDefault is the default walkable area assigned by BuildNavMesh.
// NavAreaRoad marks fast-travel surfaces such as roads or paved paths.
// NavAreaGrass marks ordinary open ground.
// NavAreaMud marks slow or difficult terrain.
// NavAreaWater marks water surfaces typically paired with NavFlagSwim.
// NavAreaDoor marks dynamic doorway or gate polygons.
// NavAreaHazard marks hazardous ground such as traps, fire, or lava.
// NavAreaJump marks jump or drop-off off-mesh links and landing surfaces.
// NavAreaClimb marks climbable off-mesh links such as ladders and ledges.
// NavAreaTeleport marks teleporter or portal off-mesh links.
)type NavFilter struct {
// IncludeFlags requires a polygon to have at least one matching flag bit
// when non-zero. When zero, no inclusion bit is required.
// ExcludeFlags forbids any polygon with any matching flag bit set.
// AreaCosts overrides the traversal cost multiplier per NavArea.
// Omitted areas default to 1.0. Values <= 0, NaN, or ±Inf forbid traversal
// of that area.
// ExcludedAreas optionally forbids specific NavArea IDs regardless of flags.
}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() NavFilterDefaultNavFilter returns the default query filter matching BuildNavMesh defaults: every non-zero, non-disabled polygon is traversable at unit cost (1.0).
func (f NavFilter) Allows(area NavArea, flags NavFlags) boolAllows reports whether a polygon with the given area and flags passes the filter.
func (f NavFilter) AreaCost(area NavArea) float64AreaCost returns the traversal cost multiplier for area. Omitted areas return 1.0. Excluded areas or areas with non-positive, NaN, or infinite configured costs return +Inf.
func (f NavFilter) Clone() NavFilterClone returns an independent deep copy of f.
func (f *NavFilter) ExcludeArea(area NavArea)ExcludeArea marks area as non-traversable on f regardless of polygon flags.
func (f *NavFilter) IncludeArea(area NavArea)IncludeArea removes area from f's ExcludedAreas set.
func (f *NavFilter) SetAreaCost(area NavArea, cost float64)SetAreaCost sets the traversal cost multiplier for area on f.
type NavFlags uint32NavFlags is a bitmask of runtime traversal capabilities and states on a navigation polygon (such as walk, swim, door, jump, climb, teleport, or disabled).
const (
// NavFlagWalk marks standard ground-walkable polygons (default for BuildNavMesh).
// NavFlagSwim marks water polygons traversable by swimming agents.
// NavFlagDoor marks doorway or gate polygons that may open or close at runtime.
// NavFlagJump marks jump or drop-off traversal polygons and off-mesh links.
// NavFlagClimb marks climbable off-mesh links such as ladders.
// NavFlagTeleport marks teleporter or portal off-mesh links.
// NavFlagDisabled marks polygons or links disabled at runtime (excluded by DefaultNavFilter).
// NavFlagAll matches any non-zero flag bitmask.
)type NavLinkEvent struct {
}NavLinkEvent describes a flagged shared-edge or off-mesh link transition encountered by a NavAgent.
type NavListenerID uint64NavListenerID identifies a tile-change listener registered on a TiledNavMesh.
type NavMesh struct {
// contains filtered or unexported fields
}NavMesh is a 2D navigation mesh built from convex polygons connected across shared edges and optional point-to-point off-mesh links.
func BuildNavMesh(polys [][]core.Point) *NavMeshBuildNavMesh constructs a NavMesh from convex 2D polygons, normalizing winding order and automatically connecting adjacent polygons along shared edges (including partial collinear overlaps).
Each polygon is assigned NavAreaDefault and NavFlagWalk. Degenerate polygons with fewer than three vertices or near-zero area are skipped.
func BuildNavMeshWithAreas(polys []NavPolygonInput) *NavMeshBuildNavMeshWithAreas constructs a NavMesh from convex 2D polygons carrying per-polygon area IDs and runtime traversal flags, normalizing winding order and automatically connecting adjacent polygons along shared edges (including partial collinear overlaps).
Polygons with zero Flags default to NavFlagWalk. Degenerate polygons with fewer than three vertices or near-zero area are skipped.
func (m *NavMesh) AddOffMeshLink(link NavOffMeshLink) boolAddOffMeshLink connects the polygons containing (or within link.Radius of) link.Start and link.End with a directed (or bidirectional) off-mesh portal and bumps the mesh revision. Returns false if the mesh is nil, link coordinates or Radius are invalid, either endpoint cannot attach to the mesh, or both endpoints collapse to the same point on the same polygon.
func (m *NavMesh) AddPolygonFlags(index int, flags NavFlags)AddPolygonFlags sets the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (m *NavMesh) BumpRevision()BumpRevision increments the mesh revision so NavAgents watching this mesh invalidate cached corridors and replan.
func (m *NavMesh) ClearOffMeshLinks()ClearOffMeshLinks removes all off-mesh links from m and bumps the mesh revision when any were present.
func (m *NavMesh) ClearPolygonFlags(index int, flags NavFlags)ClearPolygonFlags clears the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (m *NavMesh) Contains(p core.Point) boolContains reports whether p lies inside or on the boundary of any polygon in the mesh.
func (m *NavMesh) ContainsWithFilter(p core.Point, filter NavFilter) boolContainsWithFilter reports whether p lies inside or on the boundary of any polygon passing filter.
func (m *NavMesh) FindCorridor(start, goal core.Point) ([]int, bool)FindCorridor finds the sequence of polygon indices from start to goal using DefaultNavFilter and portal-graph A*. Returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (m *NavMesh) FindCorridorInto(dst []int, start, goal core.Point) ([]int, bool)FindCorridorInto behaves like FindCorridor but writes polygon indices into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.
FindCorridorInto is not safe for concurrent use on the same NavMesh; use NewNavMeshQuery per goroutine.
func (m *NavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]int, bool)FindCorridorWithFilter finds the minimum-cost sequence of polygon indices from start to goal restricted to filter. Returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (m *NavMesh) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)FindCorridorWithFilterInto behaves like FindCorridorWithFilter but writes polygon indices into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.
func (m *NavMesh) FindPath(start, goal core.Point) ([]core.Point, bool)FindPath finds the shortest path inside the navigation mesh from start to goal using DefaultNavFilter, portal-graph A*, and Simple Stupid Funnel Algorithm string-pulling.
It returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (m *NavMesh) FindPathInto(dst []core.Point, start, goal core.Point) ([]core.Point, bool)FindPathInto behaves like FindPath but writes waypoints into dst[:0] and reuses the mesh's internal search buffers so repeated calls allocate zero heap memory once warmed up.
FindPathInto is not safe for concurrent use on the same NavMesh; construct separate NewNavMeshQuery instances when running concurrent path searches against a shared read-only NavMesh.
func (m *NavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)FindPathWithFilter finds the minimum-cost path inside the navigation mesh from start to goal restricted to polygons allowed by filter, weighting traversal through each polygon by filter.AreaCost(area) and using an admissible distance heuristic scaled by the minimum allowed area cost.
It returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (m *NavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResultFindPathWithFilterAndOptions finds a minimum-cost path inside the navigation mesh restricted to polygons allowed by filter under opts, supporting an expansion budget and optional partial paths.
func (m *NavMesh) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResultFindPathWithFilterAndOptionsInto behaves like FindPathWithFilterAndOptions but writes waypoints into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up. The returned res.Links slice reuses the mesh's internal query buffer (like dst) and is overwritten on subsequent queries.
func (m *NavMesh) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)FindPathWithFilterInto behaves like FindPathWithFilter but writes waypoints into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.
FindPathWithFilterInto is not safe for concurrent use on the same NavMesh; use NewNavMeshQuery per goroutine.
func (m *NavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) NavPathResultFindPathWithOptions finds a path inside the navigation mesh under DefaultNavFilter and opts, supporting an expansion budget and optional partial paths to the closest reachable point when goal is outside the mesh, in a disconnected region, or beyond MaxExpansions.
func (m *NavMesh) FindPolygon(p core.Point) intFindPolygon returns the lowest index of a polygon containing p (including its edges and vertices), or -1 if p lies outside the mesh.
func (m *NavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) intFindPolygonWithFilter returns the lowest index of a polygon passing filter that contains p (including its edges and vertices), or -1 if none match.
func (m *NavMesh) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)MoveAlongSurface slides an agent from start toward target while staying on polygons allowed by DefaultNavFilter.
Returns (NavMoveResult{Point: start, Poly: -1}, false) if start lies outside the allowed mesh.
func (m *NavMesh) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)MoveAlongSurfaceWithFilter slides an agent from start toward target while staying on polygons allowed by filter.
Returns (NavMoveResult{Point: start, Poly: -1}, false) if start lies outside the allowed mesh.
func (m *NavMesh) NearestPoint(p, extent core.Point) (point core.Point, poly int, ok bool)NearestPoint returns the closest point on any polygon allowed by DefaultNavFilter within the axis-aligned search half-extents [p.X-extent.X, p.X+extent.X] x [p.Y-extent.Y, p.Y+extent.Y], together with that polygon's index.
Returns (zero, -1, false) if m is empty, inputs are invalid/negative, or no allowed polygon point lies within extent.
func (m *NavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (point core.Point, poly int, ok bool)NearestPointWithFilter returns the closest point on any polygon allowed by filter within the axis-aligned search half-extents [p.X-extent.X, p.X+extent.X] x [p.Y-extent.Y, p.Y+extent.Y], together with that polygon's index.
Returns (zero, -1, false) if m is empty, inputs are invalid/negative, or no allowed polygon point lies within extent.
func (m *NavMesh) NearestPolygon(p core.Point) (index int, point core.Point, ok bool)NearestPolygon returns the polygon closest to p and the closest point on or inside that polygon. When p lies inside a polygon, NearestPolygon returns that polygon and p itself.
func (m *NavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (index int, point core.Point, ok bool)NearestPolygonWithFilter returns the polygon passing filter closest to p and the closest point on or inside that polygon. When p lies inside a matching polygon, NearestPolygonWithFilter returns that polygon and p itself.
func (m *NavMesh) Neighbors(index int) []intNeighbors returns the indices of polygons sharing an edge with polygon index.
func (m *NavMesh) OffMeshLinks() []NavOffMeshLinkOffMeshLinks returns a copy of all off-mesh links registered on m in insertion order.
func (m *NavMesh) Polygon(index int) []core.PointPolygon returns a copy of the vertices of polygon index, or nil if index is out of range.
func (m *NavMesh) PolygonArea(index int) NavAreaPolygonArea returns the area ID of polygon index, or NavAreaDefault if index is out of range.
func (m *NavMesh) PolygonCount() intPolygonCount returns the number of valid convex polygons in the mesh.
func (m *NavMesh) PolygonFlags(index int) NavFlagsPolygonFlags returns the runtime traversal flags of polygon index, or 0 if index is out of range.
func (m *NavMesh) RandomPoint(rng *random.Stream) (point core.Point, poly int, ok bool)RandomPoint picks an area-weighted uniformly random point anywhere on polygons allowed by DefaultNavFilter, using rng. Results are bit-identical across runs and platforms for the same seed.
Returns (zero, -1, false) if m is empty, rng is nil, or no polygons are allowed.
func (m *NavMesh) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (point core.Point, poly int, ok bool)RandomPointAround picks an area-weighted uniformly random point within Euclidean distance radius of center on polygons allowed by DefaultNavFilter that are reachable from center's polygon. Disconnected islands are never returned, and results are bit-identical across runs and platforms for the same seed.
Returns (zero, -1, false) if m is empty, rng is nil, radius < 0, or center lies outside the allowed mesh.
func (m *NavMesh) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)RandomPointAroundWithFilter behaves like RandomPointAround while restricting reachability and sampling to polygons allowed by filter.
func (m *NavMesh) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)RandomPointWithFilter picks an area-weighted uniformly random point anywhere on polygons allowed by filter, using rng. Results are bit-identical across runs and platforms for the same seed.
Returns (zero, -1, false) if m is empty, rng is nil, or no polygons pass filter.
func (m *NavMesh) Raycast(start, target core.Point) (NavRaycastHit, bool)Raycast casts a segment along the mesh surface from start toward target using DefaultNavFilter, walking shared-edge portals across allowed polygons until reaching target or hitting a boundary edge or disallowed polygon.
The second return value equals hit.Hit: false means unobstructed line of sight across the mesh (hit.T == 1, hit.Point == target, hit.Poly >= 0); true means the segment was obstructed (or start lies outside the allowed mesh, in which case hit.Poly == -1 and hit.T == 0).
func (m *NavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)RaycastWithFilter behaves like Raycast while restricting traversal to polygons allowed by filter.
func (m *NavMesh) Revision() uint64Revision returns a monotonically increasing number bumped whenever the mesh topology, area costs/flags, or link flags change.
func (m *NavMesh) SetEdgeFlags(fromPoly, toPoly int, flags uint32) boolSetEdgeFlags sets custom flags on the shared-edge portal from fromPoly to toPoly and bumps the mesh revision. Returns false if no shared-edge portal connects fromPoly to toPoly.
func (m *NavMesh) SetPolygonArea(index int, area NavArea)SetPolygonArea updates the area ID of polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (m *NavMesh) SetPolygonFlags(index int, flags NavFlags)SetPolygonFlags replaces the runtime traversal flags of polygon index without rebuilding the mesh. Out-of-range indices are ignored.
func (m *NavMesh) StartSearch(start, goal core.Point, opts PathOptions) *NavMeshSearchStartSearch begins an incremental 2D NavMesh path search from start to goal under DefaultNavFilter and opts.
func (m *NavMesh) StartSearchWithFilter(start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearchStartSearchWithFilter begins an incremental 2D NavMesh path search from start to goal under filter and opts.
type NavMeshGenerator struct {
// Mesh is the 2D navigation mesh to sample.
// Center selects the origin for MaxRadius filtering (defaults to OriginQuerier).
// CustomCenter is used when Center is OriginCustom.
// MaxRadius restricts samples to within MaxRadius of Center (<= 0 samples the whole mesh).
// Spacing sets the world spacing between grid samples inside the mesh (<= 0 emits polygon centroids).
}NavMeshGenerator emits deterministic sample points lying inside a 2D NavMesh.
When Spacing > 0, it samples a regular grid clipped to the mesh bounds (and optional MaxRadius) keeping every point contained in the mesh. When Spacing <= 0, it emits each polygon's centroid.
func (g *NavMeshGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidateGenerate appends NavMesh sample candidates in deterministic order with zero heap allocations.
type NavMeshQuery struct {
// contains filtered or unexported fields
}NavMeshQuery holds reusable generation-stamped scratch buffers for zero-allocation pathfinding and spatial queries over a 2D NavMesh.
Create one NavMeshQuery per worker or system with NewNavMeshQuery(mesh) when running repeated queries or querying a shared read-only NavMesh from separate goroutines. A NavMeshQuery is not safe for concurrent use by multiple goroutines.
func NewNavMeshQuery(mesh *NavMesh) *NavMeshQueryNewNavMeshQuery creates a reusable query instance bound to mesh.
func (q *NavMeshQuery) FindCorridorInto(dst []int, start, goal core.Point) ([]int, bool)FindCorridorInto finds the polygon corridor from start to goal under DefaultNavFilter, writing polygon indices into dst[:0] with zero heap allocations after warm-up.
func (q *NavMeshQuery) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)FindCorridorWithFilterInto finds the minimum-cost polygon corridor from start to goal restricted to filter, writing polygon indices into dst[:0] with zero heap allocations after warm-up.
func (q *NavMeshQuery) FindPathInto(dst []core.Point, start, goal core.Point) ([]core.Point, bool)FindPathInto finds the shortest path inside q's mesh from start to goal using DefaultNavFilter, writing waypoints into dst[:0] and reusing q's internal buffers so repeated calls perform zero heap allocations once dst and q are warmed up.
func (q *NavMeshQuery) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResultFindPathWithFilterAndOptionsInto runs a bounded or partial 2D NavMesh search restricted to filter under opts, writing the resulting waypoints into dst[:0] and reusing q's internal buffers with zero heap allocations after warm-up. The returned res.Links slice reuses q's internal buffer (like dst) and is overwritten on subsequent queries on q.
func (q *NavMeshQuery) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)FindPathWithFilterInto finds the minimum-cost path inside q's mesh from start to goal restricted to filter, writing waypoints into dst[:0] and reusing q's internal buffers with zero heap allocations after warm-up.
func (q *NavMeshQuery) Mesh() *NavMeshMesh returns the NavMesh currently bound to q.
func (q *NavMeshQuery) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)MoveAlongSurface delegates to q's NavMesh.MoveAlongSurface.
func (q *NavMeshQuery) MoveAlongSurfaceInto(visitedDst []int, start, target core.Point) (NavMoveResult, bool)MoveAlongSurfaceInto slides from start toward target under DefaultNavFilter, appending visited polygon IDs into visitedDst[:0].
func (q *NavMeshQuery) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)MoveAlongSurfaceWithFilter delegates to q's NavMesh.MoveAlongSurfaceWithFilter.
func (q *NavMeshQuery) MoveAlongSurfaceWithFilterInto(visitedDst []int, start, target core.Point, filter NavFilter) (NavMoveResult, bool)MoveAlongSurfaceWithFilterInto slides from start toward target under filter, appending visited polygon IDs into visitedDst[:0].
func (q *NavMeshQuery) NearestPoint(p, extent core.Point) (core.Point, int, bool)NearestPoint delegates to q's NavMesh.NearestPoint.
func (q *NavMeshQuery) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, int, bool)NearestPointWithFilter delegates to q's NavMesh.NearestPointWithFilter.
func (q *NavMeshQuery) RandomPoint(rng *random.Stream) (core.Point, int, bool)RandomPoint delegates to q's NavMesh.RandomPoint.
func (q *NavMeshQuery) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (core.Point, int, bool)RandomPointAround picks a random reachable point within radius of center using q's reusable BFS and clipping buffers.
func (q *NavMeshQuery) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (core.Point, int, bool)RandomPointAroundWithFilter picks a random reachable point within radius of center allowed by filter using q's reusable buffers.
func (q *NavMeshQuery) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (core.Point, int, bool)RandomPointWithFilter delegates to q's NavMesh.RandomPointWithFilter.
func (q *NavMeshQuery) Raycast(start, target core.Point) (NavRaycastHit, bool)Raycast delegates to q's NavMesh.Raycast.
func (q *NavMeshQuery) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)RaycastWithFilter delegates to q's NavMesh.RaycastWithFilter.
func (q *NavMeshQuery) SetMesh(mesh *NavMesh)SetMesh rebinds q to mesh while keeping its allocated scratch capacity for reuse.
type NavMeshSearch struct {
// contains filtered or unexported fields
}NavMeshSearch runs a deterministic 2D NavMesh portal A* search incrementally across bounded Step calls.
Stepping a search with any positive per-step expansion budget produces the exact same path, links, partial flag, and expansion count as NavMesh.FindPathWithOptions / FindPathWithFilterAndOptions. *NavMeshSearch implements IncrementalSearch.
func NewNavMeshSearch(m *NavMesh, start, goal core.Point, opts PathOptions) *NavMeshSearchNewNavMeshSearch initializes an incremental 2D NavMesh search from start to goal under DefaultNavFilter and opts.
func NewNavMeshSearchWithFilter(m *NavMesh, start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearchNewNavMeshSearchWithFilter initializes an incremental 2D NavMesh search from start to goal under filter and opts.
func (s *NavMeshSearch) Expansions() intExpansions returns the cumulative number of portal nodes expanded so far.
func (s *NavMeshSearch) Result() NavPathResultResult returns the search outcome once finished (or a result with Found == false while still in progress).
func (s *NavMeshSearch) Status() SearchStatusStatus returns the search's current status.
func (s *NavMeshSearch) Step(maxExpansions int) (status SearchStatus, expansions int)Step advances the search by at most maxExpansions portal node expansions and returns the updated status and exact number of expansions performed. When maxExpansions <= 0 or the search is already finished, Step performs 0 expansions.
type NavMoveResult struct {
// Point is the final position clamped onto the mesh surface.
// Poly is the index of the final polygon containing Point, or -1 if start lies outside the allowed mesh.
// Visited is the ordered sequence of polygon indices traversed from start to Point.
// HitBoundary is true if movement was constrained by a mesh boundary edge or disallowed polygon.
}NavMoveResult describes the outcome of sliding a position across a 2D NavMesh surface.
type NavObstacle struct {
}NavObstacle describes a temporary runtime obstacle applied to a 2D TiledNavMesh.
func NavBoxObstacle(minPt, maxPt core.Point) NavObstacleNavBoxObstacle constructs an axis-aligned 2D box obstacle spanning [minPt, maxPt].
func NavCircleObstacle(center core.Point, radius float32) NavObstacleNavCircleObstacle constructs a 2D circular obstacle centered at center with radius.
func NavOrientedBoxObstacle(center, halfExtents core.Point, angleRad float32) NavObstacleNavOrientedBoxObstacle constructs a rotated 2D box obstacle centered at center with halfExtents and rotation angleRad.
func NavPolygonObstacle(verts []core.Point) NavObstacleNavPolygonObstacle constructs a 2D polygonal obstacle (convex or concave) from verts.
type NavObstacleID uint64NavObstacleID identifies a dynamic obstacle registered on a TiledNavMesh.
type NavObstacleKind uint8NavObstacleKind selects the geometric shape of a 2D NavObstacle.
const (
// NavObstacleBox is an axis-aligned or rotated 2D box (Center, HalfExtents, Angle).
// NavObstacleCircle is a 2D circle approximated by a circumscribed regular polygon (Center, Radius, Segments).
// NavObstaclePolygon is an arbitrary simple 2D polygon (Vertices, convex or concave).
)type NavObstacleMode uint8NavObstacleMode selects how a dynamic obstacle modifies walkable polygons in touched tiles.
const (
// NavObstacleCarve subtracts the obstacle footprint from walkable polygons so paths detour around it.
// NavObstacleMark splits walkable polygons along the obstacle footprint and applies Area/Flags
// (defaulting to NavFlagDisabled when both Area and Flags are zero) to the covered polygons.
)type NavOffMeshLink struct {
// Start and End are the world-space endpoints on (or within Radius of) the mesh.
// Radius is the optional endpoint snap and agent entry tolerance in world units.
// When positive, an endpoint outside a polygon snaps to the nearest polygon point within Radius,
// and NavAgent uses max(entryRadius, Radius) when entering the link.
// When zero, endpoints must lie on or inside a polygon. Negative or non-finite values are rejected.
// Bidirectional adds portals in both Start->End and End->Start directions when true.
// Flags stores game-defined link flags; NavLinkOffMesh is always set automatically.
// ID is an optional game-defined link identifier delivered in NavLinkEvent.LinkID and NavPathLink.LinkID.
// Cost overrides the A* traversal cost when positive; <= 0 uses Euclidean distance.
// Area assigns a NavArea to the link so NavFilter can exclude it or scale its traversal cost.
// Defaults to NavAreaDefault (0).
// UserData holds optional game-defined metadata (such as "jump", "ladder", "teleport", or a custom value)
// carried through to NavPathLink and NavLinkEvent.
}NavOffMeshLink describes a custom off-mesh connection between two points on a 2D NavMesh (such as a jump, drop-down, ladder, door, or teleporter).
type NavPathLink struct {
// StartIndex is the index in NavPathResult.Path where the off-mesh link begins.
// EndIndex is the index in NavPathResult.Path where the off-mesh link ends (StartIndex + 1).
// 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 is the link's configured connection/entry radius.
// Area is the link's navigation area.
// Flags are the link's flags (including NavLinkOffMesh).
// LinkID is the link's configured identifier.
// UserData is the link's configured custom metadata.
}NavPathLink marks a segment in NavPathResult.Path that traverses an off-mesh link. Path[StartIndex] is the link's entry point on the mesh and Path[EndIndex] is its exit point (with EndIndex == StartIndex + 1).
type NavPathResult struct {
// 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 (r NavPathResult) HasLinks() boolHasLinks reports whether r traverses at least one off-mesh link.
func (r NavPathResult) LinkAt(segmentIndex int) (NavPathLink, bool)LinkAt returns the off-mesh link traversed by path segment segmentIndex (from Path[segmentIndex] to Path[segmentIndex+1]), or (zero, false) when that segment is ordinary walking movement.
type NavPathWatchID uint64NavPathWatchID identifies a path-invalidation watcher registered on a TiledNavMesh.
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 (r NavPolyRef) Valid() boolValid reports whether r holds a non-zero tile salt and non-negative polygon index.
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 struct {
// Point is the impact point on the obstructing edge when Hit is true,
// or target when the ray reaches target unobstructed (Hit is false).
// Normal is the unit inward normal of the boundary edge that stopped the ray
// (pointing back into the walkable polygon, opposing the ray direction), or zero when Hit is false or Poly < 0.
// Poly is the index of the polygon containing Point, or -1 if start lies outside the allowed mesh.
// T is the normalized distance along start->target in [0, 1].
// T is 1 when target is reached unobstructed; T is 0 when start is outside the allowed mesh.
// Hit is true if a mesh boundary edge or disallowed polygon obstructed the ray (or if start is outside the allowed mesh).
}NavRaycastHit describes the result of casting a segment along a 2D NavMesh surface.
type NavTile struct {
// contains filtered or unexported fields
}NavTile is an independently baked 2D navigation tile covering a fixed square region [minX, maxX] x [minY, maxY]. A NavTile may be baked off the main thread with BakeNavTile and installed into a TiledNavMesh with AddTile, ReplaceTile, or SetTile.
func BakeNavTile(coord NavTileCoord, tileSize float32, origin core.Point, polys []NavPolygonInput) *NavTileBakeNavTile bakes an independent 2D NavTile for coord from convex walkable polygons polys, clipping every polygon to the tile's exact bounds [origin + coord*tileSize, origin + (coord+1)*tileSize]. Degenerate polygons or polygons outside the tile bounds are omitted. BakeNavTile is pure and safe to call concurrently from worker goroutines.
func (t *NavTile) BasePolygonCount() intBasePolygonCount returns the number of base walkable polygons baked into this tile.
func (t *NavTile) Bounds() (minPt, maxPt core.Point)Bounds returns the world-space [min, max] rectangle of this tile.
func (t *NavTile) Coord() NavTileCoordCoord returns the tile coordinate this tile was baked for.
type NavTileChange struct {
}NavTileChange describes a single tile mutation event delivered to tile listeners and path watchers.
type NavTileChangeKind uint8NavTileChangeKind classifies why a tile in a TiledNavMesh changed.
const (
// NavTileAdded indicates a tile was inserted into a previously empty coordinate.
// NavTileUpdated indicates an existing tile was replaced or rebuilt (for example due to a dynamic obstacle).
// NavTileRemoved indicates an existing tile was removed from the mesh.
)type NavTileCoord struct {
}NavTileCoord identifies a fixed-size tile in a 2D TiledNavMesh.
type NavTileVersion struct {
}NavTileVersion records a tile coordinate together with its revision number when a path was computed.
type NeighborGrid struct {
// contains filtered or unexported fields
}NeighborGrid is a deterministic 2D uniform spatial hash index for fast, zero-allocation neighbor queries during flocking.
After an initial warm-up step, Rebuild, Query, and QueryInto reuse all internal slices and perform zero heap allocations per step.
func NewNeighborGrid(cellSize float32) *NeighborGridNewNeighborGrid returns a 2D NeighborGrid with the given spatial cell size. Cell sizes less than or equal to 0 default to 32.
func (g *NeighborGrid) Query(pos core.Point, radius float32) []AgentQuery returns all indexed agents within radius of pos using an internal scratch slice owned by g. The returned slice is overwritten by subsequent Query calls; use QueryInto to write into a caller-owned buffer.
func (g *NeighborGrid) QueryInto(dst []Agent, pos core.Point, radius float32) []AgentQueryInto writes all indexed agents within radius of pos into dst[:0] and returns the resulting slice.
func (g *NeighborGrid) Rebuild(agents []Agent)Rebuild indexes agents into g, reusing internal buffers with zero heap allocations once warmed up for a given agent count.
type NeighborGrid3D struct {
// contains filtered or unexported fields
}NeighborGrid3D is a deterministic 3D (or XZ-planar) uniform spatial hash index for fast, zero-allocation neighbor queries during 3D flocking.
func NewNeighborGrid3D(cellSize float32, planarXZ bool) *NeighborGrid3DNewNeighborGrid3D returns a 3D NeighborGrid3D with the given cell size. When planarXZ is true, indexing and radius queries project onto the XZ plane. Cell sizes less than or equal to 0 default to 32.
func (g *NeighborGrid3D) Query(pos Vec3, radius float32) []Agent3DQuery returns all indexed agents within radius of pos using an internal scratch slice owned by g.
func (g *NeighborGrid3D) QueryInto(dst []Agent3D, pos Vec3, radius float32) []Agent3DQueryInto writes all indexed agents within radius of pos into dst[:0] and returns the resulting slice.
func (g *NeighborGrid3D) Rebuild(agents []Agent3D)Rebuild indexes agents into g, reusing internal buffers with zero heap allocations once warmed up.
type Node interface {
// Tick advances the node by dt and returns its current status.
Tick(dt time.Duration) Status
// Reset clears any in-progress state on this node and its descendants.
Reset()
}Node is one node in a behavior tree.
func Action(fn func(dt time.Duration) Status) NodeAction wraps fn as a leaf node.
func BlackboardCondition(bb *Blackboard, key string, op BlackboardOp, value BlackboardValue, abort AbortMode, child Node) NodeBlackboardCondition evaluates key on bb using op and value, optionally wrapping child as a decorator (when child is nil, it acts as a condition leaf returning StatusSuccess when the condition holds and StatusFailure otherwise).
When abort is AbortSelf or AbortBoth, a key change that falsifies the condition while child is running resets child and returns StatusFailure on the next tick. When abort is AbortLower or AbortBoth, a key change that makes the condition true while a lower-priority sibling in an enclosing Selector is running aborts that lower-priority sibling on the next tick.
func BuildBehaviorTree(doc *BehaviorTreeDoc, bind BTBindings) (Node, error)BuildBehaviorTree validates doc, seeds any unset declared blackboard defaults, resolves subtrees and bindings, and returns the executable Node tree.
func BuildBehaviorTreeFS(fsys fs.FS, name string, bind BTBindings) (Node, error)BuildBehaviorTreeFS loads the behavior tree at name in fsys and builds its runtime Node.
func Condition(fn func() bool) NodeCondition wraps predicate fn as a leaf node returning StatusSuccess when true and StatusFailure when false.
func Cooldown(d time.Duration, child Node) NodeCooldown prevents child from starting again for duration d after it succeeds, returning StatusFailure while cooling down.
func Failer(child Node) NodeFailer turns both StatusSuccess and StatusFailure from child into StatusFailure while passing StatusRunning through.
func Guard(cond func() bool, child Node) NodeGuard ticks child only while cond returns true; if cond becomes false while child is running, Guard resets child and returns StatusFailure.
func HasAttackToken(pool *TokenPool, agentID uint64) NodeHasAttackToken returns a Condition behavior tree node that succeeds while agentID holds a token in pool.
func Inverter(child Node) NodeInverter flips StatusSuccess and StatusFailure from child while passing StatusRunning through unchanged.
func Named(name string, child Node) NodeNamed attaches an optional human-readable name to child for inspection, debug overlays, and statedump formatting.
Named is transparent to tree topology: inspecting a Named built-in node reports a single entry with child's Kind and children and the given Name. Wrapping a custom Node also records its last Tick status for inspection. If name is empty, Named returns child unchanged.
func Parallel(policy ParallelPolicy, children ...Node) NodeParallel ticks all still-running children each tick and finishes according to policy, resetting any remaining running children on completion.
func RandomSelector(stream *random.Stream, children ...Node) NodeRandomSelector tries children in a shuffled order drawn from stream at the start of each run, returning on the first child that succeeds or runs.
When a child returns StatusRunning, RandomSelector keeps the chosen order and resumes that child on subsequent ticks; if that child later fails, evaluation continues with the remaining untried children in the shuffled order. A nil stream falls back to declaration order.
func RandomSequence(stream *random.Stream, children ...Node) NodeRandomSequence runs children in a shuffled order drawn from stream at the start of each run, succeeding when every child succeeds and failing on the first failure.
When a child returns StatusRunning, RandomSequence keeps the chosen order and resumes at that child on subsequent ticks until completion or Reset. A nil stream falls back to declaration order.
func Repeater(count int, child Node) NodeRepeater runs child until it succeeds count times, returning StatusRunning between iterations and StatusFailure immediately if child fails.
When count is less than or equal to 0, Repeater repeats indefinitely until child fails.
func Retry(n int, child Node) NodeRetry reruns a failing child up to n additional times (up to 1+n total attempts).
Like Repeater, Retry ticks child at most once per Tick, returning StatusRunning between failed attempts and StatusSuccess as soon as child succeeds. When n <= 0, no retries are performed and a child failure returns StatusFailure immediately.
func Selector(children ...Node) NodeSelector tries children in priority order, returning on the first child that succeeds or runs.
If a higher-priority child preempts a lower-priority child that was previously running, Selector resets the interrupted child. Higher-priority children guarded by a BlackboardCondition only preempt a running lower-priority branch when their abort mode includes AbortLower or AbortBoth and their watched key changes.
func Sequence(children ...Node) NodeSequence runs children in order, succeeding when all succeed and failing on the first failure.
When a child returns StatusRunning, Sequence remembers its position and resumes at that child on the next tick.
func Service(interval time.Duration, fn func(dt time.Duration), child Node) NodeService invokes fn immediately on entry into child and then every interval of game time while child remains StatusRunning, before ticking child.
On entry, fn receives the tick's dt; on subsequent periodic ticks, fn receives the elapsed game time since fn last ran (preserving phase across non-divisor steps and firing at most once per Tick). When interval <= 0, fn runs on every tick while active. Finishing (StatusSuccess or StatusFailure) or calling Reset stops the service so the next activation runs fn on entry again.
func SquadHasOrder(squad *Squad, kind string) NodeSquadHasOrder returns a Condition behavior tree node that succeeds when squad has an active order matching kind (or any non-empty order when kind is "").
func SquadHasRole(squad *Squad, agentID uint64, role string) NodeSquadHasRole returns a Condition behavior tree node that succeeds when agentID holds role in squad.
func SquadOrderAction(squad *Squad, fn func(order SquadOrder, dt time.Duration) Status) NodeSquadOrderAction returns an Action behavior tree node that reads squad's current SquadOrder and invokes fn(order, dt). It returns StatusFailure when squad or fn is nil or no order is active.
func SquadStateBool(squad *Squad, key string) NodeSquadStateBool returns a Condition behavior tree node that succeeds when squad's shared state holds a true bool value under key.
func Succeeder(child Node) NodeSucceeder turns both StatusSuccess and StatusFailure from child into StatusSuccess while passing StatusRunning through.
func TimeLimit(d time.Duration, child Node) NodeTimeLimit ticks child and enforces a maximum duration d of game time for one run.
If child is still returning StatusRunning once accumulated dt reaches d (or immediately when d <= 0), TimeLimit calls child.Reset(), clears its timer, and returns StatusFailure. Completing with StatusSuccess or StatusFailure, or calling Reset, clears the elapsed timer.
func UntilFail(child Node) NodeUntilFail ticks child once per tick, returning StatusRunning until child returns StatusFailure, at which point UntilFail returns StatusSuccess.
func UtilitySelector[C any](reasoner *Reasoner[C], ctx func() C, rng *random.Stream, subtrees map[string]Node) NodeUtilitySelector creates a behavior tree Node that uses reasoner to pick an action on each Tick and runs that action's bound subtree from subtrees (keyed by UtilityAction.Name).
Each UtilitySelector tracks its own active action for momentum, so multiple agents can share one Reasoner safely. When a different action beats a currently running subtree, the interrupted subtree is Reset before the newly chosen subtree is ticked. If no action scores above 0 or the chosen action has no subtree, Tick returns StatusFailure.
func Wait(d time.Duration) NodeWait returns StatusRunning until the accumulated dt reaches d, then resets and returns StatusSuccess.
func WeightedSelector(stream *random.Stream, options ...WeightedNode) NodeWeightedSelector draws children without replacement from stream with probability proportional to each WeightedNode.Weight until one returns StatusSuccess or StatusRunning.
When a drawn child returns StatusRunning, WeightedSelector resumes that child on subsequent ticks; if it later returns StatusFailure, drawing continues among the remaining untried eligible options. Options with non-positive, NaN, or infinite weight (or nil Node) are skipped. When stream is nil, eligible options are tried in descending Weight order (ties broken in declaration order).
func WithAttackToken(pool *TokenPool, agentID uint64, priority func() float64, child Node) NodeWithAttackToken returns a behavior tree decorator that requests an attack token for agentID on pool (evaluating priority on each tick if non-nil, else 0) and ticks child only while agentID holds a token.
While waiting for a token, or if the token is preempted, WithAttackToken resets child (if it was running) and returns StatusFailure so a parent Selector can fall back to circling or holding position. When child finishes with StatusSuccess or StatusFailure, WithAttackToken releases the token back to pool. Calling Reset cancels any pending request or releases the held token.
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 Noise struct {
// Source identifies what made the noise; the memory of it is kept under this ID.
Source StimulusID
// Team is the source's team.
Team Team
// Pos is where the noise was made.
Pos core.Point
// Loudness scales each listener's hearing range: a noise of loudness 2 is heard twice as far as one of loudness 1. Zero or less is inaudible.
Loudness float32
}Noise is a sound posted to a PerceptionSystem and heard on its next Step.
type ORCAAgent struct {
// ID optionally identifies the agent for canonical tie-breaking when agents overlap or coincide.
ID uint64
// Pos is the agent's current 2D position.
Pos math2d.Vec2
// Vel is the agent's current 2D velocity.
Vel math2d.Vec2
// PrefVel is the agent's desired 2D velocity before local avoidance.
PrefVel math2d.Vec2
// Radius is the agent's body radius.
Radius float32
// MaxSpeed caps the magnitude of the computed collision-free velocity.
MaxSpeed float32
// Priority controls reciprocal avoidance responsibility. Higher-priority agents yield less
// to lower-priority agents; equal priorities split avoidance 50/50. Negative or non-finite
// values are treated as 0.
Priority float32
// Stationary marks an agent holding its position: it outputs zero velocity and forces
// avoiding neighbors to take full responsibility for steering around it.
Stationary bool
// Layer is a bitmask of avoidance layers this agent occupies (0 defaults to ORCALayerDefault).
Layer uint32
// Mask is a bitmask of avoidance layers this agent avoids (0 defaults to ORCAMaskAll).
Mask uint32
}ORCAAgent describes a 2D agent participating in ORCA velocity-based local avoidance.
type ORCAAgent3D struct {
ID uint64
Pos Vec3
Vel Vec3
PrefVel Vec3
Radius float32
MaxSpeed float32
Priority float32
Stationary bool
Layer uint32
Mask uint32
}ORCAAgent3D describes a 3D agent performing ORCA local avoidance on the horizontal XZ plane (matching ai.Vec3 / math3d.Vec3 with +X right, +Y up, -Z forward).
type ORCAConfig struct {
// TimeHorizon is how far ahead (in seconds) agents anticipate collisions with other agents.
// Defaults to DefaultORCATimeHorizon (2.0) when <= 0 or non-finite.
TimeHorizon float32
// TimeHorizonObst is how far ahead (in seconds) agents anticipate collisions with static obstacle edges.
// Defaults to DefaultORCATimeHorizonObst (1.0) when <= 0 or non-finite.
TimeHorizonObst float32
// NeighborDist is the maximum center-to-center distance to consider neighboring agents.
// When <= 0 or non-finite, the solver derives a conservative search radius per agent from
// its speed, body radius, and TimeHorizon.
NeighborDist float32
// MaxNeighbors caps how many nearest matching neighbors contribute ORCA half-planes per agent.
// Defaults to DefaultORCAMaxNeighbors (16) when <= 0.
MaxNeighbors int
// CellSize is the spatial hash cell size used during batch Solve/Step queries.
// When <= 0 or non-finite, it is derived automatically from NeighborDist or agent speeds and radii.
CellSize float32
}ORCAConfig tunes an ORCASolver. Zero or non-finite fields use sensible defaults.
type ORCAObstacle struct {
A, B math2d.Vec2
// Layer is a bitmask of avoidance layers this obstacle occupies (0 defaults to ORCAMaskAll).
Layer uint32
}ORCAObstacle is a static 2D line-segment obstacle from A to B. Segments are treated as two-sided so agents stay clear regardless of endpoint order.
type ORCAObstacle3D struct {
A, B Vec3
Layer uint32
}ORCAObstacle3D is a static vertical obstacle wall segment projected onto the horizontal XZ plane.
type ORCASolver struct {
// contains filtered or unexported fields
}ORCASolver computes collision-free 2D (and 3D XZ-plane) velocities using Optimal Reciprocal Collision Avoidance (ORCA / RVO2). It reuses internal spatial-hash and linear-programming scratch buffers across calls for zero heap allocations after warm-up, and canonicalizes neighbor and obstacle ordering so results are deterministic and independent of input order.
A zero-value ORCASolver is ready to use with default settings. ORCASolver is not safe for concurrent use.
func NewORCASolver(cfg ORCAConfig) *ORCASolverNewORCASolver creates an ORCASolver configured with cfg.
func (s *ORCASolver) Config() ORCAConfigConfig returns the solver's effective configuration with defaults applied.
func (s *ORCASolver) SetConfig(cfg ORCAConfig)SetConfig updates the solver's configuration.
func (s *ORCASolver) Solve(dst []math2d.Vec2, agents []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration) []math2d.Vec2Solve computes collision-free 2D velocities for every agent in agents and appends them to dst[:0]. Neighbor lookups use an internal spatial hash grid; results are deterministic and independent of input order.
func (s *ORCASolver) SolveAgent(agent ORCAAgent, neighbors []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration) math2d.Vec2SolveAgent computes a single collision-free 2D velocity for agent given its neighbors and optional static obstacle edges. Results are deterministic and independent of the order of neighbors or obstacles.
func (s *ORCASolver) SolveAgentXZ(agent ORCAAgent3D, neighbors []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration) Vec3SolveAgentXZ computes a collision-free horizontal XZ-plane velocity for a 3D agent. The returned velocity has Y = 0; X and Z map directly to the 2D ORCA plane.
func (s *ORCASolver) SolveXZ(dst []Vec3, agents []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration) []Vec3SolveXZ computes collision-free horizontal XZ-plane velocities for all 3D agents and appends them to dst[:0]. Returned velocities have Y = 0.
func (s *ORCASolver) Step(agents []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration)Step computes collision-free 2D velocities for all agents and synchronously integrates Vel and Pos by dt. Stationary agents keep zero velocity and fixed position.
func (s *ORCASolver) StepXZ(agents []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration)StepXZ computes collision-free XZ-plane velocities for all 3D agents and integrates Pos.X and Pos.Z by dt, preserving Pos.Y and zeroing Vel.Y.
type Obstacle struct {
Center core.Point
Radius float32
}Obstacle is a circular 2D obstacle used by ObstacleAvoidance and Hide.
type Obstacle3D struct {
Center Vec3
Radius float32
}Obstacle3D is a spherical 3D obstacle (or vertical cylinder on XZ when the steering agent has PlanarXZ set) used by ObstacleAvoidance3D and Hide3D.
type ParallelPolicy uint8ParallelPolicy chooses when a Parallel composite finishes.
const (
// RequireAll succeeds when every child succeeds and fails as soon as any child fails.
RequireAll ParallelPolicy = iota
// RequireOne succeeds as soon as any child succeeds and fails when every child fails.
RequireOne
)type PathDistanceTest struct {
// From selects the path start point (defaults to OriginQuerier).
From QueryOrigin
// CustomFrom is used when From is OriginCustom.
CustomFrom math2d.Vec2
// PathCost optionally computes path distance directly via a game-supplied callback.
// When non-nil, it takes precedence over Grid and NavMesh.
PathCost func(from, to math2d.Vec2) (cost float64, ok bool)
// Grid and AStar run zero-allocation grid A* pathfinding when PathCost is nil and Grid is non-nil.
// If AStar is nil, TacticalQuery uses its internal reusable AStar searcher.
Grid Grid
GridOrigin math2d.Vec2
CellSize float32
AStar *AStar
// NavMesh computes zero-allocation funnel-smoothed path length when PathCost and Grid are nil.
// Purpose selects filtering, scoring, or both (defaults to TestFilterAndScore).
Purpose TestPurpose
// Filter optionally restricts acceptable path lengths.
Filter FloatRange
// NormMin and NormMax optionally specify fixed normalization bounds.
// When NormMax <= NormMin, values normalize dynamically across surviving candidates.
NormMin, NormMax float64
// Weight scales the normalized [0, 1] score contribution.
Weight float64
// Invert flips the normalized score (1 - norm) so shorter paths score higher.
Invert bool
}PathDistanceTest measures path travel cost from a starting position to each candidate using a custom callback, an ai.Grid with AStar, or a 2D NavMesh.
Each path lookup consumes one path query from ctx.Budget (when non-nil). When the budget is exhausted, remaining candidates are skipped (dropped if filtering, or scored 0 if TestScoreOnly).
type PathFollowState struct {
Index int
Done bool
}PathFollowState tracks which waypoint an agent is currently heading toward.
type PathOptions struct {
// MaxExpansions caps the number of search nodes expanded before stopping.
// Zero means unlimited expansions (for AStar, zero falls back to AStar.MaxExpansions when > 0);
// a negative value always forces unlimited expansions.
MaxExpansions int
// AllowPartial returns a path to the explored node closest to the goal when
// the goal is unreachable or MaxExpansions is reached, flagged with Partial = true.
AllowPartial bool
}PathOptions configures bounded and partial pathfinding queries across grid A* and 2D/3D navigation meshes.
type PathQueue struct {
// contains filtered or unexported fields
}PathQueue services multiple incremental path searches within a strict per-step node-expansion budget.
All scheduling is deterministic, single-threaded, and free of background goroutines.
func NewPathQueue(cfg PathQueueConfig) *PathQueueNewPathQueue returns a new PathQueue with the given configuration.
func (q *PathQueue) Cancel(id PathRequestID) boolCancel removes a pending request from the queue. It returns true if the request was found and removed; canceled requests are not stepped again and their callbacks are not invoked.
func (q *PathQueue) Clear()Clear removes all pending requests without invoking callbacks.
func (q *PathQueue) Completed() intCompleted returns the cumulative number of requests that finished (complete, partial, or failed).
func (q *PathQueue) IsPending(id PathRequestID) boolIsPending reports whether id is currently queued and has not finished or been canceled.
func (q *PathQueue) Pending() intPending returns the number of active requests currently waiting in the queue.
func (q *PathQueue) Step(budget int) intStep advances queued requests using at most budget total node expansions, returning the exact number of expansions performed (always in [0, budget] when budget > 0, or 0 when budget <= 0).
func (q *PathQueue) StepDefault() intStepDefault advances queued requests using the queue's configured DefaultBudget.
func (q *PathQueue) Submit(search IncrementalSearch, priority int, onDone func(PathRequestID, SearchStatus)) PathRequestIDSubmit enqueues search with the given priority (higher values run first; ties break in FIFO submission order). When the search reaches a terminal status during Step, onDone (if non-nil) is invoked synchronously with the request ID and final status.
Submitting a nil search is ignored and returns 0.
func (q *PathQueue) SubmitGrid(a *AStar, g Grid, start, goal Cell, opts PathOptions, priority int, onDone func(PathRequestID, GridPathResult)) (PathRequestID, *AStarSearch)SubmitGrid creates an incremental AStarSearch and enqueues it on q, returning the request ID (for Cancel) and the search handle (for polling Status/Result). If onDone is non-nil, it is called with the completed GridPathResult once the search finishes.
func (q *PathQueue) SubmitNavMesh(m *NavMesh, start, goal core.Point, opts PathOptions, priority int, onDone func(PathRequestID, NavPathResult)) (PathRequestID, *NavMeshSearch)SubmitNavMesh creates an incremental NavMeshSearch and enqueues it on q, returning the request ID (for Cancel) and the search handle (for polling Status/Result). If onDone is non-nil, it is called with the completed NavPathResult once the search finishes.
func (q *PathQueue) TotalExpansions() intTotalExpansions returns the cumulative number of node expansions performed across all Step calls.
type PathQueueConfig struct {
// DefaultBudget is the per-step expansion budget used by StepDefault.
DefaultBudget int
// Policy selects FIFO (default) or fair round-robin scheduling within each priority tier.
Policy PathQueuePolicy
// SliceSize caps the expansions granted per turn in PathQueueRoundRobin mode.
// Zero or negative divides the remaining step budget evenly across requests in the active priority tier.
SliceSize int
}PathQueueConfig configures a PathQueue.
type PathQueuePolicy uint8PathQueuePolicy 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 uint64PathRequestID uniquely identifies a request submitted to a PathQueue. Zero is never assigned to a valid request.
type Perception struct {
// Self is the agent's own StimulusID, so the agent never senses itself; zero means the agent is not a stimulus, so an agent that is one needs a non-zero ID.
Self StimulusID
// Team is the agent's team.
Team Team
// Pos is the agent's position.
Pos core.Point
// Facing is the direction the sight cone points along; its length does not matter, and zero faces +X.
Facing core.Point
// EyeOffset is added to Pos, in world space, to give the point both senses measure from and sight looks from.
EyeOffset core.Point
// Sight is the agent's vision.
Sight SightConfig
// Hearing is the agent's hearing.
Hearing HearingConfig
// ForgetAfter is how long a stimulus is remembered after it was last sensed; zero or less forgets it on the step after.
ForgetAfter time.Duration
// contains filtered or unexported fields
}Perception is one agent's senses and memory. Set its exported fields, add it to a PerceptionSystem, and step the system on game.Loop's fixed steps; the system reads the fields at the start of every Step, so a game moves and turns the agent by changing Pos and Facing.
func (p *Perception) AppendMemories(dst []Memory) []MemoryAppendMemories appends every memory, sorted by ID, to dst and returns the extended slice, so a caller can reuse one buffer every step.
func (p *Perception) Clear()Clear drops every memory and the last step's events.
func (p *Perception) Events() []EventEvents returns the events of the last Step, in order: per memory as sight, hearing and forgetting reached it. The slice is reused by the next Step.
func (p *Perception) Forget(id StimulusID) boolForget drops the memory of id without an event and reports whether there was one.
func (p *Perception) Memories() []MemoryMemories returns a new slice of every memory, sorted by ID.
func (p *Perception) Memory(id StimulusID) (Memory, bool)Memory returns the memory of the stimulus id, if any.
func (p *Perception) Sees(id StimulusID) boolSees reports whether the stimulus id is in sight now.
type PerceptionStats struct {
// Candidates is the number of agent-target pairs in view.
Candidates int
// Checks is the number of LineOfSight calls made, never more than a positive Budget and zero when LineOfSight is nil.
Checks int
// Deferred is the number of candidates left to later steps by the budget; they keep their previous result meanwhile.
Deferred int
}PerceptionStats reports the line-of-sight work of the last step.
type PerceptionSystem struct {
// LineOfSight decides whether a target in view is seen; nil means nothing blocks sight.
LineOfSight LineOfSight
// Attitude decides how agents regard targets and noises; nil means DefaultAttitude.
Attitude AttitudeFunc
// Budget caps the LineOfSight calls of one step; zero or less checks every pair in view, and a nil LineOfSight makes no calls, so the budget does not apply and every pair in view is seen at once. When the cap is reached, the remaining pairs are checked first on the next step, round-robin, and keep their previous result until then.
Budget int
// contains filtered or unexported fields
}PerceptionSystem steps the Perceptions of many agents together, so the line-of-sight checks of all of them share one per-step Budget. The zero PerceptionSystem is ready to use, with every line of sight clear.
Step it once per fixed step of game.Loop. Agents are served in the order they were added and targets in ID order, so a run is identical every time given the same inputs.
func (s *PerceptionSystem) Add(p *Perception)Add adds p to the system, after the agents already in it. Adding p again does nothing; adding a Perception that belongs to another system panics. A copy of a Perception that was added, such as a configured prototype, is a separate agent: Add gives it its own copy of the memories and no events.
func (s *PerceptionSystem) Len() intLen returns the number of agents in the system.
func (s *PerceptionSystem) PostNoise(n Noise)PostNoise queues n to be heard on the next Step. Noises are heard in the order they were posted.
func (s *PerceptionSystem) Remove(p *Perception) boolRemove removes p from the system and reports whether it was there. p keeps its memories, but none of them is visible any more and Events is empty, so Sees reports false until p is added and stepped again.
func (s *PerceptionSystem) Stats() PerceptionStatsStats returns the line-of-sight work of the last Step.
func (s *PerceptionSystem) Step(dt time.Duration, targets []Target)Step advances every agent by dt: memories age, targets in view are checked for line of sight within the budget, posted noises are heard, and memories not sensed for ForgetAfter are forgotten. Each agent's Events then report what changed. targets is read only during the call.
type PlanRunner struct {
// contains filtered or unexported fields
}PlanRunner plans toward prioritized GOAPGoals and executes the resulting action sequence step by step.
PlanRunner implements Node directly, so it can be ticked on game.Loop or embedded inside a behavior tree. When an action returns StatusFailure, or when the current WorldState invalidates the remaining plan or activates a higher-priority achievable goal, PlanRunner resets the running action node and replans automatically.
func NewPlanRunner(planner *GOAPPlanner, world func() WorldState, goals []GOAPGoal, executors map[string]Node) *PlanRunnerNewPlanRunner creates a PlanRunner that plans using planner and snapshots from world, selects goals in descending Priority order, and executes each action using executors[action.Name].
func (r *PlanRunner) ActiveGoal() intActiveGoal returns the index into the runner's goals slice currently being pursued, or -1 if none.
func (r *PlanRunner) CurrentAction() stringCurrentAction returns the Name of the action currently being executed, or "" if no plan is active.
func (r *PlanRunner) LastError() errorLastError returns the error from the most recent failed planning attempt, or nil if the last plan succeeded.
func (r *PlanRunner) Plans() intPlans returns the total number of plans computed since creation or the last Reset.
func (r *PlanRunner) Reset()Reset cancels any in-progress plan, resets any running action node, and clears failure tracking.
func (r *PlanRunner) Step() intStep returns the index of the currently active step in the plan, or -1 if no plan is active.
func (r *PlanRunner) Tick(dt time.Duration) StatusTick advances the current plan by dt, replanning automatically on action failure, world-state invalidation, or higher-priority goal preemption.
type PointReservations struct {
// contains filtered or unexported fields
}PointReservations tracks exclusive reservations of cover points and tactical positions across agents.
Each agent holds at most one active reservation at a time: reserving a new point automatically releases that agent's prior reservation, while two different agents can never hold the same CoverID or positions closer than MinSeparation. Step(dt) deterministically expires timed reservations with zero heap allocations.
PointReservations is not safe for concurrent use; drive it on game.Loop's fixed steps.
func NewPointReservations(cfg ReservationConfig) *PointReservationsNewPointReservations returns a PointReservations tracker with cfg.
func (r *PointReservations) Clear()Clear removes all active reservations while retaining slice capacity.
func (r *PointReservations) Config() ReservationConfigConfig returns the tracker's effective ReservationConfig.
func (r *PointReservations) Count() intCount returns the number of currently active reservations.
func (r *PointReservations) Entries(dst []Reservation) []ReservationEntries appends all active reservations to dst[:0] in deterministic ascending AgentID order.
func (r *PointReservations) Get(agentID uint64) (Reservation, bool)Get returns agentID's active reservation, if any.
func (r *PointReservations) HolderOfCover(coverID uint64) (uint64, bool)HolderOfCover returns the AgentID currently holding coverID, if any.
func (r *PointReservations) IsReservedByOther(agentID, coverID uint64, pos math2d.Vec2) boolIsReservedByOther reports whether coverID (when non-zero) or pos (within MinSeparation) is currently reserved by an agent other than agentID.
func (r *PointReservations) Refresh(agentID uint64, timeout time.Duration) boolRefresh resets the timeout of agentID's active reservation to timeout (or DefaultTimeout when <= 0).
func (r *PointReservations) Release(agentID uint64) boolRelease frees agentID's active reservation (for example on death or disengage). It returns true if agentID held a reservation.
func (r *PointReservations) ReleaseCover(coverID uint64) boolReleaseCover frees whichever agent currently holds coverID (for example when destructible cover breaks).
func (r *PointReservations) Reserve(agentID uint64, c TacticalCandidate, timeout time.Duration) boolReserve reserves candidate c for agentID for timeout (or Config().DefaultTimeout when timeout <= 0).
It returns false without altering agentID's existing reservation if agentID is 0 or if the candidate conflicts with another agent's reservation. On success, any prior reservation held by agentID is replaced atomically.
func (r *PointReservations) ReserveCover(agentID uint64, cp CoverPoint, timeout time.Duration) boolReserveCover reserves CoverPoint cp for agentID for timeout (or Config().DefaultTimeout when timeout <= 0).
func (r *PointReservations) ReservePos(agentID uint64, pos math2d.Vec2, timeout time.Duration) boolReservePos reserves an arbitrary world position pos for agentID for timeout (or Config().DefaultTimeout when timeout <= 0).
func (r *PointReservations) Step(dt time.Duration)Step advances all timed reservations by dt and removes any whose remaining time reaches <= 0. Preserves deterministic order and performs zero heap allocations.
type QueryBudget struct {
// MaxRaycasts is the maximum number of LOS raycast callbacks allowed per step (<= 0 means unlimited).
MaxRaycasts int
// MaxPathQueries is the maximum number of pathfinding queries allowed per step (<= 0 means unlimited).
MaxPathQueries int
// contains filtered or unexported fields
}QueryBudget caps expensive spatial tests (line-of-sight raycasts and pathfinding searches) performed across one or more TacticalQuery runs within a single simulation step.
Call Reset at the start of each game.Loop step. Non-positive limits mean unlimited for that resource.
func NewQueryBudget(maxRaycasts, maxPathQueries int) *QueryBudgetNewQueryBudget returns a QueryBudget with the given per-step limits (<= 0 means unlimited).
func (b *QueryBudget) PathQueriesRemaining() intPathQueriesRemaining returns remaining path queries for the current step, or -1 if unlimited.
func (b *QueryBudget) PathQueriesUsed() intPathQueriesUsed returns how many path queries have been consumed since the last Reset.
func (b *QueryBudget) RaycastsRemaining() intRaycastsRemaining returns remaining raycasts for the current step, or -1 if unlimited.
func (b *QueryBudget) RaycastsUsed() intRaycastsUsed returns how many raycasts have been consumed since the last Reset.
func (b *QueryBudget) Reset()Reset zeroes the step's consumed raycast and path-query counters.
func (b *QueryBudget) TryConsumePathQuery() boolTryConsumePathQuery consumes one path query from the step budget and returns true, or returns false if MaxPathQueries has been reached. A nil budget is unlimited.
func (b *QueryBudget) TryConsumeRaycast() boolTryConsumeRaycast consumes one raycast from the step budget and returns true, or returns false if MaxRaycasts has been reached. A nil budget is unlimited.
type QueryOrigin uint8QueryOrigin selects a reference point from a TacticalContext.
const (
// OriginDefault uses the generator's or test's natural default origin
// (OriginQuerier for CoverPoint/Grid/NavMesh/Distance/PathDistance; OriginTarget for Ring/LOS/Angle).
OriginDefault QueryOrigin = iota
// OriginQuerier uses TacticalContext.QuerierPos.
OriginQuerier
// OriginTarget uses TacticalContext.TargetPos.
OriginTarget
// OriginCustom uses the generator's or test's explicit CustomPos / CustomCenter / CustomTarget field.
OriginCustom
)type QueryStats struct {
// CandidatesGenerated is the total number of candidates produced by all generators.
CandidatesGenerated int
// CandidatesSurviving is the number of candidates remaining after all filters and budget checks.
CandidatesSurviving int
// RaycastsUsed is the number of LOS callbacks invoked during this query.
RaycastsUsed int
// PathQueriesUsed is the number of path queries invoked during this query.
PathQueriesUsed int
// BudgetExhausted is true if any expensive test stopped early because ctx.Budget ran out.
BudgetExhausted bool
}QueryStats summarizes the work performed during the most recent TacticalQuery run.
type ReachableCell struct {
Cell Cell
Cost float64
}ReachableCell is one cell returned by a movement-range query together with its minimum path cost from the start cell.
func ReachableCells(g Grid, topology GridTopology, start Cell, budget float64, edgeCost func(from, to Cell) float64) []ReachableCellReachableCells returns every cell reachable from start on g within budget under topology, ordered by ascending cost then row-major cell index.
When edgeCost is non-nil it overrides CostGrid and EdgeCostGrid with a custom step cost multiplier. For repeated zero-allocation queries, configure an AStar with Topology and call MovementRangeInto or MovementRangeWithCost.
type ReachableNode[N comparable] struct {
Node N
Cost float64
}ReachableNode pairs a node reached by GraphSearch.Range with its minimum path cost from start.
type Reasoner[C any] struct {
// TopN chooses weighted-randomly among the top TopN positive-scoring actions when TopN > 1 and a non-nil *random.Stream is provided.
// When TopN <= 1 or the stream is nil, the single highest-scoring action is picked deterministically.
TopN int
// Momentum is an optional bonus added to the currently active action's positive score to prevent oscillation between nearly equal actions.
Momentum float64
// contains filtered or unexported fields
}Reasoner scores a fixed set of UtilityActions and chooses either the highest-scoring action or a weighted random choice among the top TopN positive-scoring actions from a random.Stream.
Ties always break in fixed action order (lowest index wins). After warm-up, Choose, ChooseWithCurrent, ScoreAction, and ScoreAll make zero heap allocations.
func BuildReasoner[C any](cfg *UtilityConfig, bind UtilityBindings[C]) (*Reasoner[C], error)BuildReasoner validates cfg and resolves its input names and resource curve files into a Reasoner.
func NewReasoner[C any](actions ...UtilityAction[C]) *Reasoner[C]NewReasoner constructs a Reasoner with defensive copies of actions and their consideration slices.
func (r *Reasoner[C]) ActionCount() intActionCount returns the number of actions configured on r.
func (r *Reasoner[C]) ActionIndex(name string) intActionIndex returns the index of the first action named name, or -1 if none matches.
func (r *Reasoner[C]) ActionName(index int) stringActionName returns the Name of action at index, or "" if index is out of bounds.
func (r *Reasoner[C]) Choose(ctx C, rng *random.Stream) (int, float64)Choose scores all actions using r.Current() for momentum, selects the winning action, updates r.Current() to that action, and returns its index and score. Returns (-1, 0) if no action has a positive score.
func (r *Reasoner[C]) ChooseWithCurrent(ctx C, current int, rng *random.Stream) (int, float64)ChooseWithCurrent scores all actions using current as the active action index for momentum, without modifying r.Current(). This lets one shared Reasoner score many agents without per-agent copies or heap allocations. Returns (-1, 0) if no action has a positive score.
func (r *Reasoner[C]) Current() intCurrent returns the index of the currently active action tracked by Choose, or -1 if none is active.
func (r *Reasoner[C]) Reset()Reset clears the currently active action tracked by Choose.
func (r *Reasoner[C]) ScoreAction(index int, ctx C, isCurrent bool) float64ScoreAction scores the action at index for ctx, applying momentum when isCurrent is true. Out-of-range indices return 0.
func (r *Reasoner[C]) ScoreAll(ctx C, current int, dst []float64) []float64ScoreAll evaluates every action for ctx (applying momentum to action current) and writes the scores into dst, reusing dst's backing array when its capacity is at least ActionCount().
func (r *Reasoner[C]) SetCurrent(index int)SetCurrent sets the currently active action index tracked by Choose. Out-of-range values clear the active action to -1.
type Reservation struct {
// AgentID is the reserving agent's unique identifier.
AgentID uint64
// CoverID is the reserved CoverPoint.ID, or 0 for a non-cover spatial position.
CoverID uint64
// Pos is the reserved world position.
Pos math2d.Vec2
// Remaining is the time left before automatic expiry when HasTimeout is true.
Remaining time.Duration
// HasTimeout reports whether this reservation expires automatically on Step.
HasTimeout bool
}Reservation describes a single agent's active tactical position or cover reservation.
type ReservationConfig struct {
// MinSeparation is the minimum allowed distance between two reserved positions that do not
// share a non-zero CoverID. Values <= 0 enforce exclusivity only on matching CoverIDs.
MinSeparation float32
// DefaultTimeout is the automatic expiration duration used when Reserve is called with
// timeout <= 0. Values <= 0 keep reservations active until explicitly released.
DefaultTimeout time.Duration
}ReservationConfig configures a PointReservations tracker.
type ResponseCurve struct {
// Kind selects the curve formula; empty acts as identity unless Evaluator is set.
Kind CurveKind
// Slope scales the curve output (or defines the step height high - low for CurveStep).
Slope float64
// Exponent sets the power for CurvePolynomial or the steepness for CurveLogistic.
Exponent float64
// ShiftX shifts the input (the midpoint for CurveLogistic/CurveLogit or threshold for CurveStep).
ShiftX float64
// ShiftY offsets the output (or defines the low output below ShiftX for CurveStep).
ShiftY float64
// Evaluator supplies custom or resource-backed evaluation when Kind is CurveResource (or empty).
Evaluator CurveEvaluator
}ResponseCurve maps a normalized input x in [0, 1] into a utility score in [0, 1].
The zero ResponseCurve acts as the identity curve (y = x).
func CustomCurve(fn func(float64) float64) ResponseCurveCustomCurve returns a response curve backed by fn.
func LinearCurve(slope, shiftX, shiftY float64) ResponseCurveLinearCurve returns a linear response curve y = slope*(x - shiftX) + shiftY clamped to [0, 1].
func LogisticCurve(slope, steepness, midpoint, shiftY float64) ResponseCurveLogisticCurve returns an S-shaped logistic response curve y = slope/(1 + exp(-steepness*(x - midpoint))) + shiftY clamped to [0, 1].
func LogitCurve(slope, midpoint, shiftY float64) ResponseCurveLogitCurve returns a logit response curve y = slope*ln(u/(1 - u)) + shiftY where u = x - midpoint + 0.5, clamped to [0, 1].
func PolynomialCurve(slope, exponent, shiftX, shiftY float64) ResponseCurvePolynomialCurve returns a polynomial response curve y = slope*(x - shiftX)^exponent + shiftY clamped to [0, 1].
func ResourceCurve(eval CurveEvaluator) ResponseCurveResourceCurve returns a response curve backed by eval (for example a *resource.Curve).
func StepCurve(threshold, low, high float64) ResponseCurveStepCurve returns a threshold step response curve returning low for x < threshold and high for x >= threshold, clamped to [0, 1].
func (c ResponseCurve) Eval(x float64) float64Eval evaluates c at x, clamping both the input and output to [0, 1]. A NaN input or output yields 0.
type RingGenerator struct {
// Center selects the ring center (defaults to OriginTarget).
Center QueryOrigin
// CustomCenter is used when Center is OriginCustom.
CustomCenter math2d.Vec2
// InnerRadius is the innermost ring radius (used directly when OuterRadius <= InnerRadius or Rings <= 1).
InnerRadius float32
// OuterRadius is the outermost ring radius.
OuterRadius float32
// Rings is the number of concentric rings (values <= 0 default to 1).
Rings int
// PointsPerRing is the number of evenly spaced samples per ring (values <= 0 default to 8).
PointsPerRing int
// StartAngle is the base angle in radians (0 along +X; for arcs < 2*pi, the arc is centered on StartAngle).
StartAngle float32
// Arc is the angular span in radians; values <= 0 or >= 2*pi generate a full 360-degree ring.
Arc float32
// FaceCenter sets each candidate's Facing to the unit vector pointing toward the ring center.
FaceCenter bool
}RingGenerator emits candidates arranged on one or more concentric rings (or arcs) around a center.
func (g *RingGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidateGenerate appends concentric ring candidates in deterministic ring-major, angle-minor order.
type SearchStatus uint8SearchStatus reports the lifecycle state of an incremental path search.
const (
// SearchInProgress indicates the search still has work remaining and has not reached the goal or its expansion budget.
SearchInProgress SearchStatus = iota
// SearchComplete indicates a complete path to the goal was found.
SearchComplete
// SearchPartial indicates a partial path to the closest explored node was produced
// because the goal was unreachable or MaxExpansions was reached with AllowPartial enabled.
SearchPartial
// SearchFailed indicates no path was produced (invalid endpoints, unreachable goal without AllowPartial, or budget exhausted without AllowPartial).
SearchFailed
)func (s SearchStatus) Done() boolDone reports whether the search has reached a terminal state (complete, partial, or failed).
func (s SearchStatus) String() stringString returns a human-readable status name.
type Sense uint8Sense names the sense that last refreshed a memory.
const (
// SenseSight is a stimulus seen inside a sight cone with a clear line of sight.
SenseSight Sense = iota + 1
// SenseHearing is a noise heard within hearing range.
SenseHearing
)func (s Sense) String() stringString returns the sense's lower-case name.
type SightConfig struct {
// Range is how far the agent sees inside its cone; +Inf sees any finite distance, and zero, less or NaN disables the cone.
Range float32
// HalfAngle is the half-angle of the sight cone around the facing direction; zero, less or NaN disables the cone.
HalfAngle float32
// PeripheralRange is a shorter range seen over PeripheralHalfAngle, so a guard notices a target right beside it.
PeripheralRange float32
// PeripheralHalfAngle is the half-angle the peripheral range covers; zero means π, all around the agent, and a negative or NaN value disables the peripheral range.
PeripheralHalfAngle float32
// Detect selects the attitudes sight detects; zero detects hostile targets only.
Detect AttitudeMask
}SightConfig describes an agent's vision. The zero SightConfig sees nothing.
A target is in view when it lies within Range of the eye and within HalfAngle of the facing direction, or within PeripheralRange and within PeripheralHalfAngle. Angles are in radians; a half-angle of π or more covers every direction. Ranges are inclusive. A target in view is seen when the line of sight to it is clear.
type SlotAgent struct {
// ID uniquely identifies the agent for deterministic tie-breaking and cross-frame stability.
ID uint64
// Pos is the agent's current world position.
Pos core.Point
}SlotAgent describes an agent competing for an engagement slot around a target.
type SlotAssigner struct {
// StayBias subtracts this many world units from the assignment cost of an agent's
// previously held slot so agents do not swap slots unnecessarily as the target moves.
// Values <= 0 disable hysteresis.
StayBias float64
// contains filtered or unexported fields
}SlotAssigner assigns agents to concentric engagement rings around a target using optimal minimum-cost bipartite matching (the Hungarian algorithm).
Inner rings fill completely before outer rings are used, straight-line paths between agents and their assigned slots do not cross (by the triangle inequality on Euclidean distance), and assignments are strictly deterministic regardless of input slice order.
Set StayBias > 0 to give each agent a cost bonus (in world distance units) for retaining its previous slot as the target moves, suppressing oscillation across slot boundaries.
SlotAssigner reuses internal solver buffers across calls and is not safe for concurrent use.
func NewSlotAssigner(rings ...EngagementRing) *SlotAssignerNewSlotAssigner builds a SlotAssigner for the given concentric rings. Rings are filled in the order given (typically innermost first); rings with Slots <= 0 or non-finite/negative Radius are ignored.
func (a *SlotAssigner) Assign(dst []SlotAssignment, target core.Point, agents []SlotAgent) []SlotAssignmentAssign matches agents to engagement slots around target, appending the assignments to dst[:0] sorted by ascending AgentID.
Each agent should have a unique ID; duplicate IDs keep the entry with the earliest position after deterministic sorting. Agents no longer present in agents are pruned from stability memory.
func (a *SlotAssigner) Assignment(agentID uint64) (SlotAssignment, bool)Assignment returns the most recent SlotAssignment computed for agentID.
func (a *SlotAssigner) Release(agentID uint64)Release removes agentID from the assigner's stability memory and last-assignment cache.
func (a *SlotAssigner) Reset()Reset clears all stability memory and cached assignments.
func (a *SlotAssigner) Rings() []EngagementRingRings returns a copy of the assigner's configured engagement rings.
func (a *SlotAssigner) Slots(dst []EngagementSlot, target core.Point) []EngagementSlotSlots computes the world-space engagement slots around target and appends them to dst[:0].
func (a *SlotAssigner) TotalSlots() intTotalSlots returns the total number of slots across all configured rings.
type SlotAssignment struct {
// AgentID is the agent's ID.
AgentID uint64
// Ring is the assigned ring index, or -1 when Assigned is false.
Ring int
// Slot is the assigned slot index within Ring, or -1 when Assigned is false.
Slot int
// Pos is the assigned slot's world position (zero when Assigned is false).
Pos core.Point
// Assigned reports whether the agent received a slot.
Assigned bool
}SlotAssignment pairs an agent with its assigned engagement slot.
type SnapshotNode interface {
Node
SnapshotKind() string
SnapshotState() (any, error)
RestoreState(state any) error
}SnapshotNode is an optional interface that custom Node implementations may implement to participate in SnapshotBehaviorTree and RestoreBehaviorTree.
SnapshotKind returns a stable, non-empty identifier (for example "patrol") recorded in the snapshot as "custom:<kind>" to verify tree shape on restore. SnapshotState returns plain serializable data (scalars, slices, maps, or exported structs with json and yaml tags) representing the node's mutable runtime state, or nil when stateless. RestoreState validates and applies that state; on error it must leave the node unchanged.
type SpreadOptions struct {
// Decay is the fraction of influence lost per unit cell distance in [0, 1].
// Cardinal neighbors retain (1 - Decay); diagonal neighbors retain (1 - Decay)^sqrt(2).
// Values <= 0 keep full strength (retention 1); values >= 1 or NaN prevent spreading (retention 0).
Decay float32
// Momentum blends previous cell values with newly propagated targets in [0, 1]:
// next = prev*Momentum + target*(1 - Momentum).
// Values <= 0 or NaN replace immediately; values >= 1 keep previous values unchanged.
Momentum float32
// Iterations is the number of propagation passes to run; values <= 0 run 1 pass.
Iterations int
// Diagonal allows 8-way propagation with step distance sqrt(2) and no corner-cutting around blocked cells.
// False restricts propagation to the 4 cardinal directions.
Diagonal bool
}SpreadOptions configures iterative influence propagation around blocked cells on a Grid.
type Squad struct {
// contains filtered or unexported fields
}Squad coordinates a group of AI agents with a deterministic member roster, shared SquadState, score-driven tactical role assignments, and squad-level orders readable by behavior trees.
Squad is not safe for concurrent use; drive it on game.Loop's fixed steps.
func NewSquad(id uint64, members ...uint64) *SquadNewSquad returns a Squad with identifier id and optional initial member IDs.
func (s *Squad) AddMember(agentID uint64) boolAddMember adds agentID to the squad roster, maintaining ascending ID order. It reports whether agentID was newly added.
func (s *Squad) AssignRoles(specs ...SquadRoleSpec) intAssignRoles assigns tactical roles to current squad members using maximum-weight bipartite matching driven by each spec's Score function, replacing previous role assignments.
AssignRoles maximizes the number of filled eligible role slots first and total score second. Ineligible pairs (Score returning NaN or ±Inf) are never assigned. Ties break deterministically by spec declaration order and ascending member ID. Returns the number of members assigned a role.
func (s *Squad) ClearOrder()ClearOrder clears the squad's directive and increments Revision.
func (s *Squad) ClearRoles()ClearRoles removes all role assignments from the squad.
func (s *Squad) HasMember(agentID uint64) boolHasMember reports whether agentID belongs to the squad.
func (s *Squad) HasRole(agentID uint64, role string) boolHasRole reports whether agentID is a member currently assigned role.
func (s *Squad) MemberCount() intMemberCount returns the number of members in the squad.
func (s *Squad) Members(dst []uint64) []uint64Members appends all member IDs to dst[:0] in deterministic ascending order.
func (s *Squad) MembersWithRole(dst []uint64, role string) []uint64MembersWithRole appends all member IDs holding role to dst[:0] in deterministic ascending order.
func (s *Squad) Order() SquadOrderOrder returns the squad's current directive.
func (s *Squad) RemoveMember(agentID uint64) boolRemoveMember removes agentID from the squad roster and clears its assigned role. It reports whether agentID was a member.
func (s *Squad) Role(agentID uint64) stringRole returns the tactical role currently assigned to agentID, or "" if unassigned or not a member.
func (s *Squad) SetOrder(order SquadOrder) SquadOrderSetOrder updates the squad's directive, increments Revision, and returns the stored order.
func (s *Squad) SetRole(agentID uint64, role string) boolSetRole manually assigns role to agentID if agentID is a member (passing "" unassigns it). It reports whether agentID is in the squad.
func (s *Squad) State() *SquadStateState returns the squad's shared key-value state.
type SquadOrder struct {
// Kind names the directive (for example, "engage", "flank", "suppress", "hold", "retreat").
// An empty Kind indicates no active order.
Kind string
// TargetID identifies an optional target entity for the order.
TargetID uint64
// Position specifies an optional world-space coordinate (such as a rally or flank point).
Position core.Point
// Revision increments each time Squad.SetOrder or Squad.ClearOrder updates the order,
// letting behavior trees detect freshly issued orders even with the same Kind.
Revision uint64
}SquadOrder is a squad-level directive readable by members' behavior trees.
type SquadRoleSpec struct {
// Name identifies the role (for example, "flanker", "suppressor", "rusher").
Name string
// Count is the maximum number of squad members to assign to this role.
// Values <= 0 assign no members; counts larger than the squad size are clamped to the squad size.
Count int
// Score evaluates how well agentID fits this role (higher is better; negative finite scores
// such as -distance are supported). Return a non-finite value (NaN or ±Inf) to mark agentID
// ineligible for this role. A nil Score treats all members as equally eligible with score 0.
Score func(agentID uint64) float64
}SquadRoleSpec describes a tactical role to fill within a Squad and how each member scores for it.
type SquadState struct {
// contains filtered or unexported fields
}SquadState is a shared key-value state store for a Squad, readable and writable by squad members and their behavior trees. Its zero value is ready to use.
func (s *SquadState) Bool(key string) (bool, bool)Bool retrieves a bool value stored under key.
func (s *SquadState) Float(key string) (float64, bool)Float retrieves a float64 value stored under key.
func (s *SquadState) Get(key string) (any, bool)Get retrieves the value stored under key.
func (s *SquadState) Has(key string) boolHas reports whether key is present in s.
func (s *SquadState) ID(key string) (uint64, bool)ID retrieves a uint64 identifier stored under key.
func (s *SquadState) Int(key string) (int, bool)Int retrieves an int value stored under key.
func (s *SquadState) Keys(dst []string) []stringKeys appends all keys in s to dst[:0] in deterministic ascending lexicographical order.
func (s *SquadState) Len() intLen returns the number of keys stored in s.
func (s *SquadState) Point(key string) (core.Point, bool)Point retrieves a core.Point value stored under key.
func (s *SquadState) Set(key string, value any)Set stores value under key.
func (s *SquadState) SetBool(key string, v bool)SetBool stores a bool value under key.
func (s *SquadState) SetFloat(key string, v float64)SetFloat stores a float64 value under key.
func (s *SquadState) SetID(key string, v uint64)SetID stores a uint64 identifier under key.
func (s *SquadState) SetInt(key string, v int)SetInt stores an int value under key.
func (s *SquadState) SetPoint(key string, v core.Point)SetPoint stores a core.Point value under key.
func (s *SquadState) SetString(key string, v string)SetString stores a string value under key.
func (s *SquadState) String(key string) (string, bool)String retrieves a string value stored under key.
type Status uint8Status is the outcome of one Tick of a behavior tree Node.
const (
// StatusSuccess reports that a node completed its work successfully.
StatusSuccess Status = iota
// StatusFailure reports that a node failed or its condition did not hold.
StatusFailure
// StatusRunning reports that a node needs more ticks to finish.
StatusRunning
)func (s Status) MarshalText() ([]byte, error)MarshalText encodes s as its lowercase name ("success", "failure", or "running") so snapshots read clearly in YAML and JSON.
func (s Status) String() stringString returns a human-readable name for s.
func (s *Status) UnmarshalText(text []byte) errorUnmarshalText decodes a status name written by Status.MarshalText.
type StimulusID uint64StimulusID identifies something an agent can sense: a target it can see or the source of a noise it can hear. A memory is kept per StimulusID, so a target seen and later heard refreshes one memory. IDs are the game's own, such as entity IDs. Zero is a valid target or noise ID, and anonymous noises usually share it, but Perception.Self treats zero as "not a stimulus", so an agent that is also a target or a noise source needs a non-zero ID.
type TacticalCandidate struct {
// Pos is the candidate world position.
Pos math2d.Vec2
// Facing is the candidate's unit facing vector (for cover points, points into the cover obstacle).
Facing math2d.Vec2
// Height is CoverHalf or CoverFull for cover candidates, or 0 for non-cover candidates.
Height CoverHeight
// CoverID is the CoverPoint.ID for cover candidates, or 0 otherwise.
CoverID uint64
// CoverIndex is the source index in CoverPointGenerator.Points, or -1 for non-cover candidates.
CoverIndex int
// Elevation is the optional 3D vertical coordinate (0 in 2D).
Elevation float32
// Score is the final composite score computed by TacticalQuery.
Score float64
}TacticalCandidate is one spatial position evaluated by a TacticalQuery.
type TacticalContext struct {
// QuerierID identifies the querying agent (used by PointReservations to ignore the agent's own reservation).
QuerierID uint64
// QuerierPos is the querying agent's world position.
QuerierPos math2d.Vec2
// TargetPos is the primary threat, enemy, or objective world position.
TargetPos math2d.Vec2
// TargetDir is an optional reference direction (for example, the threat's look direction for flanking).
TargetDir math2d.Vec2
// Reservations optionally excludes positions currently reserved by other agents before tests run.
Reservations *PointReservations
// Budget optionally caps raycasts and path queries across queries in the current step.
Budget *QueryBudget
}TacticalContext supplies per-agent runtime state to a TacticalQuery.
type TacticalQuery struct {
// Generators produce candidate positions in declaration order.
Generators []CandidateGenerator
// Tests evaluate surviving candidates in declaration order.
// Place cheap filters and scorers (Distance, Angle, CoverHeight, Influence) before
// expensive budgeted tests (LOS, PathDistance) so step budgets are spent on top candidates.
Tests []TacticalTest
// contains filtered or unexported fields
}TacticalQuery executes an EQS-style pipeline: generate candidate positions, exclude points reserved by other agents, run ordered filter/score tests within any configured step budget, and sort surviving candidates deterministically by descending score.
TacticalQuery reuses all internal scratch buffers across runs so Best, RunInto, and RunAndReserve perform zero heap allocations after warm-up. It is not safe for concurrent use.
func NewTacticalQuery(generators []CandidateGenerator, tests ...TacticalTest) *TacticalQueryNewTacticalQuery returns a TacticalQuery configured with the given generators and tests.
func (q *TacticalQuery) Best(ctx TacticalContext) (TacticalCandidate, bool)Best executes the query and returns the highest-scoring surviving candidate without allocating.
func (q *TacticalQuery) LastStats() QueryStatsLastStats returns diagnostic counts from the most recent Run, RunInto, Best, or RunAndReserve call.
func (q *TacticalQuery) Run(ctx TacticalContext) []TacticalCandidateRun executes the query and returns a newly allocated slice of surviving candidates sorted deterministically from highest to lowest Score. Use RunInto or Best to avoid heap allocations.
func (q *TacticalQuery) RunAndReserve(ctx TacticalContext, timeout time.Duration) (TacticalCandidate, bool)RunAndReserve executes the query, picks the highest-scoring surviving candidate, and reserves it for ctx.QuerierID on ctx.Reservations (when non-nil) for timeout (or DefaultTimeout when <= 0). Returns (best, true) on success, or (zero, false) if no candidate survived or reservation failed.
func (q *TacticalQuery) RunInto(dst []TacticalCandidate, ctx TacticalContext) []TacticalCandidateRunInto executes the query and appends surviving candidates in deterministic descending Score order into dst[:0], performing zero heap allocations once internal buffers and dst are warmed up.
type TacticalTest interface {
// contains filtered or unexported methods
}TacticalTest filters and/or scores candidates inside a TacticalQuery.
type Target struct {
// ID identifies the target; a later target with the same ID in one step is ignored.
ID StimulusID
// Team is the target's team, compared with each agent's team by the system's AttitudeFunc.
Team Team
// Pos is the point agents look at.
Pos core.Point
// Vel is the target's velocity, remembered while it is seen.
Vel core.Point
}Target is a stimulus that agents can see during one step.
type Team uint8Team is a team affiliation, compared by an AttitudeFunc to decide whether an agent treats a stimulus as hostile, neutral or friendly.
const NoTeam Team = 255NoTeam is the team of things that belong to no side; DefaultAttitude treats it as neutral to everyone.
type TestPurpose uint8TestPurpose controls whether a TacticalTest filters candidates, scores them, or both.
const (
// TestFilterAndScore filters candidates failing the test's filter criteria and adds normalized score * Weight.
TestFilterAndScore TestPurpose = iota
// TestFilterOnly removes candidates failing the test's filter criteria without modifying scores.
TestFilterOnly
// TestScoreOnly scores surviving candidates without removing any.
TestScoreOnly
)type TileCoverOptions struct {
// Origin shifts generated world coordinates by Origin (defaults to (0, 0)).
Origin math2d.Vec2
// Spacing is the distance between cover points along a contiguous solid wall run in world units.
// When <= 0, one cover point is placed at the midpoint of each exposed tile edge.
Spacing float32
// Standoff offsets each cover point from the solid tile edge into the adjacent open tile.
// When <= 0, defaults to half of min(TileWidth, TileHeight) so points land inside the open tile.
Standoff float32
// EdgeInset is the margin from each end of a contiguous wall run when Spacing > 0.
// When <= 0, defaults to Spacing * 0.5.
EdgeInset float32
// SolidMask selects which tile flags count as solid cover walls (defaults to tilemap.TileSolid when 0).
SolidMask tilemap.TileFlags
// HalfCoverMask optionally marks solid tiles whose flags intersect HalfCoverMask as CoverHalf.
HalfCoverMask tilemap.TileFlags
// DefaultHeight sets the height for solid tiles not classified as half cover (defaults to CoverFull).
DefaultHeight CoverHeight
// HeightFunc optionally overrides cover-height classification for solid cell (col, row).
// Returning 0 falls back to HalfCoverMask, the tile's "cover" property ("half"/"full"), or DefaultHeight.
HeightFunc func(col, row int) CoverHeight
// StartID is the first CoverPoint.ID assigned (defaults to 1 when 0).
StartID uint64
}TileCoverOptions configures cover-point generation from a tilemap.Tilemap.
type TiledNavMesh struct {
// contains filtered or unexported fields
}TiledNavMesh is a 2D navigation mesh partitioned into fixed-size square tiles that can be baked, added, removed, and replaced independently at runtime. Polygons are automatically linked across tile borders, dynamic obstacles rebuild only the touched tiles, a two-level spatial index avoids whole-mesh scans, and per-tile versions + watchers invalidate paths crossing changed tiles.
TiledNavMesh is deterministic and is not safe for concurrent mutation.
func BuildTiledNavMesh(polys [][]core.Point, tileSize float32) *TiledNavMeshBuildTiledNavMesh constructs a 2D TiledNavMesh from convex polygons using fixed square tiles of size tileSize.
func BuildTiledNavMeshWithAreas(polys []NavPolygonInput, tileSize float32) *TiledNavMeshBuildTiledNavMeshWithAreas constructs a 2D TiledNavMesh from convex polygons carrying per-polygon areas and flags.
func NewTiledNavMesh(cfg TiledNavMeshConfig) *TiledNavMeshNewTiledNavMesh creates an empty 2D TiledNavMesh with cfg.
func (tm *TiledNavMesh) AddObstacle(obs NavObstacle) (NavObstacleID, bool)AddObstacle registers a dynamic obstacle and immediately rebuilds only the touched tiles (or defers rebuild until Batch returns if called inside Batch). Returns (0, false) if tm is nil or obs has invalid geometry.
func (tm *TiledNavMesh) AddTile(coord NavTileCoord, tile *NavTile) boolAddTile installs tile at coord only if no tile currently exists at coord. Returns false if tm or tile is nil or coord is already occupied.
func (tm *TiledNavMesh) AddTileListener(fn func(NavTileChange)) NavListenerIDAddTileListener registers fn to be invoked whenever any tile is added, updated, or removed.
func (tm *TiledNavMesh) BakeTile(coord NavTileCoord, polys []NavPolygonInput) *NavTileBakeTile bakes polys into a NavTile for coord using tm's TileSize and Origin and installs it into tm.
func (tm *TiledNavMesh) Batch(fn func())Batch groups multiple tile or obstacle mutations so each touched tile is rebuilt at most once in deterministic sorted order when fn returns, and notifications fire once per changed tile.
func (tm *TiledNavMesh) ClearObstacles()ClearObstacles removes all dynamic obstacles and rebuilds only tiles that had obstacles.
func (tm *TiledNavMesh) Contains(p core.Point) boolContains reports whether p lies inside any polygon of the tiled mesh.
func (tm *TiledNavMesh) ContainsWithFilter(p core.Point, filter NavFilter) boolContainsWithFilter reports whether p lies inside any polygon passing filter.
func (tm *TiledNavMesh) FindCorridor(start, goal core.Point) ([]NavPolyRef, bool)FindCorridor finds the sequence of NavPolyRefs from start to goal using DefaultNavFilter.
func (tm *TiledNavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]NavPolyRef, bool)FindCorridorWithFilter finds the sequence of NavPolyRefs from start to goal restricted to filter.
func (tm *TiledNavMesh) FindPath(start, goal core.Point) ([]core.Point, bool)FindPath finds the shortest path inside tm from start to goal using DefaultNavFilter.
func (tm *TiledNavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)FindPathWithFilter finds the minimum-cost path inside tm restricted to filter.
func (tm *TiledNavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) TiledNavPathResultFindPathWithFilterAndOptions finds a minimum-cost path across tm restricted to filter and opts. Portal A* touches only visited portals (sparse state, independent of total mesh size) and runs Simple Stupid Funnel Algorithm string-pulling across tile borders so paths match an untiled NavMesh for the same geometry.
func (tm *TiledNavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) TiledNavPathResultFindPathWithOptions finds a path using DefaultNavFilter and opts, returning the full TiledNavPathResult with tile footprint and version stamps for invalidation checking.
func (tm *TiledNavMesh) FindPolygon(p core.Point) (NavPolyRef, bool)FindPolygon locates a polygon containing p in O(1) tile lookup + O(log P_tile) local BVH.
func (tm *TiledNavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, bool)FindPolygonWithFilter locates a polygon passing filter that contains p.
func (tm *TiledNavMesh) HasTile(coord NavTileCoord) boolHasTile reports whether a tile is currently installed at coord.
func (tm *TiledNavMesh) IsPathValid(res TiledNavPathResult) boolIsPathValid reports whether every tile crossed by res is still present and unchanged since res was computed.
func (tm *TiledNavMesh) NearestPoint(p, extent core.Point) (core.Point, NavPolyRef, bool)NearestPoint returns the closest point on any polygon allowed by DefaultNavFilter within half-extents [p - extent, p + extent], together with its NavPolyRef.
func (tm *TiledNavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, NavPolyRef, bool)NearestPointWithFilter behaves like NearestPoint restricted to filter.
func (tm *TiledNavMesh) NearestPolygon(p core.Point) (NavPolyRef, core.Point, bool)NearestPolygon returns the polygon closest to p and the closest point on or inside it, using the two-level spatial index (coarse tile BVH + per-tile BVH).
func (tm *TiledNavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, core.Point, bool)NearestPolygonWithFilter returns the closest polygon passing filter and the closest point on it.
func (tm *TiledNavMesh) Neighbors(ref NavPolyRef) []NavPolyRefNeighbors returns the polygon references sharing an edge (intra-tile or cross-tile) with ref.
func (tm *TiledNavMesh) ObstacleCount() intObstacleCount returns the number of active dynamic obstacles.
func (tm *TiledNavMesh) Origin() core.PointOrigin returns the world-space origin of tile (0, 0).
func (tm *TiledNavMesh) Polygon(ref NavPolyRef) []core.PointPolygon returns a copy of the vertices of ref, or nil if ref is stale or invalid.
func (tm *TiledNavMesh) PolygonArea(ref NavPolyRef) NavAreaPolygonArea returns the area of ref, or NavAreaDefault if ref is invalid.
func (tm *TiledNavMesh) PolygonCount() intPolygonCount returns the total number of active walkable polygons across all installed tiles.
func (tm *TiledNavMesh) PolygonFlags(ref NavPolyRef) NavFlagsPolygonFlags returns the runtime flags of ref, or 0 if ref is invalid.
func (tm *TiledNavMesh) Raycast(start, target core.Point) (TiledNavRaycastHit, bool)Raycast casts a segment along the 2D TiledNavMesh surface from start toward target using DefaultNavFilter.
func (tm *TiledNavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (TiledNavRaycastHit, bool)RaycastWithFilter behaves like Raycast restricted to polygons allowed by filter.
func (tm *TiledNavMesh) RebuildTile(coord NavTileCoord) boolRebuildTile rebuilds the existing tile at coord from its base polygons and active dynamic obstacles. Returns false if no tile exists at coord.
func (tm *TiledNavMesh) RemoveObstacle(id NavObstacleID) boolRemoveObstacle removes dynamic obstacle id and rebuilds only the tiles it touched, restoring their uncarved geometry.
func (tm *TiledNavMesh) RemoveTile(coord NavTileCoord) boolRemoveTile unloads the tile at coord, removes cross-tile border links from neighboring tiles, bumps coord's tile version, and notifies listeners / invalidates paths crossing coord.
func (tm *TiledNavMesh) RemoveTileListener(id NavListenerID) boolRemoveTileListener unregisters a listener previously added with AddTileListener.
func (tm *TiledNavMesh) ReplaceTile(coord NavTileCoord, tile *NavTile) boolReplaceTile replaces the existing tile at coord with tile. Returns false if tm or tile is nil or no tile currently exists at coord.
func (tm *TiledNavMesh) Revision() uint64Revision returns a monotonically increasing number bumped on any tile or obstacle mutation.
func (tm *TiledNavMesh) SetTile(coord NavTileCoord, tile *NavTile) boolSetTile installs or replaces tile at coord, applying any active dynamic obstacles touching coord and linking polygons across borders with neighboring tiles.
func (tm *TiledNavMesh) TileBounds(coord NavTileCoord) (minPt, maxPt core.Point)TileBounds returns the exact world-space [min, max] bounds of tile coord.
func (tm *TiledNavMesh) TileCoordAt(p core.Point) NavTileCoordTileCoordAt returns the tile coordinate containing p.
func (tm *TiledNavMesh) TileCoords() []NavTileCoordTileCoords returns all installed tile coordinates in deterministic sorted order.
func (tm *TiledNavMesh) TileCount() intTileCount returns the number of currently installed tiles.
func (tm *TiledNavMesh) TilePolygonCount(coord NavTileCoord) intTilePolygonCount returns the number of active polygons currently inside tile coord.
func (tm *TiledNavMesh) TileSize() float32TileSize returns the configured tile size in world units.
func (tm *TiledNavMesh) TileVersion(coord NavTileCoord) uint64TileVersion returns the current revision number of tile coord (0 if never modified).
func (tm *TiledNavMesh) UnwatchPath(id NavPathWatchID) boolUnwatchPath cancels a path watcher previously registered with WatchPath.
func (tm *TiledNavMesh) UpdateObstacle(id NavObstacleID, obs NavObstacle) boolUpdateObstacle replaces the geometry or mode of an existing dynamic obstacle id, rebuilding only tiles touched by either its old or new footprint.
func (tm *TiledNavMesh) WatchPath(tiles []NavTileCoord, onInvalidate func(NavTileChange)) NavPathWatchIDWatchPath registers a one-shot invalidation callback invoked when any tile in tiles changes. Because watchers are indexed per tile, changing a tile notifies only paths crossing that tile. Once triggered, the watch is automatically removed.
type TiledNavMeshConfig struct {
// TileSize is the width and height of each square tile in world units.
// Defaults to 64 when <= 0.
// Origin is the world-space origin of tile (0, 0). Defaults to (0, 0).
}TiledNavMeshConfig configures a 2D TiledNavMesh.
type TiledNavPathResult struct {
}TiledNavPathResult is the outcome of a 2D TiledNavMesh path search, including the tile footprint and tile versions crossed so callers can detect invalidation.
func (r TiledNavPathResult) CrossesTile(coord NavTileCoord) boolCrossesTile reports whether r's corridor passes through coord.
func (r TiledNavPathResult) TileCoords() []NavTileCoordTileCoords returns the deduplicated list of tile coordinates crossed by r.
type TiledNavRaycastHit struct {
}TiledNavRaycastHit describes the result of casting a segment across a 2D TiledNavMesh.
type TokenHolder struct {
// AgentID uniquely identifies the holding agent.
AgentID uint64
// Priority is the agent's current attack priority used for preemption comparisons.
Priority float64
// Held is how long the agent has held this token.
Held time.Duration
}TokenHolder describes an agent that currently holds an attack token.
type TokenManager struct {
// contains filtered or unexported fields
}TokenManager maintains one TokenPool per target ID.
Targets that have not been explicitly configured with ConfigureTarget are created on demand with the manager's default TokenPoolConfig when Request is called. All multi-target operations iterate targets in ascending target ID order for determinism.
func NewTokenManager(defaultCfg TokenPoolConfig) *TokenManagerNewTokenManager returns a TokenManager using defaultCfg for targets created on demand.
func (m *TokenManager) Cancel(targetID, agentID uint64) boolCancel withdraws agentID's pending request for targetID.
func (m *TokenManager) ConfigureTarget(targetID uint64, cfg TokenPoolConfig) *TokenPoolConfigureTarget creates or replaces the TokenPool for targetID with cfg and returns it.
func (m *TokenManager) HasToken(targetID, agentID uint64) boolHasToken reports whether agentID holds an attack token for targetID.
func (m *TokenManager) Pool(targetID uint64) *TokenPoolPool returns the TokenPool for targetID, or nil if none exists yet.
func (m *TokenManager) Release(targetID, agentID uint64) boolRelease returns agentID's held token for targetID to cooldown and cancels any pending request.
func (m *TokenManager) RemoveAgent(agentID uint64)RemoveAgent releases any tokens held by agentID and cancels any pending requests across all targets.
func (m *TokenManager) RemoveTarget(targetID uint64) boolRemoveTarget deletes targetID's TokenPool (for example, when that target is defeated).
func (m *TokenManager) Request(targetID, agentID uint64, priority float64)Request submits or updates an attack token request for agentID against targetID, creating targetID's pool with the manager's default configuration if needed.
func (m *TokenManager) Reset()Reset removes all target pools from m.
func (m *TokenManager) Step(dt time.Duration)Step advances every target's TokenPool by dt in deterministic ascending target ID order.
type TokenPool struct {
// contains filtered or unexported fields
}TokenPool arbitrates a fixed number of attack tokens for one target.
Agents request tokens with a priority via Request, and Step advances cooldown and timeout durations while resolving pending requests deterministically (highest priority first, breaking ties by lowest agent ID regardless of submission order). Higher-priority requesters can preempt lower-priority holders when no free tokens remain. Returned tokens wait for Cooldown before becoming available again.
TokenPool is not safe for concurrent use; drive it on game.Loop's fixed steps.
func NewTokenPool(cfg TokenPoolConfig) *TokenPoolNewTokenPool returns a TokenPool initialized with cfg.
func (p *TokenPool) Available() intAvailable returns the number of tokens immediately free to grant on the next Step.
func (p *TokenPool) Cancel(agentID uint64) boolCancel withdraws a pending request for agentID without releasing a held token. It reports whether a pending request existed.
func (p *TokenPool) Capacity() intCapacity returns the maximum number of tokens in the pool.
func (p *TokenPool) Config() TokenPoolConfigConfig returns the pool's effective configuration.
func (p *TokenPool) CoolingDown() intCoolingDown returns the number of returned tokens currently waiting on cooldown.
func (p *TokenPool) HasToken(agentID uint64) boolHasToken reports whether agentID currently holds an attack token from p.
func (p *TokenPool) HeldCount() intHeldCount returns the number of tokens currently held by agents.
func (p *TokenPool) Holder(agentID uint64) (TokenHolder, bool)Holder returns the TokenHolder record for agentID if it currently holds a token.
func (p *TokenPool) Holders(dst []TokenHolder) []TokenHolderHolders appends all active holders to dst[:0], sorted by ascending AgentID.
func (p *TokenPool) PendingCount() intPendingCount returns the number of waiting token requests.
func (p *TokenPool) Release(agentID uint64) boolRelease returns agentID's held token to the pool (starting Cooldown if configured) and withdraws any pending request for agentID. It reports whether agentID held a token.
func (p *TokenPool) Remove(agentID uint64) boolRemove releases any token held by agentID and cancels any pending request for agentID. Call Remove when an agent dies, despawns, or disengages from the target. It reports whether agentID held a token or had a pending request.
func (p *TokenPool) Request(agentID uint64, priority float64)Request submits or updates an attack token request for agentID at priority.
If agentID already holds a token, Request refreshes its priority for future preemption comparisons without consuming a second token. Requests with a NaN priority are ignored. Pending requests persist until granted, cancelled via Cancel or Remove, or cleared by Reset.
func (p *TokenPool) Reset()Reset clears all active holders, pending requests, and cooldown timers, restoring Available() to Capacity().
func (p *TokenPool) Step(dt time.Duration)Step advances cooldown and hold timers by dt and deterministically resolves pending requests.
Within a step:
- Cooling-down tokens advance; any token whose remaining cooldown reaches <= 0 becomes available.
- Active holders' hold durations advance; any holder reaching MaxHoldDuration returns its token (entering Cooldown with its full duration when Cooldown > 0, or becoming available immediately).
- Pending requests are sorted by descending priority, breaking ties by ascending AgentID.
- Requests first consume available tokens, then preempt the lowest-priority holder (breaking holder ties by highest AgentID) when the requester's priority exceeds the holder's by PreemptMargin (or strictly exceeds it when PreemptMargin == 0).
type TokenPoolConfig struct {
// Capacity is the maximum number of attack tokens that may be held at once.
// Values <= 0 allow no tokens to be granted.
Capacity int
// Cooldown is the duration a returned token must wait before it can be acquired again.
// Tokens transferred directly by preemption do not enter cooldown.
Cooldown time.Duration
// PreemptMargin is the minimum priority advantage a waiting requester must have over the
// lowest-priority holder to take (preempt) its token. When <= 0, any strictly higher
// priority (requester > holder) may preempt.
PreemptMargin float64
// MaxHoldDuration automatically releases a held token once it has been held for this
// duration, returning it to cooldown. Values <= 0 disable automatic timeout.
MaxHoldDuration time.Duration
}TokenPoolConfig configures a TokenPool for a single target.
type UtilityAction[C any] struct {
// Name identifies the action (used to match behavior tree subtrees and YAML definitions).
Name string
// Weight scales the compensated consideration score. Zero defaults to 1; negative disables the action.
Weight float64
// Momentum is an optional per-action bonus added on top of Reasoner.Momentum while this action is active and scores > 0.
Momentum float64
// Considerations are the scoring axes for this action. Any consideration returning 0 vetoes the action (score 0).
Considerations []Consideration[C]
}UtilityAction is one candidate action scored by a Reasoner.
Its score is the product of its Considerations adjusted by Dave Mark's compensation factor:
modFactor = 1 - 1/N score = score + (1 - score)*modFactor*score
multiplied by Weight (defaulting to 1 when Weight == 0; negative Weight disables the action), plus any momentum bonus when the action is currently active and its base score is positive.
func (a *UtilityAction[C]) Score(ctx C, momentumBonus float64) float64Score computes the action's utility score for ctx. When momentumBonus > 0 and the weighted compensated score is strictly positive, momentumBonus is added to resist rapid switching.
type UtilityActionDef struct {
// Name uniquely identifies the action within the config.
Name string `yaml:"name"`
// Weight scales the compensated consideration score; 0 defaults to 1.
Weight float64 `yaml:"weight,omitempty"`
// Momentum is an optional per-action bonus added on top of UtilityConfig.Momentum while active.
Momentum float64 `yaml:"momentum,omitempty"`
// Considerations are the scoring considerations evaluated for this action.
Considerations []ConsiderationDef `yaml:"considerations,omitempty"`
}UtilityActionDef defines one action in a UtilityConfig file.
type UtilityBindings[C any] struct {
// Inputs maps each ConsiderationDef.Input name to a function extracting that value from C.
Inputs map[string]func(C) float64
// LoadCurve resolves a CurveDef.File path into a CurveEvaluator (for example via resource.LoadAs[*resource.Curve]).
// Required only when the UtilityConfig contains at least one CurveResource curve.
LoadCurve func(path string) (CurveEvaluator, error)
}UtilityBindings provides the Go input readers and optional resource curve loader used by BuildReasoner.
type UtilityConfig struct {
// Version is the schema version; it must equal UtilityVersion (1).
Version int `yaml:"version"`
// TopN enables weighted random selection among the top TopN positive-scoring actions when greater than 1.
TopN int `yaml:"topN,omitempty"`
// Momentum is the default bonus added to the currently active action's positive score.
Momentum float64 `yaml:"momentum,omitempty"`
// Actions are the candidate actions in fixed declaration order (used for deterministic tie-breaking).
Actions []UtilityActionDef `yaml:"actions"`
}UtilityConfig is a versioned YAML definition of utility AI actions, considerations, and response curves.
func ParseUtility(data []byte) (*UtilityConfig, error)ParseUtility decodes and validates a utility AI YAML document. Unknown fields, missing or unsupported versions, duplicate keys, and trailing YAML documents are refused.
func (cfg *UtilityConfig) Validate() errorValidate checks that cfg has version UtilityVersion, valid parameters, unique action names, and well-formed considerations and curves.
type ValidatedGraph[N comparable] interface {
ValidNode(node N) bool
}ValidatedGraph is an optional interface a Graph may implement to reject invalid, out-of-bounds, blocked, or removed nodes before searching.
type Vec3 struct {
X, Y, Z float32
}Vec3 is a 3-component float32 vector in right-handed Y-up space (+X right, +Y up, -Z forward). Its field layout matches math3d.Vec3 so callers can convert values with a zero-cost ai.Vec3(v) cast without importing the experimental game/math3d package from stable game/ai.
func Alignment3D(a Agent3D, neighbors []Agent3D, radius float32) Vec3Alignment3D steers a toward the average heading of neighbors within radius (or all non-coincident neighbors when radius <= 0).
func Arrive3D(a Agent3D, target Vec3, slowRadius float32) Vec3Arrive3D returns a steering force toward target that smoothly scales desired speed down to zero inside slowRadius.
func Cohesion3D(a Agent3D, neighbors []Agent3D, radius float32) Vec3Cohesion3D steers a toward the center of mass of neighbors within radius (or all non-coincident neighbors when radius <= 0).
func Combine3D(maxForce float32, forces ...WeightedForce3D) Vec3Combine3D sums weighted 3D steering forces and clamps the result's magnitude to maxForce when maxForce is positive.
func CombinePrioritized3D(maxForce float32, forces ...WeightedForce3D) Vec3CombinePrioritized3D blends 3D steering forces in priority order, spending at most maxForce total magnitude. Once a force saturates the remaining budget it is truncated to the remainder and lower-priority forces are ignored.
func Evade3D(a, pursuer Agent3D, panicRadius, maxLookAhead float32) Vec3Evade3D returns a steering force that flees from the predicted position of pursuer while closer than panicRadius (or always when panicRadius <= 0).
func Flee3D(a Agent3D, threat Vec3, panicRadius float32) Vec3Flee3D returns the steering force accelerating a away from threat at MaxSpeed. When panicRadius is positive, Flee3D returns zero once a is at least panicRadius away from threat.
func FollowPath3D(a Agent3D, path []Vec3, state *PathFollowState, waypointRadius float32, loop bool) Vec3FollowPath3D steers a along path, advancing state.Index when a enters waypointRadius of the current waypoint (measured on XZ when a.PlanarXZ is true, so grounded agents follow sloped world3d.NavMesh paths smoothly).
func Hide3D(a, pursuer Agent3D, obstacles []Obstacle3D, standoff, slowRadius float32) Vec3Hide3D picks the closest hiding spot behind an Obstacle3D opposite pursuer and steers a toward it with Arrive3D, falling back to Evade3D when no valid obstacle exists.
func Interpose3D(a, targetA, targetB Agent3D, slowRadius float32) Vec3Interpose3D steers a to intercept the predicted midpoint between moving agents targetA and targetB, slowing smoothly inside slowRadius via Arrive3D.
func ObstacleAvoidance3D(a Agent3D, obstacles []Obstacle3D, maxAhead float32) Vec3ObstacleAvoidance3D deflects a around the nearest 3D spherical obstacle (or XZ cylinder when a.PlanarXZ is true) intersecting its forward detection corridor of length maxAhead.
func OffsetPursuit3D(a, leader Agent3D, localOffset Vec3, slowRadius, maxLookAhead float32) Vec3OffsetPursuit3D steers a toward localOffset expressed in leader's right-handed Y-up heading frame (+X right, +Y up, -Z forward, so +Z trails behind the leader), predicting leader's motion up to maxLookAhead seconds when positive and slowing smoothly inside slowRadius via Arrive3D.
func Pursue3D(a, target Agent3D, maxLookAhead float32) Vec3Pursue3D returns a steering force that intercepts target by predicting its future position from target.Vel, capped to maxLookAhead seconds when positive.
func Seek3D(a Agent3D, target Vec3) Vec3Seek3D returns the 3D (or XZ-planar) steering force accelerating a toward target at MaxSpeed.
func Separation3D(a Agent3D, neighbors []Agent3D, desiredSep float32) Vec3Separation3D pushes a away from neighbors closer than desiredSep (defaulting to a.Radius + neighbor.Radius when desiredSep <= 0).
func WallAvoidance3D(a Agent3D, walls []Wall3D, feelerLength float32) Vec3WallAvoidance3D steers a away from vertical XZ wall segments using three horizontal feeler whiskers and direct radius clearance containment.
type Wall struct {
A, B core.Point
}Wall is a 2D line segment from A to B used by WallAvoidance.
type Wall3D struct {
A, B Vec3
}Wall3D is a vertical wall segment from A to B projected onto the horizontal XZ plane, used by WallAvoidance3D.
type WanderState struct {
Angle float32
}WanderState holds the persistent wander angle for an agent across steps.
type WaypointEdge struct {
To int
Cost float64
}WaypointEdge is a directed outgoing edge in a WaypointGraph.
type WaypointGraph struct {
// contains filtered or unexported fields
}WaypointGraph is a weighted graph of hand-placed 2D or 3D waypoints implementing HeuristicGraph[int], ValidatedGraph[int], and NodeOrder[int].
Each added waypoint receives a stable integer ID (0, 1, 2, ...). Removing a waypoint invalidates its ID without renumbering remaining waypoints. Edges may be directed or undirected, with either automatic Euclidean-distance costs (Connect / ConnectUndirected) or explicit non-negative weights (AddEdge / AddUndirectedEdge).
Heuristic returns the Euclidean distance between two waypoints, which is admissible when every edge cost is at least Euclidean distance; use GraphSearch.FindDijkstra or FindWithHeuristic when graphs contain shortcut or portal edges cheaper than Euclidean distance.
func NewWaypointGraph() *WaypointGraphNewWaypointGraph returns an empty WaypointGraph.
func (g *WaypointGraph) Add(pos core.Point) intAdd adds a 2D waypoint at pos (with Z = 0) and returns its stable node ID.
func (g *WaypointGraph) Add3D(pos Vec3) intAdd3D adds a 3D waypoint at pos and returns its stable node ID.
func (g *WaypointGraph) AddEdge(from, to int, cost float64) boolAddEdge adds or updates a directed edge from -> to with explicit non-negative finite cost. Returns false if either endpoint is invalid/removed or cost is negative, NaN, or infinite.
func (g *WaypointGraph) AddUndirectedEdge(a, b int, cost float64) boolAddUndirectedEdge adds or updates bidirectional edges between a and b with explicit non-negative finite cost. Returns false if either endpoint is invalid/removed or cost is negative, NaN, or infinite.
func (g *WaypointGraph) AppendNeighbors(dst []GraphEdge[int], id int) []GraphEdge[int]AppendNeighbors appends all outgoing edges from id to enabled destination waypoints onto dst in deterministic ascending destination ID order.
func (g *WaypointGraph) Connect(from, to int) boolConnect adds or updates a directed edge from -> to whose cost is the live Euclidean distance between the two waypoints. Returns false if either endpoint is invalid or removed.
func (g *WaypointGraph) ConnectUndirected(a, b int) boolConnectUndirected adds or updates bidirectional edges between a and b whose cost is the live Euclidean distance between them. Returns false if either endpoint is invalid or removed.
func (g *WaypointGraph) Edges(id int) []WaypointEdgeEdges returns a copy of waypoint id's outgoing edges ordered by ascending destination ID.
func (g *WaypointGraph) Enabled(id int) boolEnabled reports whether id is an active, enabled waypoint.
func (g *WaypointGraph) Heuristic(from, goal int) float64Heuristic returns the Euclidean distance between waypoints from and goal.
func (g *WaypointGraph) Nearest(pos core.Point) (int, bool)Nearest returns the ID of the enabled waypoint closest to 2D point pos (in XY), breaking distance ties deterministically by lowest waypoint ID.
func (g *WaypointGraph) Nearest3D(pos Vec3) (int, bool)Nearest3D returns the ID of the enabled waypoint closest to 3D point pos, breaking distance ties deterministically by lowest waypoint ID.
func (g *WaypointGraph) NodeCount() intNodeCount returns the number of active (non-removed) waypoints in g.
func (g *WaypointGraph) NodeLess(a, b int) boolNodeLess breaks search ties deterministically by ascending waypoint ID.
func (g *WaypointGraph) Points(ids []int) []core.PointPoints converts a slice of waypoint IDs into their 2D positions.
func (g *WaypointGraph) Points3D(ids []int) []Vec3Points3D converts a slice of waypoint IDs into their 3D positions.
func (g *WaypointGraph) Points3DInto(dst []Vec3, ids []int) []Vec3Points3DInto writes the 3D positions of ids into dst[:0], avoiding allocations when dst has enough capacity.
func (g *WaypointGraph) PointsInto(dst []core.Point, ids []int) []core.PointPointsInto writes the 2D positions of ids into dst[:0], avoiding allocations when dst has enough capacity.
func (g *WaypointGraph) Pos(id int) (core.Point, bool)Pos returns the 2D position of active waypoint id, or (zero, false) if id is invalid or removed.
func (g *WaypointGraph) Pos3D(id int) (Vec3, bool)Pos3D returns the 3D position of active waypoint id, or (zero, false) if id is invalid or removed.
func (g *WaypointGraph) Remove(id int) boolRemove deletes waypoint id and all edges incident to it while keeping all other node IDs stable. It returns false if id is invalid or already removed.
func (g *WaypointGraph) RemoveEdge(from, to int) boolRemoveEdge removes the directed edge from -> to, returning true if it existed.
func (g *WaypointGraph) RemoveUndirectedEdge(a, b int) boolRemoveUndirectedEdge removes both a -> b and b -> a, returning true if either existed.
func (g *WaypointGraph) SetEnabled(id int, enabled bool)SetEnabled enables or disables an active waypoint without removing its edges. Disabled waypoints are skipped during searches and Nearest queries.
func (g *WaypointGraph) SetPos(id int, pos core.Point)SetPos updates the 2D position of waypoint id (setting Z = 0).
func (g *WaypointGraph) SetPos3D(id int, pos Vec3)SetPos3D updates the 3D position of waypoint id.
func (g *WaypointGraph) ValidNode(id int) boolValidNode reports whether id is an active, enabled waypoint in g.
type WeightedForce struct {
Force core.Point
Weight float32
}WeightedForce pairs a steering force with a scalar weight for Combine.
type WeightedForce3D struct {
Force Vec3
Weight float32
}WeightedForce3D pairs a 3D steering force with a scalar weight for Combine3D and CombinePrioritized3D.
type WeightedLayer struct {
Layer *InfluenceLayer
Weight float32
}WeightedLayer pairs an InfluenceLayer with a scalar weight for InfluenceLayer.Combine.
type WeightedNode struct {
Node Node
Weight float64
}WeightedNode pairs a behavior tree child Node with a relative selection weight for WeightedSelector.
Options with Weight <= 0, NaN, Inf, or a nil Node are never selected.
type WorldState struct {
// contains filtered or unexported fields
}WorldState is a compact, comparable snapshot of an agent's world facts: up to MaxBoolFacts boolean facts packed into a 128-bit bitset and up to MaxIntFacts small int16 facts.
func (w WorldState) Apply(eff Effects) WorldStateApply returns a copy of w updated with eff.
func (w WorldState) Bool(f BoolFact) boolBool returns the value of boolean fact f, or false if f is out of range.
func (w WorldState) Int(f IntFact) intInt returns the value of integer fact f, or 0 if f is out of range.
func (w WorldState) Satisfies(cond Conditions) boolSatisfies reports whether w satisfies every boolean and integer requirement in cond.
func (w *WorldState) SetBool(f BoolFact, v bool)SetBool sets boolean fact f to v. Out-of-range facts are ignored.
func (w *WorldState) SetInt(f IntFact, v int)SetInt sets integer fact f to v, clamped to the int16 range [-32768, 32767]. Out-of-range facts are ignored.
func (w WorldState) WithBool(f BoolFact, v bool) WorldStateWithBool returns a copy of w with boolean fact f set to v.
func (w WorldState) WithInt(f IntFact, v int) WorldStateWithInt returns a copy of w with integer fact f set to v (clamped to int16 range).