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 ¶
- Constants
- Variables
- func Encode(doc *Document) ([]byte, error)
- func EncodeLayout[ID cmp.Ordered](l *Layout[ID]) ([]byte, error)
- func Validate(doc *Document) error
- func ValidateLayout[ID cmp.Ordered](l *Layout[ID]) error
- type Area
- type Cell
- type Change
- type Document
- type Footprint
- type Grid
- func (g *Grid[ID]) All() iter.Seq2[ID, Placement]
- func (g *Grid[ID]) At(c Cell) (ID, bool)
- func (g *Grid[ID]) CanMove(id ID, at Cell, rotation int) Result
- func (g *Grid[ID]) CanPlace(footprint string, at Cell, rotation int) Result
- func (g *Grid[ID]) Cells(id ID) []Cell
- func (g *Grid[ID]) Footprint(name string) (Footprint, bool)
- func (g *Grid[ID]) Get(id ID) (Placement, bool)
- func (g *Grid[ID]) Lattice() Lattice
- func (g *Grid[ID]) Layout() *Layout[ID]
- func (g *Grid[ID]) Len() int
- func (g *Grid[ID]) Load(l *Layout[ID]) error
- func (g *Grid[ID]) Move(id ID, at Cell, rotation int) error
- func (g *Grid[ID]) Place(id ID, footprint string, at Cell, rotation int) error
- func (g *Grid[ID]) PlanMove(id ID, at Cell, rotation int) (Change[ID], error)
- func (g *Grid[ID]) PlanPlace(id ID, footprint string, at Cell, rotation int) (Change[ID], error)
- func (g *Grid[ID]) PlanRemove(id ID) (Change[ID], error)
- func (g *Grid[ID]) Remove(id ID) error
- type Lattice
- type Layout
- type Object
- type Placement
- type Problem
- type Reason
- type RefusedError
- type Result
- type Terrain
Examples ¶
Constants ¶
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.
const LayoutVersion = 1
LayoutVersion is the layout document schema version that ParseLayout accepts and EncodeLayout writes.
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.
const Version = 1
Version is the footprint document schema version that Parse accepts and Encode writes.
Variables ¶
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 ¶
Encode validates doc and writes it as deterministic two-space YAML that Parse decodes to an equal Document.
func EncodeLayout ¶
EncodeLayout validates l and writes it as deterministic two-space YAML that ParseLayout decodes to an equal Layout.
func Validate ¶
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.
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.
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.
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.
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.
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 ¶
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 ¶
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]) At ¶
At returns the ID of the object covering c, and false when no object covers it.
func (*Grid[ID]) CanMove ¶
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 ¶
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 ¶
Cells returns the cells the object id covers, in row order, and nil when no object has it.
func (*Grid[ID]) Footprint ¶
Footprint returns a copy of the footprint name declares, and false when the grid's document declares none.
func (*Grid[ID]) Layout ¶
Layout returns the grid's objects as a layout document, in increasing order of ID.
func (*Grid[ID]) Load ¶
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]) Place ¶
Place places a new object id of footprint at a cell with a rotation, as PlanPlace checks it.
func (*Grid[ID]) PlanMove ¶
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 ¶
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 ¶
PlanRemove returns the change that removes the object id, without applying it, and ErrUnknownID when no object has id.
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 ¶
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.
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 ¶
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.
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 )
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.
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.