GitHub快速開始

API 參考取自原始碼中的 Go 文件註解,以英文撰寫。

package pathfind3d

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

概覽

Package pathfind3d provides deterministic 3D navigation for NSGo 3D games: navigation meshes of walkable 3D polygons with slope filtering, polygon areas/flags/filters, off-mesh links, a BVH spatial index, reusable zero-allocation queries (NavMeshQuery) and incremental searches, path-corridor navigation agents and agent groups, and tiled navigation meshes with dynamic obstacles that stream in and out with world3d's chunks (NavTileStreamer).

It shares NavArea, NavFlags and NavFilter with package pathfind, its 2D counterpart, and package navbake3d bakes its meshes from level geometry. All positions follow package math3d's right-handed Y-up conventions (+X right, +Y up, -Z forward).

索引

常數

const (
	NavAreaDefault  = pathfind.NavAreaDefault
	NavAreaRoad     = pathfind.NavAreaRoad
	NavAreaGrass    = pathfind.NavAreaGrass
	NavAreaMud      = pathfind.NavAreaMud
	NavAreaWater    = pathfind.NavAreaWater
	NavAreaDoor     = pathfind.NavAreaDoor
	NavAreaHazard   = pathfind.NavAreaHazard
	NavAreaJump     = pathfind.NavAreaJump
	NavAreaClimb    = pathfind.NavAreaClimb
	NavAreaTeleport = pathfind.NavAreaTeleport
)
const (
	NavFlagWalk     = pathfind.NavFlagWalk
	NavFlagSwim     = pathfind.NavFlagSwim
	NavFlagDoor     = pathfind.NavFlagDoor
	NavFlagJump     = pathfind.NavFlagJump
	NavFlagClimb    = pathfind.NavFlagClimb
	NavFlagTeleport = pathfind.NavFlagTeleport
	NavFlagDisabled = pathfind.NavFlagDisabled
	NavFlagAll      = pathfind.NavFlagAll
)
const (
	NavTileAdded   = pathfind.NavTileAdded
	NavTileUpdated = pathfind.NavTileUpdated
	NavTileRemoved = pathfind.NavTileRemoved
)
const (
	NavObstacleCarve = pathfind.NavObstacleCarve
	NavObstacleMark  = pathfind.NavObstacleMark
)
const NavLinkOffMesh uint32 = 1 << 0

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

型別

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

NavAgent navigates a 3D NavMesh by maintaining an active polygon corridor, steering smoothly along XZ toward the next funnel corner while tracking exact 3D surface height across sloped ramps and multi-level bridges, repairing its corridor locally when pushed or when the target shifts, and invoking callbacks for off-mesh or flagged links.

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

func NewNavAgent(mesh *NavMesh, pos math3d.Vec3, cfg NavAgentConfig) *NavAgent

NewNavAgent constructs a 3D navigation agent placed at pos on mesh. If pos lies over a walkable polygon within VerticalTolerance, its Y coordinate is snapped to the surface.

func (a *NavAgent) ClearTarget()

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

func (a *NavAgent) Config() NavAgentConfig

Config returns the sanitized configuration of the agent.

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

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

func (a *NavAgent) ForceReplan() bool

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

func (a *NavAgent) HasTarget() bool

HasTarget reports whether the agent currently has a target.

func (a *NavAgent) LocalRepairCount() int

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

func (a *NavAgent) NeedsReplan() bool

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

func (a *NavAgent) NextCorner() (math3d.Vec3, bool)

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

func (a *NavAgent) Path() []math3d.Vec3

Path returns the full 3D smoothed waypoint path (including slope/ramp transitions) from the agent's current position to its target along its active corridor, or nil when no valid corridor exists.

func (a *NavAgent) Pos() math3d.Vec3

Pos returns the agent's current 3D position.

func (a *NavAgent) ReplanCount() int

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

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

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

func (a *NavAgent) SetPosition(pos math3d.Vec3)

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

func (a *NavAgent) SetTarget(target math3d.Vec3)

SetTarget sets or updates the agent's 3D destination.

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

func (a *NavAgent) SetVelocity(v math3d.Vec3)

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

func (a *NavAgent) State() NavAgentState

State returns the agent's current navigation state.

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

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

func (a *NavAgent) Target() math3d.Vec3

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

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

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

func (a *NavAgent) Vel() math3d.Vec3

Vel returns the agent's current 3D velocity.

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

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

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

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

func NewNavAgentGroup(cfg NavAgentGroupConfig) *NavAgentGroup

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

func (g *NavAgentGroup) Add(mesh *NavMesh, pos math3d.Vec3, cfg NavAgentConfig) *NavAgent

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

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

AddAgent attaches an existing 3D NavAgent to the group.

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

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

func (g *NavAgentGroup) LastStepReplans() int

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

func (g *NavAgentGroup) Len() int

Len returns the number of agents in the group.

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

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

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

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

