GitHubはじめる

API リファレンスはソースコード内の Go ドキュメントコメントから生成されており、英語で記述されています。

package world3d

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

概要

Package world3d provides 3D world-building primitives for NSGo 3D games: heightmap terrain, 3D navigation meshes and path-corridor navigation agents, 3D GridMaps of modular mesh tiles, procedural foliage/scattered instance fields, and large-world chunk streaming with floating-origin rebasing.

All positions, normals, rays, and bounding volumes follow package math3d's right-handed Y-up conventions (+X right, +Y up, -Z forward).

目次

定数

const (
	NavAreaDefault  = ai.NavAreaDefault
	NavAreaRoad     = ai.NavAreaRoad
	NavAreaGrass    = ai.NavAreaGrass
	NavAreaMud      = ai.NavAreaMud
	NavAreaWater    = ai.NavAreaWater
	NavAreaDoor     = ai.NavAreaDoor
	NavAreaHazard   = ai.NavAreaHazard
	NavAreaJump     = ai.NavAreaJump
	NavAreaClimb    = ai.NavAreaClimb
	NavAreaTeleport = ai.NavAreaTeleport
)
const (
	NavFlagWalk     = ai.NavFlagWalk
	NavFlagSwim     = ai.NavFlagSwim
	NavFlagDoor     = ai.NavFlagDoor
	NavFlagJump     = ai.NavFlagJump
	NavFlagClimb    = ai.NavFlagClimb
	NavFlagTeleport = ai.NavFlagTeleport
	NavFlagDisabled = ai.NavFlagDisabled
	NavFlagAll      = ai.NavFlagAll
)
const (
	NavTileAdded   = ai.NavTileAdded
	NavTileUpdated = ai.NavTileUpdated
	NavTileRemoved = ai.NavTileRemoved
)
const (
	NavObstacleCarve = ai.NavObstacleCarve
	NavObstacleMark  = ai.NavObstacleMark
)
const DefaultTerrainLayerRoughness float32 = 0.85

DefaultTerrainLayerRoughness is the roughness factor used when a TerrainLayerDoc omits both roughness and a metallicRoughness texture.

const FoliageFormatVersion = 1

FoliageFormatVersion is the current YAML foliage definition schema version.

const FoliageSchemaComment = "# yaml-language-server: $schema=" + FoliageSchemaURL

FoliageSchemaComment is the first line EncodeFoliage writes so YAML language servers validate and complete foliage definition files automatically.

const FoliageSchemaURL = "https://game.nsgo.dev/schemas/foliage.v1.json"

FoliageSchemaURL is where the JSON Schema of version 1 foliage documents is published.

const GridMapFormatVersion = 1

GridMapFormatVersion is the current YAML grid map schema version.

const GridMapSchemaComment = "# yaml-language-server: $schema=" + GridMapSchemaURL

GridMapSchemaComment is the first line EncodeGridMap writes so YAML language servers validate and complete grid map files automatically.

const GridMapSchemaURL = "https://game.nsgo.dev/schemas/gridmap.v1.json"

GridMapSchemaURL is where the JSON Schema of version 1 grid map documents is published.

const GridOrientationCount = 24

GridOrientationCount is the number of distinct proper 3D orthogonal 90-degree rotations supported by GridCell.Orientation (the 24 rotational symmetries of a cube). Orientations 0..3 are 0°, 90°, 180°, and 270° counter-clockwise quarter-turns around the +Y axis.

const MaxTerrainLayers = 8

MaxTerrainLayers is the maximum number of PBR terrain material layers driven by splat maps (up to 2 RGBA weight maps × 4 channels per map).

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.

const TerrainFormatVersion = 1

TerrainFormatVersion is the current YAML terrain definition schema version.

const TerrainSchemaComment = "# yaml-language-server: $schema=" + TerrainSchemaURL

TerrainSchemaComment is the first line EncodeTerrain writes so YAML language servers validate and complete terrain definition files automatically.

const TerrainSchemaURL = "https://game.nsgo.dev/schemas/terrain.v1.json"

TerrainSchemaURL is where the JSON Schema of version 1 terrain documents is published.

変数

var ErrInvalidTerrainSplat = errors.New("world3d: invalid terrain splat map")

ErrInvalidTerrainSplat is wrapped by errors returned when constructing or validating a TerrainSplatMap.

関数

func BlendTerrainWeights(raw, heights [MaxTerrainLayers]float32, count int, contrast float32) [MaxTerrainLayers]float32

BlendTerrainWeights normalizes raw splat weights across [0, count) and, when contrast > 0, applies height-based blending using each layer's effective height in [0, 1]. Higher contrast values (clamped to [0, 0.98]) produce sharper transitions while guaranteeing zero weights stay zero and the output always sums to 1 (falling back to layer 0 = 1 if all raw weights are <= 0).

This exact algebraic formula is shared with package render3d's GPU terrain shader and CPU reference evaluator.

func EncodeDensityMapPNG(d *DensityMap) ([]byte, error)

EncodeDensityMapPNG encodes d as an 8-bit grayscale PNG byte slice.

func EncodeFoliage(doc *FoliageDoc) ([]byte, error)

EncodeFoliage validates doc and serializes it as deterministic 2-space YAML prefixed with FoliageSchemaComment.

func EncodeGridMap(doc *GridMapDoc) ([]byte, error)

EncodeGridMap validates doc and serializes it as deterministic 2-space YAML prefixed with GridMapSchemaComment, with boxes and cells sorted into canonical (y, z, x) order. The input doc is not modified.

func EncodeHeightmapPNG(h *Heightmap) ([]byte, error)

EncodeHeightmapPNG encodes h as a 16-bit grayscale PNG byte slice.

func EncodeTerrain(doc *TerrainDoc) ([]byte, error)

EncodeTerrain validates doc and serializes it as deterministic 2-space YAML prefixed with TerrainSchemaComment.

func FindGridOrientation(m math3d.Mat4) (uint8, bool)

FindGridOrientation returns the orientation index (0..23) whose exact orthogonal rotation matrix matches the upper-left 3x3 of m, or (0, false) if none does.

func GridOrientationMat4(orient uint8) math3d.Mat4

GridOrientationMat4 returns the exact orthogonal 4x4 rotation matrix for orientation index orient (modulo GridOrientationCount). Orientations 0..3 correspond to 0°, 90°, 180°, and 270° rotations around the +Y axis.

func LoadGridMapFS(fsys fs.FS, name string) (*GridMap, *GridMapDoc, error)

LoadGridMapFS reads the YAML grid map at name in fsys, loads its referenced glTF mesh library from fsys, and returns the constructed *GridMap alongside the parsed *GridMapDoc.

func LoadTerrainFS(fsys fs.FS, name string) (*Heightmap, *TerrainDoc, error)

LoadTerrainFS reads the YAML terrain definition at name in fsys, validates it, decodes its referenced heightmap and splat images from fsys, and returns the constructed *Heightmap alongside the parsed *TerrainDoc.

func PackLayerWeightMaps(weights ...image.Image) (splat0, splat1 *image.NRGBA, err error)

PackLayerWeightMaps packs 1 to 8 per-layer grayscale weight-map images into 1 (for 1..4 layers) or 2 (for 5..8 layers) straight-alpha RGBA *image.NRGBA splat maps suitable for LoadTerrainSplatMap and GPU terrain shaders.

The output dimensions match the first non-nil weight image (or 1x1 when all images are nil, in which case layer 0 defaults to weight 255). Non-nil images with different dimensions are bilinearly resampled to match. Nil entries contribute zero weight to their channel.

func RebaseMat4(m math3d.Mat4, shift math3d.Vec3) math3d.Mat4

RebaseMat4 applies a floating-origin shift to the translation column of m.

func RotateGridOrientation(orient uint8, axis GridAxis, quarterTurns int) uint8

RotateGridOrientation applies quarterTurns 90-degree rotations around axis (world-space X, Y, or Z) to orient and returns the resulting orientation in 0..23. Composing X, Y, and Z quarter-turns reaches all 24 cube orientations.

func TerrainLODBiasFor(l quality.Level) float32

TerrainLODBiasFor returns the recommended terrain LOD bias for a game-wide quality preset: +1.0 for quality.Low (one LOD coarser), +0.5 for quality.Medium, and 0.0 for quality.High (full detail distances). An invalid level maps to quality.Medium, matching quality.DefaultPreset and QualityLevelFor.

Positive bias shifts chunks toward coarser LODs by scaling distance thresholds by 2^(-bias); negative bias keeps finer LODs farther away.

func ValidateFoliage(doc *FoliageDoc) error

ValidateFoliage checks that doc conforms to the version 1 foliage schema.

func ValidateGridMap(doc *GridMapDoc) error

ValidateGridMap checks that doc conforms to the version 1 grid map schema.

func ValidateTerrain(doc *TerrainDoc) error

ValidateTerrain checks that doc conforms to the version 1 terrain schema.

型

type ChunkCoord struct {
	X, Z int32
}

ChunkCoord identifies a 2D streaming chunk in the XZ world plane.

type ChunkStreamer[T any] struct {
	// contains filtered or unexported fields
}

ChunkStreamer asynchronously streams 2D world chunks around a moving WorldPos64 with bounded worker concurrency, per-frame integration budgets, hysteresis unloading, and cancellation of stale in-flight loads.

