Documentation
¶
Overview ¶
Package spatial finds the 2D objects near an area or inside a view without testing every one, built on NSGo's public core types and the game sprite package:
- Broad-phase indices (Hash and Quadtree) for O(k) area queries, point queries and collision pair generation, allocation-free once warm.
- Viewport culling helpers (Intersects, SpriteBounds, CullSprites, CullBatch, BatchCuller and generic Cull) to skip off-screen work.
Index ¶
- func Cull[T any](view core.Bounds, items []T, boundsOf func(T) core.Bounds, dst []T) []T
- func CullBatch(batch *sprite.Batch, view core.Bounds, d *core.Drawing)
- func CullSprites(view core.Bounds, src []*sprite.Sprite, dst []*sprite.Sprite) []*sprite.Sprite
- func Intersects(a, b core.Bounds) bool
- func SpriteBounds(s *sprite.Sprite) core.Bounds
- type BatchCuller
- type Hash
- func (sh *Hash[ID]) CellSize() float32
- func (sh *Hash[ID]) Clear()
- func (sh *Hash[ID]) Insert(id ID, bounds core.Bounds)
- func (sh *Hash[ID]) Len() int
- func (sh *Hash[ID]) Query(area core.Bounds, out []ID) []ID
- func (sh *Hash[ID]) QueryPairs(fn func(a, b ID))
- func (sh *Hash[ID]) QueryPoint(p core.Point, out []ID) []ID
- func (sh *Hash[ID]) Remove(id ID)
- func (sh *Hash[ID]) Update(id ID, bounds core.Bounds)
- type Quadtree
- func (qt *Quadtree[ID]) Clear()
- func (qt *Quadtree[ID]) Insert(id ID, bounds core.Bounds)
- func (qt *Quadtree[ID]) Len() int
- func (qt *Quadtree[ID]) Query(area core.Bounds, out []ID) []ID
- func (qt *Quadtree[ID]) QueryPoint(p core.Point, out []ID) []ID
- func (qt *Quadtree[ID]) Remove(id ID)
- func (qt *Quadtree[ID]) Update(id ID, bounds core.Bounds)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Cull ¶
Cull appends every item from items whose bounds (computed by boundsOf) intersect view to dst and returns the extended slice. Pass dst[:0] to reuse backing storage with 0 allocations.
Example ¶
Cull keeps only the items whose bounds touch the view, so offscreen objects are not drawn.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/spatial"
"github.com/nsgo-dev/nsgo/core"
)
func box(x, y, w, h core.Points) core.Bounds {
return core.Bounds{Origin: core.Point{X: x, Y: y}, Size: core.Size{Width: w, Height: h}}
}
func main() {
trees := []core.Bounds{box(0, 0, 10, 10), box(500, 0, 10, 10), box(95, 95, 10, 10)}
view := box(0, 0, 100, 100)
visible := spatial.Cull(view, trees, func(b core.Bounds) core.Bounds { return b }, nil)
fmt.Println(len(visible), spatial.Intersects(view, trees[1]))
}
Output: 2 false
func CullBatch ¶
CullBatch draws only the visible sprites from batch whose world-space bounds intersect view into d, preserving Z-order without mutating batch.Sprites.
For zero-allocation repeated draws across frames, use BatchCuller.
func CullSprites ¶
CullSprites appends every sprite from src that is visible (Alpha > 0 and whose world-space SpriteBounds intersect view) to dst and returns the extended slice. Pass dst[:0] to reuse backing storage with 0 allocations.
func Intersects ¶
Intersects reports whether rectangles a and b overlap with positive area using half-open [Origin, Origin+Size) semantics consistent with core.Bounds.Contains. Empty or non-finite rectangles never intersect.
func SpriteBounds ¶
SpriteBounds computes the exact axis-aligned world-space bounding box of s's drawn pixels, accounting for frame trim offsets, origin, scale, flip, and rotation identically to sprite.Batch.Draw.
It returns a zero core.Bounds when s is nil, has a zero-sized frame, or has zero ScaleX or ScaleY.
Types ¶
type BatchCuller ¶
type BatchCuller struct {
// contains filtered or unexported fields
}
BatchCuller draws only visible sprites from a sprite.Batch while reusing internal scratch slices across frames for zero steady-state allocations.
type Hash ¶
type Hash[ID comparable] struct { // contains filtered or unexported fields }
Hash is a uniform 2D grid broad-phase index for fast area queries, point queries, and collision pair generation.
Clear retains all bucket slices and map tables so per-frame rebuilds (Clear + Insert + Query) run with 0 allocations in steady state. Query and QueryPairs iterate cells in deterministic row-major order without iterating over Go maps, deduplicating multi-cell entries via generation counters.
Example ¶
A Hash finds the objects near an area without testing every one, here for collision pairs between enemies.
package main
import (
"fmt"
"slices"
"github.com/nsgo-dev/game/pkg/spatial"
"github.com/nsgo-dev/nsgo/core"
)
func box(x, y, w, h core.Points) core.Bounds {
return core.Bounds{Origin: core.Point{X: x, Y: y}, Size: core.Size{Width: w, Height: h}}
}
func main() {
grid := spatial.NewHash[string](32)
grid.Insert("slime", box(10, 10, 8, 8))
grid.Insert("bat", box(14, 12, 8, 8))
grid.Insert("golem", box(200, 200, 16, 16))
near := grid.Query(box(0, 0, 40, 40), nil)
slices.Sort(near)
fmt.Println(near)
var pairs []string
grid.QueryPairs(func(a, b string) {
if a > b {
a, b = b, a
}
pairs = append(pairs, a+"+"+b)
})
fmt.Println(pairs)
}
Output: [bat slime] [bat+slime]
func NewHash ¶
func NewHash[ID comparable](cellSize float32) *Hash[ID]
NewHash returns a Hash with uniform square cells of cellSize points. If cellSize <= 0 or non-finite, it defaults to 64.
func (*Hash[ID]) Clear ¶
func (sh *Hash[ID]) Clear()
Clear removes all items from the spatial hash while keeping all bucket slice capacities and internal map tables for zero-allocation reuse on subsequent frames.
func (*Hash[ID]) Insert ¶
Insert adds id with bounds to the spatial hash. If id is already present, its bounds are updated in place.
func (*Hash[ID]) Query ¶
Query appends all IDs whose bounds intersect area to out and returns the extended slice. Multi-cell entries are reported once in deterministic order. Pass out[:0] to reuse a buffer across frames with 0 allocations.
func (*Hash[ID]) QueryPairs ¶
func (sh *Hash[ID]) QueryPairs(fn func(a, b ID))
QueryPairs invokes fn once for every unordered pair (a, b) of distinct intersecting items in the spatial hash, without duplicates and with zero allocations. Callers must not mutate the spatial hash during fn.
func (*Hash[ID]) QueryPoint ¶
QueryPoint appends all IDs whose bounds contain p to out and returns the extended slice.
type Quadtree ¶
type Quadtree[ID comparable] struct { // contains filtered or unexported fields }
Quadtree is an adaptive 2D spatial index that recursively partitions a world rectangle into four quadrants.
Each item is placed in the deepest quadrant that completely contains its bounds, so straddling and out-of-world items remain in their parent (or root) without duplication. Internal nodes are stored in a flat pooled slice so Clear + Insert + Query runs with 0 allocations in steady state.
Example ¶
A Quadtree indexes objects across a large world and answers point and area queries.
package main
import (
"fmt"
"slices"
"github.com/nsgo-dev/game/pkg/spatial"
"github.com/nsgo-dev/nsgo/core"
)
func box(x, y, w, h core.Points) core.Bounds {
return core.Bounds{Origin: core.Point{X: x, Y: y}, Size: core.Size{Width: w, Height: h}}
}
func main() {
qt := spatial.NewQuadtree[int](box(0, 0, 1024, 1024), 4, 8)
for i := range 10 {
qt.Insert(i, box(core.Points(i)*100, 0, 10, 10))
}
hits := qt.Query(box(150, 0, 300, 50), nil)
slices.Sort(hits)
fmt.Println(hits, qt.QueryPoint(core.Point{X: 905, Y: 5}, nil))
}
Output: [2 3 4] [9]
func NewQuadtree ¶
func NewQuadtree[ID comparable](world core.Bounds, maxItems, maxDepth int) *Quadtree[ID]
NewQuadtree returns a Quadtree covering world. When a leaf exceeds maxItems and its depth is below maxDepth, it splits into four equal quadrants. Non-positive maxItems or maxDepth default to 8.
func (*Quadtree[ID]) Clear ¶
func (qt *Quadtree[ID]) Clear()
Clear removes all items and collapses all subdivisions while keeping pooled node and slice capacities for zero-allocation reuse.
func (*Quadtree[ID]) Insert ¶
Insert adds id with bounds to the quadtree. If id is already present, its bounds are replaced.
func (*Quadtree[ID]) Query ¶
Query appends all IDs whose bounds intersect area to out and returns the extended slice. Pass out[:0] to reuse a buffer with 0 allocations.
func (*Quadtree[ID]) QueryPoint ¶
QueryPoint appends all IDs whose bounds contain p to out and returns the extended slice.