aabbworld

package module
v1.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

aabbworld

Go Version GoDoc License

aabbworld is a Go library for 2D worlds made of axis-aligned boxes (AABBs). It began as a set of operations on the boxes themselves and grew upward from there: a plane with its own edge rules (stop, wrap or open at each edge) and the transformations that move boxes on it, a spatial index over the boxes placed in it, a collision engine that separates the ones that overlap, and a line-of-sight scan. Space is the whole of it; geom and plane are its vocabulary.

Features Β β€’Β  Installation Β β€’Β  Example Β β€’Β  Edges Β β€’Β  Architecture Β β€’Β  Benchmarks Β β€’Β  Documentation

Design Goals

aabbworld is the geometry and the per-tick questions of a simulation, with no opinion about how the simulation stores its entities. It is built around a few principles:

  • The world is a slice. A Space is told its items as []Item β€” whose box, where it lies, what may be done with it β€” and answers questions about them. It fits under any entity system, or none.
  • No hidden costs. Rebuild records the slice and defers indexing to the first query that needs it; several rebuilds in a tick cost one indexing. Boxes are read as they are now, so a collision tick needs no second rebuild for queries to see its pushes.
  • Zero-allocation hot paths. Rebuilding, pairing, solving, querying and scanning reuse their buffers; a steady tick allocates nothing.
  • Edge rules are the plane's business. Wrapping, clamping and leaving are applied by the Space to a box once, and every index and query understands the wrapped pieces that result.
  • Native Go, one small dependency (kjkrol/uid) for entity identifiers, no CGO.

πŸ“¦ Installation

aabbworld requires Go 1.27 or newer.

go get github.com/kjkrol/aabbworld

✨ Key Features

Area What you get
Boxes geom.Vec, geom.AABB: intersection, containment, penetration, axis distance
Plane-aware boxes plane.AABB keeps its size and how far it runs past a wrapping seam; its wrapped pieces follow (VisitFragments, DeepestOverlapWith)
Edge rules Per axis: stop whole, wrap (WrapX, WrapY, Torus) or open (OpenX, OpenY, boxes may leave)
Transformations Place, Move, MoveTo, WrapAABB fold a box into the space under its edge rules and say when it has left
Spatial index Rebuild from a slice, Query by rectangle and Capability mask, seams included
Collisions CollideEngine: pairs every two CanCollide boxes within reach, asks your Handler to confirm each overlap, separates them over a few passes, reports who moved and who left; Config.Field pushes boxes out of the solid ground of a grid through its open sides only
Sight Scan fills a View with what an observer sees through a Cone: entities nearest first, depth samples, or the lit outline; Cone.Transparency lets a forest shorten sight where a wall cuts it; Cone.Eye, Elevation and Ground give sight heights, so a hawk looks over the wall and a hill hides the plain behind it; View.Shadows lists the ground out of sight, holes in a view drawn to its full reach; Cone.Cover walks the walls and forests of a grid cell by cell along each ray instead of holding them as entities

Example

One tick of a small world: move, rebuild, collide, then ask who is where and who sees whom. This is ExampleSpace and runs as a test, so it stays in step with the API.

package main