Build one with NewChunkStreamer. A zero ChunkStreamer is usable too: it behaves like NewChunkStreamer with a zero config (synchronous, no loader, 64-unit chunks) instead of panicking (#546).

func NewChunkStreamer[T any](cfg ChunkStreamerConfig[T]) *ChunkStreamer[T]

NewChunkStreamer constructs a ChunkStreamer and starts its worker goroutines when cfg.Workers > 0. Call Close when finished to stop workers and unload remaining chunks cleanly.

func (s *ChunkStreamer[T]) Close()

Close cancels all in-flight loads, waits for worker goroutines to exit, and unloads all remaining loaded chunks via OnUnload. Calling Close multiple times is safe.

func (s *ChunkStreamer[T]) Get(coord ChunkCoord) (T, bool)

Get returns the loaded chunk data for coord, or (zero, false) if not loaded.

func (s *ChunkStreamer[T]) LoadedChunks() []ChunkCoord

LoadedChunks returns a sorted slice of all currently loaded chunk coordinates.

func (s *ChunkStreamer[T]) PendingCount() int

PendingCount returns the number of chunks currently queued or loading in workers.

func (s *ChunkStreamer[T]) ReadyCount() int

ReadyCount returns the number of completed chunks awaiting integration on subsequent Update calls.

func (s *ChunkStreamer[T]) Update(worldPos WorldPos64)

Update advances streaming for worldPos:

  1. Unloads loaded chunks beyond UnloadRadius and cancels stale in-flight loads.
  2. Integrates up to MaxIntegrationsPerFrame completed chunks (closest first).
  3. Enqueues missing chunks within LoadRadius (closest first).

When Workers == 0, missing chunks are loaded synchronously up to the remaining per-frame integration budget.

type ChunkStreamerConfig[T any] struct {
	// ChunkSize is the width/depth of each square XZ chunk in world units.
	// Defaults to 64 if <= 0.
	ChunkSize float64
	// LoadRadius is the Chebyshev chunk radius around the player chunk to load.
	LoadRadius int
	// UnloadRadius is the Chebyshev chunk radius beyond which loaded and
	// in-flight chunks are unloaded/canceled. Defaults to LoadRadius + 1 if
	// smaller than LoadRadius.
	UnloadRadius int
	// MaxIntegrationsPerFrame caps how many completed chunks are integrated
	// into the active map per Update call to prevent frame-time hitches.
	// Values <= 0 allow unlimited integrations per frame.
	MaxIntegrationsPerFrame int
	// Workers sets the number of background loader goroutines. When 0, Loader
	// executes synchronously inside Update (useful for deterministic tests).
	Workers int
	// Loader loads chunk data for coord. It must respect ctx cancellation.
	Loader func(ctx context.Context, coord ChunkCoord) (T, error)
	// OnLoad is called on the Update goroutine after a chunk is integrated.
	OnLoad func(coord ChunkCoord, data T)
	// OnUnload is called on the Update/Close goroutine after a chunk is unloaded.
	OnUnload func(coord ChunkCoord, data T)
	// OnError is called on the Update goroutine when Loader returns a non-nil error.
	OnError func(coord ChunkCoord, err error)
}

ChunkStreamerConfig configures a ChunkStreamer.

type DensityMap struct {
	Width  int
	Height int
	Data   []float32
}

DensityMap stores normalized [0, 1] 2D scatter density weights in row-major order.

func LoadDensityMapGray(img image.Image) *DensityMap

LoadDensityMapGray constructs a DensityMap from a grayscale (or color, converted to 16-bit luminance) image with pixel intensities normalized to [0, 1].

func NewDensityMap(width, height int) *DensityMap

NewDensityMap allocates a zero-initialized DensityMap of width x height samples.

func (d *DensityMap) At(x, y int) float32

At returns the density sample at texel (x, y), or 0 if out of range.

func (d *DensityMap) Clone() *DensityMap

Clone returns a deep copy of d, or nil if d is nil.

func (d *DensityMap) EncodePNG(w io.Writer) error

EncodePNG encodes d as an 8-bit grayscale PNG image into w.

func (d *DensityMap) Sample(u, v float32) float32

Sample returns the bilinearly interpolated density weight in [0, 1] at normalized UV coordinates (u, v) in [0, 1]. If d is nil or empty, 1.0 is returned.

func (d *DensityMap) Set(x, y int, v float32)

Set writes a clamped [0, 1] density value at texel (x, y); out-of-range coordinates are ignored.

func (d *DensityMap) ToGray() *image.Gray

ToGray converts d into an 8-bit grayscale image with values in [0, 255].

func (d *DensityMap) ToGray16() *image.Gray16

ToGray16 converts d into a 16-bit grayscale image with values in [0, 65535].

type FloatingOrigin struct {
	Origin    WorldPos64
	Threshold float64
}

FloatingOrigin maintains a double-precision world origin offset so that local float32 physics, animation, and rendering coordinates stay near (0, 0, 0).

func NewFloatingOrigin(threshold float64) *FloatingOrigin

NewFloatingOrigin constructs a FloatingOrigin with the given rebase distance threshold (in world units). Non-positive thresholds default to 512.

func (f *FloatingOrigin) LocalToWorld(local math3d.Vec3) WorldPos64

LocalToWorld converts a local float32 position back into double-precision world coordinates.

func (f *FloatingOrigin) Update(playerLocal math3d.Vec3) (rebased bool, shift math3d.Vec3)

Update checks whether playerLocal has moved farther than Threshold from the local origin (0, 0, 0). When exceeded, Origin advances by playerLocal and Update returns (true, shift) where shift == -playerLocal is the additive offset to apply to every active local position/transform (pos = pos.Add(shift)) so playerLocal rebases back to (0, 0, 0) while preserving exact WorldPos64 coordinates.

func (f *FloatingOrigin) WorldToLocal(w WorldPos64) math3d.Vec3

WorldToLocal converts double-precision world position w into local float32 space by subtracting Origin in float64 before narrowing to float32.

type FoliageBuildOptions struct {
	// ResolveMesh maps a layer's Mesh asset path to a runtime MeshID. When nil, MeshID is 0.
	ResolveMesh func(path string) (uint32, error)
	// ResolveMaterial maps a layer's Material asset path (when non-empty) to a runtime MaterialID. When nil, MaterialID is 0.
	ResolveMaterial func(path string) (uint32, error)
	// LoadDensityMap loads a layer's DensityMap asset path (when non-empty) into a [*DensityMap].
	// When nil and FS is non-nil, the image is decoded from FS with [LoadDensityMapGray].
	LoadDensityMap func(path string) (*DensityMap, error)
	// FS is an optional filesystem used to decode DensityMap images when LoadDensityMap is nil.
	FS fs.FS
}

FoliageBuildOptions supplies runtime mesh/material ID resolution and density map loading when converting a FoliageDoc into runtime FoliageLayer values.

type FoliageDoc struct {
	// Version is the schema version; must be 1.
	Version int `yaml:"version" schema:"required"`
	// Name is an optional human-readable name for the foliage set.
	Name string `yaml:"name,omitempty"`
	// Terrain is an optional asset path to the terrain definition (*.terrain.yaml) these foliage layers scatter over.
	Terrain string `yaml:"terrain,omitempty"`
	// Layers lists 1 or more procedural foliage scatter layers in authoring order.
	Layers []FoliageLayerDoc `yaml:"layers" schema:"required,minItems=1"`
}

FoliageDoc is the root of a versioned YAML foliage definition declaring one or more procedural foliage scatter layers over a terrain heightmap.

func LoadFoliageFS(fsys fs.FS, name string) (*FoliageDoc, error)

LoadFoliageFS reads and validates the YAML foliage definition at name in fsys.

func ParseFoliage(data []byte) (*FoliageDoc, error)

ParseFoliage decodes and validates a YAML foliage definition document. Unknown fields and trailing YAML documents are rejected. Returned errors are *loaderr.Error values carrying line, column, field path, and a fix hint.

func ParseFoliageWith(data []byte, file string) (*FoliageDoc, error)

ParseFoliageWith is ParseFoliage with an optional source file name attached to errors.

func (d *FoliageDoc) BuildLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)

BuildLayers validates d and converts every entry in d.Layers into a runtime FoliageLayer.

func (d *FoliageDoc) ScatterAll(hm *Heightmap, region math3d.AABB, opts FoliageBuildOptions) ([]*FoliageField, error)

ScatterAll builds every foliage layer in d and scatters it across hm within region (or the full heightmap bounds when region is empty/zero).

type FoliageField struct {
	Layer FoliageLayer
	// contains filtered or unexported fields
}

FoliageField holds deterministically scattered, spatially chunked foliage instances for fast frustum and distance culling.

func Scatter(hm *Heightmap, layer FoliageLayer, region math3d.AABB) *FoliageField

Scatter deterministically generates a chunked FoliageField across region on hm. If region is empty or zero, the full Heightmap bounds are used.

Instances within each spatial chunk are stored in deterministic pseudo-random order so runtime QualityProfile.DensityScale sub-sampling is spatially uniform, strictly nested across quality levels, and branch-free.

func (f *FoliageField) Bounds() math3d.AABB

Bounds returns the world-space AABB enclosing all scattered instances in f.

func (f *FoliageField) ChunkCount() int

ChunkCount returns the number of non-empty spatial chunks in f.

func (f *FoliageField) CollectVisible(
	camPos math3d.Vec3,
	frustum math3d.Frustum,
	quality QualityProfile,
	out []FoliageInstance,
) []FoliageInstance

CollectVisible culls f against frustum and effective draw distance from camPos, applies quality.DensityScale, computes smooth per-instance Fade factors (1.0 inside fade start -> 0.0 at MaxDistance), and appends visible instances into out[:0].

Passing back the slice returned on the previous frame avoids heap allocations in steady state.

func (f *FoliageField) TotalCount() int

TotalCount returns the total number of scattered instances stored in f.

type FoliageInstance struct {
	Transform math3d.Mat4
	Fade      float32 // 1.0 inside fade start distance, smoothly transitioning to 0.0 at MaxDistance
}

