Documentation
¶
Overview ¶
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 ¶
- Constants
- Variables
- 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, ...) 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 ResetCooldowns(root Node)
- 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, ...) core.Point
- type AStar
- func (a *AStar) Find(g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (a *AStar) FindInto(dst []Cell, g Grid, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (a *AStar) FindWithOptions(g Grid, start, goal Cell, opts PathOptions) GridPathResult
- func (a *AStar) FindWithOptionsInto(dst []Cell, g Grid, start, goal Cell, opts PathOptions) GridPathResult
- func (a *AStar) MovementRange(g Grid, start Cell, budget float64) []ReachableCell
- func (a *AStar) MovementRangeInto(dst []ReachableCell, g Grid, start Cell, budget float64) []ReachableCell
- func (a *AStar) MovementRangeWithCost(dst []ReachableCell, g Grid, start Cell, budget float64, ...) []ReachableCell
- func (a *AStar) StartSearch(g Grid, start, goal Cell, opts PathOptions) *AStarSearch
- type AStarSearch
- func (s *AStarSearch) Expansions() int
- func (s *AStarSearch) Reset(a *AStar, g Grid, start, goal Cell, opts PathOptions)
- func (s *AStarSearch) Result() GridPathResult
- func (s *AStarSearch) ResultInto(dst []Cell) GridPathResult
- func (s *AStarSearch) Status() SearchStatus
- func (s *AStarSearch) Step(maxExpansions int) (status SearchStatus, expansions int)
- type AbortMode
- type Agent
- type Agent3D
- type AngleMode
- type AngleTest
- type Attitude
- type AttitudeFunc
- type AttitudeMask
- type BTBindings
- type BTBlackboardKeyDoc
- type 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 (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
- 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, ...) []CoverPoint
- func GenerateCoverFromSegments(segments []CoverSegment, opts ColliderCoverOptions) []CoverPoint
- func GenerateCoverFromTilemap(m *tilemap.Tilemap, opts TileCoverOptions) []CoverPoint
- func GenerateCoverFromWorld(w *physics.World, opts ColliderCoverOptions) []CoverPoint
- 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 (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 (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 (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
- type HPA
- func (h *HPA) AllowCornerCutting() bool
- func (h *HPA) ClusterAt(c Cell) (ClusterID, bool)
- func (h *HPA) ClusterGridSize() (cols, rows int)
- func (h *HPA) ClusterRect(id ClusterID) (ClusterRect, bool)
- func (h *HPA) ClusterSize() int
- func (h *HPA) Diagonal() bool
- func (h *HPA) Find(start, goal Cell) (path []Cell, cost float64, ok bool)
- func (h *HPA) FindAbstract(start, goal Cell) (waypoints []Cell, cost float64, ok bool)
- func (h *HPA) FindAbstractInto(dst []Cell, start, goal Cell) (waypoints []Cell, cost float64, ok bool)
- func (h *HPA) FindClusters(start, goal Cell) (clusters []ClusterID, cost float64, ok bool)
- func (h *HPA) FindClustersInto(dst []ClusterID, start, goal Cell) (clusters []ClusterID, cost float64, ok bool)
- func (h *HPA) FindInto(dst []Cell, start, goal Cell) (path []Cell, cost float64, ok bool)
- func (h *HPA) Grid() Grid
- func (h *HPA) GridSize() (cols, rows int)
- func (h *HPA) RebuildDirty() int
- func (h *HPA) Stats() HPAStats
- func (h *HPA) UpdateCell(col, row int)
- func (h *HPA) UpdateRect(minCol, minRow, maxCol, maxRow int)
- type HPAOptions
- type HPAStats
- type HearingConfig
- type HeatmapOptions
- type HeuristicGraph
- type HexGrid
- func (h *HexGrid) AppendNeighbors(dst []GraphEdge[Cell], c Cell) []GraphEdge[Cell]
- func (h *HexGrid) EdgeCost(fromCol, fromRow, toCol, toRow int) float64
- func (h *HexGrid) GridSize() (cols, rows int)
- func (h *HexGrid) Heuristic(from, goal Cell) float64
- func (h *HexGrid) MoveCost(col, row int) float64
- func (h *HexGrid) NodeLess(a, b Cell) bool
- func (h *HexGrid) ValidNode(c Cell) bool
- func (h *HexGrid) Walkable(col, row int) bool
- type IncrementalSearch
- type 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 (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 (a *NavAgent) ClearTarget()
- func (a *NavAgent) Config() NavAgentConfig
- func (a *NavAgent) Corridor() []int
- func (a *NavAgent) ForceReplan() bool
- func (a *NavAgent) HasTarget() bool
- func (a *NavAgent) LocalRepairCount() int
- func (a *NavAgent) NeedsReplan() bool
- func (a *NavAgent) NextCorner() (core.Point, bool)
- func (a *NavAgent) Path() []core.Point
- func (a *NavAgent) Pos() core.Point
- func (a *NavAgent) ReplanCount() int
- func (a *NavAgent) SetMesh(mesh *NavMesh)
- func (a *NavAgent) SetPosition(pos core.Point)
- func (a *NavAgent) SetTarget(target core.Point)
- func (a *NavAgent) SetVelocity(v core.Point)
- func (a *NavAgent) State() NavAgentState
- func (a *NavAgent) Step(dt time.Duration)
- func (a *NavAgent) Target() core.Point
- func (a *NavAgent) TraversingLink() (NavLinkEvent, bool)
- func (a *NavAgent) Vel() core.Point
- type NavAgentConfig
- type NavAgentGroup
- func (g *NavAgentGroup) Add(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgent
- func (g *NavAgentGroup) AddAgent(a *NavAgent)
- func (g *NavAgentGroup) Agents() []*NavAgent
- func (g *NavAgentGroup) LastStepReplans() int
- func (g *NavAgentGroup) Len() int
- func (g *NavAgentGroup) Remove(a *NavAgent) bool
- func (g *NavAgentGroup) Step(dt time.Duration)
- func (g *NavAgentGroup) Steps() uint64
- func (g *NavAgentGroup) TotalReplans() int
- type NavAgentGroupConfig
- type NavAgentState
- type NavArea
- type NavFilter
- type NavFlags
- type NavLinkEvent
- type NavListenerID
- type NavMesh
- func (m *NavMesh) AddOffMeshLink(link NavOffMeshLink) bool
- func (m *NavMesh) AddPolygonFlags(index int, flags NavFlags)
- func (m *NavMesh) 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 (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
- 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, ...) 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, ...) 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 (s *ORCASolver) Config() ORCAConfig
- func (s *ORCASolver) SetConfig(cfg ORCAConfig)
- func (s *ORCASolver) Solve(dst []math2d.Vec2, agents []ORCAAgent, obstacles []ORCAObstacle, ...) []math2d.Vec2
- func (s *ORCASolver) SolveAgent(agent ORCAAgent, neighbors []ORCAAgent, obstacles []ORCAObstacle, ...) math2d.Vec2
- func (s *ORCASolver) SolveAgentXZ(agent ORCAAgent3D, neighbors []ORCAAgent3D, obstacles []ORCAObstacle3D, ...) 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 (q *PathQueue) Cancel(id PathRequestID) bool
- func (q *PathQueue) Clear()
- func (q *PathQueue) Completed() int
- func (q *PathQueue) IsPending(id PathRequestID) bool
- func (q *PathQueue) Pending() int
- func (q *PathQueue) Step(budget int) int
- func (q *PathQueue) StepDefault() int
- func (q *PathQueue) Submit(search IncrementalSearch, priority int, ...) PathRequestID
- func (q *PathQueue) SubmitGrid(a *AStar, g Grid, start, goal Cell, opts PathOptions, priority int, ...) (PathRequestID, *AStarSearch)
- func (q *PathQueue) SubmitNavMesh(m *NavMesh, start, goal core.Point, opts PathOptions, priority int, ...) (PathRequestID, *NavMeshSearch)
- func (q *PathQueue) TotalExpansions() int
- type PathQueueConfig
- type PathQueuePolicy
- type PathRequestID
- type 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
- func (s *PerceptionSystem) Add(p *Perception)
- func (s *PerceptionSystem) Len() int
- func (s *PerceptionSystem) PostNoise(n Noise)
- func (s *PerceptionSystem) Remove(p *Perception) bool
- func (s *PerceptionSystem) Stats() PerceptionStats
- func (s *PerceptionSystem) Step(dt time.Duration, targets []Target)
- type PlanRunner
- type 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 (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 (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
- type RingGenerator
- type SearchStatus
- type Sense
- type SightConfig
- type SlotAgent
- type 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 (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 (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 (tm *TiledNavMesh) AddObstacle(obs NavObstacle) (NavObstacleID, bool)
- func (tm *TiledNavMesh) AddOffMeshLink(link NavOffMeshLink) bool
- func (tm *TiledNavMesh) AddTile(coord NavTileCoord, tile *NavTile) bool
- func (tm *TiledNavMesh) AddTileListener(fn func(NavTileChange)) NavListenerID
- func (tm *TiledNavMesh) BakeTile(coord NavTileCoord, polys []NavPolygonInput) *NavTile
- func (tm *TiledNavMesh) Batch(fn func())
- func (tm *TiledNavMesh) ClearObstacles()
- func (tm *TiledNavMesh) ClearOffMeshLinks()
- func (tm *TiledNavMesh) Contains(p core.Point) bool
- func (tm *TiledNavMesh) ContainsWithFilter(p core.Point, filter NavFilter) bool
- func (tm *TiledNavMesh) FindCorridor(start, goal core.Point) ([]NavPolyRef, bool)
- func (tm *TiledNavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]NavPolyRef, bool)
- func (tm *TiledNavMesh) FindPath(start, goal core.Point) ([]core.Point, bool)
- func (tm *TiledNavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)
- func (tm *TiledNavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) TiledNavPathResult
- func (tm *TiledNavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) TiledNavPathResult
- func (tm *TiledNavMesh) FindPolygon(p core.Point) (NavPolyRef, bool)
- func (tm *TiledNavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, bool)
- func (tm *TiledNavMesh) HasTile(coord NavTileCoord) bool
- func (tm *TiledNavMesh) IsPathValid(res TiledNavPathResult) bool
- func (tm *TiledNavMesh) NearestPoint(p, extent core.Point) (core.Point, NavPolyRef, bool)
- func (tm *TiledNavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, NavPolyRef, bool)
- func (tm *TiledNavMesh) NearestPolygon(p core.Point) (NavPolyRef, core.Point, bool)
- func (tm *TiledNavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, core.Point, bool)
- func (tm *TiledNavMesh) Neighbors(ref NavPolyRef) []NavPolyRef
- func (tm *TiledNavMesh) ObstacleCount() int
- func (tm *TiledNavMesh) OffMeshLinks() []NavOffMeshLink
- func (tm *TiledNavMesh) Origin() core.Point
- func (tm *TiledNavMesh) Polygon(ref NavPolyRef) []core.Point
- func (tm *TiledNavMesh) PolygonArea(ref NavPolyRef) NavArea
- func (tm *TiledNavMesh) PolygonCount() int
- func (tm *TiledNavMesh) PolygonFlags(ref NavPolyRef) NavFlags
- func (tm *TiledNavMesh) Raycast(start, target core.Point) (TiledNavRaycastHit, bool)
- func (tm *TiledNavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (TiledNavRaycastHit, bool)
- func (tm *TiledNavMesh) RebuildTile(coord NavTileCoord) bool
- func (tm *TiledNavMesh) RemoveObstacle(id NavObstacleID) bool
- func (tm *TiledNavMesh) RemoveTile(coord NavTileCoord) bool
- func (tm *TiledNavMesh) RemoveTileListener(id NavListenerID) bool
- func (tm *TiledNavMesh) ReplaceTile(coord NavTileCoord, tile *NavTile) bool
- func (tm *TiledNavMesh) Revision() uint64
- func (tm *TiledNavMesh) SetTile(coord NavTileCoord, tile *NavTile) bool
- func (tm *TiledNavMesh) TileBounds(coord NavTileCoord) (minPt, maxPt core.Point)
- func (tm *TiledNavMesh) TileCoordAt(p core.Point) NavTileCoord
- func (tm *TiledNavMesh) TileCoords() []NavTileCoord
- func (tm *TiledNavMesh) TileCount() int
- func (tm *TiledNavMesh) TilePolygonCount(coord NavTileCoord) int
- func (tm *TiledNavMesh) TileSize() float32
- func (tm *TiledNavMesh) TileVersion(coord NavTileCoord) uint64
- func (tm *TiledNavMesh) UnwatchPath(id NavPathWatchID) bool
- func (tm *TiledNavMesh) UpdateObstacle(id NavObstacleID, obs NavObstacle) bool
- func (tm *TiledNavMesh) WatchPath(tiles []NavTileCoord, onInvalidate func(NavTileChange)) NavPathWatchID
- type TiledNavMeshConfig
- type TiledNavPathLink
- type TiledNavPathResult
- type TiledNavRaycastHit
- type TokenHolder
- type 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 (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, ...) 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 (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
Examples ¶
Constants ¶
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 = 1
BTFormatVersion is the behavior tree YAML schema version this package reads and writes.
const BTSchemaComment = "# yaml-language-server: $schema=" + BTSchemaURL
BTSchemaComment 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 = 1
BTSnapshotVersion is the BehaviorTreeSnapshot schema version written and read by SnapshotBehaviorTree and RestoreBehaviorTree.
const GOAPVersion = 1
GOAPVersion 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 = 1
UtilityVersion is the utility AI YAML schema version this package reads and writes.
Variables ¶
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.
Functions ¶
func Alignment ¶
Alignment 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 ¶
Arrive returns a steering force toward target that smoothly scales desired speed down to zero inside slowRadius.
func Cohesion ¶
Cohesion 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 ¶
func Combine(maxForce float32, forces ...WeightedForce) core.Point
Combine sums weighted steering forces and clamps the result's magnitude to maxForce when maxForce is positive.
func CombinePrioritized ¶
func CombinePrioritized(maxForce float32, forces ...WeightedForce) core.Point
CombinePrioritized 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 ¶
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 ¶
func EncodeGOAP(cfg *GOAPConfig) ([]byte, error)
EncodeGOAP validates cfg and encodes it as deterministic 2-space YAML in fixed field order.
func EncodeUtility ¶
func EncodeUtility(cfg *UtilityConfig) ([]byte, error)
EncodeUtility validates cfg and encodes it as deterministic 2-space YAML in fixed field order.
func Evade ¶
Evade 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 ¶
Flee 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 ¶
func FollowPath(a Agent, path []core.Point, state *PathFollowState, waypointRadius float32, loop bool) core.Point
FollowPath 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.
Example ¶
FollowPath steers along waypoints and records progress in a PathFollowState.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/ai"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
a := ai.Agent{MaxSpeed: 50, MaxForce: 500}
path := []core.Point{{X: 10, Y: 0}, {X: 10, Y: 10}}
var state ai.PathFollowState
steps := 0
for !state.Done && steps < 1000 {
a.Step(ai.FollowPath(a, path, &state, 1, false), time.Second/60)
steps++
}
fmt.Println(state.Done, state.Index)
}
Output: true 1
func FormatBTTrace ¶
func FormatBTTrace(nodes []BTNodeTrace) string
FormatBTTrace 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 ¶
func GridLineOfSight(g Grid, a, b core.Point, opts GridPathOptions) bool
GridLineOfSight reports whether a circular body of radius opts.Radius can move straight from a to b on g without passing within opts.Radius of any blocked cell (!g.Walkable(col, row)).
Returns false when g is nil, has non-positive dimensions, or either endpoint lies outside the grid's world bounds.
func Hide ¶
Hide 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 ¶
func InfluenceHeatmapEnabled() bool
InfluenceHeatmapEnabled reports whether DrawHeatmap is compiled into this build. It is true in default builds and false when built with -tags release.
func Interpose ¶
Interpose steers a to intercept the predicted midpoint between two moving agents targetA and targetB, slowing smoothly inside slowRadius via Arrive.
func ObstacleAvoidance ¶
ObstacleAvoidance 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 ¶
func OffsetPursuit(a, leader Agent, localOffset core.Point, slowRadius, maxLookAhead float32) core.Point
OffsetPursuit 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 ¶
Pursue 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 ResetCooldowns ¶
func ResetCooldowns(root Node)
ResetCooldowns clears every active Cooldown timer in the behavior tree rooted at root without interrupting running branches.
Unlike Node.Reset, which preserves active cooldowns across branch interruptions such as Guard, Selector preemption, and TimeLimit, ResetCooldowns performs an explicit cooldown reset (for example when respawning an agent).
func RestoreBehaviorTree ¶
func RestoreBehaviorTree(root Node, snap BehaviorTreeSnapshot) error
RestoreBehaviorTree 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 Separation ¶
Separation 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 ¶
func SmoothGridPath(g Grid, path []Cell, opts GridPathOptions) []core.Point
SmoothGridPath converts a grid cell path (such as from AStar.Find) into world-space waypoints, dropping intermediate cells whenever a body of radius opts.Radius can walk straight between kept waypoints without passing within opts.Radius of any blocked cell.
SmoothGridPath checks walkability via g.Walkable and ignores CostGrid terrain weights. When smoothing with a positive opts.Radius, pair it with standard cell-by-cell AStar (AnyAngle: false) so corner cells remain available when the body radius cannot clear a corner directly.
It allocates only the returned waypoint slice; use SmoothGridPathInto to reuse a caller-owned slice with zero allocations.
Example ¶
SmoothGridPath turns a grid A* path into world-space waypoints while keeping a body radius clear of blocked cells.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
grid := ai.NewBoolGrid(6, 4)
path, _, _ := ai.NewAStar().Find(grid, ai.Cell{Col: 0, Row: 0}, ai.Cell{Col: 5, Row: 3})
waypoints := ai.SmoothGridPath(grid, path, ai.GridPathOptions{CellSize: 16, Radius: 5})
fmt.Println(len(path), "->", len(waypoints), waypoints)
}
Output: 9 -> 2 [{8 8} {88 56}]
func SmoothGridPathInto ¶
SmoothGridPathInto behaves like SmoothGridPath but appends the smoothed waypoints into dst[:0], avoiding heap allocations when dst has enough capacity.
func SquadStateGet ¶
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 ¶
func ValidateBehaviorTree(doc *BehaviorTreeDoc) error
ValidateBehaviorTree checks that doc conforms to the version 1 behavior tree schema.
func WallAvoidance ¶
WallAvoidance 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 ¶
func Wander(a Agent, state *WanderState, radius, distance, jitter float32, nextRand func() float32) core.Point
Wander 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.
Example ¶
Wander picks a smoothly changing heading from a caller-supplied random source, so the same source gives the same walk.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
seed := uint32(1)
next := func() float32 {
seed = seed*1664525 + 1013904223
return float32(seed>>8) / (1 << 24)
}
a := ai.Agent{MaxSpeed: 20, MaxForce: 40}
var state ai.WanderState
for range 10 {
a.Step(ai.Wander(a, &state, 5, 10, 0.5, next), time.Second/10)
}
fmt.Printf("%.2f %.2f\n", a.Pos.X, a.Pos.Y)
}
Output: 7.96 -2.05
Types ¶
type AStar ¶
type AStar struct {
// Diagonal allows 8-way movement with step distance sqrt(2) on diagonals; false restricts movement to 4 cardinal directions.
// On hexagonal topologies Diagonal has no effect; TopologySquare4 and TopologySquare8 override Diagonal.
Diagonal bool
// NoCornerCutting prevents diagonal moves when either adjacent cardinal cell is blocked. It only takes effect when diagonal moves are enabled, and also prevents Theta* any-angle lines of sight from grazing blocked cell corners when AnyAngle is true.
NoCornerCutting bool
// AnyAngle enables Theta*-style any-angle pathfinding on square grids (TopologySquare, TopologySquare4, TopologySquare8),
// linking neighbors directly to an ancestor cell whenever line of sight between cell centers is unobstructed across uniform-cost cells.
// AnyAngle is ignored on hexagonal or staggered topologies and on EdgeCostGrid maps.
// When smoothing a path for a body with positive clearance radius, prefer standard cell-by-cell A* (AnyAngle: false) followed by SmoothGridPath or SmoothGridPathInto.
AnyAngle bool
// Topology selects the cell adjacency and admissible distance heuristic. The zero value (TopologySquare) preserves square-grid behavior.
Topology GridTopology
// MaxExpansions caps the number of cells expanded per Find or FindInto call.
// Zero or negative means unlimited expansions. FindWithOptions uses this limit when PathOptions.MaxExpansions is zero.
MaxExpansions int
// contains filtered or unexported fields
}
AStar finds lowest-cost paths on a Grid, reusing its internal search buffers across calls.
NewAStar returns a searcher with NoCornerCutting enabled by default. An AStar is not safe for concurrent use by multiple goroutines.
Example ¶
AStar finds the cheapest path around the walls of a BoolGrid.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
grid := ai.NewBoolGrid(5, 3)
for row := range 2 {
grid.SetWalkable(2, row, false)
}
path, cost, ok := ai.NewAStar().Find(grid, ai.Cell{Col: 0, Row: 0}, ai.Cell{Col: 4, Row: 0})
fmt.Println(ok, cost)
fmt.Println(path)
}
Output: true 8 [{0 0} {1 0} {1 1} {1 2} {2 2} {3 2} {3 1} {3 0} {4 0}]
func NewAStar ¶
func NewAStar() *AStar
NewAStar returns an AStar searcher with 4-way movement and NoCornerCutting enabled by default.
func (*AStar) Find ¶
Find searches g for a minimum-cost path from start to goal, returning the cells from start to goal inclusive and the total path cost.
It reuses all internal search buffers and allocates only the returned path slice.
func (*AStar) FindInto ¶
FindInto behaves like Find but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.
func (*AStar) FindWithOptions ¶
func (a *AStar) FindWithOptions(g Grid, start, goal Cell, opts PathOptions) GridPathResult
FindWithOptions searches g from start to goal under opts, supporting an expansion budget and optional partial paths to the closest explored cell when the goal is unreachable or the budget runs out.
func (*AStar) FindWithOptionsInto ¶
func (a *AStar) FindWithOptionsInto(dst []Cell, g Grid, start, goal Cell, opts PathOptions) GridPathResult
FindWithOptionsInto behaves like FindWithOptions but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.
func (*AStar) MovementRange ¶
func (a *AStar) MovementRange(g Grid, start Cell, budget float64) []ReachableCell
MovementRange runs a Dijkstra search from start on g under a.Topology (and a.Diagonal / a.NoCornerCutting) and returns every reachable cell whose minimum traversal cost is at most budget, ordered by ascending cost then row-major cell index.
It reuses a's internal search buffers and allocates only the returned slice.
func (*AStar) MovementRangeInto ¶
func (a *AStar) MovementRangeInto(dst []ReachableCell, g Grid, start Cell, budget float64) []ReachableCell
MovementRangeInto behaves like MovementRange but writes results into dst[:0], avoiding heap allocations when dst has enough capacity.
func (*AStar) MovementRangeWithCost ¶
func (a *AStar) MovementRangeWithCost(dst []ReachableCell, g Grid, start Cell, budget float64, edgeCost func(from, to Cell) float64) []ReachableCell
MovementRangeWithCost behaves like MovementRangeInto, and when edgeCost is non-nil uses edgeCost(from, to) as the step cost multiplier instead of CostGrid or EdgeCostGrid.
Returning a negative, NaN or infinite value from edgeCost forbids moving along that edge. Non-negative finite values (including costs between 0 and 1, such as roads) are multiplied by the step's geometric length (1 for cardinal/hex/staggered edges, sqrt(2) for diagonals).
func (*AStar) StartSearch ¶
func (a *AStar) StartSearch(g Grid, start, goal Cell, opts PathOptions) *AStarSearch
StartSearch begins an incremental grid A* search using a's configuration (Diagonal, NoCornerCutting, Topology, MaxExpansions). The returned AStarSearch owns independent search buffers so multiple searches may run across frames concurrently.
type AStarSearch ¶
type AStarSearch struct {
// contains filtered or unexported fields
}
AStarSearch runs a deterministic grid A* search incrementally across bounded Step calls.
Stepping a search with any positive per-step expansion budget produces the exact same path, cost, partial flag, and expansion count as a single-shot AStar.FindWithOptions call. *AStarSearch implements IncrementalSearch.
func NewAStarSearch ¶
func NewAStarSearch(a *AStar, g Grid, start, goal Cell, opts PathOptions) *AStarSearch
NewAStarSearch initializes an incremental grid A* search copying configuration from a (when a is nil, defaults to 4-way TopologySquare with NoCornerCutting enabled).
func (*AStarSearch) Expansions ¶
func (s *AStarSearch) Expansions() int
Expansions returns the cumulative number of grid cells expanded so far.
func (*AStarSearch) Reset ¶
func (s *AStarSearch) Reset(a *AStar, g Grid, start, goal Cell, opts PathOptions)
Reset reinitializes s for a new query, reusing its internal search buffers.
func (*AStarSearch) Result ¶
func (s *AStarSearch) Result() GridPathResult
Result returns the search outcome once finished (or a result with Found == false while still in progress).
func (*AStarSearch) ResultInto ¶
func (s *AStarSearch) ResultInto(dst []Cell) GridPathResult
ResultInto behaves like Result but writes the path into dst[:0] when finished.
func (*AStarSearch) Status ¶
func (s *AStarSearch) Status() SearchStatus
Status returns the search's current status.
func (*AStarSearch) Step ¶
func (s *AStarSearch) Step(maxExpansions int) (status SearchStatus, expansions int)
Step advances the search by at most maxExpansions grid cell expansions and returns the updated status and exact number of expansions performed. When maxExpansions <= 0 or the search is already finished, Step performs 0 expansions.
type AbortMode ¶
type AbortMode string
AbortMode 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" )
type Agent ¶
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.
Example ¶
Steering forces move an Agent; Combine weighs several of them and caps the total at the agent's MaxForce.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/ai"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
a := ai.Agent{MaxSpeed: 100, MaxForce: 400}
target := core.Point{X: 100, Y: 0}
for range 30 {
force := ai.Combine(a.MaxForce,
ai.WeightedForce{Force: ai.Arrive(a, target, 40), Weight: 1},
ai.WeightedForce{Force: ai.Flee(a, core.Point{X: 0, Y: 50}, 20), Weight: 2},
)
a.Step(force, time.Second/30)
}
fmt.Printf("x %.1f y %.1f\n", a.Pos.X, a.Pos.Y)
}
Output: x 38.3 y 0.0
type Agent3D ¶
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.
type AngleMode ¶
type AngleMode uint8
AngleMode 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 ¶
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 ¶
type Attitude uint8
Attitude is how an observer regards another team.
func DefaultAttitude ¶
DefaultAttitude treats the same team as friendly, NoTeam on either side as neutral, and every other pair of teams as hostile.
type AttitudeFunc ¶
AttitudeFunc decides how an observer on team observer regards a stimulus on team other.
type AttitudeMask ¶
type AttitudeMask uint8
AttitudeMask 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 (AttitudeMask) Has ¶
func (m AttitudeMask) Has(a Attitude) bool
Has reports whether m detects attitude a, treating a zero mask as DetectHostile.
type BTBindings ¶
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 ¶
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 bool `yaml:"shared,omitempty"`
// 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 ¶
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 ¶
func NewBTInspector(root Node) *BTInspector
NewBTInspector 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 (*BTInspector) Format ¶
func (ins *BTInspector) Format() string
Format returns a deterministic, human-readable text snapshot of the tree's current state suitable for statedump Values and diffing AI decisions across runs.
func (*BTInspector) Len ¶
func (ins *BTInspector) Len() int
Len returns the total number of nodes in the inspected tree.
func (*BTInspector) Reset ¶
func (ins *BTInspector) Reset()
Reset resets ins's root node and clears any root fallback status.
func (*BTInspector) Root ¶
func (ins *BTInspector) Root() Node
Root returns the behavior tree root inspected by ins.
func (*BTInspector) RunningPath ¶
func (ins *BTInspector) RunningPath() []BTNodeTrace
RunningPath 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 (*BTInspector) String ¶
func (ins *BTInspector) String() string
String implements fmt.Stringer by returning ins.Format().
func (*BTInspector) Tick ¶
func (ins *BTInspector) Tick(dt time.Duration) Status
Tick 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 (*BTInspector) Walk ¶
func (ins *BTInspector) Walk() []BTNodeTrace
Walk 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 (*BTInspector) WalkInto ¶
func (ins *BTInspector) WalkInto(dst []BTNodeTrace) []BTNodeTrace
WalkInto 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 ¶
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 (BTNodeContext) Key ¶
func (c BTNodeContext) Key(name string) string
Key resolves a blackboard key name through any enclosing subtree key bindings, returning name unchanged when no remapping applies.
type BTNodeDoc ¶
type BTNodeDoc struct {
// Type selects the behavior tree node kind.
Type BTNodeType `` /* 248-byte string literal not displayed */
// 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 ¶
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 ¶
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 ¶
func InspectBehaviorTree(root Node) []BTNodeTrace
InspectBehaviorTree 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 ¶
func RunningPathInto(dst []BTNodeTrace, nodes []BTNodeTrace) []BTNodeTrace
RunningPathInto 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 (BTNodeTrace) StatusString ¶
func (t BTNodeTrace) StatusString() string
StatusString returns "Idle" when t has not been ticked since construction or Reset, and t.LastStatus.String() otherwise.
type BTNodeType ¶
type BTNodeType string
BTNodeType 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 ¶
type BTParallelPolicyName string
BTParallelPolicyName 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 ¶
BTParams holds resolved typed parameters passed to a leaf or service factory.
func (BTParams) Bool ¶
Bool returns the bool parameter name, or (false, false) if absent or not a bool.
func (BTParams) Duration ¶
Duration parses a Go duration string parameter name, returning (0, false) if absent or invalid.
func (BTParams) Float ¶
Float returns the numeric parameter name as float64, accepting int or float values.
func (BTParams) Int ¶
Int returns the integer parameter name, or (0, false) if absent or not an integer.
func (BTParams) Point ¶
Point returns a 2-element numeric array parameter as a core.Point.
func (BTParams) String ¶
String returns the string parameter name, or ("", false) if absent or not a string.
func (BTParams) Vec2 ¶
Vec2 returns a 2-element numeric array parameter as a math2d.Vec2.
type BehaviorTree ¶
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 ¶
func NewBehaviorTree(root Node) *BehaviorTree
NewBehaviorTree wraps root in a BehaviorTree.
func (*BehaviorTree) Reset ¶
func (bt *BehaviorTree) Reset()
Reset clears any in-progress state on the root node and its descendants. Active Cooldown timers are preserved; call BehaviorTree.ResetCooldowns to clear them.
func (*BehaviorTree) ResetCooldowns ¶
func (bt *BehaviorTree) ResetCooldowns()
ResetCooldowns clears every active Cooldown timer in bt without interrupting running branches.
func (*BehaviorTree) Restore ¶
func (bt *BehaviorTree) Restore(snap BehaviorTreeSnapshot) error
Restore validates snap against bt's structure and applies it atomically without mutating any node on error.
func (*BehaviorTree) Root ¶
func (bt *BehaviorTree) Root() Node
Root returns the tree's root Node, or nil if bt is nil.
func (*BehaviorTree) Snapshot ¶
func (bt *BehaviorTree) Snapshot() (BehaviorTreeSnapshot, error)
Snapshot captures bt's structural shape and mutable runtime state.
func (*BehaviorTree) Tick ¶
func (bt *BehaviorTree) Tick(dt time.Duration) Status
Tick advances the root node by dt, returning StatusFailure when bt or its root is nil.
type BehaviorTreeDoc ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func NewBlackboard() *Blackboard
NewBlackboard creates an empty standalone Blackboard.
func NewChildBlackboard ¶
func NewChildBlackboard(parent *Blackboard) *Blackboard
NewChildBlackboard creates a Blackboard scoped to an agent that falls back to parent for reads not shadowed locally.
func (*Blackboard) Bool ¶
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 (*Blackboard) Clear ¶
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 (*Blackboard) Delete ¶
func (b *Blackboard) Delete(key string)
Delete removes key from b's local scope, exposing any value stored in Parent.
func (*Blackboard) DeleteShared ¶
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 (*Blackboard) Entity ¶
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 (*Blackboard) Float ¶
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 (*Blackboard) Get ¶
func (b *Blackboard) Get(key string) (BlackboardValue, bool)
Get returns the effective value for key, falling back to Parent when unset locally.
func (*Blackboard) GetLocal ¶
func (b *Blackboard) GetLocal(key string) (BlackboardValue, bool)
GetLocal returns the value stored directly on b without consulting Parent.
func (*Blackboard) Has ¶
func (b *Blackboard) Has(key string) bool
Has reports whether key is set on b or any ancestor blackboard.
func (*Blackboard) HasLocal ¶
func (b *Blackboard) HasLocal(key string) bool
HasLocal reports whether key is set directly on b.
func (*Blackboard) Int ¶
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 (*Blackboard) KeyRevision ¶
func (b *Blackboard) KeyRevision(key string) uint64
KeyRevision returns a monotonically increasing mutation counter for key across b and any ancestor blackboards. It allocates zero bytes.
func (*Blackboard) Keys ¶
func (b *Blackboard) Keys(dst []string) []string
Keys appends all visible keys on b and its ancestors to dst[:0] in deterministic ascending order without duplicates.
func (*Blackboard) Kind ¶
func (b *Blackboard) Kind(key string) BlackboardKind
Kind returns the BlackboardKind of key, or BlackboardNone when unset.
func (*Blackboard) LocalKeys ¶
func (b *Blackboard) LocalKeys(dst []string) []string
LocalKeys appends all keys stored directly on b to dst[:0] in deterministic ascending order.
func (*Blackboard) Parent ¶
func (b *Blackboard) Parent() *Blackboard
Parent returns b's shared parent blackboard, or nil when b has no parent.
func (*Blackboard) Point ¶
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 (*Blackboard) Revision ¶
func (b *Blackboard) Revision() uint64
Revision returns a monotonically increasing mutation counter covering b and any ancestor blackboards.
func (*Blackboard) Set ¶
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 (*Blackboard) SetBool ¶
func (b *Blackboard) SetBool(key string, v bool)
SetBool stores a bool under key on b.
func (*Blackboard) SetEntity ¶
func (b *Blackboard) SetEntity(key string, id uint64)
SetEntity stores an entity ID under key on b.
func (*Blackboard) SetFloat ¶
func (b *Blackboard) SetFloat(key string, v float64)
SetFloat stores a float64 under key on b.
func (*Blackboard) SetInt ¶
func (b *Blackboard) SetInt(key string, v int)
SetInt stores an int under key on b.
func (*Blackboard) SetPoint ¶
func (b *Blackboard) SetPoint(key string, p core.Point)
SetPoint stores a core.Point as a 2D vector under key on b.
func (*Blackboard) SetShared ¶
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 (*Blackboard) SetSharedBool ¶
func (b *Blackboard) SetSharedBool(key string, v bool)
SetSharedBool stores a bool on the shared parent blackboard (or b if standalone).
func (*Blackboard) SetSharedEntity ¶
func (b *Blackboard) SetSharedEntity(key string, id uint64)
SetSharedEntity stores an entity ID on the shared parent blackboard (or b if standalone).
func (*Blackboard) SetSharedFloat ¶
func (b *Blackboard) SetSharedFloat(key string, v float64)
SetSharedFloat stores a float64 on the shared parent blackboard (or b if standalone).
func (*Blackboard) SetSharedInt ¶
func (b *Blackboard) SetSharedInt(key string, v int)
SetSharedInt stores an int on the shared parent blackboard (or b if standalone).
func (*Blackboard) SetSharedPoint ¶
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 (*Blackboard) SetSharedString ¶
func (b *Blackboard) SetSharedString(key string, v string)
SetSharedString stores a string on the shared parent blackboard (or b if standalone).
func (*Blackboard) SetSharedVec2 ¶
func (b *Blackboard) SetSharedVec2(key string, v math2d.Vec2)
SetSharedVec2 stores a 2D vector on the shared parent blackboard (or b if standalone).
func (*Blackboard) SetSharedVec3 ¶
func (b *Blackboard) SetSharedVec3(key string, v Vec3)
SetSharedVec3 stores a 3D vector on the shared parent blackboard (or b if standalone).
func (*Blackboard) SetString ¶
func (b *Blackboard) SetString(key string, v string)
SetString stores a string under key on b.
func (*Blackboard) SetVec2 ¶
func (b *Blackboard) SetVec2(key string, v math2d.Vec2)
SetVec2 stores a 2D vector under key on b.
func (*Blackboard) SetVec3 ¶
func (b *Blackboard) SetVec3(key string, v Vec3)
SetVec3 stores a 3D vector under key on b.
func (*Blackboard) String ¶
func (b *Blackboard) String(key string) (string, bool)
String returns the string stored under key, or ("", false) if unset or of another type.
func (*Blackboard) Vec2 ¶
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 (*Blackboard) Vec3 ¶
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 (*Blackboard) Watch ¶
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 ¶
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 ¶
type BlackboardKind uint8
BlackboardKind 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 (BlackboardKind) String ¶
func (k BlackboardKind) String() string
String returns the canonical YAML name for k.
type BlackboardKindName ¶
type BlackboardKindName string
BlackboardKindName 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 (BlackboardKindName) Kind ¶
func (n BlackboardKindName) Kind() (BlackboardKind, bool)
Kind converts a YAML BlackboardKindName into a BlackboardKind.
type BlackboardListener ¶
type BlackboardListener func(change BlackboardChange)
BlackboardListener is invoked synchronously when a watched blackboard key changes.
type BlackboardOp ¶
type BlackboardOp string
BlackboardOp 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 (BlackboardOp) NeedsValue ¶
func (op BlackboardOp) NeedsValue() bool
NeedsValue reports whether op compares against an explicit operand value.
func (BlackboardOp) Valid ¶
func (op BlackboardOp) Valid() bool
Valid reports whether op is a known BlackboardOp.
type BlackboardValue ¶
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 ¶
func BBEntity(id uint64) BlackboardValue
BBEntity returns a BlackboardValue holding entity identifier id.
func BBPoint ¶
func BBPoint(p core.Point) BlackboardValue
BBPoint returns a BlackboardValue holding p as a 2D vector.
func BBString ¶
func BBString(v string) BlackboardValue
BBString returns a BlackboardValue holding v.
func BBVec2 ¶
func BBVec2(v math2d.Vec2) BlackboardValue
BBVec2 returns a BlackboardValue holding v.
func (BlackboardValue) Equal ¶
func (v BlackboardValue) Equal(o BlackboardValue) bool
Equal reports whether v and o have the same kind and identical stored value.
func (BlackboardValue) IsZero ¶
func (v BlackboardValue) IsZero() bool
IsZero reports whether v represents an unset value (BlackboardNone).
type BoolFact ¶
type BoolFact uint8
BoolFact identifies a boolean fact slot (0..MaxBoolFacts-1) in a FactSchema and WorldState.
type BoolGrid ¶
type BoolGrid struct {
// contains filtered or unexported fields
}
BoolGrid is a Grid backed by a flat boolean slice. All cells start walkable.
func NewBoolGrid ¶
NewBoolGrid returns a cols-by-rows grid with every cell walkable.
func (*BoolGrid) SetWalkable ¶
SetWalkable marks (col, row) as walkable or blocked. Out-of-bounds coordinates are ignored.
type CandidateGenerator ¶
type CandidateGenerator interface {
Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidate
}
CandidateGenerator appends deterministic candidate positions to dst and returns the extended slice.
type ChildNodes ¶
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 ¶
type ClusterID struct {
Col, Row int
}
ClusterID identifies a cluster in an HPA grid by its cluster column and row.
type ClusterRect ¶
ClusterRect describes the inclusive-exclusive cell bounds [MinCol, MaxCol) x [MinRow, MaxRow) of an HPA cluster.
type ColliderCoverOptions ¶
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 ¶
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 (Conditions) Empty ¶
func (c Conditions) Empty() bool
Empty reports whether c imposes no boolean or integer constraints.
func (Conditions) RequireBool ¶
func (c Conditions) RequireBool(f BoolFact, v bool) Conditions
RequireBool returns a copy of c requiring boolean fact f to equal v.
func (Conditions) RequireIntEq ¶
func (c Conditions) RequireIntEq(f IntFact, v int) Conditions
RequireIntEq returns a copy of c requiring integer fact f == v.
func (Conditions) RequireIntGt ¶
func (c Conditions) RequireIntGt(f IntFact, v int) Conditions
RequireIntGt returns a copy of c requiring integer fact f > v.
func (Conditions) RequireIntGte ¶
func (c Conditions) RequireIntGte(f IntFact, v int) Conditions
RequireIntGte returns a copy of c requiring integer fact f >= v.
func (Conditions) RequireIntLt ¶
func (c Conditions) RequireIntLt(f IntFact, v int) Conditions
RequireIntLt returns a copy of c requiring integer fact f < v.
func (Conditions) RequireIntLte ¶
func (c Conditions) RequireIntLte(f IntFact, v int) Conditions
RequireIntLte returns a copy of c requiring integer fact f <= v.
func (Conditions) RequireIntRange ¶
func (c Conditions) RequireIntRange(f IntFact, lo, hi int) Conditions
RequireIntRange 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 (Conditions) SatisfiedBy ¶
func (c Conditions) SatisfiedBy(w WorldState) bool
SatisfiedBy reports whether w satisfies every constraint in c.
type Consideration ¶
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 (Consideration[C]) Eval ¶
func (c Consideration[C]) Eval(ctx C) float64
Eval reads Input(ctx), normalizes it to [0, 1], and evaluates Curve.
type ConsiderationDef ¶
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 ¶
CostGrid is a Grid whose walkable cells carry individual traversal costs.
MoveCost returns the cost multiplier for entering (col, row), at least 1 so the distance heuristic remains admissible; values less than or equal to 0 are treated as 1.
type CostMap ¶
type CostMap struct {
// contains filtered or unexported fields
}
CostMap is a CostGrid backed by a flat cost slice. All cells start walkable with cost 1.
Example ¶
A CostMap makes some cells dearer to cross, so AStar goes around them when that is cheaper.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
m := ai.NewCostMap(3, 3)
m.SetCost(1, 1, 10)
path, cost, _ := ai.NewAStar().Find(m, ai.Cell{Col: 1, Row: 0}, ai.Cell{Col: 1, Row: 2})
fmt.Println(len(path), cost)
}
Output: 5 4
func NewCostMap ¶
NewCostMap returns a cols-by-rows CostMap with every cell walkable at cost 1.
func (*CostMap) MoveCost ¶
MoveCost returns the traversal cost of entering (col, row), or 1 if unset. Costs below 1 are clamped to 1 so a cheaper cell cannot make the distance heuristic overestimate and break A*'s optimality.
func (*CostMap) SetCost ¶
SetCost sets the traversal cost for (col, row). Negative, infinite or NaN costs mark the cell unwalkable; 0 or a cost below 1 restores the default cost of 1, as the distance heuristic assumes every step costs at least 1.
func (*CostMap) SetWalkable ¶
SetWalkable marks (col, row) as walkable or blocked. Unblocking a cell restores its cost to 1.
type CoverHeight ¶
type CoverHeight uint8
CoverHeight 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 ¶
func ParseCoverHeight(s string) (CoverHeight, bool)
ParseCoverHeight parses "half" or "full" (case-insensitive, trimmed) into a CoverHeight.
func (CoverHeight) String ¶
func (h CoverHeight) String() string
String returns "half" for CoverHalf, "full" for CoverFull, or "none" for an unset value.
type CoverHeightTest ¶
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 ¶
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 ¶
func GenerateCoverFromBoxes(boxes []physics.Box, opts ColliderCoverOptions) []CoverPoint
GenerateCoverFromBoxes 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 ¶
func GenerateCoverFromGrid(g Grid, origin math2d.Vec2, cellWidth, cellHeight float32, opts GridCoverOptions) []CoverPoint
GenerateCoverFromGrid generates deterministic cover points along exposed edges of blocked cells (!g.Walkable) on g, offset into adjacent walkable cells.
func GenerateCoverFromSegments ¶
func GenerateCoverFromSegments(segments []CoverSegment, opts ColliderCoverOptions) []CoverPoint
GenerateCoverFromSegments samples deterministic cover points along straight obstacle segments.
func GenerateCoverFromTilemap ¶
func GenerateCoverFromTilemap(m *tilemap.Tilemap, opts TileCoverOptions) []CoverPoint
GenerateCoverFromTilemap 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 ¶
func GenerateCoverFromWorld(w *physics.World, opts ColliderCoverOptions) []CoverPoint
GenerateCoverFromWorld 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 (CoverPoint) HasTag ¶
func (c CoverPoint) HasTag(tag string) bool
HasTag reports whether c carries tag.
type CoverPointGenerator ¶
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 (*CoverPointGenerator) Generate ¶
func (g *CoverPointGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidate
Generate appends matching cover points to dst in deterministic slice order.
type CoverSegment ¶
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 ¶
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 ¶
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 CurveKind ¶
type CurveKind string
CurveKind 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 ¶
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 ¶
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 ¶
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 ¶
type Effects struct {
// contains filtered or unexported fields
}
Effects describes the boolean and integer fact changes produced when an action completes.
func (Effects) AddInt ¶
AddInt returns a copy of e that adds delta to integer fact f. A zero delta clears any effect on f.
func (Effects) Apply ¶
func (e Effects) Apply(w WorldState) WorldState
Apply returns a copy of w with all boolean and integer effects in e applied.
type EngagementRing ¶
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 ¶
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 ¶
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 ¶
type EventKind uint8
EventKind 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 )
type FactSchema ¶
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 (*FactSchema) Bool ¶
func (s *FactSchema) Bool(name string) (BoolFact, error)
Bool registers (or returns the existing slot for) a named boolean fact.
func (*FactSchema) BoolCount ¶
func (s *FactSchema) BoolCount() int
BoolCount returns the number of registered boolean facts.
func (*FactSchema) BoolName ¶
func (s *FactSchema) BoolName(f BoolFact) string
BoolName returns the registered name for f, or "" if out of range.
func (*FactSchema) Clone ¶
func (s *FactSchema) Clone() *FactSchema
Clone returns an independent copy of s.
func (*FactSchema) Int ¶
func (s *FactSchema) Int(name string) (IntFact, error)
Int registers (or returns the existing slot for) a named small integer fact.
func (*FactSchema) IntCount ¶
func (s *FactSchema) IntCount() int
IntCount returns the number of registered integer facts.
func (*FactSchema) IntName ¶
func (s *FactSchema) IntName(f IntFact) string
IntName returns the registered name for f, or "" if out of range.
func (*FactSchema) LookupBool ¶
func (s *FactSchema) LookupBool(name string) (BoolFact, bool)
LookupBool returns the slot for a registered boolean fact.
func (*FactSchema) LookupInt ¶
func (s *FactSchema) LookupInt(name string) (IntFact, bool)
LookupInt returns the slot for a registered integer fact.
func (*FactSchema) MustBool ¶
func (s *FactSchema) MustBool(name string) BoolFact
MustBool registers a named boolean fact like Bool and panics on error.
func (*FactSchema) MustInt ¶
func (s *FactSchema) MustInt(name string) IntFact
MustInt registers a named small integer fact like Int and panics on error.
type FalloffKind ¶
type FalloffKind uint8
FalloffKind 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 ¶
FloatRange represents an optional inclusive [Min, Max] filter interval for continuous tactical tests.
func AtLeast ¶
func AtLeast(minVal float64) FloatRange
AtLeast returns a FloatRange requiring values >= minVal.
func AtMost ¶
func AtMost(maxVal float64) FloatRange
AtMost returns a FloatRange requiring values <= maxVal.
func Between ¶
func Between(minVal, maxVal float64) FloatRange
Between returns a FloatRange requiring values in [minVal, maxVal].
func (FloatRange) Contains ¶
func (r FloatRange) Contains(v float64) bool
Contains reports whether v satisfies the configured bounds. NaN always returns false.
type GOAPAction ¶
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 ¶
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 ¶
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 ¶
GOAPBoolFactDef binds a named boolean fact to a true/false value.
type GOAPCompareOp ¶
type GOAPCompareOp string
GOAPCompareOp 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 ¶
type GOAPConditionsDef struct {
Bools []GOAPBoolFactDef `yaml:"bools,omitempty"`
Ints []GOAPIntConditionDef `yaml:"ints,omitempty"`
}
GOAPConditionsDef defines boolean and integer requirements in YAML.
type GOAPConfig ¶
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 ¶
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 (*GOAPConfig) Validate ¶
func (cfg *GOAPConfig) Validate() error
Validate checks that cfg has version GOAPVersion, valid facts, unique actions and goals, valid operators/ranges, and no undefined fact references.
type GOAPEffectsDef ¶
type GOAPEffectsDef struct {
Bools []GOAPBoolFactDef `yaml:"bools,omitempty"`
Ints []GOAPIntEffectDef `yaml:"ints,omitempty"`
}
GOAPEffectsDef defines boolean and integer effects in YAML.
type GOAPFactsDef ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
type GOAPIntEffectOp string
GOAPIntEffectOp 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 ¶
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 ¶
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 (*GOAPPlanner) Action ¶
func (p *GOAPPlanner) Action(index int) GOAPAction
Action returns a copy of the action at index, or the zero GOAPAction if index is out of bounds.
func (*GOAPPlanner) ActionCount ¶
func (p *GOAPPlanner) ActionCount() int
ActionCount returns the number of actions configured on p.
func (*GOAPPlanner) ActionIndex ¶
func (p *GOAPPlanner) ActionIndex(name string) int
ActionIndex returns the index of the action named name, or -1 if none matches.
func (*GOAPPlanner) ActionName ¶
func (p *GOAPPlanner) ActionName(index int) string
ActionName returns the Name of the action at index, or "" if index is out of bounds.
func (*GOAPPlanner) Plan ¶
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 (*GOAPPlanner) PlanBestGoal ¶
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 (*GOAPPlanner) PlanBestGoalInto ¶
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 (*GOAPPlanner) PlanInto ¶
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 (*GOAPPlanner) PlanNames ¶
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 ¶
type GOAPSet struct {
Schema *FactSchema
Planner *GOAPPlanner
Goals []GOAPGoal
}
GOAPSet holds the compiled FactSchema, GOAPPlanner, and prioritized GOAPGoals produced by BuildGOAP.
func 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 ¶
type Graph[N comparable] interface { AppendNeighbors(dst []GraphEdge[N], node N) []GraphEdge[N] }
Graph defines weighted directed adjacency over nodes of comparable type N.
AppendNeighbors appends all outgoing edges from node onto dst and returns the extended slice. Reusing dst lets GraphSearch expand nodes without heap allocations on repeated searches. Edges with negative, NaN, or infinite Cost are ignored.
type GraphEdge ¶
type GraphEdge[N comparable] struct { To N Cost float64 }
GraphEdge is a directed outgoing edge from a graph node with a finite non-negative step cost.
type GraphFunc ¶
type GraphFunc[N comparable] struct { // Neighbors appends outgoing edges from node onto dst. Neighbors func(dst []GraphEdge[N], node N) []GraphEdge[N] // Estimate optionally returns an admissible heuristic from -> goal (nil uses 0 / Dijkstra). Estimate func(from, goal N) float64 // Valid optionally checks whether a start or goal node is valid (nil accepts all nodes). Valid func(node N) bool // Less optionally defines a strict total order on nodes for tie-breaking. Less func(a, b N) bool }
GraphFunc adapts callback functions to HeuristicGraph[N].
func (GraphFunc[N]) AppendNeighbors ¶
AppendNeighbors delegates to Neighbors when non-nil.
func (GraphFunc[N]) Heuristic ¶
Heuristic delegates to Estimate when non-nil, returning 0 otherwise.
type GraphRange ¶
type GraphRange[N comparable] struct { // contains filtered or unexported fields }
GraphRange holds the shortest-path tree produced by GraphSearch.Range or GraphSearch.RangeInto: every node reachable from Start within Budget, its minimum cost, and the parent links needed to reconstruct the optimal path to any reached node.
func (*GraphRange[N]) Budget ¶
func (r *GraphRange[N]) Budget() float64
Budget returns the maximum path cost budget used to compute this range.
func (*GraphRange[N]) Contains ¶
func (r *GraphRange[N]) Contains(node N) bool
Contains reports whether node is reachable within the query's budget.
func (*GraphRange[N]) Cost ¶
func (r *GraphRange[N]) Cost(node N) (float64, bool)
Cost returns the minimum path cost from Start to node, or (0, false) if node is not in the range.
func (*GraphRange[N]) Len ¶
func (r *GraphRange[N]) Len() int
Len returns the number of reachable nodes in the range.
func (*GraphRange[N]) Nodes ¶
func (r *GraphRange[N]) Nodes() []ReachableNode[N]
Nodes returns all reachable nodes and their minimum costs in deterministic order (ascending Cost, then deterministic tie-breaking order). The returned slice aliases r's internal storage and is overwritten by a subsequent RangeInto call on r.
func (*GraphRange[N]) Parent ¶
func (r *GraphRange[N]) Parent(node N) (N, bool)
Parent returns the predecessor of node on its shortest path from Start. It returns (zero, false) for Start itself or for nodes outside the range.
func (*GraphRange[N]) Path ¶
func (r *GraphRange[N]) Path(node N) ([]N, bool)
Path returns the shortest path from Start to node inclusive, or (nil, false) if node is not reachable.
func (*GraphRange[N]) PathInto ¶
func (r *GraphRange[N]) PathInto(dst []N, node N) ([]N, bool)
PathInto writes the shortest path from Start to node inclusive into dst[:0], allocating zero times when dst has enough capacity.
func (*GraphRange[N]) Start ¶
func (r *GraphRange[N]) Start() (N, bool)
Start returns the origin node of the range query and whether the range is non-empty.
type GraphSearch ¶
type GraphSearch[N comparable] struct { // MaxExpansions caps the number of node expansions per search. Zero or negative means unlimited. MaxExpansions int // Less optionally defines a strict total order on N for tie-breaking equal (f, h) nodes. // When nil, GraphSearch checks whether the graph implements NodeOrder[N] and falls back // to deterministic discovery order. Less func(a, b N) bool // contains filtered or unexported fields }
GraphSearch performs deterministic A*, Dijkstra, and budgeted range searches over any Graph[N], reusing its internal search buffers across calls.
Tie-breaking matches AStar: lowest f, then lowest h, then Less (or the graph's NodeOrder[N]), and finally deterministic node discovery order. A GraphSearch is not safe for concurrent use.
func NewGraphSearch ¶
func NewGraphSearch[N comparable]() *GraphSearch[N]
NewGraphSearch returns a new reusable GraphSearch for nodes of type N.
func (*GraphSearch[N]) Find ¶
func (s *GraphSearch[N]) Find(g Graph[N], start, goal N) (path []N, cost float64, ok bool)
Find runs A* from start to goal on g (using g.Heuristic when g implements HeuristicGraph[N], or Dijkstra otherwise), returning the lowest-cost path inclusive of endpoints and its total cost.
Internal search buffers are reused across calls; only the returned path slice is allocated.
func (*GraphSearch[N]) FindDijkstra ¶
func (s *GraphSearch[N]) FindDijkstra(g Graph[N], start, goal N) (path []N, cost float64, ok bool)
FindDijkstra runs Dijkstra's algorithm from start to goal on g (ignoring any HeuristicGraph method), returning the lowest-cost path inclusive of endpoints and its total cost.
Internal search buffers are reused across calls; only the returned path slice is allocated.
func (*GraphSearch[N]) FindDijkstraInto ¶
func (s *GraphSearch[N]) FindDijkstraInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)
FindDijkstraInto behaves like FindDijkstra but writes the path into dst[:0], avoiding allocations when dst has enough capacity.
func (*GraphSearch[N]) FindInto ¶
func (s *GraphSearch[N]) FindInto(dst []N, g Graph[N], start, goal N) (path []N, cost float64, ok bool)
FindInto behaves like Find but writes the resulting path into dst[:0], avoiding allocations when dst has enough capacity.
func (*GraphSearch[N]) FindWithHeuristic ¶
func (s *GraphSearch[N]) FindWithHeuristic(g Graph[N], start, goal N, h func(from, goal N) float64) (path []N, cost float64, ok bool)
FindWithHeuristic runs A* from start to goal on g using heuristic h (nil runs Dijkstra). Internal search buffers are reused across calls; only the returned path slice is allocated.
func (*GraphSearch[N]) FindWithHeuristicInto ¶
func (s *GraphSearch[N]) FindWithHeuristicInto(dst []N, g Graph[N], start, goal N, h func(from, goal N) float64) (path []N, cost float64, ok bool)
FindWithHeuristicInto behaves like FindWithHeuristic but writes the path into dst[:0], avoiding allocations when dst has enough capacity.
func (*GraphSearch[N]) Range ¶
func (s *GraphSearch[N]) Range(g Graph[N], start N, budget float64) *GraphRange[N]
Range runs a budgeted Dijkstra search from start on g and returns a GraphRange containing every node reachable within budget, its minimum cost, and parent links for path reconstruction.
Internal search buffers are reused across calls; only the returned GraphRange is allocated.
func (*GraphSearch[N]) RangeInto ¶
func (s *GraphSearch[N]) RangeInto(dst *GraphRange[N], g Graph[N], start N, budget float64) *GraphRange[N]
RangeInto behaves like Range but reuses dst's storage when dst is non-nil, avoiding heap allocations after warm-up.
type Grid ¶
type Grid interface {
// GridSize returns the grid's width in columns and height in rows.
GridSize() (cols, rows int)
// Walkable reports whether the cell at (col, row) can be entered.
Walkable(col, row int) bool
}
Grid is a two-dimensional tile grid that AStar searches.
type GridCoverOptions ¶
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 ¶
type GridFunc struct {
Cols, Rows int
// Walk reports whether (col, row) is walkable; a nil Walk treats all in-bounds cells as walkable.
Walk func(col, row int) bool
// Cost returns the traversal cost of entering (col, row); a nil Cost uses 1 everywhere.
Cost func(col, row int) float64
}
GridFunc adapts callback functions to CostGrid, letting any tilemap or custom map plug into AStar in a few lines.
Example ¶
GridFunc adapts a game's own map to Grid without copying it.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
level := []string{
"..#",
".##",
"...",
}
g := ai.GridFunc{
Cols: 3, Rows: 3,
Walk: func(col, row int) bool { return level[row][col] == '.' },
}
path, _, ok := ai.NewAStar().Find(g, ai.Cell{Col: 1, Row: 0}, ai.Cell{Col: 2, Row: 2})
fmt.Println(ok, path)
}
Output: true [{1 0} {0 0} {0 1} {0 2} {1 2} {2 2}]
type GridGenerator ¶
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 (*GridGenerator) Generate ¶
func (g *GridGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidate
Generate appends grid candidates in deterministic row-major order.
type GridPathOptions ¶
type GridPathOptions struct {
// Origin is the world-space coordinate of cell (0, 0)'s top-left corner.
Origin core.Point
// CellSize is the width and height of one square grid cell in world units.
// Positive CellWidth or CellHeight values override CellSize on their respective axes.
// When no positive size is set on an axis, that axis defaults to 1.
CellSize float32
// CellWidth overrides CellSize along the X axis when positive, supporting rectangular tiles.
CellWidth float32
// CellHeight overrides CellSize along the Y axis when positive, supporting rectangular tiles.
CellHeight float32
// Radius is the circular body radius in world units that smoothed segments must keep clear of every blocked cell.
// Values less than or equal to 0 test a zero-width ray that still rejects corner-cutting through blocked cells.
Radius float32
}
GridPathOptions configures world-space conversion and body clearance for SmoothGridPath, SmoothGridPathInto, and GridLineOfSight.
The zero value uses 1x1 world-unit cells rooted at (0, 0) with a zero-width line-of-sight ray (still preventing corner cuts across blocked cells).
func (GridPathOptions) CellCenter ¶
func (o GridPathOptions) CellCenter(c Cell) core.Point
CellCenter returns the world-space center of cell c under o.
type GridPathResult ¶
type GridPathResult struct {
Path []Cell
Cost float64
Found bool // true when a complete or partial path was produced
Partial bool // true when Path ends at the closest explored cell rather than goal
Exhausted bool // true when the search stopped because MaxExpansions was reached
Expansions int // total number of grid cells expanded during the search
}
GridPathResult is the outcome of a bounded or incremental grid A* search.
type GridTopology ¶
type GridTopology uint8
GridTopology selects the cell adjacency and admissible distance heuristic used by AStar and movement-range queries.
The zero value (TopologySquare) uses the square grid (4-way or 8-way depending on AStar.Diagonal), preserving backward compatibility with existing AStar callers.
const ( // TopologySquare is an orthogonal (or diamond isometric) square grid. // With AStar.Diagonal false it uses 4-way cardinal neighbors and Manhattan distance; // with AStar.Diagonal true it uses 8-way neighbors (respecting NoCornerCutting) and octile distance. TopologySquare GridTopology = iota // TopologySquare4 forces 4-way cardinal adjacency and Manhattan distance regardless of AStar.Diagonal. TopologySquare4 // TopologySquare8 forces 8-way adjacency (respecting AStar.NoCornerCutting) and octile distance regardless of AStar.Diagonal. TopologySquare8 // TopologyHexPointyOdd is a pointy-top hexagonal grid with odd rows shifted right (StaggerY, StaggerOdd; Tiled default). TopologyHexPointyOdd // TopologyHexPointyEven is a pointy-top hexagonal grid with even rows shifted right (StaggerY, StaggerEven). TopologyHexPointyEven // TopologyHexFlatOdd is a flat-top hexagonal grid with odd columns shifted down (StaggerX, StaggerOdd). TopologyHexFlatOdd // TopologyHexFlatEven is a flat-top hexagonal grid with even columns shifted down (StaggerX, StaggerEven). TopologyHexFlatEven // TopologyStaggeredYOdd is a staggered isometric grid with odd rows shifted right (StaggerY, StaggerOdd). // With AStar.Diagonal false it moves along the 4 diamond edges; with AStar.Diagonal true it also allows the 4 vertex-adjacent diagonals. TopologyStaggeredYOdd // TopologyStaggeredYEven is a staggered isometric grid with even rows shifted right (StaggerY, StaggerEven). TopologyStaggeredYEven // TopologyStaggeredXOdd is a staggered isometric grid with odd columns shifted down (StaggerX, StaggerOdd). TopologyStaggeredXOdd // TopologyStaggeredXEven is a staggered isometric grid with even columns shifted down (StaggerX, StaggerEven). TopologyStaggeredXEven )
func TopologyFromTilemap ¶
func TopologyFromTilemap(m *tilemap.Tilemap) GridTopology
TopologyFromTilemap returns the GridTopology matching m's Orientation, StaggerAxis and StaggerIndex.
A nil tilemap, OrientationOrthogonal or OrientationIsometric returns TopologySquare (diamond isometric cells share the same 4/8-way (col, row) adjacency as orthogonal squares).
func (GridTopology) Distance ¶
func (t GridTopology) Distance(a, b Cell) float64
Distance returns the exact open-ground step distance (and admissible A* heuristic) between a and b under t.
For TopologySquare and TopologyStaggered* it computes 4-way distance; TopologySquare8 computes octile distance; hexagonal topologies compute exact cube distance matching tilemap.Tilemap.HexDistance.
func (GridTopology) IsHex ¶
func (t GridTopology) IsHex() bool
IsHex reports whether t is one of the four hexagonal grid topologies.
func (GridTopology) IsStaggered ¶
func (t GridTopology) IsStaggered() bool
IsStaggered reports whether t is one of the four staggered isometric grid topologies.
func (GridTopology) Neighbors ¶
func (t GridTopology) Neighbors(c Cell) []Cell
Neighbors returns the adjacent cells of c under t in deterministic order.
For TopologySquare and TopologyStaggered* it returns the 4 edge-adjacent neighbors; use TopologySquare8 for 8-way square neighbors, or NeighborsInto with an explicit diagonal flag via AStar.
func (GridTopology) NeighborsInto ¶
func (t GridTopology) NeighborsInto(dst []Cell, c Cell) []Cell
NeighborsInto appends the adjacent cells of c under t into dst[:0].
func (GridTopology) String ¶
func (t GridTopology) String() string
String returns the topology's canonical name.
type HPA ¶
type HPA struct {
// contains filtered or unexported fields
}
HPA implements Hierarchical Pathfinding A* (HPA*) over a square Grid, CostGrid, or EdgeCostGrid.
It partitions the grid into fixed-size square clusters, places entrance nodes along shared cluster borders, precomputes intra-cluster shortest paths between entrances, and supports O(affected clusters) incremental updates via UpdateCell, UpdateRect, and RebuildDirty.
All search and refinement buffers are reused across calls. An HPA is not safe for concurrent use by multiple goroutines.
func NewHPA ¶
func NewHPA(g Grid, opts HPAOptions) *HPA
NewHPA builds an HPA* hierarchy over g with opts.
If g is nil or empty, the returned HPA is valid but all searches return ok=false.
func (*HPA) AllowCornerCutting ¶
AllowCornerCutting reports whether diagonal moves may cut blocked corners.
func (*HPA) ClusterAt ¶
ClusterAt returns the ClusterID containing cell c and whether c is in bounds.
func (*HPA) ClusterGridSize ¶
ClusterGridSize returns the number of cluster columns and cluster rows.
func (*HPA) ClusterRect ¶
func (h *HPA) ClusterRect(id ClusterID) (ClusterRect, bool)
ClusterRect returns the cell bounds of cluster id and whether id is in bounds.
func (*HPA) ClusterSize ¶
ClusterSize returns the configured cluster width and height in cells.
func (*HPA) Find ¶
Find searches the hierarchical graph for a near-optimal path from start to goal, refining it into a contiguous concrete slice of walkable cells and returning the exact path cost.
func (*HPA) FindAbstract ¶
FindAbstract searches only the hierarchical abstract graph without refining intra-cluster segments, returning the sequence of entrance waypoints from start to goal inclusive and the path cost.
func (*HPA) FindAbstractInto ¶
func (h *HPA) FindAbstractInto(dst []Cell, start, goal Cell) (waypoints []Cell, cost float64, ok bool)
FindAbstractInto behaves like FindAbstract but writes the abstract waypoints into dst[:0].
func (*HPA) FindClusters ¶
FindClusters searches only the hierarchical abstract graph and returns the ordered list of clusters traversed from start to goal.
func (*HPA) FindClustersInto ¶
func (h *HPA) FindClustersInto(dst []ClusterID, start, goal Cell) (clusters []ClusterID, cost float64, ok bool)
FindClustersInto behaves like FindClusters but writes the traversed ClusterIDs into dst[:0].
func (*HPA) FindInto ¶
FindInto behaves like Find but writes the refined cell path into dst[:0], avoiding heap allocations when dst has enough capacity.
func (*HPA) RebuildDirty ¶
RebuildDirty incrementally rebuilds only the borders and clusters marked dirty by UpdateCell or UpdateRect.
It returns the number of clusters rebuilt.
func (*HPA) UpdateCell ¶
UpdateCell marks the cluster containing (col, row), and any shared border and neighboring cluster it touches, as dirty.
Call RebuildDirty to apply pending updates immediately, or let the next Find / FindAbstract / FindClusters call rebuild them automatically.
func (*HPA) UpdateRect ¶
UpdateRect marks every cluster and shared border overlapping the inclusive cell rectangle [minCol..maxCol] x [minRow..maxRow] as dirty.
type HPAOptions ¶
type HPAOptions struct {
// ClusterSize is the width and height of each cluster in cells.
// Values <= 0 use DefaultHPAClusterSize (16); 1 is clamped to 2.
ClusterSize int
// MaxEntranceSpan is the maximum contiguous walkable border run represented by a single entrance.
// Longer runs receive two entrances at their endpoints (plus a lowest-cost cell on weighted grids when cheaper).
// Values <= 0 use DefaultHPAMaxEntranceSpan (6).
MaxEntranceSpan int
// Diagonal allows 8-way movement with step distance sqrt(2) on diagonals; false restricts movement to 4 cardinal directions.
Diagonal bool
// AllowCornerCutting permits diagonal moves when one or both adjacent cardinal cells are blocked.
// When false (the default), diagonal moves never cut corners, matching NewAStar.
AllowCornerCutting bool
}
HPAOptions configures an HPA hierarchical pathfinder.
type HPAStats ¶
type HPAStats struct {
ClusterCols int
ClusterRows int
ClusterSize int
NodeCount int
DirtyClusters int
TotalClusterRebuilds int
LastRebuiltClusters int
}
HPAStats reports structural and incremental-rebuild metrics for an HPA instance.
type HearingConfig ¶
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 ¶
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 ¶
type HeuristicGraph[N comparable] interface { Graph[N] Heuristic(from, goal N) float64 }
HeuristicGraph is a Graph that supplies an admissible lower-bound cost estimate between two nodes for A* search.
type HexGrid ¶
type HexGrid struct {
// Map is the backing hexagonal tilemap. Must be non-nil with positive Width and Height.
Map *tilemap.Tilemap
// SolidMask selects which tilemap.TileFlags block entry into a cell.
// When 0, defaults to tilemap.TileSolid unless Walk is set.
SolidMask tilemap.TileFlags
// Walk optionally overrides cell walkability for in-bounds cells.
// When nil, a cell is walkable iff Map.FlagsAt(col, row)&effectiveSolidMask == 0.
Walk func(col, row int) bool
// Cost optionally returns the traversal cost of entering (col, row).
// Negative, NaN, or infinite values mark the cell unwalkable when StepCost is nil.
// When nil, every walkable cell has cost 1.
Cost func(col, row int) float64
// StepCost optionally returns the directed traversal cost from -> to, taking precedence over Cost.
// Negative, NaN, or infinite values forbid moving along that edge.
StepCost func(from, to Cell) float64
}
HexGrid adapts a hexagonal tilemap.Tilemap to HeuristicGraph[Cell] (and Grid / EdgeCostGrid) using tilemap.Tilemap.HexNeighbors and tilemap.Tilemap.HexDistance across all stagger axes (StaggerX, StaggerY) and stagger indices (StaggerOdd, StaggerEven).
Heuristic returns the exact cube step distance (Map.HexDistance), which is admissible whenever every step costs at least 1. When using sub-unit road costs (< 1), prefer GraphSearch.FindDijkstra, GraphSearch.Range, or GraphSearch.FindWithHeuristic with a scaled distance heuristic.
Example ¶
HexGrid adapts a hexagonal tilemap.Tilemap to GraphSearch for both A* paths and budgeted movement ranges with reconstructed paths.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/ai"
"github.com/nsgo-dev/game/pkg/tilemap"
)
func main() {
m := tilemap.New(5, 5, 32, 36)
m.Orientation = tilemap.OrientationHexagonal
m.StaggerAxis = tilemap.StaggerY
m.StaggerIndex = tilemap.StaggerOdd
m.SetCellFlags(2, 2, tilemap.TileSolid)
hex := ai.NewHexGrid(m)
search := ai.NewGraphSearch[ai.Cell]()
rng := search.Range(hex, ai.Cell{Col: 1, Row: 2}, 3)
path, ok := rng.Path(ai.Cell{Col: 3, Row: 2})
cost, _ := rng.Cost(ai.Cell{Col: 3, Row: 2})
fmt.Println(ok, cost, len(path))
}
Output: true 3 4
func NewHexGrid ¶
NewHexGrid returns a HexGrid over m blocking tiles with tilemap.TileSolid and using unit step cost 1.
func (*HexGrid) AppendNeighbors ¶
AppendNeighbors appends all passable hexagonal neighbor transitions of c onto dst using Map.HexNeighbors in deterministic order.
func (*HexGrid) EdgeCost ¶
EdgeCost returns the directed traversal cost from (fromCol, fromRow) to (toCol, toRow) for EdgeCostGrid compatibility. Negative, NaN, or infinite values forbid the transition.
func (*HexGrid) Heuristic ¶
Heuristic returns the exact hexagonal step distance between from and goal via Map.HexDistance.
func (*HexGrid) MoveCost ¶
MoveCost returns the traversal cost of entering (col, row) for CostGrid compatibility, clamping values below 1 to 1 so AStar's distance heuristic remains admissible.
func (*HexGrid) NodeLess ¶
NodeLess orders cells in row-major order, matching AStar's deterministic cell-ID tie-breaking.
type IncrementalSearch ¶
type IncrementalSearch interface {
// Step advances the search by at most maxExpansions node expansions and returns
// the updated status along with the exact number of expansions performed.
// When maxExpansions <= 0 or the search is already done, Step performs 0 expansions.
Step(maxExpansions int) (status SearchStatus, expansions int)
// Status returns the search's current status.
Status() SearchStatus
// Expansions returns the cumulative number of node expansions performed so far.
Expansions() int
}
IncrementalSearch is a deterministic path search that advances in bounded expansion steps.
*AStarSearch, *NavMeshSearch, and *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 ¶
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 ¶
func NewInfluenceLayer(cols, rows int) *InfluenceLayer
NewInfluenceLayer returns a cols-by-rows InfluenceLayer with CellSize 1 and Origin (0, 0).
func NewInfluenceLayerForGrid ¶
func NewInfluenceLayerForGrid(g Grid, origin math2d.Vec2, cellSize float32) *InfluenceLayer
NewInfluenceLayerForGrid 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 (*InfluenceLayer) Abs ¶
func (l *InfluenceLayer) Abs()
Abs replaces every cell value in l with its absolute value in place.
func (*InfluenceLayer) Add ¶
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 (*InfluenceLayer) AddScaled ¶
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 (*InfluenceLayer) AddSource ¶
func (l *InfluenceLayer) AddSource(src InfluenceSource) InfluenceSourceID
AddSource 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 (*InfluenceLayer) At ¶
func (l *InfluenceLayer) At(col, row int) float32
At returns the value at (col, row), or 0 when out of bounds.
func (*InfluenceLayer) CellAt ¶
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 (*InfluenceLayer) CellCenter ¶
func (l *InfluenceLayer) CellCenter(c Cell) math2d.Vec2
CellCenter returns the world position at the center of cell c.
func (*InfluenceLayer) Clamp ¶
func (l *InfluenceLayer) Clamp(minVal, maxVal float32)
Clamp clamps every cell of l into [minVal, maxVal] in place.
func (*InfluenceLayer) Clear ¶
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 (*InfluenceLayer) ClearSources ¶
func (l *InfluenceLayer) ClearSources()
ClearSources removes all tracked sources and marks the layer dirty so the next Update or Spread clears their influence.
func (*InfluenceLayer) Combine ¶
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 (*InfluenceLayer) CopyFrom ¶
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 (*InfluenceLayer) DrawHeatmap ¶
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 (*InfluenceLayer) Fill ¶
func (l *InfluenceLayer) Fill(v float32)
Fill sets every cell in the layer to v (non-finite values are treated as 0).
func (*InfluenceLayer) Gradient ¶
func (l *InfluenceLayer) Gradient(p math2d.Vec2) math2d.Vec2
Gradient 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 (*InfluenceLayer) GradientAtCell ¶
func (l *InfluenceLayer) GradientAtCell(col, row int) math2d.Vec2
GradientAtCell 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 (*InfluenceLayer) Highest ¶
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 (*InfluenceLayer) HighestInRadius ¶
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 (*InfluenceLayer) Lowest ¶
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 (*InfluenceLayer) LowestInRadius ¶
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 (*InfluenceLayer) MarkDirtyCell ¶
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 (*InfluenceLayer) MarkDirtyRect ¶
func (l *InfluenceLayer) MarkDirtyRect(minCol, minRow, maxCol, maxRow int)
MarkDirtyRect marks the inclusive cell rectangle [minCol..maxCol] x [minRow..maxRow] for incremental recomputation.
func (*InfluenceLayer) MoveSource ¶
func (l *InfluenceLayer) MoveSource(id InfluenceSourceID, cell Cell) bool
MoveSource 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 (*InfluenceLayer) Multiply ¶
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 (*InfluenceLayer) Normalize ¶
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 (*InfluenceLayer) Rebuild ¶
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 (*InfluenceLayer) RemoveSource ¶
func (l *InfluenceLayer) RemoveSource(id InfluenceSourceID) bool
RemoveSource 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 (*InfluenceLayer) Resize ¶
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 (*InfluenceLayer) Sample ¶
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 (*InfluenceLayer) Scale ¶
func (l *InfluenceLayer) Scale(s float32)
Scale multiplies every cell of l by s in place (non-finite values are treated as 0).
func (*InfluenceLayer) Set ¶
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 (*InfluenceLayer) SetSource ¶
func (l *InfluenceLayer) SetSource(id InfluenceSourceID, src InfluenceSource) bool
SetSource 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 (*InfluenceLayer) Size ¶
func (l *InfluenceLayer) Size() (cols, rows int)
Size returns the layer's width in columns and height in rows.
func (*InfluenceLayer) Source ¶
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 (*InfluenceLayer) SourceCount ¶
func (l *InfluenceLayer) SourceCount() int
SourceCount returns the number of active tracked sources registered on the layer.
func (*InfluenceLayer) Spread ¶
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 (*InfluenceLayer) Stamp ¶
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 (*InfluenceLayer) Subtract ¶
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 (*InfluenceLayer) Update ¶
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 (*InfluenceLayer) Values ¶
func (l *InfluenceLayer) Values() []float32
Values 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 ¶
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 ¶
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 ¶
type InfluenceSourceID uint64
InfluenceSourceID identifies a tracked source registered on an InfluenceLayer. The zero value is invalid.
type InfluenceTest ¶
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 ¶
type IntEffectKind uint8
IntEffectKind 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 ¶
type IntFact uint8
IntFact identifies a small integer fact slot (0..MaxIntFacts-1) in a FactSchema and WorldState.
type JPS ¶
type JPS struct {
// NoCornerCutting prevents diagonal moves when either adjacent cardinal cell is blocked.
// NewJPS sets this to true, matching NewAStar.
NoCornerCutting bool
// contains filtered or unexported fields
}
JPS implements Jump Point Search for 8-way uniform-cost square grids, returning exact optimal paths matching AStar with Diagonal=true while skipping symmetric open-space nodes.
JPS assumes every walkable cell has uniform traversal cost 1 (ignoring CostGrid and EdgeCostGrid). Use NewJPS for a searcher with NoCornerCutting enabled by default. All internal search buffers are reused across calls; a JPS is not safe for concurrent use by multiple goroutines.
func NewJPS ¶
func NewJPS() *JPS
NewJPS returns a JPS searcher with NoCornerCutting enabled by default.
func (*JPS) Find ¶
Find searches uniform-cost square grid g for an optimal 8-way path from start to goal, returning every cell along the path from start to goal inclusive and the exact octile path cost.
func (*JPS) FindInto ¶
FindInto behaves like Find but writes the expanded cell path into dst[:0], avoiding allocations when dst has enough capacity.
func (*JPS) FindJumpPoints ¶
FindJumpPoints searches uniform-cost square grid g and returns only the jump-point waypoints (start, turning points, and goal) together with the exact optimal 8-way cost.
type LOSFunc ¶
LOSFunc reports whether there is an unobstructed line of sight between world points from and to.
type LOSTest ¶
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 ¶
LineOfSight 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 ¶
func PhysicsLineOfSight(w *physics.World, query physics.QueryMask, layers physics.LayerMask) LineOfSight
PhysicsLineOfSight 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 ¶
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 ¶
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 ¶
func NewNavAgent(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgent
NewNavAgent constructs a 2D navigation agent placed at pos on mesh.
func (*NavAgent) ClearTarget ¶
func (a *NavAgent) ClearTarget()
ClearTarget clears the agent's goal, resets its corridor, stops velocity, and sets state to NavAgentIdle.
func (*NavAgent) Config ¶
func (a *NavAgent) Config() NavAgentConfig
Config returns the sanitized configuration of the agent.
func (*NavAgent) ForceReplan ¶
ForceReplan immediately executes a full A* replan from the agent's current position to its target, ignoring ReplanInterval and group throttling, and reports whether a valid corridor was found.
func (*NavAgent) LocalRepairCount ¶
LocalRepairCount returns the number of cheap local corridor repairs performed without a full A* replan.
func (*NavAgent) NeedsReplan ¶
NeedsReplan reports whether the agent is waiting for a full A* replan.
func (*NavAgent) NextCorner ¶
NextCorner returns the next funnel steering corner along the agent's remaining corridor. Returns (zero, false) when the agent has no valid corridor.
func (*NavAgent) Path ¶
Path returns the full string-pulled waypoint path from the agent's current position to its target along its active corridor, or nil when no valid corridor exists.
func (*NavAgent) ReplanCount ¶
ReplanCount returns the total number of full A* replans performed by this agent.
func (*NavAgent) SetMesh ¶
SetMesh attaches a new NavMesh to the agent, invalidating any existing corridor so the agent replans.
func (*NavAgent) SetPosition ¶
SetPosition updates the agent's position (for example after physics knockback or external push). When the agent has an active corridor and is not mid-link, it attempts cheap local corridor repair immediately without running a full A* replan.
func (*NavAgent) SetTarget ¶
SetTarget sets or updates the agent's destination.
When the agent already holds a valid corridor, SetTarget tries cheap local end-of-corridor repair (same polygon, corridor truncation, or bounded bridge extension) before scheduling a full A* replan. Agents managed by a NavAgentGroup defer full replans to NavAgentGroup.Step so MaxReplansPerStep is strictly respected.
func (*NavAgent) SetVelocity ¶
SetVelocity overrides the agent's current velocity. Non-finite values are ignored.
func (*NavAgent) State ¶
func (a *NavAgent) State() NavAgentState
State returns the agent's current navigation state.
func (*NavAgent) Step ¶
Step advances the agent by fixed duration dt: ticks replan cooldown, detects mesh changes, repairs the corridor locally or replans if needed, steers toward the next funnel corner, traverses off-mesh/flagged links, and settles cleanly on arrival.
func (*NavAgent) TraversingLink ¶
func (a *NavAgent) TraversingLink() (NavLinkEvent, bool)
TraversingLink returns the active link event while the agent is traversing an off-mesh or flagged link.
type NavAgentConfig ¶
type NavAgentConfig struct {
MaxSpeed float32
// Defaults to 4 * MaxSpeed when <= 0.
MaxAcceleration float32
Radius float32
// Defaults to max(Radius, 0.25) when <= 0.
StoppingDistance float32
// Defaults to max(StoppingDistance*3, MaxSpeed*MaxSpeed/(2*MaxAcceleration)*2) when <= 0.
ArrivalRadius float32
// Zero allows immediate replanning whenever the corridor becomes invalid.
ReplanInterval time.Duration
// repairing a displaced corridor start or moved target before falling back to a full A* replan.
// Defaults to 2 when <= 0.
MaxRepairDepth int
// When nil, DefaultNavFilter() is used (all walkable non-disabled polygons at unit cost).
Filter *NavFilter
// crossing a flagged shared-edge portal. Return true when the transition is complete; return
// false to keep control of the agent on subsequent steps. When nil, off-mesh links traverse
// linearly at MaxSpeed and flagged shared-edge portals are crossed automatically.
OnLink func(agent *NavAgent, link NavLinkEvent, dt time.Duration) bool
}
NavAgentConfig configures steering, arrival, corridor repair, replan throttling, and off-mesh link traversal for a 2D NavAgent.
type NavAgentGroup ¶
type NavAgentGroup struct {
// contains filtered or unexported fields
}
NavAgentGroup coordinates multiple 2D NavAgents with throttled, round-robin budgeted, and optionally staggered replanning so large groups chasing moving targets never spike a single frame.
func NewNavAgentGroup ¶
func NewNavAgentGroup(cfg NavAgentGroupConfig) *NavAgentGroup
NewNavAgentGroup constructs a NavAgentGroup with the given replan budget and staggering settings.
func (*NavAgentGroup) Add ¶
func (g *NavAgentGroup) Add(mesh *NavMesh, pos core.Point, cfg NavAgentConfig) *NavAgent
Add creates a new NavAgent, registers it in the group, and returns it.
func (*NavAgentGroup) AddAgent ¶
func (g *NavAgentGroup) AddAgent(a *NavAgent)
AddAgent attaches an existing NavAgent to the group.
func (*NavAgentGroup) Agents ¶
func (g *NavAgentGroup) Agents() []*NavAgent
Agents returns the group's agents in deterministic registration order.
func (*NavAgentGroup) LastStepReplans ¶
func (g *NavAgentGroup) LastStepReplans() int
LastStepReplans returns how many full A* replans executed during the most recent Step.
func (*NavAgentGroup) Len ¶
func (g *NavAgentGroup) Len() int
Len returns the number of agents in the group.
func (*NavAgentGroup) Remove ¶
func (g *NavAgentGroup) Remove(a *NavAgent) bool
Remove detaches a from the group while preserving deterministic ordering of remaining agents.
func (*NavAgentGroup) Step ¶
func (g *NavAgentGroup) Step(dt time.Duration)
Step advances every agent in the group by dt while strictly bounding full A* replans to MaxReplansPerStep in deterministic round-robin order.
func (*NavAgentGroup) Steps ¶
func (g *NavAgentGroup) Steps() uint64
Steps returns the number of times Step has advanced this group.
func (*NavAgentGroup) TotalReplans ¶
func (g *NavAgentGroup) TotalReplans() int
TotalReplans returns the cumulative number of full A* replans executed by Step across all agents.
type NavAgentGroupConfig ¶
type NavAgentGroupConfig struct {
// Defaults to 4 when <= 0.
MaxReplansPerStep int
// NavAgentConfig.ReplanInterval is 0.
ReplanInterval time.Duration
// Defaults to 1 (every agent is eligible in round-robin order up to MaxReplansPerStep).
StaggerStride int
}
NavAgentGroupConfig configures budgeted and staggered replanning across a group of 2D NavAgents.
type NavAgentState ¶
type NavAgentState uint8
NavAgentState reports the navigation status of a 2D NavAgent.
const ( NavAgentIdle NavAgentState = iota NavAgentMoving NavAgentArrived NavAgentUnreachable )
func (NavAgentState) String ¶
func (s NavAgentState) String() string
String returns a human-readable state name.
type NavArea ¶
type NavArea uint8
NavArea identifies the surface or terrain category of a navigation polygon (for example road, grass, mud, water, or a door threshold). Area 0 is NavAreaDefault. Games may assign any custom uint8 ID up to 255.
type NavFilter ¶
type NavFilter struct {
// when non-zero. When zero, no inclusion bit is required.
IncludeFlags NavFlags
ExcludeFlags NavFlags
// Omitted areas default to 1.0. Values <= 0, NaN, or ±Inf forbid traversal
// of that area.
AreaCosts map[NavArea]float64
ExcludedAreas map[NavArea]bool
}
NavFilter controls which navigation polygons a query may traverse and how each polygon's area scales traversal cost.
A polygon with (area, flags) is traversable when:
- area is not marked excluded in ExcludedAreas,
- flags has no bits in common with ExcludeFlags (flags & ExcludeFlags == 0),
- when IncludeFlags is non-zero, flags shares at least one bit with IncludeFlags (flags & IncludeFlags != 0),
- its effective area cost multiplier is positive and finite.
Areas omitted from AreaCosts default to a cost multiplier of 1.0. Use DefaultNavFilter for a filter matching BuildNavMesh defaults (IncludeFlags: NavFlagAll, ExcludeFlags: NavFlagDisabled, unit cost for all areas).
func DefaultNavFilter ¶
func DefaultNavFilter() NavFilter
DefaultNavFilter returns the default query filter matching BuildNavMesh defaults: every non-zero, non-disabled polygon is traversable at unit cost (1.0).
func (NavFilter) Allows ¶
Allows reports whether a polygon with the given area and flags passes the filter.
func (NavFilter) AreaCost ¶
AreaCost returns the traversal cost multiplier for area. Omitted areas return 1.0. Excluded areas or areas with non-positive, NaN, or infinite configured costs return +Inf.
func (*NavFilter) ExcludeArea ¶
ExcludeArea marks area as non-traversable on f regardless of polygon flags.
func (*NavFilter) IncludeArea ¶
IncludeArea removes area from f's ExcludedAreas set.
func (*NavFilter) SetAreaCost ¶
SetAreaCost sets the traversal cost multiplier for area on f.
type NavFlags ¶
type NavFlags uint32
NavFlags is a bitmask of runtime traversal capabilities and states on a navigation polygon (such as walk, swim, door, jump, climb, teleport, or disabled).
type NavLinkEvent ¶
type NavLinkEvent struct {
}
NavLinkEvent describes a flagged shared-edge or off-mesh link transition encountered by a NavAgent.
type NavListenerID ¶
type NavListenerID uint64
NavListenerID identifies a tile-change listener registered on a TiledNavMesh.
type NavMesh ¶
type NavMesh struct {
// contains filtered or unexported fields
}
NavMesh is a 2D navigation mesh built from convex polygons connected across shared edges and optional point-to-point off-mesh links.
func BuildNavMesh ¶
BuildNavMesh constructs a NavMesh from convex 2D polygons, normalizing winding order and automatically connecting adjacent polygons along shared edges (including partial collinear overlaps).
Each polygon is assigned NavAreaDefault and NavFlagWalk. Degenerate polygons with fewer than three vertices or near-zero area are skipped.
func BuildNavMeshWithAreas ¶
func BuildNavMeshWithAreas(polys []NavPolygonInput) *NavMesh
BuildNavMeshWithAreas constructs a NavMesh from convex 2D polygons carrying per-polygon area IDs and runtime traversal flags, normalizing winding order and automatically connecting adjacent polygons along shared edges (including partial collinear overlaps).
Polygons with zero Flags default to NavFlagWalk. Degenerate polygons with fewer than three vertices or near-zero area are skipped.
func (*NavMesh) AddOffMeshLink ¶
func (m *NavMesh) AddOffMeshLink(link NavOffMeshLink) bool
AddOffMeshLink connects the polygons containing (or within link.Radius of) link.Start and link.End with a directed (or bidirectional) off-mesh portal and bumps the mesh revision. Returns false if the mesh is nil, link coordinates or Radius are invalid, either endpoint cannot attach to the mesh, or both endpoints collapse to the same point on the same polygon.
func (*NavMesh) AddPolygonFlags ¶
AddPolygonFlags sets the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) BumpRevision ¶
func (m *NavMesh) BumpRevision()
BumpRevision increments the mesh revision so NavAgents watching this mesh invalidate cached corridors and replan.
func (*NavMesh) ClearOffMeshLinks ¶
func (m *NavMesh) ClearOffMeshLinks()
ClearOffMeshLinks removes all off-mesh links from m and bumps the mesh revision when any were present.
func (*NavMesh) ClearPolygonFlags ¶
ClearPolygonFlags clears the bits in flags on polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) Contains ¶
Contains reports whether p lies inside or on the boundary of any polygon in the mesh.
func (*NavMesh) ContainsWithFilter ¶
ContainsWithFilter reports whether p lies inside or on the boundary of any polygon passing filter.
func (*NavMesh) FindCorridor ¶
FindCorridor finds the sequence of polygon indices from start to goal using DefaultNavFilter and portal-graph A*. Returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (*NavMesh) FindCorridorInto ¶
FindCorridorInto behaves like FindCorridor but writes polygon indices into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.
FindCorridorInto is not safe for concurrent use on the same NavMesh; use NewNavMeshQuery per goroutine.
func (*NavMesh) FindCorridorWithFilter ¶
FindCorridorWithFilter finds the minimum-cost sequence of polygon indices from start to goal restricted to filter. Returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (*NavMesh) FindCorridorWithFilterInto ¶
func (m *NavMesh) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)
FindCorridorWithFilterInto behaves like FindCorridorWithFilter but writes polygon indices into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.
func (*NavMesh) FindPath ¶
FindPath finds the shortest path inside the navigation mesh from start to goal using DefaultNavFilter, portal-graph A*, and Simple Stupid Funnel Algorithm string-pulling.
It returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (*NavMesh) FindPathInto ¶
FindPathInto behaves like FindPath but writes waypoints into dst[:0] and reuses the mesh's internal search buffers so repeated calls allocate zero heap memory once warmed up.
FindPathInto is not safe for concurrent use on the same NavMesh; construct separate NewNavMeshQuery instances when running concurrent path searches against a shared read-only NavMesh.
func (*NavMesh) FindPathWithFilter ¶
FindPathWithFilter finds the minimum-cost path inside the navigation mesh from start to goal restricted to polygons allowed by filter, weighting traversal through each polygon by filter.AreaCost(area) and using an admissible distance heuristic scaled by the minimum allowed area cost.
It returns (nil, false) if start or goal lies outside traversable polygons or in disconnected regions.
func (*NavMesh) FindPathWithFilterAndOptions ¶
func (m *NavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult
FindPathWithFilterAndOptions finds a minimum-cost path inside the navigation mesh restricted to polygons allowed by filter under opts, supporting an expansion budget and optional partial paths.
func (*NavMesh) FindPathWithFilterAndOptionsInto ¶
func (m *NavMesh) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult
FindPathWithFilterAndOptionsInto behaves like FindPathWithFilterAndOptions but writes waypoints into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up. The returned res.Links slice reuses the mesh's internal query buffer (like dst) and is overwritten on subsequent queries.
func (*NavMesh) FindPathWithFilterInto ¶
func (m *NavMesh) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)
FindPathWithFilterInto behaves like FindPathWithFilter but writes waypoints into dst[:0] and reuses the mesh's internal search buffers with zero heap allocations after warm-up.
FindPathWithFilterInto is not safe for concurrent use on the same NavMesh; use NewNavMeshQuery per goroutine.
func (*NavMesh) FindPathWithOptions ¶
func (m *NavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) NavPathResult
FindPathWithOptions finds a path inside the navigation mesh under DefaultNavFilter and opts, supporting an expansion budget and optional partial paths to the closest reachable point when goal is outside the mesh, in a disconnected region, or beyond MaxExpansions.
func (*NavMesh) FindPolygon ¶
FindPolygon returns the lowest index of a polygon containing p (including its edges and vertices), or -1 if p lies outside the mesh.
func (*NavMesh) FindPolygonWithFilter ¶
FindPolygonWithFilter returns the lowest index of a polygon passing filter that contains p (including its edges and vertices), or -1 if none match.
func (*NavMesh) MoveAlongSurface ¶
func (m *NavMesh) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)
MoveAlongSurface slides an agent from start toward target while staying on polygons allowed by DefaultNavFilter.
Returns (NavMoveResult{Point: start, Poly: -1}, false) if start lies outside the allowed mesh.
func (*NavMesh) MoveAlongSurfaceWithFilter ¶
func (m *NavMesh) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)
MoveAlongSurfaceWithFilter slides an agent from start toward target while staying on polygons allowed by filter.
Returns (NavMoveResult{Point: start, Poly: -1}, false) if start lies outside the allowed mesh.
func (*NavMesh) NearestPoint ¶
NearestPoint returns the closest point on any polygon allowed by DefaultNavFilter within the axis-aligned search half-extents [p.X-extent.X, p.X+extent.X] x [p.Y-extent.Y, p.Y+extent.Y], together with that polygon's index.
Returns (zero, -1, false) if m is empty, inputs are invalid/negative, or no allowed polygon point lies within extent.
func (*NavMesh) NearestPointWithFilter ¶
func (m *NavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (point core.Point, poly int, ok bool)
NearestPointWithFilter returns the closest point on any polygon allowed by filter within the axis-aligned search half-extents [p.X-extent.X, p.X+extent.X] x [p.Y-extent.Y, p.Y+extent.Y], together with that polygon's index.
Returns (zero, -1, false) if m is empty, inputs are invalid/negative, or no allowed polygon point lies within extent.
func (*NavMesh) NearestPolygon ¶
NearestPolygon returns the polygon closest to p and the closest point on or inside that polygon. When p lies inside a polygon, NearestPolygon returns that polygon and p itself.
func (*NavMesh) NearestPolygonWithFilter ¶
func (m *NavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (index int, point core.Point, ok bool)
NearestPolygonWithFilter returns the polygon passing filter closest to p and the closest point on or inside that polygon. When p lies inside a matching polygon, NearestPolygonWithFilter returns that polygon and p itself.
func (*NavMesh) Neighbors ¶
Neighbors returns the indices of polygons sharing an edge with polygon index.
func (*NavMesh) OffMeshLinks ¶
func (m *NavMesh) OffMeshLinks() []NavOffMeshLink
OffMeshLinks returns a copy of all off-mesh links registered on m in insertion order.
func (*NavMesh) Polygon ¶
Polygon returns a copy of the vertices of polygon index, or nil if index is out of range.
func (*NavMesh) PolygonArea ¶
PolygonArea returns the area ID of polygon index, or NavAreaDefault if index is out of range.
func (*NavMesh) PolygonCount ¶
PolygonCount returns the number of valid convex polygons in the mesh.
func (*NavMesh) PolygonFlags ¶
PolygonFlags returns the runtime traversal flags of polygon index, or 0 if index is out of range.
func (*NavMesh) RandomPoint ¶
RandomPoint picks an area-weighted uniformly random point anywhere on polygons allowed by DefaultNavFilter, using rng. Results are bit-identical across runs and platforms for the same seed.
Returns (zero, -1, false) if m is empty, rng is nil, or no polygons are allowed.
func (*NavMesh) RandomPointAround ¶
func (m *NavMesh) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (point core.Point, poly int, ok bool)
RandomPointAround picks an area-weighted uniformly random point within Euclidean distance radius of center on polygons allowed by DefaultNavFilter that are reachable from center's polygon. Disconnected islands are never returned, and results are bit-identical across runs and platforms for the same seed.
Returns (zero, -1, false) if m is empty, rng is nil, radius < 0, or center lies outside the allowed mesh.
func (*NavMesh) RandomPointAroundWithFilter ¶
func (m *NavMesh) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)
RandomPointAroundWithFilter behaves like RandomPointAround while restricting reachability and sampling to polygons allowed by filter.
func (*NavMesh) RandomPointWithFilter ¶
func (m *NavMesh) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (point core.Point, poly int, ok bool)
RandomPointWithFilter picks an area-weighted uniformly random point anywhere on polygons allowed by filter, using rng. Results are bit-identical across runs and platforms for the same seed.
Returns (zero, -1, false) if m is empty, rng is nil, or no polygons pass filter.
func (*NavMesh) Raycast ¶
func (m *NavMesh) Raycast(start, target core.Point) (NavRaycastHit, bool)
Raycast casts a segment along the mesh surface from start toward target using DefaultNavFilter, walking shared-edge portals across allowed polygons until reaching target or hitting a boundary edge or disallowed polygon.
The second return value equals hit.Hit: false means unobstructed line of sight across the mesh (hit.T == 1, hit.Point == target, hit.Poly >= 0); true means the segment was obstructed (or start lies outside the allowed mesh, in which case hit.Poly == -1 and hit.T == 0).
func (*NavMesh) RaycastWithFilter ¶
func (m *NavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)
RaycastWithFilter behaves like Raycast while restricting traversal to polygons allowed by filter.
func (*NavMesh) Revision ¶
Revision returns a monotonically increasing number bumped whenever the mesh topology, area costs/flags, or link flags change.
func (*NavMesh) SetEdgeFlags ¶
SetEdgeFlags sets custom flags on the shared-edge portal from fromPoly to toPoly and bumps the mesh revision. Returns false if no shared-edge portal connects fromPoly to toPoly.
func (*NavMesh) SetPolygonArea ¶
SetPolygonArea updates the area ID of polygon index at runtime without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) SetPolygonFlags ¶
SetPolygonFlags replaces the runtime traversal flags of polygon index without rebuilding the mesh. Out-of-range indices are ignored.
func (*NavMesh) StartSearch ¶
func (m *NavMesh) StartSearch(start, goal core.Point, opts PathOptions) *NavMeshSearch
StartSearch begins an incremental 2D NavMesh path search from start to goal under DefaultNavFilter and opts.
func (*NavMesh) StartSearchWithFilter ¶
func (m *NavMesh) StartSearchWithFilter(start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearch
StartSearchWithFilter begins an incremental 2D NavMesh path search from start to goal under filter and opts.
type NavMeshGenerator ¶
type NavMeshGenerator struct {
Mesh *NavMesh
Center QueryOrigin
CustomCenter math2d.Vec2
MaxRadius float32
Spacing float32
}
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 (*NavMeshGenerator) Generate ¶
func (g *NavMeshGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidate
Generate appends NavMesh sample candidates in deterministic order with zero heap allocations.
type NavMeshQuery ¶
type NavMeshQuery struct {
// contains filtered or unexported fields
}
NavMeshQuery holds reusable generation-stamped scratch buffers for zero-allocation pathfinding and spatial queries over a 2D NavMesh.
Create one NavMeshQuery per worker or system with NewNavMeshQuery(mesh) when running repeated queries or querying a shared read-only NavMesh from separate goroutines. A NavMeshQuery is not safe for concurrent use by multiple goroutines.
func NewNavMeshQuery ¶
func NewNavMeshQuery(mesh *NavMesh) *NavMeshQuery
NewNavMeshQuery creates a reusable query instance bound to mesh.
func (*NavMeshQuery) FindCorridorInto ¶
FindCorridorInto finds the polygon corridor from start to goal under DefaultNavFilter, writing polygon indices into dst[:0] with zero heap allocations after warm-up.
func (*NavMeshQuery) FindCorridorWithFilterInto ¶
func (q *NavMeshQuery) FindCorridorWithFilterInto(dst []int, start, goal core.Point, filter NavFilter) ([]int, bool)
FindCorridorWithFilterInto finds the minimum-cost polygon corridor from start to goal restricted to filter, writing polygon indices into dst[:0] with zero heap allocations after warm-up.
func (*NavMeshQuery) FindPathInto ¶
FindPathInto finds the shortest path inside q's mesh from start to goal using DefaultNavFilter, writing waypoints into dst[:0] and reusing q's internal buffers so repeated calls perform zero heap allocations once dst and q are warmed up.
func (*NavMeshQuery) FindPathWithFilterAndOptionsInto ¶
func (q *NavMeshQuery) FindPathWithFilterAndOptionsInto(dst []core.Point, start, goal core.Point, filter NavFilter, opts PathOptions) NavPathResult
FindPathWithFilterAndOptionsInto runs a bounded or partial 2D NavMesh search restricted to filter under opts, writing the resulting waypoints into dst[:0] and reusing q's internal buffers with zero heap allocations after warm-up. The returned res.Links slice reuses q's internal buffer (like dst) and is overwritten on subsequent queries on q.
func (*NavMeshQuery) FindPathWithFilterInto ¶
func (q *NavMeshQuery) FindPathWithFilterInto(dst []core.Point, start, goal core.Point, filter NavFilter) ([]core.Point, bool)
FindPathWithFilterInto finds the minimum-cost path inside q's mesh from start to goal restricted to filter, writing waypoints into dst[:0] and reusing q's internal buffers with zero heap allocations after warm-up.
func (*NavMeshQuery) Mesh ¶
func (q *NavMeshQuery) Mesh() *NavMesh
Mesh returns the NavMesh currently bound to q.
func (*NavMeshQuery) MoveAlongSurface ¶
func (q *NavMeshQuery) MoveAlongSurface(start, target core.Point) (NavMoveResult, bool)
MoveAlongSurface delegates to q's NavMesh.MoveAlongSurface.
func (*NavMeshQuery) MoveAlongSurfaceInto ¶
func (q *NavMeshQuery) MoveAlongSurfaceInto(visitedDst []int, start, target core.Point) (NavMoveResult, bool)
MoveAlongSurfaceInto slides from start toward target under DefaultNavFilter, appending visited polygon IDs into visitedDst[:0].
func (*NavMeshQuery) MoveAlongSurfaceWithFilter ¶
func (q *NavMeshQuery) MoveAlongSurfaceWithFilter(start, target core.Point, filter NavFilter) (NavMoveResult, bool)
MoveAlongSurfaceWithFilter delegates to q's NavMesh.MoveAlongSurfaceWithFilter.
func (*NavMeshQuery) MoveAlongSurfaceWithFilterInto ¶
func (q *NavMeshQuery) MoveAlongSurfaceWithFilterInto(visitedDst []int, start, target core.Point, filter NavFilter) (NavMoveResult, bool)
MoveAlongSurfaceWithFilterInto slides from start toward target under filter, appending visited polygon IDs into visitedDst[:0].
func (*NavMeshQuery) NearestPoint ¶
NearestPoint delegates to q's NavMesh.NearestPoint.
func (*NavMeshQuery) NearestPointWithFilter ¶
func (q *NavMeshQuery) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, int, bool)
NearestPointWithFilter delegates to q's NavMesh.NearestPointWithFilter.
func (*NavMeshQuery) RandomPoint ¶
RandomPoint delegates to q's NavMesh.RandomPoint.
func (*NavMeshQuery) RandomPointAround ¶
func (q *NavMeshQuery) RandomPointAround(center core.Point, radius float32, rng *random.Stream) (core.Point, int, bool)
RandomPointAround picks a random reachable point within radius of center using q's reusable BFS and clipping buffers.
func (*NavMeshQuery) RandomPointAroundWithFilter ¶
func (q *NavMeshQuery) RandomPointAroundWithFilter(center core.Point, radius float32, rng *random.Stream, filter NavFilter) (core.Point, int, bool)
RandomPointAroundWithFilter picks a random reachable point within radius of center allowed by filter using q's reusable buffers.
func (*NavMeshQuery) RandomPointWithFilter ¶
func (q *NavMeshQuery) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (core.Point, int, bool)
RandomPointWithFilter delegates to q's NavMesh.RandomPointWithFilter.
func (*NavMeshQuery) Raycast ¶
func (q *NavMeshQuery) Raycast(start, target core.Point) (NavRaycastHit, bool)
Raycast delegates to q's NavMesh.Raycast.
func (*NavMeshQuery) RaycastWithFilter ¶
func (q *NavMeshQuery) RaycastWithFilter(start, target core.Point, filter NavFilter) (NavRaycastHit, bool)
RaycastWithFilter delegates to q's NavMesh.RaycastWithFilter.
func (*NavMeshQuery) SetMesh ¶
func (q *NavMeshQuery) SetMesh(mesh *NavMesh)
SetMesh rebinds q to mesh while keeping its allocated scratch capacity for reuse.
type NavMeshSearch ¶
type NavMeshSearch struct {
// contains filtered or unexported fields
}
NavMeshSearch runs a deterministic 2D NavMesh portal A* search incrementally across bounded Step calls.
Stepping a search with any positive per-step expansion budget produces the exact same path, links, partial flag, and expansion count as NavMesh.FindPathWithOptions / FindPathWithFilterAndOptions. *NavMeshSearch implements IncrementalSearch.
func NewNavMeshSearch ¶
func NewNavMeshSearch(m *NavMesh, start, goal core.Point, opts PathOptions) *NavMeshSearch
NewNavMeshSearch initializes an incremental 2D NavMesh search from start to goal under DefaultNavFilter and opts.
func NewNavMeshSearchWithFilter ¶
func NewNavMeshSearchWithFilter(m *NavMesh, start, goal core.Point, filter NavFilter, opts PathOptions) *NavMeshSearch
NewNavMeshSearchWithFilter initializes an incremental 2D NavMesh search from start to goal under filter and opts.
func (*NavMeshSearch) Expansions ¶
func (s *NavMeshSearch) Expansions() int
Expansions returns the cumulative number of portal nodes expanded so far.
func (*NavMeshSearch) Result ¶
func (s *NavMeshSearch) Result() NavPathResult
Result returns the search outcome once finished (or a result with Found == false while still in progress).
func (*NavMeshSearch) Status ¶
func (s *NavMeshSearch) Status() SearchStatus
Status returns the search's current status.
func (*NavMeshSearch) Step ¶
func (s *NavMeshSearch) Step(maxExpansions int) (status SearchStatus, expansions int)
Step advances the search by at most maxExpansions portal node expansions and returns the updated status and exact number of expansions performed. When maxExpansions <= 0 or the search is already finished, Step performs 0 expansions.
type NavMoveResult ¶
NavMoveResult describes the outcome of sliding a position across a 2D NavMesh surface.
type NavObstacle ¶
type NavObstacle struct {
}
NavObstacle describes a temporary runtime obstacle applied to a 2D TiledNavMesh.
func NavBoxObstacle ¶
func NavBoxObstacle(minPt, maxPt core.Point) NavObstacle
NavBoxObstacle constructs an axis-aligned 2D box obstacle spanning [minPt, maxPt].
func NavCircleObstacle ¶
func NavCircleObstacle(center core.Point, radius float32) NavObstacle
NavCircleObstacle constructs a 2D circular obstacle centered at center with radius.
func NavOrientedBoxObstacle ¶
func NavOrientedBoxObstacle(center, halfExtents core.Point, angleRad float32) NavObstacle
NavOrientedBoxObstacle constructs a rotated 2D box obstacle centered at center with halfExtents and rotation angleRad.
func NavPolygonObstacle ¶
func NavPolygonObstacle(verts []core.Point) NavObstacle
NavPolygonObstacle constructs a 2D polygonal obstacle (convex or concave) from verts.
type NavObstacleID ¶
type NavObstacleID uint64
NavObstacleID identifies a dynamic obstacle registered on a TiledNavMesh.
type NavObstacleKind ¶
type NavObstacleKind uint8
NavObstacleKind selects the geometric shape of a 2D NavObstacle.
const ( NavObstacleBox NavObstacleKind = iota NavObstacleCircle NavObstaclePolygon )
type NavObstacleMode ¶
type NavObstacleMode uint8
NavObstacleMode selects how a dynamic obstacle modifies walkable polygons in touched tiles.
const ( NavObstacleCarve NavObstacleMode = iota // (defaulting to NavFlagDisabled when both Area and Flags are zero) to the covered polygons. NavObstacleMark )
type NavOffMeshLink ¶
type NavOffMeshLink struct {
// Start and End are the world-space endpoints on (or within Radius of) the mesh.
// When positive, an endpoint outside a polygon snaps to the nearest polygon point within Radius,
// and NavAgent uses max(entryRadius, Radius) when entering the link.
// When zero, endpoints must lie on or inside a polygon. Negative or non-finite values are rejected.
Radius float32
Bidirectional bool
Flags uint32
ID int
Cost float32
// Defaults to NavAreaDefault (0).
Area NavArea
// carried through to NavPathLink and NavLinkEvent.
UserData any
}
NavOffMeshLink describes a custom off-mesh connection between two points on a 2D NavMesh (such as a jump, drop-down, ladder, door, or teleporter).
type NavPathLink ¶
type NavPathLink struct {
StartIndex int
EndIndex int
// FromPoly and ToPoly are the source and destination polygon indices connected by the link.
// Start and End are the world-space entry and exit positions of the traversed link direction.
Radius float32
Area NavArea
Flags uint32
LinkID int
UserData any
}
NavPathLink marks a segment in NavPathResult.Path that traverses an off-mesh link. Path[StartIndex] is the link's entry point on the mesh and Path[EndIndex] is its exit point (with EndIndex == StartIndex + 1).
type NavPathResult ¶
type NavPathResult struct {
// Links lists each segment of Path that traverses an off-mesh link, in path order.
// For each link, Path[link.StartIndex] is the entry point and Path[link.EndIndex]
// (with EndIndex == StartIndex + 1) is the exit point.
}
NavPathResult is the outcome of a bounded or incremental 2D NavMesh search.
func (NavPathResult) HasLinks ¶
func (r NavPathResult) HasLinks() bool
HasLinks reports whether r traverses at least one off-mesh link.
func (NavPathResult) LinkAt ¶
func (r NavPathResult) LinkAt(segmentIndex int) (NavPathLink, bool)
LinkAt returns the off-mesh link traversed by path segment segmentIndex (from Path[segmentIndex] to Path[segmentIndex+1]), or (zero, false) when that segment is ordinary walking movement.
type NavPathWatchID ¶
type NavPathWatchID uint64
NavPathWatchID identifies a path-invalidation watcher registered on a TiledNavMesh.
type NavPolyRef ¶
type NavPolyRef struct {
}
NavPolyRef uniquely identifies a walkable convex polygon inside a 2D TiledNavMesh. Salt increments whenever the owning tile is replaced, rebuilt, or removed so stale references are detected in O(1).
func (NavPolyRef) Valid ¶
func (r NavPolyRef) Valid() bool
Valid reports whether r holds a non-zero tile salt and non-negative polygon index.
type NavPolygonInput ¶
type NavPolygonInput struct {
}
NavPolygonInput describes a single convex 2D polygon together with its initial area ID and runtime traversal flags for BuildNavMeshWithAreas. A zero Flags value defaults to NavFlagWalk.
type NavRaycastHit ¶
type NavRaycastHit struct {
// or target when the ray reaches target unobstructed (Hit is false).
Point core.Point
// (pointing back into the walkable polygon, opposing the ray direction), or zero when Hit is false or Poly < 0.
Normal core.Point
Poly int
// T is 1 when target is reached unobstructed; T is 0 when start is outside the allowed mesh.
T float32
Hit bool
}
NavRaycastHit describes the result of casting a segment along a 2D NavMesh surface.
type NavTile ¶
type NavTile struct {
// contains filtered or unexported fields
}
NavTile is an independently baked 2D navigation tile covering a fixed square region [minX, maxX] x [minY, maxY]. A NavTile may be baked off the main thread with BakeNavTile and installed into a TiledNavMesh with AddTile, ReplaceTile, or SetTile.
func BakeNavTile ¶
func BakeNavTile(coord NavTileCoord, tileSize float32, origin core.Point, polys []NavPolygonInput) *NavTile
BakeNavTile bakes an independent 2D NavTile for coord from convex walkable polygons polys, clipping every polygon to the tile's exact bounds [origin + coord*tileSize, origin + (coord+1)*tileSize]. Degenerate polygons or polygons outside the tile bounds are omitted. BakeNavTile is pure and safe to call concurrently from worker goroutines.
func (*NavTile) BasePolygonCount ¶
BasePolygonCount returns the number of base walkable polygons baked into this tile.
func (*NavTile) Coord ¶
func (t *NavTile) Coord() NavTileCoord
Coord returns the tile coordinate this tile was baked for.
type NavTileChange ¶
type NavTileChange struct {
}
NavTileChange describes a single tile mutation event delivered to tile listeners and path watchers.
type NavTileChangeKind ¶
type NavTileChangeKind uint8
NavTileChangeKind classifies why a tile in a TiledNavMesh changed.
const ( NavTileAdded NavTileChangeKind = iota NavTileUpdated NavTileRemoved )
type NavTileCoord ¶
type NavTileCoord struct {
NavTileCoord identifies a fixed-size tile in a 2D TiledNavMesh.
type NavTileVersion ¶
type NavTileVersion struct {
}
NavTileVersion records a tile coordinate together with its revision number when a path was computed.
type NeighborGrid ¶
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 ¶
func NewNeighborGrid(cellSize float32) *NeighborGrid
NewNeighborGrid returns a 2D NeighborGrid with the given spatial cell size. Cell sizes less than or equal to 0 default to 32.
func (*NeighborGrid) Query ¶
func (g *NeighborGrid) Query(pos core.Point, radius float32) []Agent
Query 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 (*NeighborGrid) QueryInto ¶
QueryInto writes all indexed agents within radius of pos into dst[:0] and returns the resulting slice.
func (*NeighborGrid) Rebuild ¶
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 ¶
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 ¶
func NewNeighborGrid3D(cellSize float32, planarXZ bool) *NeighborGrid3D
NewNeighborGrid3D 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 (*NeighborGrid3D) Query ¶
func (g *NeighborGrid3D) Query(pos Vec3, radius float32) []Agent3D
Query returns all indexed agents within radius of pos using an internal scratch slice owned by g.
func (*NeighborGrid3D) QueryInto ¶
func (g *NeighborGrid3D) QueryInto(dst []Agent3D, pos Vec3, radius float32) []Agent3D
QueryInto writes all indexed agents within radius of pos into dst[:0] and returns the resulting slice.
func (*NeighborGrid3D) Rebuild ¶
func (g *NeighborGrid3D) Rebuild(agents []Agent3D)
Rebuild indexes agents into g, reusing internal buffers with zero heap allocations once warmed up.
type Node ¶
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 BlackboardCondition ¶
func BlackboardCondition(bb *Blackboard, key string, op BlackboardOp, value BlackboardValue, abort AbortMode, child Node) Node
BlackboardCondition 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 ¶
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 ¶
BuildBehaviorTreeFS loads the behavior tree at name in fsys and builds its runtime Node.
func Condition ¶
Condition wraps predicate fn as a leaf node returning StatusSuccess when true and StatusFailure when false.
func Cooldown ¶
Cooldown prevents child from starting again for duration d after it succeeds, returning StatusFailure while cooling down.
Cooldown measures elapsed time against the enclosing tree's monotonic clock, so cooldowns continue counting down even on ticks when this branch is not visited. Calling Node.Reset cancels an in-progress child run without clearing an active cooldown; use ResetCooldowns or BehaviorTree.ResetCooldowns to clear active cooldowns explicitly (for example when respawning an agent).
Example ¶
Cooldown lets its child run again only after the given time has passed.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
shots := 0
fire := ai.Cooldown(time.Second, ai.Action(func(time.Duration) ai.Status { shots++; return ai.StatusSuccess }))
for range 6 {
fire.Tick(time.Second / 4)
}
fmt.Println("shots:", shots)
}
Output: shots: 2
func Failer ¶
Failer turns both StatusSuccess and StatusFailure from child into StatusFailure while passing StatusRunning through.
func Guard ¶
Guard ticks child only while cond returns true; if cond becomes false while child is running, Guard resets child and returns StatusFailure.
func HasAttackToken ¶
HasAttackToken returns a Condition behavior tree node that succeeds while agentID holds a token in pool.
func Inverter ¶
Inverter flips StatusSuccess and StatusFailure from child while passing StatusRunning through unchanged.
func Named ¶
Named 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 ¶
func Parallel(policy ParallelPolicy, children ...Node) Node
Parallel ticks all still-running children each tick and finishes according to policy, resetting any remaining running children on completion.
Example ¶
Parallel runs its children together; RequireAll succeeds once every child has.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
tree := ai.Parallel(ai.RequireAll,
ai.Wait(time.Second),
ai.Repeater(2, ai.Succeeder(ai.Inverter(ai.Condition(func() bool { return true })))),
)
fmt.Println(tree.Tick(time.Second / 2))
fmt.Println(tree.Tick(time.Second / 2))
}
Output: Running Success
func RandomSelector ¶
RandomSelector 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 ¶
RandomSequence 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 ¶
Repeater 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 ¶
Retry 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 ¶
Selector 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 whose gating is governed solely by BlackboardCondition observers only preempt a running lower-priority branch when an observer's abort mode includes AbortLower or AbortBoth and its watched key changes; branches that mix non-blackboard conditions or guards (such as Condition, Guard, or WithAttackToken) are re-evaluated on every tick.
Example ¶
A behavior tree ticks from the root each update: here a guard picks between attacking a target in range and patrolling.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/ai"
)
func main() {
inRange := false
log := func(name string) ai.Node {
return ai.Action(func(time.Duration) ai.Status {
fmt.Println(name)
return ai.StatusSuccess
})
}
tree := ai.Selector(
ai.Sequence(ai.Condition(func() bool { return inRange }), log("attack")),
ai.Sequence(log("patrol"), ai.Wait(time.Second)),
)
fmt.Println(tree.Tick(time.Second / 2))
inRange = true
fmt.Println(tree.Tick(time.Second / 2))
}
Output: patrol Running attack Success
func Sequence ¶
Sequence 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 ¶
Service 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 ¶
SquadHasOrder 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 ¶
SquadHasRole returns a Condition behavior tree node that succeeds when agentID holds role in squad.
func SquadOrderAction ¶
SquadOrderAction 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 ¶
SquadStateBool returns a Condition behavior tree node that succeeds when squad's shared state holds a true bool value under key.
func Succeeder ¶
Succeeder turns both StatusSuccess and StatusFailure from child into StatusSuccess while passing StatusRunning through.
func TimeLimit ¶
TimeLimit 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 ¶
UntilFail ticks child once per tick, returning StatusRunning until child returns StatusFailure, at which point UntilFail returns StatusSuccess.
func UtilitySelector ¶
func UtilitySelector[C any](reasoner *Reasoner[C], ctx func() C, rng *random.Stream, subtrees map[string]Node) Node
UtilitySelector 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 ¶
Wait returns StatusRunning until the accumulated dt reaches d, then resets and returns StatusSuccess.
func WeightedSelector ¶
func WeightedSelector(stream *random.Stream, options ...WeightedNode) Node
WeightedSelector 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 ¶
WithAttackToken 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ORCAObstacle3D is a static vertical obstacle wall segment projected onto the horizontal XZ plane.
type ORCASolver ¶
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 ¶
func NewORCASolver(cfg ORCAConfig) *ORCASolver
NewORCASolver creates an ORCASolver configured with cfg.
func (*ORCASolver) Config ¶
func (s *ORCASolver) Config() ORCAConfig
Config returns the solver's effective configuration with defaults applied.
func (*ORCASolver) SetConfig ¶
func (s *ORCASolver) SetConfig(cfg ORCAConfig)
SetConfig updates the solver's configuration.
func (*ORCASolver) Solve ¶
func (s *ORCASolver) Solve(dst []math2d.Vec2, agents []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration) []math2d.Vec2
Solve 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 (*ORCASolver) SolveAgent ¶
func (s *ORCASolver) SolveAgent(agent ORCAAgent, neighbors []ORCAAgent, obstacles []ORCAObstacle, dt time.Duration) math2d.Vec2
SolveAgent 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 (*ORCASolver) SolveAgentXZ ¶
func (s *ORCASolver) SolveAgentXZ(agent ORCAAgent3D, neighbors []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration) Vec3
SolveAgentXZ 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 (*ORCASolver) SolveXZ ¶
func (s *ORCASolver) SolveXZ(dst []Vec3, agents []ORCAAgent3D, obstacles []ORCAObstacle3D, dt time.Duration) []Vec3
SolveXZ computes collision-free horizontal XZ-plane velocities for all 3D agents and appends them to dst[:0]. Returned velocities have Y = 0.
func (*ORCASolver) Step ¶
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 (*ORCASolver) StepXZ ¶
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 Obstacle3D ¶
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 ¶
type ParallelPolicy uint8
ParallelPolicy 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 ¶
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 *NavMesh
// 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 ¶
PathFollowState tracks which waypoint an agent is currently heading toward.
type PathOptions ¶
type PathOptions struct {
// MaxExpansions caps the number of search nodes expanded before stopping.
// Zero means unlimited expansions (for AStar, zero falls back to AStar.MaxExpansions when > 0);
// a negative value always forces unlimited expansions.
MaxExpansions int
// AllowPartial returns a path to the explored node closest to the goal when
// the goal is unreachable or MaxExpansions is reached, flagged with Partial = true.
AllowPartial bool
}
PathOptions configures bounded and partial pathfinding queries across grid A* and 2D/3D navigation meshes.
type PathQueue ¶
type PathQueue struct {
// contains filtered or unexported fields
}
PathQueue services multiple incremental path searches within a strict per-step node-expansion budget.
All scheduling is deterministic, single-threaded, and free of background goroutines.
func NewPathQueue ¶
func NewPathQueue(cfg PathQueueConfig) *PathQueue
NewPathQueue returns a new PathQueue with the given configuration.
func (*PathQueue) Cancel ¶
func (q *PathQueue) Cancel(id PathRequestID) bool
Cancel removes a pending request from the queue. It returns true if the request was found and removed; canceled requests are not stepped again and their callbacks are not invoked.
func (*PathQueue) Clear ¶
func (q *PathQueue) Clear()
Clear removes all pending requests without invoking callbacks.
func (*PathQueue) Completed ¶
Completed returns the cumulative number of requests that finished (complete, partial, or failed).
func (*PathQueue) IsPending ¶
func (q *PathQueue) IsPending(id PathRequestID) bool
IsPending reports whether id is currently queued and has not finished or been canceled.
func (*PathQueue) Pending ¶
Pending returns the number of active requests currently waiting in the queue.
func (*PathQueue) Step ¶
Step advances queued requests using at most budget total node expansions, returning the exact number of expansions performed (always in [0, budget] when budget > 0, or 0 when budget <= 0).
func (*PathQueue) StepDefault ¶
StepDefault advances queued requests using the queue's configured DefaultBudget.
func (*PathQueue) Submit ¶
func (q *PathQueue) Submit(search IncrementalSearch, priority int, onDone func(PathRequestID, SearchStatus)) PathRequestID
Submit enqueues search with the given priority (higher values run first; ties break in FIFO submission order). When the search reaches a terminal status during Step, onDone (if non-nil) is invoked synchronously with the request ID and final status.
Submitting a nil search is ignored and returns 0.
func (*PathQueue) SubmitGrid ¶
func (q *PathQueue) SubmitGrid(a *AStar, g Grid, start, goal Cell, opts PathOptions, priority int, onDone func(PathRequestID, GridPathResult)) (PathRequestID, *AStarSearch)
SubmitGrid creates an incremental AStarSearch and enqueues it on q, returning the request ID (for Cancel) and the search handle (for polling Status/Result). If onDone is non-nil, it is called with the completed GridPathResult once the search finishes.
func (*PathQueue) SubmitNavMesh ¶
func (q *PathQueue) SubmitNavMesh(m *NavMesh, start, goal core.Point, opts PathOptions, priority int, onDone func(PathRequestID, NavPathResult)) (PathRequestID, *NavMeshSearch)
SubmitNavMesh creates an incremental NavMeshSearch and enqueues it on q, returning the request ID (for Cancel) and the search handle (for polling Status/Result). If onDone is non-nil, it is called with the completed NavPathResult once the search finishes.
func (*PathQueue) TotalExpansions ¶
TotalExpansions returns the cumulative number of node expansions performed across all Step calls.
type PathQueueConfig ¶
type PathQueueConfig struct {
// DefaultBudget is the per-step expansion budget used by StepDefault.
DefaultBudget int
// Policy selects FIFO (default) or fair round-robin scheduling within each priority tier.
Policy PathQueuePolicy
// SliceSize caps the expansions granted per turn in PathQueueRoundRobin mode.
// Zero or negative divides the remaining step budget evenly across requests in the active priority tier.
SliceSize int
}
PathQueueConfig configures a PathQueue.
type PathQueuePolicy ¶
type PathQueuePolicy uint8
PathQueuePolicy controls how a PathQueue divides its per-step expansion budget among active requests within the same priority tier.
const ( // PathQueueFIFO runs the highest-priority earliest-submitted request until it // completes or the step's remaining expansion budget is spent. PathQueueFIFO PathQueuePolicy = iota // PathQueueRoundRobin shares the step budget fairly across all active requests // in the highest pending priority tier in deterministic rotation order. PathQueueRoundRobin )
type PathRequestID ¶
type PathRequestID uint64
PathRequestID uniquely identifies a request submitted to a PathQueue. Zero is never assigned to a valid request.
type Perception ¶
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 (*Perception) AppendMemories ¶
func (p *Perception) AppendMemories(dst []Memory) []Memory
AppendMemories appends every memory, sorted by ID, to dst and returns the extended slice, so a caller can reuse one buffer every step.
func (*Perception) Clear ¶
func (p *Perception) Clear()
Clear drops every memory and the last step's events.
func (*Perception) Events ¶
func (p *Perception) Events() []Event
Events 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 (*Perception) Forget ¶
func (p *Perception) Forget(id StimulusID) bool
Forget drops the memory of id without an event and reports whether there was one.
func (*Perception) Memories ¶
func (p *Perception) Memories() []Memory
Memories returns a new slice of every memory, sorted by ID.
func (*Perception) Memory ¶
func (p *Perception) Memory(id StimulusID) (Memory, bool)
Memory returns the memory of the stimulus id, if any.
func (*Perception) Sees ¶
func (p *Perception) Sees(id StimulusID) bool
Sees reports whether the stimulus id is in sight now.
type PerceptionStats ¶
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 ¶
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.
Example ¶
A PerceptionSystem steps each guard's senses: a target in its sight cone with a clear line of sight is seen, a noise within hearing range is remembered where it was made, and memories are forgotten once nothing has sensed them for ForgetAfter.
package main
import (
"fmt"
"math"
"time"
"github.com/nsgo-dev/game/pkg/ai"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
guard := &ai.Perception{
Self: 1,
Team: 1,
Facing: core.Point{X: 1},
Sight: ai.SightConfig{Range: 100, HalfAngle: math.Pi / 4},
Hearing: ai.HearingConfig{Range: 60},
ForgetAfter: time.Second,
}
sys := ai.PerceptionSystem{Budget: 32}
sys.Add(guard)
const dt = time.Second / 4
sys.Step(dt, []ai.Target{{ID: 7, Team: 2, Pos: core.Point{X: 50, Y: 10}}})
sys.PostNoise(ai.Noise{Source: 8, Team: 2, Pos: core.Point{X: -30}, Loudness: 1})
sys.Step(dt, nil)
for _, ev := range guard.Events() {
fmt.Println(ev.Kind, ev.Memory.ID, ev.Memory.Sense, ev.Memory.Pos)
}
for range 4 {
sys.Step(dt, nil)
for _, ev := range guard.Events() {
fmt.Println(ev.Kind, ev.Memory.ID, ev.Memory.Age)
}
}
}
Output: lost 7 sight {50 10} gained 8 hearing {-30 0} forgotten 7 1s forgotten 8 1s
func (*PerceptionSystem) Add ¶
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 (*PerceptionSystem) Len ¶
func (s *PerceptionSystem) Len() int
Len returns the number of agents in the system.
func (*PerceptionSystem) PostNoise ¶
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 (*PerceptionSystem) Remove ¶
func (s *PerceptionSystem) Remove(p *Perception) bool
Remove 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 (*PerceptionSystem) Stats ¶
func (s *PerceptionSystem) Stats() PerceptionStats
Stats returns the line-of-sight work of the last Step.
func (*PerceptionSystem) 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 ¶
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 ¶
func NewPlanRunner(planner *GOAPPlanner, world func() WorldState, goals []GOAPGoal, executors map[string]Node) *PlanRunner
NewPlanRunner 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 (*PlanRunner) ActiveGoal ¶
func (r *PlanRunner) ActiveGoal() int
ActiveGoal returns the index into the runner's goals slice currently being pursued, or -1 if none.
func (*PlanRunner) CurrentAction ¶
func (r *PlanRunner) CurrentAction() string
CurrentAction returns the Name of the action currently being executed, or "" if no plan is active.
func (*PlanRunner) LastError ¶
func (r *PlanRunner) LastError() error
LastError returns the error from the most recent failed planning attempt, or nil if the last plan succeeded.
func (*PlanRunner) Plans ¶
func (r *PlanRunner) Plans() int
Plans returns the total number of plans computed since creation or the last Reset.
func (*PlanRunner) Reset ¶
func (r *PlanRunner) Reset()
Reset cancels any in-progress plan, resets any running action node, and clears failure tracking.
func (*PlanRunner) Step ¶
func (r *PlanRunner) Step() int
Step returns the index of the currently active step in the plan, or -1 if no plan is active.
type PointReservations ¶
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 ¶
func NewPointReservations(cfg ReservationConfig) *PointReservations
NewPointReservations returns a PointReservations tracker with cfg.
func (*PointReservations) Clear ¶
func (r *PointReservations) Clear()
Clear removes all active reservations while retaining slice capacity.
func (*PointReservations) Config ¶
func (r *PointReservations) Config() ReservationConfig
Config returns the tracker's effective ReservationConfig.
func (*PointReservations) Count ¶
func (r *PointReservations) Count() int
Count returns the number of currently active reservations.
func (*PointReservations) Entries ¶
func (r *PointReservations) Entries(dst []Reservation) []Reservation
Entries appends all active reservations to dst[:0] in deterministic ascending AgentID order.
func (*PointReservations) Get ¶
func (r *PointReservations) Get(agentID uint64) (Reservation, bool)
Get returns agentID's active reservation, if any.
func (*PointReservations) HolderOfCover ¶
func (r *PointReservations) HolderOfCover(coverID uint64) (uint64, bool)
HolderOfCover returns the AgentID currently holding coverID, if any.
func (*PointReservations) IsReservedByOther ¶
func (r *PointReservations) IsReservedByOther(agentID, coverID uint64, pos math2d.Vec2) bool
IsReservedByOther reports whether coverID (when non-zero) or pos (within MinSeparation) is currently reserved by an agent other than agentID.
func (*PointReservations) Refresh ¶
func (r *PointReservations) Refresh(agentID uint64, timeout time.Duration) bool
Refresh resets the timeout of agentID's active reservation to timeout (or DefaultTimeout when <= 0).
func (*PointReservations) Release ¶
func (r *PointReservations) Release(agentID uint64) bool
Release frees agentID's active reservation (for example on death or disengage). It returns true if agentID held a reservation.
func (*PointReservations) ReleaseCover ¶
func (r *PointReservations) ReleaseCover(coverID uint64) bool
ReleaseCover frees whichever agent currently holds coverID (for example when destructible cover breaks).
func (*PointReservations) Reserve ¶
func (r *PointReservations) Reserve(agentID uint64, c TacticalCandidate, timeout time.Duration) bool
Reserve 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 (*PointReservations) ReserveCover ¶
func (r *PointReservations) ReserveCover(agentID uint64, cp CoverPoint, timeout time.Duration) bool
ReserveCover reserves CoverPoint cp for agentID for timeout (or Config().DefaultTimeout when timeout <= 0).
func (*PointReservations) ReservePos ¶
ReservePos reserves an arbitrary world position pos for agentID for timeout (or Config().DefaultTimeout when timeout <= 0).
func (*PointReservations) Step ¶
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 ¶
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 ¶
func NewQueryBudget(maxRaycasts, maxPathQueries int) *QueryBudget
NewQueryBudget returns a QueryBudget with the given per-step limits (<= 0 means unlimited).
func (*QueryBudget) PathQueriesRemaining ¶
func (b *QueryBudget) PathQueriesRemaining() int
PathQueriesRemaining returns remaining path queries for the current step, or -1 if unlimited.
func (*QueryBudget) PathQueriesUsed ¶
func (b *QueryBudget) PathQueriesUsed() int
PathQueriesUsed returns how many path queries have been consumed since the last Reset.
func (*QueryBudget) RaycastsRemaining ¶
func (b *QueryBudget) RaycastsRemaining() int
RaycastsRemaining returns remaining raycasts for the current step, or -1 if unlimited.
func (*QueryBudget) RaycastsUsed ¶
func (b *QueryBudget) RaycastsUsed() int
RaycastsUsed returns how many raycasts have been consumed since the last Reset.
func (*QueryBudget) Reset ¶
func (b *QueryBudget) Reset()
Reset zeroes the step's consumed raycast and path-query counters.
func (*QueryBudget) TryConsumePathQuery ¶
func (b *QueryBudget) TryConsumePathQuery() bool
TryConsumePathQuery 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 (*QueryBudget) TryConsumeRaycast ¶
func (b *QueryBudget) TryConsumeRaycast() bool
TryConsumeRaycast 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 ¶
type QueryOrigin uint8
QueryOrigin 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 ¶
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 ¶
ReachableCell is one cell returned by a movement-range query together with its minimum path cost from the start cell.
func ReachableCells ¶
func ReachableCells(g Grid, topology GridTopology, start Cell, budget float64, edgeCost func(from, to Cell) float64) []ReachableCell
ReachableCells returns every cell reachable from start on g within budget under topology, ordered by ascending cost then row-major cell index.
When edgeCost is non-nil it overrides CostGrid and EdgeCostGrid with a custom step cost multiplier. For repeated zero-allocation queries, configure an AStar with Topology and call MovementRangeInto or MovementRangeWithCost.
type ReachableNode ¶
type ReachableNode[N comparable] struct { Node N Cost float64 }
ReachableNode pairs a node reached by GraphSearch.Range with its minimum path cost from start.
type Reasoner ¶
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 ¶
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 ¶
func NewReasoner[C any](actions ...UtilityAction[C]) *Reasoner[C]
NewReasoner constructs a Reasoner with defensive copies of actions and their consideration slices.
func (*Reasoner[C]) ActionCount ¶
ActionCount returns the number of actions configured on r.
func (*Reasoner[C]) ActionIndex ¶
ActionIndex returns the index of the first action named name, or -1 if none matches.
func (*Reasoner[C]) ActionName ¶
ActionName returns the Name of action at index, or "" if index is out of bounds.
func (*Reasoner[C]) Choose ¶
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 (*Reasoner[C]) ChooseWithCurrent ¶
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 (*Reasoner[C]) Current ¶
Current returns the index of the currently active action tracked by Choose, or -1 if none is active.
func (*Reasoner[C]) Reset ¶
func (r *Reasoner[C]) Reset()
Reset clears the currently active action tracked by Choose.
func (*Reasoner[C]) ScoreAction ¶
ScoreAction scores the action at index for ctx, applying momentum when isCurrent is true. Out-of-range indices return 0.
func (*Reasoner[C]) ScoreAll ¶
ScoreAll 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 (*Reasoner[C]) SetCurrent ¶
SetCurrent sets the currently active action index tracked by Choose. Out-of-range values clear the active action to -1.
type Reservation ¶
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 ¶
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 ¶
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 ¶
func CustomCurve(fn func(float64) float64) ResponseCurve
CustomCurve returns a response curve backed by fn.
func LinearCurve ¶
func LinearCurve(slope, shiftX, shiftY float64) ResponseCurve
LinearCurve returns a linear response curve y = slope*(x - shiftX) + shiftY clamped to [0, 1].
func LogisticCurve ¶
func LogisticCurve(slope, steepness, midpoint, shiftY float64) ResponseCurve
LogisticCurve returns an S-shaped logistic response curve y = slope/(1 + exp(-steepness*(x - midpoint))) + shiftY clamped to [0, 1].
func LogitCurve ¶
func LogitCurve(slope, midpoint, shiftY float64) ResponseCurve
LogitCurve returns a logit response curve y = slope*ln(u/(1 - u)) + shiftY where u = x - midpoint + 0.5, clamped to [0, 1].
func PolynomialCurve ¶
func PolynomialCurve(slope, exponent, shiftX, shiftY float64) ResponseCurve
PolynomialCurve returns a polynomial response curve y = slope*(x - shiftX)^exponent + shiftY clamped to [0, 1].
func ResourceCurve ¶
func ResourceCurve(eval CurveEvaluator) ResponseCurve
ResourceCurve returns a response curve backed by eval (for example a *resource.Curve).
func StepCurve ¶
func StepCurve(threshold, low, high float64) ResponseCurve
StepCurve returns a threshold step response curve returning low for x < threshold and high for x >= threshold, clamped to [0, 1].
func (ResponseCurve) Eval ¶
func (c ResponseCurve) Eval(x float64) float64
Eval evaluates c at x, clamping both the input and output to [0, 1]. A NaN input or output yields 0.
type RingGenerator ¶
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 (*RingGenerator) Generate ¶
func (g *RingGenerator) Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidate
Generate appends concentric ring candidates in deterministic ring-major, angle-minor order.
type SearchStatus ¶
type SearchStatus uint8
SearchStatus reports the lifecycle state of an incremental path search.
const ( // SearchInProgress indicates the search still has work remaining and has not reached the goal or its expansion budget. SearchInProgress SearchStatus = iota // SearchComplete indicates a complete path to the goal was found. SearchComplete // SearchPartial indicates a partial path to the closest explored node was produced // because the goal was unreachable or MaxExpansions was reached with AllowPartial enabled. SearchPartial // SearchFailed indicates no path was produced (invalid endpoints, unreachable goal without AllowPartial, or budget exhausted without AllowPartial). SearchFailed )
func (SearchStatus) Done ¶
func (s SearchStatus) Done() bool
Done reports whether the search has reached a terminal state (complete, partial, or failed).
func (SearchStatus) String ¶
func (s SearchStatus) String() string
String returns a human-readable status name.
type SightConfig ¶
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 ¶
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 ¶
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 ¶
func NewSlotAssigner(rings ...EngagementRing) *SlotAssigner
NewSlotAssigner 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 (*SlotAssigner) Assign ¶
func (a *SlotAssigner) Assign(dst []SlotAssignment, target core.Point, agents []SlotAgent) []SlotAssignment
Assign 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 (*SlotAssigner) Assignment ¶
func (a *SlotAssigner) Assignment(agentID uint64) (SlotAssignment, bool)
Assignment returns the most recent SlotAssignment computed for agentID.
func (*SlotAssigner) Release ¶
func (a *SlotAssigner) Release(agentID uint64)
Release removes agentID from the assigner's stability memory and last-assignment cache.
func (*SlotAssigner) Reset ¶
func (a *SlotAssigner) Reset()
Reset clears all stability memory and cached assignments.
func (*SlotAssigner) Rings ¶
func (a *SlotAssigner) Rings() []EngagementRing
Rings returns a copy of the assigner's configured engagement rings.
func (*SlotAssigner) Slots ¶
func (a *SlotAssigner) Slots(dst []EngagementSlot, target core.Point) []EngagementSlot
Slots computes the world-space engagement slots around target and appends them to dst[:0].
func (*SlotAssigner) TotalSlots ¶
func (a *SlotAssigner) TotalSlots() int
TotalSlots returns the total number of slots across all configured rings.
type SlotAssignment ¶
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 ¶
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 ¶
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 ¶
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 (*Squad) AddMember ¶
AddMember adds agentID to the squad roster, maintaining ascending ID order. It reports whether agentID was newly added.
func (*Squad) AssignRoles ¶
func (s *Squad) AssignRoles(specs ...SquadRoleSpec) int
AssignRoles 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 (*Squad) ClearOrder ¶
func (s *Squad) ClearOrder()
ClearOrder clears the squad's directive and increments Revision.
func (*Squad) ClearRoles ¶
func (s *Squad) ClearRoles()
ClearRoles removes all role assignments from the squad.
func (*Squad) MemberCount ¶
MemberCount returns the number of members in the squad.
func (*Squad) MembersWithRole ¶
MembersWithRole appends all member IDs holding role to dst[:0] in deterministic ascending order.
func (*Squad) Order ¶
func (s *Squad) Order() SquadOrder
Order returns the squad's current directive.
func (*Squad) RemoveMember ¶
RemoveMember removes agentID from the squad roster and clears its assigned role. It reports whether agentID was a member.
func (*Squad) Role ¶
Role returns the tactical role currently assigned to agentID, or "" if unassigned or not a member.
func (*Squad) SetOrder ¶
func (s *Squad) SetOrder(order SquadOrder) SquadOrder
SetOrder updates the squad's directive, increments Revision, and returns the stored order.
func (*Squad) SetRole ¶
SetRole manually assigns role to agentID if agentID is a member (passing "" unassigns it). It reports whether agentID is in the squad.
func (*Squad) State ¶
func (s *Squad) State() *SquadState
State returns the squad's shared key-value state.
type SquadOrder ¶
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 ¶
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 ¶
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 (*SquadState) Bool ¶
func (s *SquadState) Bool(key string) (bool, bool)
Bool retrieves a bool value stored under key.
func (*SquadState) Float ¶
func (s *SquadState) Float(key string) (float64, bool)
Float retrieves a float64 value stored under key.
func (*SquadState) Get ¶
func (s *SquadState) Get(key string) (any, bool)
Get retrieves the value stored under key.
func (*SquadState) Has ¶
func (s *SquadState) Has(key string) bool
Has reports whether key is present in s.
func (*SquadState) ID ¶
func (s *SquadState) ID(key string) (uint64, bool)
ID retrieves a uint64 identifier stored under key.
func (*SquadState) Int ¶
func (s *SquadState) Int(key string) (int, bool)
Int retrieves an int value stored under key.
func (*SquadState) Keys ¶
func (s *SquadState) Keys(dst []string) []string
Keys appends all keys in s to dst[:0] in deterministic ascending lexicographical order.
func (*SquadState) Point ¶
func (s *SquadState) Point(key string) (core.Point, bool)
Point retrieves a core.Point value stored under key.
func (*SquadState) Set ¶
func (s *SquadState) Set(key string, value any)
Set stores value under key.
func (*SquadState) SetBool ¶
func (s *SquadState) SetBool(key string, v bool)
SetBool stores a bool value under key.
func (*SquadState) SetFloat ¶
func (s *SquadState) SetFloat(key string, v float64)
SetFloat stores a float64 value under key.
func (*SquadState) SetID ¶
func (s *SquadState) SetID(key string, v uint64)
SetID stores a uint64 identifier under key.
func (*SquadState) SetInt ¶
func (s *SquadState) SetInt(key string, v int)
SetInt stores an int value under key.
func (*SquadState) SetPoint ¶
func (s *SquadState) SetPoint(key string, v core.Point)
SetPoint stores a core.Point value under key.
func (*SquadState) SetString ¶
func (s *SquadState) SetString(key string, v string)
SetString stores a string value under key.
type Status ¶
type Status uint8
Status is the outcome of one Tick of a behavior tree Node.
func (Status) MarshalText ¶
MarshalText encodes s as its lowercase name ("success", "failure", or "running") so snapshots read clearly in YAML and JSON.
func (*Status) UnmarshalText ¶
UnmarshalText decodes a status name written by Status.MarshalText.
type StimulusID ¶
type StimulusID uint64
StimulusID 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 ¶
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 ¶
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 ¶
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 ¶
func NewTacticalQuery(generators []CandidateGenerator, tests ...TacticalTest) *TacticalQuery
NewTacticalQuery returns a TacticalQuery configured with the given generators and tests.
func (*TacticalQuery) Best ¶
func (q *TacticalQuery) Best(ctx TacticalContext) (TacticalCandidate, bool)
Best executes the query and returns the highest-scoring surviving candidate without allocating.
func (*TacticalQuery) LastStats ¶
func (q *TacticalQuery) LastStats() QueryStats
LastStats returns diagnostic counts from the most recent Run, RunInto, Best, or RunAndReserve call.
func (*TacticalQuery) Run ¶
func (q *TacticalQuery) Run(ctx TacticalContext) []TacticalCandidate
Run 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 (*TacticalQuery) RunAndReserve ¶
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 (*TacticalQuery) RunInto ¶
func (q *TacticalQuery) RunInto(dst []TacticalCandidate, ctx TacticalContext) []TacticalCandidate
RunInto 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 ¶
type TacticalTest interface {
// contains filtered or unexported methods
}
TacticalTest filters and/or scores candidates inside a TacticalQuery.
type Target ¶
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 ¶
type Team uint8
Team is a team affiliation, compared by an AttitudeFunc to decide whether an agent treats a stimulus as hostile, neutral or friendly.
const NoTeam Team = 255
NoTeam is the team of things that belong to no side; DefaultAttitude treats it as neutral to everyone.
type TestPurpose ¶
type TestPurpose uint8
TestPurpose 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 ¶
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 ¶
type TiledNavMesh struct {
// contains filtered or unexported fields
}
TiledNavMesh is a 2D navigation mesh partitioned into fixed-size square tiles that can be baked, added, removed, and replaced independently at runtime. Polygons are automatically linked across tile borders, dynamic obstacles rebuild only the touched tiles, a two-level spatial index avoids whole-mesh scans, and per-tile versions + watchers invalidate paths crossing changed tiles.
TiledNavMesh is deterministic and is not safe for concurrent mutation.
func BuildTiledNavMesh ¶
func BuildTiledNavMesh(polys [][]core.Point, tileSize float32) *TiledNavMesh
BuildTiledNavMesh constructs a 2D TiledNavMesh from convex polygons using fixed square tiles of size tileSize.
func BuildTiledNavMeshWithAreas ¶
func BuildTiledNavMeshWithAreas(polys []NavPolygonInput, tileSize float32) *TiledNavMesh
BuildTiledNavMeshWithAreas constructs a 2D TiledNavMesh from convex polygons carrying per-polygon areas and flags.
func NewTiledNavMesh ¶
func NewTiledNavMesh(cfg TiledNavMeshConfig) *TiledNavMesh
NewTiledNavMesh creates an empty 2D TiledNavMesh with cfg.
func (*TiledNavMesh) AddObstacle ¶
func (tm *TiledNavMesh) AddObstacle(obs NavObstacle) (NavObstacleID, bool)
AddObstacle registers a dynamic obstacle and immediately rebuilds only the touched tiles (or defers rebuild until Batch returns if called inside Batch). Returns (0, false) if tm is nil or obs has invalid geometry.
func (*TiledNavMesh) AddOffMeshLink ¶
func (tm *TiledNavMesh) AddOffMeshLink(link NavOffMeshLink) bool
AddOffMeshLink connects the polygons containing (or within link.Radius of) link.Start and link.End with a directed (or bidirectional) off-mesh portal and automatically re-attaches it whenever touched tiles are replaced, rebuilt, or carved by dynamic obstacles. Returns false if tm is nil or empty, link coordinates or Radius are invalid, either endpoint cannot attach to the mesh, or both endpoints collapse to the same point on the same polygon.
func (*TiledNavMesh) AddTile ¶
func (tm *TiledNavMesh) AddTile(coord NavTileCoord, tile *NavTile) bool
AddTile installs tile at coord only if no tile currently exists at coord. Returns false if tm or tile is nil or coord is already occupied.
func (*TiledNavMesh) AddTileListener ¶
func (tm *TiledNavMesh) AddTileListener(fn func(NavTileChange)) NavListenerID
AddTileListener registers fn to be invoked whenever any tile is added, updated, or removed.
func (*TiledNavMesh) BakeTile ¶
func (tm *TiledNavMesh) BakeTile(coord NavTileCoord, polys []NavPolygonInput) *NavTile
BakeTile bakes polys into a NavTile for coord using tm's TileSize and Origin and installs it into tm.
func (*TiledNavMesh) Batch ¶
func (tm *TiledNavMesh) Batch(fn func())
Batch groups multiple tile or obstacle mutations so each touched tile is rebuilt at most once in deterministic sorted order when fn returns, and notifications fire once per changed tile.
func (*TiledNavMesh) ClearObstacles ¶
func (tm *TiledNavMesh) ClearObstacles()
ClearObstacles removes all dynamic obstacles and rebuilds only tiles that had obstacles.
func (*TiledNavMesh) ClearOffMeshLinks ¶
func (tm *TiledNavMesh) ClearOffMeshLinks()
ClearOffMeshLinks removes all off-mesh links from tm and bumps the mesh revision when any were present.
func (*TiledNavMesh) Contains ¶
func (tm *TiledNavMesh) Contains(p core.Point) bool
Contains reports whether p lies inside any polygon of the tiled mesh.
func (*TiledNavMesh) ContainsWithFilter ¶
func (tm *TiledNavMesh) ContainsWithFilter(p core.Point, filter NavFilter) bool
ContainsWithFilter reports whether p lies inside any polygon passing filter.
func (*TiledNavMesh) FindCorridor ¶
func (tm *TiledNavMesh) FindCorridor(start, goal core.Point) ([]NavPolyRef, bool)
FindCorridor finds the sequence of NavPolyRefs from start to goal using DefaultNavFilter.
func (*TiledNavMesh) FindCorridorWithFilter ¶
func (tm *TiledNavMesh) FindCorridorWithFilter(start, goal core.Point, filter NavFilter) ([]NavPolyRef, bool)
FindCorridorWithFilter finds the sequence of NavPolyRefs from start to goal restricted to filter.
func (*TiledNavMesh) FindPath ¶
FindPath finds the shortest path inside tm from start to goal using DefaultNavFilter.
func (*TiledNavMesh) FindPathWithFilter ¶
func (tm *TiledNavMesh) FindPathWithFilter(start, goal core.Point, filter NavFilter) ([]core.Point, bool)
FindPathWithFilter finds the minimum-cost path inside tm restricted to filter.
func (*TiledNavMesh) FindPathWithFilterAndOptions ¶
func (tm *TiledNavMesh) FindPathWithFilterAndOptions(start, goal core.Point, filter NavFilter, opts PathOptions) TiledNavPathResult
FindPathWithFilterAndOptions finds a minimum-cost path across tm restricted to filter and opts. Portal A* touches only visited portals (sparse state, independent of total mesh size) and runs Simple Stupid Funnel Algorithm string-pulling across tile borders so paths match an untiled NavMesh for the same geometry.
func (*TiledNavMesh) FindPathWithOptions ¶
func (tm *TiledNavMesh) FindPathWithOptions(start, goal core.Point, opts PathOptions) TiledNavPathResult
FindPathWithOptions finds a path using DefaultNavFilter and opts, returning the full TiledNavPathResult with tile footprint and version stamps for invalidation checking.
func (*TiledNavMesh) FindPolygon ¶
func (tm *TiledNavMesh) FindPolygon(p core.Point) (NavPolyRef, bool)
FindPolygon locates a polygon containing p in O(1) tile lookup + O(log P_tile) local BVH.
func (*TiledNavMesh) FindPolygonWithFilter ¶
func (tm *TiledNavMesh) FindPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, bool)
FindPolygonWithFilter locates a polygon passing filter that contains p.
func (*TiledNavMesh) HasTile ¶
func (tm *TiledNavMesh) HasTile(coord NavTileCoord) bool
HasTile reports whether a tile is currently installed at coord.
func (*TiledNavMesh) IsPathValid ¶
func (tm *TiledNavMesh) IsPathValid(res TiledNavPathResult) bool
IsPathValid reports whether every tile crossed by res is still present and unchanged since res was computed.
func (*TiledNavMesh) NearestPoint ¶
func (tm *TiledNavMesh) NearestPoint(p, extent core.Point) (core.Point, NavPolyRef, bool)
NearestPoint returns the closest point on any polygon allowed by DefaultNavFilter within half-extents [p - extent, p + extent], together with its NavPolyRef.
func (*TiledNavMesh) NearestPointWithFilter ¶
func (tm *TiledNavMesh) NearestPointWithFilter(p, extent core.Point, filter NavFilter) (core.Point, NavPolyRef, bool)
NearestPointWithFilter behaves like NearestPoint restricted to filter.
func (*TiledNavMesh) NearestPolygon ¶
func (tm *TiledNavMesh) NearestPolygon(p core.Point) (NavPolyRef, core.Point, bool)
NearestPolygon returns the polygon closest to p and the closest point on or inside it, using the two-level spatial index (coarse tile BVH + per-tile BVH).
func (*TiledNavMesh) NearestPolygonWithFilter ¶
func (tm *TiledNavMesh) NearestPolygonWithFilter(p core.Point, filter NavFilter) (NavPolyRef, core.Point, bool)
NearestPolygonWithFilter returns the closest polygon passing filter and the closest point on it.
func (*TiledNavMesh) Neighbors ¶
func (tm *TiledNavMesh) Neighbors(ref NavPolyRef) []NavPolyRef
Neighbors returns the polygon references sharing an edge (intra-tile or cross-tile) with ref.
func (*TiledNavMesh) ObstacleCount ¶
func (tm *TiledNavMesh) ObstacleCount() int
ObstacleCount returns the number of active dynamic obstacles.
func (*TiledNavMesh) OffMeshLinks ¶
func (tm *TiledNavMesh) OffMeshLinks() []NavOffMeshLink
OffMeshLinks returns a copy of all off-mesh links registered on tm in insertion order.
func (*TiledNavMesh) Origin ¶
func (tm *TiledNavMesh) Origin() core.Point
Origin returns the world-space origin of tile (0, 0).
func (*TiledNavMesh) Polygon ¶
func (tm *TiledNavMesh) Polygon(ref NavPolyRef) []core.Point
Polygon returns a copy of the vertices of ref, or nil if ref is stale or invalid.
func (*TiledNavMesh) PolygonArea ¶
func (tm *TiledNavMesh) PolygonArea(ref NavPolyRef) NavArea
PolygonArea returns the area of ref, or NavAreaDefault if ref is invalid.
func (*TiledNavMesh) PolygonCount ¶
func (tm *TiledNavMesh) PolygonCount() int
PolygonCount returns the total number of active walkable polygons across all installed tiles.
func (*TiledNavMesh) PolygonFlags ¶
func (tm *TiledNavMesh) PolygonFlags(ref NavPolyRef) NavFlags
PolygonFlags returns the runtime flags of ref, or 0 if ref is invalid.
func (*TiledNavMesh) Raycast ¶
func (tm *TiledNavMesh) Raycast(start, target core.Point) (TiledNavRaycastHit, bool)
Raycast casts a segment along the 2D TiledNavMesh surface from start toward target using DefaultNavFilter.
func (*TiledNavMesh) RaycastWithFilter ¶
func (tm *TiledNavMesh) RaycastWithFilter(start, target core.Point, filter NavFilter) (TiledNavRaycastHit, bool)
RaycastWithFilter behaves like Raycast restricted to polygons allowed by filter.
func (*TiledNavMesh) RebuildTile ¶
func (tm *TiledNavMesh) RebuildTile(coord NavTileCoord) bool
RebuildTile rebuilds the existing tile at coord from its base polygons and active dynamic obstacles. Returns false if no tile exists at coord.
func (*TiledNavMesh) RemoveObstacle ¶
func (tm *TiledNavMesh) RemoveObstacle(id NavObstacleID) bool
RemoveObstacle removes dynamic obstacle id and rebuilds only the tiles it touched, restoring their uncarved geometry.
func (*TiledNavMesh) RemoveTile ¶
func (tm *TiledNavMesh) RemoveTile(coord NavTileCoord) bool
RemoveTile unloads the tile at coord, removes cross-tile border links from neighboring tiles, bumps coord's tile version, and notifies listeners / invalidates paths crossing coord.
func (*TiledNavMesh) RemoveTileListener ¶
func (tm *TiledNavMesh) RemoveTileListener(id NavListenerID) bool
RemoveTileListener unregisters a listener previously added with AddTileListener.
func (*TiledNavMesh) ReplaceTile ¶
func (tm *TiledNavMesh) ReplaceTile(coord NavTileCoord, tile *NavTile) bool
ReplaceTile replaces the existing tile at coord with tile. Returns false if tm or tile is nil or no tile currently exists at coord.
func (*TiledNavMesh) Revision ¶
func (tm *TiledNavMesh) Revision() uint64
Revision returns a monotonically increasing number bumped on any tile or obstacle mutation.
func (*TiledNavMesh) SetTile ¶
func (tm *TiledNavMesh) SetTile(coord NavTileCoord, tile *NavTile) bool
SetTile installs or replaces tile at coord, applying any active dynamic obstacles touching coord and linking polygons across borders with neighboring tiles.
func (*TiledNavMesh) TileBounds ¶
func (tm *TiledNavMesh) TileBounds(coord NavTileCoord) (minPt, maxPt core.Point)
TileBounds returns the exact world-space [min, max] bounds of tile coord.
func (*TiledNavMesh) TileCoordAt ¶
func (tm *TiledNavMesh) TileCoordAt(p core.Point) NavTileCoord
TileCoordAt returns the tile coordinate containing p.
func (*TiledNavMesh) TileCoords ¶
func (tm *TiledNavMesh) TileCoords() []NavTileCoord
TileCoords returns all installed tile coordinates in deterministic sorted order.
func (*TiledNavMesh) TileCount ¶
func (tm *TiledNavMesh) TileCount() int
TileCount returns the number of currently installed tiles.
func (*TiledNavMesh) TilePolygonCount ¶
func (tm *TiledNavMesh) TilePolygonCount(coord NavTileCoord) int
TilePolygonCount returns the number of active polygons currently inside tile coord.
func (*TiledNavMesh) TileSize ¶
func (tm *TiledNavMesh) TileSize() float32
TileSize returns the configured tile size in world units.
func (*TiledNavMesh) TileVersion ¶
func (tm *TiledNavMesh) TileVersion(coord NavTileCoord) uint64
TileVersion returns the current revision number of tile coord (0 if never modified).
func (*TiledNavMesh) UnwatchPath ¶
func (tm *TiledNavMesh) UnwatchPath(id NavPathWatchID) bool
UnwatchPath cancels a path watcher previously registered with WatchPath.
func (*TiledNavMesh) UpdateObstacle ¶
func (tm *TiledNavMesh) UpdateObstacle(id NavObstacleID, obs NavObstacle) bool
UpdateObstacle replaces the geometry or mode of an existing dynamic obstacle id, rebuilding only tiles touched by either its old or new footprint.
func (*TiledNavMesh) WatchPath ¶
func (tm *TiledNavMesh) WatchPath(tiles []NavTileCoord, onInvalidate func(NavTileChange)) NavPathWatchID
WatchPath registers a one-shot invalidation callback invoked when any tile in tiles changes. Because watchers are indexed per tile, changing a tile notifies only paths crossing that tile. Once triggered, the watch is automatically removed.
type TiledNavMeshConfig ¶
TiledNavMeshConfig configures a 2D TiledNavMesh.
type TiledNavPathLink ¶
type TiledNavPathLink struct {
StartIndex int
EndIndex int
// FromPoly and ToPoly are the source and destination polygon references connected by the link.
// Start and End are the world-space entry and exit positions of the traversed link direction.
Radius float32
Area NavArea
Flags uint32
LinkID int
UserData any
}
TiledNavPathLink marks a segment in TiledNavPathResult.Path that traverses an off-mesh link. Path[StartIndex] is the link's entry point on the mesh and Path[EndIndex] is its exit point (with EndIndex == StartIndex + 1).
type TiledNavPathResult ¶
type TiledNavPathResult struct {
// Links lists each segment of Path that traverses an off-mesh link, in path order.
// For each link, Path[link.StartIndex] is the entry point and Path[link.EndIndex]
// (with EndIndex == StartIndex + 1) is the exit point.
}
TiledNavPathResult is the outcome of a 2D TiledNavMesh path search, including the tile footprint and tile versions crossed so callers can detect invalidation.
func (TiledNavPathResult) CrossesTile ¶
func (r TiledNavPathResult) CrossesTile(coord NavTileCoord) bool
CrossesTile reports whether r's corridor passes through coord.
func (TiledNavPathResult) HasLinks ¶
func (r TiledNavPathResult) HasLinks() bool
HasLinks reports whether r traverses at least one off-mesh link.
func (TiledNavPathResult) LinkAt ¶
func (r TiledNavPathResult) LinkAt(segmentIndex int) (TiledNavPathLink, bool)
LinkAt returns the off-mesh link traversed by path segment segmentIndex (from Path[segmentIndex] to Path[segmentIndex+1]), or (zero, false) when that segment is ordinary walking movement.
func (TiledNavPathResult) TileCoords ¶
func (r TiledNavPathResult) TileCoords() []NavTileCoord
TileCoords returns the deduplicated list of tile coordinates crossed by r.
type TiledNavRaycastHit ¶
type TiledNavRaycastHit struct {
}
TiledNavRaycastHit describes the result of casting a segment across a 2D TiledNavMesh.
type TokenHolder ¶
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 ¶
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 ¶
func NewTokenManager(defaultCfg TokenPoolConfig) *TokenManager
NewTokenManager returns a TokenManager using defaultCfg for targets created on demand.
func (*TokenManager) Cancel ¶
func (m *TokenManager) Cancel(targetID, agentID uint64) bool
Cancel withdraws agentID's pending request for targetID.
func (*TokenManager) ConfigureTarget ¶
func (m *TokenManager) ConfigureTarget(targetID uint64, cfg TokenPoolConfig) *TokenPool
ConfigureTarget creates or replaces the TokenPool for targetID with cfg and returns it.
func (*TokenManager) HasToken ¶
func (m *TokenManager) HasToken(targetID, agentID uint64) bool
HasToken reports whether agentID holds an attack token for targetID.
func (*TokenManager) Pool ¶
func (m *TokenManager) Pool(targetID uint64) *TokenPool
Pool returns the TokenPool for targetID, or nil if none exists yet.
func (*TokenManager) Release ¶
func (m *TokenManager) Release(targetID, agentID uint64) bool
Release returns agentID's held token for targetID to cooldown and cancels any pending request.
func (*TokenManager) RemoveAgent ¶
func (m *TokenManager) RemoveAgent(agentID uint64)
RemoveAgent releases any tokens held by agentID and cancels any pending requests across all targets.
func (*TokenManager) RemoveTarget ¶
func (m *TokenManager) RemoveTarget(targetID uint64) bool
RemoveTarget deletes targetID's TokenPool (for example, when that target is defeated).
func (*TokenManager) Request ¶
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 (*TokenManager) Step ¶
func (m *TokenManager) Step(dt time.Duration)
Step advances every target's TokenPool by dt in deterministic ascending target ID order.
type TokenPool ¶
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 ¶
func NewTokenPool(cfg TokenPoolConfig) *TokenPool
NewTokenPool returns a TokenPool initialized with cfg.
func (*TokenPool) Available ¶
Available returns the number of tokens immediately free to grant on the next Step.
func (*TokenPool) Cancel ¶
Cancel withdraws a pending request for agentID without releasing a held token. It reports whether a pending request existed.
func (*TokenPool) Config ¶
func (p *TokenPool) Config() TokenPoolConfig
Config returns the pool's effective configuration.
func (*TokenPool) CoolingDown ¶
CoolingDown returns the number of returned tokens currently waiting on cooldown.
func (*TokenPool) HasToken ¶
HasToken reports whether agentID currently holds an attack token from p.
func (*TokenPool) Holder ¶
func (p *TokenPool) Holder(agentID uint64) (TokenHolder, bool)
Holder returns the TokenHolder record for agentID if it currently holds a token.
func (*TokenPool) Holders ¶
func (p *TokenPool) Holders(dst []TokenHolder) []TokenHolder
Holders appends all active holders to dst[:0], sorted by ascending AgentID.
func (*TokenPool) PendingCount ¶
PendingCount returns the number of waiting token requests.
func (*TokenPool) Release ¶
Release 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 (*TokenPool) Remove ¶
Remove 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 (*TokenPool) Request ¶
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 (*TokenPool) Reset ¶
func (p *TokenPool) Reset()
Reset clears all active holders, pending requests, and cooldown timers, restoring Available() to Capacity().
func (*TokenPool) Step ¶
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 ¶
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 ¶
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 (*UtilityAction[C]) Score ¶
func (a *UtilityAction[C]) Score(ctx C, momentumBonus float64) float64
Score 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 ¶
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 ¶
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 ¶
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 ¶
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 (*UtilityConfig) Validate ¶
func (cfg *UtilityConfig) Validate() error
Validate checks that cfg has version UtilityVersion, valid parameters, unique action names, and well-formed considerations and curves.
type ValidatedGraph ¶
type ValidatedGraph[N comparable] interface { ValidNode(node N) bool }
ValidatedGraph is an optional interface a Graph may implement to reject invalid, out-of-bounds, blocked, or removed nodes before searching.
type Vec3 ¶
type Vec3 struct {
X, Y, Z float32
}
Vec3 is a 3-component float32 vector in right-handed Y-up space (+X right, +Y up, -Z forward). Its field layout matches math3d.Vec3 so callers can convert values with a zero-cost ai.Vec3(v) cast without importing the experimental game/math3d package from stable game/ai.
func Alignment3D ¶
Alignment3D steers a toward the average heading of neighbors within radius (or all non-coincident neighbors when radius <= 0).
func Arrive3D ¶
Arrive3D returns a steering force toward target that smoothly scales desired speed down to zero inside slowRadius.
func Cohesion3D ¶
Cohesion3D steers a toward the center of mass of neighbors within radius (or all non-coincident neighbors when radius <= 0).
func Combine3D ¶
func Combine3D(maxForce float32, forces ...WeightedForce3D) Vec3
Combine3D sums weighted 3D steering forces and clamps the result's magnitude to maxForce when maxForce is positive.
func CombinePrioritized3D ¶
func CombinePrioritized3D(maxForce float32, forces ...WeightedForce3D) Vec3
CombinePrioritized3D 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 ¶
Evade3D returns a steering force that flees from the predicted position of pursuer while closer than panicRadius (or always when panicRadius <= 0).
func Flee3D ¶
Flee3D 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 ¶
func FollowPath3D(a Agent3D, path []Vec3, state *PathFollowState, waypointRadius float32, loop bool) Vec3
FollowPath3D 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 ¶
func Hide3D(a, pursuer Agent3D, obstacles []Obstacle3D, standoff, slowRadius float32) Vec3
Hide3D 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 ¶
Interpose3D steers a to intercept the predicted midpoint between moving agents targetA and targetB, slowing smoothly inside slowRadius via Arrive3D.
func ObstacleAvoidance3D ¶
func ObstacleAvoidance3D(a Agent3D, obstacles []Obstacle3D, maxAhead float32) Vec3
ObstacleAvoidance3D 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 ¶
OffsetPursuit3D 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 ¶
Pursue3D returns a steering force that intercepts target by predicting its future position from target.Vel, capped to maxLookAhead seconds when positive.
func Seek3D ¶
Seek3D returns the 3D (or XZ-planar) steering force accelerating a toward target at MaxSpeed.
func Separation3D ¶
Separation3D pushes a away from neighbors closer than desiredSep (defaulting to a.Radius + neighbor.Radius when desiredSep <= 0).
type Wall3D ¶
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 ¶
type WanderState struct {
Angle float32
}
WanderState holds the persistent wander angle for an agent across steps.
type WaypointEdge ¶
WaypointEdge is a directed outgoing edge in a WaypointGraph.
type WaypointGraph ¶
type WaypointGraph struct {
// contains filtered or unexported fields
}
WaypointGraph is a weighted graph of hand-placed 2D or 3D waypoints implementing HeuristicGraph[int], ValidatedGraph[int], and NodeOrder[int].
Each added waypoint receives a stable integer ID (0, 1, 2, ...). Removing a waypoint invalidates its ID without renumbering remaining waypoints. Edges may be directed or undirected, with either automatic Euclidean-distance costs (Connect / ConnectUndirected) or explicit non-negative weights (AddEdge / AddUndirectedEdge).
Heuristic returns the Euclidean distance between two waypoints, which is admissible when every edge cost is at least Euclidean distance; use GraphSearch.FindDijkstra or FindWithHeuristic when graphs contain shortcut or portal edges cheaper than Euclidean distance.
Example ¶
WaypointGraph stores hand-placed 2D or 3D waypoints with weighted edges searched by GraphSearch.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/ai"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
g := ai.NewWaypointGraph()
a := g.Add(core.Point{X: 0, Y: 0})
b := g.Add(core.Point{X: 30, Y: 0})
c := g.Add(core.Point{X: 30, Y: 40})
g.ConnectUndirected(a, b)
g.ConnectUndirected(b, c)
g.ConnectUndirected(a, c)
path, cost, ok := ai.NewGraphSearch[int]().Find(g, a, c)
fmt.Println(ok, cost, path)
}
Output: true 50 [0 2]
func NewWaypointGraph ¶
func NewWaypointGraph() *WaypointGraph
NewWaypointGraph returns an empty WaypointGraph.
func (*WaypointGraph) Add ¶
func (g *WaypointGraph) Add(pos core.Point) int
Add adds a 2D waypoint at pos (with Z = 0) and returns its stable node ID.
func (*WaypointGraph) Add3D ¶
func (g *WaypointGraph) Add3D(pos Vec3) int
Add3D adds a 3D waypoint at pos and returns its stable node ID.
func (*WaypointGraph) AddEdge ¶
func (g *WaypointGraph) AddEdge(from, to int, cost float64) bool
AddEdge adds or updates a directed edge from -> to with explicit non-negative finite cost. Returns false if either endpoint is invalid/removed or cost is negative, NaN, or infinite.
func (*WaypointGraph) AddUndirectedEdge ¶
func (g *WaypointGraph) AddUndirectedEdge(a, b int, cost float64) bool
AddUndirectedEdge adds or updates bidirectional edges between a and b with explicit non-negative finite cost. Returns false if either endpoint is invalid/removed or cost is negative, NaN, or infinite.
func (*WaypointGraph) AppendNeighbors ¶
AppendNeighbors appends all outgoing edges from id to enabled destination waypoints onto dst in deterministic ascending destination ID order.
func (*WaypointGraph) Connect ¶
func (g *WaypointGraph) Connect(from, to int) bool
Connect adds or updates a directed edge from -> to whose cost is the live Euclidean distance between the two waypoints. Returns false if either endpoint is invalid or removed.
func (*WaypointGraph) ConnectUndirected ¶
func (g *WaypointGraph) ConnectUndirected(a, b int) bool
ConnectUndirected adds or updates bidirectional edges between a and b whose cost is the live Euclidean distance between them. Returns false if either endpoint is invalid or removed.
func (*WaypointGraph) Edges ¶
func (g *WaypointGraph) Edges(id int) []WaypointEdge
Edges returns a copy of waypoint id's outgoing edges ordered by ascending destination ID.
func (*WaypointGraph) Enabled ¶
func (g *WaypointGraph) Enabled(id int) bool
Enabled reports whether id is an active, enabled waypoint.
func (*WaypointGraph) Heuristic ¶
func (g *WaypointGraph) Heuristic(from, goal int) float64
Heuristic returns the Euclidean distance between waypoints from and goal.
func (*WaypointGraph) Nearest ¶
func (g *WaypointGraph) Nearest(pos core.Point) (int, bool)
Nearest returns the ID of the enabled waypoint closest to 2D point pos (in XY), breaking distance ties deterministically by lowest waypoint ID.
func (*WaypointGraph) Nearest3D ¶
func (g *WaypointGraph) Nearest3D(pos Vec3) (int, bool)
Nearest3D returns the ID of the enabled waypoint closest to 3D point pos, breaking distance ties deterministically by lowest waypoint ID.
func (*WaypointGraph) NodeCount ¶
func (g *WaypointGraph) NodeCount() int
NodeCount returns the number of active (non-removed) waypoints in g.
func (*WaypointGraph) NodeLess ¶
func (g *WaypointGraph) NodeLess(a, b int) bool
NodeLess breaks search ties deterministically by ascending waypoint ID.
func (*WaypointGraph) Points ¶
func (g *WaypointGraph) Points(ids []int) []core.Point
Points converts a slice of waypoint IDs into their 2D positions.
func (*WaypointGraph) Points3D ¶
func (g *WaypointGraph) Points3D(ids []int) []Vec3
Points3D converts a slice of waypoint IDs into their 3D positions.
func (*WaypointGraph) Points3DInto ¶
func (g *WaypointGraph) Points3DInto(dst []Vec3, ids []int) []Vec3
Points3DInto writes the 3D positions of ids into dst[:0], avoiding allocations when dst has enough capacity.
func (*WaypointGraph) PointsInto ¶
PointsInto writes the 2D positions of ids into dst[:0], avoiding allocations when dst has enough capacity.
func (*WaypointGraph) Pos ¶
func (g *WaypointGraph) Pos(id int) (core.Point, bool)
Pos returns the 2D position of active waypoint id, or (zero, false) if id is invalid or removed.
func (*WaypointGraph) Pos3D ¶
func (g *WaypointGraph) Pos3D(id int) (Vec3, bool)
Pos3D returns the 3D position of active waypoint id, or (zero, false) if id is invalid or removed.
func (*WaypointGraph) Remove ¶
func (g *WaypointGraph) Remove(id int) bool
Remove deletes waypoint id and all edges incident to it while keeping all other node IDs stable. It returns false if id is invalid or already removed.
func (*WaypointGraph) RemoveEdge ¶
func (g *WaypointGraph) RemoveEdge(from, to int) bool
RemoveEdge removes the directed edge from -> to, returning true if it existed.
func (*WaypointGraph) RemoveUndirectedEdge ¶
func (g *WaypointGraph) RemoveUndirectedEdge(a, b int) bool
RemoveUndirectedEdge removes both a -> b and b -> a, returning true if either existed.
func (*WaypointGraph) SetEnabled ¶
func (g *WaypointGraph) SetEnabled(id int, enabled bool)
SetEnabled enables or disables an active waypoint without removing its edges. Disabled waypoints are skipped during searches and Nearest queries.
func (*WaypointGraph) SetPos ¶
func (g *WaypointGraph) SetPos(id int, pos core.Point)
SetPos updates the 2D position of waypoint id (setting Z = 0).
func (*WaypointGraph) SetPos3D ¶
func (g *WaypointGraph) SetPos3D(id int, pos Vec3)
SetPos3D updates the 3D position of waypoint id.
func (*WaypointGraph) ValidNode ¶
func (g *WaypointGraph) ValidNode(id int) bool
ValidNode reports whether id is an active, enabled waypoint in g.
type WeightedForce ¶
WeightedForce pairs a steering force with a scalar weight for Combine.
type WeightedForce3D ¶
WeightedForce3D pairs a 3D steering force with a scalar weight for Combine3D and CombinePrioritized3D.
type WeightedLayer ¶
type WeightedLayer struct {
Layer *InfluenceLayer
Weight float32
}
WeightedLayer pairs an InfluenceLayer with a scalar weight for InfluenceLayer.Combine.
type WeightedNode ¶
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 ¶
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 (WorldState) Apply ¶
func (w WorldState) Apply(eff Effects) WorldState
Apply returns a copy of w updated with eff.
func (WorldState) Bool ¶
func (w WorldState) Bool(f BoolFact) bool
Bool returns the value of boolean fact f, or false if f is out of range.
func (WorldState) Int ¶
func (w WorldState) Int(f IntFact) int
Int returns the value of integer fact f, or 0 if f is out of range.
func (WorldState) Satisfies ¶
func (w WorldState) Satisfies(cond Conditions) bool
Satisfies reports whether w satisfies every boolean and integer requirement in cond.
func (*WorldState) SetBool ¶
func (w *WorldState) SetBool(f BoolFact, v bool)
SetBool sets boolean fact f to v. Out-of-range facts are ignored.
func (*WorldState) SetInt ¶
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 (WorldState) WithBool ¶
func (w WorldState) WithBool(f BoolFact, v bool) WorldState
WithBool returns a copy of w with boolean fact f set to v.
func (WorldState) WithInt ¶
func (w WorldState) WithInt(f IntFact, v int) WorldState
WithInt returns a copy of w with integer fact f set to v (clamped to int16 range).
Source Files
¶
- astar.go
- blackboard.go
- bt.go
- bt_blackboard.go
- bt_ext.go
- bt_inspect.go
- bt_snapshot.go
- bt_yaml.go
- cover.go
- doc.go
- goap.go
- goap_yaml.go
- graph.go
- hex_graph.go
- hpa.go
- influence.go
- influence_debug.go
- jps.go
- navagent.go
- navmesh.go
- navmesh_filter.go
- navmesh_query.go
- orca.go
- pathsearch.go
- perception.go
- perception2d.go
- perception_los.go
- smooth.go
- squad.go
- steering.go
- steering3d.go
- steering_ext.go
- tactical.go
- tiled_navmesh.go
- tiled_navmesh_geom.go
- tokens.go
- topology.go
- utility.go
- utility_yaml.go
- waypoint.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
sense
Package sense is the perception engine behind ai.PerceptionSystem and perception3d.System: sight cones, a round-robin line-of-sight budget, hearing, and per-stimulus memory, all on float64 3D vectors so the 2D and 3D front ends share one implementation.
|
Package sense is the perception engine behind ai.PerceptionSystem and perception3d.System: sight cones, a round-robin line-of-sight budget, hearing, and per-stimulus memory, all on float64 3D vectors so the 2D and 3D front ends share one implementation. |
|
Package navbake bakes 2D navigation meshes for game/ai from level geometry: an outline with concave obstacles and holes, or a tilemap's solid cells, shrunk by an agent's radius and divided into the convex polygons ai.NavMesh searches.
|
Package navbake bakes 2D navigation meshes for game/ai from level geometry: an outline with concave obstacles and holes, or a tilemap's solid cells, shrunk by an agent's radius and divided into the convex polygons ai.NavMesh searches. |
|
Package navbake3d bakes 3D navigation meshes from level geometry, as Recast, Godot's NavigationRegion3D and Unity's NavMeshSurface do, so a 3D game no longer authors world3d.NavMesh polygons by hand.
|
Package navbake3d bakes 3D navigation meshes from level geometry, as Recast, Godot's NavigationRegion3D and Unity's NavMeshSurface do, so a 3D game no longer authors world3d.NavMesh polygons by hand. |
|
Package perception3d is ai's perception for agents in a 3D world: sight cones around a forward vector, hearing and per-stimulus memory on math3d.Vec3, with line of sight through physics3d raycasts or a game's own check.
|
Package perception3d is ai's perception for agents in a 3D world: sight cones around a forward vector, hearing and per-stimulus memory on math3d.Vec3, with line of sight through physics3d raycasts or a game's own check. |