ai

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 23 Imported by: 4 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ai provides deterministic game AI decision-making and movement building blocks: 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. Grids, A*, graphs, waypoints and 2D navigation meshes live in game/pathfind.

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

Index

Examples

Constants

View Source
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
)
View Source
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)
)
View Source
const BTFormatVersion = 1

BTFormatVersion is the behavior tree YAML schema version this package reads and writes.

View Source
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.

View Source
const BTSchemaURL = "https://game.nsgo.dev/schemas/bt.v1.json"

BTSchemaURL is where the JSON Schema of version 1 behavior tree documents is published.

View Source
const BTSnapshotVersion = 1

BTSnapshotVersion is the BehaviorTreeSnapshot schema version written and read by SnapshotBehaviorTree and RestoreBehaviorTree.

View Source
const GOAPVersion = 1

GOAPVersion is the GOAP action-set YAML schema version this package reads and writes.

View Source
const UtilityVersion = 1

UtilityVersion is the utility AI YAML schema version this package reads and writes.

Variables

View Source
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")
)
View Source
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

func Alignment(a Agent, neighbors []Agent, radius float32) core.Point

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

func Arrive(a Agent, target core.Point, slowRadius float32) core.Point

Arrive returns a steering force toward target that smoothly scales desired speed down to zero inside slowRadius.

func Cohesion

func Cohesion(a Agent, neighbors []Agent, radius float32) core.Point

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

func Evade(a, pursuer Agent, panicRadius, maxLookAhead float32) core.Point

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

func Flee(a Agent, threat core.Point, panicRadius float32) core.Point

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 Hide

func Hide(a, pursuer Agent, obstacles []Obstacle, standoff, slowRadius float32) core.Point

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

func Interpose(a, targetA, targetB Agent, slowRadius float32) core.Point

Interpose steers a to intercept the predicted midpoint between two moving agents targetA and targetB, slowing smoothly inside slowRadius via Arrive.

func ObstacleAvoidance

func ObstacleAvoidance(a Agent, obstacles []Obstacle, maxAhead float32) core.Point

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

func Pursue(a, target Agent, maxLookAhead float32) core.Point

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 Seek

func Seek(a Agent, target core.Point) core.Point

Seek returns the steering force that accelerates a toward target at MaxSpeed.

func Separation

func Separation(a Agent, neighbors []Agent, desiredSep float32) core.Point

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 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

func WallAvoidance(a Agent, walls []Wall, feelerLength float32) core.Point

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 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"
)

func (AbortMode) Valid

func (m AbortMode) Valid() bool

Valid reports whether m is a recognized AbortMode (including empty, which means AbortNone).

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

func (*Agent) Step

func (a *Agent) Step(force core.Point, dt time.Duration)

Step integrates a by dt under steering acceleration force, clamping force to MaxForce and velocity to MaxSpeed when positive.

type Agent3D

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 pathfind3d.NavMesh paths.

func (*Agent3D) Step

func (a *Agent3D) Step(force Vec3, dt time.Duration)

Step integrates a by dt under steering acceleration force, clamping force to MaxForce and velocity to MaxSpeed when positive. When a.PlanarXZ is true, force.Y and Vel.Y are zeroed and a.Pos.Y is preserved.

type AngleMode

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.

const (
	// Hostile marks an enemy.
	Hostile Attitude = iota
	// Neutral marks something on no side.
	Neutral
	// Friendly marks an ally.
	Friendly
)

func DefaultAttitude

func DefaultAttitude(observer, other Team) Attitude

DefaultAttitude treats the same team as friendly, NoTeam on either side as neutral, and every other pair of teams as hostile.

func (Attitude) String

func (a Attitude) String() string

String returns the attitude's lower-case name.

type AttitudeFunc

type AttitudeFunc func(observer, other Team) Attitude

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 targets the parent (squad or team) blackboard instead of the agent's local blackboard when seeding Default.
	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

type BTParams map[string]any

BTParams holds resolved typed parameters passed to a leaf or service factory.

func (BTParams) Bool