FoliageInstance is a visible scattered instance ready for instanced rendering.

type FoliageLayer struct {
	Name            string
	MeshID          uint32
	MaterialID      uint32
	Density         float32     // target candidate instances per square meter
	MinScale        float32     // minimum uniform instance scale (defaults to 1 if both <= 0)
	MaxScale        float32     // maximum uniform instance scale
	AlignToNormal   float32     // 0 = upright (+Y), 1 = fully aligned to terrain normal
	MinSlopeDeg     float32     // minimum terrain slope in degrees [0, 90]
	MaxSlopeDeg     float32     // maximum terrain slope in degrees [0, 90]; 0 with MinSlopeDeg==0 allows all slopes
	MinHeight       float32     // minimum world Y height (unconstrained if MinHeight == 0 && MaxHeight == 0)
	MaxHeight       float32     // maximum world Y height (unconstrained if MinHeight == 0 && MaxHeight == 0)
	DensityMap      *DensityMap // optional normalized density mask across terrain bounds
	BaseMaxDistance float32     // default maximum draw distance in world units
	Seed            uint64      // deterministic PRNG seed
	// BoundingRadius is the radius, at scale 1, of a sphere around the mesh pivot that encloses the mesh. When > 0, frustum culling uses each instance's scaled sphere and the draw distance and fade are measured from the sphere's nearest point, so a large tree is kept while any part of it is within range (#546). When <= 0, culling assumes a unit-radius mesh and distances are measured from the pivot.
	BoundingRadius float32
}

FoliageLayer configures deterministic procedural scattering of a foliage or prop mesh across a Heightmap.

type FoliageLayerDoc struct {
	// Name is the unique identifier for this foliage layer (such as "grass", "pine_tree", "boulder").
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Mesh is the asset path to the foliage mesh (such as a .gltf or .glb model).
	Mesh string `yaml:"mesh" schema:"required,minLength=1"`
	// Material is an optional asset path to a material override for the foliage mesh.
	Material string `yaml:"material,omitempty"`
	// DensityMap is an optional asset path to a grayscale density mask image covering the terrain bounds.
	DensityMap string `yaml:"densityMap,omitempty"`
	// Density is the target candidate instances per square meter; set either density or spacing (not both).
	Density float32 `yaml:"density,omitempty" schema:"exclusiveMinimum=0"`
	// Spacing is the target average world-space spacing between instances in meters (equivalent to density = 1 / spacing^2); set either spacing or density (not both).
	Spacing float32 `yaml:"spacing,omitempty" schema:"exclusiveMinimum=0"`
	// MinScale is the minimum uniform instance scale; omitted defaults to 1 (or maxScale when only maxScale is set).
	MinScale float32 `yaml:"minScale,omitempty" schema:"exclusiveMinimum=0"`
	// MaxScale is the maximum uniform instance scale; omitted defaults to 1 (or minScale when only minScale is set).
	MaxScale float32 `yaml:"maxScale,omitempty" schema:"exclusiveMinimum=0"`
	// AlignToNormal blends instance up-axis alignment from upright (0) to terrain surface normal (1).
	AlignToNormal float32 `yaml:"alignToNormal,omitempty" schema:"minimum=0,maximum=1"`
	// MinSlopeDeg is the minimum terrain slope in degrees [0, 90] where instances may spawn.
	MinSlopeDeg float32 `yaml:"minSlopeDeg,omitempty" schema:"minimum=0,maximum=90"`
	// MaxSlopeDeg is the maximum terrain slope in degrees [0, 90] where instances may spawn; 0 with minSlopeDeg 0 allows all slopes.
	MaxSlopeDeg float32 `yaml:"maxSlopeDeg,omitempty" schema:"minimum=0,maximum=90"`
	// MinHeight is the minimum world-space Y elevation where instances may spawn.
	MinHeight *float32 `yaml:"minHeight,omitempty"`
	// MaxHeight is the maximum world-space Y elevation where instances may spawn.
	MaxHeight *float32 `yaml:"maxHeight,omitempty"`
	// BaseMaxDistance is the default maximum draw distance in world units; 0 means uncapped unless limited by QualityProfile.
	BaseMaxDistance float32 `yaml:"baseMaxDistance,omitempty" schema:"minimum=0"`
	// BoundingRadius is the bounding sphere radius at scale 1 around the mesh pivot for frustum culling and distance fade; 0 defaults to 1 around the pivot.
	BoundingRadius float32 `yaml:"boundingRadius,omitempty" schema:"minimum=0"`
	// Seed is the deterministic PRNG seed for repeatable scattering.
	Seed uint64 `yaml:"seed,omitempty"`
}

FoliageLayerDoc describes one procedural foliage scatter layer in a FoliageDoc.

func FoliageLayerToDoc(layer FoliageLayer, meshPath, materialPath, densityMapPath string) FoliageLayerDoc

FoliageLayerToDoc converts a runtime FoliageLayer and its asset paths into a FoliageLayerDoc suitable for deterministic YAML encoding.

func (l FoliageLayerDoc) EffectiveDensity() float32

EffectiveDensity returns the candidate density in instances per square meter: l.Density when positive, or 1 / (l.Spacing * l.Spacing) when l.Spacing is positive.

func (l FoliageLayerDoc) ToLayer(opts FoliageBuildOptions) (FoliageLayer, error)

ToLayer converts l into a runtime FoliageLayer using opts.

type GridAxis int

GridAxis identifies a principal 3D axis for 90-degree GridMap item rotations.

const (
	// GridAxisX is the world X axis.
	GridAxisX GridAxis = iota
	// GridAxisY is the world Y axis.
	GridAxisY
	// GridAxisZ is the world Z axis.
	GridAxisZ
)
type GridBoxDoc struct {
	// Min is the inclusive minimum integer [x, y, z] grid coordinate of the filled box.
	Min *[3]int `yaml:"min" schema:"required"`
	// Max is the inclusive maximum integer [x, y, z] grid coordinate of the filled box; each axis must be >= min.
	Max *[3]int `yaml:"max" schema:"required"`
	// Tile is the name of the tile in the referenced mesh library.
	Tile string `yaml:"tile" schema:"required,minLength=1"`
	// Orientation is the orthogonal cube rotation index in 0..23 (0..3 are 0°, 90°, 180°, 270° around +Y); omitted defaults to 0.
	Orientation uint8 `yaml:"orientation,omitempty" schema:"minimum=0,maximum=23"`
}

GridBoxDoc describes an axis-aligned box run of identical tiles placed from Min to Max (inclusive).

type GridCell struct {
	TileID      uint16
	Orientation uint8
}

GridCell stores the tile ID and orthogonal orientation (0..23) of a GridMap cell.

type GridCellDoc struct {
	// At is the discrete integer [x, y, z] grid coordinate of the cell.
	At *[3]int `yaml:"at" schema:"required"`
	// Tile is the name of the tile in the referenced mesh library.
	Tile string `yaml:"tile" schema:"required,minLength=1"`
	// Orientation is the orthogonal cube rotation index in 0..23 (0..3 are 0°, 90°, 180°, 270° around +Y); omitted defaults to 0.
	Orientation uint8 `yaml:"orientation,omitempty" schema:"minimum=0,maximum=23"`
}

GridCellDoc describes one occupied cell in a GridMapDoc.

type GridColliderOptions struct {
	// DisableMerge emits one static body per cell ColliderBox instead of
	// greedily merging adjacent aligned boxes along X, then Z, then Y.
	DisableMerge bool
	// MergeTolerance sets the face-alignment tolerance for greedy box merging
	// (defaults to 1e-4 when <= 0).
	MergeTolerance float32
	// Friction is the Coulomb friction coefficient for created static bodies
	// (defaults to 0.5 when <= 0).
	Friction float32
	// Restitution is the bounciness in [0, 1] for created static bodies.
	Restitution float32
	// Layer is the collision layer bitmask (0 defaults to physics3d.LayerAll).
	Layer physics3d.LayerMask
	// Mask is the collision filter bitmask (0 defaults to physics3d.LayerAll).
	Mask physics3d.LayerMask
	// Tag is an optional label assigned to every created static body.
	Tag string
}

GridColliderOptions configures static physics bodies created from a GridMap.

type GridCoord struct {
	X, Y, Z int
}

GridCoord identifies a discrete 3D cell coordinate in a GridMap.

type GridHit struct {
	Coord    GridCoord
	Cell     GridCell
	Point    math3d.Vec3
	Normal   math3d.Vec3
	Distance float32
}

GridHit describes the closest intersection between a ray and an occupied GridMap cell.

type GridInstanceBatch struct {
	MeshID     uint32
	MaterialID uint32
	Transforms []math3d.Mat4
}

GridInstanceBatch groups world-space instance transforms sharing the same (MeshID, MaterialID) pair for instanced 3D rendering.

type GridMap struct {
	Origin   math3d.Vec3
	CellSize math3d.Vec3
	Library  *MeshLibrary
	// contains filtered or unexported fields
}

GridMap is a sparse 3D grid of modular mesh tiles with runtime editing, frustum-culled instanced batch generation, AABB collision queries, and raycasting.

Each cell c spans [Origin + c*CellSize, Origin + (c+1)*CellSize] and places its tile's local origin at the center of that cell, rotated by GridOrientationMat4(cell.Orientation).

func NewGridMap(cellSize math3d.Vec3, lib *MeshLibrary) *GridMap

NewGridMap creates an empty GridMap with the given cell dimensions and tile library. Any non-positive CellSize axis defaults to 1.0.

func (g *GridMap) AddCollidersToWorld(w *physics3d.World, opts GridColliderOptions) []*physics3d.Body

