GitHub快速开始

API 参考取自源码中的 Go 文档注释,以英文书写。

package tilemap

import "github.com/nsgo-dev/game/pkg/tilemap"

概述

Package tilemap draws tiled worlds, queries tile flags and rays against them, loads Tiled maps, and moves a 2D camera over the world.

索引

常量

const (
	MaskNorth     uint8 = 1 << 0
	MaskEast      uint8 = 1 << 1
	MaskSouth     uint8 = 1 << 2
	MaskWest      uint8 = 1 << 3
	MaskNorthEast uint8 = 1 << 4
	MaskSouthEast uint8 = 1 << 5
	MaskSouthWest uint8 = 1 << 6
	MaskNorthWest uint8 = 1 << 7
)

Bitmask constants for 4-bit cardinal and 8-bit corner-gated autotiling.

const (
	// DefaultChunkSize is the default power-of-two edge length (in tiles) for sparse chunked tile layers.
	DefaultChunkSize = 16
	// MinChunkSize is the smallest supported power-of-two edge length (in tiles) for a chunked tile layer.
	MinChunkSize = 2
	// MaxChunkSize is the largest supported power-of-two edge length (in tiles) for a chunked tile layer.
	MaxChunkSize = 256
)
const (
	// FlipHorizontal mirrors a tile left to right (Tiled GID bit 31).
	FlipHorizontal uint32 = 0x80000000
	// FlipVertical mirrors a tile top to bottom (Tiled GID bit 30).
	FlipVertical uint32 = 0x40000000
	// FlipDiagonal swaps a tile's X and Y axes before horizontal and vertical flips (Tiled GID bit 29).
	FlipDiagonal uint32 = 0x20000000
	// FlipMask masks the three orthogonal Tiled flip bits from a raw GID.
	FlipMask uint32 = FlipHorizontal | FlipVertical | FlipDiagonal
	// TileIDMask masks the global tile ID from a raw GID, stripping flip and rotation bits.
	TileIDMask uint32 = 0x0FFFFFFF
)
const (
	WangTop         = 0
	WangTopRight    = 1
	WangRight       = 2
	WangBottomRight = 3
	WangBottom      = 4
	WangBottomLeft  = 5
	WangLeft        = 6
	WangTopLeft     = 7
)

Clockwise indices into WangID, matching Tiled's wangid JSON array order.

const ChunkFormatVersion = 1

ChunkFormatVersion is the current schema version of the plain-text chunk YAML and JSON format.

const EllipseShapeSegments = 16

EllipseShapeSegments is the number of straight edges LoadTiled uses to approximate an ellipse a tileset draws on a tile as its collision shape.

const MaxTilesetTiles = 1 << 24

MaxTilesetTiles is the most tiles one YAML tileset may define, its TileCount or the length of its Frames.

const PropSortOriginY = "sort_origin_y"

PropSortOriginY is the tile custom property name for an explicit vertical Y-sort origin offset (in points) added to a tile's default bottom-edge sort line.

