placement

package
v0.4.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 12 Imported by: 0 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.

Documentation

Overview

Package placement is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package placement places objects that cover several cells of a grid, such as buildings, towers, fences and furniture: footprints with a cell mask, a pivot and allowed rotations, loaded from versioned YAML; occupancy over square cells (orthogonal and isometric tilemaps, 3D grid maps) or axial hex cells; per-cell rules on the terrain's tags; undoable changes; and the placed objects saved as a deterministic YAML list.

Footprints

Parse reads a footprint document. Each footprint's mask is rows of 'x' (covered) and '.' (empty), and its pivot is the mask cell that lands on the cell an object is placed at. A footprint may require tags on every covered cell (requires), refuse tags on any covered cell (forbids), and require each of a list of tags on at least one cell next to it (adjacent).

Grids

A Grid holds the placed objects of one map. Grid.CanPlace and Grid.CanMove return a Result that lists every cell the object would cover and every problem with it, for drawing a green or red preview; Grid.Place, Grid.Move and Grid.Remove change the grid, and Grid.PlanPlace, Grid.PlanMove and Grid.PlanRemove return the same changes as a Change for an undo history (package undo). Grid.Layout and Grid.Load save and restore the placed objects through EncodeLayout and ParseLayout.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/placement"
	"github.com/nsgo-dev/game/pkg/undo"
)

func main() {
	doc, err := placement.Parse([]byte(`version: 1
lattice: square
footprints:
  - name: house
    mask:
      - xx
      - x.
    rotations: [0, 1, 2, 3]
    requires: [grass]
    adjacent: [road]
`))
	if err != nil {
		fmt.Println(err)
		return
	}

	// A 5 by 4 field of grass with a road along its bottom row.
	var area placement.Area
	area.AddRect(placement.Cell{}, 5, 3, "grass")
	area.AddRect(placement.Cell{Y: 3}, 5, 1, "road")
	grid, err := placement.NewGrid[string](doc, &area)
	if err != nil {
		fmt.Println(err)
		return
	}

	// CanPlace lists every problem, for drawing the preview red or green.
	for _, p := range grid.CanPlace("house", placement.Cell{X: 4}, 0).Problems {
		fmt.Println(p)
	}

	// Record placements in an undo history.
	history := undo.New[*placement.Grid[string], placement.Change[string]](grid)
	change, err := grid.PlanPlace("home", "house", placement.Cell{X: 1, Y: 1}, 1)
	if err != nil {
		fmt.Println(err)
		return
	}
	history.Do(change)
	fmt.Println("covers:", grid.Cells("home"))

	saved, _ := placement.EncodeLayout(grid.Layout())
	fmt.Print(string(saved))

	history.Undo()
	fmt.Println("after undo:", grid.Len())
}
Output:
(5,0) outside the map
(4,0) not adjacent road
covers: [{0 1} {1 1} {1 2}]
version: 1
objects:
  - id: home
    footprint: house
    at: {x: 1, "y": 1}
    rotation: 1
after undo: 0

Index

Examples

Constants

View Source
const (
	// MaxFootprints is the most footprints one document may declare.
	MaxFootprints = 4096
	// MaxMaskSize is the most rows a mask may have and the most cells a row may have.
	MaxMaskSize = 64
	// MaxTags is the most tags one of a footprint's requires, forbids and adjacent lists may hold.
	MaxTags = 64
)

Limits that keep a footprint document bounded. Validate refuses a document that exceeds them.

View Source
const LayoutVersion = 1

LayoutVersion is the layout document schema version that ParseLayout accepts and EncodeLayout writes.

View Source
const SchemaURL = "https://nsgo.games/schemas/placement.v1.json"

SchemaURL is where the JSON Schema of version 1 footprint documents is published, for editors and AI tools to validate and complete them as they are written.

View Source
const Version = 1

Version is the footprint document schema version that Parse accepts and Encode writes.

Variables

View Source
var (
	// ErrDuplicateID is the error of placing an object with an ID already on the grid.
	ErrDuplicateID = errors.New("placement: an object with this ID is already placed")
	// ErrUnknownID is the error of moving or removing an ID no object on the grid has.
	ErrUnknownID = errors.New("placement: no object with this ID is placed")
)

Functions

func Encode

func Encode(doc *Document) ([]byte, error)

Encode validates doc and writes it as deterministic two-space YAML that Parse decodes to an equal Document.

func EncodeLayout

func EncodeLayout[ID cmp.Ordered](l *Layout[ID]) ([]byte, error)

EncodeLayout validates l and writes it as deterministic two-space YAML that ParseLayout decodes to an equal Layout.

func Validate

func Validate(doc *Document) error