AddCollidersToWorld creates static bodies in w for g's ColliderBoxes (greedily merged along X, then Z, then Y unless opts.DisableMerge is true) and returns the added body pointers in deterministic order.

func (g *GridMap) Bounds() math3d.AABB

Bounds returns the tight world-space AABB enclosing all occupied cells.

func (g *GridMap) BuildInstances(frustum *math3d.Frustum, out []GridInstanceBatch) []GridInstanceBatch

BuildInstances gathers world transforms for all visible occupied cells, grouped into instanced draw batches by (MeshID, MaterialID).

If frustum is non-nil, chunks and cells outside the view frustum are culled. To avoid steady-state heap allocations, callers can pass back the slice returned from the previous frame; its batch slots and Transforms backing arrays are reused in place.

func (g *GridMap) BuildStaticBodies(opts GridColliderOptions) []physics3d.Body

BuildStaticBodies builds static physics3d.Body values for g's ColliderBoxes. Adjacent aligned boxes are greedily merged along X, then Z, then Y unless opts.DisableMerge is true.

func (g *GridMap) Cell(c GridCoord) (GridCell, bool)

Cell returns the GridCell at coordinate c, or (GridCell{}, false) if empty.

func (g *GridMap) CellBounds(c GridCoord) math3d.AABB

CellBounds returns the world-space axis-aligned bounding box of cell c.

func (g *GridMap) CellTransform(c GridCoord, orient uint8) math3d.Mat4

CellTransform returns the world-space transform matrix placing a tile at the center of cell c rotated by orient (0..23).

func (g *GridMap) Clear()

Clear removes all cells from the GridMap.

func (g *GridMap) ClearCell(c GridCoord)

ClearCell removes any tile stored at grid coordinate c.

func (g *GridMap) ColliderBoxes() []math3d.AABB

ColliderBoxes returns all world-space collider AABBs from every occupied cell in g, in deterministic (Y, Z, X) cell order.

func (g *GridMap) CollisionBoxesIn(region math3d.AABB) []math3d.AABB

CollisionBoxesIn returns all world-space collider AABBs from occupied cells that intersect region. Tiles with no ColliderBoxes emit no collision boxes.

func (g *GridMap) Count() int

Count returns the number of occupied cells in the GridMap.

func (g *GridMap) EachCell(fn func(c GridCoord, cell GridCell) bool)

EachCell calls fn for every occupied cell in the GridMap until fn returns false or all cells have been visited.

func (g *GridMap) FillBox(minC, maxC GridCoord, tileID uint16, orient uint8)

FillBox sets every cell in the inclusive coordinate box [minC, maxC] to tileID with orientation orient. Component order is normalized automatically if any minC axis exceeds maxC. Setting tileID to 0 clears the box.

func (g *GridMap) MergedColliderBoxes() []math3d.AABB

MergedColliderBoxes extracts all world-space ColliderBoxes from g's occupied cells and greedily merges adjacent aligned boxes along X, then Z, then Y using physics3d.MergeBoxes. The union of the returned AABBs equals the union of g.ColliderBoxes() while reducing collider count and eliminating internal cell seams.

func (g *GridMap) Raycast(ray math3d.Ray, maxDist float32) (GridHit, bool)

Raycast intersects ray with occupied cells up to maxDist (in world-space Euclidean units; ray.Dir need not be unit-length). For each cell, Raycast tests its transformed ColliderBoxes when present, falling back to its transformed LocalBounds or CellBounds so non-colliding tiles remain pickable.

func (g *GridMap) SetCell(c GridCoord, tileID uint16, orient uint8)

SetCell places tileID with orientation orient (0..23) at grid coordinate c. Setting tileID to 0 clears the cell.

func (g *GridMap) ToDoc(name, meshLibrary string) (*GridMapDoc, error)

ToDoc exports g as a canonical deterministic *GridMapDoc, compressing contiguous axis-aligned runs of identical tiles into GridBoxDoc entries and emitting isolated cells as GridCellDoc entries in (y, z, x) order. Every occupied cell's TileID must resolve to a named MeshTileDef in g.Library.

type GridMapDoc struct {
	// Version is the schema version; must be 1.
	Version int `yaml:"version" schema:"required"`
	// Name is an optional human-readable name for the grid map.
	Name string `yaml:"name,omitempty"`
	// Origin is the world-space [x, y, z] origin of grid cell (0, 0, 0); omitted defaults to [0, 0, 0].
	Origin *[3]float32 `yaml:"origin,omitempty"`
	// CellSize is the world-space [x, y, z] dimensions of one grid cell; omitted defaults to [1, 1, 1].
	CellSize *[3]float32 `yaml:"cellSize,omitempty"`
	// MeshLibrary is the optional asset path to the glTF 2.0 (.gltf) mesh library supplying named tiles.
	MeshLibrary string `yaml:"meshLibrary,omitempty"`
	// Boxes lists non-overlapping filled axis-aligned coordinate box runs placed before individual cells, written in canonical (y, z, x) order.
	Boxes []GridBoxDoc `yaml:"boxes,omitempty"`
	// Cells lists individual occupied cells placed in canonical (y, z, x) coordinate order.
	Cells []GridCellDoc `yaml:"cells,omitempty"`
}

GridMapDoc is the root of a versioned YAML modular 3D grid map document referencing a mesh library and placing tiles on an integer 3D lattice.

func ParseGridMap(data []byte) (*GridMapDoc, error)

ParseGridMap decodes and validates a YAML grid map document. Unknown fields and trailing YAML documents are rejected. Returned errors are *loaderr.Error values carrying line, column, field path, and a fix hint.

func ParseGridMapWith(data []byte, file string) (*GridMapDoc, error)

ParseGridMapWith is ParseGridMap with an optional source file name attached to errors.

func (d *GridMapDoc) Build(lib *MeshLibrary) (*GridMap, error)

Build validates d and constructs a *GridMap populated with d's boxes and cells, resolving tile names against lib.

func (d *GridMapDoc) EffectiveCellSize() math3d.Vec3

EffectiveCellSize returns d.CellSize as a math3d.Vec3, defaulting to (1, 1, 1) when omitted.

func (d *GridMapDoc) EffectiveOrigin() math3d.Vec3

EffectiveOrigin returns d.Origin as a math3d.Vec3, defaulting to the zero vector when omitted.

func (d *GridMapDoc) Load(fsys fs.FS) (*GridMap, error)

Load loads d.MeshLibrary from fsys (when set, as glTF 2.0) and builds a runtime *GridMap.

type Heightmap struct {
	Cols        int
	Rows        int
	CellSize    float32
	HeightScale float32
	Origin      math3d.Vec3
	Heights     []float32
	// Splat optionally attaches splat-map material layers for gameplay queries via [Heightmap.LayerAt].
	Splat *TerrainSplatMap
	// FoliageDensity optionally attaches per-layer foliage scatter density maps keyed by foliage layer name, queried via [Heightmap.FoliageDensityAt].
	FoliageDensity map[string]*DensityMap
}

Heightmap represents a regular grid terrain surface in the XZ plane with +Y elevation. Sample (col, row) lives at world position:

(Origin.X + col*CellSize, Origin.Y + Heights[row*Cols+col]*HeightScale, Origin.Z + row*CellSize)

Every quad cell (col, row) is triangulated consistently across HeightAt, NormalAt, Raycast, and BuildMesh along the diagonal from (col+1, row) to (col, row+1):

  • Triangle 0 (fx+fz <= 1): (v00, v01, v10)
  • Triangle 1 (fx+fz > 1): (v10, v01, v11)
func DecodeHeightmapPNG(r io.Reader, cellSize, heightScale float32) (*Heightmap, error)

DecodeHeightmapPNG decodes a PNG image (preserving full 16-bit precision for 16-bit grayscale PNGs) from r and returns a *Heightmap with cellSize and heightScale.

func LoadHeightmapGray(img image.Image, cellSize, heightScale float32) *Heightmap

LoadHeightmapGray constructs a Heightmap from a grayscale (or color, converted to 16-bit luminance) image. Pixel intensities are normalized to [0, 1] with full 16-bit precision for *image.Gray16 inputs and scaled by heightScale during height evaluation.

func NewHeightmap(cols, rows int, cellSize, heightScale float32) *Heightmap

NewHeightmap allocates a flat (zero-elevation) Heightmap of cols x rows samples with the given cellSize and heightScale.

func (h *Heightmap) Bounds() math3d.AABB

Bounds returns the world-space axis-aligned bounding box enclosing the terrain.

func (h *Heightmap) BuildMesh(chunkCol, chunkRow, chunkCols, chunkRows int) TerrainMesh

BuildMesh generates an indexed triangle mesh for the rectangular chunk of grid cells starting at (chunkCol, chunkRow) and spanning (chunkCols, chunkRows) cells. If chunkCols or chunkRows is <= 0, the chunk extends to the remaining edge of the heightmap.

func (h *Heightmap) BuildMeshLOD(chunkCol, chunkRow, chunkCols, chunkRows int, lod int, neighbors TerrainEdgeLODs) TerrainMesh

BuildMeshLOD generates an indexed triangle mesh for the rectangular chunk of grid cells starting at (chunkCol, chunkRow) and spanning (chunkCols, chunkRows) cells at the given LOD level (vertex stride 1 << lod).

Whenever a neighbor in neighbors has a strictly coarser LOD (> lod), the shared border strip is re-triangulated to connect directly to that neighbor's coarser edge vertices, eliminating both height cracks and T-junctions across any pair of adjacent LOD levels (including partial border chunks). All triangles use counter-clockwise upward (+Y) winding and every emitted vertex is referenced by at least one triangle.

func (h *Heightmap) ChunkBounds(chunkCol, chunkRow, chunkCols, chunkRows int) math3d.AABB