func (g *NavAgentGroup) Steps() uint64

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

func (g *NavAgentGroup) TotalReplans() int

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

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

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

type NavAgentState uint8

NavAgentState reports the navigation status of a 3D NavAgent.

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

String returns a human-readable state name.

type NavArea = pathfind.NavArea

NavArea identifies the surface or terrain category of a 3D navigation polygon. It aliases pathfind.NavArea so the same area IDs and NavFilters work seamlessly across 2D and 3D meshes.

type NavFilter = pathfind.NavFilter

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

func DefaultNavFilter() NavFilter

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

type NavFlags = pathfind.NavFlags

NavFlags is a bitmask of runtime traversal capabilities and states on a 3D navigation polygon. It aliases pathfind.NavFlags so the same flags and NavFilters work seamlessly across 2D and 3D meshes.

type NavLink struct {
	Neighbor int
	Left     math3d.Vec3
	Right    math3d.Vec3
	Flags    uint32

	LinkID  int
	OffMesh bool
	End     math3d.Vec3
	Cost    float32
	// contains filtered or unexported fields
}

NavLink describes a traversable 3D portal edge (or off-mesh link) from one NavPoly to another NavPoly. For shared-edge portals, Left and Right are ordered as seen when looking from the source polygon outward across the shared edge into Neighbor. For off-mesh links (OffMesh == true), Left and Right hold the entry point and End holds the exit point.

type NavLinkEvent struct {
	FromPoly int
	ToPoly   int
	Start    math3d.Vec3
	End      math3d.Vec3
	Radius   float32
	Area     NavArea
	Flags    uint32
	LinkID   int
	UserData any
	OffMesh  bool
}

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

type NavListenerID uint64

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

type NavMesh struct {
	Polys             []NavPoly
	VerticalTolerance float32
	// contains filtered or unexported fields
}

NavMesh is a 3D navigation mesh built from convex polygons. It supports sloped ramps, obstacles, and vertically stacked walkable levels (bridges, overpasses, multi-story floors) linked strictly along shared 3D edges.

func BuildNavMesh(polys [][]math3d.Vec3, maxSlopeRad float32) *NavMesh

BuildNavMesh constructs a NavMesh from convex 3D polygons, filtering out degenerate polygons and slopes steeper than maxSlopeRad radians from horizontal (upward normal angle from +Y). Adjacent walkable polygons are linked automatically along shared 3D edges (including collinear T-junction overlaps) so vertically separated levels never falsely connect.

Each polygon is assigned NavAreaDefault and NavFlagWalk. If maxSlopeRad < 0, a default limit of 45 degrees (pi/4) is used.

func BuildNavMeshWithAreas(polys []NavPolygonInput, maxSlopeRad float32) *NavMesh

BuildNavMeshWithAreas constructs a NavMesh from convex 3D polygons carrying per-polygon area IDs and runtime traversal flags, filtering out degenerate polygons and slopes steeper than maxSlopeRad radians from horizontal.

Polygons with zero Flags default to NavFlagWalk. If maxSlopeRad < 0, a default limit of 45 degrees (pi/4) is used.

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

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

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

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

func (nm *NavMesh) BumpRevision()

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

func (nm *NavMesh) ClearOffMeshLinks()

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

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

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

func (nm *NavMesh) Contains(p math3d.Vec3) bool

Contains reports whether p lies on any polygon in the mesh within VerticalTolerance.

func (nm *NavMesh) ContainsWithFilter(p math3d.Vec3, filter NavFilter) bool

ContainsWithFilter reports whether p lies on any polygon passing filter within VerticalTolerance.

func (nm *NavMesh) FindCorridor(start, goal math3d.Vec3) ([]int, bool)

FindCorridor computes the sequence of walkable polygon indices from start to goal under DefaultNavFilter. Returns (nil, false) if either endpoint is off the traversable NavMesh or no connected corridor exists.

func (nm *NavMesh) FindCorridorInto(dst []int, start, goal math3d.Vec3) ([]int, bool)

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

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

func (nm *NavMesh) FindCorridorWithFilter(start, goal math3d.Vec3, filter NavFilter) ([]int, bool)

FindCorridorWithFilter computes the minimum-cost sequence of walkable polygon indices from start to goal under filter. Returns (nil, false) if either endpoint is off the traversable NavMesh or no connected corridor exists.

func (nm *NavMesh) FindCorridorWithFilterInto(dst []int, start, goal math3d.Vec3, filter NavFilter) ([]int, bool)

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

func (nm *NavMesh) FindPath(start, goal math3d.Vec3) ([]math3d.Vec3, bool)

FindPath computes a shortest 3D path from start to goal across the NavMesh using DefaultNavFilter, 3D portal-graph A*, and XZ-projected funnel smoothing with exact 3D height interpolation across sloped ramps and multi-level bridges.