func (p BTParams) Bool(name string) (bool, bool)

Bool returns the bool parameter name, or (false, false) if absent or not a bool.

func (BTParams) Duration

func (p BTParams) Duration(name string) (time.Duration, bool)

Duration parses a Go duration string parameter name, returning (0, false) if absent or invalid.

func (BTParams) Entity

func (p BTParams) Entity(name string) (uint64, bool)

Entity returns a non-negative integer parameter as a uint64 entity ID.

func (BTParams) Float

func (p BTParams) Float(name string) (float64, bool)

Float returns the numeric parameter name as float64, accepting int or float values.

func (BTParams) Int

func (p BTParams) Int(name string) (int, bool)

Int returns the integer parameter name, or (0, false) if absent or not an integer.

func (BTParams) Point

func (p BTParams) Point(name string) (core.Point, bool)

Point returns a 2-element numeric array parameter as a core.Point.

func (BTParams) String

func (p BTParams) String(name string) (string, bool)

String returns the string parameter name, or ("", false) if absent or not a string.

func (BTParams) Vec2

func (p BTParams) Vec2(name string) (math2d.Vec2, bool)

Vec2 returns a 2-element numeric array parameter as a math2d.Vec2.

func (BTParams) Vec3

func (p BTParams) Vec3(name string) (Vec3, bool)

Vec3 returns a 3-element numeric array parameter as an ai.Vec3.

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

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 BBBool

func BBBool(v bool) BlackboardValue

BBBool returns a BlackboardValue holding v.

func BBEntity

func BBEntity(id uint64) BlackboardValue

BBEntity returns a BlackboardValue holding entity identifier id.

func BBFloat

func BBFloat(v float64) BlackboardValue

BBFloat returns a BlackboardValue holding v.

func BBInt

func BBInt(v int) BlackboardValue

BBInt returns a BlackboardValue holding v.

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 BBVec3

func BBVec3(v Vec3) BlackboardValue

BBVec3 returns a BlackboardValue holding v.

func (BlackboardValue) Equal

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 CandidateGenerator

type CandidateGenerator interface {
	Generate(ctx TacticalContext, dst []TacticalCandidate) []TacticalCandidate
}

CandidateGenerator appends deterministic candidate positions to dst and returns the extended slice.

type ChildNodes

type ChildNodes interface {
	Node
	Children() []Node
}

ChildNodes is an optional interface that custom composite or decorator Node implementations may implement so SnapshotBehaviorTree and RestoreBehaviorTree traverse and preserve the state of their child nodes.

type 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 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); game/pkg/ai/cover3d generates 3D cover points on the XZ plane from a physics3d world.

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 pathfind.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

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

type CurveEvaluator interface {
	Eval(t float32) float32
}

CurveEvaluator evaluates a curve at a normalized input t in [0, 1].

*resource.Curve satisfies CurveEvaluator directly through its Eval(float32) float32 method, allowing stable package game/ai to use resource curves without importing experimental package game/resource.

type CurveFunc

type CurveFunc func(t float64) float64

CurveFunc adapts a Go function into a CurveEvaluator.

func (CurveFunc) Eval

func (f CurveFunc) Eval(t float32) float32

Eval calls f(float64(t)) and returns the result as float32, or 0 if f is nil.

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 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

func (e Effects) AddInt(f IntFact, delta int) Effects

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.

func (Effects) Empty

func (e Effects) Empty() bool

Empty reports whether e makes no changes to any fact.

func (Effects) SetBool

func (e Effects) SetBool(f BoolFact, v bool) Effects

SetBool returns a copy of e that sets boolean fact f to v.

func (Effects) SetInt

func (e Effects) SetInt(f IntFact, v int) Effects

SetInt returns a copy of e that sets integer fact f to v (clamped to int16 range).

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
)

func (EventKind) String

func (k EventKind) String() string

String returns the event kind's lower-case name.

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 NewFactSchema

func NewFactSchema() *FactSchema

NewFactSchema creates an empty FactSchema.

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