Validate checks doc against the version 1 schema: the version, a known lattice, unique names, rectangular masks of 'x' and '.' that cover at least one cell, a pivot inside the mask, rotations the lattice has, tag lists without blanks or duplicates, no tag both required and forbidden, and the size limits.

func ValidateLayout

func ValidateLayout[ID cmp.Ordered](l *Layout[ID]) error

ValidateLayout checks l against the version 1 schema: the version, a footprint name on every object, rotations that are not negative, and IDs in strictly increasing order.

Types

type Area

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

Area is a Terrain held in memory: a set of cells, each with its tags. The zero Area contains no cell.

func (*Area) Add

func (a *Area) Add(c Cell, tags ...string)

Add puts c on the map, if it is not already, and gives it tags.

func (*Area) AddRect

func (a *Area) AddRect(min Cell, w, h int, tags ...string)

AddRect adds the w by h cells whose top-left cell is min, each with tags.

func (*Area) Contains

func (a *Area) Contains(c Cell) bool

Contains reports whether c is on the map.

func (*Area) Delete

func (a *Area) Delete(c Cell)

Delete takes c off the map.

func (*Area) HasTag

func (a *Area) HasTag(c Cell, tag string) bool

HasTag reports whether c has tag.

func (*Area) Untag

func (a *Area) Untag(c Cell, tags ...string)

Untag takes tags off c.

type Cell

type Cell struct {
	// X is the column, or q on the hex lattice.
	X int `yaml:"x"`
	// Y is the row, or r on the hex lattice.
	Y int `yaml:"y"`
}

Cell is a cell of a grid. On the square lattice it is a column and a row, with rows growing downward as a tilemap's do; on the hex lattice it is axial coordinates, q in X and r in Y.

func (Cell) Add

func (c Cell) Add(d Cell) Cell

Add returns c moved by d.

type Change

type Change[ID cmp.Ordered] struct {
	// ID is the object's ID.
	ID ID
	// Before is where the object was, nil when the change places it.
	Before *Placement
	// After is where the object is after the change, nil when the change removes it.
	After *Placement
}

Change is one change to a grid: an object placed (Before nil), moved, or removed (After nil). It is an undo.Move[*Grid[ID]], so a game records it with an undo.History, which applies it.

func (Change[ID]) Apply

func (c Change[ID]) Apply(g *Grid[ID])

Apply puts the object where After says. The grid must be as it was when the change was planned, as an undo history keeps it.

func (Change[ID]) Revert

func (c Change[ID]) Revert(g *Grid[ID])

Revert puts the object back where Before says.

type Document

type Document struct {
	// Version is the schema version; it must equal Version (1).
	Version int `yaml:"version"`
	// Lattice is the shape of the grid's cells, square or hex, which decides how masks turn and which cells are next to each other.
	Lattice Lattice `yaml:"lattice"`
	// Footprints are the shapes, with unique names.
	Footprints []Footprint `yaml:"footprints"`
}

Document is the root of a versioned YAML footprint document: the shapes of the objects a game places on one kind of grid.

func Parse

func Parse(data []byte) (*Document, error)

Parse decodes a YAML footprint document and validates it. Unknown fields, duplicate keys and trailing YAML documents are refused, with a *loaderr.Error naming the field.

type Footprint

type Footprint struct {
	// Name identifies the footprint within its document, such as "farmhouse".
	Name string `yaml:"name"`
	// Mask is the cells the object covers, as rows of the same length: 'x' covers a cell and '.' leaves it empty (not '#', which starts a comment in YAML). Row i is the cells with Y = i and column j those with X = j, before the pivot is subtracted; on the hex lattice X is q and Y is r.
	Mask []string `yaml:"mask"`
	// Pivot is the mask cell, by column and row, that lands on the cell the object is placed at and that the object turns about. It need not be covered. Zero is the top-left cell.
	Pivot Cell `yaml:"pivot,omitempty,flow"`
	// Rotations are the rotations the object may take, in strictly increasing order: quarter turns 0 to 3 on the square lattice and sixth turns 0 to 5 on the hex lattice, clockwise. Empty allows only 0.
	Rotations []int `yaml:"rotations,omitempty,flow"`
	// Requires are tags every covered cell must have, such as soil.
	Requires []string `yaml:"requires,omitempty,flow"`
	// Forbids are tags no covered cell may have, such as water.
	Forbids []string `yaml:"forbids,omitempty,flow"`
	// Adjacent are tags each of which at least one cell next to the object, outside it, must have, such as road.
	Adjacent []string `yaml:"adjacent,omitempty,flow"`
}

Footprint is the shape of one kind of object and the rules for where it may go.

type Grid

type Grid[ID cmp.Ordered] struct {
	// contains filtered or unexported fields
}

Grid holds the objects placed on one map, each under an ID of the game's choice, and which cells they cover. A Grid is not safe for concurrent use.

func NewGrid

func NewGrid[ID cmp.Ordered](doc *Document, terrain Terrain) (*Grid[ID], error)

NewGrid returns an empty grid over terrain whose objects take their shapes from doc. It returns doc's validation error, and an error when terrain is nil.

func (*Grid[ID]) All

func (g *Grid[ID]) All() iter.Seq2[ID, Placement]

All yields every placed object in increasing order of ID.

func (*Grid[ID]) At

func (g *Grid[ID]) At(c Cell) (ID, bool)

At returns the ID of the object covering c, and false when no object covers it.

func (*Grid[ID]) CanMove

func (g *Grid[ID]) CanMove(id ID, at Cell, rotation int) Result

CanMove checks moving the object id to a cell with a rotation; the cells it covers now do not block it.

func (*Grid[ID]) CanPlace

func (g *Grid[ID]) CanPlace(footprint string, at Cell, rotation int) Result

CanPlace checks placing a new object of footprint at a cell with a rotation, which may be any integer and counts modulo the lattice's turns.

func (*Grid[ID]) Cells

func (g *Grid[ID]) Cells(id ID) []Cell

Cells returns the cells the object id covers, in row order, and nil when no object has it.

func (*Grid[ID]) Footprint

func (g *Grid[ID]) Footprint(name string) (Footprint, bool)

Footprint returns a copy of the footprint name declares, and false when the grid's document declares none.

func (*Grid[ID]) Get

func (g *Grid[ID]) Get(id ID) (Placement, bool)

Get returns where the object id is, and false when no object has it.

func (*Grid[ID]) Lattice

func (g *Grid[ID]) Lattice() Lattice

Lattice returns the lattice of the grid's document.

func (*Grid[ID]) Layout

func (g *Grid[ID]) Layout() *Layout[ID]

Layout returns the grid's objects as a layout document, in increasing order of ID.

func (*Grid[ID]) Len

func (g *Grid[ID]) Len() int

Len returns how many objects are placed.

func (*Grid[ID]) Load

func (g *Grid[ID]) Load(l *Layout[ID]) error

Load replaces the grid's objects with those of l, checking each against the grid's footprints, terrain and the objects before it as Place does. It changes nothing when l is invalid or any object is refused, and returns a *loaderr.Error naming the object.

func (*Grid[ID]) Move

func (g *Grid[ID]) Move(id ID, at Cell, rotation int) error

Move moves the object id to a cell with a rotation, as PlanMove checks it.

func (*Grid[ID]) Place

func (g *Grid[ID]) Place(id ID, footprint string, at Cell, rotation int) error

Place places a new object id of footprint at a cell with a rotation, as PlanPlace checks it.

func (*Grid[ID]) PlanMove

func (g *Grid[ID]) PlanMove(id ID, at Cell, rotation int) (Change[ID], error)

PlanMove checks moving the object id to a cell with a rotation and returns the change that moves it, without applying it. It returns ErrUnknownID when no object has id and a *RefusedError when the check fails.

func (*Grid[ID]) PlanPlace

func (g *Grid[ID]) PlanPlace(id ID, footprint string, at Cell, rotation int) (Change[ID], error)

PlanPlace checks placing a new object id of footprint at a cell with a rotation and returns the change that places it, without applying it. It returns ErrDuplicateID when id is already placed and a *RefusedError when the check fails.

func (*Grid[ID]) PlanRemove

func (g *Grid[ID]) PlanRemove(id ID) (Change[ID], error)

PlanRemove returns the change that removes the object id, without applying it, and ErrUnknownID when no object has id.

func (*Grid[ID]) Remove

func (g *Grid[ID]) Remove(id ID) error

Remove removes the object id, and returns ErrUnknownID when no object has it.

type Lattice

type Lattice string

Lattice is the shape of a grid's cells, which decides how a footprint turns and which cells are next to each other.

const (
	// Square is the lattice of orthogonal and isometric tilemaps and of 3D grid maps (X and Z of world3d.GridMap): a footprint turns in quarter turns, and a cell's neighbors are the four cells that share an edge with it.
	Square Lattice = "square"
	// Hex is the lattice of hex maps in axial coordinates (q, r): a footprint turns in sixth turns, and a cell has six neighbors.
	Hex Lattice = "hex"
)

func (Lattice) Neighbors

func (l Lattice) Neighbors(c Cell) []Cell

Neighbors returns the cells next to c: the four that share an edge on Square, the six on Hex, and none for a lattice this package does not know.

func (Lattice) Rotate

func (l Lattice) Rotate(c Cell, turns int) Cell

Rotate turns c clockwise about the origin by turns steps of the lattice, a quarter turn on Square and a sixth turn on Hex, as seen with rows growing downward. Negative turns go counterclockwise. A lattice this package does not know leaves c as it is.

func (Lattice) Turns

func (l Lattice) Turns() int

Turns is how many rotations the lattice has: 4 for Square and 6 for Hex, and 0 for a lattice this package does not know.

type Layout

type Layout[ID cmp.Ordered] struct {
	// Version is the schema version; it must equal LayoutVersion (1).
	Version int `yaml:"version"`
	// Objects are the placed objects in strictly increasing order of ID, so the same grid always saves the same bytes.
	Objects []Object[ID] `yaml:"objects"`
}

Layout is the root of a versioned YAML layout document: the objects placed on one grid, for a save or a level's starting state. Grid.Layout writes one and Grid.Load restores it.

func ParseLayout

func ParseLayout[ID cmp.Ordered](data []byte) (*Layout[ID], error)

ParseLayout decodes a YAML layout document and validates it, as ValidateLayout does. Unknown fields, duplicate keys and trailing YAML documents are refused, with a *loaderr.Error naming the field. Footprint names are checked when Grid.Load restores the layout.

type Object

type Object[ID cmp.Ordered] struct {
	// ID is the object's ID.
	ID ID `yaml:"id"`
	// Placement is where it is.
	Placement `yaml:",inline"`
}

Object is one placed object of a Layout.

type Placement

type Placement struct {
	// Footprint names the object's footprint.
	Footprint string `yaml:"footprint"`
	// At is the cell the footprint's pivot is on.
	At Cell `yaml:"at,flow"`
	// Rotation is the object's rotation, from 0 to the lattice's turns minus one.
	Rotation int `yaml:"rotation,omitempty"`
}

Placement is where one object is: its footprint, the cell its pivot is on, and its rotation.

type Problem

type Problem struct {
	// Cell is the refused cell. For NotAdjacent, RotationNotAllowed, UnknownFootprint and UnknownObject, which no one cell causes, it is the cell the object is placed at.
	Cell Cell
	// Reason is why.
	Reason Reason
	// Tag is the tag a MissingTag, ForbiddenTag or NotAdjacent problem is about.
	Tag string
}

Problem is one reason a placement is refused.

func (Problem) String

func (p Problem) String() string

String describes the problem, such as "(3,1) missing tag soil".

type Reason

type Reason int

Reason is why a cell, or a whole placement, is refused.

const (
	// Outside is a covered cell the terrain does not contain.
	Outside Reason = iota + 1
	// Occupied is a covered cell another object covers.
	Occupied
	// MissingTag is a covered cell without a tag the footprint requires.
	MissingTag
	// ForbiddenTag is a covered cell with a tag the footprint forbids.
	ForbiddenTag
	// NotAdjacent is a tag of the footprint's adjacent list that no cell next to the object has.
	NotAdjacent
	// RotationNotAllowed is a rotation the footprint does not allow.
	RotationNotAllowed
	// UnknownFootprint is a footprint name the grid's document does not declare.
	UnknownFootprint
	// UnknownObject is an ID no object on the grid has.
	UnknownObject
)

func (Reason) String

func (r Reason) String() string

String returns the reason in words, such as "occupied".

type RefusedError

type RefusedError struct {
	// Footprint, At and Rotation are the refused placement.
	Footprint string
	At        Cell
	Rotation  int
	// Result lists its problems.
	Result Result
}

RefusedError is the error of a placement or move its Result refuses.

func (*RefusedError) Error

func (e *RefusedError) Error() string

Error names the placement and its first problem, and counts the rest.

type Result

type Result struct {
	// Cells are the cells the object would cover, in row order, for drawing it; nil when the footprint, rotation or object is unknown.
	Cells []Cell
	// Problems are every reason the placement is refused, those of each covered cell in the order of Cells and then those of the footprint as a whole; empty when it is allowed.
	Problems []Problem
}

Result is the outcome of checking a placement: the cells the object would cover and every problem with it.

func (Result) Blocked

func (r Result) Blocked(c Cell) bool

Blocked reports whether a problem of c itself (Outside, Occupied, MissingTag or ForbiddenTag) refuses c, so a preview can draw c in red and the rest of Cells in green.

func (Result) OK

func (r Result) OK() bool

OK reports whether the placement is allowed.

type Terrain

type Terrain interface {
	// Contains reports whether c is on the map. An object may cover only cells the map contains.
	Contains(c Cell) bool
	// HasTag reports whether c has tag. It is asked only about cells Contains reports.
	HasTag(c Cell, tag string) bool
}

Terrain is the map under a grid: which cells exist and which tags each has. A game implements it over its tilemap, its 3D grid map or its own data, so tags can come from tile flags, typed tile data, or the game's state, such as the road its player built. Area is a Terrain held in memory.

Jump to

Keyboard shortcuts

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