Returns (nil, false) if either endpoint is off the traversable NavMesh or no connected corridor exists between them.

func (nm *NavMesh) FindPathInto(dst []math3d.Vec3, start, goal math3d.Vec3) ([]math3d.Vec3, bool)

FindPathInto behaves like FindPath but writes waypoints into dst[:0] and reuses the mesh's internal search buffers so repeated calls perform zero heap allocations after warm-up.

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

func (nm *NavMesh) FindPathWithFilter(start, goal math3d.Vec3, filter NavFilter) ([]math3d.Vec3, bool)

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

Returns (nil, false) if either endpoint is off the traversable NavMesh or no connected corridor exists between them.

func (nm *NavMesh) FindPathWithFilterAndOptions(start, goal math3d.Vec3, filter NavFilter, opts pathfind.PathOptions) NavPathResult

FindPathWithFilterAndOptions computes a minimum-cost 3D path from start to goal restricted to polygons allowed by filter under opts, supporting an expansion budget and optional partial paths.

func (nm *NavMesh) FindPathWithFilterAndOptionsInto(dst []math3d.Vec3, start, goal math3d.Vec3, filter NavFilter, opts pathfind.PathOptions) NavPathResult

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

func (nm *NavMesh) FindPathWithFilterInto(dst []math3d.Vec3, start, goal math3d.Vec3, filter NavFilter) ([]math3d.Vec3, bool)

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

func (nm *NavMesh) FindPathWithOptions(start, goal math3d.Vec3, opts pathfind.PathOptions) NavPathResult

FindPathWithOptions computes a 3D path from start to goal under DefaultNavFilter and opts, supporting an expansion budget and optional partial paths ending at the closest reachable 3D point on the NavMesh when goal is off-mesh, disconnected, or beyond MaxExpansions.

func (nm *NavMesh) FindPolygon(p math3d.Vec3) (int, bool)

FindPolygon returns the index of the walkable polygon containing (p.X, p.Z) whose 3D surface height is closest to p.Y within VerticalTolerance.

Stacked levels (such as a bridge above a ground floor) remain cleanly separated because the polygon minimizing |p.Y - poly.HeightAt(p.X, p.Z)| is chosen. Returns (-1, false) if no polygon matches.

func (nm *NavMesh) FindPolygonWithFilter(p math3d.Vec3, filter NavFilter) (int, bool)

FindPolygonWithFilter returns the index of the polygon passing filter that contains (p.X, p.Z) and whose 3D surface height is closest to p.Y within VerticalTolerance. Returns (-1, false) if no matching polygon is found.

func (nm *NavMesh) MoveAlongSurface(start, target math3d.Vec3) (NavMoveResult, bool)

MoveAlongSurface slides an agent from start toward target while staying on 3D polygons allowed by DefaultNavFilter. Vertically stacked levels stay cleanly separated because only shared 3D polygon edges are traversed.

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

func (nm *NavMesh) MoveAlongSurfaceWithFilter(start, target math3d.Vec3, filter NavFilter) (NavMoveResult, bool)

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

func (nm *NavMesh) NearestPoint(p, extent math3d.Vec3) (point math3d.Vec3, poly int, ok bool)

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

Because the search bounds are 3D, stacked floors and bridges outside [p.Y-extent.Y, p.Y+extent.Y] are cleanly excluded. Returns (zero, -1, false) if nm is empty, inputs are invalid/negative, or no allowed polygon point lies within extent.

func (nm *NavMesh) NearestPointWithFilter(p, extent math3d.Vec3, filter NavFilter) (point math3d.Vec3, poly int, ok bool)

NearestPointWithFilter behaves like NearestPoint while restricting matches to polygons allowed by filter.

func (nm *NavMesh) NearestPolygon(p math3d.Vec3) (index int, point math3d.Vec3, ok bool)

NearestPolygon returns the polygon closest to p in 3D and the closest point on or inside that polygon.

func (nm *NavMesh) NearestPolygonWithFilter(p math3d.Vec3, filter NavFilter) (index int, point math3d.Vec3, ok bool)

NearestPolygonWithFilter returns the polygon passing filter closest to p in 3D and the closest point on or inside that polygon.

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

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

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

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

func (nm *NavMesh) PolygonCount() int

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

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

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

func (nm *NavMesh) RandomPoint(rng *random.Stream) (point math3d.Vec3, poly int, ok bool)

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

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

func (nm *NavMesh) RandomPointAround(center math3d.Vec3, radius float32, rng *random.Stream) (point math3d.Vec3, poly int, ok bool)