type FloatRange struct {
	Min    float64
	Max    float64
	HasMin bool
	HasMax bool
}

FloatRange represents an optional inclusive [Min, Max] filter interval for continuous tactical tests.

func AtLeast

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

type GOAPBoolFactDef struct {
	Fact  string `yaml:"fact"`
	Value bool   `yaml:"value"`
}

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 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 pathfind.Grid (blocked cells are solid walls).

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 pathfind.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 a pathfind.Grid's walkable cells.

func (*GridGenerator) Generate

Generate appends grid candidates in deterministic row-major order.

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 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 a pathfind.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 pathfind.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

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) (pathfind.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 pathfind.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 pathfind.Grid) (pathfind.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 pathfind.Cell, radius float32, q InfluenceQuery) (pathfind.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

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 pathfind.Cell, radius float32, q InfluenceQuery) (pathfind.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 pathfind.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 pathfind.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 pathfind.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

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 pathfind.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 pathfind.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 pathfind.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 pathfind.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 pathfind.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 LOSFunc

type LOSFunc func(from, to math2d.Vec2) bool

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

type LineOfSight func(from, to core.Point) bool

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 NavMeshGenerator struct {
	// Mesh is the 2D navigation mesh to sample.
	Mesh *pathfind.NavMesh
	// Center selects the origin for MaxRadius filtering (defaults to OriginQuerier).
	Center QueryOrigin
	// CustomCenter is used when Center is OriginCustom.
	CustomCenter math2d.Vec2
	// MaxRadius restricts samples to within MaxRadius of Center (<= 0 samples the whole mesh).
	MaxRadius float32
	// Spacing sets the world spacing between grid samples inside the mesh (<= 0 emits polygon centroids).
	Spacing float32
	// contains filtered or unexported fields
}

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.

Generate appends NavMesh sample candidates in deterministic order with zero heap allocations after warm-up.

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

func (g *NeighborGrid) QueryInto(dst []Agent, pos core.Point, radius float32) []Agent

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 Action

func Action(fn func(dt time.Duration) Status) Node

Action wraps fn as a leaf node.

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

func BuildBehaviorTreeFS(fsys fs.FS, name string, bind BTBindings) (Node, error)

BuildBehaviorTreeFS loads the behavior tree at name in fsys and builds its runtime Node.

func Condition

func Condition(fn func() bool) Node

Condition wraps predicate fn as a leaf node returning StatusSuccess when true and StatusFailure when false.

func Cooldown

func Cooldown(d time.Duration, child Node) Node

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

func Failer(child Node) Node

Failer turns both StatusSuccess and StatusFailure from child into StatusFailure while passing StatusRunning through.

func Guard

func Guard(cond func() bool, child Node) Node

Guard ticks child only while cond returns true; if cond becomes false while child is running, Guard resets child and returns StatusFailure.

func HasAttackToken

func HasAttackToken(pool *TokenPool, agentID uint64) Node

HasAttackToken returns a Condition behavior tree node that succeeds while agentID holds a token in pool.

func Inverter

func Inverter(child Node) Node

Inverter flips StatusSuccess and StatusFailure from child while passing StatusRunning through unchanged.

func Named

func Named(name string, child Node) Node

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

func RandomSelector(stream *random.Stream, children ...Node) Node

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

func RandomSequence(stream *random.Stream, children ...Node) Node

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

func Repeater(count int, child Node) Node

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

func Retry(n int, child Node) Node

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

func Selector(children ...Node) Node

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

func Sequence(children ...Node) Node

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

func Service(interval time.Duration, fn func(dt time.Duration), child Node) Node

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

func SquadHasOrder(squad *Squad, kind string) Node

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

func SquadHasRole(squad *Squad, agentID uint64, role string) Node

SquadHasRole returns a Condition behavior tree node that succeeds when agentID holds role in squad.

func SquadOrderAction

func SquadOrderAction(squad *Squad, fn func(order SquadOrder, dt time.Duration) Status) Node

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

func SquadStateBool(squad *Squad, key string) Node

SquadStateBool returns a Condition behavior tree node that succeeds when squad's shared state holds a true bool value under key.

func Succeeder

func Succeeder(child Node) Node

Succeeder turns both StatusSuccess and StatusFailure from child into StatusSuccess while passing StatusRunning through.

func TimeLimit

func TimeLimit(d time.Duration, child Node) Node

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

func UntilFail(child Node) Node

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

func Wait(d time.Duration) Node

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

func WithAttackToken(pool *TokenPool, agentID uint64, priority func() float64, child Node) Node

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 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

type ORCAObstacle3D struct {
	A, B  Vec3
	Layer uint32
}

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 Obstacle

type Obstacle struct {
	Center core.Point
	Radius float32
}

Obstacle is a circular 2D obstacle used by ObstacleAvoidance and Hide.

type Obstacle3D

type Obstacle3D struct {
	Center Vec3
	Radius float32
}

Obstacle3D is a spherical 3D obstacle (or vertical cylinder on XZ when the steering agent has PlanarXZ set) used by ObstacleAvoidance3D and Hide3D.

type ParallelPolicy

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       pathfind.Grid
	GridOrigin math2d.Vec2
	CellSize   float32
	AStar      *pathfind.AStar
	// NavMesh computes zero-allocation funnel-smoothed path length when PathCost and Grid are nil.
	NavMesh *pathfind.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, a pathfind.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

type PathFollowState struct {
	Index int
	Done  bool
}

PathFollowState tracks which waypoint an agent is currently heading toward.

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.

func (*PlanRunner) Tick

func (r *PlanRunner) Tick(dt time.Duration) Status

Tick advances the current plan by dt, replanning automatically on action failure, world-state invalidation, or higher-priority goal preemption.

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

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

func (r *PointReservations) ReservePos(agentID uint64, pos math2d.Vec2, timeout time.Duration) bool

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 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

func (r *Reasoner[C]) ActionCount() int

ActionCount returns the number of actions configured on r.

func (*Reasoner[C]) ActionIndex

func (r *Reasoner[C]) ActionIndex(name string) int

ActionIndex returns the index of the first action named name, or -1 if none matches.

func (*Reasoner[C]) ActionName

func (r *Reasoner[C]) ActionName(index int) string

ActionName returns the Name of action at index, or "" if index is out of bounds.

func (*Reasoner[C]) Choose

func (r *Reasoner[C]) Choose(ctx C, rng *random.Stream) (int, float64)

Choose scores all actions using r.Current() for momentum, selects the winning action, updates r.Current() to that action, and returns its index and score. Returns (-1, 0) if no action has a positive score.

func (*Reasoner[C]) ChooseWithCurrent

func (r *Reasoner[C]) ChooseWithCurrent(ctx C, current int, rng *random.Stream) (int, float64)

ChooseWithCurrent scores all actions using current as the active action index for momentum, without modifying r.Current(). This lets one shared Reasoner score many agents without per-agent copies or heap allocations. Returns (-1, 0) if no action has a positive score.

func (*Reasoner[C]) Current

func (r *Reasoner[C]) Current() int

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

func (r *Reasoner[C]) ScoreAction(index int, ctx C, isCurrent bool) float64

ScoreAction scores the action at index for ctx, applying momentum when isCurrent is true. Out-of-range indices return 0.

func (*Reasoner[C]) ScoreAll

func (r *Reasoner[C]) ScoreAll(ctx C, current int, dst []float64) []float64

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

func (r *Reasoner[C]) SetCurrent(index int)

SetCurrent sets the currently active action index tracked by Choose. Out-of-range values clear the active action to -1.

type Reservation

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

Generate appends concentric ring candidates in deterministic ring-major, angle-minor order.

type Sense

type Sense uint8

Sense names the sense that last refreshed a memory.

const (
	// SenseSight is a stimulus seen inside a sight cone with a clear line of sight.
	SenseSight Sense = iota + 1
	// SenseHearing is a noise heard within hearing range.
	SenseHearing
)

func (Sense) String

func (s Sense) String() string

String returns the sense's lower-case 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 NewSquad

func NewSquad(id uint64, members ...uint64) *Squad

NewSquad returns a Squad with identifier id and optional initial member IDs.

func (*Squad) AddMember

func (s *Squad) AddMember(agentID uint64) bool

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) HasMember