import (
	"fmt"
	"math"
	"slices"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/collide"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

// printer is a collide.Handler that confirms every pair and says what the engine did.
type printer struct{}

func (printer) Touch(_, _ uid.UID64, pen geom.Vec) (geom.Vec, bool) { return pen, true }
func (printer) Contact(a, b uid.UID64, pen geom.Vec) {
	fmt.Printf("contact %d-%d, penetration %s\n", a, b, pen)
}
func (printer) Moved(id uid.UID64, box plane.AABB) { fmt.Printf("moved %d to %s\n", id, box) }

func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 100, Height: 100, Edges: aabbworld.Torus, BucketSize: 16,
	})
	if err != nil {
		panic(err)
	}

	// The world as a slice: whose box, where it lies, what may be done with it.
	items := []aabbworld.Item{
		{ID: 1, Box: plane.NewAABB(geom.NewVec(10, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 2, Box: plane.NewAABB(geom.NewVec(24, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 3, Box: plane.NewAABB(geom.NewVec(60, 10), 10, 10), Caps: aabbworld.CanCollide | aabbworld.Static},
	}
	for i := range items {
		space.Place(&items[i].Box)
	}
	engine := space.CollideEngine(printer{}, collide.Config{Reach: 0.5, Iterations: 8})

	// Tick: box 2 drifts left into box 1, the space is told, the engine separates them.
	space.Move(&items[1].Box, geom.NewVec(-6, 0))
	space.Rebuild(items)
	engine.Tick()

	// Query sees the boxes where the engine left them.
	var inQuarter []uid.UID64
	space.Query(geom.NewAABBAt(geom.NewVec(0, 0), 50, 50), aabbworld.AnyCapability, func(id uid.UID64) {
		inQuarter = append(inQuarter, id)
	})
	slices.Sort(inQuarter)
	fmt.Println("in the top-left quarter:", inQuarter)

	// Sight: what box 1 sees looking right.
	var view aabbworld.View
	cone := aabbworld.Cone{Direction: geom.NewVec(1, 0), HalfAngle: math.Pi / 8, Radius: 60}
	if space.Scan(1, cone, &view) {
		view.Entities(func(id uid.UID64, dist float64) { fmt.Printf("1 sees %d at distance %.0f\n", id, dist) })
	}
}
contact 1-2, penetration (-2,0)
moved 1 to {(9,10) (19,20)}
moved 2 to {(19,10) (29,20)}
in the top-left quarter: [1 2]
1 sees 2 at distance 5

Tick lifecycle

  1. Move the boxes with Space.Move (or MoveTo); the edge rules are applied to each.
  2. Rebuild with the items as they now stand. This is the one stamp a Space needs: it records the slice and which id sits where, and indexes lazily.
  3. Tick the engine. Every two CanCollide boxes within Reach of each other are paired; each overlapping pair is put to Handler.Touch, which may confirm it, refine the penetration, or veto it; confirmed pairs are separated over up to Iterations passes and reported by Contact; every pushed box is reported once by Moved, or listed by Engine.Left β€” with the box it came to rest at β€” when the push took it out through an open edge.
  4. Ask. Query and Scan see the pushed boxes as they are now.

Items must stay put between rebuilds β€” their boxes may move, but the slice may not grow, shrink or reorder without a Rebuild.

Edges

Edges says what a box does at each edge of the world, per axis. The zero value stops it whole. WrapX and WrapY make an axis periodic: a box leaving by one edge comes back through the opposite one. OpenX and OpenY let a box leave; Place and Move return false once it is wholly outside, and it drops out of the index. Torus wraps both axes. An axis cannot both wrap and be open.

Conceptually a torus glues the top edge of the plane to the bottom, then the left edge to the right; this seam-stitching turns the rectangle into the surface shown below.

Torus

A box straddling a seam is held as its main piece plus up to three wrapped pieces, and every index and query understands them. This program moves a 2Γ—2 box at the origin of a 16Γ—16 torus by (-1,-1), so it wraps past the right and bottom edges and splits into the pieces plotted below (it is ExampleSpace_Move):

Wrapped AABB fragments

space, _ := aabbworld.NewSpace(aabbworld.Config{Width: 16, Height: 16, Edges: aabbworld.Torus, BucketSize: 4})

items := []aabbworld.Item{{ID: uid.UID64(1), Box: space.WrapAABB(geom.NewAABBAt(geom.NewVec(0, 0), 2, 2))}}
box := &items[0].Box
space.Move(box, geom.NewVec(-1, -1))
space.Rebuild(items)

fmt.Printf("New position: %s\n", box)
box.VisitFragments(func(pos plane.FragPosition, piece geom.AABB) bool {
	fmt.Printf("- Fragment %d: %s\n", pos, piece)
	return true
})
New position: {(15,15) (16,16)}
- Fragment 1: {(0,15) (1,16)}
- Fragment 2: {(15,0) (16,1)}
- Fragment 3: {(0,0) (1,1)}

Architecture

The packages form a strict acyclic graph; each imports only the layers below it. Every package has a doc.go describing what it brings.

Package Responsibility
github.com/kjkrol/uid 64-bit generational entity identifiers; a Space never mints one, it only names what it was told
geom The vocabulary: Vec and AABB, with intersection, containment, penetration and axis distance; no notion of a world
plane A box as a Space holds it: AABB with a Size and an Overhang, its wrapped pieces (VisitFragments), the deepest Overlap of two boxes
internal/plane The surface behind a Space: Edges rules and what they do to a box β€” Translate, Expand, WrapAABB, Left
internal/spatial The index: Grid over a slice of items with lazily built cells for Query and a counting-sorted sweep for Pairs; Capability, Resolution
internal/raycast Sight: a cone scan over any queryable index β€” the angular sweep, shadows, and the View it fills
collide The public contract of a collision engine: Config, Handler, Engine
internal/collide The engine behind it: Pairs from the grid β†’ Solver β†’ Handler, and who Left through an open edge
aabbworld (public) The package you import: Space, Item, Capability, Edges, Config, View, Cone; wires the rest together
geom ──► plane ──► internal/plane ──► internal/spatial ──► internal/collide ──┐
  β”‚        β”‚                                                                  β”œβ”€β–Ί aabbworld
  β”‚        └──► collide ───────────────────────────────────────────────────────
  └───────────► internal/raycast β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⏱️ Performance

Measured on an Intel i5-8265U (see BENCHMARKS.md); every path below reports 0 allocs/op.

Operation Scene Cost
Collision tick (pair, ask, separate) 8,388 boxes, 10Γ—10 each, covering 20% of a 2048Γ—2048 torus 1.78 ms
Collision tick 33,554 boxes, 5Γ—5 each, covering 20% of the same torus 8.6 ms
Rebuild + pairs + 8 queries 8,388 boxes, 5Γ—5 each, on a 1024Γ—1024 torus 1.23 ms
Solve confirmed pairs 13,547 candidate pairs, 3,763 contacts 4.25 ms
Scan a 90Β° cone and list what it sees 1,000 entities in sight range 26.7 Β΅s
Scan a 90Β° cone through see-through entities, list and outline 1,000 entities, 3 in 10 at Ο„ = 0.5 32.4 Β΅s
The same scan with heights over a 32-unit heightfield 1,000 entities, 3 in 10 at Ο„ = 0.5, ground sampled every 32 112 Β΅s (3.2Γ— the scan without heights)
Fold a box across the far corner (WrapAABB) torus 31 ns

Deep dive: per-scene tables, what each benchmark measures, and what the numbers taught us (why the index keeps two layouts, why Rebuild is lazy) are in BENCHMARKS.md.

make bench

Projects using aabbworld

  • gram β€” a game engine over the GOKe ECS and Ebitengine (formerly gokebiten); its world, collision and vision plugins are built on Space.

πŸ“– Documentation

Contributing

Commit prefixes and conventions are in Contributor Recommendations.

License

MIT

Documentation ΒΆ

Overview ΒΆ

Package aabbworld is a 2D world of axis-aligned boxes: the boxes themselves, a plane with its own edge rules, a spatial index over the boxes placed in it, and the questions a simulation asks of them each tick β€” who is near whom, who is pushing whom apart, who sees what.

It began as a library of operations on the boxes (packages geom and plane) and grew upward from there: a plane the boxes move on (stop, wrap or open at each edge), a grid that indexes them, a collision engine that separates the ones that overlap, and a line-of-sight scan. Space is the whole of it; geom and plane are its vocabulary. It knows nothing of any entity system: it is told the world as a slice and answers questions about it.

Space and Item ΒΆ

A Space is built once by NewSpace from a Config: the world's size, what happens at its edges, and the side of one grid cell. It is then told the world by Space.Rebuild, as a slice of Item β€” whose box it is (a uid.UID64), where it lies (a plane.AABB), and what may be done with it (a Capability).

The items are a snapshot the caller owns. A Space keeps the slice it was last handed and reads the boxes in it as they are now, so the caller may move them between Rebuilds; what it may not do is add, drop or reorder items without a Rebuild. Rebuild itself is cheap: it records the slice and which id sits where, and leaves indexing to the first query that needs it, so several Rebuilds in a tick cost one indexing.

Edges ΒΆ

Edges says what a box does at each edge of the world, per axis. The zero value stops it whole: a box is clamped so it never leaves. WrapX and WrapY make the axis periodic β€” a box leaving by one edge comes back through the opposite one, and while it straddles the seam it is held as a main box plus up to three wrapped pieces (see plane.AABB.VisitFragments). OpenX and OpenY let a box leave; once wholly outside it is reported gone by Space.Place and Space.Move and dropped from the index. Torus wraps on both axes. An axis cannot both wrap and be open.

Space.Place, Space.Move and Space.MoveTo apply those rules to a box; Space.WrapAABB folds any rectangle into the space the same way.

Capability ΒΆ

A Capability is a set of up to eight bits that says what may be done with an item. Every question names the bits it wants and is answered only with items sharing at least one of them; AnyCapability accepts everything, Plain is geometry and nothing more. CanCollide is what a collision engine pairs up; Static marks a side a contact never shifts; Sensor marks one that is detected but separates nothing.

Tick lifecycle ΒΆ

One tick of a simulation reads:

  1. Move the boxes: Space.Move on each, under the edge rules.
  2. Space.Rebuild with the items as they now stand.
  3. collide.Engine.Tick on the engine built by Space.CollideEngine: every two CanCollide boxes within reach of each other are paired, each overlapping pair is put to the handler's Touch, confirmed pairs are separated over a few passes and reported by Contact, and every box that was pushed is reported once by Moved β€” unless the push took it out through an open edge, in which case it is listed by collide.Engine.Left instead, with the box it came to rest at. With collide.Config.Field the engine also pushes every movable box out of the solid ground of a grid, in the same passes.
  4. Ask: Space.Query and Space.Scan see the pushed boxes as they are now; no further Rebuild is owed for that.

Queries and sight ΒΆ

Space.Query calls back for every indexed piece intersecting a rectangle, seams included β€” a box straddling a seam may be reported once per piece. Space.Scan fills a View with what one observer sees through a Cone: the entities in sight, nearest first (View.Entities), the reach of sight at evenly spaced angles (View.Depths), or the lit region as a fan of points (View.Outline). A View is a reusable buffer for one goroutine.

Sight has a budget of the cone's radius along every angle. An empty stretch costs its length; a stretch through an entity of transparency Ο„ costs its length divided by Ο„; an entity at Ο„ ≀ 0 blocks sight where it is met. A forest at Ο„ = 0.5 is thus looked through at half the reach, a wall is not looked through at all. Cone.Transparency gives Ο„ per entity and is nil by default, when everything blocks. Every entity sight reaches is seen, a forest looked into as much as a wall looked at.

Sight has heights once Cone.Elevation or Cone.Ground is set: the eye is Cone.Eye up, an entity spans its bottom to its top, the ground lies at Cone.Ground of a point and is sampled every Cone.GroundStep along a ray. An entity is seen when the straight line from the eye to its top clears the ground and every nearer blocking entity's band, within the budget β€” a see-through entity charges only the stretch the line spends inside its band. The reach of an angle is the farthest lit ground, so a hawk looks over a wall the walker beside it is stopped by, and a hill hides the plain behind it from the lowland alone. View.Shadows lists the stretches of ground an observer cannot see within the radius, so a view with heights can be drawn to its full reach with holes where the ground is out of sight. Details are in internal/raycast.

Ground on a grid ΒΆ

Walls, forests and rock laid out on a grid need not be entities. Cone.Cover is a CoverField: for every ray the scan asks its owner for the stretches of the ray inside cells with cover β€” where the ray enters and leaves each cell, the band the cover spans, how see-through it is β€” and treats them as it treats entities, budget, walls and shadows alike; they are never listed as seen. The owner walks its cells exactly, so on a plane nothing behind a wall is read, and the cost of a scan follows the cells the rays cross, not how much cover the world holds or how it is laid out. collide.Config.Field is a collide.SolidField: for every movable box the engine asks for the solid boxes of the ground around it, with the sides of each that face open ground, and pushes the box out only through those β€” a box sliding along a wall of many cells never catches on a seam. A collide.FieldHandler hears of each contact with the ground once per entity and cell a tick.

Package dependencies ΒΆ

The packages form a strict acyclic graph. Each layer imports only layers below it:

Layer 0   geom              β€” the vocabulary: Vec, AABB
Layer 1   plane             β€” AABB with a Size and an Overhang, wrapped pieces, Overlap        (β†’ geom)
Layer 2   internal/plane    β€” Surface: the edge rules; Translate, Expand, WrapAABB, Left      (β†’ geom, plane)
Layer 3   internal/spatial  β€” Grid: the items, lazy cells for Query, a sweep for Pairs;
                              Capability, Resolution                                          (β†’ geom, plane, internal/plane)
          internal/raycast  β€” View: a cone scan over any queryable index, shadows and depths  (β†’ geom)
          collide           β€” the public contract of an engine: Config, Handler, Engine       (β†’ geom, plane)
Layer 4   internal/collide  β€” Engine over a Grid: Pairs β†’ Solver β†’ Handler; Left               (β†’ geom, plane, internal/plane, internal/spatial)
Layer 5   aabbworld         β€” Space, Item, Capability, Edges, Config, View, Cone: the package
                              you import, wiring the rest together                           (β†’ all of the above)

Expressed as a directed graph (arrow = "is imported by"):

geom ──► plane ──► internal/plane ──► internal/spatial ──► internal/collide ──┐
  β”‚        β”‚                                                                  β”œβ”€β–Ί aabbworld
  β”‚        └──► collide ───────────────────────────────────────────────────────
  └───────────► internal/raycast β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

github.com/kjkrol/uid is an external module used throughout for 64-bit generational entity identifiers; a Space never mints one, it only names what it was told.

Index ΒΆ

Examples ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type Capability ΒΆ

type Capability uint8

Capability is what may be done with an entity, as a set of up to eight bits β€” a question names the bits it wants, and only entities sharing one are answered with.

const (
	// Plain is an entity that is nothing but geometry; the zero value.
	Plain Capability = 0
	// CanCollide is an entity that takes part in collisions β€” what a CollideEngine pairs up.
	CanCollide Capability = 1 << 1
	// Static is an entity nothing shifts; a contact pushes only the other side.
	Static Capability = 1 << 2
	// Sensor is an entity only ever detected; a contact with it separates nothing.
	Sensor Capability = 1 << 3
	// AnyCapability accepts every entity.
	AnyCapability Capability = 0xFF
)

type Cone ΒΆ

type Cone struct {
	Direction geom.Vec
	HalfAngle float64 // below Ο€
	Radius    float64
	// Transparency is Ο„ per entity: 1 as empty, 0.5 costs twice its depth, ≀ 0 blocks; nil blocks all.
	Transparency func(id uid.UID64) float64
	// Eye is the height the observer looks from; it matters once Elevation or Ground is set.
	Eye float64
	// Elevation is the bottom and top of each entity; nil spans every entity over all heights.
	Elevation func(id uid.UID64) (bottom, top float64)
	// Ground is the height of the ground at a point, sampled every GroundStep along a ray (0: a
	// sixteenth of Radius); nil is flat ground at 0.
	Ground     func(p geom.Vec) float64
	GroundStep float64
	// Cover is the ground cover of a world on a grid β€” walls, forests β€” walked cell by cell along
	// each ray instead of being entities in the Space; nil is none.
	Cover CoverField
}

Cone bounds a visibility query: a direction, a half-angle either side of it, how far it reaches, how see-through each entity is and, when sight has heights, where the eye is and how the world stands. The budget model behind Transparency and the sightlines behind Eye, Elevation and Ground are in the package doc.

type Config ΒΆ

type Config struct {
	// Width and Height of the world, in world units.
	Width, Height uint32
	// Edges is what happens to a box at the edges of the world; the zero value stops it whole.
	Edges Edges
	// BucketSize is the side of one grid cell in world units, rounded up to a power of two.
	BucketSize uint32
}

Config sizes a Space.

type CoverField ΒΆ added in v1.9.0

type CoverField = iraycast.CoverField

CoverField is what stands on the cells of a grid and holds sight back, as a ray meets it: Walk follows the ray from origin along the unit dir for length and calls visit, nearest first, for every stretch inside a cell with cover β€” where the ray enters and leaves the cell, the band the cover spans (bottom, top; Β±Inf without heights) and how see-through it is (tau as Transparency: ≀ 0 blocks). visit returning false ends the walk. The owner of the grid walks it exactly (a DDA over its cells), so what lies behind a wall on a plane is never read.

type Edges ΒΆ

type Edges uint8

Edges is what happens to a box at the edges of the world, per axis; zero stops it whole.

const (
	// WrapX returns a box leaving by the left or right edge through the opposite one.
	WrapX Edges = 1 << iota
	// WrapY returns a box leaving by the top or bottom edge through the opposite one.
	WrapY
	// OpenX lets a box leave by the left or right edge; wholly outside, it is dropped from the index.
	OpenX
	// OpenY lets a box leave by the top or bottom edge; wholly outside, it is dropped from the index.
	OpenY
	// Torus wraps on both axes.
	Torus = WrapX | WrapY
)

func (Edges) WrapsX ΒΆ

func (e Edges) WrapsX() bool

WrapsX reports whether the left and right edges wrap.

func (Edges) WrapsY ΒΆ

func (e Edges) WrapsY() bool

WrapsY reports whether the top and bottom edges wrap.

type Item ΒΆ added in v1.5.0

type Item struct {
	ID   uid.UID64
	Box  plane.AABB
	Caps Capability
}

Item is one box a Rebuild hands the Space: whose it is, where it lies, what may be done with it.

type Shadow ΒΆ added in v1.8.0

type Shadow struct {
	Sample   int
	From, To float32
}

Shadow is a stretch of ground along one of the angles a View reads, From to To away from the observer, that the observer cannot see; Sample is the angle's index, as in Depths.

type Space ΒΆ

type Space struct {
	Config
	// contains filtered or unexported fields
}

Space is a plane with edge rules and a grid over the items of its last Rebuild, read as they are now: a Tick that pushes them is seen by the next Query without another Rebuild.

Example ΒΆ

ExampleSpace is one tick of a small world: move, rebuild, collide, then ask who is where and who sees whom.

package main

import (
	"fmt"
	"math"
	"slices"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/collide"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

// printer is a collide.Handler that confirms every pair and says what the engine did.
type printer struct{}

func (printer) Touch(_, _ uid.UID64, pen geom.Vec) (geom.Vec, bool) { return pen, true }
func (printer) Contact(a, b uid.UID64, pen geom.Vec) {
	fmt.Printf("contact %d-%d, penetration %s\n", a, b, pen)
}
func (printer) Moved(id uid.UID64, box plane.AABB) { fmt.Printf("moved %d to %s\n", id, box) }

// ExampleSpace is one tick of a small world: move, rebuild, collide, then ask who is where and
// who sees whom.
func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 100, Height: 100, Edges: aabbworld.Torus, BucketSize: 16,
	})
	if err != nil {
		panic(err)
	}

	// The world as a slice: whose box, where it lies, what may be done with it.
	items := []aabbworld.Item{
		{ID: 1, Box: plane.NewAABB(geom.NewVec(10, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 2, Box: plane.NewAABB(geom.NewVec(24, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 3, Box: plane.NewAABB(geom.NewVec(60, 10), 10, 10), Caps: aabbworld.CanCollide | aabbworld.Static},
	}
	for i := range items {
		space.Place(&items[i].Box)
	}
	engine := space.CollideEngine(printer{}, collide.Config{Reach: 0.5, Iterations: 8})

	// Tick: box 2 drifts left into box 1, the space is told, the engine separates them.
	space.Move(&items[1].Box, geom.NewVec(-6, 0))
	space.Rebuild(items)
	engine.Tick()

	// Query sees the boxes where the engine left them.
	var inQuarter []uid.UID64
	space.Query(geom.NewAABBAt(geom.NewVec(0, 0), 50, 50), aabbworld.AnyCapability, func(id uid.UID64) {
		inQuarter = append(inQuarter, id)
	})
	slices.Sort(inQuarter)
	fmt.Println("in the top-left quarter:", inQuarter)

	// Sight: what box 1 sees looking right.
	var view aabbworld.View
	cone := aabbworld.Cone{Direction: geom.NewVec(1, 0), HalfAngle: math.Pi / 8, Radius: 60}
	if space.Scan(1, cone, &view) {
		view.Entities(func(id uid.UID64, dist float64) { fmt.Printf("1 sees %d at distance %.0f\n", id, dist) })
	}
}
Output:
contact 1-2, penetration (-2,0)
moved 1 to {(9,10) (19,20)}
moved 2 to {(19,10) (29,20)}
in the top-left quarter: [1 2]
1 sees 2 at distance 5

func NewSpace ΒΆ

func NewSpace(cfg Config) (*Space, error)

NewSpace builds a Space, fitting the world into the nearest power-of-two grid.

func (*Space) Bounds ΒΆ

func (s *Space) Bounds() (width, height uint32, edges Edges)

Bounds is the world's size and what happens at its edges.

func (*Space) CollideEngine ΒΆ added in v1.5.0

func (s *Space) CollideEngine(handler collide.Handler, cfg collide.Config) collide.Engine

CollideEngine builds an engine over the Space's CanCollide boxes, reporting to handler.

func (*Space) Move ΒΆ added in v1.5.0

func (s *Space) Move(box *plane.AABB, delta geom.Vec) bool

Move moves box by delta under the edge rules; false once it has left by an open edge.

Example ΒΆ
package main

import (
	"fmt"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 16, Height: 16, Edges: aabbworld.Torus, BucketSize: 4,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	items := []aabbworld.Item{{ID: uid.UID64(1), Box: space.WrapAABB(geom.NewAABBAt(geom.NewVec(0, 0), 2, 2))}}
	box := &items[0].Box
	space.Move(box, geom.NewVec(-1, -1))
	space.Rebuild(items)

	fmt.Printf("New position: %s\n", box)
	box.VisitFragments(func(pos plane.FragPosition, piece geom.AABB) bool {
		fmt.Printf("- Fragment %d: %s\n", pos, piece)
		return true
	})
}
Output:
New position: {(15,15) (16,16)}
- Fragment 1: {(0,15) (1,16)}
- Fragment 2: {(15,0) (16,1)}
- Fragment 3: {(0,0) (1,1)}

func (*Space) MoveTo ΒΆ

func (s *Space) MoveTo(box *plane.AABB, to geom.Vec) bool

MoveTo puts box with its top-left at to, under the edge rules; false once it has left that way.

func (*Space) Place ΒΆ added in v1.5.0

func (s *Space) Place(box *plane.AABB) bool

Place puts a fresh box under the edge rules; false if it lies wholly past an open edge.

func (*Space) Query ΒΆ

func (s *Space) Query(box geom.AABB, want Capability, fn func(id uid.UID64)) int

Query calls fn for every indexed piece in box sharing want, seams included, and returns how many.

func (*Space) Rebuild ΒΆ added in v1.5.0

func (s *Space) Rebuild(items []Item)

Rebuild hands the Space items, which must stay put until the next Rebuild. Indexing waits for the first Query or Scan that needs it, so several Rebuilds in a row cost one indexing.

func (*Space) Scan ΒΆ

func (s *Space) Scan(observer uid.UID64, cone Cone, v *View) bool

Scan fills v with what observer sees through cone and reports whether it could.

func (*Space) WrapAABB ΒΆ

func (s *Space) WrapAABB(box geom.AABB) plane.AABB

WrapAABB folds any rectangle into the space: wrapped pieces on a wrapping axis, else clipped.

type View ΒΆ

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

View is one observer's line of sight: filled by Space.Scan, then read as many ways as needed. The zero value is ready; it must not be copied once scanned, and serves one goroutine.

Example ΒΆ
package main

import (
	"fmt"
	"math"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 1000, Height: 1000,
		BucketSize: 256,
	})
	if err != nil {
		panic(err)
	}

	const guard = uid.UID64(1)
	space.Rebuild([]aabbworld.Item{
		{ID: guard, Box: plane.NewAABB(geom.NewVec(100, 100), 10, 10)},
		{ID: uid.UID64(2), Box: plane.NewAABB(geom.NewVec(300, 100), 10, 10)},
		{ID: uid.UID64(3), Box: plane.NewAABB(geom.NewVec(500, 100), 10, 10)},
	})

	cone := aabbworld.Cone{
		Direction: geom.NewVec(1.0, 0.0),
		HalfAngle: math.Pi / 6,
		Radius:    600,
	}

	var view aabbworld.View
	var fog []geom.Vec

	grew := 0
	for tick := 1; tick <= 3; tick++ {
		before := cap(fog)
		if !space.Scan(guard, cone, &view) {
			continue
		}

		view.Entities(func(id uid.UID64, dist float64) {
			if tick == 1 {
				fmt.Printf("sees %d at %.0f\n", id, dist)
			}
		})

		fog = view.Outline(0, fog[:0])
		if cap(fog) != before {
			grew++
		}
	}
	fmt.Printf("outline buffer grew %d time(s) over 3 ticks\n", grew)
}
Output:
sees 2 at 195
outline buffer grew 1 time(s) over 3 ticks

func (*View) Depths ΒΆ

func (v *View) Depths(k int, dst []float32) []float32

Depths appends to dst the reach at k β‰₯ 2 angles evenly spaced across the cone.

func (*View) Entities ΒΆ

func (v *View) Entities(fn func(id uid.UID64, dist float64)) int

Entities calls fn for every entity in view, nearest first, and returns how many.

func (*View) Outline ΒΆ

func (v *View) Outline(maxArcStep float64, dst []geom.Vec) []geom.Vec

Outline appends the lit region to dst as a fan from the observer; maxArcStep 0 picks a default.

func (*View) Shadows ΒΆ added in v1.8.0

func (v *View) Shadows(k int, dst []Shadow) []Shadow

Shadows appends to dst the stretches of ground the observer cannot see within the radius, at the same k β‰₯ 2 angles as Depths: with heights every run of hidden ground β€” behind a crest, in a wall's shadow, past a cliff β€” up to where ground is lit again; on a plane, the reach to the radius.

Directories ΒΆ

Path Synopsis
Package collide is the contract of a Space's collision engine: what it is told (Config), whom it reports to (Handler), and what a caller drives (Engine).
Package collide is the contract of a Space's collision engine: what it is told (Config), whom it reports to (Handler), and what a caller drives (Engine).
Package geom holds the 2D vocabulary of aabbworld: Vec, a point or a displacement, and AABB, an axis-aligned box.
Package geom holds the 2D vocabulary of aabbworld: Vec, a point or a displacement, and AABB, an axis-aligned box.
internal
collide
Package collide is the engine behind the public collide contract: it finds the overlapping items of one grid, separates them and reports as it goes.
Package collide is the engine behind the public collide contract: it finds the overlapping items of one grid, separates them and reports as it goes.
plane
Package plane is the surface behind a Space: the edge rules of a bounded plane or a torus, and what they do to the public plane's boxes β€” folding, moving, growing, and telling when one has left.
Package plane is the surface behind a Space: the edge rules of a bounded plane or a torus, and what they do to the public plane's boxes β€” folding, moving, growing, and telling when one has left.
raycast
Package raycast is the state and the algorithm behind the public View of package aabbworld: what one observer sees through a cone, worked out over any index that can be queried by rectangle.
Package raycast is the state and the algorithm behind the public View of package aabbworld: what one observer sees through a cone, worked out over any index that can be queried by rectangle.
spatial
Package spatial is the index behind a Space: a cell grid over a slice of items, answering range queries and finding every two items close enough to matter.
Package spatial is the index behind a Space: a cell grid over a slice of items, answering range queries and finding every two items close enough to matter.
Package plane is a box as a Space holds it: a geom.AABB that knows its own size and how far it runs past the far edges of a wrapping world, so that its wrapped pieces follow from it.
Package plane is a box as a Space holds it: a geom.AABB that knows its own size and how far it runs past the far edges of a wrapping world, so that its wrapped pieces follow from it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL