aabbworld

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 8 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

GOKG

aka "Golang kjkrol Geometry"

GOKG is a Go toolkit focused on practical 2D computational geometry. It splits into two packages: geom supplies numeric vectors (Vec), axis-aligned bounding boxes (AABB), and vector math; plane wraps those primitives in boundary-aware Space2D implementations (Euclidean2D and Toroidal2D) that keep boxes canonical to a surface. plane.AABB caches size and fragments so translations, wraps, and clamps obey the space’s rules without duplicating bookkeeping. The library stays focused on mathematical geometry; rendering or UI concerns live in neighbouring packages.

Space2D boundary handling

  • Euclidean2D spaces clamp boxes to the viewport while keeping their size consistent, so expansions never bleed beyond the defined world.

  • Toroidal2D spaces automatically wrap boxes that cross an edge and split them into fragments that continue on the opposite side, making toroidal worlds easy to model. Conceptually, glue the top edge of the plane to the bottom edge, then the left edge to the right; this seam-stitching turns the rectangle into the torus shown in the animation below.

    Torus

  • The helper methods Translate and Expand renormalise boxes on every call, updating cached fragments and ensuring touch/collision queries remain accurate without extra bookkeeping.

Usage example

This snippet shifts a contiguous plane.AABB by (-1,-1) across a 10×10 toroidal Space2D, so the box wraps past the right and bottom edges and automatically splits into the fragments returned by Fragments(). The exact situation is illustrated by the plot below.

Wrapped AABB fragments

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, BucketCapacity: 4,
	})
	if err != nil {
		panic(err)
	}

	id := uid.UID64(1)
	box := space.WrapAABB(geom.NewAABBAt(geom.NewVec(0, 0), 2, 2))
	space.Insert(id, &box)
	space.Translate(id, &box, geom.NewVec(-1, -1))

	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
	})
}

For more scenarios, browse the example-based tests under pkg/plane and pkg/geom, which double as runnable documentation.

Projects using GOKG

  • gokq — GOKQ is a quadtree utility library that relies on geom.Vec, geom.AABB, and plane.AABB operations.
  • gokx — GOKX is a Go library that provides a lightweight experimental framework for 2D graphics applications.

*Contributor Recommendations

Documentation

Overview

Package aabbworld is a 2D world of axis-aligned boxes: a plane with its own edge rules, a spatial index over the boxes placed in it, and the questions a simulation asks of them — who is near whom, who sees what, what overlaps. Space is the whole of it; geom and plane are its vocabulary.

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 — what one is until SetCapabilities.
	Plain Capability = 1 << 0
	// CanCollide is an entity that takes part in collisions — what collide.BroadPhase asks for.
	CanCollide Capability = 1 << 1
	// AnyCapability accepts every entity.
	AnyCapability Capability = 0xFF
)

type Cone

type Cone struct {
	Direction geom.Vec
	HalfAngle float64 // below π
	Radius    float64
}

Cone bounds a visibility query: a direction, a half-angle either side of it, and how far it reaches.

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 index bucket in world units, rounded up to a power of two.
	BucketSize uint32
	// BucketCapacity is how many entities a bucket holds before it grows.
	BucketCapacity int
	// OpsBufferSize is how many queued changes fit between two Flushes.
	OpsBufferSize int
}

Config sizes a Space.

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 Space

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

Space is a plane with boundary rules and a spatial index over the boxes placed in it. Changes are queued and take effect at the next Flush.

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) Flush

func (s *Space) Flush(onDirty func(geom.AABB))

Flush applies every queued change, reporting each changed box to onDirty if given.

func (*Space) Insert

func (s *Space) Insert(id uid.UID64, box *plane.AABB) bool

Insert places box under the edge rules and queues it for the index; false if past an open edge.

func (*Space) MoveTo

func (s *Space) MoveTo(id uid.UID64, 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) 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) Remove

func (s *Space) Remove(id uid.UID64)

Remove queues id's removal from the index.

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) SetCapabilities

func (s *Space) SetCapabilities(id uid.UID64, c Capability)

SetCapabilities records what may be done with id, from the next Flush on.

func (*Space) Translate

func (s *Space) Translate(id uid.UID64, box *plane.AABB, delta geom.Vec) bool

Translate 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, BucketCapacity: 4,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	id := uid.UID64(1)
	box := space.WrapAABB(geom.NewAABBAt(geom.NewVec(0, 0), 2, 2))
	space.Insert(id, &box)
	space.Translate(id, &box, geom.NewVec(-1, -1))

	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) 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
space, err := aabbworld.NewSpace(aabbworld.Config{
	Width: 1000, Height: 1000,
	BucketSize: 256, BucketCapacity: 8,
})
if err != nil {
	panic(err)
}

const guard = uid.UID64(1)
space.Insert(guard, ptr(plane.NewAABB(geom.NewVec(100, 100), 10, 10)))
space.Insert(uid.UID64(2), ptr(plane.NewAABB(geom.NewVec(300, 100), 10, 10)))
space.Insert(uid.UID64(3), ptr(plane.NewAABB(geom.NewVec(500, 100), 10, 10)))
space.Flush(nil)

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.

Directories

Path Synopsis
Package collide finds and separates overlapping boxes of a Space: BroadPhase names the pairs that may touch, a NarrowPhase gathers them as Pairs, and Separate tests each exactly and pushes the overlapping apart.
Package collide finds and separates overlapping boxes of a Space: BroadPhase names the pairs that may touch, a NarrowPhase gathers them as Pairs, and Separate tests each exactly and pushes the overlapping apart.
Package geom holds the 2D vocabulary of aabbworld: Vec and the axis-aligned box AABB.
Package geom holds the 2D vocabulary of aabbworld: Vec and the axis-aligned box AABB.
internal
core
Package core is the inside of a Space, shared by the packages of this module that work on one.
Package core is the inside of a Space, shared by the packages of this module that work on one.
plane
Package plane is the surface behind a Space: normalisation, translation, growth and distance on a bounded plane and on a torus, working on the public plane's boxes.
Package plane is the surface behind a Space: normalisation, translation, growth and distance on a bounded plane and on a torus, working on the public plane's boxes.
raycast
Package raycast is the state and the algorithm behind the public raycast package: the sweep, the shadows, and the View they fill.
Package raycast is the state and the algorithm behind the public raycast package: the sweep, the shadows, and the View they fill.
spatial
Package spatial provides a discrete spatial index over a 2D power-of-two grid for storing and querying objects by integer coordinates, with support for range queries (AABB) and bulk operations.
Package spatial provides a discrete spatial index over a 2D power-of-two grid for storing and querying objects by integer coordinates, with support for range queries (AABB) and bulk operations.
Package plane defines 2D spaces (cartesian and torus) plus plane-aware boxes and metrics.
Package plane defines 2D spaces (cartesian and torus) plus plane-aware boxes and metrics.

Jump to

Keyboard shortcuts

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