Documentation
¶
Overview ¶
Package world3d provides 3D world-building primitives for NSGo 3D games: heightmap terrain, 3D GridMaps of modular mesh tiles, procedural foliage/scattered instance fields, and large-world chunk streaming with floating-origin rebasing. Package pathfind3d builds 3D navigation meshes and path-corridor navigation agents on its chunk coordinates.
All positions, normals, rays, and bounding volumes follow package math3d's right-handed Y-up conventions (+X right, +Y up, -Z forward).
Index ¶
- Constants
- Variables
- func BlendTerrainWeights(raw, heights [MaxTerrainLayers]float32, count int, contrast float32) [MaxTerrainLayers]float32
- func EncodeDensityMapPNG(d *DensityMap) ([]byte, error)
- func EncodeFoliage(doc *FoliageDoc) ([]byte, error)
- func EncodeGridMap(doc *GridMapDoc) ([]byte, error)
- func EncodeHeightmapPNG(h *Heightmap) ([]byte, error)
- func EncodeTerrain(doc *TerrainDoc) ([]byte, error)
- func FindGridOrientation(m math3d.Mat4) (uint8, bool)
- func GridOrientationMat4(orient uint8) math3d.Mat4
- func LoadGridMapFS(fsys fs.FS, name string) (*GridMap, *GridMapDoc, error)
- func LoadTerrainFS(fsys fs.FS, name string) (*Heightmap, *TerrainDoc, error)
- func PackLayerWeightMaps(weights ...image.Image) (splat0, splat1 *image.NRGBA, err error)
- func RebaseMat4(m math3d.Mat4, shift math3d.Vec3) math3d.Mat4
- func RotateGridOrientation(orient uint8, axis GridAxis, quarterTurns int) uint8
- func TerrainLODBiasFor(l quality.Level) float32
- func ValidateFoliage(doc *FoliageDoc) error
- func ValidateGridMap(doc *GridMapDoc) error
- func ValidateTerrain(doc *TerrainDoc) error
- type ChunkCoord
- type ChunkStreamer
- type ChunkStreamerConfig
- type DensityMap
- func (d *DensityMap) At(x, y int) float32
- func (d *DensityMap) Clone() *DensityMap
- func (d *DensityMap) EncodePNG(w io.Writer) error
- func (d *DensityMap) Sample(u, v float32) float32
- func (d *DensityMap) Set(x, y int, v float32)
- func (d *DensityMap) ToGray() *image.Gray
- func (d *DensityMap) ToGray16() *image.Gray16
- type FloatingOrigin
- type FoliageBuildOptions
- type FoliageDoc
- type FoliageField
- type FoliageInstance
- type FoliageLayer
- type FoliageLayerDoc
- type GridAxis
- type GridBoxDoc
- type GridCell
- type GridCellDoc
- type GridColliderOptions
- type GridCoord
- type GridHit
- type GridInstanceBatch
- type GridMap
- func (g *GridMap) AddCollidersToWorld(w *physics3d.World, opts GridColliderOptions) []*physics3d.Body
- func (g *GridMap) Bounds() math3d.AABB
- func (g *GridMap) BuildInstances(frustum *math3d.Frustum, out []GridInstanceBatch) []GridInstanceBatch
- func (g *GridMap) BuildStaticBodies(opts GridColliderOptions) []physics3d.Body
- func (g *GridMap) Cell(c GridCoord) (GridCell, bool)
- func (g *GridMap) CellBounds(c GridCoord) math3d.AABB
- func (g *GridMap) CellTransform(c GridCoord, orient uint8) math3d.Mat4
- func (g *GridMap) Clear()
- func (g *GridMap) ClearCell(c GridCoord)
- func (g *GridMap) ColliderBoxes() []math3d.AABB
- func (g *GridMap) CollisionBoxesIn(region math3d.AABB) []math3d.AABB
- func (g *GridMap) Count() int
- func (g *GridMap) EachCell(fn func(c GridCoord, cell GridCell) bool)
- func (g *GridMap) FillBox(minC, maxC GridCoord, tileID uint16, orient uint8)
- func (g *GridMap) MergedColliderBoxes() []math3d.AABB
- func (g *GridMap) Raycast(ray math3d.Ray, maxDist float32) (GridHit, bool)
- func (g *GridMap) SetCell(c GridCoord, tileID uint16, orient uint8)
- func (g *GridMap) ToDoc(name, meshLibrary string) (*GridMapDoc, error)
- type GridMapDoc
- type Heightmap
- func (h *Heightmap) Bounds() math3d.AABB
- func (h *Heightmap) BuildMesh(chunkCol, chunkRow, chunkCols, chunkRows int) TerrainMesh
- func (h *Heightmap) BuildMeshLOD(chunkCol, chunkRow, chunkCols, chunkRows int, lod int, ...) TerrainMesh
- func (h *Heightmap) ChunkBounds(chunkCol, chunkRow, chunkCols, chunkRows int) math3d.AABB
- func (h *Heightmap) Collider() *physics3d.HeightfieldCollider
- func (h *Heightmap) EncodePNG(w io.Writer) error
- func (h *Heightmap) FoliageDensityAt(layer string, x, z float32) (float32, bool)
- func (h *Heightmap) HeightAt(x, z float32) (float32, bool)
- func (h *Heightmap) LayerAt(x, z float32) (TerrainLayerSample, bool)
- func (h *Heightmap) NormalAt(x, z float32) math3d.Vec3
- func (h *Heightmap) Raycast(ray math3d.Ray, maxDist float32) (TerrainHit, bool)
- func (h *Heightmap) SampleHeight(col, row int) float32
- func (h *Heightmap) ToGray16() *image.Gray16
- type MeshLibrary
- type MeshTileDef
- type QualityLevel
- type QualityProfile
- type TerrainDoc
- func (d *TerrainDoc) BuildFoliageLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)
- func (d *TerrainDoc) BuildHeightmap(imgs TerrainImages) (*Heightmap, error)
- func (d *TerrainDoc) BuildLOD(hm *Heightmap) *TerrainLOD
- func (d *TerrainDoc) EffectiveCellSize() float32
- func (d *TerrainDoc) EffectiveChunkSize() int
- func (d *TerrainDoc) EffectiveOrigin() math3d.Vec3
- func (d *TerrainDoc) HasLayerWeightMaps() bool
- func (d *TerrainDoc) LODConfig() TerrainLODConfig
- func (d *TerrainDoc) LayerInfos() []TerrainLayerInfo
- func (d *TerrainDoc) LoadHeightmap(fsys fs.FS) (*Heightmap, error)
- func (d *TerrainDoc) ScatterFoliage(hm *Heightmap, region math3d.AABB, opts FoliageBuildOptions) ([]*FoliageField, error)
- type TerrainEdgeLODs
- type TerrainHeightLayer
- type TerrainHit
- type TerrainImages
- type TerrainLOD
- func (t *TerrainLOD) ChunkBounds(coord ChunkCoord) (math3d.AABB, bool)
- func (t *TerrainLOD) ChunkCells() int
- func (t *TerrainLOD) ChunkCount() int
- func (t *TerrainLOD) ChunkLOD(coord ChunkCoord) (int, bool)
- func (t *TerrainLOD) ChunkWorldSize() float64
- func (t *TerrainLOD) EvictHiddenMeshes()
- func (t *TerrainLOD) GridSize() (cols, rows int)
- func (t *TerrainLOD) InvalidateAll()
- func (t *TerrainLOD) InvalidateChunk(coord ChunkCoord)
- func (t *TerrainLOD) IsChunkActive(coord ChunkCoord) bool
- func (t *TerrainLOD) LODBias() float32
- func (t *TerrainLOD) MaxLOD() int
- func (t *TerrainLOD) SetChunkActive(coord ChunkCoord, active bool)
- func (t *TerrainLOD) SetLODBias(bias float32)
- func (t *TerrainLOD) SetQualityLevel(level quality.Level)
- func (t *TerrainLOD) Stats() TerrainLODStats
- func (t *TerrainLOD) Update(camPos math3d.Vec3, frustum *math3d.Frustum) []TerrainLODChunk
- func (t *TerrainLOD) UpdateWithOrigin(camLocal math3d.Vec3, frustumLocal *math3d.Frustum, origin *FloatingOrigin) []TerrainLODChunk
- type TerrainLODChunk
- type TerrainLODConfig
- type TerrainLODStats
- type TerrainLayerDoc
- type TerrainLayerInfo
- type TerrainLayerSample
- type TerrainMesh
- type TerrainSplatMap
- func LoadTerrainSplatMap(layers []TerrainLayerInfo, maps ...image.Image) (*TerrainSplatMap, error)
- func LoadTerrainSplatMapFromWeights(layers []TerrainLayerInfo, weights []image.Image) (*TerrainSplatMap, error)
- func NewTerrainSplatMapFromRGBA(width, height int, layers []TerrainLayerInfo, splat0, splat1 []byte) (*TerrainSplatMap, error)
- func (s *TerrainSplatMap) Height() int
- func (s *TerrainSplatMap) LayerAt(x, z float32) TerrainLayerSample
- func (s *TerrainSplatMap) LayerCount() int
- func (s *TerrainSplatMap) LayerIndex(name string) int
- func (s *TerrainSplatMap) LayerName(index int) string
- func (s *TerrainSplatMap) LayerWeightImage(layer int) *image.Gray
- func (s *TerrainSplatMap) SampleUV(u, v float32) TerrainLayerSample
- func (s *TerrainSplatMap) SetTexelWeight(layer, x, y int, weight float32)
- func (s *TerrainSplatMap) SplatImages() (splat0, splat1 *image.NRGBA)
- func (s *TerrainSplatMap) TexelWeight(layer, x, y int) float32
- func (s *TerrainSplatMap) Width() int
- type TerrainTriplanarDoc
- type TilemapStreamer
- type TilemapStreamerConfig
- type WorldPos64
Examples ¶
Constants ¶
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 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.
Variables ¶
var ErrInvalidTerrainSplat = errors.New("world3d: invalid terrain splat map")
ErrInvalidTerrainSplat is wrapped by errors returned when constructing or validating a TerrainSplatMap.
Functions ¶
func BlendTerrainWeights ¶
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 ¶
func EncodeDensityMapPNG(d *DensityMap) ([]byte, error)
EncodeDensityMapPNG encodes d as an 8-bit grayscale PNG byte slice.
func EncodeFoliage ¶
func EncodeFoliage(doc *FoliageDoc) ([]byte, error)
EncodeFoliage validates doc and serializes it as deterministic 2-space YAML prefixed with FoliageSchemaComment.
func EncodeGridMap ¶
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 ¶
EncodeHeightmapPNG encodes h as a 16-bit grayscale PNG byte slice.
func EncodeTerrain ¶
func EncodeTerrain(doc *TerrainDoc) ([]byte, error)
EncodeTerrain validates doc and serializes it as deterministic 2-space YAML prefixed with TerrainSchemaComment.
func FindGridOrientation ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
RebaseMat4 applies a floating-origin shift to the translation column of m.
func RotateGridOrientation ¶
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 ¶
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 ¶
func ValidateFoliage(doc *FoliageDoc) error
ValidateFoliage checks that doc conforms to the version 1 foliage schema.
func ValidateGridMap ¶
func ValidateGridMap(doc *GridMapDoc) error
ValidateGridMap checks that doc conforms to the version 1 grid map schema.
func ValidateTerrain ¶
func ValidateTerrain(doc *TerrainDoc) error
ValidateTerrain checks that doc conforms to the version 1 terrain schema.
Types ¶
type ChunkCoord ¶
type ChunkCoord struct {
X, Z int32
}
ChunkCoord identifies a 2D streaming chunk in the XZ world plane.
type ChunkStreamer ¶
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 ¶
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 (*ChunkStreamer[T]) Close ¶
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 (*ChunkStreamer[T]) Get ¶
func (s *ChunkStreamer[T]) Get(coord ChunkCoord) (T, bool)
Get returns the loaded chunk data for coord, or (zero, false) if not loaded.
func (*ChunkStreamer[T]) LoadedChunks ¶
func (s *ChunkStreamer[T]) LoadedChunks() []ChunkCoord
LoadedChunks returns a sorted slice of all currently loaded chunk coordinates.
func (*ChunkStreamer[T]) PendingCount ¶
func (s *ChunkStreamer[T]) PendingCount() int
PendingCount returns the number of chunks currently queued or loading in workers.
func (*ChunkStreamer[T]) ReadyCount ¶
func (s *ChunkStreamer[T]) ReadyCount() int
ReadyCount returns the number of completed chunks awaiting integration on subsequent Update calls.
func (*ChunkStreamer[T]) Update ¶
func (s *ChunkStreamer[T]) Update(worldPos WorldPos64)
Update advances streaming for worldPos:
- Unloads loaded chunks beyond UnloadRadius and cancels stale in-flight loads.
- Integrates up to MaxIntegrationsPerFrame completed chunks (closest first).
- 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 ¶
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 ¶
DensityMap stores normalized [0, 1] 2D scatter density weights in row-major order.
func LoadDensityMapGray ¶
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 ¶
func NewDensityMap(width, height int) *DensityMap
NewDensityMap allocates a zero-initialized DensityMap of width x height samples.
func (*DensityMap) At ¶
func (d *DensityMap) At(x, y int) float32
At returns the density sample at texel (x, y), or 0 if out of range.
func (*DensityMap) Clone ¶
func (d *DensityMap) Clone() *DensityMap
Clone returns a deep copy of d, or nil if d is nil.
func (*DensityMap) EncodePNG ¶
func (d *DensityMap) EncodePNG(w io.Writer) error
EncodePNG encodes d as an 8-bit grayscale PNG image into w.
func (*DensityMap) Sample ¶
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 (*DensityMap) Set ¶
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 (*DensityMap) ToGray ¶
func (d *DensityMap) ToGray() *image.Gray
ToGray converts d into an 8-bit grayscale image with values in [0, 255].
func (*DensityMap) ToGray16 ¶
func (d *DensityMap) ToGray16() *image.Gray16
ToGray16 converts d into a 16-bit grayscale image with values in [0, 65535].
type FloatingOrigin ¶
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).
Example ¶
A FloatingOrigin keeps positions near zero in float32 by moving the origin when the player wanders far, while WorldPos64 keeps the true position in float64.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/nsgo-dev/game/pkg/math3d"
"github.com/nsgo-dev/game/pkg/world3d"
)
// show prints vectors to one decimal, writing a rounded negative zero as 0.
func show(vs ...math3d.Vec3) string {
num := func(f float32) string {
s := strconv.FormatFloat(float64(f), 'f', 1, 32)
if s == "-0.0" {
s = "0.0"
}
return s
}
out := make([]string, len(vs))
for i, v := range vs {
out[i] = "(" + num(v.X) + ", " + num(v.Y) + ", " + num(v.Z) + ")"
}
return strings.Join(out, " ")
}
func main() {
fo := world3d.NewFloatingOrigin(1000)
rebased, shift := fo.Update(math3d.Vec3{X: 1500, Z: 20})
fmt.Println(rebased, show(shift))
fmt.Println(fo.Origin, show(fo.WorldToLocal(world3d.WorldPos64{X: 1600, Z: 20})))
}
Output: true (-1500.0, 0.0, -20.0) {1500 0 20} (100.0, 0.0, 0.0)
func NewFloatingOrigin ¶
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 (*FloatingOrigin) LocalToWorld ¶
func (f *FloatingOrigin) LocalToWorld(local math3d.Vec3) WorldPos64
LocalToWorld converts a local float32 position back into double-precision world coordinates.
func (*FloatingOrigin) Update ¶
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 (*FloatingOrigin) WorldToLocal ¶
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 ¶
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 ¶
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 ¶
func LoadFoliageFS(fsys fs.FS, name string) (*FoliageDoc, error)
LoadFoliageFS reads and validates the YAML foliage definition at name in fsys.
func ParseFoliage ¶
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 ¶
func ParseFoliageWith(data []byte, file string) (*FoliageDoc, error)
ParseFoliageWith is ParseFoliage with an optional source file name attached to errors.
func (*FoliageDoc) BuildLayers ¶
func (d *FoliageDoc) BuildLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)
BuildLayers validates d and converts every entry in d.Layers into a runtime FoliageLayer.
func (*FoliageDoc) ScatterAll ¶
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 ¶
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 ¶
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 (*FoliageField) Bounds ¶
func (f *FoliageField) Bounds() math3d.AABB
Bounds returns the world-space AABB enclosing all scattered instances in f.
func (*FoliageField) ChunkCount ¶
func (f *FoliageField) ChunkCount() int
ChunkCount returns the number of non-empty spatial chunks in f.
func (*FoliageField) CollectVisible ¶
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 (*FoliageField) TotalCount ¶
func (f *FoliageField) TotalCount() int
TotalCount returns the total number of scattered instances stored in f.
type FoliageInstance ¶
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 ¶
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 ¶
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 ¶
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 (FoliageLayerDoc) EffectiveDensity ¶
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 (FoliageLayerDoc) ToLayer ¶
func (l FoliageLayerDoc) ToLayer(opts FoliageBuildOptions) (FoliageLayer, error)
ToLayer converts l into a runtime FoliageLayer using opts.
type GridAxis ¶
type GridAxis int
GridAxis identifies a principal 3D axis for 90-degree GridMap item rotations.
type GridBoxDoc ¶
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 GridCellDoc ¶
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 ¶
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 ¶
type GridCoord struct {
X, Y, Z int
}
GridCoord identifies a discrete 3D cell coordinate in a GridMap.
type GridHit ¶
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 ¶
GridInstanceBatch groups world-space instance transforms sharing the same (MeshID, MaterialID) pair for instanced 3D rendering.
type GridMap ¶
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).
Example ¶
A GridMap places tiles from a mesh library on a 3D grid, as a block or dungeon editor does, and raycasts against them.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/math3d"
"github.com/nsgo-dev/game/pkg/world3d"
)
func main() {
g := world3d.NewGridMap(math3d.Vec3{X: 2, Y: 2, Z: 2}, world3d.NewMeshLibrary())
g.FillBox(world3d.GridCoord{X: 0, Y: 0, Z: 0}, world3d.GridCoord{X: 4, Y: 0, Z: 4}, 1, 0)
fmt.Println(g.Count(), g.Bounds())
hit, ok := g.Raycast(math3d.Ray{Origin: math3d.Vec3{X: 3, Y: 10, Z: 3}, Dir: math3d.Vec3{Y: -1}}, 50)
fmt.Println(ok, hit.Coord, hit.Point.Y)
}
Output: 25 {{0 0 0} {10 2 10}} true {1 0 1} 2
func NewGridMap ¶
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 (*GridMap) AddCollidersToWorld ¶
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 (*GridMap) BuildInstances ¶
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 (*GridMap) BuildStaticBodies ¶
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 (*GridMap) CellBounds ¶
CellBounds returns the world-space axis-aligned bounding box of cell c.
func (*GridMap) CellTransform ¶
CellTransform returns the world-space transform matrix placing a tile at the center of cell c rotated by orient (0..23).
func (*GridMap) ColliderBoxes ¶
ColliderBoxes returns all world-space collider AABBs from every occupied cell in g, in deterministic (Y, Z, X) cell order.
func (*GridMap) CollisionBoxesIn ¶
CollisionBoxesIn returns all world-space collider AABBs from occupied cells that intersect region. Tiles with no ColliderBoxes emit no collision boxes.
func (*GridMap) EachCell ¶
EachCell calls fn for every occupied cell in the GridMap until fn returns false or all cells have been visited.
func (*GridMap) FillBox ¶
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 (*GridMap) MergedColliderBoxes ¶
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 (*GridMap) Raycast ¶
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 (*GridMap) SetCell ¶
SetCell places tileID with orientation orient (0..23) at grid coordinate c. Setting tileID to 0 clears the cell.
func (*GridMap) ToDoc ¶
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 ¶
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 ¶
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 ¶
func ParseGridMapWith(data []byte, file string) (*GridMapDoc, error)
ParseGridMapWith is ParseGridMap with an optional source file name attached to errors.
func (*GridMapDoc) Build ¶
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 (*GridMapDoc) EffectiveCellSize ¶
func (d *GridMapDoc) EffectiveCellSize() math3d.Vec3
EffectiveCellSize returns d.CellSize as a math3d.Vec3, defaulting to (1, 1, 1) when omitted.
func (*GridMapDoc) EffectiveOrigin ¶
func (d *GridMapDoc) EffectiveOrigin() math3d.Vec3
EffectiveOrigin returns d.Origin as a math3d.Vec3, defaulting to the zero vector when omitted.
type Heightmap ¶
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)
Example ¶
A Heightmap is terrain from a grid of heights: HeightAt reads the ground under a point, interpolating between samples, and Raycast finds where a ray meets it.
package main
import (
"fmt"
"strconv"
"strings"
"github.com/nsgo-dev/game/pkg/math3d"
"github.com/nsgo-dev/game/pkg/world3d"
)
// show prints vectors to one decimal, writing a rounded negative zero as 0.
func show(vs ...math3d.Vec3) string {
num := func(f float32) string {
s := strconv.FormatFloat(float64(f), 'f', 1, 32)
if s == "-0.0" {
s = "0.0"
}
return s
}
out := make([]string, len(vs))
for i, v := range vs {
out[i] = "(" + num(v.X) + ", " + num(v.Y) + ", " + num(v.Z) + ")"
}
return strings.Join(out, " ")
}
func main() {
h := &world3d.Heightmap{
Cols: 3, Rows: 3, CellSize: 10, HeightScale: 2,
Heights: []float32{
0, 0, 0,
0, 1, 0,
0, 0, 0,
},
}
y, ok := h.HeightAt(10, 10)
fmt.Println(y, ok)
y, _ = h.HeightAt(5, 10)
fmt.Println(y)
hit, ok := h.Raycast(math3d.Ray{Origin: math3d.Vec3{X: 10, Y: 50, Z: 10}, Dir: math3d.Vec3{Y: -1}}, 100)
fmt.Println(ok, show(hit.Point))
}
Output: 2 true 1 true (10.0, 2.0, 10.0)
func DecodeHeightmapPNG ¶
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 ¶
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 ¶
NewHeightmap allocates a flat (zero-elevation) Heightmap of cols x rows samples with the given cellSize and heightScale.
func (*Heightmap) Bounds ¶
Bounds returns the world-space axis-aligned bounding box enclosing the terrain.
func (*Heightmap) BuildMesh ¶
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 (*Heightmap) BuildMeshLOD ¶
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 (*Heightmap) ChunkBounds ¶
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 (*Heightmap) Collider ¶
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 (*Heightmap) FoliageDensityAt ¶
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 (*Heightmap) HeightAt ¶
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 (*Heightmap) LayerAt ¶
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 (*Heightmap) NormalAt ¶
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 (*Heightmap) Raycast ¶
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 (*Heightmap) SampleHeight ¶
SampleHeight returns the world-space Y height at grid sample (col, row), clamping col and row to valid sample indices.
type MeshLibrary ¶
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 ¶
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 ¶
func NewMeshLibrary() *MeshLibrary
NewMeshLibrary returns an empty MeshLibrary ready to register tile definitions.
func (*MeshLibrary) Add ¶
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 (*MeshLibrary) ByName ¶
func (l *MeshLibrary) ByName(name string) (MeshTileDef, bool)
ByName looks up a tile definition by Name.
func (*MeshLibrary) Get ¶
func (l *MeshLibrary) Get(id uint16) (MeshTileDef, bool)
Get looks up a tile definition by ID.
func (*MeshLibrary) Items ¶
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 (*MeshLibrary) Len ¶
func (l *MeshLibrary) Len() int
Len returns the number of tile definitions registered in the library.
func (*MeshLibrary) Revision ¶
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 ¶
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 QualityLevel ¶
type QualityLevel uint8
QualityLevel selects a built-in foliage density and draw-distance tier.
const ( QualityLow QualityLevel = iota QualityMedium QualityHigh QualityUltra )
func QualityLevelFor ¶
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 ¶
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 ¶
func DefaultQualityProfile(level QualityLevel) QualityProfile
DefaultQualityProfile returns recommended foliage settings for level.
type TerrainDoc ¶
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 ¶
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 ¶
func ParseTerrainWith(data []byte, file string) (*TerrainDoc, error)
ParseTerrainWith is ParseTerrain with an optional source file name attached to errors.
func (*TerrainDoc) BuildFoliageLayers ¶
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 (*TerrainDoc) BuildHeightmap ¶
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 (*TerrainDoc) BuildLOD ¶
func (d *TerrainDoc) BuildLOD(hm *Heightmap) *TerrainLOD
BuildLOD constructs a *TerrainLOD for hm using d's TerrainDoc.LODConfig.
func (*TerrainDoc) EffectiveCellSize ¶
func (d *TerrainDoc) EffectiveCellSize() float32
EffectiveCellSize returns d.CellSize, defaulting to 1 when zero.
func (*TerrainDoc) EffectiveChunkSize ¶
func (d *TerrainDoc) EffectiveChunkSize() int
EffectiveChunkSize returns d.ChunkSize, defaulting to 64 when omitted or zero.
func (*TerrainDoc) EffectiveOrigin ¶
func (d *TerrainDoc) EffectiveOrigin() math3d.Vec3
EffectiveOrigin returns d.Origin as a math3d.Vec3, defaulting to the zero vector when omitted.
func (*TerrainDoc) HasLayerWeightMaps ¶
func (d *TerrainDoc) HasLayerWeightMaps() bool
HasLayerWeightMaps reports whether any layer in d specifies a per-layer WeightMap path.
func (*TerrainDoc) LODConfig ¶
func (d *TerrainDoc) LODConfig() TerrainLODConfig
LODConfig returns a TerrainLODConfig populated from d's ChunkSize.
func (*TerrainDoc) LayerInfos ¶
func (d *TerrainDoc) LayerInfos() []TerrainLayerInfo
LayerInfos converts d.Layers into TerrainLayerInfo metadata (name, UV scale, and height bias) suitable for constructing a TerrainSplatMap.
func (*TerrainDoc) LoadHeightmap ¶
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 (*TerrainDoc) ScatterFoliage ¶
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 ¶
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 ¶
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 ¶
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 (*TerrainHeightLayer) SampleUV ¶
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 ¶
TerrainHit describes the closest intersection between a ray and a Heightmap.
type TerrainImages ¶
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 ¶
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 ¶
func NewTerrainLOD(hm *Heightmap, cfg TerrainLODConfig) *TerrainLOD
NewTerrainLOD constructs a TerrainLOD manager for hm using cfg.
func (*TerrainLOD) ChunkBounds ¶
func (t *TerrainLOD) ChunkBounds(coord ChunkCoord) (math3d.AABB, bool)
ChunkBounds returns the world-space AABB for the chunk at coord.
func (*TerrainLOD) ChunkCells ¶
func (t *TerrainLOD) ChunkCells() int
ChunkCells returns the nominal cell count along each chunk edge.
func (*TerrainLOD) ChunkCount ¶
func (t *TerrainLOD) ChunkCount() int
ChunkCount returns the total number of chunks partitioning the heightmap.
func (*TerrainLOD) ChunkLOD ¶
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 (*TerrainLOD) ChunkWorldSize ¶
func (t *TerrainLOD) ChunkWorldSize() float64
ChunkWorldSize returns the world-space width of a full chunk (ChunkCells * Heightmap.CellSize), suitable for configuring ChunkStreamerConfig.ChunkSize.
func (*TerrainLOD) EvictHiddenMeshes ¶
func (t *TerrainLOD) EvictHiddenMeshes()
EvictHiddenMeshes frees cached TerrainMesh buffers for chunks that were not visible in the most recent Update.
func (*TerrainLOD) GridSize ¶
func (t *TerrainLOD) GridSize() (cols, rows int)
GridSize returns the number of terrain chunks along X (cols) and Z (rows).
func (*TerrainLOD) InvalidateAll ¶
func (t *TerrainLOD) InvalidateAll()
InvalidateAll recomputes every chunk AABB and forces all cached meshes to rebuild as they become visible.
func (*TerrainLOD) InvalidateChunk ¶
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 (*TerrainLOD) IsChunkActive ¶
func (t *TerrainLOD) IsChunkActive(coord ChunkCoord) bool
IsChunkActive reports whether coord is a valid chunk coordinate in t and is currently active.
func (*TerrainLOD) LODBias ¶
func (t *TerrainLOD) LODBias() float32
LODBias returns the current LOD bias.
func (*TerrainLOD) MaxLOD ¶
func (t *TerrainLOD) MaxLOD() int
MaxLOD returns the coarsest LOD index managed by t.
func (*TerrainLOD) SetChunkActive ¶
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 (*TerrainLOD) SetLODBias ¶
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 (*TerrainLOD) SetQualityLevel ¶
func (t *TerrainLOD) SetQualityLevel(level quality.Level)
SetQualityLevel applies TerrainLODBiasFor(level) to t.
func (*TerrainLOD) Stats ¶
func (t *TerrainLOD) Stats() TerrainLODStats
Stats returns summary statistics from the most recent Update or UpdateWithOrigin call.
func (*TerrainLOD) Update ¶
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 (*TerrainLOD) UpdateWithOrigin ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (TerrainLayerDoc) EffectiveColor ¶
func (l TerrainLayerDoc) EffectiveColor() [3]float32
EffectiveColor returns l.Color when set, or linear white [1, 1, 1] when omitted.
func (TerrainLayerDoc) EffectiveNormalScale ¶
func (l TerrainLayerDoc) EffectiveNormalScale() float32
EffectiveNormalScale returns l.NormalScale when set, or 1.0 when omitted.
func (TerrainLayerDoc) EffectiveRoughness ¶
func (l TerrainLayerDoc) EffectiveRoughness() float32
EffectiveRoughness returns l.Roughness when set, 1.0 when MetallicRoughness is set, or DefaultTerrainLayerRoughness (0.85) otherwise.
func (TerrainLayerDoc) EffectiveUVScale ¶
func (l TerrainLayerDoc) EffectiveUVScale() math3d.Vec2
EffectiveUVScale returns l.UVScale when set, or [1, 1] when omitted.
type TerrainLayerInfo ¶
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 ¶
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 (TerrainLayerSample) Weight ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (*TerrainSplatMap) Height ¶
func (s *TerrainSplatMap) Height() int
Height returns the texel height of splat map 0, or 0 for a nil splat map.
func (*TerrainSplatMap) LayerAt ¶
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 (*TerrainSplatMap) LayerCount ¶
func (s *TerrainSplatMap) LayerCount() int
LayerCount returns the number of active layers in s (0 for nil).
func (*TerrainSplatMap) LayerIndex ¶
func (s *TerrainSplatMap) LayerIndex(name string) int
LayerIndex returns the index of the first layer named name, or -1 if not found.
func (*TerrainSplatMap) LayerName ¶
func (s *TerrainSplatMap) LayerName(index int) string
LayerName returns the name of layer index, or "" if out of range.
func (*TerrainSplatMap) LayerWeightImage ¶
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 (*TerrainSplatMap) SampleUV ¶
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 (*TerrainSplatMap) SetTexelWeight ¶
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 (*TerrainSplatMap) SplatImages ¶
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 (*TerrainSplatMap) TexelWeight ¶
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 (*TerrainSplatMap) Width ¶
func (s *TerrainSplatMap) Width() int
Width returns the texel width of splat map 0, or 0 for a nil splat map.
type TerrainTriplanarDoc ¶
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 (*TerrainTriplanarDoc) EffectiveScale ¶
func (t *TerrainTriplanarDoc) EffectiveScale() float32
EffectiveScale returns t.Scale, defaulting to 0.25 when zero.
func (*TerrainTriplanarDoc) EffectiveSharpness ¶
func (t *TerrainTriplanarDoc) EffectiveSharpness() float32
EffectiveSharpness returns t.Sharpness, defaulting to 4.0 when zero.
func (*TerrainTriplanarDoc) EffectiveSlopeBlend ¶
func (t *TerrainTriplanarDoc) EffectiveSlopeBlend() float32
EffectiveSlopeBlend returns t.SlopeBlend, defaulting to 0.15 when zero.
func (*TerrainTriplanarDoc) EffectiveSlopeThreshold ¶
func (t *TerrainTriplanarDoc) EffectiveSlopeThreshold() float32
EffectiveSlopeThreshold returns t.SlopeThreshold, defaulting to 0.7 when zero.
type TilemapStreamer ¶
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 ¶
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 (*TilemapStreamer) Close ¶
func (s *TilemapStreamer) Close()
Close stops background loader workers and unloads all remaining chunks, saving any modified chunks to Store.
func (*TilemapStreamer) SaveModified ¶
func (s *TilemapStreamer) SaveModified() error
SaveModified persists every currently loaded modified chunk in deterministic order to Store.
func (*TilemapStreamer) Streamer ¶
func (s *TilemapStreamer) Streamer() *ChunkStreamer[*tilemap.Chunk]
Streamer returns the underlying world3d.ChunkStreamer[*tilemap.Chunk].
func (*TilemapStreamer) Update ¶
func (s *TilemapStreamer) Update(worldX, worldY float64)
Update advances chunk streaming for a 2D world position (worldX, worldY) in tilemap world points.
type TilemapStreamerConfig ¶
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 ¶
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 (WorldPos64) ChunkCoord ¶
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.
Example ¶
WorldPos64 finds the chunk a position falls in, as a ChunkStreamer does to decide which chunks to load.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/world3d"
)
func main() {
for _, p := range []world3d.WorldPos64{{X: 10, Z: 10}, {X: 130, Z: -1}, {X: 1e6, Z: 0}} {
fmt.Println(p.ChunkCoord(128))
}
}
Output: {0 0} {1 -1} {7812 0}
func (WorldPos64) Dist ¶
func (p WorldPos64) Dist(b WorldPos64) float64
Dist returns the Euclidean distance between p and b.
func (WorldPos64) DistSq ¶
func (p WorldPos64) DistSq(b WorldPos64) float64
DistSq returns the squared Euclidean distance between p and b.