RandomPointAround picks a 3D surface-area-weighted uniformly random point within 3D Euclidean distance radius of center (snapped onto center's walkable polygon) on polygons allowed by DefaultNavFilter that are reachable from center's polygon. Disconnected islands and unreachable stacked floors are never returned, and results are bit-identical across runs and platforms for the same seed.

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

func (nm *NavMesh) RandomPointAroundWithFilter(center math3d.Vec3, radius float32, rng *random.Stream, filter NavFilter) (point math3d.Vec3, poly int, ok bool)

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

func (nm *NavMesh) RandomPointWithFilter(rng *random.Stream, filter NavFilter) (point math3d.Vec3, poly int, ok bool)

RandomPointWithFilter behaves like RandomPoint while restricting sampling to polygons allowed by filter.

func (nm *NavMesh) Raycast(start, target math3d.Vec3) (NavRaycastHit, bool)

Raycast casts a segment along the 3D mesh surface from start toward target using DefaultNavFilter, walking shared 3D polygon edges across allowed polygons until reaching target or hitting a boundary edge or disallowed polygon. Vertically stacked levels never falsely connect because only shared 3D edges are crossed.

The second return value equals hit.Hit: false means unobstructed traversal to target (hit.T == 1, hit.Poly >= 0); true means the segment was obstructed (or start lies outside the allowed mesh, with hit.Poly == -1 and hit.T == 0).

func (nm *NavMesh) RaycastWithFilter(start, target math3d.Vec3, filter NavFilter) (NavRaycastHit, bool)

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

func (nm *NavMesh) Revision() uint64

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

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

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

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

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

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

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

func (nm *NavMesh) StartSearch(start, goal math3d.Vec3, opts pathfind.PathOptions) *NavMeshSearch

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

func (nm *NavMesh) StartSearchWithFilter(start, goal math3d.Vec3, filter NavFilter, opts pathfind.PathOptions) *NavMeshSearch

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

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

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

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

func NewNavMeshQuery(mesh *NavMesh) *NavMeshQuery

NewNavMeshQuery creates a reusable 3D query instance bound to mesh.

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

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

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

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

func (q *NavMeshQuery) FindPathInto(dst []math3d.Vec3, start, goal math3d.Vec3) ([]math3d.Vec3, bool)

FindPathInto finds the shortest 3D path from start to goal under DefaultNavFilter, writing waypoints into dst[:0] and reusing q's internal buffers so repeated calls perform zero heap allocations after warm-up.

func (q *NavMeshQuery) FindPathWithFilterAndOptionsInto(dst []math3d.Vec3, start, goal math3d.Vec3, filter NavFilter, opts pathfind.PathOptions) NavPathResult

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

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

FindPathWithFilterInto finds the minimum-cost 3D path from start to goal restricted to filter, writing waypoints into dst[:0] with zero heap allocations after warm-up.

func (q *NavMeshQuery) Mesh() *NavMesh

Mesh returns the NavMesh currently bound to q.

func (q *NavMeshQuery) MoveAlongSurface(start, target math3d.Vec3) (NavMoveResult, bool)

MoveAlongSurface delegates to q's NavMesh.MoveAlongSurface.

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

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

func (q *NavMeshQuery) MoveAlongSurfaceWithFilter(start, target math3d.Vec3, filter NavFilter) (NavMoveResult, bool)

MoveAlongSurfaceWithFilter delegates to q's NavMesh.MoveAlongSurfaceWithFilter.

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

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

func (q *NavMeshQuery) NearestPoint(p, extent math3d.Vec3) (math3d.Vec3, int, bool)

NearestPoint delegates to q's NavMesh.NearestPoint.

func (q *NavMeshQuery) NearestPointWithFilter(p, extent math3d.Vec3, filter NavFilter) (math3d.Vec3, int, bool)

NearestPointWithFilter delegates to q's NavMesh.NearestPointWithFilter.

func (q *NavMeshQuery) RandomPoint(rng *random.Stream) (math3d.Vec3, int, bool)

RandomPoint delegates to q's NavMesh.RandomPoint.

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

RandomPointAround picks a random reachable 3D point within radius of center using q's reusable buffers.

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

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

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

RandomPointWithFilter delegates to q's NavMesh.RandomPointWithFilter.

func (q *NavMeshQuery) Raycast(start, target math3d.Vec3) (NavRaycastHit, bool)

Raycast delegates to q's NavMesh.Raycast.

func (q *NavMeshQuery) RaycastWithFilter(start, target math3d.Vec3, filter NavFilter) (NavRaycastHit, bool)

RaycastWithFilter delegates to q's NavMesh.RaycastWithFilter.

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

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

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

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

Stepping a search with any positive per-step expansion budget produces the exact same path, links, partial flag, and expansion count as NavMesh.FindPathWithOptions / FindPathWithFilterAndOptions. *NavMeshSearch implements pathfind.IncrementalSearch so it can be scheduled directly on pathfind.PathQueue.

func NewNavMeshSearch(nm *NavMesh, start, goal math3d.Vec3, opts pathfind.PathOptions) *NavMeshSearch

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

func NewNavMeshSearchWithFilter(nm *NavMesh, start, goal math3d.Vec3, filter NavFilter, opts pathfind.PathOptions) *NavMeshSearch

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

func (s *NavMeshSearch) Expansions() int

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

func (s *NavMeshSearch) Result() NavPathResult

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

func (s *NavMeshSearch) Status() pathfind.SearchStatus

Status returns the search's current status.

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

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

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

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

type NavObstacle struct {
	Kind        NavObstacleKind
	Mode        NavObstacleMode
	Center      math3d.Vec3   // Box and Cylinder center
	HalfExtents math3d.Vec3   // Box half-extents along X, Y, Z (each > 0)
	Yaw         float32       // Optional Box rotation around +Y in radians
	Radius      float32       // Cylinder radius (> 0)
	Height      float32       // Cylinder total height along Y (0 = unbounded vertically)
	Segments    int           // Cylinder approximation segments (default 12, clamped to [6, 64])
	Vertices    []math3d.Vec3 // Polygon footprint vertices in XZ (at least 3; convex or concave)
	MinY        float32       // Polygon vertical minimum (MinY == MaxY means unbounded vertically)
	MaxY        float32       // Polygon vertical maximum
	Margin      float32       // Optional horizontal outward inflation in world units (>= 0)
	Area        NavArea       // Applied in NavObstacleMark mode when non-zero
	Flags       NavFlags      // Applied in NavObstacleMark mode (defaults to NavFlagDisabled when both Area and Flags are 0)
}

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

func NavBoxObstacle(minPt, maxPt math3d.Vec3) NavObstacle

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

func NavCylinderObstacle(center math3d.Vec3, radius, height float32) NavObstacle

NavCylinderObstacle constructs a vertical 3D cylinder obstacle centered at center with radius and total height. Passing height == 0 makes the cylinder affect all vertical levels.

func NavOrientedBoxObstacle(center, halfExtents math3d.Vec3, yawRad float32) NavObstacle

NavOrientedBoxObstacle constructs a yaw-rotated 3D box obstacle centered at center with halfExtents.

func NavPolygonObstacle(verts []math3d.Vec3, minY, maxY float32) NavObstacle

NavPolygonObstacle constructs a vertically extruded 3D polygon obstacle (convex or concave in XZ) spanning [minY, maxY]. Passing minY == maxY makes it affect all vertical levels.

type NavObstacleID uint64

NavObstacleID identifies a dynamic obstacle registered on a 3D TiledNavMesh.

type NavObstacleKind uint8

NavObstacleKind selects the geometric shape of a 3D NavObstacle.

const (
	// NavObstacleBox is an axis-aligned or yaw-rotated 3D box (Center, HalfExtents, Yaw).
	NavObstacleBox NavObstacleKind = iota
	// NavObstacleCylinder is a vertical 3D cylinder (Center, Radius, Height, Segments).
	// When Height == 0, the cylinder affects all vertical levels.
	NavObstacleCylinder
	// NavObstaclePolygon is a vertically extruded 3D polygon prism (Vertices in XZ, MinY, MaxY).
	// When MinY == MaxY, the polygon affects all vertical levels.
	NavObstaclePolygon
)
type NavObstacleMode = pathfind.NavObstacleMode

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

type NavOffMeshLink struct {
	// Start and End are the 3D endpoints on (or within Radius of) the mesh.
	Start math3d.Vec3
	End   math3d.Vec3
	// Radius is the optional endpoint snap and agent entry tolerance in world units.
	// When positive, an endpoint outside a polygon snaps to the nearest polygon point within Radius,
	// and NavAgent uses max(entryRadius, Radius) when entering the link.
	// When zero, endpoints must lie on a walkable polygon within VerticalTolerance.
	Radius float32
	// Bidirectional adds links in both Start->End and End->Start directions when true.
	Bidirectional bool
	// Flags stores game-defined link flags; NavLinkOffMesh is always set automatically.
	Flags uint32
	// ID is an optional game-defined link identifier delivered in NavLinkEvent.LinkID and NavPathLink.LinkID.
	ID int
	// Cost overrides the A* traversal cost when positive; <= 0 uses 3D Euclidean distance.
	Cost float32
	// Area assigns a NavArea to the link so NavFilter can exclude it or scale its traversal cost.
	// Defaults to NavAreaDefault (0).
	Area NavArea
	// UserData holds optional game-defined metadata (such as "jump", "ladder", "teleport", or a custom value)
	// carried through to NavPathLink and NavLinkEvent.
	UserData any
}

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

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

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

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

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

func (r NavPathResult) HasLinks() bool

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

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

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

type NavPathWatchID uint64

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

type NavPoly struct {
	Vertices []math3d.Vec3
	Normal   math3d.Vec3
	PlaneD   float32
	Center   math3d.Vec3
	Bounds   math3d.AABB
	Links    []NavLink
	Area     NavArea
	Flags    NavFlags
}

NavPoly is a single walkable convex 3D polygon in a NavMesh. Vertices are normalized to counter-clockwise winding when viewed from +Y so Normal always points upward (Normal.Y > 0).

func (p *NavPoly) ContainsXZ(x, z float32) bool

ContainsXZ reports whether (x, z) lies inside or on the boundary of p's XZ projection.

func (p *NavPoly) HeightAt(x, z float32) float32

HeightAt returns the Y coordinate of the polygon's supporting 3D plane at (x, z).

type NavPolyRef struct {
	Tile world3d.ChunkCoord
	Poly int32
	Salt uint32
}

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

func (r NavPolyRef) Valid() bool

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

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

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

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

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

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

NavTile is an independently baked 3D navigation tile covering a fixed XZ square region [minX, maxX] x [minZ, maxZ]. A NavTile may be baked concurrently on worker goroutines with BakeNavTile and installed into a TiledNavMesh with AddTile, ReplaceTile, or SetTile.

func BakeNavTile(coord world3d.ChunkCoord, tileSize float32, origin math3d.Vec3, polys []NavPolygonInput, maxSlopeRad float32) *NavTile

BakeNavTile bakes an independent 3D NavTile for coord from convex walkable 3D polygons, filtering slopes steeper than maxSlopeRad (default pi/4 when < 0) and clipping every polygon cleanly to the tile's exact XZ bounds while preserving exact 3D plane heights. BakeNavTile is pure and safe to call concurrently from world3d.ChunkStreamer worker goroutines.

func (t *NavTile) BasePolygonCount() int

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

func (t *NavTile) Bounds() math3d.AABB

BoundsXZ returns the world-space XZ bounds of this tile (with Y spanning the tile's polygons, or 0 if empty).

func (t *NavTile) Coord() world3d.ChunkCoord

Coord returns the chunk/tile coordinate this tile was baked for.

type NavTileChange struct {
	Coord   world3d.ChunkCoord
	Kind    NavTileChangeKind
	Version uint64
}

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

type NavTileChangeKind = pathfind.NavTileChangeKind

NavTileChangeKind classifies why a tile in a 3D TiledNavMesh changed.

type NavTileCoord = world3d.ChunkCoord

NavTileCoord identifies a fixed-size tile in a 3D TiledNavMesh. It aliases world3d.ChunkCoord so 3D navmesh tiles align 1:1 with world3d.ChunkStreamer chunks.

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

NavTileStreamer bridges world3d.ChunkStreamer[*NavTile] onto a 3D TiledNavMesh: chunks entering LoadRadius are baked (optionally on background workers) and installed into Mesh with active dynamic obstacles applied and cross-border portals linked; chunks leaving UnloadRadius are removed from Mesh, unlinking neighbor portals and invalidating paths that crossed them.

func NewNavTileStreamer(cfg NavTileStreamerConfig) (*NavTileStreamer, error)

NewNavTileStreamer constructs a NavTileStreamer backed by a world3d.ChunkStreamer[*NavTile] whose ChunkSize matches cfg.Mesh.TileSize(). Call Close when finished to stop worker goroutines and unload remaining tiles.

func (s *NavTileStreamer) Close()

Close cancels in-flight bakes, waits for worker goroutines to exit, and unloads all remaining tiles.

func (s *NavTileStreamer) LoadedTiles() []world3d.ChunkCoord

LoadedTiles returns a sorted slice of chunk coordinates currently tracked as loaded.

func (s *NavTileStreamer) Streamer() *world3d.ChunkStreamer[*NavTile]

Streamer returns the underlying world3d.ChunkStreamer[*NavTile].

func (s *NavTileStreamer) Update(worldPos world3d.WorldPos64)

Update advances chunk streaming around worldPos (offset by Mesh.Origin() when non-zero), installing completed tiles up to MaxIntegrationsPerFrame and unloading distant tiles.

type NavTileStreamerConfig struct {
	// Mesh is the target TiledNavMesh whose tiles are added on chunk load and removed on chunk unload.
	Mesh *TiledNavMesh
	// LoadRadius is the Chebyshev chunk radius around the anchor position to load.
	LoadRadius int
	// UnloadRadius is the Chebyshev chunk radius beyond which loaded and in-flight tiles unload/cancel.
	// Defaults to LoadRadius + 1 when smaller than LoadRadius.
	UnloadRadius int
	// MaxIntegrationsPerFrame caps how many completed tiles are installed into Mesh per Update call
	// (<= 0 allows unlimited integrations per frame).
	MaxIntegrationsPerFrame int
	// Workers sets the number of background world3d.ChunkStreamer loader goroutines.
	// When 0, Bake runs synchronously inside Update (useful for deterministic tests).
	Workers int
	// Bake builds the standalone *NavTile for chunk coord and world-space XZ bounds.
	// When Workers > 0, Bake runs on worker goroutines and must respect ctx cancellation.
	// Return (nil, nil) for a chunk with no walkable surface.
	Bake func(ctx context.Context, coord world3d.ChunkCoord, bounds math3d.AABB) (*NavTile, error)
	// OnLoad runs on the Update goroutine after the tile is installed into Mesh.
	OnLoad func(coord world3d.ChunkCoord, tile *NavTile)
	// OnUnload runs on the Update/Close goroutine after the tile is removed from Mesh.
	OnUnload func(coord world3d.ChunkCoord)
	// OnError runs on the Update goroutine when Bake returns a non-nil error.
	OnError func(coord world3d.ChunkCoord, err error)
}

NavTileStreamerConfig configures a NavTileStreamer that drives a 3D TiledNavMesh from a world3d.ChunkStreamer[*NavTile], loading and unloading navmesh tiles in lockstep with streamed world chunks.

type NavTileVersion struct {
	Coord   world3d.ChunkCoord
	Version uint64
}

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

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

TiledNavMesh is a 3D navigation mesh partitioned into fixed-size XZ tiles that can be baked, added, removed, and replaced independently at runtime (including via NavTileStreamer / world3d.ChunkStreamer). Polygons are automatically linked in full 3D across tile borders (preserving multi-level separation), dynamic obstacles rebuild only the touched tiles, a two-level 3D spatial index avoids whole-mesh scans, and per-tile versions + watchers invalidate paths crossing changed tiles.

TiledNavMesh is deterministic and is not safe for concurrent mutation.

func BuildTiledNavMesh(polys [][]math3d.Vec3, maxSlopeRad, tileSize float32) *TiledNavMesh

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

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

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

func NewTiledNavMesh(cfg TiledNavMeshConfig) *TiledNavMesh

NewTiledNavMesh creates an empty 3D TiledNavMesh with cfg.

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

AddObstacle registers a dynamic 3D obstacle and rebuilds only the touched tiles (or defers rebuild until Batch returns if called inside Batch).

func (tm *TiledNavMesh) AddTile(coord world3d.ChunkCoord, tile *NavTile) bool

AddTile installs tile at coord only if no tile currently exists at coord.

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

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

func (tm *TiledNavMesh) BakeTile(coord world3d.ChunkCoord, polys []NavPolygonInput) *NavTile

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

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

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

func (tm *TiledNavMesh) ClearObstacles()

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

func (tm *TiledNavMesh) Contains(p math3d.Vec3) bool

Contains reports whether p lies on any walkable polygon within VerticalTolerance.

func (tm *TiledNavMesh) ContainsWithFilter(p math3d.Vec3, filter NavFilter) bool

ContainsWithFilter reports whether p lies on any walkable polygon passing filter within VerticalTolerance.

func (tm *TiledNavMesh) FindCorridor(start, goal math3d.Vec3) ([]NavPolyRef, bool)

FindCorridor computes the sequence of 3D NavPolyRefs from start to goal under DefaultNavFilter.

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

FindCorridorWithFilter computes the sequence of 3D NavPolyRefs from start to goal restricted to filter.

func (tm *TiledNavMesh) FindPath(start, goal math3d.Vec3) ([]math3d.Vec3, bool)

FindPath computes the shortest 3D path across tm from start to goal using DefaultNavFilter.

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

FindPathWithFilter computes the minimum-cost 3D path across tm restricted to filter.

func (tm *TiledNavMesh) FindPathWithFilterAndOptions(start, goal math3d.Vec3, filter NavFilter, opts pathfind.PathOptions) TiledNavPathResult

FindPathWithFilterAndOptions finds a minimum-cost 3D path across tm restricted to filter and opts. Sparse portal-graph A* touches only visited portals and runs 3D XZ-funnel smoothing with exact plane-transition crossings so paths across tile borders match an untiled NavMesh.

func (tm *TiledNavMesh) FindPathWithOptions(start, goal math3d.Vec3, opts pathfind.PathOptions) TiledNavPathResult

FindPathWithOptions computes a 3D path under DefaultNavFilter and opts, returning the full TiledNavPathResult with crossed tile versions for invalidation checking.

func (tm *TiledNavMesh) FindPolygon(p math3d.Vec3) (NavPolyRef, bool)

FindPolygon locates the walkable polygon containing (p.X, p.Z) whose 3D surface height is closest to p.Y within VerticalTolerance, using O(1) tile lookup + O(log P_tile) local 3D BVH.

func (tm *TiledNavMesh) FindPolygonWithFilter(p math3d.Vec3, filter NavFilter) (NavPolyRef, bool)

FindPolygonWithFilter locates the vertically closest matching polygon passing filter at p.

func (tm *TiledNavMesh) HasTile(coord world3d.ChunkCoord) bool

HasTile reports whether a tile is currently installed at coord.

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

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

func (tm *TiledNavMesh) NearestPoint(p, extent math3d.Vec3) (math3d.Vec3, NavPolyRef, bool)

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

func (tm *TiledNavMesh) NearestPointWithFilter(p, extent math3d.Vec3, filter NavFilter) (math3d.Vec3, NavPolyRef, bool)

NearestPointWithFilter behaves like NearestPoint restricted to filter.

func (tm *TiledNavMesh) NearestPolygon(p math3d.Vec3) (NavPolyRef, math3d.Vec3, bool)

NearestPolygon returns the 3D polygon closest to p and the closest 3D point on it.

func (tm *TiledNavMesh) NearestPolygonWithFilter(p math3d.Vec3, filter NavFilter) (NavPolyRef, math3d.Vec3, bool)

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

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

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

func (tm *TiledNavMesh) ObstacleCount() int

ObstacleCount returns the number of active dynamic obstacles.

func (tm *TiledNavMesh) Origin() math3d.Vec3

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

func (tm *TiledNavMesh) Polygon(ref NavPolyRef) []math3d.Vec3

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

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

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

func (tm *TiledNavMesh) PolygonCount() int

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

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

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

func (tm *TiledNavMesh) Raycast(start, target math3d.Vec3) (TiledNavRaycastHit, bool)

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

func (tm *TiledNavMesh) RaycastWithFilter(start, target math3d.Vec3, filter NavFilter) (TiledNavRaycastHit, bool)

RaycastWithFilter behaves like Raycast restricted to polygons allowed by filter.

func (tm *TiledNavMesh) RebuildTile(coord world3d.ChunkCoord) bool

RebuildTile rebuilds the existing tile at coord from its base polygons and active dynamic obstacles.

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

RemoveObstacle removes dynamic obstacle id and rebuilds only the tiles it touched.

func (tm *TiledNavMesh) RemoveTile(coord world3d.ChunkCoord) bool

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

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

RemoveTileListener unregisters a listener previously added with AddTileListener.

func (tm *TiledNavMesh) ReplaceTile(coord world3d.ChunkCoord, tile *NavTile) bool

ReplaceTile replaces the existing tile at coord with tile.

func (tm *TiledNavMesh) Revision() uint64

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

func (tm *TiledNavMesh) SetTile(coord world3d.ChunkCoord, tile *NavTile) bool

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

func (tm *TiledNavMesh) TileBounds(coord world3d.ChunkCoord) math3d.AABB

TileBounds returns the world-space XZ bounds of tile coord (with Y spanning [-math.MaxFloat32/4, +math.MaxFloat32/4] when empty or the tile's polygon Y bounds when loaded).

func (tm *TiledNavMesh) TileCoordAt(p math3d.Vec3) world3d.ChunkCoord

TileCoordAt returns the world3d.ChunkCoord containing (p.X, p.Z).

func (tm *TiledNavMesh) TileCoords() []world3d.ChunkCoord

TileCoords returns all installed tile coordinates in deterministic sorted order.

func (tm *TiledNavMesh) TileCount() int

TileCount returns the number of currently installed tiles.

func (tm *TiledNavMesh) TilePolygonCount(coord world3d.ChunkCoord) int

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

func (tm *TiledNavMesh) TileSize() float32

TileSize returns the configured XZ tile size in world units.

func (tm *TiledNavMesh) TileVersion(coord world3d.ChunkCoord) uint64

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

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

UnwatchPath cancels a path watcher previously registered with WatchPath.

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

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

func (tm *TiledNavMesh) WatchPath(tiles []world3d.ChunkCoord, onInvalidate func(NavTileChange)) NavPathWatchID

WatchPath registers a one-shot invalidation callback invoked when any tile in tiles changes. Once triggered, the watch is automatically removed.

type TiledNavMeshConfig struct {
	// TileSize is the XZ width and depth of each square tile in world units.
	// Defaults to 64 when <= 0 (matching world3d.ChunkStreamerConfig.ChunkSize).
	TileSize float32
	// Origin is the world-space XZ origin of tile (0, 0). Defaults to (0, 0, 0).
	Origin math3d.Vec3
	// MaxSlopeRad is the default slope limit used by BakeTile when building tiles.
	// Defaults to pi/4 (45 degrees) when < 0.
	MaxSlopeRad float32
	// VerticalTolerance is the maximum vertical distance from a query point to a walkable polygon.
	// Defaults to 2.0 when <= 0.
	VerticalTolerance float32
}

TiledNavMeshConfig configures a 3D TiledNavMesh.

type TiledNavPathResult struct {
	Path       []math3d.Vec3
	Corridor   []NavPolyRef
	Tiles      []NavTileVersion
	Found      bool
	Partial    bool
	Exhausted  bool
	Expansions int
}

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

func (r TiledNavPathResult) CrossesTile(coord world3d.ChunkCoord) bool

CrossesTile reports whether r's corridor passes through coord.

func (r TiledNavPathResult) TileCoords() []world3d.ChunkCoord

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

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

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