func (s *Squad) HasMember(agentID uint64) bool

HasMember reports whether agentID belongs to the squad.

func (*Squad) HasRole

func (s *Squad) HasRole(agentID uint64, role string) bool

HasRole reports whether agentID is a member currently assigned role.

func (*Squad) ID

func (s *Squad) ID() uint64

ID returns the squad's identifier.

func (*Squad) MemberCount

func (s *Squad) MemberCount() int

MemberCount returns the number of members in the squad.

func (*Squad) Members

func (s *Squad) Members(dst []uint64) []uint64

Members appends all member IDs to dst[:0] in deterministic ascending order.

func (*Squad) MembersWithRole

func (s *Squad) MembersWithRole(dst []uint64, role string) []uint64

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

func (s *Squad) RemoveMember(agentID uint64) bool

RemoveMember removes agentID from the squad roster and clears its assigned role. It reports whether agentID was a member.

func (*Squad) Role

func (s *Squad) Role(agentID uint64) string

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

func (s *Squad) SetRole(agentID uint64, role string) bool

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) Clear

func (s *SquadState) Clear()

Clear removes all entries from s.

func (*SquadState) Delete

func (s *SquadState) Delete(key string)

Delete removes key from s.

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) Len

func (s *SquadState) Len() int

Len returns the number of keys stored in s.

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.