ChunkBounds returns the world-space axis-aligned bounding box enclosing the rectangular chunk of grid cells starting at (chunkCol, chunkRow) and spanning (chunkCols, chunkRows) cells. If chunkCols or chunkRows is <= 0, the chunk extends to the remaining edge of the heightmap.

func (h *Heightmap) Collider() *physics3d.HeightfieldCollider

Collider constructs a static physics3d.HeightfieldCollider matching h's grid dimensions, cell size, origin, and scaled vertex heights.

func (h *Heightmap) EncodePNG(w io.Writer) error

EncodePNG encodes h as a 16-bit grayscale PNG image into w.

func (h *Heightmap) FoliageDensityAt(layer string, x, z float32) (float32, bool)

FoliageDensityAt samples the attached foliage density map for layer at world coordinates (x, z). The boolean reports whether (x, z) lies inside the heightmap's XZ footprint. Returns (0, false) when h is invalid or has no density map for layer.

func (h *Heightmap) HeightAt(x, z float32) (float32, bool)

HeightAt returns the exact barycentric triangle-interpolated world Y height at world coordinates (x, z), or (0, false) if (x, z) lies outside the terrain.

func (h *Heightmap) LayerAt(x, z float32) (TerrainLayerSample, bool)

LayerAt samples the terrain material layers attached to h.Splat at world coordinates (x, z). The boolean reports whether (x, z) lies inside the heightmap's XZ footprint; when (x, z) is outside the footprint but h and h.Splat are valid, LayerAt still clamps to the nearest terrain edge and returns the clamped edge sample alongside ok == false.

Returns (zero, false) when h is invalid or h.Splat is nil/empty.

func (h *Heightmap) NormalAt(x, z float32) math3d.Vec3

NormalAt returns the unit upward (+Y) surface normal of the terrain triangle containing (x, z). If (x, z) lies outside the terrain, Vec3Up is returned.

func (h *Heightmap) Raycast(ray math3d.Ray, maxDist float32) (TerrainHit, bool)

Raycast intersects ray with the heightmap using 2D grid DDA traversal paired with exact Möller-Trumbore triangle intersection. It visits only the cells under the ray, O(Cols+Rows) at most, and never scans the whole height grid. Distance and maxDist are measured in world-space Euclidean units (ray.Dir need not be unit-length).

func (h *Heightmap) SampleHeight(col, row int) float32

SampleHeight returns the world-space Y height at grid sample (col, row), clamping col and row to valid sample indices.

func (h *Heightmap) ToGray16() *image.Gray16

ToGray16 converts h's normalized [0, 1] heights into a 16-bit grayscale image suitable for lossless 16-bit PNG encoding without 8-bit banding. Values outside [0, 1] are clamped. Returns nil if h has non-positive dimensions or insufficient samples.

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

MeshLibrary is a registry of MeshTileDef entries indexed by ID and Name. Tile ID 0 is reserved to denote an empty grid cell.

func LoadMeshLibraryFromGLTF(gltfJSON []byte) (*MeshLibrary, error)

LoadMeshLibraryFromGLTF parses a glTF 2.0 JSON (.gltf) or binary (.glb) document's nodes, meshes, and POSITION accessor min/max bounds to build a MeshLibrary without external dependencies. Each node referencing a mesh becomes a MeshTileDef whose MeshID is the glTF mesh index, MaterialID is the first primitive's material index (or 0 if omitted), LocalBounds is the union of all primitive POSITION accessor bounds, and ColliderBoxes defaults to LocalBounds when present.

Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read the document from a file names it with loaderr.WithFile.

func NewMeshLibrary() *MeshLibrary

NewMeshLibrary returns an empty MeshLibrary ready to register tile definitions.

func (l *MeshLibrary) Add(def MeshTileDef) uint16

