Documentation
¶
Overview ¶
Package perf provides allocation-free game-loop performance primitives built on NSGo's public core types and the game sprite package:
- Deterministic object pools (Pool, Arena, SlicePool) that reuse memory across frames without dropping entries during garbage collection.
- 2D broad-phase spatial indices (SpatialHash and Quadtree) for O(k) area queries, point queries, and collision pair generation.
- 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 Arena
- func (a *Arena[T]) Add(v T) Handle
- func (a *Arena[T]) All() iter.Seq2[Handle, *T]
- func (a *Arena[T]) Alloc() (Handle, *T)
- func (a *Arena[T]) Cap() int
- func (a *Arena[T]) ForEach(fn func(h Handle, v *T))
- func (a *Arena[T]) Get(h Handle) (*T, bool)
- func (a *Arena[T]) Has(h Handle) bool
- func (a *Arena[T]) Len() int
- func (a *Arena[T]) Remove(h Handle) bool
- func (a *Arena[T]) Reset()
- func (a *Arena[T]) Slice() []T
- type BatchCuller
- type Handle
- type Pool
- 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)
- type SlicePool
- type SpatialHash
- func (sh *SpatialHash[ID]) CellSize() float32
- func (sh *SpatialHash[ID]) Clear()
- func (sh *SpatialHash[ID]) Insert(id ID, bounds core.Bounds)
- func (sh *SpatialHash[ID]) Len() int
- func (sh *SpatialHash[ID]) Query(area core.Bounds, out []ID) []ID
- func (sh *SpatialHash[ID]) QueryPairs(fn func(a, b ID))
- func (sh *SpatialHash[ID]) QueryPoint(p core.Point, out []ID) []ID
- func (sh *SpatialHash[ID]) Remove(id ID)
- func (sh *SpatialHash[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/perf"
"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 := perf.Cull(view, trees, func(b core.Bounds) core.Bounds { return b }, nil)
fmt.Println(len(visible), perf.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 Arena ¶
type Arena[T any] struct { // contains filtered or unexported fields }
Arena is a dense, contiguous object pool with stable generational [Handle]s and O(1) swap-remove. Active values live contiguously in memory for cache-friendly iteration via Arena.ForEach, Arena.All, and Arena.Slice.
Example ¶
An Arena stores values densely and hands out Handles that stay valid until their value is removed, and stop matching after.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/perf"
)
type bullet struct{ X, Y, VX float32 }
func main() {
arena := perf.NewArena[bullet](4, nil)
h1 := arena.Add(bullet{X: 1})
h2 := arena.Add(bullet{X: 2})
arena.Remove(h1)
_, ok := arena.Get(h1)
b, _ := arena.Get(h2)
fmt.Println(arena.Len(), ok, b.X)
}
Output: 1 false 2
func NewArena ¶
NewArena creates an Arena with initial backing capacity for initialCap items. When reset is non-nil, it is invoked on removed or reset elements instead of zeroing them.
func (*Arena[T]) All ¶
All returns an iterator over every live (handle, pointer) pair in dense memory order, supporting early termination with break.
func (*Arena[T]) Alloc ¶
Alloc reserves a slot in the arena and returns its handle and a pointer to the newly reserved element for in-place initialization. The pointer is valid only until the next Add, Alloc, Remove, or Reset.
func (*Arena[T]) ForEach ¶
ForEach invokes fn for every live element in dense memory order. Callers must not add or remove elements while iterating.
func (*Arena[T]) Get ¶
Get resolves h to a pointer to its live element. It returns (nil, false) if h is zero or has been removed. The returned pointer is valid until the next mutation of the arena.
func (*Arena[T]) Remove ¶
Remove deletes the element referenced by h in O(1) time via swap-remove and invalidates h. It returns false if h is already invalid.
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 Handle ¶
type Handle struct {
// contains filtered or unexported fields
}
Handle is a stable generational reference to an element inside an Arena. Its zero value is always invalid.
type Pool ¶
type Pool[T any] struct { // contains filtered or unexported fields }
Pool is a deterministic, single-threaded object pool for game-loop entities such as bullets, enemies, particles, and transient structs.
Unlike sync.Pool, Pool never discards pooled objects on garbage collection: once warmed up, Acquire and Release run in O(1) time with 0 allocations. Pointers returned by Acquire remain stable across pool growth because memory is allocated in fixed chunks.
Example ¶
A Pool reuses objects such as bullets, so firing does not allocate once the pool is warm.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/perf"
)
type bullet struct{ X, Y, VX float32 }
func main() {
pool := perf.NewPool(8, func(b *bullet) { *b = bullet{} })
pool.Prewarm(4)
a := pool.Acquire()
a.VX = 300
b := pool.Acquire()
fmt.Println(pool.Active(), pool.Free())
pool.Release(a)
pool.Release(b)
c := pool.Acquire()
fmt.Println(pool.Active(), c.VX)
}
Output: 2 6 1 0
func NewPool ¶
NewPool creates a Pool pre-populated with initialCap reusable objects.
When reset is non-nil, it is called on each object when released or when Reset is called, allowing callers to clear fields while keeping internal slice capacities. When reset is nil, objects are zeroed on release and Reset.
func (*Pool[T]) Acquire ¶
func (p *Pool[T]) Acquire() *T
Acquire returns a pointer to a pooled object, allocating a new chunk only when no free objects remain.
func (*Pool[T]) Prewarm ¶
Prewarm ensures at least n objects are available in the free list so that subsequent Acquire calls do not allocate.
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/perf"
"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 := perf.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.
type SlicePool ¶
type SlicePool[T any] struct { // contains filtered or unexported fields }
SlicePool is a deterministic pool of reusable []T scratch slices (for query buffers, draw lists, particle emitters, etc.) that never drops slices on GC.
Example ¶
A SlicePool lends out scratch slices for per-frame work and takes them back for reuse.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/perf"
)
func main() {
pool := perf.NewSlicePool[int](4)
s := pool.Acquire(16)
s = append(s, 1, 2, 3)
fmt.Println(len(s), cap(s) >= 16)
pool.Release(s)
fmt.Println(pool.Free(), len(pool.Acquire(8)))
}
Output: 3 true 1 0
func NewSlicePool ¶
NewSlicePool creates a SlicePool that retains up to maxPooled slices. When maxPooled <= 0, the pool retains all released slices without a cap.
func (*SlicePool[T]) Acquire ¶
Acquire returns a zero-length slice with capacity at least minCap, reusing the tightest-fitting pooled slice when available.
type SpatialHash ¶
type SpatialHash[ID comparable] struct { // contains filtered or unexported fields }
SpatialHash 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 SpatialHash 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/perf"
"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 := perf.NewSpatialHash[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 NewSpatialHash ¶
func NewSpatialHash[ID comparable](cellSize float32) *SpatialHash[ID]
NewSpatialHash returns a SpatialHash with uniform square cells of cellSize points. If cellSize <= 0 or non-finite, it defaults to 64.
func (*SpatialHash[ID]) CellSize ¶
func (sh *SpatialHash[ID]) CellSize() float32
CellSize returns the grid cell width and height in points.
func (*SpatialHash[ID]) Clear ¶
func (sh *SpatialHash[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 (*SpatialHash[ID]) Insert ¶
func (sh *SpatialHash[ID]) Insert(id ID, bounds core.Bounds)
Insert adds id with bounds to the spatial hash. If id is already present, its bounds are updated in place.
func (*SpatialHash[ID]) Len ¶
func (sh *SpatialHash[ID]) Len() int
Len returns the number of items currently stored in the spatial hash.
func (*SpatialHash[ID]) Query ¶
func (sh *SpatialHash[ID]) Query(area core.Bounds, out []ID) []ID
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 (*SpatialHash[ID]) QueryPairs ¶
func (sh *SpatialHash[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 (*SpatialHash[ID]) QueryPoint ¶
func (sh *SpatialHash[ID]) QueryPoint(p core.Point, out []ID) []ID
QueryPoint appends all IDs whose bounds contain p to out and returns the extended slice.
func (*SpatialHash[ID]) Remove ¶
func (sh *SpatialHash[ID]) Remove(id ID)
Remove deletes id from the spatial hash. Removing an absent id is a no-op.
func (*SpatialHash[ID]) Update ¶
func (sh *SpatialHash[ID]) Update(id ID, bounds core.Bounds)
Update changes the bounds associated with id. If id is not yet in the spatial hash, Update inserts it. When the item stays within the same grid cells, Update completes in O(1) without touching any buckets.