func (*SquadState) String

func (s *SquadState) String(key string) (string, bool)

String retrieves a string value stored under key.

type Status

type Status uint8

Status is the outcome of one Tick of a behavior tree Node.

const (
	// StatusSuccess reports that a node completed its work successfully.
	StatusSuccess Status = iota
	// StatusFailure reports that a node failed or its condition did not hold.
	StatusFailure
	// StatusRunning reports that a node needs more ticks to finish.
	StatusRunning
)

func (Status) MarshalText

func (s Status) MarshalText() ([]byte, error)

MarshalText encodes s as its lowercase name ("success", "failure", or "running") so snapshots read clearly in YAML and JSON.

func (Status) String

func (s Status) String() string

String returns a human-readable name for s.

func (*Status) UnmarshalText

func (s *Status) UnmarshalText(text []byte) error

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

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

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

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 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) Reset

func (m *TokenManager) Reset()

Reset removes all target pools from m.

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

func (p *TokenPool) Available() int

Available returns the number of tokens immediately free to grant on the next Step.

func (*TokenPool) Cancel

func (p *TokenPool) Cancel(agentID uint64) bool

Cancel withdraws a pending request for agentID without releasing a held token. It reports whether a pending request existed.

func (*TokenPool) Capacity

func (p *TokenPool) Capacity() int

Capacity returns the maximum number of tokens in the pool.

func (*TokenPool) Config

func (p *TokenPool) Config() TokenPoolConfig

Config returns the pool's effective configuration.

func (*TokenPool) CoolingDown

func (p *TokenPool) CoolingDown() int

CoolingDown returns the number of returned tokens currently waiting on cooldown.

func (*TokenPool) HasToken

func (p *TokenPool) HasToken(agentID uint64) bool

HasToken reports whether agentID currently holds an attack token from p.

func (*TokenPool) HeldCount

func (p *TokenPool) HeldCount() int

HeldCount returns the number of tokens currently held by agents.

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

func (p *TokenPool) PendingCount() int

PendingCount returns the number of waiting token requests.

func (*TokenPool) Release

func (p *TokenPool) Release(agentID uint64) bool

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

func (p *TokenPool) Remove(agentID uint64) bool

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

func (p *TokenPool) Request(agentID uint64, priority float64)

Request submits or updates an attack token request for agentID at priority.