Add registers def in the library and returns its assigned non-zero tile ID. If def.ID is 0, the next available ID starting from 1 is assigned. If def.ID already exists in the library, its definition is replaced. When all 65535 IDs are taken, Add registers nothing and returns 0 (#546).

func (l *MeshLibrary) ByName(name string) (MeshTileDef, bool)

ByName looks up a tile definition by Name.

func (l *MeshLibrary) Get(id uint16) (MeshTileDef, bool)

Get looks up a tile definition by ID.

func (l *MeshLibrary) Items() []MeshTileDef

Items returns all tile definitions registered in the library sorted by ascending ID. Each returned entry owns a copy of its ColliderBoxes.

func (l *MeshLibrary) Len() int

Len returns the number of tile definitions registered in the library.

func (l *MeshLibrary) Revision() uint64

Revision returns a counter that changes whenever Add replaces or registers a definition, so caches derived from the library can invalidate.

type MeshTileDef struct {
	ID            uint16
	Name          string
	MeshID        uint32
	MaterialID    uint32
	LocalBounds   math3d.AABB
	ColliderBoxes []math3d.AABB
}

MeshTileDef describes a modular 3D tile stored in a MeshLibrary.

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

NavAgent navigates a 3D world3d.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 = ai.NavArea

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

type NavFilter = ai.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 = ai.NavFlags

NavFlags is a bitmask of runtime traversal capabilities and states on a 3D navigation polygon. It aliases ai.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 ai.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 ai.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 ai.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 ai.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 ai.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 world3d.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 ai.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 ai.IncrementalSearch so it can be scheduled directly on ai.PathQueue.

func NewNavMeshSearch(nm *NavMesh, start, goal math3d.Vec3, opts ai.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 ai.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() ai.SearchStatus

Status returns the search's current status.

func (s *NavMeshSearch) Step(maxExpansions int) (status ai.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 world3d.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 = ai.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 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 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 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() ChunkCoord

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

type NavTileChange struct {
	Coord   ChunkCoord
	Kind    NavTileChangeKind
	Version uint64
}

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

type NavTileChangeKind = ai.NavTileChangeKind

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

type NavTileCoord = ChunkCoord

NavTileCoord identifies a fixed-size tile in a 3D TiledNavMesh. It aliases 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 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() []ChunkCoord

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

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

Streamer returns the underlying ChunkStreamer[*NavTile].

func (s *NavTileStreamer) Update(worldPos 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 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 ChunkCoord, bounds math3d.AABB) (*NavTile, error)
	// OnLoad runs on the Update goroutine after the tile is installed into Mesh.
	OnLoad func(coord ChunkCoord, tile *NavTile)
	// OnUnload runs on the Update/Close goroutine after the tile is removed from Mesh.
	OnUnload func(coord ChunkCoord)
	// OnError runs on the Update goroutine when Bake returns a non-nil error.
	OnError func(coord 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   ChunkCoord
	Version uint64
}

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

type QualityLevel uint8

QualityLevel selects a built-in foliage density and draw-distance tier.

const (
	QualityLow QualityLevel = iota
	QualityMedium
	QualityHigh
	QualityUltra
)
func QualityLevelFor(l quality.Level) QualityLevel

QualityLevelFor returns the foliage tier for a game-wide quality level: QualityLow for quality.Low, QualityMedium for quality.Medium and QualityHigh for quality.High. QualityUltra stays an explicit choice above every preset. An invalid level maps to QualityMedium, as quality.DefaultPreset does.

type QualityProfile struct {
	// DensityScale scales the fraction of scattered instances emitted, in [0, 1].
	DensityScale float32
	// MaxDistance caps the maximum visible distance in world units (meters).
	// If <= 0, the layer's BaseMaxDistance is used.
	MaxDistance float32
	// FadeStartRatio is the fraction of effective MaxDistance in [0, 1] at which
	// instances begin fading smoothly from 1.0 down to 0.0 at MaxDistance.
	FadeStartRatio float32
}

QualityProfile controls runtime foliage density scaling, maximum visibility distance, and smooth distance fade-out.

func DefaultQualityProfile(level QualityLevel) QualityProfile

DefaultQualityProfile returns recommended foliage settings for level.

type TerrainDoc struct {
	// Version is the schema version; must be 1.
	Version int `yaml:"version" schema:"required"`
	// Name is an optional human-readable name for the terrain.
	Name string `yaml:"name,omitempty"`
	// Size is the optional [cols, rows] heightmap grid dimensions (each >= 2). When set alongside heightmap, the decoded heightmap image must match these dimensions; when heightmap is omitted, a flat heightmap of this size is created.
	Size *[2]int `yaml:"size,omitempty"`
	// Heightmap is the asset path to the 16-bit (or 8-bit) grayscale PNG heightmap image.
	Heightmap string `yaml:"heightmap,omitempty"`
	// CellSize is the world-space XZ spacing between adjacent heightmap samples; omitted or 0 defaults to 1.
	CellSize float32 `yaml:"cellSize,omitempty" schema:"exclusiveMinimum=0"`
	// HeightScale scales normalized [0, 1] heightmap samples into world-space Y units.
	HeightScale float32 `yaml:"heightScale,omitempty" schema:"minimum=0"`
	// Origin is the world-space [x, y, z] origin of heightmap sample (0, 0); omitted defaults to [0, 0, 0].
	Origin *[3]float32 `yaml:"origin,omitempty"`
	// ChunkSize is the number of heightmap grid cells along each terrain LOD chunk edge; omitted or 0 defaults to 64.
	ChunkSize int `yaml:"chunkSize,omitempty" schema:"minimum=1"`
	// SplatMaps lists 1 or 2 RGBA weight-map asset paths: map 0 drives layers 0..3 (R,G,B,A) and map 1 drives layers 4..7 (R,G,B,A). Mutually exclusive with per-layer weightMap paths.
	SplatMaps []string `yaml:"splatMaps,omitempty"`
	// HeightBlendContrast enables height-based layer blending when > 0 in [0, 1]; higher values sharpen layer transitions using per-layer height maps, and 0 uses linear splat blending.
	HeightBlendContrast float32 `yaml:"heightBlendContrast,omitempty" schema:"minimum=0,maximum=1"`
	// Triplanar configures slope-driven triplanar texture projection on steep terrain faces.
	Triplanar *TerrainTriplanarDoc `yaml:"triplanar,omitempty"`
	// Layers lists 1 to 8 PBR terrain material layers in channel order (0..3 from splatMaps[0] RGBA and 4..7 from splatMaps[1] RGBA, or each driven by its own weightMap PNG).
	Layers []TerrainLayerDoc `yaml:"layers" schema:"required,minItems=1"`
	// Foliage lists optional procedural foliage scatter layers attached to this terrain, each with an optional grayscale density map PNG.
	Foliage []FoliageLayerDoc `yaml:"foliage,omitempty"`
}

TerrainDoc is the root of a versioned YAML terrain definition specifying heightmap dimensions, splat or per-layer weight-map asset paths, height-blending and triplanar settings, up to 8 PBR material layers, and optional procedural foliage scatter layers with density maps.

func ParseTerrain(data []byte) (*TerrainDoc, error)

ParseTerrain decodes and validates a YAML terrain definition document. Unknown fields and trailing YAML documents are rejected. Returned errors are *loaderr.Error values carrying line, column, field path, and a fix hint.

func ParseTerrainWith(data []byte, file string) (*TerrainDoc, error)

ParseTerrainWith is ParseTerrain with an optional source file name attached to errors.

func (d *TerrainDoc) BuildFoliageLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)

BuildFoliageLayers validates d and converts every entry in d.Foliage into a runtime FoliageLayer using opts. Returns nil, nil when d.Foliage is empty.

func (d *TerrainDoc) BuildHeightmap(imgs TerrainImages) (*Heightmap, error)

BuildHeightmap validates d and constructs a *Heightmap configured with d's CellSize, HeightScale, Origin, optional attached *TerrainSplatMap (from imgs.SplatMaps or imgs.LayerWeights, with HeightBlendContrast and per-layer height maps), and optional attached foliage density maps.

func (d *TerrainDoc) BuildLOD(hm *Heightmap) *TerrainLOD

BuildLOD constructs a *TerrainLOD for hm using d's TerrainDoc.LODConfig.

func (d *TerrainDoc) EffectiveCellSize() float32

EffectiveCellSize returns d.CellSize, defaulting to 1 when zero.

func (d *TerrainDoc) EffectiveChunkSize() int

EffectiveChunkSize returns d.ChunkSize, defaulting to 64 when omitted or zero.

func (d *TerrainDoc) EffectiveOrigin() math3d.Vec3

EffectiveOrigin returns d.Origin as a math3d.Vec3, defaulting to the zero vector when omitted.

func (d *TerrainDoc) HasLayerWeightMaps() bool

HasLayerWeightMaps reports whether any layer in d specifies a per-layer WeightMap path.

func (d *TerrainDoc) LODConfig() TerrainLODConfig

LODConfig returns a TerrainLODConfig populated from d's ChunkSize.

func (d *TerrainDoc) LayerInfos() []TerrainLayerInfo

LayerInfos converts d.Layers into TerrainLayerInfo metadata (name, UV scale, and height bias) suitable for constructing a TerrainSplatMap.

func (d *TerrainDoc) LoadHeightmap(fsys fs.FS) (*Heightmap, error)

LoadHeightmap decodes the heightmap, optional splat or per-layer weight maps, optional per-layer height maps, and optional foliage density maps referenced by d from fsys, then builds a runtime *Heightmap.

func (d *TerrainDoc) ScatterFoliage(hm *Heightmap, region math3d.AABB, opts FoliageBuildOptions) ([]*FoliageField, error)

ScatterFoliage builds every foliage layer declared in d.Foliage and scatters it across hm within region (or the full heightmap bounds when region is empty/zero). When a layer's density map is already loaded on hm.FoliageDensity and opts.LoadDensityMap is nil, the attached density map is reused directly.

type TerrainEdgeLODs struct {
	North int // neighbor toward -Z (smaller row)
	South int // neighbor toward +Z (larger row)
	West  int // neighbor toward -X (smaller col)
	East  int // neighbor toward +X (larger col)
}

TerrainEdgeLODs specifies the LOD level of each cardinal neighbor of a terrain chunk so BuildMeshLOD can stitch shared borders without cracks or T-junctions. A neighbor LOD less than or equal to the chunk's own LOD (including negative values for absent neighbors) leaves that edge unstitched.

type TerrainHeightLayer struct {
	Width   int
	Height  int
	Heights []float32
}

TerrainHeightLayer holds a CPU-readable normalized [0, 1] height texture for one terrain material layer so TerrainSplatMap.SampleUV and Heightmap.LayerAt can apply height-based blending matching the GPU terrain shader.

func LoadTerrainHeightLayer(img image.Image) *TerrainHeightLayer

LoadTerrainHeightLayer converts a grayscale (or color, converted to 16-bit luminance) image into a normalized [0, 1] TerrainHeightLayer. Returns nil if img is nil or has empty bounds.

func (l *TerrainHeightLayer) SampleUV(u, v float32) float32

SampleUV bilinearly samples the height layer at repeating texture coordinates (u, v), matching GPU linear-repeat texture sampling. Returns 0.5 when l is nil or empty.

type TerrainHit struct {
	Point    math3d.Vec3
	Normal   math3d.Vec3
	Distance float32
	Col, Row int
}

TerrainHit describes the closest intersection between a ray and a Heightmap.

type TerrainImages struct {
	// Heightmap is the grayscale heightmap image (required when TerrainDoc.Size is nil; at least 2x2 pixels).
	Heightmap image.Image
	// SplatMaps holds 0, 1, or 2 RGBA weight-map images matching TerrainDoc.SplatMaps.
	SplatMaps []image.Image
	// LayerWeights optionally maps a layer's Name to its decoded grayscale weight-map PNG when per-layer weightMap paths are used instead of SplatMaps.
	LayerWeights map[string]image.Image
	// LayerHeights optionally maps a layer's Name to its decoded grayscale height map for height-based blending.
	LayerHeights map[string]image.Image
	// FoliageDensityMaps optionally maps a foliage layer's Name to its decoded grayscale density map PNG.
	FoliageDensityMaps map[string]image.Image
}

TerrainImages holds decoded images supplied to TerrainDoc.BuildHeightmap when constructing a runtime *Heightmap without reading from an fs.FS.

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

TerrainLOD partitions a Heightmap into chunks, selects per-chunk LOD levels from camera distance with hysteresis and quality bias, culls chunk AABBs against a camera frustum, and caches crack-free stitched TerrainMesh geometry per chunk. It works in world space or with FloatingOrigin and ChunkStreamer.

func NewTerrainLOD(hm *Heightmap, cfg TerrainLODConfig) *TerrainLOD

NewTerrainLOD constructs a TerrainLOD manager for hm using cfg.

func (t *TerrainLOD) ChunkBounds(coord ChunkCoord) (math3d.AABB, bool)

ChunkBounds returns the world-space AABB for the chunk at coord.

func (t *TerrainLOD) ChunkCells() int

ChunkCells returns the nominal cell count along each chunk edge.

func (t *TerrainLOD) ChunkCount() int

ChunkCount returns the total number of chunks partitioning the heightmap.

func (t *TerrainLOD) ChunkLOD(coord ChunkCoord) (int, bool)

ChunkLOD returns the most recently selected LOD level for coord, or (-1, false) if coord is out of bounds or has not been evaluated while active.

func (t *TerrainLOD) ChunkWorldSize() float64

ChunkWorldSize returns the world-space width of a full chunk (ChunkCells * Heightmap.CellSize), suitable for configuring ChunkStreamerConfig.ChunkSize.

func (t *TerrainLOD) EvictHiddenMeshes()

EvictHiddenMeshes frees cached TerrainMesh buffers for chunks that were not visible in the most recent Update.

func (t *TerrainLOD) GridSize() (cols, rows int)

GridSize returns the number of terrain chunks along X (cols) and Z (rows).

func (t *TerrainLOD) InvalidateAll()

InvalidateAll recomputes every chunk AABB and forces all cached meshes to rebuild as they become visible.

func (t *TerrainLOD) InvalidateChunk(coord ChunkCoord)

InvalidateChunk recomputes the AABB for coord and forces its mesh to rebuild on the next Update (for example after editing Heightmap.Heights in place).

func (t *TerrainLOD) IsChunkActive(coord ChunkCoord) bool

IsChunkActive reports whether coord is a valid chunk coordinate in t and is currently active.

func (t *TerrainLOD) LODBias() float32

LODBias returns the current LOD bias.

func (t *TerrainLOD) MaxLOD() int

MaxLOD returns the coarsest LOD index managed by t.

func (t *TerrainLOD) SetChunkActive(coord ChunkCoord, active bool)

SetChunkActive activates or deactivates the chunk at coord (typically called from ChunkStreamer's OnLoad and OnUnload callbacks when StreamManaged is true). Deactivating a chunk releases its cached mesh; neighboring seams automatically re-stitch on the next Update.

func (t *TerrainLOD) SetLODBias(bias float32)

SetLODBias updates the LOD bias (threshold scale = 2^(-bias)) and resets per-chunk hysteresis memory so the next Update reflects the new bias immediately.

func (t *TerrainLOD) SetQualityLevel(level quality.Level)

SetQualityLevel applies TerrainLODBiasFor(level) to t.

func (t *TerrainLOD) Stats() TerrainLODStats

Stats returns summary statistics from the most recent Update or UpdateWithOrigin call.

func (t *TerrainLOD) Update(camPos math3d.Vec3, frustum *math3d.Frustum) []TerrainLODChunk

Update selects per-chunk LOD levels for a world-space camera at camPos, culls chunk bounds against frustum (when non-nil), builds or reuses crack-free stitched meshes for visible chunks, and returns the visible chunk slice.

The returned slice aliases internal storage reused across calls; copy any fields needed past the next Update.

func (t *TerrainLOD) UpdateWithOrigin(camLocal math3d.Vec3, frustumLocal *math3d.Frustum, origin *FloatingOrigin) []TerrainLODChunk

UpdateWithOrigin advances terrain LOD selection and frustum culling using a camera and frustum expressed in FloatingOrigin local space.

Camera-to-chunk distances are evaluated in float64 world space so LOD selection is completely invariant to FloatingOrigin rebasing. Each returned TerrainLODChunk carries Bounds and a translation Transform in local space, allowing cached chunk meshes to render cleanly across rebases without rebuilding vertex buffers.

type TerrainLODChunk struct {
	Coord     ChunkCoord
	Col       int
	Row       int
	Cols      int
	Rows      int
	LOD       int
	Edges     TerrainEdgeLODs
	Bounds    math3d.AABB
	Transform math3d.Mat4
	Mesh      *TerrainMesh
	Revision  uint64
	Changed   bool
}

TerrainLODChunk describes one visible terrain chunk returned by TerrainLOD.Update or TerrainLOD.UpdateWithOrigin.

type TerrainLODConfig struct {
	// ChunkCells is the number of heightmap grid cells along each chunk edge.
	// Defaults to 64 when <= 0.
	ChunkCells int

	// Distances lists the maximum camera-to-chunk-AABB distance for LOD 0, 1,
	// ... in world units. Chunks beyond the last entry use the coarsest level.
	// When empty, geometric distances starting at 1.0 * ChunkWorldSize (doubling
	// per LOD level up to MaxLOD) are generated automatically.
	Distances []float32

	// Hysteresis is the relative deadband in (0, 0.5] around each LOD distance
	// threshold to prevent popping when the camera oscillates near a boundary.
	// Zero uses the default 0.10 (10%); negative values disable hysteresis.
	Hysteresis float32

	// LODBias shifts LOD distance thresholds by 2^(-LODBias). Positive values
	// choose coarser LODs at shorter distances (fewer triangles); negative values
	// keep finer detail farther away. Use TerrainLODBiasFor(level) to derive a
	// bias from a game-wide quality preset.
	LODBias float32

	// MaxLOD optionally caps the coarsest LOD level (vertex stride 1<<MaxLOD).
	// When <= 0, MaxLOD is derived from ChunkCells so stride reaches ChunkCells.
	MaxLOD int

	// WorldOrigin places the heightmap's (0, 0) sample in double-precision world
	// space for FloatingOrigin and ChunkStreamer integration. When HasWorldOrigin
	// is false and WorldOrigin is zero, Heightmap.Origin is used.
	WorldOrigin    WorldPos64
	HasWorldOrigin bool

	// StreamManaged, when true, starts with all chunks inactive so a
	// ChunkStreamer activates and deactivates chunks via SetChunkActive.
	// When false (default), every chunk covering the heightmap is active.
	StreamManaged bool
}

TerrainLODConfig configures a TerrainLOD chunk manager.

type TerrainLODStats struct {
	TotalChunks    int
	ActiveChunks   int
	VisibleChunks  int
	CulledChunks   int
	RebuiltChunks  int
	TotalTriangles int
	TotalVertices  int
}

TerrainLODStats summarizes the most recent TerrainLOD update.

type TerrainLayerDoc struct {
	// Name is the unique gameplay and authoring identifier for this layer (such as "grass", "dirt", "rock", "snow").
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Material is an optional asset path to a material resource file (such as materials/grass.material.yaml) supplying default base color, texture, roughness, and metallic values.
	Material string `yaml:"material,omitempty"`
	// WeightMap is an optional asset path to a per-layer grayscale weight-map PNG covering the terrain footprint; mutually exclusive with top-level splatMaps.
	WeightMap string `yaml:"weightMap,omitempty"`
	// Albedo is the asset path to the sRGB base-color texture.
	Albedo string `yaml:"albedo,omitempty"`
	// Normal is the asset path to the linear tangent-space normal map.
	Normal string `yaml:"normal,omitempty"`
	// MetallicRoughness is the asset path to the glTF metallic-roughness map (G = roughness, B = metallic).
	MetallicRoughness string `yaml:"metallicRoughness,omitempty"`
	// Height is the asset path to the optional grayscale height map used for height-based blending.
	Height string `yaml:"height,omitempty"`
	// Color is the linear RGB tint multiplier in [0, 1]^3; omitted defaults to [1, 1, 1].
	Color *[3]float32 `yaml:"color,omitempty"`
	// Roughness is the layer roughness factor in [0, 1]; omitted defaults to 1 when metallicRoughness is set or 0.85 otherwise.
	Roughness *float32 `yaml:"roughness,omitempty" schema:"minimum=0,maximum=1"`
	// Metallic is the layer metallic factor in [0, 1]; omitted defaults to 0.
	Metallic float32 `yaml:"metallic,omitempty" schema:"minimum=0,maximum=1"`
	// NormalScale scales the XY components of the tangent-space normal map; omitted defaults to 1.
	NormalScale *float32 `yaml:"normalScale,omitempty"`
	// UVScale is the per-layer UV tiling multiplier [u, v] across the terrain; omitted defaults to [1, 1].
	UVScale *[2]float32 `yaml:"uvScale,omitempty"`
	// HeightBias biases this layer's height map during height-based blending in [-1, 1].
	HeightBias float32 `yaml:"heightBias,omitempty" schema:"minimum=-1,maximum=1"`
}

TerrainLayerDoc describes one PBR terrain material layer in a TerrainDoc.

func (l TerrainLayerDoc) EffectiveColor() [3]float32

EffectiveColor returns l.Color when set, or linear white [1, 1, 1] when omitted.

func (l TerrainLayerDoc) EffectiveNormalScale() float32

EffectiveNormalScale returns l.NormalScale when set, or 1.0 when omitted.

func (l TerrainLayerDoc) EffectiveRoughness() float32

EffectiveRoughness returns l.Roughness when set, 1.0 when MetallicRoughness is set, or DefaultTerrainLayerRoughness (0.85) otherwise.

func (l TerrainLayerDoc) EffectiveUVScale() math3d.Vec2

EffectiveUVScale returns l.UVScale when set, or [1, 1] when omitted.

type TerrainLayerInfo struct {
	// Name is the gameplay surface identifier (such as "grass", "dirt", "rock", "snow").
	Name string
	// UVScale scales terrain [0, 1] UVs when sampling HeightMap; zero components default to 1.
	UVScale math3d.Vec2
	// HeightBias biases this layer's height during height-based blending (typically in [-1, 1]).
	HeightBias float32
	// HeightMap optionally supplies a tiling height map for height-based blending; nil uses 0.5.
	HeightMap *TerrainHeightLayer
}

TerrainLayerInfo describes one material layer's gameplay identity and height-blending parameters inside a TerrainSplatMap.

type TerrainLayerSample struct {
	// Dominant is the index in [0, Count) of the layer with the highest normalized weight.
	// Ties break deterministically in favor of the lower layer index.
	Dominant int
	// Name is the configured name of the Dominant layer.
	Name string
	// Weights holds the normalized per-layer weights in [0, 1] summing to 1 across [0, Count).
	// Entries at indices >= Count are zero.
	Weights [MaxTerrainLayers]float32
	// Count is the number of active layers in [0, MaxTerrainLayers].
	Count int
}

TerrainLayerSample is the zero-allocation result of sampling terrain material layers at a world position or terrain UV for footsteps, particles, and movement logic.

func (s TerrainLayerSample) Weight(index int) float32

Weight returns the normalized weight of layer index, or 0 if index is out of range.

type TerrainMesh struct {
	Positions []math3d.Vec3
	Normals   []math3d.Vec3
	UVs       []math3d.Vec2
	Indices   []uint32
}

TerrainMesh holds indexed triangle-list geometry for a heightmap chunk ready for upload to a GPU vertex and index buffer. Triangles use counter-clockwise winding when viewed from +Y.

type TerrainSplatMap struct {
	// Layers holds the 1..8 material layer definitions in splat-channel order.
	Layers []TerrainLayerInfo
	// HeightBlendContrast controls optional height-based weight sharpening in [0, 1].
	// Zero disables height blending (pure linear splat weights).
	HeightBlendContrast float32
	// Origin is the world-space (X, Z) origin used by [TerrainSplatMap.LayerAt].
	Origin math3d.Vec2
	// Size is the world-space (X, Z) footprint used by [TerrainSplatMap.LayerAt].
	// When zero or non-positive, [TerrainSplatMap.LayerAt] treats (x, z) directly as UVs.
	Size math3d.Vec2
	// contains filtered or unexported fields
}

TerrainSplatMap stores 1 or 2 RGBA weight (splat) maps and up to 8 layer definitions for CPU-side gameplay queries via TerrainSplatMap.SampleUV, TerrainSplatMap.LayerAt, and Heightmap.LayerAt.

Splat map 0's R, G, B, A channels drive layers 0..3; splat map 1's R, G, B, A channels drive layers 4..7. Sampling uses bilinear texel-center interpolation with edge clamping, matching GPU linear clamp-to-edge sampling.

func LoadTerrainSplatMap(layers []TerrainLayerInfo, maps ...image.Image) (*TerrainSplatMap, error)

LoadTerrainSplatMap constructs a TerrainSplatMap from 1..8 layer definitions and 1 or 2 RGBA splat-map images (splat0 for layers 0..3, optional splat1 for layers 4..7). Note that standard *image.NRGBA preserves all 4 channels verbatim including zero-alpha texels.

func LoadTerrainSplatMapFromWeights(layers []TerrainLayerInfo, weights []image.Image) (*TerrainSplatMap, error)

LoadTerrainSplatMapFromWeights constructs a TerrainSplatMap from 1..8 layer definitions and per-layer grayscale weight-map images. Trailing omitted entries in weights default to zero weight; images with different dimensions are resampled to match the first non-nil weight image.

func NewTerrainSplatMapFromRGBA(width, height int, layers []TerrainLayerInfo, splat0, splat1 []byte) (*TerrainSplatMap, error)

NewTerrainSplatMapFromRGBA constructs a TerrainSplatMap from tightly packed straight-alpha RGBA8 byte buffers (width × height × 4 bytes each). splat1 may be nil when len(layers) <= 4.

func (s *TerrainSplatMap) Height() int

Height returns the texel height of splat map 0, or 0 for a nil splat map.

func (s *TerrainSplatMap) LayerAt(x, z float32) TerrainLayerSample

LayerAt maps world coordinates (x, z) using s.Origin and s.Size, clamps to the terrain's [0, 1] UV extent, and returns the dominant layer and normalized weights. When attached to a Heightmap, prefer Heightmap.LayerAt, which derives UV bounds automatically from the heightmap's Origin, Cols, Rows, and CellSize.

func (s *TerrainSplatMap) LayerCount() int

LayerCount returns the number of active layers in s (0 for nil).

func (s *TerrainSplatMap) LayerIndex(name string) int

LayerIndex returns the index of the first layer named name, or -1 if not found.

func (s *TerrainSplatMap) LayerName(index int) string

LayerName returns the name of layer index, or "" if out of range.

func (s *TerrainSplatMap) LayerWeightImage(layer int) *image.Gray

LayerWeightImage extracts layer's weight channel (0..7) as an 8-bit grayscale image, or nil if s is nil or layer is out of range.

func (s *TerrainSplatMap) SampleUV(u, v float32) TerrainLayerSample

SampleUV samples the splat map(s) at normalized terrain UV coordinates (u, v), clamping out-of-bounds UVs to [0, 1], applying optional height-based blending, and returning the dominant layer and normalized per-layer weights.

func (s *TerrainSplatMap) SetTexelWeight(layer, x, y int, weight float32)

SetTexelWeight writes a clamped [0, 1] weight for layer at texel (x, y). Out-of-range coordinates or layers are ignored.

func (s *TerrainSplatMap) SplatImages() (splat0, splat1 *image.NRGBA)

SplatImages returns copies of s's RGBA splat map(s) as *image.NRGBA images (splat1 is nil when s has at most 4 layers).

func (s *TerrainSplatMap) TexelWeight(layer, x, y int) float32

TexelWeight returns the raw weight in [0, 1] stored for layer at texel (x, y), or 0 if out of range.

func (s *TerrainSplatMap) Width() int

Width returns the texel width of splat map 0, or 0 for a nil splat map.

type TerrainTriplanarDoc struct {
	// Enabled activates triplanar projection on steep slopes whose upward normal falls below SlopeThreshold.
	Enabled bool `yaml:"enabled,omitempty"`
	// SlopeThreshold is the world normal Y threshold in [0, 1] below which triplanar projection begins blending in; omitted or 0 defaults to 0.7.
	SlopeThreshold float32 `yaml:"slopeThreshold,omitempty" schema:"minimum=0,maximum=1"`
	// SlopeBlend is the transition width in [0, 1] over which planar UVs cross-fade into triplanar projection; omitted or 0 defaults to 0.15.
	SlopeBlend float32 `yaml:"slopeBlend,omitempty" schema:"minimum=0,maximum=1"`
	// Sharpness controls triplanar axis blend sharpness (typically 1..16); omitted or 0 defaults to 4.
	Sharpness float32 `yaml:"sharpness,omitempty" schema:"exclusiveMinimum=0"`
	// Scale is the world-space triplanar repeat rate (repeats per world unit); omitted or 0 defaults to 0.25.
	Scale float32 `yaml:"scale,omitempty" schema:"exclusiveMinimum=0"`
}

TerrainTriplanarDoc configures slope-driven triplanar projection in a TerrainDoc.

func (t *TerrainTriplanarDoc) EffectiveScale() float32

EffectiveScale returns t.Scale, defaulting to 0.25 when zero.

func (t *TerrainTriplanarDoc) EffectiveSharpness() float32

EffectiveSharpness returns t.Sharpness, defaulting to 4.0 when zero.

func (t *TerrainTriplanarDoc) EffectiveSlopeBlend() float32

EffectiveSlopeBlend returns t.SlopeBlend, defaulting to 0.15 when zero.

func (t *TerrainTriplanarDoc) EffectiveSlopeThreshold() float32

EffectiveSlopeThreshold returns t.SlopeThreshold, defaulting to 0.7 when zero.

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 / 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 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 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 ai.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 world3d.NavMesh.

func (tm *TiledNavMesh) FindPathWithOptions(start, goal math3d.Vec3, opts ai.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 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 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 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 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 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 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) ChunkCoord

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

func (tm *TiledNavMesh) TileCoords() []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 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 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 []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 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 ChunkCoord) bool

CrossesTile reports whether r's corridor passes through coord.

func (r TiledNavPathResult) TileCoords() []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.

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

TilemapStreamer bridges world3d.ChunkStreamer[*tilemap.Chunk] onto a sparse chunked tilemap.TileLayer, providing bounded streaming, background generation, hysteresis unloading, and deterministic YAML/JSON persistence of modified chunks without breaking game/tilemap's stability boundary.

func NewTilemapStreamer(cfg TilemapStreamerConfig) (*TilemapStreamer, error)

NewTilemapStreamer constructs a TilemapStreamer backed by a world3d.ChunkStreamer[*tilemap.Chunk]. Call Close when finished to save any loaded modified chunks and stop worker goroutines.

func (s *TilemapStreamer) Close()

Close stops background loader workers and unloads all remaining chunks, saving any modified chunks to Store.

func (s *TilemapStreamer) SaveModified() error

SaveModified persists every currently loaded modified chunk in deterministic order to Store.

func (s *TilemapStreamer) Streamer() *ChunkStreamer[*tilemap.Chunk]

Streamer returns the underlying world3d.ChunkStreamer[*tilemap.Chunk].

func (s *TilemapStreamer) Update(worldX, worldY float64)

Update advances chunk streaming for a 2D world position (worldX, worldY) in tilemap world points.

type TilemapStreamerConfig struct {
	// Map is the Tilemap owning LayerIndex.
	Map *tilemap.Tilemap
	// LayerIndex selects the chunked TileLayer inside Map.Layers.
	LayerIndex int
	// LoadRadius is the Chebyshev chunk radius around the player chunk to load.
	LoadRadius int
	// UnloadRadius is the Chebyshev chunk radius beyond which loaded and in-flight chunks unload/cancel.
	// Defaults to LoadRadius + 1 when smaller than LoadRadius.
	UnloadRadius int
	// MaxIntegrationsPerFrame caps how many completed chunks integrate into Map per Update call (<= 0 means unlimited).
	MaxIntegrationsPerFrame int
	// Workers sets the number of background ChunkStreamer loader goroutines (0 runs synchronously inside Update).
	Workers int
	// Format selects tilemap.ChunkFormatYAML (default) or tilemap.ChunkFormatJSON for Store persistence.
	Format tilemap.ChunkFormat
	// Store persists modified chunks on unload and restores them on reload before invoking Generator.
	// When Workers > 0, Store must be safe for concurrent use (such as tilemap.MemoryChunkStore or tilemap.DirChunkStore).
	Store tilemap.ChunkStore
	// Generator populates a freshly allocated chunk when Store has no saved entry for coord.
	// It must respect ctx cancellation when Workers > 0.
	Generator func(ctx context.Context, coord tilemap.ChunkCoord, chunk *tilemap.Chunk) error
	// OnLoad runs on the Update goroutine after a chunk is installed into Map.Layers[LayerIndex].
	OnLoad func(coord tilemap.ChunkCoord, chunk *tilemap.Chunk)
	// OnUnload runs on the Update/Close goroutine after a chunk is saved (if modified) and removed from Map.Layers[LayerIndex].
	OnUnload func(coord tilemap.ChunkCoord, chunk *tilemap.Chunk)
	// OnError runs on the Update goroutine when loading, generating, or saving a chunk fails.
	OnError func(coord tilemap.ChunkCoord, err error)
}

TilemapStreamerConfig configures a TilemapStreamer that drives a sparse chunked tilemap.TileLayer with a world3d.ChunkStreamer[*tilemap.Chunk].

type WorldPos64 struct {
	X, Y, Z float64
}

WorldPos64 is a double-precision 3D world-space position used for large worlds (tens to hundreds of kilometers) where float32 world coordinates would suffer noticeable precision jitter.

func (p WorldPos64) Add(b WorldPos64) WorldPos64

Add returns p + b.

func (p WorldPos64) ChunkCoord(chunkSize float64) ChunkCoord

ChunkCoord returns the 2D XZ streaming chunk coordinate containing p for a world partitioned into square chunks of size chunkSize.

func (p WorldPos64) Dist(b WorldPos64) float64

Dist returns the Euclidean distance between p and b.

func (p WorldPos64) DistSq(b WorldPos64) float64

DistSq returns the squared Euclidean distance between p and b.

func (p WorldPos64) Sub(b WorldPos64) WorldPos64

Sub returns p - b.