Negative values move the sort line upward (for example into a tall tree's trunk); positive values move it downward. Lookup also accepts "y_sort_origin" and "ysort_origin" as aliases.

const TilesetFormatVersion = 1

TilesetFormatVersion is the schema version of the YAML tileset format (*.tileset.yaml) that ParseTileset reads and EncodeTileset writes.

const TilesetSchemaComment = "# yaml-language-server: $schema=" + TilesetSchemaURL

TilesetSchemaComment is the first line EncodeTileset writes: a YAML comment that points a YAML language server at TilesetSchemaURL. ParseTileset ignores it like any other comment.

const TilesetSchemaURL = "https://game.nsgo.dev/schemas/tileset.v1.json"

TilesetSchemaURL is where the JSON Schema of version 1 tileset documents is published. EncodeTileset names it in TilesetSchemaComment on the first line of every file.

函数

func ComputeMask4(match func(col, row int) bool, col, row int) uint8

ComputeMask4 computes the 4-bit cardinal neighbor mask (N=1, E=2, S=4, W=8) at (col, row).

func ComputeMask8(match func(col, row int) bool, col, row int) uint8

ComputeMask8 computes the 8-bit corner-gated Wang/blob neighbor mask (47-tile blob) at (col, row).

Diagonal bits (NE, SE, SW, NW) are only set when both adjacent cardinal neighbors also match.

func EncodeChunk(c *Chunk, format ChunkFormat) ([]byte, error)

EncodeChunk encodes c in format (ChunkFormatYAML or ChunkFormatJSON).

func EncodeChunkJSON(doc *ChunkDoc) ([]byte, error)

EncodeChunkJSON validates doc and encodes it as deterministic indented JSON with a trailing newline.

func EncodeChunkYAML(doc *ChunkDoc) ([]byte, error)

EncodeChunkYAML validates doc and encodes it as deterministic 2-space YAML.

func EncodeTiled(m *Tilemap) ([]byte, error)

EncodeTiled encodes m as a deterministic, indented Tiled JSON (.tmj) document.

All tilesets (embedded inline), tile layers (dense or chunked), image layers, object layers, custom properties, tile animations, Wang sets, and per-tile collision object groups (from Tileset.TileCollisions, or synthesized from Tileset.Shapes when no TileCollisions entry exists) are written in canonical order so round-tripping through LoadTiled and EncodeTiled preserves per-tile collision data and produces byte-identical output.

func EncodeTileset(doc *TilesetDoc) ([]byte, error)

EncodeTileset validates doc and writes it as deterministic 2-space YAML, starting with TilesetSchemaComment. Keys come in a fixed order and maps in sorted key order, so the same tileset always gives the same bytes, and a file in that form parses and encodes back unchanged.

func LoadLDtkAll(data []byte, resolveImage func(relPath string) core.ImageSource) (map[string]*Tilemap, error)

LoadLDtkAll parses an LDtk JSON project and builds a Tilemap for every level, keyed by level identifier. For Free and GridVania layouts, each Tilemap carries its world Origin (worldX, worldY) and Neighbours list. Its errors are *loaderr.Error values, as LoadLDtk's are.

func LoadLDtkAllWith(data []byte, opts LDtkOptions) (map[string]*Tilemap, error)

LoadLDtkAllWith parses an LDtk JSON project with opts and builds a Tilemap for every level, keyed by level identifier.

func SortYSortTiles(tiles []YSortTile)

SortYSortTiles sorts tiles in stable ascending SortY order without allocating.

func TerrainMaskNeighbors(mask uint8) []string

TerrainMaskNeighbors returns the canonical list of neighbor direction names for mask, or nil when mask is 0.

func TerrainNeighborsMask(neighbors []string) (uint8, error)

TerrainNeighborsMask converts a list of neighbor direction names to a bitmask, returning an error on unknown or duplicate directions.

func TilesetFrame(doc *TilesetDoc, atlas *sprite.Atlas, id int) (sprite.Frame, bool)

TilesetFrame returns where local tile id of doc lies in the image it is drawn from: a rectangle of the grid image for an image tileset, or the frame of atlas, the atlas doc names, for an atlas tileset. It reports false for an ID outside the tileset, an atlas tileset with a nil atlas and a frame the atlas lacks. An editor's tile palette uses it to show a tileset's tiles.

func ToggleTerrainMask(mode AutotileMode, mask, bit uint8) uint8

ToggleTerrainMask toggles bit in mask while keeping the result valid for mode. In Autotile4 diagonal bits are ignored and stripped. In Autotile8 enabling a corner bit also enables its two adjacent cardinal edges, and disabling an edge bit clears any corner bits that depend on it.

func ValidChunkSize(n int) bool

ValidChunkSize reports whether n is a supported power-of-two chunk edge length in [MinChunkSize, MaxChunkSize].

func ValidTerrainMask(mode AutotileMode, mask uint8) bool

ValidTerrainMask reports whether mask is a valid neighbor bitmask for mode: for Autotile4 only the four cardinal bits (N, E, S, W) may be set; for Autotile8 each diagonal corner bit may only be set when both adjacent cardinal bits are also set.

func ValidateChunkDoc(doc *ChunkDoc) error

ValidateChunkDoc checks that doc conforms to the version 1 chunk schema.

func ValidateTileset(doc *TilesetDoc) error

ValidateTileset checks doc against the version 1 tileset schema: a positive tile size, exactly one of a grid image (with its columns and tile count) or an atlas (with its frames), tiles in ascending ID order within the tile count, scalar properties, well-formed shapes, animations of positive durations over existing tiles, and terrains whose tiles list valid, distinct neighbour sets. Its errors are *loaderr.Error values naming the field at fault.

类型

type AutotileMode int

AutotileMode chooses between 4-bit cardinal (16-tile) and 8-bit corner-gated (47-tile) autotiling.

const (
	// Autotile4 uses the 4 cardinal neighbors (N=1, E=2, S=4, W=8; 16 combinations).
	Autotile4 AutotileMode = iota
	// Autotile8 uses the 4 cardinal neighbors plus 4 corner-gated diagonal neighbors (47 combinations).
	Autotile8
)
type AutotileSet struct {
	Mode    AutotileMode
	Tiles   map[uint8]uint32
	Default uint32
}

AutotileSet maps autotile neighbor bitmasks to tile GIDs, falling back to Default when a mask has no entry in Tiles.

func (s AutotileSet) ComputeMask(match func(col, row int) bool, col, row int) uint8

ComputeMask computes the neighbor bitmask at (col, row) using s.Mode (ComputeMask4 for Autotile4, ComputeMask8 for Autotile8).

func (s AutotileSet) Tile(mask uint8) uint32

Tile returns the GID mapped to mask, or s.Default when mask is not present in s.Tiles.

type Camera struct {
	// X and Y are the world point at the center of the view.
	X, Y float32
	// Zoom scales the world in the view; values <= 0 behave as 1.
	Zoom float32
	// Rotation turns the camera clockwise in the world, in radians.
	Rotation float32
	// Width and Height are the view's size in points.
	Width, Height float32
	// Bounds, when non-nil, limits where Clamp and Follow let the visible view reach.
	Bounds *core.Bounds
	// ShakeSeed seeds the deterministic shake offset; 0 uses a fixed default seed.
	ShakeSeed uint64
	// contains filtered or unexported fields
}

Camera maps world coordinates to a view of size Width by Height centered on (X, Y), zoomed by Zoom and turned clockwise by Rotation.

A zero or negative Zoom behaves as 1. When Bounds is set, Clamp and Follow keep the visible view inside it, centering any axis where the world is smaller than the view.

func (c *Camera) Apply(d *core.Drawing)

Apply multiplies d's transform by the world-to-view transform, including any active shake offset.

func (c *Camera) Clamp()

Clamp keeps the camera's visible view inside Bounds when Bounds is non-nil. On any axis where Bounds is smaller than the view, it centers the camera on Bounds.

func (c *Camera) Follow(target core.Point, smoothing float32, dt time.Duration)

Follow moves the camera toward target with exponential smoothing over a fixed Loop step dt, then clamps to Bounds if set.

A smoothing <= 0 snaps directly to target. Higher positive values converge faster (factor 1 - exp(-smoothing*dt)).

func (c *Camera) Parallax(factorX, factorY float32) Camera

Parallax returns a Camera with c's zoom, rotation, and viewport size whose position (including any active shake offset) is scaled by factorX and factorY.

func (c *Camera) Shake(intensity float32, duration time.Duration)

Shake starts a deterministic screen shake with maximum displacement intensity in world points that decays to zero over duration.

A non-positive intensity or duration cancels any active shake.

func (c *Camera) ShakeOffset() core.Point

ShakeOffset returns the current screen shake displacement in world points, or (0, 0) when idle.

func (c *Camera) Update(dt time.Duration)

Update advances an active screen shake by dt, returning the shake offset to (0, 0) once its duration elapses.

func (c *Camera) ViewToWorld(p core.Point) core.Point

ViewToWorld converts a point in the view to its position in world coordinates.

func (c *Camera) VisibleBounds() core.Bounds

VisibleBounds returns the axis-aligned world rectangle covering all four corners of the view at the camera's current position, zoom, rotation and shake offset.

func (c *Camera) WorldToView(p core.Point) core.Point

WorldToView converts a point in world coordinates to its position in the view.

type Chunk struct {
	Coord ChunkCoord
	Size  int
	Tiles []uint32
	// Dirty reports whether this chunk's tiles changed since its static cache was last baked.
	Dirty bool
	// Modified reports whether this chunk's tiles were edited after it was generated or loaded.
	Modified bool
	// contains filtered or unexported fields
}

Chunk holds one fixed power-of-two square (Size × Size, row-major) of raw tile GIDs inside a chunked TileLayer.

func ChunkFromDoc(doc *ChunkDoc) (*Chunk, error)

ChunkFromDoc validates doc and decodes it into a clean Chunk (Dirty=true, Modified=false).

func DecodeChunk(data []byte, format ChunkFormat) (*Chunk, error)

DecodeChunk decodes raw YAML or JSON bytes in format into a clean Chunk (Dirty=true, Modified=false).

func NewChunk(coord ChunkCoord, size int) *Chunk

NewChunk allocates an empty Size × Size chunk at coord. Non-positive or non-power-of-two sizes are normalized into [MinChunkSize, MaxChunkSize] (defaulting to DefaultChunkSize).

func (c *Chunk) Cache() *LayerCache

Cache returns this chunk's static LayerCache, or nil if the chunk has not been baked.

func (c *Chunk) Clone() *Chunk

Clone returns a deep copy of c's tile data and metadata without copying its static GPU/RGBA cache.

func (c *Chunk) Empty() bool

Empty reports whether every cell in c has GID 0.

func (c *Chunk) SetTile(lx, ly int, gid uint32) bool

SetTile writes gid at chunk-local (lx, ly) and reports whether the cell changed. Changing a cell marks the chunk both Dirty and Modified and invalidates its static cache.

func (c *Chunk) TileAt(lx, ly int) uint32

TileAt returns the raw GID (including flip flags) at chunk-local (lx, ly), or 0 if out of range.

func (c *Chunk) ToDoc() *ChunkDoc

ToDoc converts c into its deterministic ChunkDoc representation. Returns nil if c is nil.

type ChunkCoord struct {
	X, Y int
}

ChunkCoord identifies one sparse chunk in chunk-grid coordinates. Both X and Y may be negative.

func TileToChunk(col, row, chunkSize int) (coord ChunkCoord, lx, ly int)

TileToChunk converts a world tile coordinate (col, row) into its chunk coordinate and chunk-local (lx, ly) offset for a power-of-two chunkSize (invalid chunkSize falls back to DefaultChunkSize).

Negative tile coordinates floor toward negative infinity, so local coordinates are always in [0, chunkSize).

type ChunkDoc struct {
	// Version is the schema version; must be 1.
	Version int `yaml:"version" json:"version"`
	// X is the chunk's X coordinate in chunk-grid space (may be negative).
	X int `yaml:"x" json:"x"`
	// Y is the chunk's Y coordinate in chunk-grid space (may be negative).
	Y int `yaml:"y" json:"y"`
	// Size is the power-of-two chunk edge length in tiles.
	Size int `yaml:"size" json:"size"`
	// Runs holds row-major run-length encoded raw tile GIDs (including flip bits),
	// formatted as "gid" (count 1) or "gid*count" (count > 1), whose counts sum to Size*Size.
	Runs []string `yaml:"runs" json:"runs"`
}

ChunkDoc is the versioned plain-text representation of one sparse tilemap chunk, suitable for deterministic YAML or JSON persistence.

func DecodeChunkJSON(data []byte) (*ChunkDoc, error)

DecodeChunkJSON decodes and validates a JSON ChunkDoc, refusing unknown fields and trailing data. Errors are returned as *loaderr.Error values.

func DecodeChunkYAML(data []byte) (*ChunkDoc, error)

DecodeChunkYAML decodes and validates a YAML ChunkDoc, refusing unknown fields and trailing documents. Errors are returned as *loaderr.Error values.

type ChunkFormat int

ChunkFormat selects the plain-text encoding used when persisting modified chunks.

const (
	// ChunkFormatYAML encodes persisted chunks as deterministic YAML (default).
	ChunkFormatYAML ChunkFormat = iota
	// ChunkFormatJSON encodes persisted chunks as deterministic JSON.
	ChunkFormatJSON
)
type ChunkStore interface {
	LoadChunk(coord ChunkCoord) (data []byte, found bool, err error)
	SaveChunk(coord ChunkCoord, data []byte) error
}

ChunkStore loads and saves serialized plain-text chunk documents keyed by ChunkCoord. Implementations used with concurrent loaders (such as world3d.TilemapStreamer with Workers > 0) must be safe for concurrent use.

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

ChunkStream streams sparse chunks around a moving 2D world position with hysteresis unloading, per-update load budgets, procedural generation, and deterministic YAML/JSON persistence of modified chunks.

func NewChunkStream(cfg ChunkStreamConfig) *ChunkStream

NewChunkStream constructs a ChunkStream from cfg.

func (s *ChunkStream) CenterChunk(worldPos core.Point) ChunkCoord

CenterChunk returns the ChunkCoord containing worldPos in s's layer.

func (s *ChunkStream) Close() error

Close saves all loaded modified chunks and unloads every chunk from the layer.

func (s *ChunkStream) LoadOrGenerateChunk(coord ChunkCoord) (*Chunk, error)

LoadOrGenerateChunk restores coord from Store if present, or otherwise allocates a new Chunk and runs Generator. The returned Chunk always has Dirty=true and Modified=false.

func (s *ChunkStream) LoadedCount() int

LoadedCount returns the number of currently loaded chunks in the streamed layer.

func (s *ChunkStream) SaveChunk(ch *Chunk) error

SaveChunk encodes ch in s's configured format and writes it to Store, clearing ch.Modified on success.

func (s *ChunkStream) SaveModified() error

SaveModified persists every currently loaded modified chunk in deterministic (Y, X) order.

func (s *ChunkStream) Update(worldPos core.Point)

Update advances streaming for worldPos:

  1. Unloads loaded chunks beyond UnloadRadius (saving modified chunks to Store first).
  2. Loads from Store or generates missing chunks within LoadRadius (closest first), up to MaxLoadsPerUpdate.
type ChunkStreamConfig struct {
	// Map is the Tilemap owning LayerIndex.
	Map *Tilemap
	// LayerIndex selects the chunked TileLayer inside Map.Layers.
	LayerIndex int
	// LoadRadius is the Chebyshev chunk radius around the center chunk to keep loaded.
	LoadRadius int
	// UnloadRadius is the Chebyshev chunk radius beyond which loaded chunks are unloaded.
	// Defaults to LoadRadius + 1 when smaller than LoadRadius.
	UnloadRadius int
	// MaxLoadsPerUpdate caps how many missing chunks are loaded or generated per Update call (<= 0 means unlimited).
	MaxLoadsPerUpdate int
	// Format selects ChunkFormatYAML (default) or ChunkFormatJSON when saving and restoring modified chunks.
	Format ChunkFormat
	// Store persists modified chunks on unload and restores them on reload before invoking Generator.
	Store ChunkStore
	// Generator populates a freshly allocated chunk when Store has no saved entry for coord.
	Generator func(coord ChunkCoord, chunk *Chunk) error
	// OnLoad is called after a chunk is loaded or generated and installed into the layer.
	OnLoad func(coord ChunkCoord, chunk *Chunk)
	// OnUnload is called after a chunk is saved (if modified) and removed from the layer.
	OnUnload func(coord ChunkCoord, chunk *Chunk)
	// OnError is called when loading, generating, or saving a chunk fails.
	OnError func(coord ChunkCoord, err error)
}

ChunkStreamConfig configures a synchronous ChunkStream for one chunked TileLayer. For multi-threaded background chunk loading on top of world3d.ChunkStreamer, see world3d.NewTilemapStreamer.

type DirChunkStore struct {
	Dir    string
	Format ChunkFormat
	// contains filtered or unexported fields
}

DirChunkStore is a directory-backed ChunkStore that saves each chunk as a plain-text file named "chunk_<x>_<y>.yaml" (or ".json" when Format is ChunkFormatJSON).

func NewDirChunkStore(dir string, format ChunkFormat) *DirChunkStore

NewDirChunkStore constructs a DirChunkStore rooted at dir with the given plain-text format.

func (s *DirChunkStore) LoadChunk(coord ChunkCoord) ([]byte, bool, error)

LoadChunk reads coord's file from s.Dir, returning found=false if the file does not exist.

func (s *DirChunkStore) Path(coord ChunkCoord) string

Path returns the file path for coord inside s.Dir.

func (s *DirChunkStore) SaveChunk(coord ChunkCoord, data []byte) error

SaveChunk atomically writes data to coord's file inside s.Dir, creating s.Dir if needed.

type ImageLayer struct {
	Name       string
	Image      core.ImageSource
	Width      float32
	Height     float32
	OffsetX    float32
	OffsetY    float32
	ParallaxX  float32
	ParallaxY  float32
	RepeatX    bool
	RepeatY    bool
	Opacity    float32
	TintColor  core.Color
	Tinted     bool
	Visible    bool
	Properties Properties
}

ImageLayer is an image layer (such as a sky, parallax backdrop, or foreground overlay) drawn in map layer order.

type LDtkOptions struct {
	// ResolveImage maps an LDtk tileset relative path into an ImageSource.
	// When nil, core.ImageSource{URI: relPath} is used.
	ResolveImage func(relPath string) core.ImageSource
	// IntGridFlags maps LDtk IntGrid value identifiers or IntGrid value group identifiers
	// (case-insensitive) to TileFlags, overriding the built-in heuristic.
	// Mapping a name to 0 explicitly marks matching IntGrid cells non-colliding.
	IntGridFlags map[string]TileFlags
	// IntGridValueFlags maps positive numeric LDtk IntGrid values (1, 2, ...) directly to TileFlags,
	// taking precedence over IntGridFlags and the built-in heuristic.
	// Mapping a value to 0 explicitly marks matching IntGrid cells non-colliding.
	IntGridValueFlags map[int]TileFlags
}

LDtkOptions configures LoadLDtkWith, LoadLDtkAllWith, and LoadLDtkWorldWith.

type LayerCache struct {
	Pixels  *image.RGBA
	Source  core.ImageSource
	OriginX float32
	OriginY float32
	Width   float32
	Height  float32
	Dirty   bool
	Version uint64
}

LayerCache holds a static tile layer baked into a premultiplied RGBA pixel buffer so DrawLayer can emit a single DrawImageFrom op.

type LevelNeighbour struct {
	// Identifier is the neighbour level's identifier, resolved from the world's level list when available.
	Identifier string
	// IID is the neighbour level's LDtk instance ID (levelIid), when present.
	IID string
	// UID is the neighbour level's numeric LDtk UID (levelUid), when present.
	UID int
	// Dir is the direction from this level to the neighbour:
	// "n", "s", "e", "w", "ne", "nw", "se", "sw", "o" (overlapping), "<" (lower depth), or ">" (higher depth).
	Dir string
}

LevelNeighbour describes one adjacent or overlapping level in a multi-level world (such as an LDtk project).

type LevelWorld struct {
	// Name is the world identifier (for multi-world LDtk projects) or empty.
	Name string
	// Layout is the world layout ("Free", "GridVania", or "Tiled").
	Layout string
	// Levels lists every level in deterministic world order.
	Levels []WorldLevel
}

LevelWorld holds the layout of a multi-level 2D world loaded from an LDtk project or a Tiled .world file.

func LoadLDtkWorld(data []byte, worldIdentifier string, resolveImage func(relPath string) core.ImageSource) (*LevelWorld, error)

LoadLDtkWorld parses an LDtk JSON project (.ldtk) into a LevelWorld whose levels carry their world Origin, pixel Bounds, WorldDepth, and Neighbours list, and load lazily into *Tilemap values on demand.

An empty worldIdentifier selects the project's top-level levels (or the sole world when multi-worlds has one entry); a multi-world project with multiple worlds names the world by its identifier. The world's layout must be Free or GridVania (or omitted, defaulting to Free); LinearHorizontal and LinearVertical layouts are refused because they assign no 2D world coordinates.

Its errors are *loaderr.Error values, as LoadLDtk's are.

func LoadLDtkWorldWith(data []byte, worldIdentifier string, opts LDtkOptions) (*LevelWorld, error)

LoadLDtkWorldWith parses an LDtk JSON project (.ldtk) into a LevelWorld using opts (including custom IntGrid-to-TileFlags mappings).

func LoadTiledWorld(data []byte, loader TiledWorldLoader) (*LevelWorld, error)

LoadTiledWorld parses a Tiled .world JSON file and builds a LevelWorld whose levels load lazily through loader.

Each loaded *Tilemap has its Origin set to the map's (x, y) placement from the .world file. When an explicit map entry omits width or height, LoadTiledWorld reads the map's header via loader.LoadMap to populate exact world bounds for streaming; entries with explicit dimensions remain completely lazy until loaded.

func (w *LevelWorld) Level(id string) *WorldLevel

Level returns the first WorldLevel with the given ID, or nil if none matches.

func (w *LevelWorld) LevelAt(p core.Point) *WorldLevel

LevelAt returns the first WorldLevel whose Bounds contain p (using half-open [Origin, Origin+Size)), or nil if none matches.

func (w *LevelWorld) LevelsInRect(r core.Bounds) []*WorldLevel

LevelsInRect returns every WorldLevel whose Bounds overlap r, in deterministic Levels order.

func (w *LevelWorld) LoadAll() (map[string]*Tilemap, error)

LoadAll eagerly loads every level in w and returns them keyed by WorldLevel.ID.

func (w *LevelWorld) LoadLevel(id string) (*Tilemap, error)

LoadLevel loads and returns the *Tilemap for the level with the given ID.

func (w *LevelWorld) WorldBounds() core.Bounds

WorldBounds returns the bounding rectangle spanning every level in w, or a zero Bounds if w has no levels.

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

MemoryChunkStore is an in-memory, concurrency-safe ChunkStore storing plain-text chunk bytes.

func NewMemoryChunkStore() *MemoryChunkStore

NewMemoryChunkStore returns an empty MemoryChunkStore.

func (s *MemoryChunkStore) Bytes(coord ChunkCoord) []byte

Bytes returns a copy of the raw saved bytes for coord, or nil if absent.

func (s *MemoryChunkStore) Count() int

Count returns the number of saved chunks in s.

func (s *MemoryChunkStore) Delete(coord ChunkCoord)

Delete removes any saved entry for coord.

func (s *MemoryChunkStore) Has(coord ChunkCoord) bool

Has reports whether coord has a saved entry in s.

func (s *MemoryChunkStore) LoadChunk(coord ChunkCoord) ([]byte, bool, error)

LoadChunk returns a copy of the saved bytes for coord, or found=false if absent.

func (s *MemoryChunkStore) SaveChunk(coord ChunkCoord, data []byte) error

SaveChunk stores a copy of data under coord.

type Object struct {
	ID       int
	Name     string
	Type     string
	Shape    ObjectShape
	X, Y     float32
	Width    float32
	Height   float32
	Rotation float32
	GID      uint32
	Visible  bool
	Points   []core.Point
	// Text holds the text content and styling when Shape is ObjectText, or nil otherwise.
	Text       *TextObject
	Properties Properties
}

Object is one object from a Tiled objectgroup layer.

func (o Object) FlipFlags() uint32

FlipFlags returns the Tiled flip bits set on a tile object's GID.

func (o Object) PhysicsShape() (physics.Shape, bool)

PhysicsShape returns o's collision shape in map coordinates for static level geometry:

  • a rectangle becomes a physics.Box, or a physics.Polygon when it is rotated;
  • an ellipse becomes a physics.Circle when it is round and a physics.Polygon of 8 vertices inscribed in it otherwise;
  • a polygon becomes a physics.Polygon when it is convex with at most physics.MaxPolygonVertices vertices, and a closed physics.Chain along its outline otherwise, which keeps concave terrain exact;
  • a polyline becomes a physics.Segment when it has two points and an open physics.Chain when it has more.

Rotation turns the object clockwise about (X, Y), as Tiled does. Points, tile objects and objects too small to collide (a rectangle without area, a polygon whose points all lie on one line, a polyline with fewer than two distinct points) report false. The shape ignores the object layer's offset; ObjectLayer.PhysicsBodies applies it.

func (o Object) TileID() uint32

TileID returns the global tile ID of a tile object with flip bits stripped, or 0 for non-tile objects.

func (o Object) WorldPoints() []core.Point

WorldPoints returns the vertices of a polygon or polyline object translated by (X, Y).

type ObjectAlignment int

ObjectAlignment controls which point of a tile object sits at its (X, Y) position and acts as its rotation pivot.

const (
	// ObjectAlignmentUnspecified uses bottom-left in orthogonal/staggered/hexagonal maps and bottom in isometric maps, matching Tiled.
	ObjectAlignmentUnspecified ObjectAlignment = iota
	ObjectAlignmentTopLeft
	ObjectAlignmentTop
	ObjectAlignmentTopRight
	ObjectAlignmentLeft
	ObjectAlignmentCenter
	ObjectAlignmentRight
	ObjectAlignmentBottomLeft
	ObjectAlignmentBottom
	ObjectAlignmentBottomRight
)
type ObjectLayer struct {
	Name       string
	OffsetX    float32
	OffsetY    float32
	ParallaxX  float32
	ParallaxY  float32
	Opacity    float32
	TintColor  core.Color
	Tinted     bool
	Visible    bool
	Objects    []Object
	Properties Properties
}

ObjectLayer is a Tiled objectgroup layer.

func (l *ObjectLayer) PhysicsBodies() []*physics.Body

PhysicsBodies returns a physics.Body for every object of l that has a PhysicsShape, in object order, moved by the layer's offset, for a physics.World's static level geometry. Each body's ID is the object's ID, its Tag the object's Type and its UserData the Object. Hidden objects are included, since collision layers are often hidden in Tiled. Use physics.NewStaticRigidBody(body.Shape) to collide them with a physics.RigidWorld. A nil layer, which Tilemap.ObjectLayer returns for a name the map does not have, has no bodies. Like the objects, the bodies are in the map's local coordinates and ignore Tilemap.Origin; translate their shapes by it for a map placed in a world.

type ObjectShape int

ObjectShape identifies the geometric shape of a Tiled object.

const (
	ObjectRect ObjectShape = iota
	ObjectPoint
	ObjectEllipse
	ObjectPolygon
	ObjectPolyline
	ObjectTile
	ObjectText
)
type Orientation int

Orientation selects how tiles are arranged and projected into world coordinates.

const (
	// OrientationOrthogonal lays tiles out on an axis-aligned rectangular grid.
	OrientationOrthogonal Orientation = iota
	// OrientationIsometric lays tiles out on a diamond isometric grid.
	OrientationIsometric
	// OrientationStaggered lays isometric diamonds out with alternating rows or columns shifted by half a tile.
	OrientationStaggered
	// OrientationHexagonal lays hexagons out with alternating rows (pointy-top) or columns (flat-top) shifted by half a tile.
	OrientationHexagonal
)
type Properties map[string]Property

Properties is a set of named custom properties with typed getters.

func (p Properties) Bool(name string) (bool, bool)

Bool returns the boolean value of name.

func (p Properties) Color(name string) (core.Color, bool)

Color parses a Tiled color property (#RRGGBB or #AARRGGBB) into a core.Color.

func (p Properties) File(name string) (string, bool)

File returns the file path value of a file property (or string property).

func (p Properties) Float(name string) (float64, bool)

Float returns the floating-point value of name (accepting float or int properties).

func (p Properties) Has(name string) bool

Has reports whether a property named name exists.

func (p Properties) Int(name string) (int, bool)

Int returns the integer value of name (matching int and object properties).

func (p Properties) ObjectID(name string) (int, bool)

ObjectID returns the referenced object ID of an object property.

func (p Properties) String(name string) (string, bool)

String returns the string value of name (matching string, color and file properties).

type Property struct {
	Name  string
	Type  string
	Value any
}

Property is one typed custom property on a map, layer, tileset, tile or object.

type RaycastHit struct {
	Col, Row int
	TileID   uint32
	Flags    TileFlags
	Point    core.Point
	Normal   core.Point
	// T is the hit's fraction along the segment from -> to, in [0, 1].
	T float32
}

RaycastHit is the first tile cell met by Tilemap.Raycast.

type StaggerAxis int

StaggerAxis selects which axis is staggered for staggered isometric and hexagonal maps.

const (
	// StaggerY staggers alternating rows horizontally (pointy-top hexagons).
	StaggerY StaggerAxis = iota
	// StaggerX staggers alternating columns vertically (flat-top hexagons).
	StaggerX
)
type StaggerIndex int

StaggerIndex selects whether odd or even rows/columns are shifted in staggered and hexagonal maps.

const (
	// StaggerOdd shifts odd-indexed rows or columns (Tiled default).
	StaggerOdd StaggerIndex = iota
	// StaggerEven shifts even-indexed rows or columns.
	StaggerEven
)
type Terrain struct {
	// Name is the terrain's name in its tileset.
	Name string
	// Autotile maps neighbour masks to the terrain's GIDs; its Default is the tile that lists no neighbours, or 0 when none does.
	Autotile AutotileSet
}

Terrain is one terrain set of a tileset, from a TilesetDoc's Terrains: the autotile set that maps the neighbour mask of a cell to the terrain's tile, in global tile IDs, ready for Tilemap.ApplyAutotile and Tilemap.SetAutotile with Contains as their terrainID.

func (t *Terrain) Contains(gid uint32) bool

Contains reports whether gid, flip bits ignored, is one of the terrain's tiles.

type TerrainDoc struct {
	// Name identifies the terrain within the tileset; tiles name it in TileDoc.Terrain.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Mode is "cardinal", which matches the four edge neighbours (Autotile4, 16 tiles), or "blob", which also matches a corner neighbour when both edges beside it match (Autotile8, 47 tiles).
	Mode string `yaml:"mode" schema:"required,enum=cardinal|blob"`
	// Default is the optional local tile ID used when a cell's neighbour mask has no tile mapped to it. When omitted, the tile of the terrain that lists no neighbours (mask 0) is the default.
	Default *int `yaml:"default,omitempty" schema:"minimum=0"`
}

TerrainDoc is one terrain set of a TilesetDoc: a family of tiles, such as the edges and corners of grass, from which autotiling picks a tile by which neighbouring cells hold the same terrain (Tilemap.ApplyAutotile).

type TerrainRand interface {
	Float64() float64
}

TerrainRand supplies deterministic uniform [0, 1) floats for weighted tie-breaking in SetTerrain and SetTerrainRect. *random.Stream satisfies TerrainRand.

type TextObject struct {
	Text       string
	FontFamily string
	PixelSize  int
	Wrap       bool
	Color      core.Color
	Bold       bool
	Italic     bool
	Underline  bool
	Strikeout  bool
	Kerning    bool
	HAlign     string
	VAlign     string
}

TextObject holds the text content and styling of a Tiled text object.

type TileAnimFrame struct {
	TileID   uint32
	Duration time.Duration
}

TileAnimFrame is one frame of an animated tile: its local tile ID in the tileset and how long it shows.

type TileAnimation struct {
	Frames []TileAnimFrame
	// contains filtered or unexported fields
}

TileAnimation advances one animated tile through its frames in a loop on Tilemap.Update.

func (a *TileAnimation) CurrentTileID() uint32

CurrentTileID returns the local tile ID showing now, or 0 for an empty animation.

func (a *TileAnimation) Index() int

Index returns the index in Frames of the frame showing now.

func (a *TileAnimation) Reset()

Reset restarts the animation from its first frame.

func (a *TileAnimation) Update(dt time.Duration)

Update moves the animation forward by dt, wrapping cleanly across full cycles.

type TileDoc struct {
	// ID is the tile's local ID, from 0 to the tileset's tile count less 1.
	ID int `yaml:"id" schema:"required,minimum=0"`
	// Name is an optional human-readable name for the tile, such as "stone" or "moss".
	Name string `yaml:"name,omitempty"`
	// Solid sets TileSolid on the tile, so collision queries and tileshape treat its cells as blocked.
	Solid bool `yaml:"solid,omitempty"`
	// OneWay sets TileOneWay on the tile, a platform that blocks only from above.
	OneWay bool `yaml:"oneWay,omitempty"`
	// Flags are further TileFlags bits the game defines, such as a water or ladder bit, set on the tile beside Solid and OneWay.
	Flags TileFlags `yaml:"flags,omitempty"`
	// Weight is the tile's optional relative selection weight for random and variant brushes (>= 0; omitted defaults to 1).
	Weight *float64 `yaml:"weight,omitempty" schema:"minimum=0"`
	// Properties are the tile's custom properties, each a bool, an integer, a number or a string, as Tilemap.TileProperties returns them.
	Properties map[string]any `yaml:"properties,omitempty"`
	// Shapes are the tile's collision shapes in its own coordinates, (0, 0) at its top left, as Tileset.Shapes holds them.
	Shapes []TileShapeDoc `yaml:"shapes,omitempty"`
	// Animation, when set, makes the tile cycle through these frames in a loop as Tilemap.Update advances time.
	Animation []TileFrameDoc `yaml:"animation,omitempty"`
	// Terrain names the entry of TilesetDoc.Terrains the tile belongs to.
	Terrain string `yaml:"terrain,omitempty"`
	// Neighbors lists the directions in which a cell of the same terrain lies next to a cell this tile fills: north, east, south and west, and for a blob terrain also northeast, southeast, southwest and northwest, each only with both edges beside it (northeast with north and east), since a corner matches only when they do. No two tiles of one terrain list the same set, and the tile that lists none is the terrain's default. It requires Terrain.
	Neighbors []string `yaml:"neighbors,omitempty,flow"`
}

TileDoc describes one tile of a TilesetDoc.

type TileFlags uint32

TileFlags is a bitmask of gameplay and collision properties on a tile.

const (
	// TileSolid marks a tile that blocks movement from all sides.
	TileSolid TileFlags = 1 << 0
	// TileOneWay marks a tile that blocks movement only from one side (such as a platform).
	TileOneWay TileFlags = 1 << 1
)
func (f TileFlags) PhysicsFlags() physics.TileFlags

PhysicsFlags maps tilemap TileFlags to physics.TileFlags. TileSolid (bit 0) and TileOneWay (bit 1) map directly to physics.TileSolid and physics.TileOneWay, and game-defined bits 2..31 are preserved verbatim.

type TileFrameDoc struct {
	// Tile is the local ID of the tile the frame shows. It is required, so a frame never shows tile 0 by omission.
	Tile int `yaml:"tile" schema:"required,minimum=0"`
	// Duration is how long the frame shows, positive, written as a Go duration such as 150ms.
	Duration time.Duration `yaml:"duration" schema:"required"`
}

TileFrameDoc is one frame of a tile's animation.

type TileHit struct {
	Col, Row int
	TileID   uint32
	Flags    TileFlags
	Bounds   core.Bounds
}

TileHit is one tile cell returned by Tilemap.TilesInRect.

type TileImage struct {
	Image  core.ImageSource
	X      float32
	Y      float32
	Width  float32
	Height float32
}

TileImage is one tile's image and source rectangle in an image-collection tileset.

type TileLayer struct {
	Name   string
	Width  int
	Height int
	StartX int
	StartY int
	Data   []uint32
	// ChunkSize is the power-of-two edge length (in tiles) for sparse chunked layers; 0 selects a dense Data layer.
	ChunkSize int
	OffsetX   float32
	OffsetY   float32
	ParallaxX float32
	ParallaxY float32
	Opacity   float32
	TintColor core.Color
	// Tinted distinguishes an explicit TintColor (including transparent black #00000000) from an untinted layer.
	// Setting TintColor to a non-zero color also tints the layer when Tinted is false.
	Tinted  bool
	Visible bool
	// YSort enables per-tile Y-sorting for this layer. When true, visible tiles sort by
	// their bottom edge (plus any per-tile PropSortOriginY property offset) and join a
	// Y-sorted scene.Layer's draw list alongside sprites and drawables.
	YSort      bool
	Properties Properties
	// contains filtered or unexported fields
}

TileLayer is one row-major grid of tile GIDs drawn in map order, or a sparse chunked layer when ChunkSize > 0.

Its zero value is hidden and transparent; NewTileLayer and NewChunkedTileLayer return visible layers at full opacity.

func NewChunkedTileLayer(name string, chunkSize int) TileLayer

NewChunkedTileLayer returns a visible sparse chunked TileLayer at full opacity using a power-of-two chunkSize (defaulting to DefaultChunkSize when chunkSize <= 0).

func NewTileLayer(name string, width, height int, data []uint32) TileLayer

NewTileLayer returns a visible TileLayer at full opacity. When data is nil it allocates a width*height slice.

func (l *TileLayer) Chunk(coord ChunkCoord) *Chunk

Chunk returns the loaded chunk at coord, or nil if coord is not loaded.

func (l *TileLayer) ChunkCoords() []ChunkCoord

ChunkCoords returns the coordinates of all currently loaded chunks in deterministic row-major (Y, X) order.

func (l *TileLayer) ChunkCount() int

ChunkCount returns the number of currently loaded chunks in l, or 0 for dense or empty layers.

func (l *TileLayer) ChunkTileBounds() (minCol, minRow, maxCol, maxRow int, ok bool)

ChunkTileBounds returns the inclusive tile-coordinate bounding box [minCol, maxCol] × [minRow, maxRow] spanning all currently loaded chunks in l, or ok=false if no chunks are loaded.

func (l *TileLayer) DirtyChunks() []ChunkCoord

DirtyChunks returns the coordinates of all loaded chunks whose Dirty flag is set, sorted in deterministic (Y, X) order.

func (l *TileLayer) EffectiveChunkSize() int

EffectiveChunkSize returns the power-of-two chunk size for a chunked layer, or 0 for a dense layer.

func (l *TileLayer) IsChunked() bool

IsChunked reports whether l uses sparse chunked storage rather than a dense Data slice.

func (l *TileLayer) ModifiedChunks() []ChunkCoord

ModifiedChunks returns the coordinates of all loaded chunks whose Modified flag is set, sorted in deterministic (Y, X) order.

type TileShape struct {
	// Shape is the kind of object the shape came from: ObjectRect, ObjectEllipse, ObjectPolygon or ObjectPolyline.
	Shape ObjectShape
	// Name and Type are the object's name and type (or class) in the collision editor.
	Name string
	Type string
	// Points are the shape's vertices in the tile's coordinates.
	Points []core.Point
	// Properties are the object's custom properties.
	Properties Properties
}

TileShape is one collision shape a tileset gives a tile, such as the rectangles, polygons and ellipses Tiled's collision editor stores on a tile.

Points are in the tile's own coordinates, with (0, 0) at the top-left of the tileset's tile and (TileWidth, TileHeight) at its bottom-right, already rotated by the object's rotation. A closed shape (every Shape except ObjectPolyline) is the polygon through its points, with an edge from the last point back to the first; an ellipse is approximated by EllipseShapeSegments points on its outline, and a rectangle has its four corners.

func (s TileShape) Closed() bool

Closed reports whether s is a closed polygon rather than an open polyline.

func (s TileShape) Flipped(flags uint32, tileWidth, tileHeight float32) TileShape

Flipped returns s mirrored and rotated as Tiled's flip bits in flags place a tile of tileWidth by tileHeight on a map, the same transform DrawLayer applies to the tile's image.

FlipDiagonal swaps the axes first, then FlipHorizontal mirrors left to right and FlipVertical top to bottom, so the eight combinations give every 90 degree rotation of a tile with and without a mirror. Flipped returns s unchanged when flags holds no flip bit, and a copy with new Points otherwise.

type TileShapeDoc struct {
	// Kind is "rect" or "ellipse", given by X, Y, Width and Height, or "polygon" or "polyline", given by Points. An ellipse becomes a polygon of EllipseShapeSegments edges.
	Kind string `yaml:"kind" schema:"required,enum=rect|ellipse|polygon|polyline"`
	// Name and Type label the shape for game code, as a Tiled object's name and type do.
	Name string `yaml:"name,omitempty"`
	Type string `yaml:"type,omitempty"`
	// X and Y are the top left of a rect or ellipse's box, and Width and Height its positive size.
	X      float32 `yaml:"x,omitempty"`
	Y      float32 `yaml:"y,omitempty"`
	Width  float32 `yaml:"width,omitempty" schema:"minimum=0"`
	Height float32 `yaml:"height,omitempty" schema:"minimum=0"`
	// Points are the [x, y] vertices of a polygon (at least 3) or polyline (at least 2).
	Points [][]float32 `yaml:"points,omitempty,flow"`
	// Properties are the shape's custom properties, each a bool, an integer, a number or a string.
	Properties map[string]any `yaml:"properties,omitempty"`
}

TileShapeDoc is one collision shape of a tile, in the tile's coordinates.

type TiledWorld struct {
	Maps                 []TiledWorldMap
	Patterns             []TiledWorldPattern
	OnlyShowAdjacentMaps bool
}

TiledWorld is the parsed representation of a Tiled .world JSON file.

func ParseTiledWorld(data []byte) (*TiledWorld, error)

ParseTiledWorld parses a Tiled .world JSON file, compiling and validating every pattern regular expression.

Both explicit maps entries (fileName, x, y, optional width and height) and regex patterns (regexp, multiplierX, multiplierY, offsetX, offsetY, mapWidth, mapHeight) are supported.

Its errors are *loaderr.Error values that give the line, column and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.

func (w *TiledWorld) Resolve(fileNames []string) []TiledWorldMap

Resolve expands w into every concrete map placement: explicit Maps first (in file order), followed by any candidate file in fileNames matching Patterns (sorted lexicographically, with the first matching pattern winning and files already listed in Maps skipped).

type TiledWorldLoader struct {
	// LoadMap reads the raw .tmj JSON bytes for fileName (as written in the .world file or returned by ListFiles).
	LoadMap func(fileName string) ([]byte, error)
	// ListFiles returns candidate map filenames (relative to the .world file) to match against Patterns.
	// Optional when the .world file defines no patterns.
	ListFiles func() ([]string, error)
	// Tilesets resolves external .tsj tilesets and images for each map when ResolveTilesets is nil.
	Tilesets TilesetLoader
	// ResolveTilesets optionally builds a map-specific TilesetLoader for fileName (for example when maps live in subdirectories).
	ResolveTilesets func(fileName string) TilesetLoader
}

TiledWorldLoader configures how LoadTiledWorld reads .tmj map files and discovers pattern-matched filenames.

type TiledWorldMap struct {
	FileName string
	X        int
	Y        int
	Width    int
	Height   int
}

TiledWorldMap describes one map placement inside a Tiled .world file.

func (m TiledWorldMap) Bounds() core.Bounds

Bounds returns the map's world bounding rectangle. Width and Height may be 0 if omitted in the .world file.

func (m TiledWorldMap) Origin() core.Point

Origin returns the map's top-left world position (X, Y) in points.

type TiledWorldPattern struct {
	Regexp      string
	MultiplierX int
	MultiplierY int
	OffsetX     int
	OffsetY     int
	MapWidth    int
	MapHeight   int
	// contains filtered or unexported fields
}

TiledWorldPattern describes one regex-based map grid pattern inside a Tiled .world file.

Capturing group 1 gives the grid X index and capturing group 2 (when present) gives the grid Y index; the world position is (gx*MultiplierX + OffsetX, gy*MultiplierY + OffsetY). Following Tiled's specification, MultiplierX/MapWidth and MultiplierY/MapHeight default to each other when one is 0.

func (p *TiledWorldPattern) Match(fileName string) (TiledWorldMap, bool)

Match tests fileName against p's regular expression and returns its resolved TiledWorldMap when it matches. If fileName includes a directory prefix and does not match directly, its base filename is tested as well.

type Tilemap struct {
	Width      int
	Height     int
	TileWidth  float32
	TileHeight float32
	// Origin is the world-space position of the map's local (0, 0) point (typically the top-left corner of cell (0, 0)).
	// Drawing, WorldBounds, TileOrigin, TileToWorld, WorldToTile, TilesInRect, Raycast, and AppendYSortTiles all honor Origin.
	Origin        core.Point
	Orientation   Orientation
	StaggerAxis   StaggerAxis
	StaggerIndex  StaggerIndex
	HexSideLength float32
	Infinite      bool
	Layers        []TileLayer
	ImageLayers   []ImageLayer
	Tilesets      []*Tileset
	Objects       []ObjectLayer
	Properties    Properties
	// Neighbours lists adjacent or overlapping levels in a multi-level world (populated by LDtk loaders).
	Neighbours []LevelNeighbour
	// contains filtered or unexported fields
}

Tilemap is a tiled world of tile layers, image layers, tilesets, object layers, custom properties and per-tile collision flags.

func LoadLDtk(data []byte, levelIdentifier string, resolveImage func(relPath string) core.ImageSource) (*Tilemap, error)

LoadLDtk parses an LDtk JSON project and builds a Tilemap for the level matching levelIdentifier (or the first level when levelIdentifier is empty).

Tiles (gridTiles), AutoLayer (autoLayerTiles), IntGrid (intGridCsv mapped to TileSolid/TileFlags plus optional autoLayerTiles), and Entities (entityInstances mapped to ObjectLayer with fieldInstances properties) are supported, including LDtk flip bits (bit 0 = FlipHorizontal, bit 1 = FlipVertical). For Free and GridVania layouts, the returned Tilemap's Origin is set from the level's (worldX, worldY) and its Neighbours are populated from __neighbours.

Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.

func LoadLDtkWith(data []byte, levelIdentifier string, opts LDtkOptions) (*Tilemap, error)

LoadLDtkWith parses an LDtk JSON project with opts (including custom IntGrid-to-TileFlags mappings, such as those produced by project.File.LDtkOptions) and builds a Tilemap for the level matching levelIdentifier (or the first level when levelIdentifier is empty).

func LoadTiled(data []byte, resolve TilesetLoader) (*Tilemap, error)
func New(width, height int, tileWidth, tileHeight float32, tilesets ...*Tileset) *Tilemap

New constructs an empty Tilemap of width by height tiles sized tileWidth by tileHeight points.

func NewInfinite(tileWidth, tileHeight float32, tilesets ...*Tileset) *Tilemap

NewInfinite constructs an unbounded Tilemap with Infinite set to true. Add sparse layers with NewChunkedTileLayer.

func (m *Tilemap) AddTilesetDoc(doc *TilesetDoc, firstGID uint32, assets TilesetAssets) (*Tileset, error)

AddTilesetDoc builds doc, which must validate, into a Tileset whose global tile IDs start at firstGID (1 when 0), resolving its image or atlas through assets, appends it to m.Tilesets in FirstGID order and sets the flags of its tiles on m (SetFlags). The new tileset carries doc's properties, per-tile properties, collision shapes, animations and terrain sets.

It refuses a tileset whose IDs would run past TileIDMask or overlap a tileset m already has, an atlas tileset without assets.Atlas, and atlas frames the atlas lacks.

func (m *Tilemap) AppendYSortTiles(dst []YSortTile, layer *TileLayer, cam *Camera) []YSortTile

AppendYSortTiles appends every visible non-empty tile of layer overlapping cam.VisibleBounds() (or every non-empty tile when cam is nil) to dst in deterministic painter's order, returning the updated slice.

Each tile's SortY is its bottom edge in world coordinates (offY + tileOriginY + TileHeight) plus any per-tile PropSortOriginY offset. Animated tiles resolve to their current frame at call time. Reusing dst across frames performs zero heap allocations once its capacity is warmed up.

func (m *Tilemap) ApplyAutotile(layerIndex int, set AutotileSet, terrainID func(gid uint32) bool)

ApplyAutotile updates every terrain cell in layerIndex using set's bitmask-to-GID mapping.

terrainID reports whether a raw tile GID belongs to the terrain (nil treats any non-zero GID as terrain).

func (m *Tilemap) ApplyTerrain(layerIndex int, terrainName string) bool

ApplyTerrain updates every cell belonging to the named terrain in layerIndex using its autotile rules, returning false when the terrain is not defined on any tileset of m or layerIndex is out of range.

func (m *Tilemap) CacheDirtyChunks(layerIndex int, images map[string]image.Image) (int, error)

CacheDirtyChunks bakes every dirty or uncached loaded chunk in the chunked layer at layerIndex (in deterministic (Y, X) order) and returns how many chunks were baked.

func (m *Tilemap) CacheStaticChunk(layerIndex int, coord ChunkCoord, images map[string]image.Image) (*LayerCache, error)

CacheStaticChunk bakes one loaded chunk of a sparse chunked layer into a premultiplied *image.RGBA buffer so Draw and DrawLayer draw that chunk in a single DrawImageFrom operation.

If the chunk is empty (all GIDs are 0), any existing cache on that chunk is cleared and (nil, nil) is returned. Editing a tile inside another chunk never invalidates this chunk's cache.

func (m *Tilemap) CacheStaticLayer(layerIndex int, images map[string]image.Image) (*image.RGBA, core.ImageSource, error)

CacheStaticLayer bakes a static (non-animated) tile layer into a premultiplied *image.RGBA buffer and attaches it to the map so Draw and DrawLayer draw the layer in a single DrawImageFrom operation.

images maps tileset image URIs (with or without an "asset:" prefix) or tileset names to decoded image.Image pixel data; tilesets whose core.ImageSource.Pixels is already populated do not need an entry in images. Modifying the layer via SetTile or FillRect automatically marks the cache dirty.

func (m *Tilemap) CellFlags(col, row int) (TileFlags, bool)

CellFlags returns the per-cell override SetCellFlags set at (col, row) and whether one is set.

func (m *Tilemap) ChunkAt(layerIndex int, coord ChunkCoord) *Chunk

ChunkAt returns the loaded chunk at coord in layerIndex, or nil if layerIndex is out of range, dense, or does not currently have coord loaded.

func (m *Tilemap) ChunkCache(layerIndex int, coord ChunkCoord) *LayerCache

ChunkCache returns the static cache entry for coord in the chunked layer at layerIndex, or nil if absent or uncached.

func (m *Tilemap) ChunkCoordForTile(layerIndex, col, row int) (ChunkCoord, bool)

ChunkCoordForTile converts tile (col, row) to the ChunkCoord owning it in layerIndex. Returns ok=false if layerIndex is out of range or not a chunked layer.

func (m *Tilemap) ClearCellFlags(col, row int)

ClearCellFlags removes any per-cell flag override at (col, row), restoring its tile-ID flags.

func (m *Tilemap) ClearChunkCache(layerIndex int, coord ChunkCoord)

ClearChunkCache removes the static cache for coord in layerIndex without affecting other chunks.

func (m *Tilemap) ClearLayerCache(layerIndex int)

ClearLayerCache removes any cached image for layerIndex (or all per-chunk caches on a chunked layer).

func (m *Tilemap) Draw(d *core.Drawing, cam *Camera)

Draw draws every visible tile layer, image layer, and object layer (tile objects) into d in map layer order, culling to cam's visible world region when cam is non-nil.

Draw draws in world coordinates: call cam.Apply(d) before Draw (and any world-space sprites) to position the view.

func (m *Tilemap) DrawImageLayer(d *core.Drawing, layer *ImageLayer, cam *Camera)

DrawImageLayer draws one image layer into d, applying its visibility, opacity, tint, offset, parallax factor, and repeat flags.

func (m *Tilemap) DrawLayer(d *core.Drawing, layer *TileLayer, cam *Camera)

DrawLayer draws one tile layer into d, visiting only the visible tiles overlapping cam.VisibleBounds() when cam is non-nil.

When layer.YSort is true, visible tiles are sorted in stable ascending SortY order (respecting per-tile PropSortOriginY offsets) and drawn individually without using any static layer cache. Otherwise, when the layer has a clean static cache created via CacheStaticLayer, DrawLayer draws it in a single DrawImageFrom operation.

func (m *Tilemap) DrawObjectLayer(d *core.Drawing, layer *ObjectLayer, cam *Camera)

DrawObjectLayer draws every visible tile object in layer into d in object order, applying layer visibility, opacity, tint, offset, parallax, object size, rotation, flip flags, tileset tileoffset, and tileset objectalignment, culling to cam.VisibleBounds() when cam is non-nil.

func (m *Tilemap) FillRect(layerIndex, col, row, w, h int, gid uint32)

FillRect writes gid across [col, col+w) x [row, row+h) in layerIndex.

On dense layers, out-of-bounds portions are clipped; on sparse chunked layers, arbitrary negative and positive rectangles are supported and only chunks whose tiles actually change are marked Dirty and Modified. Non-positive sizes are ignored.

func (m *Tilemap) Flags(tileID uint32) TileFlags

Flags returns the TileFlags set on global tile ID tileID with SetFlags or from its tileset's properties, ignoring flip bits and any per-cell override.

func (m *Tilemap) FlagsAt(col, row int) TileFlags

FlagsAt returns the combined TileFlags at (col, row) across all tile layers, or 0 if out of bounds.

func (m *Tilemap) GridOrigin() (x, y float32)

GridOrigin returns the world-space origin of cell (0, 0), satisfying physics.TileGridOrigin.

func (m *Tilemap) GridSize() (cols, rows int)

GridSize returns the map's width and height in tile columns and rows, satisfying physics.TileGrid.

func (m *Tilemap) HasYSortLayers() bool

HasYSortLayers reports whether m contains at least one visible tile layer with YSort enabled.

func (m *Tilemap) HexDistance(c1, r1, c2, r2 int) int

HexDistance returns the grid step distance between hexagonal cells (c1, r1) and (c2, r2).

func (m *Tilemap) HexNeighbors(col, row int) [6][2]int

HexNeighbors returns the 6 hexagonal neighbors of offset cell (col, row) for the map's StaggerAxis and StaggerIndex.

func (m *Tilemap) ImageLayer(name string) *ImageLayer

ImageLayer returns the first image layer with the given name, or nil if none matches.

func (m *Tilemap) InvalidateChunkCache(layerIndex int, coord ChunkCoord)

InvalidateChunkCache marks only the chunk at coord in layerIndex dirty without disturbing other chunks.

func (m *Tilemap) InvalidateLayerCache(layerIndex int)

InvalidateLayerCache marks any cached image for layerIndex dirty so subsequent Draw calls fall back to live tile drawing until recached. For sparse chunked layers, all loaded chunks in layerIndex are marked dirty.

func (m *Tilemap) Layer(name string) *TileLayer

Layer returns the first tile layer with the given name, or nil if none matches.

func (m *Tilemap) LayerCache(layerIndex int) *LayerCache

LayerCache returns the static cache entry for layerIndex, or nil if that layer has not been cached.

func (m *Tilemap) ObjectLayer(name string) *ObjectLayer

ObjectLayer returns the first object layer with the given name, or nil if none matches.

func (m *Tilemap) PutChunk(layerIndex int, chunk *Chunk) error

PutChunk installs chunk into the chunked layer at layerIndex, replacing any existing chunk at chunk.Coord.

chunk.Size must match the layer's EffectiveChunkSize() and len(chunk.Tiles) must equal chunk.Size*chunk.Size. The installed chunk's Dirty flag is set to true so any static chunk cache is rebuilt, while chunk.Modified is preserved as passed.

func (m *Tilemap) Raycast(from, to core.Point, mask TileFlags) (RaycastHit, bool)

Raycast traces the line segment from -> to and returns the first tile matching mask (or any non-empty tile when mask == 0).

func (m *Tilemap) RemoveChunk(layerIndex int, coord ChunkCoord) *Chunk

RemoveChunk unloads and returns the chunk at coord from layerIndex (clearing its static cache), or returns nil if layerIndex is out of range, dense, or coord is not loaded.

func (m *Tilemap) SetAutotile(layerIndex, col, row int, placed bool, set AutotileSet, terrainID func(gid uint32) bool)

SetAutotile places (placed=true) or removes (placed=false) a terrain tile at (col, row) in layerIndex and updates that cell and all 8 surrounding terrain neighbors cleanly.

terrainID reports whether a raw tile GID belongs to the terrain (nil treats any non-zero GID as terrain).

func (m *Tilemap) SetCellFlags(col, row int, flags TileFlags)

SetCellFlags overrides the flags at a single map cell (col, row), taking precedence over per-tile flags. On maps with sparse chunked layers (or Infinite=true), negative and arbitrary positive coordinates are supported.

func (m *Tilemap) SetFlags(tileID uint32, flags TileFlags)

SetFlags sets the TileFlags associated with global tile ID tileID (flip bits are ignored).

func (m *Tilemap) SetLayerYSort(layerIndex int, enabled bool)

SetLayerYSort enables or disables per-tile Y-sorting on m.Layers[layerIndex]. Out-of-range layer indices are ignored.

func (m *Tilemap) SetTerrain(layerIndex, col, row int, set *WangSet, terrain uint8, rng TerrainRand)

SetTerrain paints terrain (1-based index into set.Colors, or 0 to erase) at (col, row) in layerIndex, choosing tiles matching every neighbor's shared edges and corners for corner, edge, and mixed Wang sets.

Works on both orthogonal and isometric maps as well as dense and sparse chunked layers. When multiple tiles tie for best match, SetTerrain picks deterministically by tile probability using rng (or the lowest local TileID when rng is nil).

func (m *Tilemap) SetTerrainRect(layerIndex, col, row, w, h int, set *WangSet, terrain uint8, rng TerrainRand)

SetTerrainRect paints terrain (1-based index into set.Colors, or 0 to erase) across [col, col+w) x [row, row+h) in layerIndex, updating painted cells and all affected neighbors so multi-terrain transitions remain seamless.

On dense layers, out-of-bounds portions are clipped; on sparse chunked layers, arbitrary negative and positive rectangles are supported. Non-positive sizes are ignored.

func (m *Tilemap) SetTerrainTile(layerIndex, col, row int, terrainName string, placed bool) bool

SetTerrainTile places (placed=true) or removes (placed=false) a tile of the named terrain at (col, row) in layerIndex and updates that cell and its neighbors using SetAutotile, returning false when the terrain is not defined on any tileset of m or layerIndex is out of range.

func (m *Tilemap) SetTile(layerIndex, col, row int, gid uint32)

SetTile writes a raw GID at (col, row) in layerIndex; out-of-bounds calls on dense layers are ignored.

On sparse chunked layers, arbitrary negative and positive coordinates are supported, allocating a chunk on demand when gid != 0, and marking only that chunk Dirty and Modified (leaving all other chunks and their static caches clean). On dense layers, any cached static image for layerIndex is marked dirty so subsequent draws reflect the change immediately, and collision queries (FlagsAt, TilesInRect, Raycast) observe the updated tile at once.

func (m *Tilemap) SetTileSortOriginY(gid uint32, offsetY float32)

SetTileSortOriginY sets the per-tile vertical Y-sort origin offset (in points relative to the tile's default bottom edge) on gid's tileset under PropSortOriginY.

Negative values shift the sort line upward (for example into a tall tree's trunk); positive values shift it downward.

func (m *Tilemap) Terrain(name string) *Terrain

Terrain returns the terrain set named name of the first of m's tilesets that defines one, or nil.

func (m *Tilemap) TileAt(layerIndex, col, row int) uint32

TileAt returns the raw GID (including flip flags) at (col, row) in layerIndex, or 0 if out of bounds or unloaded. For sparse chunked layers, negative and arbitrary positive coordinates are supported.

func (m *Tilemap) TileBox(gid uint32) (width, height float32)

TileBox returns the size of gid's tile in its tileset, which is the box its collision shapes are measured in, falling back to the map's tile size when the tileset gives none or gid has no tileset.

func (m *Tilemap) TileChangesSince(rev uint64, fn func(col, row int)) (current uint64, ok bool)

TileChangesSince calls fn for each cell (col, row) whose tile or per-cell flags changed (through SetTile, FillRect, SetCellFlags or ClearCellFlags) since rev, and returns the current revision and whether every change since rev fit in the log.

When ok is false (for example after a bulk FillRect, a PutChunk or RemoveChunk, a SetFlags call, which can change every cell showing the tile, or more edits than the log holds), callers should rebuild from the full map.

func (m *Tilemap) TileCollisionGroup(gid uint32) (ObjectLayer, bool)

TileCollisionGroup returns the collision ObjectLayer authored on gid's tile in its tileset (flip bits ignored), and whether the tile defines one.

func (m *Tilemap) TileFlagsAt(col, row int) physics.TileFlags

TileFlagsAt returns the collision flags at (col, row) mapped to physics.TileFlags, satisfying physics.TileGrid.

func (m *Tilemap) TileOrigin(col, row int) core.Point

TileOrigin returns the top-left corner of tile (col, row)'s bounding box in world coordinates.

func (m *Tilemap) TileProperties(gid uint32) Properties

TileProperties returns the custom properties attached to gid in its tileset, or nil if none exist.

func (m *Tilemap) TileRevision() uint64

TileRevision returns a counter incremented whenever SetTile, FillRect, PutChunk or RemoveChunk changes a tile cell, or SetFlags, SetCellFlags or ClearCellFlags changes collision flags.

func (m *Tilemap) TileShapes(gid uint32) []TileShape

TileShapes returns the collision shapes of gid's tile, flipped and rotated by gid's flip bits in the coordinates of its tileset's tile, or nil when the tile has none.

An unflipped gid returns the tileset's own slice, which the caller must not modify.

func (m *Tilemap) TileSize() (width, height float32)

TileSize returns the width and height of one tile in world coordinates, satisfying physics.TileGrid.

func (m *Tilemap) TileSortOriginY(gid uint32) float32

TileSortOriginY returns the per-tile vertical Y-sort origin offset configured on gid (checking PropSortOriginY, "y_sort_origin", and "ysort_origin"), or 0 if unset.

func (m *Tilemap) TileToWorld(col, row int) core.Point

TileToWorld returns the world-space center of tile (col, row) for the map's Orientation and Origin.

WorldToTile(TileToWorld(col, row)) round-trips back to (col, row) for orthogonal, isometric, staggered, and hexagonal maps.

func (m *Tilemap) TilesInRect(r core.Bounds, mask TileFlags) []TileHit

TilesInRect returns every map cell overlapping r whose flags match mask (or every non-empty cell when mask == 0), in row-major order.

Cells are half-open [col*TileWidth, (col+1)*TileWidth) x [row*TileHeight, (row+1)*TileHeight), so a rectangle touching an adjacent tile's edge or corner does not include it.

func (m *Tilemap) TilesetForGID(gid uint32) (*Tileset, uint32)

TilesetForGID finds the tileset owning gid and returns it along with the 0-based local tile ID.

func (m *Tilemap) Update(dt time.Duration)

Update advances all animated tiles in every tileset by dt.

func (m *Tilemap) VisitLayers(fn func(tile *TileLayer, img *ImageLayer))

VisitLayers calls fn for every tile layer and image layer of m in map draw order. Exactly one of tile or img is non-nil on each call.

func (m *Tilemap) WangSet(name string) *WangSet

WangSet returns the first WangSet named name across all tilesets of m, or nil if none matches.

func (m *Tilemap) WorldBounds() core.Bounds

WorldBounds returns the world rectangle covering the whole map for its Orientation and Origin. For unbounded chunked maps with non-positive Width/Height, it returns the bounding box of currently loaded chunks.

func (m *Tilemap) WorldToTile(p core.Point) (col, row int)

WorldToTile converts a world-space point into the (col, row) tile coordinates containing it for the map's Orientation and Origin.

type Tileset struct {
	Name     string
	FirstGID uint32
	Image    core.ImageSource
	Atlas    *sprite.Atlas
	Frames   []sprite.Frame
	// TileImages holds per-tile images for image-collection tilesets, keyed by 0-based local tile ID.
	TileImages      map[uint32]TileImage
	TileWidth       float32
	TileHeight      float32
	TileOffsetX     float32
	TileOffsetY     float32
	ObjectAlignment ObjectAlignment
	Columns         int
	TileCount       int
	Spacing         float32
	Margin          float32
	Properties      Properties
	// TileProperties holds custom properties keyed by 0-based local tile ID.
	TileProperties map[uint32]Properties
	// TileProbabilities holds per-tile random selection weights keyed by 0-based local tile ID (unset defaults to 1).
	TileProbabilities map[uint32]float64
	// Animations holds tile animations keyed by 0-based local tile ID.
	Animations map[uint32]*TileAnimation
	// TileCollisions holds each tile's collision object group as authored in Tiled's collision editor (.tmj/.tsj/.tmx/.tsx), keyed by 0-based local tile ID.
	TileCollisions map[uint32]*ObjectLayer
	// Shapes holds the collision shapes of tiles keyed by 0-based local tile ID, such as the ones Tiled's collision editor draws; an animated tile keeps the shapes of its own ID whichever frame shows.
	Shapes map[uint32][]TileShape
	// WangSets holds Tiled Wang sets (terrain sets) defined on this tileset.
	WangSets []WangSet
	// Terrains are the tileset's terrain sets, such as the ones a YAML tileset defines (TilesetDoc.Terrains), in their order there; Tilemap.Terrain finds one by name.
	Terrains []*Terrain
}

Tileset maps global tile IDs starting at FirstGID to rectangles of a grid image, frames of a sprite.Atlas, or per-tile images of an image-collection tileset.

func NewAtlasTileset(firstGID uint32, atlas *sprite.Atlas, frameNames ...string) *Tileset

NewAtlasTileset builds a Tileset from atlas whose local tile IDs (0, 1, ...) correspond to frameNames in order.

FirstGID defaults to 1 when 0.

func NewGridTileset(firstGID uint32, img core.ImageSource, tileWidth, tileHeight float32, columns, tileCount int) *Tileset

NewGridTileset builds a uniform grid Tileset over img with columns tiles per row.

FirstGID defaults to 1 when 0.

func (ts *Tileset) TileProbability(localID uint32) float64

TileProbability returns the selection probability for localID, defaulting to 1 when unset.

func (ts *Tileset) WangSet(name string) *WangSet

WangSet returns the first WangSet on ts with the given name, or nil if none matches.

func (ts *Tileset) WangSetAt(index int) *WangSet

WangSetAt returns the WangSet at index in ts.WangSets, or nil if index is out of range.

type TilesetAssets struct {
	// Image returns the image at a tileset's Image path. When nil the image is core.ImageSource{URI: path}.
	Image func(path string) (core.ImageSource, error)
	// Atlas returns the atlas a tileset's Atlas names. It is required for an atlas tileset.
	Atlas func(name string) (*sprite.Atlas, error)
}

TilesetAssets resolves the image or atlas a TilesetDoc draws from, for Tilemap.AddTilesetDoc.

type TilesetDoc struct {
	// Version is the schema version; it must be 1.
	Version int `yaml:"version" schema:"required"`
	// Name is the tileset's human-readable name.
	Name string `yaml:"name,omitempty"`
	// TileWidth and TileHeight are each tile's size in points; both must be positive.
	TileWidth  int `yaml:"tileWidth" schema:"required,exclusiveMinimum=0"`
	TileHeight int `yaml:"tileHeight" schema:"required,exclusiveMinimum=0"`
	// Image is the grid image the tiles are cut from, a slash-separated path from the project root such as "tiles/cave.png". It requires Columns and TileCount.
	Image string `yaml:"image,omitempty"`
	// Columns is how many tiles one row of Image holds.
	Columns int `yaml:"columns,omitempty" schema:"minimum=0"`
	// TileCount is how many tiles Image holds, at most MaxTilesetTiles.
	TileCount int `yaml:"tileCount,omitempty" schema:"minimum=0"`
	// Spacing is the gap in points between neighbouring tiles of Image, and Margin the gap around its edge.
	Spacing int `yaml:"spacing,omitempty" schema:"minimum=0"`
	Margin  int `yaml:"margin,omitempty" schema:"minimum=0"`
	// Atlas names the sprite atlas the tiles are frames of, as a scene's sprites name atlases. It requires Frames.
	Atlas string `yaml:"atlas,omitempty"`
	// Frames are the names of Atlas's frames that are the tiles, in local ID order, at most MaxTilesetTiles and each named once.
	Frames []string `yaml:"frames,omitempty"`
	// Properties are custom properties of the whole tileset, each a bool, an integer, a number or a string. EncodeTileset writes a whole-number float with a decimal point (2.0), so that it reads back as a float.
	Properties map[string]any `yaml:"properties,omitempty"`
	// Terrains are the terrain sets the tiles' Terrain fields name, each with a unique name.
	Terrains []TerrainDoc `yaml:"terrains,omitempty"`
	// Tiles describe the tiles that carry anything beyond their picture, in ascending ID order with each ID at most once. A tile left out has no properties, flags, shapes, animation or terrain.
	Tiles []TileDoc `yaml:"tiles,omitempty"`
}

TilesetDoc is a versioned YAML tileset (*.tileset.yaml), the text counterpart of Godot's TileSet resource: what each tile of one image or sprite atlas is, its custom properties, collision flags and shapes, animation and terrain, defined once so that maps only place tiles. Tilemap.AddTilesetDoc builds it into a Tileset.

A tileset draws its tiles either from a grid image (Image, Columns and TileCount, with optional Spacing and Margin) or from frames of a sprite atlas (Atlas and Frames); exactly one of Image and Atlas is set. A tile's local ID is its index in the grid, row by row from the top left, or in Frames, starting at 0.

func LoadTilesetFS(fsys fs.FS, path string) (*TilesetDoc, error)

LoadTilesetFS reads the tileset file at path from fsys and parses it with ParseTileset, naming the file in its errors.

func ParseTileset(data []byte) (*TilesetDoc, error)

ParseTileset decodes and validates a YAML tileset document (ValidateTileset), refusing unknown fields, a key given twice and a trailing document.

Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.

func (doc *TilesetDoc) Clone() *TilesetDoc

Clone returns a deep copy of doc, or nil when doc is nil.

func (doc *TilesetDoc) Count() int

Count returns how many tiles doc defines: its TileCount for a grid image, or the length of its Frames for an atlas.

func (doc *TilesetDoc) Terrain(name string, firstGID uint32) *Terrain

Terrain builds and returns the named terrain set from doc with global tile IDs starting at firstGID (1 when 0), or nil if doc defines no terrain with that name.

type TilesetLoader struct {
	// LoadTileset reads the raw bytes of an external tileset file (.tsx or .tsj) given its source path in the map (or resolved relative to a template's directory).
	// When nil, LoadTiled falls back to LoadJSON.
	LoadTileset func(source string) ([]byte, error)
	// LoadJSON reads the raw bytes of an external tileset file (.tsj or .tsx) given its source path in the map.
	// Kept for compatibility with existing callers; used when LoadTileset is nil.
	LoadJSON func(source string) ([]byte, error)
	// LoadTemplate reads the raw bytes of an external object template file (.tx or .tj) given its source path in the map.
	LoadTemplate func(source string) ([]byte, error)
	// LoadImage returns the ImageSource for a tileset, tile, or image-layer image path (resolved relative to the external tileset's or template's directory when loaded from one).
	LoadImage func(imagePath string) (core.ImageSource, error)
}

TilesetLoader resolves external tileset files, object template files, and images referenced by a Tiled map.

Any callback may be nil: LoadTileset (or LoadJSON as a fallback) is only needed when the map or a template references an external .tsx or .tsj tileset, LoadTemplate is only needed when an object references an external .tx or .tj template, and LoadImage defaults to core.ImageSource{URI: imagePath}.

type WangColor struct {
	Name        string
	Color       core.Color
	Tile        int // 0-based local representative tile ID, or -1 if unset
	Probability float64
	Class       string
	Properties  Properties
	// contains filtered or unexported fields
}

WangColor describes one terrain color in a Tiled WangSet. Its 1-based terrain index in WangID values is its slice index + 1.

type WangID [8]uint8

WangID holds the 8 terrain color indices around a tile in Tiled's clockwise order: [Top, TopRight, Right, BottomRight, Bottom, BottomLeft, Left, TopLeft].

Terrain indices are 1-based (1..len(WangSet.Colors)); 0 means unset or empty.

type WangSet struct {
	Name       string
	Type       WangSetType
	Tile       int // 0-based local representative tile ID, or -1 if unset
	Class      string
	FirstGID   uint32 // FirstGID of the owning Tileset (defaults to 1 when 0)
	Colors     []WangColor
	WangTiles  []WangTile
	Properties Properties
	// contains filtered or unexported fields
}

WangSet is a Tiled Wang set (terrain set) defining corner, edge, or mixed multi-terrain autotiling rules.

func (ws *WangSet) ColorIndex(name string) (uint8, bool)

ColorIndex returns the 1-based terrain index of the first color named name in ws.Colors.

func (ws *WangSet) WangIDForTile(localTileID uint32) (WangID, bool)

WangIDForTile returns the WangID assigned to the 0-based local tile ID in ws, if any.

type WangSetType uint8

WangSetType selects which tile edges and corners a Tiled WangSet matches.

const (
	// WangCorner matches the four tile corners (TopRight, BottomRight, BottomLeft, TopLeft).
	WangCorner WangSetType = iota
	// WangEdge matches the four tile edges (Top, Right, Bottom, Left).
	WangEdge
	// WangMixed matches all four tile edges and all four tile corners.
	WangMixed
)
func (t WangSetType) String() string

String returns the Tiled JSON name ("corner", "edge", or "mixed") for t.

type WangTile struct {
	TileID      uint32
	WangID      WangID
	Probability float64
	// contains filtered or unexported fields
}

WangTile maps a 0-based local tile ID in its Tileset to its 8-slot WangID and selection probability.

type WorldLevel struct {
	// ID is the unique level identifier (LDtk level identifier or Tiled map fileName).
	ID string
	// IID is the LDtk instance ID, when loaded from an LDtk project.
	IID string
	// UID is the LDtk numeric UID, when loaded from an LDtk project.
	UID int
	// FileName is the Tiled map file path, when loaded from a Tiled .world file.
	FileName string
	// Origin is the level's top-left world position in points.
	Origin core.Point
	// Bounds is the level's world-space bounding rectangle in points.
	Bounds core.Bounds
	// WorldDepth is the LDtk worldDepth layer (0 for Tiled worlds).
	WorldDepth int
	// Neighbours lists adjacent or overlapping levels (populated by LDtk world loaders).
	Neighbours []LevelNeighbour
	// Load builds this level's *Tilemap with Origin (and Neighbours) populated.
	Load func() (*Tilemap, error)
}

WorldLevel describes one level's world placement, metadata, and lazy loader inside a LevelWorld.

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

WorldStream keeps the levels of a LevelWorld overlapping a moving camera or query region loaded at their world origins, unloads levels outside an optional hysteresis margin, reports enter/leave events, draws all loaded levels seamlessly, and supports cross-seam queries and uniform-grid physics adapters.

func NewWorldStream(cfg WorldStreamConfig) *WorldStream

NewWorldStream constructs a WorldStream from cfg.

func (s *WorldStream) Close() []WorldStreamEvent

Close unloads every currently loaded level in deterministic world order, firing OnLeave and returning the leave events.

func (s *WorldStream) Draw(d *core.Drawing, cam *Camera)

Draw draws every currently loaded level into d in deterministic world order, honoring each level's Origin and culling to cam.

func (s *WorldStream) FlagsAtWorld(p core.Point) TileFlags

FlagsAtWorld returns the combined TileFlags at world point p across all currently loaded levels.

func (s *WorldStream) GridFlagsAt(col, row int) TileFlags

GridFlagsAt returns the combined TileFlags at uniform grid cell (col, row) relative to GridOrigin across all loaded levels.

Together with TileSize, GridSize, and GridOrigin, this lets a thin physics.TileGrid + physics.TileGridOrigin adapter move a physics.Body or physics.CharacterBody seamlessly across seams between adjacent loaded levels.

func (s *WorldStream) GridOrigin() (x, y float32)

GridOrigin returns the world-space origin (min X, min Y) of the combined loaded levels, implementing physics.TileGridOrigin.

func (s *WorldStream) GridSize() (cols, rows int)

GridSize returns the combined column and row counts covering all currently loaded levels from GridOrigin.

func (s *WorldStream) LevelAt(p core.Point) (*WorldLevel, *Tilemap)

LevelAt returns the first currently loaded level and its *Tilemap containing world point p, or (nil, nil) if none matches.

func (s *WorldStream) Loaded() []*Tilemap

Loaded returns all currently loaded *Tilemap instances in deterministic world order.

func (s *WorldStream) LoadedCount() int

LoadedCount returns the number of currently loaded levels.

func (s *WorldStream) LoadedLevels() []*WorldLevel

LoadedLevels returns all currently loaded *WorldLevel descriptors in deterministic world order.

func (s *WorldStream) Map(id string) *Tilemap

Map returns the currently loaded *Tilemap for level ID id, or nil if it is not loaded.

func (s *WorldStream) Raycast(from, to core.Point, mask TileFlags) (RaycastHit, bool)

Raycast traces from -> to across all currently loaded levels and returns the closest hit matching mask.

func (s *WorldStream) TileFlagsAt(col, row int) physics.TileFlags

TileFlagsAt returns the combined collision flags at uniform grid cell (col, row) relative to GridOrigin mapped to physics.TileFlags, satisfying physics.TileGrid.

func (s *WorldStream) TileSize() (width, height float32)

TileSize returns the tile dimensions of the loaded levels for uniform-grid physics adapters (0, 0 when no levels are loaded).

func (s *WorldStream) TilesInRect(r core.Bounds, mask TileFlags) []TileHit

TilesInRect returns every matching tile across all currently loaded levels overlapping r, in deterministic level order.

func (s *WorldStream) Update(region core.Bounds) []WorldStreamEvent

Update unloads any loaded level whose Bounds no longer overlap region expanded by UnloadMargin, then loads any unloaded level whose Bounds overlap region expanded by LoadMargin.

Transitions happen in deterministic World.Levels order (unloads first, then loads), firing OnLeave / OnEnter and returning the resulting events.

func (s *WorldStream) UpdateAnimations(dt time.Duration)

UpdateAnimations advances animated tiles on every currently loaded level by dt.

func (s *WorldStream) UpdateCamera(cam *Camera) []WorldStreamEvent

UpdateCamera updates streaming for cam.VisibleBounds() (doing nothing when cam is nil).

type WorldStreamConfig struct {
	// World is the multi-level world to stream.
	World *LevelWorld
	// LoadMargin expands the query/camera rectangle on all four sides (in world points)
	// when choosing which levels to load. Negative values are treated as 0.
	LoadMargin float32
	// UnloadMargin expands the query/camera rectangle on all four sides (in world points)
	// beyond which loaded levels are unloaded (hysteresis). Values smaller than LoadMargin
	// default to LoadMargin so a level cannot load and unload on the same update.
	UnloadMargin float32
	// OnEnter is called after a level is loaded and added to the active set.
	OnEnter func(level *WorldLevel, m *Tilemap)
	// OnLeave is called after a level is unloaded and removed from the active set.
	OnLeave func(level *WorldLevel, m *Tilemap)
	// OnError is called when loading a level fails.
	OnError func(level *WorldLevel, err error)
}

WorldStreamConfig configures a region-based WorldStream over a LevelWorld.

type WorldStreamEvent struct {
	Kind  WorldStreamEventKind
	Level *WorldLevel
	Map   *Tilemap
}

WorldStreamEvent describes one level load or unload transition produced by WorldStream.Update or Close.

type WorldStreamEventKind uint8

WorldStreamEventKind identifies whether a level entered or left a WorldStream's loaded set.

const (
	// WorldLevelEntered reports that a level was loaded and added to the active set.
	WorldLevelEntered WorldStreamEventKind = iota
	// WorldLevelLeft reports that a level was unloaded and removed from the active set.
	WorldLevelLeft
)
type YSortDrawer struct {
	// contains filtered or unexported fields
}

YSortDrawer batches consecutive unflipped YSortTile values sharing the same tileset and opacity into Drawing.DrawAtlas calls while reusing its internal scratch slices across frames.

func (dr *YSortDrawer) Flush(d *core.Drawing)

Flush emits any queued tiles into d and resets the run state while preserving slice capacity.

func (dr *YSortDrawer) Push(d *core.Drawing, t *YSortTile)

Push queues tile t into d, flushing any incompatible run first.

type YSortTile struct {
	// SortY is the world-space Y coordinate used for painter's-order depth sorting:
	// the tile's bottom edge plus any per-tile PropSortOriginY offset.
	SortY float32
	// Col and Row are the tile's grid coordinates within its TileLayer.
	Col int
	Row int
	// GID is the raw global tile ID (including flip flags) stored in the layer.
	GID uint32
	// LayerIndex is the index of the source TileLayer in Tilemap.Layers, or -1 if not attached.
	LayerIndex int
	// contains filtered or unexported fields
}

YSortTile is one visible tile collected from a TileLayer so it can be depth-sorted and interleaved with scene sprites and custom drawables in ascending SortY order.

func (t *YSortTile) Draw(d *core.Drawing)

Draw draws this single tile into d, applying its layer opacity, tint, and flip flags while leaving d's state unchanged.