If agentID already holds a token, Request refreshes its priority for future preemption comparisons without consuming a second token. Requests with a NaN priority are ignored. Pending requests persist until granted, cancelled via Cancel or Remove, or cleared by Reset.

func (*TokenPool) Reset

func (p *TokenPool) Reset()

Reset clears all active holders, pending requests, and cooldown timers, restoring Available() to Capacity().

func (*TokenPool) Step

func (p *TokenPool) Step(dt time.Duration)

Step advances cooldown and hold timers by dt and deterministically resolves pending requests.

Within a step:

  1. Cooling-down tokens advance; any token whose remaining cooldown reaches <= 0 becomes available.
  2. 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).
  3. Pending requests are sorted by descending priority, breaking ties by ascending AgentID.
  4. 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 Vec3

type Vec3 = pathfind.Vec3

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.

It is an alias of pathfind.Vec3 so the 3D steering API keeps its ai.Vec3 name while ai and pathfind, both stable, share one vector type without importing the experimental game/math3d package.

func Alignment3D

func Alignment3D(a Agent3D, neighbors []Agent3D, radius float32) Vec3

Alignment3D steers a toward the average heading of neighbors within radius (or all non-coincident neighbors when radius <= 0).

func Arrive3D

func Arrive3D(a Agent3D, target Vec3, slowRadius float32) Vec3

Arrive3D returns a steering force toward target that smoothly scales desired speed down to zero inside slowRadius.

func Cohesion3D

func Cohesion3D(a Agent3D, neighbors []Agent3D, radius float32) Vec3

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

func Evade3D(a, pursuer Agent3D, panicRadius, maxLookAhead float32) Vec3

Evade3D returns a steering force that flees from the predicted position of pursuer while closer than panicRadius (or always when panicRadius <= 0).

func Flee3D

func Flee3D(a Agent3D, threat Vec3, panicRadius float32) Vec3

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 pathfind3d.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

func Interpose3D(a, targetA, targetB Agent3D, slowRadius float32) Vec3

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

func OffsetPursuit3D(a, leader Agent3D, localOffset Vec3, slowRadius, maxLookAhead float32) Vec3

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

func Pursue3D(a, target Agent3D, maxLookAhead float32) Vec3

Pursue3D returns a steering force that intercepts target by predicting its future position from target.Vel, capped to maxLookAhead seconds when positive.

func Seek3D

func Seek3D(a Agent3D, target Vec3) Vec3

Seek3D returns the 3D (or XZ-planar) steering force accelerating a toward target at MaxSpeed.

func Separation3D

func Separation3D(a Agent3D, neighbors []Agent3D, desiredSep float32) Vec3

Separation3D pushes a away from neighbors closer than desiredSep (defaulting to a.Radius + neighbor.Radius when desiredSep <= 0).

func WallAvoidance3D

func WallAvoidance3D(a Agent3D, walls []Wall3D, feelerLength float32) Vec3

WallAvoidance3D steers a away from vertical XZ wall segments using three horizontal feeler whiskers and direct radius clearance containment.

type Wall

type Wall struct {
	A, B core.Point
}

Wall is a 2D line segment from A to B used by WallAvoidance.

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 WeightedForce

type WeightedForce struct {
	Force  core.Point
	Weight float32
}

WeightedForce pairs a steering force with a scalar weight for Combine.

type WeightedForce3D

type WeightedForce3D struct {
	Force  Vec3
	Weight float32
}

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

type WeightedNode struct {
	Node   Node
	Weight float64
}

WeightedNode pairs a behavior tree child Node with a relative selection weight for WeightedSelector.

Options with Weight <= 0, NaN, Inf, or a nil Node are never selected.

type WorldState

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).

Directories

Path Synopsis
Package cover3d generates ai.CoverPoint values from the colliders of a physics3d world, projecting the vertical faces of 3D obstacles onto the XZ ground plane.
Package cover3d generates ai.CoverPoint values from the colliders of a physics3d world, projecting the vertical faces of 3D obstacles onto the XZ ground plane.
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 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.

Jump to

Keyboard shortcuts

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